code
stringlengths 1
13.8M
|
---|
NAME <- "atomic"
source(file.path('_helper', 'init.R'))
all.equal(as.character(diffPrint(chr.1, chr.2)), rdsf(100))
all.equal(
as.character(diffPrint(chr.1, chr.2, mode="unified")), rdsf(200)
)
all.equal(
as.character(diffPrint(chr.1, chr.2, mode="context")), rdsf(400)
)
all.equal(
as.character(diffPrint(chr.1[2:3], chr.2[2], mode="sidebyside")), rdsf(500)
)
all.equal(
as.character(
diffPrint(chr.1, chr.2, mode="unified", extra=list(quote=FALSE))
),
rdsf(600)
)
all.equal(
as.character(diffPrint(chr.3, chr.4)), rdsf(700)
)
all.equal(
as.character(diffPrint(chr.3, chr.4, mode="unified")), rdsf(800)
)
A <- A.1 <- B <- c(letters, LETTERS)
B[15] <- "Alabama"
A.1[5] <- "Ee"
C <- A[-15]
D <- C
E <- B[-45]
all.equal(as.character(diffPrint(A[-(1:8)], A)), rdsf(900))
all.equal(as.character(diffPrint(A, A[-(1:8)])), rdsf(1000))
all.equal(as.character(diffPrint(A[-1], A[-2])), rdsf(1100))
all.equal(as.character(diffPrint(A, B)), rdsf(1200))
all.equal(as.character(diffPrint(B, A)), rdsf(1250))
all.equal(
as.character(diffPrint(A, B, word.diff=FALSE)), rdsf(1300)
)
all.equal(
as.character(diffPrint(A, B, unwrap.atomic=FALSE)), rdsf(1400)
)
all.equal(
as.character(diffPrint(A, A.1[-(13:18)])), rdsf(1425)
)
all.equal(as.character(diffPrint(C, B)), rdsf(1450))
all.equal(as.character(diffPrint(D, E)), rdsf(1500))
all.equal(as.character(diffPrint(E, D)), rdsf(1600))
state.abb.2 <- state.abb
state.abb.2[38] <- "Pennsylvania"
all.equal(
as.character(diffPrint(state.abb, state.abb.2)), rdsf(1700)
)
all.equal(as.character(diffPrint(1:100, 2:101)), rdsf(1800))
all.equal(as.character(diffPrint(2:101, 1:100)), rdsf(1900))
all.equal(
as.character(diffPrint(2:101, (1:100)[-9])), rdsf(2000)
)
all.equal(
as.character(diffPrint((2:101)[-98], (1:100)[-9])), rdsf(2100)
)
int.1 <- int.2 <- 1:100
int.2[c(8, 20, 60)] <- 99
int.2 <- c(50:1, int.2)
all.equal(as.character(diffPrint(int.1, int.2)), rdsf(2200))
rand.chrs <- do.call(paste0, expand.grid(LETTERS, LETTERS))
F <- F1 <- F2 <- (2:105)[-98]
G <- G2 <- G3 <- G4 <- G5 <- (1:100)[-9]
nm.1 <- rand.chrs[seq_along(F)]
nm.2 <- rand.chrs[seq_along(G)]
names(F1) <- names(F2) <- nm.1
names(G3) <- names(G2) <- names(G3) <- names(G4) <- names(G5) <- nm.2
names(G3)[c(5, 25, 60)] <- c("XXXXX", rand.chrs[c(300, 350)])
names(G4)[c(5, 25, 60)] <- names(G5)[c(5, 25, 60)] <-
c("XX", rand.chrs[c(300, 350)])
attr(F2, "blah") <- 1:5
attr(G5, "blah") <- 3:8
all.equal(as.character(diffPrint(F, G)), rdsf(2300))
all.equal(as.character(diffPrint(F1, G2)), rdsf(2400))
all.equal(as.character(diffPrint(F1, G3)), rdsf(2500))
all.equal(as.character(diffPrint(F1, G4)), rdsf(2520))
all.equal(as.character(diffPrint(F2, G5)), rdsf(2530))
all.equal(as.character(diffPrint(F1, G5)), rdsf(2540))
set.seed(2)
w1 <- sample(
c(
"carrot", "cat", "cake", "eat", "rabbit", "holes", "the", "a", "pasta",
"boom", "noon", "sky", "hat", "blah", "paris", "dog", "snake"
), 25, replace=TRUE
)
w4 <- w3 <- w2 <- w1
w2[sample(seq_along(w1), 5)] <- LETTERS[1:5]
w3 <- w1[8:15]
w4 <- c(w1[1:5], toupper(w1[1:5]), w1[6:15], toupper(w1[1:5]))
all.equal(as.character(diffPrint(w1, w2)), rdsf(2600))
all.equal(as.character(diffPrint(w1, w3)), rdsf(2700))
all.equal(as.character(diffPrint(w1, w4)), rdsf(2800))
a <- c("a", "b", "c", "d")
b <- c("b", "c", "d", "e")
all.equal(as.character(diffPrint(a, b)), rdsf(2900))
a <- c("x", "a", "b", "c", "d", "z")
b <- c("x", "b", "c", "d", "e", "z")
all.equal(as.character(diffPrint(a, b)), rdsf(3000))
a <- c("x", "a", "b", "c", "d", "z")
b <- c("z", "b", "c", "d", "e", "x")
all.equal(as.character(diffPrint(a, b)), rdsf(3100))
all.equal(
as.character(diffPrint(20:50, 30:62)), rdsf(3200)
)
all.equal(
as.character(diffPrint(c(1:24,35:45), c(1:8, 17:45))), rdsf(3400)
) |
fitEM <- function(y, X.t, Z.t, K = NULL, Vg = NULL, Ve = NULL,
cov.error = TRUE, stop.if.significant = FALSE,
null.dev = NULL, alpha = 0.01, max.iter = 100,
Vg.start = NULL, Ve.start = NULL, cov.gen = TRUE) {
if (stop.if.significant == TRUE & is.null(null.dev)) {stop('No null.dev given')}
if (!is.null(Vg.start) & !is.null(Vg)) {
warning('Vg set to NULL')
Vg <- NULL
}
if (!is.null(Ve.start) & !is.null(Ve)) {
warning('Ve set to NULL')
Ve <- NULL
}
na.X <- apply(X.t, 1, function(x) any(is.na(x)))
na.Z <- apply(Z.t, 1, function(z) any(is.na(z)))
is.na <- is.na(y[1:nrow(X.t)]) | is.na(y[(nrow(X.t)+1):(2*nrow(X.t))]) | na.X | na.Z
y <- y[rep(!is.na,2)]
X.t <- X.t[!is.na,]
Z.t <- Z.t[!is.na,]
Ve.aux <- Ve
Vg.aux <- Vg
X.t <- Matrix(X.t)
if(!is.null(K)) {
eig <- eigen(K)
U <- eig$vectors
d <- eig$values
K.trans <- U %*% diag(1/sqrt(d))
Z.t <- Matrix(Z.t%*% K.trans)
} else {
Z.t <- Matrix(Z.t)
}
Z <- Diagonal(2)%x%Z.t
X <- Diagonal(2)%x%X.t
ngeno <- ncol(Z.t)
N <- nrow(Z.t)
MM <- cbind(X,Z)
XtX. <- crossprod(X.t)
XtZ. <- crossprod(X.t, Z.t)
ZtZ. <- crossprod(Z.t)
w <- rep(1, length(y))
np <- c(ncol(X), ngeno, ngeno)
devold <- 1e10
thr <- 1e-3
if (is.null(Vg)) {
est.Vg <- TRUE
est.Vg.var <- TRUE
if (is.null(Vg.start)) {
Vg <- c(1,1,0.1)
} else {
Vg <- Vg.start
}
} else {
if (length(Vg.aux) == 2) {
est.Vg <- TRUE
est.Vg.var <- FALSE
Vg <- c(Vg.aux[1], Vg.aux[2], 0.1)
} else {
if (length(Vg.aux) == 3) {
est.Vg <- FALSE
} else {
stop('The specified variance/covariance matrix for the error component is not correct')
}
}
}
if (is.null(Ve)) {
est.Ve <- TRUE
est.Ve.var <- TRUE
if (cov.error) {
if (is.null(Ve.start)) {
Ve <- c(1,1,0.1)
} else {
Ve <- Ve.start
}
} else {
if (is.null(Ve.start)) {
Ve <- c(1,1,0)
} else {
Ve <- Ve.start
Ve[3] <- 0
}
}
} else {
if (length(Ve.aux) == 2) {
est.Ve <- TRUE
cov.error <- TRUE
est.Ve.var <- FALSE
Ve <- c(Ve.aux[1], Ve.aux[2], 0.1)
} else if (length(Ve.aux) == 3) {
est.Ve <- FALSE
} else {
stop('The specified variance/covariance matrix for the error component is not correct')
}
}
g1 <- rep(c(Vg[1], 0), each = ngeno)
g2 <- rep(c(0, Vg[2]), each = ngeno)
for (it in 1:max.iter) {
Gi <- matrix(c(Vg[1], Vg[3], Vg[3], Vg[2]), ncol = 2)
G <- Gi%x%Diagonal(ngeno)
Giinv <- solve(Gi)
Ginv <- Giinv%x%Diagonal(ngeno)
Ri <- matrix(c(Ve[1], Ve[3], Ve[3], Ve[2]), ncol = 2)
R <- Ri%x%Diagonal(N)
Riinv <- solve(Ri)
Rinv <- Riinv%x%Diagonal(N)
XtRinvX. <- Riinv%x%XtX.
XtRinvZ. <- Riinv%x%XtZ.
ZtRinvZ. <- Riinv%x%ZtZ.
XtRinvy. <- ((Riinv%x%t(X.t))%*%y)[,1]
ZtRinvy. <- ((Riinv%x%t(Z.t))%*%y)[,1]
u <- c(XtRinvy.,ZtRinvy.)
V <- construct.block(XtRinvX., XtRinvZ., t(XtRinvZ.), ZtRinvZ.)
D <- bdiag(diag(rep(0,np[1])), Ginv)
H <- V + D
Hinv <- try(solve(H))
if(class(Hinv) == "try-error") {
Hinv <- ginv(as.matrix(H))
}
b <- Hinv%*%u
b.fixed <- b[1:np[1]]
b.random <- b[-(1:np[1])]
res <- (y - MM%*%b)
dev <- deviance2(H, Gi, ngeno, Ri, N, Rinv, res, t(b.random)%*%Ginv%*%b.random)[1]
if(!est.Ve & !est.Vg) {
break
}
if (est.Vg) {
Ak <- Hinv[-(1:np[1]),-(1:np[1])]
if (est.Vg.var) {
aux <- diag(G) - diag(Hinv[-(1:np[1]),-(1:np[1])])
g.inv.d <- (1/Vg[1])*g1
ed1 <- sum(aux*g.inv.d)
ssv1 <- sum(b.random^2*g1)
tau1 <- ssv1/ed1
g.inv.d <- (1/Vg[2])*g2
ed2 <- sum(aux*g.inv.d)
ssv2 <- sum(b.random^2*g2)
tau2 <- ssv2/ed2
} else {
tau1 <- Vg[1]
tau2 <- Vg[2]
}
if (cov.gen) {
A <- Ak[1:ngeno, (ngeno+1):(2*ngeno)]
tau3 <- (1/ngeno)*(sum(diag(A)) + sum(b.random[1:ngeno]*b.random[(ngeno+1):(2*ngeno)]))
} else {
tau3 <- 0
}
Vg.new <- c(tau1, tau2, tau3)
} else {
Vg.new = Vg
}
if (est.Ve) {
resm <- matrix(res, ncol = 2)
ress <- t(resm)%*%resm
aux <- MM%*%Hinv
if(est.Ve.var) {
diag.var <- rowSums(aux*MM)
aux1 <- sum(diag.var[1:N])
aux2 <- ress[1,1]
sig21 <- (1/N)*(aux1 + aux2)
aux1 <- sum(diag.var[(N+1):(2*N)])
aux2 <- ress[2,2]
sig22 <- (1/N)*(aux1 + aux2)
} else {
sig21 <- Ve[1]
sig22 <- Ve[2]
}
if (cov.error) {
diag.covar <- rowSums(aux[1:N,]*MM[(N+1):(2*N),])
aux1 <- sum(diag.covar)
aux2 <- ress[1,2]
sig212 = (1/N)*(aux1 + aux2)
} else {
sig212 = 0
}
Ve.new <- c(sig21, sig22, sig212)
} else {
Ve.new <- Ve
}
dla <- abs(devold - dev)
Ve <- Ve.new
Vg <- Vg.new
devold <- dev
if (stop.if.significant) {
loglik_Full <- -0.5 * dev
loglik_Reduced <- -0.5 * null.dev
REMLLRT <- 2 * max(loglik_Full - loglik_Reduced, 0)
pvalue <- (1 - pchisq(REMLLRT, df = 1))
if (pvalue < alpha) break
if (it > 20 & pvalue > 0.1) break
}
if (dla < thr) break
}
if(!is.null(K)) {
b.random <- (Diagonal(2)%x%K.trans)%*%b.random
}
res <- list()
res$coeff <- list(fixed = b.fixed, random = b.random)
res$variances <- list(Ve = Ve, Vg = Vg)
res$deviance <- dev
res$it <- it
if (stop.if.significant) {res$pvalue <- pvalue}
res
} |
DAISIE_loglik_rhs_precomp <- function(pars,lx)
{
lac = pars[1]
mu = pars[2]
K = pars[3]
gam = pars[4]
laa = pars[5]
kk = pars[6]
ddep = pars[7]
nn = -2:(lx+2*kk+1)
lnn = length(nn)
nn = pmax(rep(0,lnn),nn)
if(ddep == 0)
{
laavec = laa * rep(1,lnn)
lacvec = lac * rep(1,lnn)
muvec = mu * rep(1,lnn)
gamvec = gam * rep(1,lnn)
} else if(ddep == 1)
{
laavec = laa * rep(1,lnn)
lacvec = pmax(rep(0,lnn),lac * (1 - nn/K))
muvec = mu * rep(1,lnn)
gamvec = gam * rep(1,lnn)
} else if(ddep == 2)
{
laavec = laa * rep(1,lnn)
lacvec = pmax(rep(0,lnn),lac * exp(-nn/K))
muvec = mu * rep(1,lnn)
gamvec = gam * rep(1,lnn)
} else if(ddep == 11)
{
laavec = laa * rep(1,lnn)
lacvec = pmax(rep(0,lnn),lac * (1 - nn/K))
muvec = mu * rep(1,lnn)
gamvec = pmax(rep(0,lnn),gam * (1 - nn/K))
} else if(ddep == 21)
{
laavec = laa * rep(1,lnn)
lacvec = pmax(rep(0,lnn),lac * exp(-nn/K))
muvec = mu * rep(1,lnn)
gamvec = pmax(rep(0,lnn),gam * exp(-nn/K))
} else if(ddep == 3)
{
laavec = laa * rep(1,lnn)
lacvec = lac * rep(1,lnn)
muvec = mu * (1 + nn/K)
gamvec = gam * rep(1,lnn)
}
return(c(laavec, lacvec, muvec, gamvec, nn, kk))
}
DAISIE_loglik_rhs <- function(t, x, parsvec) {
kk <- parsvec[length(parsvec)]
lx <- (length(x) - 1)/2
lnn <- lx + 4 + 2 * kk
laavec <- parsvec[1:lnn]
lacvec <- parsvec[(lnn + 1):(2 * lnn)]
muvec <- parsvec[(2 * lnn + 1):(3 * lnn)]
gamvec <- parsvec[(3 * lnn + 1):(4 * lnn)]
nn <- parsvec[(4 * lnn + 1):(5 * lnn)]
xx1 = c(0,0,x[1:lx],0)
xx2 = c(0,0,x[(lx + 1):(2 * lx)],0)
xx3 = x[2 * lx + 1]
nil2lx = 3:(lx + 2)
il1 = nil2lx+kk-1
il2 = nil2lx+kk+1
il3 = nil2lx+kk
il4 = nil2lx+kk-2
in1 = nil2lx+2*kk-1
in2 = nil2lx+1
in3 = nil2lx+kk
ix1 = nil2lx-1
ix2 = nil2lx+1
ix3 = nil2lx
ix4 = nil2lx-2
dx1 = laavec[il1 + 1] * xx2[ix1] + lacvec[il4 + 1] * xx2[ix4] + muvec[il2 + 1] * xx2[ix3] +
lacvec[il1] * nn[in1] * xx1[ix1] + muvec[il2] * nn[in2] * xx1[ix2] +
-(muvec[il3] + lacvec[il3]) * nn[in3] * xx1[ix3] +
-gamvec[il3] * xx1[ix3]
dx1[1] = dx1[1] + laavec[il3[1]] * xx3 * (kk == 1)
dx1[2] = dx1[2] + 2 * lacvec[il3[1]] * xx3 * (kk == 1)
dx2 = gamvec[il3] * xx1[ix3] +
lacvec[il1 + 1] * nn[in1] * xx2[ix1] + muvec[il2 + 1] * nn[in2] * xx2[ix2] +
-(muvec[il3 + 1] + lacvec[il3 + 1]) * nn[in3 + 1] * xx2[ix3] +
-laavec[il3 + 1] * xx2[ix3]
dx3 = -(laavec[il3[1]] + lacvec[il3[1]] + gamvec[il3[1]] + muvec[il3[1]]) * xx3
return(list(c(dx1,dx2,dx3)))
}
DAISIE_loglik_rhs2 <- function(t, x, parsvec) {
kk <- parsvec[length(parsvec)]
lx <- (length(x))/3
lnn <- lx + 4 + 2 * kk
laavec <- parsvec[1:lnn]
lacvec <- parsvec[(lnn + 1):(2 * lnn)]
muvec <- parsvec[(2 * lnn + 1):(3 * lnn)]
gamvec <- parsvec[(3 * lnn + 1):(4 * lnn)]
nn <- parsvec[(4 * lnn + 1):(5 * lnn)]
xx1 = c(0,0,x[1:lx],0)
xx2 = c(0,0,x[(lx + 1):(2 * lx)],0)
xx3 = c(0,0,x[(2 * lx + 1):(3 * lx)],0)
nil2lx = 3:(lx + 2)
il1 = nil2lx+kk-1
il2 = nil2lx+kk+1
il3 = nil2lx+kk
il4 = nil2lx+kk-2
in1 = nil2lx+2*kk-1
in2 = nil2lx+1
in3 = nil2lx+kk
in4 = nil2lx-1
ix1 = nil2lx-1
ix2 = nil2lx+1
ix3 = nil2lx
ix4 = nil2lx-2
dx1 = (laavec[il3] * xx3[ix3] + 2 * lacvec[il1] * xx3[ix1]) * (kk == 1) +
laavec[il1 + 1] * xx2[ix1] + lacvec[il4 + 1] * xx2[ix4] + muvec[il2 + 1] * xx2[ix3] +
lacvec[il1] * nn[in1] * xx1[ix1] + muvec[il2] * nn[in2] * xx1[ix2] +
-(muvec[il3] + lacvec[il3]) * nn[in3] * xx1[ix3] - gamvec[il3] * xx1[ix3]
dx2 <- gamvec[il3] * xx1[ix3] +
lacvec[il1 + 1] * nn[in1] * xx2[ix1] + muvec[il2 + 1] * nn[in2] * xx2[ix2] +
-(muvec[il3 + 1] + lacvec[il3 + 1]) * nn[in3 + 1] * xx2[ix3] +
-laavec[il3 + 1] * xx2[ix3]
dx3 <- lacvec[il1] * nn[in4] * xx3[ix1] + muvec[il2] * nn[in2] * xx3[ix2] +
-(lacvec[il3] + muvec[il3]) * nn[in3] * xx3[ix3] +
-(laavec[il3] + gamvec[il3]) * xx3[ix3]
return(list(c(dx1,dx2,dx3)))
}
checkprobs <- function(lv, loglik, probs, verbose) {
probs <- probs * (probs > 0)
if (is.na(sum(probs[1:lv])) || is.nan(sum(probs))) {
loglik <- -Inf
} else if (sum(probs[1:lv]) <= 0) {
loglik <- -Inf
} else {
loglik <- loglik + log(sum(probs[1:lv]))
probs[1:lv] <- probs[1:lv] / sum(probs[1:lv])
}
if (verbose) {
cat("Numerical issues encountered \n")
}
return(list(loglik, probs))
}
checkprobs2 <- function(lx, loglik, probs, verbose) {
probs <- probs * (probs > 0)
if (is.na(sum(probs)) || is.nan(sum(probs))) {
loglik <- -Inf
} else if (sum(probs) <= 0) {
loglik <- -Inf
} else {
loglik = loglik + log(sum(probs))
probs = probs/sum(probs)
}
if (verbose) {
cat("Numerical issues encountered \n")
}
return(list(loglik, probs))
}
divdepvec <- function(lacgam,
pars1,
lx,
k1,
ddep,
island_ontogeny = NA) {
if (!is.na(island_ontogeny)) {
lacgamK <- divdepvec_time(lacgam, pars1, lx, k1, ddep, island_ontogeny)
lacgam <- lacgamK[1]
K <- lacgamK[2]
} else {
K <- pars1[1]
}
return(divdepvec1(lacgam, K, lx, k1, ddep))
}
divdepvec1 <- function(lacgam, K, lx, k1, ddep) {
if (ddep == 1 | ddep == 11) {
vec <- pmax(rep(0, lx + 1), lacgam * (1 - ( (0:lx) + k1) / K))
} else {
if (ddep == 2 | ddep == 21) {
vec <- pmax(rep(0, lx + 1), lacgam * exp(-((0:lx) + k1) / K))
} else {
if (ddep == 0 | ddep == 3) {
vec <- lacgam * rep(1, lx + 1)
}
}
}
return(vec)
}
DAISIE_loglik_CS_M1 <- DAISIE_loglik <- function(pars1,
pars2,
brts,
stac,
missnumspec,
methode = "lsodes",
abstolint = 1E-16,
reltolint = 1E-10,
verbose) {
if (any(is.infinite(pars1)) ) {
if (verbose) {
message('One of the parameters is infinite.')
}
}
if(is.na(pars2[4]))
{
pars2[4] = 0
}
ddep <- pars2[2]
cond <- pars2[3]
island_ontogeny <- pars2[5]
if (cond > 0) {
cat("Conditioning has not been implemented and may not make sense.
Cond is set to 0.\n")
}
if (is.na(island_ontogeny))
{
lac <- pars1[1]
mu <- pars1[2]
K <- pars1[3]
if (ddep == 0) {
K <- Inf
}
gam <- pars1[4]
laa <- pars1[5]
pars1_in_divdepvec_call <- K
} else {
pars1[11] <- island_ontogeny
if (pars1[11] == 0 && pars1[6] != pars1[7]) {
warning("mu_min and mu_max are not equal! Setting mu_max = mu_min")
pars1[7] <- pars1[6]
}
lac <- as.numeric(pars1[5])
K <- as.numeric(pars1[8])
gam <- as.numeric(pars1[9])
pars1_in_divdepvec_call <- pars1
}
brts = -sort(abs(as.numeric(brts)),decreasing = TRUE)
if(length(brts) == 1 & sum(brts == 0) == 1)
{
stop('The branching times contain only a 0. This means the island emerged at the present which is not allowed.');
loglik = -Inf
return(loglik)
}
if (sum(brts == 0) == 0) {
brts[length(brts) + 1] <- 0
}
S <- 0 * (stac == 0) + (stac == 1 || stac == 4 || stac == 5 || stac == 8 || stac == 9) +
(length(brts) - 2) * (stac == 2) + (length(brts) - 1) * (stac == 3) +
(length(brts) - 2) * (stac == 6) + (length(brts) - 1) * (stac == 7)
S2 <- S - (stac == 1) - (stac == 3) - (stac == 4) - (stac == 7)
loglik <- -lgamma(S2 + missnumspec + 1) +
lgamma(S2 + 1) + lgamma(missnumspec + 1)
if (min(pars1) < 0) {
message("One or more parameters are negative.")
loglik <- -Inf
return(loglik)
}
if ((ddep == 1 | ddep == 11) & ceiling(K) < (S + missnumspec)) {
if (verbose) {
message('The proposed value of K is incompatible with the number of species
in the clade. Likelihood for this parameter set
will be set to -Inf. \n')
}
loglik <- -Inf
return(loglik)
}
N <- length(brts) - 1
if(lac == Inf & missnumspec == 0 & length(pars1) == 5 & N > 1) {
loglik <- DAISIE_loglik_high_lambda(pars1, -brts, stac)
} else {
if (ddep == 1 | ddep == 11) {
lx <- min(
1 + max(missnumspec, ceiling(K)),
DDD::roundn(pars2[1]) + missnumspec
)
} else {
lx <- DDD::roundn(pars2[1]) + missnumspec
}
if(loglik > -Inf)
{
probs = rep(0,2 * lx + 1)
probs[1] = 1
k1 = 0
y = DAISIE_integrate(probs,brts[1:2],DAISIE_loglik_rhs,c(pars1,k1,ddep),rtol = reltolint,atol = abstolint,method = methode)
probs = y[2,2:(2 * lx + 2)]
cp = checkprobs(lv = 2 * lx, loglik, probs, verbose); loglik = cp[[1]]; probs = cp[[2]]
if(stac == 0)
{
loglik = loglik + log(probs[1 + missnumspec])
} else {
if (stac == 1 || stac == 5 || stac == 8 || stac == 9)
{
probs[(lx + 1):(2 * lx)] = 0
y = DAISIE_integrate(probs,brts[2:3],DAISIE_loglik_rhs,c(pars1,k1,ddep),rtol = reltolint,atol = abstolint,method = methode)
probs = y[2,2:(2 * lx + 2)]
cp = checkprobs(lv = 2 * lx, loglik, probs, verbose); loglik = cp[[1]]; probs = cp[[2]]
if (stac == 1 || stac == 5) {
loglik = loglik + log(probs[(stac == 1) * lx + (stac == 5) + 1 + missnumspec])
} else
{
probs[(2 * lx + 1):(3 * lx)] = probs[1:lx]
probs[1:(2 * lx)] = 0
k1 = 1
y = DAISIE_integrate(probs,c(brts[3:4]),DAISIE_loglik_rhs2,c(pars1,k1,ddep),rtol = reltolint,atol = abstolint,method = methode)
probs = y[2,2:(3 * lx + 1)]
cp = checkprobs2(lx,loglik,probs, verbose); loglik = cp[[1]]; probs = cp[[2]]
loglik = loglik + log(probs[(stac == 8) * lx + (stac == 9) + 1 + missnumspec])
}
} else {
if (stac == 6 || stac == 7) {
probs[(lx + 1):(2 * lx)] = 0
y = DAISIE_integrate(probs,brts[2:3],DAISIE_loglik_rhs,c(pars1,k1,ddep),rtol = reltolint,atol = abstolint,method = methode)
probs = y[2,2:(2 * lx + 2)]
cp = checkprobs(lv = 2 * lx, loglik, probs, verbose); loglik = cp[[1]]; probs = cp[[2]]
k1 = 1
}
if (stac == 2 || stac == 3 || stac == 4) {
t <- brts[2]
gamvec = divdepvec(gam,c(pars1_in_divdepvec_call,t,0),lx,k1,ddep * (ddep == 11 | ddep == 21),island_ontogeny)
probs[(2 * lx + 1):(3 * lx)] = gamvec[1:lx] * probs[1:lx]
probs[1:(2 * lx)] = 0
k1 = 1
y = DAISIE_integrate(probs,c(brts[2:3]),DAISIE_loglik_rhs2,c(pars1,k1,ddep),rtol = reltolint,atol = abstolint,method = methode)
probs = y[2,2:(3 * lx + 1)]
cp = checkprobs2(lx,loglik,probs, verbose); loglik = cp[[1]]; probs = cp[[2]]
}
if (stac == 4)
{
loglik = loglik + log(probs[2 * lx + 1 + missnumspec])
} else {
S1 = length(brts) - 1
startk = 3
if(S1 >= startk)
{
t <- brts[startk]
lacvec <- divdepvec(
lac,
c(pars1_in_divdepvec_call, t, 1),
lx,
k1,
ddep,
island_ontogeny
)
if (stac == 2 || stac == 3) {
probs[1:lx] <- lacvec[1:lx] *
(probs[1:lx] + probs[(2 * lx + 1):(3 * lx)])
probs[(lx + 1):(2 * lx)] <- lacvec[2:(lx + 1)] *
probs[(lx + 1):(2 * lx)]
probs <- probs[-c((2 * lx + 2):(3 * lx))]
probs[2 * lx + 1] <- 0
}
if(stac == 6 || stac == 7)
{
probs2 = rep(0,2 * lx + 1)
probs2[(1:(lx - 1))] = probs[(2:lx)] + 1/(2:lx) * probs[(lx + 1):(2 * lx - 1)]
probs2[lx] = 1/(lx + 1) * probs[2 * lx]
probs2[(lx + 1):(2 * lx - 1)] = (1:(lx - 1))/(2:lx) * probs[(lx + 2):(2 * lx)]
probs = probs2
rm(probs2)
probs[1:lx] = lacvec[1:lx] * probs[1:lx]
probs[(lx + 1):(2 * lx)] = lacvec[2:(lx + 1)] * probs[(lx + 1):(2 * lx)]
}
for(k in startk:S1)
{
k1 = k - 1
y = DAISIE_integrate(probs,brts[k:(k+1)],DAISIE_loglik_rhs,c(pars1,k1,ddep),rtol = reltolint,atol = abstolint,method = methode)
probs = y[2,2:(2 * lx + 2)]
cp = checkprobs2(lx, loglik, probs, verbose); loglik = cp[[1]]; probs = cp[[2]]
if(k < S1)
{
t <- brts[k + 1]
lacvec <- divdepvec(
lac,
c(pars1_in_divdepvec_call, t, 1),
lx,
k1,
ddep,
island_ontogeny
)
probs[1:(2 * lx)] <- c(lacvec[1:lx], lacvec[2:(lx + 1)]) *
probs[1:(2 * lx)]
}
}
}
loglik = loglik + log(probs[(stac == 3 || stac == 7) * lx + 1 + missnumspec])
}
}
}
}
}
if(pars2[4] >= 1)
{
if (length(pars1) == 11) {
s1 = sprintf('Status of colonist: %d, Parameters: %f %f %f %f %f %f', stac, pars1[5], pars1[6], pars1[7], pars1[8], pars1[9], pars1[10])
} else {
s1 <- sprintf(
"Status of colonist: %d, Parameters: %f %f %f %f %f ",
stac,
pars1[1],
pars1[2],
pars1[3],
pars1[4],
pars1[5]
)
}
s2 <- sprintf(", Loglikelihood: %f", loglik)
cat(s1, s2, "\n", sep = "")
utils::flush.console()
}
if (is.na(loglik)) {
cat("NA in loglik encountered. Changing to -Inf.")
loglik <- -Inf
}
loglik <- as.numeric(loglik)
return(loglik)
}
DAISIE_loglik_CS_choice = function(
pars1,
pars2,
brts,
stac,
missnumspec,
methode = "lsodes",
CS_version = 1,
abstolint = 1E-16,
reltolint = 1E-10,
verbose = FALSE
)
{
if (CS_version[[1]] == 1) {
loglik <- DAISIE_loglik(
pars1 = pars1,
pars2 = pars2,
brts = brts,
stac = stac,
missnumspec = missnumspec,
methode = methode,
abstolint = abstolint,
reltolint = reltolint,
verbose = verbose
)
} else if (CS_version[[1]] == 2) {
loglik <- DAISIE_loglik_integrate(
pars1 = pars1,
pars2 = pars2,
brts = brts,
stac = stac,
missnumspec = missnumspec,
methode = methode,
CS_version = CS_version,
abstolint = abstolint,
reltolint = reltolint,
verbose = verbose
)
} else if (CS_version[[1]] == 0) {
loglik <- DAISIE_loglik_IW_M1(
pars1 = pars1,
pars2 = pars2,
brts = brts,
stac = stac,
missnumspec = missnumspec,
methode = methode,
abstolint = abstolint,
reltolint = reltolint,
verbose = verbose
)
}
return(loglik)
}
DAISIE_loglik_CS <- DAISIE_loglik_all <- function(pars1,
pars2,
datalist,
methode = "lsodes",
CS_version = 1,
abstolint = 1E-16,
reltolint = 1E-10) {
pars1 = as.numeric(pars1)
cond = pars2[3]
endpars1 <- 5
if(length(pars1) == 5 | !is.na(pars2[5]))
{
if(!is.na(pars2[5]))
{
endpars1 <- length(pars1)
}
logp0 <- DAISIE_loglik_CS_choice(
pars1 = pars1,
pars2 = pars2,
brts = datalist[[1]]$island_age,
stac = 0,
missnumspec = 0,
methode = methode,
CS_version = CS_version,
abstolint = abstolint,
reltolint = reltolint
)
if (is.null(datalist[[1]]$not_present)) {
loglik <- (datalist[[1]]$not_present_type1 +
datalist[[1]]$not_present_type2) * logp0
numimm <- (datalist[[1]]$not_present_type1 +
datalist[[1]]$not_present_type2) + length(datalist) - 1
} else {
loglik <- datalist[[1]]$not_present * logp0
numimm <- datalist[[1]]$not_present + length(datalist) - 1
}
logcond <- (cond == 1) * log(1 - exp(numimm * logp0))
if (length(datalist) > 1) {
for (i in 2:length(datalist)) {
datalist[[i]]$type1or2 <- 1
}
}
} else {
numimm <- datalist[[1]]$not_present_type1 +
datalist[[1]]$not_present_type2 + length(datalist) - 1
numimm_type2 <- length(
which(unlist(datalist)[which(names(unlist(datalist)) == "type1or2")] == 2)
)
numimm_type1 <- length(datalist) - 1 - numimm_type2
if (is.na(pars1[11]) == FALSE) {
if (pars1[11] < numimm_type2 / numimm |
pars1[11] > (1 - numimm_type1 / numimm)) {
return(-Inf)
}
datalist[[1]]$not_present_type2 <- max(
0,
round(pars1[11] * numimm) - numimm_type2
)
datalist[[1]]$not_present_type1 <- numimm - (length(datalist) - 1) -
datalist[[1]]$not_present_type2
}
logp0_type1 <- DAISIE_loglik_CS_choice(
pars1 = pars1[1:5],
pars2 = pars2,
brts = datalist[[1]]$island_age,
stac = 0,
missnumspec = 0,
methode = methode,
CS_version = CS_version,
abstolint = abstolint,
reltolint = reltolint
)
logp0_type2 <- DAISIE_loglik_CS_choice(
pars1 = pars1[6:10],
pars2 = pars2,
brts = datalist[[1]]$island_age,
stac = 0,
missnumspec = 0,
methode = methode,
CS_version = CS_version,
abstolint = abstolint,
reltolint = reltolint
)
loglik <- datalist[[1]]$not_present_type1 * logp0_type1 +
datalist[[1]]$not_present_type2 * logp0_type2
logcond <- (cond == 1) *
log(1 - exp((datalist[[1]]$not_present_type1 + numimm_type1) *
logp0_type1 +
(datalist[[1]]$not_present_type2 + numimm_type2) *
logp0_type2))
}
loglik = loglik - logcond
if(length(datalist) > 1)
{
for(i in 2:length(datalist))
{
if(datalist[[i]]$type1or2 == 1)
{
pars = pars1[1:endpars1]
} else {
pars <- pars1[6:10]
}
loglik <- loglik + DAISIE_loglik_CS_choice(
pars1 = pars,
pars2 = pars2,
brts = datalist[[i]]$branching_times,
stac = datalist[[i]]$stac,
missnumspec = datalist[[i]]$missing_species,
methode = methode,
CS_version = CS_version,
abstolint = abstolint,
reltolint = reltolint
)
}
}
return(loglik)
}
DAISIE_integrate <- function(initprobs,
tvec,
rhs_func,
pars,
rtol,
atol,
method) {
if (length(pars) <= 7) {
return(DAISIE_integrate_const(
initprobs,
tvec,
rhs_func,
pars,
rtol,
atol,
method)
)
} else {
return(DAISIE_integrate_time(
initprobs,
tvec,
rhs_func,
pars,
rtol,
atol,
method)
)
}
}
DAISIE_integrate_const <- function(initprobs,tvec,rhs_func,pars,rtol,atol,method)
{
function_as_text <- as.character(body(rhs_func)[3])
do_fun_1 <- grepl(pattern = "lx <- \\(length\\(x\\) - 1\\)/2", x = function_as_text)
do_fun_2 <- grepl(pattern = "lx <- \\(length\\(x\\)\\)/3", x = function_as_text)
if (do_fun_1)
{
lx <- (length(initprobs) - 1)/2
parsvec <- c(DAISIE_loglik_rhs_precomp(pars,lx))
y <- DAISIE_ode_FORTRAN(initprobs,tvec,parsvec,atol,rtol,method,runmod = "daisie_runmod")
} else if (do_fun_2)
{
lx <- (length(initprobs))/3
parsvec <- c(DAISIE_loglik_rhs_precomp(pars,lx))
y <- DAISIE_ode_FORTRAN(initprobs,tvec,parsvec,atol,rtol,method,runmod = "daisie_runmod2")
} else
{
stop(
"The integrand function is written incorrectly. ",
"Value of 'function_as_text':", function_as_text
)
}
return(y)
}
DAISIE_ode_FORTRAN <- function(
initprobs,
tvec,
parsvec,
atol,
rtol,
methode,
runmod = "daisie_runmod") {
N <- length(initprobs)
kk <- parsvec[length(parsvec)]
if (runmod == "daisie_runmod") {
lx <- (N - 1) / 2
} else if (runmod == "daisie_runmod2") {
lx <- N / 3
}
probs <- deSolve::ode(y = initprobs, parms = c(lx + 0.,kk + 0.), rpar = parsvec[-length(parsvec)],
times = tvec, func = runmod, initfunc = "daisie_initmod",
ynames = c("SV"), dimens = N + 2, nout = 1, outnames = c("Sum"),
dllname = "DAISIE",atol = atol, rtol = rtol, method = methode)[,1:(N + 1)]
return(probs)
} |
library(hamcrest)
Sys.setlocale('LC_COLLATE', 'C')
as.name.foo <- function(...) 41L
as.vector.foo <- function(...) 99
as.vector.bar <- function(...) 98
Math.bar <- function(...) 44
Summary.bar <- function(...) 45
Ops.bar <- function(...) 46
test.as.name.1 <- function() assertThat(as.name(NULL), throwsError())
test.as.name.2 <- function() assertThat(as.name(logical(0)), throwsError())
test.as.name.3 <- function() assertThat(as.name(c(TRUE, TRUE, FALSE, FALSE, TRUE)), identicalTo(as.name("TRUE")))
test.as.name.4 <- function() assertThat(as.name(structure(c(TRUE, FALSE), .Names = c("a", ""))), identicalTo(as.name("TRUE")))
test.as.name.5 <- function() assertThat(as.name(c(TRUE, FALSE, NA)), identicalTo(as.name("TRUE")))
test.as.name.6 <- function() assertThat(as.name(integer(0)), throwsError())
test.as.name.7 <- function() assertThat(as.name(structure(integer(0), .Names = character(0))), throwsError())
test.as.name.8 <- function() assertThat(as.name(1:3), identicalTo(as.name("1")))
test.as.name.9 <- function() assertThat(as.name(c(1L, NA, 4L, NA, 999L)), identicalTo(as.name("1")))
test.as.name.10 <- function() assertThat(as.name(c(1L, 2L, 1073741824L, 1073741824L)), identicalTo(as.name("1")))
test.as.name.11 <- function() assertThat(as.name(numeric(0)), throwsError())
test.as.name.12 <- function() assertThat(as.name(c(3.14159, 6.28319, 9.42478, 12.5664, 15.708)), identicalTo(as.name("3.14159")))
test.as.name.13 <- function() assertThat(as.name(c(-3.14159, -6.28319, -9.42478, -12.5664, -15.708)), identicalTo(as.name("-3.14159")))
test.as.name.14 <- function() assertThat(as.name(structure(1:2, .Names = c("a", "b"))), identicalTo(as.name("1")))
test.as.name.15 <- function() assertThat(as.name(structure(c(1.5, 2.5), .Names = c("a", "b"))), identicalTo(as.name("1.5")))
test.as.name.16 <- function() assertThat(as.name(c(1.5, 1.51, 0, 1.49, -30)), identicalTo(as.name("1.5")))
test.as.name.17 <- function() assertThat(as.name(c(1.5, 1.51, 0, 1.49, -30, NA)), identicalTo(as.name("1.5")))
test.as.name.18 <- function() assertThat(as.name(c(1.5, 1.51, 0, 1.49, -30, NaN)), identicalTo(as.name("1.5")))
test.as.name.19 <- function() assertThat(as.name(c(1.5, 1.51, 0, 1.49, -30, Inf)), identicalTo(as.name("1.5")))
test.as.name.20 <- function() assertThat(as.name(c(1.5, 1.51, 0, 1.49, -30, -Inf)), identicalTo(as.name("1.5")))
test.as.name.21 <- function() assertThat(as.name(character(0)), throwsError())
test.as.name.22 <- function() assertThat(as.name(c("4.1", "blahh", "99.9", "-413", NA)), identicalTo(as.name("4.1")))
test.as.name.23 <- function() assertThat(as.name(complex(0)), throwsError())
test.as.name.24 <- function() assertThat(as.name(list(1, 2, 3)), throwsError())
test.as.name.25 <- function() assertThat(as.name(list(1, 2, NULL)), throwsError())
test.as.name.26 <- function() assertThat(as.name(list(1L, 2L, 3L)), throwsError())
test.as.name.27 <- function() assertThat(as.name(list(1L, 2L, NULL)), throwsError())
test.as.name.28 <- function() assertThat(as.name(list(1, 2, list(3, 4))), throwsError())
test.as.name.29 <- function() assertThat(as.name(list(1, 2, numeric(0))), throwsError())
test.as.name.30 <- function() assertThat(as.name(list(3, "a", structure(list("b", list(TRUE, "c")), .Names = c("", "z")))), throwsError())
test.as.name.31 <- function() assertThat(as.name(structure(list(1, 2, 3), .Names = c(NA, "", "b"))), throwsError())
test.as.name.32 <- function() assertThat(as.name(pairlist(41, "a", 21L)), throwsError())
test.as.name.33 <- function() assertThat(as.name(structure(pairlist(a = 41, 42))), throwsError())
test.as.name.34 <- function() assertThat(as.name(structure(pairlist(a = 41, NULL))), throwsError())
test.as.name.35 <- function() assertThat(as.name(structure(1:12, .Dim = 3:4)), identicalTo(as.name("1")))
test.as.name.36 <- function() assertThat(as.name(structure(1:12, .Dim = 3:4, .Dimnames = structure(list( c("a", "b", "c"), c("d", "e", "f", "g")), .Names = c("x", "y")))), identicalTo(as.name("1")))
test.as.name.37 <- function() assertThat(as.name(structure(1:3, rando.attrib = 941L)), identicalTo(as.name("1")))
test.as.name.38 <- function() assertThat(as.name(structure(1:3, .Dim = 3L, .Dimnames = list(c("a", "b", "c")))), identicalTo(as.name("1")))
test.as.name.39 <- function() assertThat(as.name(structure(1:3, .Dim = 3L, .Dimnames = structure(list( c("a", "b", "c")), .Names = "z"))), identicalTo(as.name("1")))
test.as.name.40 <- function() assertThat(as.name(structure(list("foo"), class = "foo")), identicalTo(99))
test.as.name.41 <- function() assertThat(as.name(structure(list("bar"), class = "foo")), identicalTo(99))
test.as.name.42 <- function() assertThat(as.name(quote(xyz)), identicalTo(as.name("xyz")))
test.as.name.43 <- function() assertThat(as.name(quote(sin(3.14))), throwsError())
test.as.name.44 <- function() assertThat(as.name("NaN"), identicalTo(as.name("NaN")))
test.as.name.45 <- function() assertThat(as.name("NABOOM!"), identicalTo(as.name("NABOOM!")))
test.as.name.46 <- function() assertThat(as.name("NaNaNabooboo"), identicalTo(as.name("NaNaNabooboo")))
test.as.name.47 <- function() assertThat(as.name("-Inf"), identicalTo(as.name("-Inf")))
test.as.name.48 <- function() assertThat(as.name("+Infinity"), identicalTo(as.name("+Infinity")))
test.as.name.49 <- function() assertThat(as.name("Infinity and beyond!"), identicalTo(as.name("Infinity and beyond!")))
test.as.name.50 <- function() assertThat(as.name("Infi"), identicalTo(as.name("Infi")))
test.as.name.51 <- function() assertThat(as.name("0.03f"), identicalTo(as.name("0.03f")))
test.as.name.52 <- function() assertThat(as.name(" 0.0330 "), identicalTo(as.name(" 0.0330 ")))
test.as.name.53 <- function() assertThat(as.name(structure("foo", class = "foo")), identicalTo(99))
test.as.name.54 <- function() assertThat(as.name(structure(list(1L, "bar"), class = "bar")), identicalTo(98)) |
source("ESEUR_config.r")
library(car)
pal_col=rainbow(3)
loc_hour=read.csv(paste0(ESEUR_dir, "regression/10.1.1.157.6206.csv.xz"), as.is=TRUE)
loc_hour=subset(loc_hour, !is.na(KLoC))
loc_hour=loc_hour[order(loc_hour$Hours), ]
row.names(loc_hour)=1:nrow(loc_hour)
x_bounds=range(loc_hour$Hours)
y_bounds=range(loc_hour$KLoC)
Hours_KLoC=function(df)
{
plot(df$Hours, df$KLoC, col=pal_col[2],
xaxs="i", yaxs="i",
xlim=x_bounds, ylim=y_bounds,
xlab="Effort (hours)", ylab="Lines of code (Kloc)\n")
plh_mod=glm(KLoC ~ I(Hours^0.5), data=df)
plh_pred=predict(plh_mod, type="response", se.fit=TRUE)
lines(df$Hours, plh_pred$fit, col=pal_col[1])
lines(df$Hours, plh_pred$fit+plh_pred$se.fit*1.96, col=pal_col[3])
lines(df$Hours, plh_pred$fit-plh_pred$se.fit*1.96, col=pal_col[3])
return(plh_mod)
}
plot_cutoff=function(df, model)
{
cutoff=4/(nrow(df)+1+1)
plot(model, which=4, cook.levels=cutoff, caption="")
abline(h=cutoff, lty=2, col="red")
}
s1_loc_hour=loc_hour[-c(21,25), ]
s2_loc_hour=s1_loc_hour[-c(24), ]
s1_loc_hour=loc_hour[-c(21,25,29),]
s2_loc_hour=s1_loc_hour[-c(23,24,26),]
s3_loc_hour=s2_loc_hour[-c(19,23),]
s4_loc_hour=s3_loc_hour[-c(4,19,20),]
s5_loc_hour=s4_loc_hour[-c(17),]
s6_loc_hour=s5_loc_hour[-c(17),]
s7_loc_hour=s6_loc_hour[-c(12,14),]
s8_loc_hour=s7_loc_hour[-c(12),]
s9_loc_hour=s8_loc_hour[-c(12),]
s10_loc_hour=s9_loc_hour[-c(12),]
subset10_mod=Hours_KLoC(s10_loc_hour) |
nomis_content_type <- function(content_type, id = NULL) {
if (missing(content_type)) {
stop("content_type must be specified", call. = FALSE)
}
if (is.null(id)) {
id_query <- ""
} else {
id_query <- paste0("/id/", id)
}
content_query <- paste0(content_url, content_type, id_query, ".json")
content_query2 <- jsonlite::fromJSON(content_query, flatten = TRUE)
df <- tibble::as_tibble(data.frame(content_query2$contenttype$item))
df
} |
FinTS.url <- "http://faculty.chicagogsb.edu/ruey.tsay/teaching/fts2"
localDir <- "~/TsayFiles/"
Tsay.webPage <- scan(FinTS.url, what=character(0), sep="\n")
n.webLines <- length(Tsay.webPage)
(Ch <- paste("Chapter ", 1:12, ":", sep=""))
(twelve <- c(paste("0", 1:9, sep=""), 10:12))
(ch <- paste("ch", twelve, sep=""))
names(Ch) <- ch
ch. <- rep(NA, 12)
names(ch.) <- ch
for(i in 1:12)
ch.[i] <- grep(Ch[i], Tsay.webPage)
Tsay.webPage[ch.]
(ex <- grep("Exercise", Tsay.webPage))
chEnd <- c(ch.[-1]-1, n.webLines)
names(chEnd) <- ch
ex. <- chEnd
i <- 1
for(ich in 1:12){
if(ex[i] < chEnd[ich]){
ex.[ich] <- ex[i]
i <- i+1
}
}
(ChEx <- cbind(ch=ch., ex=ex., end=chEnd))
Tsay.http <- grep("http://", Tsay.webPage)
Tsay.http. <- Tsay.webPage[Tsay.http]
http.start <- regexpr("http://", Tsay.http.)
Tsay.ht1 <- substring(Tsay.http., http.start)
http.stop <- regexpr("\"", Tsay.ht1)
Tsay.ht2 <- substring(Tsay.ht1, 1, http.stop-1)
Tsay.ht2. <- strsplit(Tsay.ht2[-1], "/")
Tsay.ht3 <- sapply(Tsay.ht2., function(x)x[length(x)])
Tsay.ht4 <- Tsay.ht2[-(1:10)]
names(Tsay.ht4) <- Tsay.ht3[-(1:9)]
Tsay.ht4. <- Tsay.http[-(1:10)]
last4 <- substring(Tsay.ht4, nchar(Tsay.ht4)-3)
table(last4)
fileTypes <- c("dat", "txt", "sor", "rats", "f")
kTypes <- length(fileTypes)
filesByType <- vector("list", length=kTypes)
names(filesByType) <- fileTypes
for(i in 1:kTypes){
fti <- paste(".", fileTypes[i], "$", sep="")
filesByType[[i]] <- grep(fti, Tsay.ht4)
}
(fileLineNums <- sort(unlist(filesByType)))
fLNm <- Tsay.http[-(1:10)][fileLineNums]
TsayFiles <- vector("list", length=12)
names(TsayFiles) <- ch
for(ich in 1:12){
sel <- ((ChEx[ich, 1]<=fLNm) & (fLNm<=ChEx[ich, 2]))
TsayFiles[[ich]]$text <- url2dat(Tsay.ht4[sel])
sel2 <- ((ChEx[ich, 2]<=fLNm) & (fLNm<=ChEx[ich, 3]))
TsayFiles[[ich]]$exercises <- url2dat(Tsay.ht4[sel2])
}
readSum <- array(0, dim=c(12, 2, 2), dimnames=list(
ch, c("text", "exercises"), c("FALSE", "TRUE") ) )
for(ich in 1:12)for(j in 1:2){
TFij <- TsayFiles[[ich]][[j]]
{
if(dim(TFij)[1]>0){
tij <- table(TFij[, 4])
readSum[ich, j, names(tij)] <- tij
}
else
readSum[ich, j, ] <- 0
}
}
sum(readSum[,,"FALSE"])
sum(readSum[,,"TRUE"])
TsayFiles$ch01$exercises[, 2]
TsayFileNames <- sapply(TsayFiles, function(x)
sapply(x, function(x2)x2[, 2]))
uniqueFileNames <- table(unlist(TsayFileNames))
duplicatedFiles <- uniqueFileNames[uniqueFileNames>1]
sort(duplicatedFiles)
save(TsayFiles, file="TsayFiles.rda") |
this_week <-
function(x = Sys.Date(),
part = getOption("timeperiodsR.parts"),
week_start = 1) {
if ( ! "Date" %in% class(x) ) {
x <- as.Date(x)
}
start <- floor_date( x, unit = "week", week_start)
stop <- start + days(6)
out <- custom_period(start, stop)
part <- match.arg(part, getOption("timeperiodsR.parts"))
if ( part == "all" ) {
return(out)
} else {
return(out[[part]])
}
} |
`write.tucson` <-
function(rwl.df, fname, header=NULL, append=FALSE, prec=0.01,
mapping.fname="", mapping.append=FALSE, long.names=FALSE,
...)
{
line.term <- "\x0D\x0A"
if (!is.data.frame(rwl.df)) {
stop("'rwl.df' must be a data.frame")
}
if (!is.numeric(prec) || length(prec) != 1 || is.na(prec) ||
!(prec == 0.01 || prec == 0.001)) {
stop("'prec' must equal 0.01 or 0.001")
}
header2 <- header
if (append) {
if (!file.exists(fname)) {
stop(gettextf("file %s does not exist, cannot append", fname))
}
if (length(header2) > 0) {
stop("bad idea to append with 'header'")
}
}
if (length(header2) > 0) {
if (!is.list(header2)) {
stop("'header' must be a list")
}
header.names <-
c("site.id", "site.name", "spp.code", "state.country",
"spp", "elev", "lat", "long", "first.yr", "last.yr",
"lead.invs", "comp.date")
if (!all(header.names %in% names(header2))) {
stop("'header' must be a list with the following names: ",
paste(dQuote(header.names), collapse = ", "))
}
header2 <- lapply(header2, as.character)
site.id <- header2$site.id[1]
site.name <- header2$site.name[1]
spp.code <- header2$spp.code[1]
state.country <- header2$state.country[1]
spp <- header2$spp[1]
elev <- header2$elev[1]
lat <- header2$lat[1]
long <- header2$long[1]
lead.invs <- header2$lead.invs[1]
comp.date <- header2$comp.date[1]
lat.long <- if (isTRUE(nchar(long) > 5)) {
paste0(lat, long)
} else {
paste(lat, long, sep=" ")
}
yrs <- paste(header2$first.yr[1], header2$last.yr[1], sep=" ")
field.name <-
c("site.id", "site.name", "spp.code", "state.country", "spp",
"elev", "lat.long", "yrs", "lead.invs", "comp.date")
field.width <- c(6, 52, 4, 13, 18, 5, 10, 9, 63, 8)
for (i in seq_along(field.name)) {
this.name <- field.name[i]
this.width <- field.width[i]
this.var <- get(this.name)
this.nchar <- nchar(this.var)
if (this.nchar > this.width) {
assign(this.name, substr(this.var, 1, this.width))
} else if (this.nchar < this.width) {
assign(this.name, encodeString(this.var, width = this.width))
}
}
hdr1 <- paste0(site.id, " ", site.name, spp.code)
hdr2 <- paste0(site.id, " ", state.country, spp, " ", elev, " ",
lat.long, " ", yrs)
hdr3 <- paste0(site.id, " ", lead.invs, comp.date)
}
nseries <- ncol(rwl.df)
yrs.all <- as.numeric(row.names(rwl.df))
col.names <- names(rwl.df)
stopifnot(is.character(col.names), !is.na(col.names),
Encoding(col.names) != "bytes")
yrs.order <- sort.list(yrs.all)
yrs.all <- yrs.all[yrs.order]
rwl.df2 <- rwl.df[yrs.order, , drop=FALSE]
first.year <- yrs.all[1]
last.year <- yrs.all[length(yrs.all)]
long.years <- FALSE
if (first.year < -999) {
long.years <- TRUE
if (first.year < -9999) {
stop("years earlier than -9999 (10000 BC) are not supported")
}
}
if (last.year > 9999) {
long.years <- TRUE
if (last.year > 99999) {
stop("years later than 99999 are not possible")
}
}
name.width <- 7
if (long.names) {
exploit.short <- TRUE
use.space <- FALSE
} else {
exploit.short <- FALSE
use.space <- TRUE
}
if (exploit.short && !long.years) {
name.width <- name.width + 1
}
if (use.space) {
name.width <- name.width - 1
opt.space <- " "
} else {
opt.space <- ""
}
name.width <- as.integer(name.width)
year.width <-
as.integer(12 - name.width - nchar(opt.space))
col.names <-
fix.names(col.names, name.width, mapping.fname, mapping.append)
if (append) {
rwl.out <- file(fname, "a")
} else {
rwl.out <- file(fname, "w")
}
on.exit(close(rwl.out))
if (length(header2) > 0) {
cat(hdr1, line.term, file=rwl.out, sep="")
cat(hdr2, line.term, file=rwl.out, sep="")
cat(hdr3, line.term, file=rwl.out, sep="")
}
if (prec == 0.01) {
na.str <- 9.99
missing.str <- -9.99
prec.rproc <- 100
} else {
na.str <- -9.999
missing.str <- 0
prec.rproc <- 1000
}
format.year <- sprintf("%%%d.0f", year.width)
for (l in seq_len(nseries)) {
series <- rwl.df2[[l]]
idx <- !is.na(series)
yrs <- yrs.all[idx]
series <- series[idx]
series <- c(series, na.str)
yrs <- c(yrs, max(yrs) + 1)
decades.vec <- yrs %/% 10 * 10
decades <- seq(from=min(decades.vec), to=max(decades.vec), by=10)
n.decades <- length(decades)
rwl.df.name <- col.names[l]
rwl.df.name <- str_pad(rwl.df.name, name.width, side = "right")
for (i in seq_len(n.decades)) {
dec <- decades[i]
dec.idx <- decades.vec %in% dec
dec.yrs <- yrs[dec.idx]
dec.rwl <- series[dec.idx]
neg.match <- dec.rwl < 0
if (prec == 0.001 && i == n.decades) {
neg.match[length(neg.match)] <- FALSE
}
dec.rwl[neg.match] <- missing.str
if (n.decades == 1) {
all.years <- dec.yrs[1]:dec.yrs[length(dec.yrs)]
} else if (i == 1) {
all.years <- dec.yrs[1]:(dec + 9)
} else if (i == n.decades) {
all.years <- dec:dec.yrs[length(dec.yrs)]
} else {
all.years <- dec:(dec + 9)
}
if (length(all.years) > length(dec.yrs)) {
missing.years <- setdiff(all.years, dec.yrs)
dec.yrs <- c(dec.yrs, missing.years)
dec.rwl <- c(dec.rwl,
rep(missing.str, times=length(missing.years)))
dec.order <- sort.list(dec.yrs)
dec.yrs <- dec.yrs[dec.order]
dec.rwl <- dec.rwl[dec.order]
}
dec.year1 <- sprintf(format.year, dec.yrs[1])
dec.rwl <- round(dec.rwl * prec.rproc)
if (prec == 0.01) {
end.match <- dec.rwl == 999
if (i == n.decades) {
end.match[length(end.match)] <- FALSE
}
dec.rwl[end.match] <-
sample(c(998, 1000), sum(end.match), replace=TRUE)
}
dec.rwl <- sprintf("%6.0f", dec.rwl)
cat(rwl.df.name, opt.space, dec.year1, dec.rwl, line.term,
file = rwl.out, sep="")
}
}
fname
} |
context("isScalarValue")
test_that("isScalarValue", {
expect_true(isScalarValue(1))
expect_true(isScalarValue(1L))
expect_true(isScalarValue("a"))
expect_true(isScalarValue(factor("a")))
expect_true(isScalarValue(as.complex(1)))
expect_true(isScalarValue(NA))
expect_true(isScalarNumeric(1))
expect_true(isScalarInteger(1L))
expect_true(isScalarCharacter("a"))
expect_true(isScalarFactor(factor("a")))
expect_true(isScalarComplex(as.complex(1)))
expect_true(isScalarLogical(NA))
expect_false(isScalarComplex(1L))
expect_false(isScalarInteger(1))
expect_false(isScalarFactor("a"))
expect_false(isScalarCharacter(factor("a")))
expect_false(isScalarNumeric(as.complex(1)))
expect_false(isScalarInteger(NA))
expect_false(isScalarValue(NULL))
expect_false(isScalarValue(iris))
expect_false(isScalarValue(1:2))
expect_false(isScalarValue(list(1)))
expect_true(isScalarValue(NULL, null.ok=TRUE))
expect_false(isScalarValue(NULL, na.ok=FALSE))
}) |
pairs.lavaan <- function(x, group=1L, ...) {
X <- x@Data@X[[group]]
colnames(X) <- x@[email protected][[group]]
pairs(X, ...)
} |
NULL
docnames.spacyr_parsed <- function(x) {
unique(x$doc_id)
}
ndoc.spacyr_parsed <- function(x) {
length(docnames(x))
}
ntoken.spacyr_parsed <- function(x, ...) {
lengths(split(x$token, x$doc_id))
}
ntype.spacyr_parsed <- function(x, ...) {
vapply(split(x$token, x$doc_id), function(y) length(unique(y)), integer(1))
}
nsentence.spacyr_parsed <- function(x, ...) {
sapply(split(x, x$doc_id), function(y) length(unique(y$sentence_id)))
} |
knitr::opts_chunk$set(echo = TRUE)
knitr::opts_chunk$set(cache= FALSE)
library(rangeModelMetadata)
library(raster)
rmm <- rmmTemplate(family=c('base'))
rmm$authorship$rmmName <- 'Owens_2015_Gadids'
rmm$authorship$names <- 'Owens, Hannah'
rmm$authorship$contact <- '[email protected]'
rmm$authorship$relatedReferences <- '@article{, title={Evolution of codfishes (Teleostei: Gadinae) in geographical and ecological space: evidence that physiological limits drove diversification of subarctic fishes},author={Owens, Hannah},journal={Journal of Biogeography}, year={2015}, publisher={Wiley-Blackwell}}'
rmm$data$occurrence$taxon <- c("Arctogadus borisovi", "Arcogadus glacialis", "Boreogadus saida", "Eleginus gracilis", "Gadus macrocephalus", "Gadus morhua", "Gadus ogac", "Melanogrammus aeglefinus", "Merlangius merlangus", "Microgadus proximus", "Microgadus tomcod", "Pollachius pollachius", "Pollachius virens", "Gadus chalcogrammus", "Trisopterus esmarkii", "Trisopterus luscus", "Trisopterus minutus")
rmm$data$occurrence$dataType <- c("Presence only")
rmm$data$occurrence$sources <- c("Global Biodiversity
Information Facility (GBIF)", "Ocean Biogeographic Information System (OBIS)", "Zoological Institute at the Russian Academy of Sciences (ZIN)", "Natural History Museum in London (NHMUK)")
rmm$data$occurrence$presenceSampleSize <- c(16, 41, 534, 121, 249, 448, 116, 273, 151, 46, 25, 68, 200, 282, 4, 5, 128)
rmm$data$occurrence$backgroundSampleSizeSet <- 10000
rmm$data$environment$variableNames <- c("Minimum Sea Ice Concentration", "Maximum Sea Ice Concentration", "Mean Mixed Layer Depth", "Minimum Mixed Layer Depth", "Maximum Mixed Layer Depth", "Mean Bottom Salinity", "Minimum Bottom Salinity", "Maximum Bottom Salinity", "Mean Surface Salinity", "Minimum Surface Salinity", "Maximum Surface Salinity", "Mean Bottom Temperature", "Minimum Bottom Temperature", "Maximum Bottom Temperature", "Mean Surface Temperature", "Minimum Surface Temperature", "Maximum Surface Temperature")
rmm$data$environment$extentSet <- list(
extent(-180,180,50.06732,90.06732),
extent(-180,180,54.77051,89.77051),
extent(-180,180,36.77808,89.77808),
extent(-180,180,39.46948,81.46948),
extent(-180,180,23.25928 ,74.25928),
extent(-80.8255,52.1745,32.15668,84.15668),
extent( -169.2665,-31.26648,35.74249,82.74249),
extent(-77.09869,56.90131,35.9895,82.9895),
extent(-27.11713,42.88287,29.41553 ,72.41553),
extent(-180,-115,31.06689 ,67.06689),
extent(-74.711,-54.711,38.268,52.268),
extent(-25.20459,34.79541,41.92908,75.92908),
extent(-79.63971,33.36029,32.28247,84.28247),
extent(-180,180,28.88068,75.88068),
extent(-26.31464,28.68536,42.62609,79.62609),
extent(-20.26068,26.73932,23.31372,64.31372),
extent(-20.40668,39.593,25.8183,71.8183))
rmm$data$environment$resolution <- "1 X 1 degree"
rmm$data$environment$sources <- c("NOAA National Geophysical Data Center", "NOAA World Ocean Atlas", "NOAA National Snow and Ice Data Center")
rmm$data$transfer$environment1$resolution <- "1 X 1 degree"
rmm$data$transfer$environment1$sources <- c("NOAA National Geophysical Data Center", "NOAA World Ocean Atlas", "NOAA National Snow and Ice Data Center")
rmm$dataPrep$duplicateRemoval$rule <- "coordinate"
rmm$dataPrep$questionablePointRemoval$notes <- "Points outside known distribution of species removed."
rmm$dataPrep$pointInPolygon$rule <- "Remove points outside training region of species."
rmm$dataPrep$spatialThin$rule <- "Reduced spatial resolution of points to match resolution of environmental data (1 X 1 resolution)."
rmm$modelFit$algorithm <- "maxent"
rmm$modelFit$algorithmCitation <- '@inproceedings{phillips2004maximum, title={A maximum entropy approach to species distribution modeling}, author={Phillips, Steven J and Dudik, Miroslav and Schapire, Robert E}, booktitle={Proceedings of the twenty-first international conference on Machine learning},pages={83},year={2004},organization={ACM}}'
rmm$modelFit$maxent$featureSet <- "LQP"
rmm$modelFit$maxent$notes <- "Ten bootstrap replicates trained with 50% of occurrence points chosen using random seed, maximum of 10000 iterations"
rmm$prediction$continuous$units <- "absolute probability"
rmm$prediction$transfer$environment1$units <- "absolute probability"
rmm$prediction$transfer$environment1$extrapolation <- "No clamping or extrapolation"
rmm$evaluation$notes <- "Inferred distribution congruent with known ranges for all species."
rmmClean <- rmmCleanNULLs(rmm)
rmmCheckFinalize(rmmClean) |
help.map.name <- function(x)
{
if(is.null(x))
return("")
x <- splitme(x)
if(resplit(x[1L:2L]) == "s(") {
x <- resplit(c("sfoofun", x[2L:length(x)]))
x <- eval(parse(text = x), envir = parent.frame())
if(is.null(x))
x <- "bayesxmap"
} else x <- "bayesxmap"
return(x)
} |
context("AdjustmentService")
skip("Reduce Total Test Runtime")
rdfp_options <- readRDS("rdfp_options.rds")
options(rdfp.network_code = rdfp_options$network_code)
options(rdfp.httr_oauth_cache = FALSE)
options(rdfp.application_name = rdfp_options$application_name)
options(rdfp.client_id = rdfp_options$client_id)
options(rdfp.client_secret = rdfp_options$client_secret)
dfp_auth(token = "rdfp token.rds")
test_that("dfp_getTrafficAdjustmentsByStatement", {
request_data <- list(filterStatement=list('query'="WHERE status='ACTIVE'"))
dfp_getTrafficAdjustmentsByStatement_result <- dfp_getTrafficAdjustmentsByStatement(request_data)
expect_is(dfp_getTrafficAdjustmentsByStatement_result, "list")
})
test_that("dfp_updateTrafficAdjustments", {
skip()
}) |
library("permutations")
jj <- array(c(
010,012,014,016,018, 011,013,015,017,019, 021,033,045,057,069, 022,034,046,058,060, 023,035,047,059,061,
020,022,024,026,028, 021,023,025,027,029, 015,067,091,081,035, 016,068,092,082,036, 017,069,093,083,037,
030,032,034,036,038, 031,033,035,037,039, 017,029,089,079,047, 018,020,080,070,048, 019,021,081,071,049,
040,042,044,046,048, 041,043,045,047,049, 010,032,078,118,050, 011,033,079,119,051, 019,031,077,117,059,
050,052,054,056,058, 051,053,055,057,059, 011,043,115,105,061, 012,044,116,106,062, 013,045,117,107,063,
060,062,064,066,068, 061,063,065,067,069, 013,055,103,093,023, 014,056,104,094,024, 015,057,105,095,025,
070,072,074,076,078, 071,073,075,077,079, 030,088,120,110,040, 031,089,121,111,041, 039,087,129,119,049,
080,082,084,086,088, 081,083,085,087,089, 027,099,121,071,037, 028,090,122,072,038, 029,091,123,073,039,
090,092,094,096,098, 091,093,095,097,099, 025,065,101,123,083, 026,066,102,124,084, 027,067,103,125,085,
100,102,104,106,108, 101,103,105,107,109, 053,113,125,095,063, 054,114,126,096,064, 055,115,127,097,065,
110,112,114,116,118, 111,113,115,117,119, 041,075,127,107,051, 042,076,128,108,052, 043,077,129,109,053,
120,122,124,126,128, 121,123,125,127,129, 073,085,097,109,111, 074,086,098,100,112, 075,087,099,101,113
),c(5,5,12))
megaminx <- rep(id,12)
chosen <- seq_len(5)
for(i in seq_len(12)){
for(j in chosen){
megaminx[i] <- megaminx[i] + as.cycle(jj[,j,i])
}
}
rm(i,j,jj)
names(megaminx) <- c("White", "Purple", "DarkYellow", "DarkBlue", "Red",
"DarkGreen", "LightGreen", "Orange", "LightBlue",
"LightYellow", "Pink", "Grey")
"W" <- megaminx[01]
"Pu" <- megaminx[02]
"DY" <- megaminx[03]
"DB" <- megaminx[04]
"R" <- megaminx[05]
"DG" <- megaminx[06]
"LG" <- megaminx[07]
"O" <- megaminx[08]
"LB" <- megaminx[09]
"LY" <- megaminx[10]
"Pi" <- megaminx[11]
"Gy" <- megaminx[12]
megaminx_colours <- noquote(rep("Black",126))
megaminx_colours[010:019] <- "White"
megaminx_colours[020:029] <- "Purple"
megaminx_colours[030:039] <- "DarkYellow"
megaminx_colours[040:049] <- "DarkBlue"
megaminx_colours[050:059] <- "Red"
megaminx_colours[060:069] <- "DarkGreen"
megaminx_colours[070:079] <- "LightGreen"
megaminx_colours[080:089] <- "Orange"
megaminx_colours[090:099] <- "LightBlue"
megaminx_colours[100:109] <- "LightYellow"
megaminx_colours[110:119] <- "Pink"
megaminx_colours[120:129] <- "Grey" |
biasCorrectionBernoulli <- function(object){
zeroLessModel <- deleteZeroComponents(object)
if (inherits(zeroLessModel, "glm")) {
return(zeroLessModel$rank)
}
signCor <- - 2 * zeroLessModel@resp$y + 1
muHat <- zeroLessModel@resp$mu
workingEta <- numeric(length(muHat))
for(i in 1:length(muHat)){
workingData <- zeroLessModel@resp$y
workingData[i] <- 1 - workingData[i]
workingModel <- refit(zeroLessModel, nresp = workingData)
workingEta[i] <- log(workingModel@resp$mu[i] / (1 - workingModel@resp$mu[i])) - log(muHat[i] / (1 - muHat[i]))
}
bc <- sum(muHat * (1 - muHat) * signCor * workingEta)
if (identical(object, zeroLessModel)) {
newModel <- NULL
new <- FALSE
} else {
newModel <- zeroLessModel
new <- TRUE
}
return(list(bc = bc, newModel = newModel, new = new))
} |
context("Benchmark against Touw and Hoogduin (2011)")
test_that(desc = "(id: f14-v0.5.1-t1) Test Sample sizes on page 17", {
SR <- c(0.05, 0.10, 0.25, 0.40, 0.50)
materiality <- 0.01
n <- numeric(length(SR))
for (i in 1:length(SR)) {
n[i] <- jfa::planning(conf.level = 1 - SR[i], materiality = materiality, likelihood = "poisson")$n
}
expect_equal(n, c(300, 230 + 1, 140 - 1, 90 + 2, 70))
})
test_that(desc = "(id: f14-v0.5.1-t2) Test Sample sizes on page 23", {
n <- jfa::planning(conf.level = 1 - 0.05, materiality = 100000 / 5000000, likelihood = "poisson")$n
expect_equal(n, 150)
n <- jfa::planning(conf.level = 1 - 0.125, materiality = 100000 / 5000000, likelihood = "poisson")$n
expect_equal(n, 104)
}) |
csmk.test <- function(x, alternative = c("two.sided", "greater", "less"))
{
if(!is.ts(x)){
stop("'x' must be objects of class 'ts'")
}
p <- frequency(x)
if (p < 2){
stop("'x' must have at least 2 seasons")
}
na.fail(x)
alternative = match.arg(alternative)
n <- length(x)
dat <- matrix(NA, ncol = p, nrow = n / p)
for (i in 1:p)
{
dat[,i] <- x[cycle(x) == i]
}
inp <- list(
x = ts(dat),
alternative = alternative)
out <- do.call("mult.mk.test", inp)
DNAME <- deparse(substitute(x))
METHOD <- "Correlated Seasonal Mann-Kendall Test"
out$method <- METHOD
out$data.name <- DNAME
return(out)
} |
define <- function(x,...)UseMethod('define')
define.character<- function(
x,
stem = 'define',
tag = names(x),
description = basename(x),
title = dirname(x[[1]]),
short = title,
protocol = '~',
sponsor = '~',
program = '~',
author = '~',
date = '\\mydate \\today',
logo = NULL,
logoscale = 1,
dir = './define',
subdir = '.',
clear = TRUE,
units = FALSE,
...
){
if(clear)unlink(dir, recursive = TRUE,force = TRUE)
if(!file.exists(dir)) dir.create(dir,recursive = TRUE)
stopifnot(file.exists(dir))
stopifnot(
length(description) == length(x),
length(tag) == length(x),
length(dir) == 1,
is.null(subdir) | length(subdir) %in% c(1,length(x)),
length(title) == 1,
length(short) == 1,
length(protocol) == 1,
length(sponsor) == 1,
length(program) == 1,
length(author) == 1,
length(date) == 1
)
description <- as.character(description)
title <- as.character(title)
short <- as.character(short)
protocol <- as.character(protocol)
sponsor <- as.character(sponsor)
program <- as.character(program)
author <- as.character(author)
date <- as.character(date)
y <- as.submission(
x = x,
tag = tag,
description = description,
dir = dir,
subdir = subdir,
...
)
z <- as.document(
y,
title = title,
short = short,
protocol = protocol,
sponsor = sponsor,
program = program,
author = author,
date = date,
logo = logo,
logoscale = logoscale,
units = units,
...
)
as.pdf(z,stem = stem,dir = dir,...)
} |
best_roster <- function(leagueId = ffl_id(),
useScore = c("actualScore", "projectedScore"),
scoringPeriodId = NULL, ...) {
useScore <- match.arg(useScore, c("actualScore", "projectedScore"))
dat <- ffl_api(
leagueId = leagueId,
view = c("mRoster", "mSettings", "mTeam"),
scoringPeriodId = scoringPeriodId,
...
)
set <- out_roster_set(dat)
slot_count <- set$lineupSlotCounts[[1]]
do_slot <- as.integer(slot_count$position[slot_count$limit > 0])
do_slot <- pos_ids$slot[pos_ids$slot %in% do_slot]
rosters <- lapply(
X = seq_along(dat$teams$roster$entries),
FUN = function(i) {
out_roster(
entry = dat$teams$roster$entries[[i]],
tid = dat$teams$id[i],
wk = dat$scoringPeriodId,
yr = dat$seasonId,
tm = out_team(dat$teams, trim = TRUE),
es = TRUE
)
}
)
names(rosters) <- dat$teams$abbrev
lapply(rosters, out_best, do_slot, slot_count, score_col = useScore)
}
out_best <- function(r,
do_slot,
slot_count,
score_col) {
most_elig <- names(sort(table(unlist(r$eligibleSlots))))
most_elig <- most_elig[most_elig %in% do_slot]
most_elig <- most_elig[most_elig != "21" & most_elig != "25"]
best <- data.frame()
for (s in most_elig) {
n_max <- slot_count$limit[slot_count$position == s]
is_elig <- sapply(r$eligibleSlots, has_slot, s)
n_elig <- sum(is_elig)
if (n_elig < n_max) {
if (s != "20") {
warning(
sprintf("Slot %s has %i maximum but %i eligible", s, n_max, n_elig),
call. = FALSE
)
}
if (n_elig == 0) {
next
}
n_max <- n_elig
}
can_max <- r[is_elig, ]
if (n_elig > 1) {
can_max <- can_max[order(can_max[[score_col]], decreasing = TRUE), ]
}
can_max <- can_max[seq(n_max), ]
can_max$actualSlot <- can_max$lineupSlot
can_max$lineupSlot <- slot_abbrev(s)
best <- rbind(best, can_max)
r <- r[!(r$playerId %in% best$playerId), ]
}
if (nrow(r) > 0) {
n_ir <- slot_count$limit[slot_count$position == 21]
if (nrow(r) == n_ir & all(r$lineupSlot == "IR")) {
r$actualSlot <- r$lineupSlot
best <- rbind(best, r)
}
}
best <- move_col(best, "actualSlot", 6)
best$eligibleSlots <- NULL
best[order(best$lineupSlot), ]
}
has_slot <- function(eligibleSlots, slot) {
slot %in% eligibleSlots
} |
checkJacobian <- function(x, f = psychonetrics_fitfunction_cpp, jac = psychonetrics_gradient_cpp, transpose = FALSE, plot = TRUE, perturbStart = FALSE){
start <- parVector(x)
if (perturbStart){
start <- start + runif(length(start),0,0.25)
}
analytic <- jac(start, x)
if (!is.matrix(analytic)){
analytic <- matrix(analytic)
}
numeric <- numDeriv::jacobian(f,start,model=x)
if (!is.matrix(numeric)){
numeric <- matrix(numeric)
}
if (transpose){
numeric <- t(numeric)
}
if (plot){
plot(Vec(analytic),Vec(numeric),xlab="analytic",ylab="numeric")
abline(0,1)
}
return(list(
analytic = as.vector(analytic),
numeric = as.vector(numeric)
))
}
checkFisher <- function(x, f = psychonetrics_gradient_cpp, fis = psychonetrics_FisherInformation_cpp, transpose = FALSE, plot = TRUE, perturbStart = FALSE){
analytic <- fis(x)
if (!is.matrix(analytic)){
analytic <- matrix(analytic)
}
numeric <- psychonetrics_FisherInformation(x, analytic = FALSE)
if (!is.matrix(numeric)){
numeric <- matrix(numeric)
}
if (transpose){
numeric <- t(numeric)
}
if (plot){
plot(Vec(analytic),Vec(numeric),xlab="analytic",ylab="numeric")
abline(0,1)
}
return(list(
analytic = as.matrix(analytic),
numeric = as.matrix(numeric)
))
} |
targets::tar_test("knitr_deps() on a bad report", {
writeLines(c("```{r}", "1 <-", "```"), "report.Rmd")
expect_error(knitr_deps("report.Rmd"), class = "tar_condition_validate")
})
targets::tar_test("knitr_deps()", {
path <- system.file("example_rmd.Rmd", package = "tarchetypes")
expect_equal(
sort(knitr_deps(path)),
sort(c("analysis", "data", "data2", "string1", "string2", "string3"))
)
})
targets::tar_test("walk_call_knitr() finds function dependencies", {
f <- function() tar_load(x)
expect_equal(walk_ast(f, walk_call_knitr), "x")
})
targets::tar_test("walk_call_knitr() warns on empty tar_load()", {
expr <- quote(tar_load())
expect_warning(
out <- walk_ast(expr, walk_call_knitr),
class = "tar_condition_validate"
)
expect_equal(out, character(0))
})
targets::tar_test("walk_call_knitr() warns on empty tar_read()", {
expr <- quote(tar_read())
expect_warning(
out <- walk_ast(expr, walk_call_knitr),
class = "tar_condition_validate"
)
expect_equal(out, character(0))
})
targets::tar_test("walk_call_knitr() warns on tidyselect", {
expr <- quote(tar_load(starts_with("xyz")))
expect_warning(
out <- walk_ast(expr, walk_call_knitr),
class = "tar_condition_validate"
)
expect_equal(out, character(0))
}) |
r1 = aggregate(sr_MI, 5)
r2 = projectRaster(d2h_lrNA, r1)
r3 = isoStack(r1, r2)
dpts = sampleRandom(stack(r1, r2), 20, sp = TRUE)
dpts$weathered.mean = dpts$weathered.mean + rnorm(20, 0, 0.0005)
dpts$mean = dpts$mean + rnorm(20, 0, 8)
dpts$Site_ID = letters[1:20]
d1 = dpts[,1:2]
d2 = dpts
d3 = suppressWarnings(subOrigData(group = c("Raptor", "Passerine", "Water bird"),
mask = states[states$STATE_ABBR == "MI",],
ref_scale = NULL))
qa1 = suppressWarnings(QA(d1, r1, valiStation = 1, valiTime = 2, by = 25,
name = "Sr", bySite = FALSE))
qa2 = suppressWarnings(QA(d2, r3, valiStation = 1,
valiTime = 2, by = 25,
name = "Multi", setSeed = F))
qa3 = suppressWarnings(QA(d3, r2, valiStation = 1,
valiTime = 2, by = 25,
name = "SOD", setSeed = F))
test_that("QA and plot.QA work",{
expect_is(qa1, "QA")
expect_is(qa2, "QA")
expect_silent(plot(qa1, qa2))
expect_silent(plot(qa3))
expect_error(plot.QA(d1))
expect_error(plot.QA(qa1, outDir = 2))
expect_silent(plot.QA(qa1, qa2))
expect_silent(plot.QA(qa1, outDir = tempdir()))
}) |
library(dplyr)
RandomlyAugmentDataBaseline <- function(Data) {
order <- sample(1:5, 1)
valuestosample <- c(-100:-1, 1:100)
if(order == 1) Data*sample(valuestosample, 1)+sample(valuestosample, 1)
else if(order == 2) sample(valuestosample, 1)*Data^2 + sample(valuestosample, 1)*Data +sample(valuestosample, 1)
else if(order == 3) sample(valuestosample, 1)*Data^3 + sample(valuestosample, 1)* Data^2 + sample(valuestosample, 1)*Data+sample(valuestosample, 1)
else if(order == 4) sample(valuestosample, 1)* Data^4 + sample(valuestosample, 1)* Data^3 + sample(valuestosample, 1)* Data^2 + sample(valuestosample, 1)*Data + sample(valuestosample, 1)
else sample(valuestosample, 1)* Data^5 +sample(valuestosample, 1)*Data^4 + sample(valuestosample, 1)*Data^3 + sample(valuestosample, 1)*Data^2 + sample(valuestosample, 1)*Data+sample(valuestosample, 1)
}
augment_full <- function(Data){
Data %>%
select(-group) %>%
dplyr::group_by(sample_name) %>%
dplyr::arrange(wavenumber) %>%
dplyr::mutate(intensity_og = minmax(intensity)) %>%
dplyr::mutate(intensity_aug1 = minmax(intensity_og + rnorm(length(wavenumber), mean = 0, sd = 1/sample(c(30:300), 1)))) %>%
dplyr::mutate(intensity_aug2 = minmax(intensity_aug1 + minmax(RandomlyAugmentDataBaseline(wavenumber)))) %>%
ungroup()
}
get_lib()
spec_lib <- load_lib()
raman_subset <- unique(spec_lib$raman$library$sample_name)[sample(1:length(unique(spec_lib$raman$library$sample_name)), 100, replace = F)]
ftir_subset <- unique(spec_lib$ftir$library$sample_name)[sample(1:length(unique(spec_lib$ftir$library$sample_name)), 100, replace = F)]
augmented_raman <- augment_full(spec_lib$raman$library %>%
filter(sample_name %in% raman_subset)) %>%
mutate(intensity = intensity_aug2)
augmented_ftir <- augment_full(spec_lib$ftir$library %>%
filter(sample_name %in% ftir_subset))%>%
mutate(intensity = intensity_aug2)
raman_proc <- augmented_raman %>%
group_by(sample_name) %>%
smooth_intens(p = 3)
subtr_bg(degree = 8) %>%
mutate()
ftir_proc <- augmented_ftir %>%
group_by(sample_name) %>%
smooth_intens() %>%
subtr_bg()
spectrum = raman_subset[100]
ggplot() +
geom_line(data = augmented_raman %>%
filter(sample_name == spectrum),
aes(x = wavenumber, y = intensity)
) +
geom_line(data = augmented_raman %>%
filter(sample_name == spectrum) %>%
smooth_intens(p = 3) %>%
subtr_bg(degree = 8),
aes(x = wavenumber, y = intensity))
augmented_raman %>%
filter(sample_name == spectrum) %>%
smooth_intens(p = 3) %>%
subtr_bg(degree = 8) %>%
match_spec(library = spec_lib, which = "raman")
spectrum
raman_identities <- c()
for(spectrum in raman_subset){
identity <- unlist(spec_lib$raman$metadata[sample_name == spectrum, "spectrum_identity"])
topmatch <- augmented_raman %>%
filter(sample_name == spectrum) %>%
smooth_intens(p = 3) %>%
subtr_bg(degree = 8) %>%
match_spec(library = spec_lib, which = "raman", top_n = 1) %>%
select(spectrum_identity) %>%
unlist()
raman_identities <- c(raman_identities, identity == topmatch)
}
sum(raman_identities)/length(raman_identities)
ftir_identities <- c()
for(spectrum in ftir_subset){
identity <- unlist(spec_lib$ftir$metadata[sample_name == spectrum, "spectrum_identity"])
topmatch <- augmented_ftir %>%
filter(sample_name == spectrum) %>%
smooth_intens(p = 3) %>%
subtr_bg(degree = 8) %>%
match_spec(library = spec_lib, which = "ftir", top_n = 1) %>%
select(spectrum_identity) %>%
unlist()
ftir_identities <- c(ftir_identities, identity == topmatch)
}
sum(ftir_identities)/length(ftir_identities) |
context("rpbdb query functions and uri generation")
test_that("Param with several (as list) values joins to csv ok", {
expect_equal(.implode_to_string(list("aa","bb")), 'aa,bb')
})
test_that("Param with several (as character vector) values joins to csv ok", {
expect_equal(.implode_to_string(c("aa","bb")), 'aa,bb')
})
test_that("Param with one value remains", {
expect_equal(.implode_to_string("aa"), "aa")
}) |
"plotSpectraSuper" <- function(multimodel, multitheta, plotoptions)
{
if(dev.cur() != 1)
dev.new()
m <- multimodel@modellist
t <- multitheta
res <- multimodel@fit@resultlist
superimpose <- plotoptions@superimpose
if(length(superimpose) < 1 || any(superimpose > length(m)))
superimpose <- 1:length(m)
divdrel <- plotoptions@divdrel
allx2 <- allx <- vector()
for(i in superimpose) {
allx2 <- append(allx2, m[[i]]@x2)
allx <- append(allx, m[[i]]@x)
}
if(length(plotoptions@xlim) == 0) {
x2max <- max(allx2)
x2min <- min(allx2)
}
allx <- sort(unique(allx))
par(plotoptions@paropt)
par(mgp = c(2, 1, 0), mar=c(0,2,3,0), oma = c(1,0,4,0))
if(length(plotoptions@selectedtraces) > 0 ) {
seltraces <- plotoptions@selectedtraces
xx <- vector()
for(i in superimpose) {
xx <- append(m[[i]]@x[seltraces],xx)
}
lensel <- length(unique(xx))
}
else {
seltraces <- 1:length(allx)
lensel <- length(seltraces)
}
ymax <- ymin <- rep(0,length(allx))
for (j in 1:length(allx)) {
for(i in 1:length(m)) {
k <- which(m[[i]]@x == allx[j])[1]
if(i %in% superimpose && k %in% seltraces) {
data <- m[[i]]@psi.df[k,]
fitted <- res[[i]]@fitted[[k]]
if(divdrel && length(t[[i]]@drel)!=0){
if(length(m[[i]]@dscalspec$perclp)!=0)
if(m[[i]]@dscalspec$perclp) {
data <- data/t[[i]]@drel[k]
fitted <- fitted/t[[i]]@drel[k]
}
else {
data <- data/t[[i]]@drel
fitted <- fitted/t[[i]]@drel
}
}
if(m[[i]]@weight)
fitted <- fitted/m[[i]]@weightM[, k]
ymax[j] <- max(fitted,data,ymax[j])
ymin[j] <- min(fitted,data,ymin[j])
}
}
}
par(mfrow = n2mfrow(lensel))
for (j in 1:length(allx)) {
plotted <- FALSE
for(i in 1:length(m)) {
k <- which(m[[i]]@x == allx[j])[1]
if(i %in% superimpose && k %in% seltraces) {
data <- m[[i]]@psi.df[k,]
fitted <- res[[i]]@fitted[[k]]
if(divdrel && length(t[[i]]@drel)!=0)
if(length(m[[i]]@dscalspec$perclp)!=0)
if(m[[i]]@dscalspec$perclp) {
data <- data/t[[i]]@drel[k]
fitted <- fitted/t[[i]]@drel[k]
}
else {
data <- data/t[[i]]@drel
fitted <- fitted/t[[i]]@drel
}
if(m[[i]]@weight)
fitted <- fitted/m[[i]]@weightM[k,]
cold <- if(length(plotoptions@coldata) == 0) i
else plotoptions@coldata[i]
ltd <- if(length(plotoptions@ltydata) == 0)
1 else plotoptions@ltydata
colf <- if(length(plotoptions@colfit) == 0)
if(length(m) > 1) i else 2 else plotoptions@colfit[i]
ltf <- if(length(plotoptions@ltyfit) == 0)
3 else plotoptions@ltyfit
if(!plotted){
plot(m[[i]]@x2, data,
type = "l",
ylim=c(ymin[j],ymax[j]),
xlab = plotoptions@xlab,
ylab ="amplitude", col = cold, lty = ltd)
title(signif(m[[i]]@x[k]), line=0)
plotted <- TRUE
}
else
lines(m[[i]]@x2, data, type = "l", col = cold, lty = ltd)
lines(m[[i]]@x2, fitted, type = "l", col = colf, lty = ltf)
}
}
}
if(length(plotoptions@title) != 0){
tit <- plotoptions@title
if(plotoptions@addfilename)
tit <- paste(tit,m[[i]]@datafile)
}
else {
tit <- ""
if(plotoptions@addfilename) tit <- paste(tit, m[[i]]@datafile)
}
mtext(tit, side = 3, outer = TRUE, line = 1)
par(las = 2)
if(dev.interactive() && length(plotoptions@makeps) != 0) {
if(plotoptions@output == "pdf")
pdev <- pdf
else pdev <- postscript
dev.print(device=pdev,
file=paste(plotoptions@makeps, "_selectedtraces.",
plotoptions@output,
sep=""))
}
} |
xabmerge <- function(df1, df2, leff, step, k, type) {
if(is.null(k)) {
h.safe <- as.numeric(hsafe(df2[1,2], leff))
hdwy <- as.numeric(df1[3] - df2[3])
if(hdwy < h.safe) {
tlen <- dim(df2)[1]
for(i in 1:tlen) df2[i,3] <- df2[i,3]- h.safe
}
k <- 0
}
df3 <- cbind(df1,df2)[,-4]
if(type == TRUE) lines(df3[,1],df3[,5], lty = 2, lwd = 2, col = "yellow")
tseq <- df3[,1]
tlen <- length(tseq)
h.safe <- hdwy <- violation <- score <- rep(NA,tlen)
for(i in 1:tlen) {
h.safe[i] <- hsafe(df3[i,4], leff)
hdwy[i] <- df3[i,3] - df3[i,5]
score[i] <- h.safe[i] - hdwy[i]
}
df3 <- cbind(df3, hdwy, h.safe, violation, score)
for(i in 1:tlen) {
if(round(df3[i,6],2) >= round(df3[i,7],2)) df3[i,8] = 0
else df3[i,8] = 1
}
maxviol <- max(df3[,9])
tmaxviol <- df3[df3[,9] == maxviol,1]
xmaxviol <- df3[df3[,9] == maxviol,5]
umaxviol <- df3[df3[,9] == maxviol,4]
if(maxviol > 0 & type == TRUE) {
points(tmaxviol, xmaxviol, pch = 16)
text(tmaxviol, xmaxviol, labels = k, pos = 4)
}
browser()
for(i in 1:(tlen-2)) {
if(df3[i,8] == 0 & df3[i+1,8] == 1 & df3[i+2,8] == 1) {
k <- k + 1
break
} else {
k <- 0
}
}
if(k == 1) {
tstart <- tend <- ustart <- uend <- xstart <- xend <- {}
for(i in 1:(tlen-2)) {
if(df3[i,8] == 0 & df3[i+1,8] == 1 & df3[i+2,8] == 1)
tstart <- as.numeric(df3[i,1])
if(df3[i,8] == 1 & df3[i+1,8] == 0)
tend <- as.numeric(df3[i,1])
if(df3[i,8] == 0 & df3[i+1,8] == 1 & df3[i+2,8] == 1)
ustart <- as.numeric(df3[i,4])
if(df3[i,8] == 1 & df3[i+1,8] == 0)
uend <- as.numeric(df3[i,4])
if(df3[i,8] == 0 & df3[i+1,8] == 1 & df3[i+2,8] == 1)
xstart <- as.numeric(df3[i,5])
if(df3[i,8] == 1 & df3[i+1,8] == 0)
xend <- as.numeric(df3[i,5])
if(!is.null(tstart) & !is.null(tend)) {
break
}
}
if(is.null(tend)) {
tend <- as.numeric(df3[tlen,1])
uend <- as.numeric(df3[tlen,4])
xend <- as.numeric(df3[tlen,3]) - as.numeric(df3[tlen,7])
}
dfab <- data.frame(tstart, tend, ustart, uend, xstart, xend, step)
trj <- trajectoryab(
tstart = tstart,
tend = tend,
ustart = ustart,
uend = uend,
xstart = xstart,
xend = xend,
step = step)
u.fix <- as.numeric(trj[[3]])
x.fix <- as.numeric(trj[[4]])
u <- c(df3[df3[,1] < tstart,4], u.fix, df3[df3[,1] > tend,4])
x <- c(df3[df3[,1] < tstart,5], x.fix, df3[df3[,1] > tend,5])
df3[,4] <- u
df3[,5] <- x
if(type == TRUE) lines(df3[,1], df3[,5], lwd = 3, col = "orange")
return(list(df3, k, dfab))
}
if(k == 0) {
tstart <- tend <- ustart <- uend <- xstart <- xend <- NA
dfab <- data.frame(tstart, tend, ustart, uend, xstart, xend, step)
return(list(df3, k, dfab))
}
if(k == 2) {
tstart <- tend <- ustart <- uend <- xstart <- xend <- {}
for(i in 1:(tlen-2)) {
if(df3[i,8] == 0 & df3[i+1,8] == 1 & df3[i+2,8] == 1)
tstart <- as.numeric(df3[i,1])
if(df3[i,8] == 1 & df3[i+1,8] == 0)
tend <- as.numeric(df3[i,1])
if(df3[i,8] == 0 & df3[i+1,8] == 1 & df3[i+2,8] == 1)
ustart <- as.numeric(df3[i,4])
if(df3[i,8] == 1 & df3[i+1,8] == 0)
uend <- as.numeric(df3[i,4])
if(df3[i,8] == 0 & df3[i+1,8] == 1 & df3[i+2,8] == 1)
xstart <- as.numeric(df3[i,5])
if(df3[i,8] == 1 & df3[i+1,8] == 0)
xend <- as.numeric(df3[i,5])
if(!is.null(tstart) & !is.null(tend)) break
}
dfab <- data.frame(tstart, tend, ustart, uend, xstart, xend, step)
tstart1 <- as.numeric(dfab[1])
ustart1 <- as.numeric(dfab[3])
xstart1 <- as.numeric(dfab[5])
tend1 <- as.numeric(tmaxviol)
uend1 <- as.numeric(umaxviol)
umn1 <- 3600/5280*uend1
xend1 <- as.numeric(xmaxviol) - hsafe(umn1,leff)
if(type == TRUE) {
points(tend1,xend1, pch = 16)
text(tend1,xend1, label = k, pos = 4)
}
trj1 <- trajectoryab(
tstart = tstart1,
tend = tend1,
ustart = ustart1,
uend = uend1,
xstart = xstart1,
xend = xend1,
step = step)
t.fix1 <- as.numeric(trj1[[2]])
u.fix1 <- as.numeric(trj1[[3]])
x.fix1 <- as.numeric(trj1[[4]])
if(type == TRUE) lines(t.fix1,x.fix1, lwd = 2, col = "wheat")
tend2 <- as.numeric(dfab[2])
uend2 <- as.numeric(dfab[4])
xend2 <- as.numeric(dfab[6])
tstart2 <- as.numeric(tmaxviol)
ustart2 <- as.numeric(umaxviol)
umn2 <- 3600/5280*ustart1
xstart2 <- as.numeric(xmaxviol) - hsafe(umn1,leff)
if(type == TRUE) {
points(tend2,xend2, pch = 16)
text(tend2,xend2, label = k, pos = 2)
}
tstart <- tstart2
ustart <- ustart2
xstart <- xstart2
tend <- tend2
ustart <- ustart2
xstart <- xstart2
df3. <- df3[df3[,1] >= tstart,]
tlen. <- dim(df3.)[1]
tend <- {}
for(i in 1:tlen.) {
if(df3.[i,8] == 1 & df3.[i+1,8] == 0) tend <- as.numeric(df3.[i,1])
if(df3.[i,8] == 1 & df3.[i+1,8] == 0) uend <- as.numeric(df3.[i,4])
if(df3.[i,8] == 1 & df3.[i+1,8] == 0) xend <- as.numeric(df3.[i,5])
if(type == TRUE) points(as.numeric(df3.[i,1]), as.numeric(df3.[i,5]))
if(!is.null(tend)) break
}
trj2 <- trajectoryab(
tstart = tstart,
tend = tend,
ustart = ustart,
uend = uend,
xstart = xstart,
xend = xend,
step = step)
t.fix2 <- as.numeric(trj2[[2]])
u.fix2 <- as.numeric(trj2[[3]])
x.fix2 <- as.numeric(trj2[[4]])
u <- c(df3[df3[,1] < tstart1,4], u.fix1, u.fix2[-1], df3[df3[,1] > tend,4])
x <- c(df3[df3[,1] < tstart1,5], x.fix1, x.fix2[-1], df3[df3[,1] > tend,5])
df3[,4] <- u
df3[,5] <- x
if(type == TRUE) {
lines(t.fix2,x.fix2, lwd = 2, col = "tan")
lines(df3[,1], df3[,5], lwd = 2)
}
return(list(df3, k, dfab))
}
} |
library(dplyr)
library(stringr)
library(statar)
context("ascii table")
test_that("format_fixedwidth gives a number with w character", {
expect_equal(format_fixedwidth(-2.3820093234*10^(-10), 8), "-2.4e-10")
expect_equal(format_fixedwidth(-2.3820093234*10^(-9), 8), "-2.4e-09")
expect_equal(format_fixedwidth(-2.3820093234*10^(-8), 8), "-2.4e-08")
expect_equal(format_fixedwidth(-2.3820093234*10^(-7), 8), "-2.4e-07")
expect_equal(format_fixedwidth(-2.3820093234*10^(-6), 8), "-2.4e-06")
expect_equal(format_fixedwidth(-2.3820093234*10^(-5), 8), "-2.4e-05")
expect_equal(format_fixedwidth(-2.3820093234*10^(-4), 8), "-0.00024")
expect_equal(format_fixedwidth(-2.3820093234*10^(-3), 8), "-0.00238")
expect_equal(format_fixedwidth(-2.3820093234*10^(-2), 8), "-0.02382")
expect_equal(format_fixedwidth(-2.3820093234*10^(-1), 8), " -0.2382")
expect_equal(format_fixedwidth(-2.3820093234*10^(0), 8), "-2.38201")
expect_equal(format_fixedwidth(-2.3820093234*10^(1), 8), "-23.8201")
expect_equal(format_fixedwidth(-2.3820093234*10^(2), 8), "-238.201")
expect_equal(format_fixedwidth(-2.3820093234*10^(3), 8), "-2382.01")
expect_equal(format_fixedwidth(-2.3820093234*10^(4), 8), "-23820.1")
expect_equal(format_fixedwidth(-2.3820093234*10^(5), 8), " -238201")
expect_equal(format_fixedwidth(-2.3820093234*10^(6), 8), "-2.4e+06")
expect_equal(format_fixedwidth(-2.3820093234*10^(7), 8), "-2.4e+07")
expect_equal(format_fixedwidth(-2.3820093234*10^(8), 8), "-2.4e+08")
expect_equal(format_fixedwidth(-2.3820093234*10^(9), 8), "-2.4e+09")
expect_equal(format_fixedwidth(-2.3820093234*10^(10), 8), "-2.4e+10")
})
test_that("format_fixedwidth gives a number with w character", {
expect_equal(format_fixedwidth(-2.3824633234*10^(-10), 8), "-2.4e-10")
expect_equal(format_fixedwidth(-2.3824633234*10^(-9), 8), "-2.4e-09")
expect_equal(format_fixedwidth(-2.3824633234*10^(-8), 8), "-2.4e-08")
expect_equal(format_fixedwidth(-2.3824633234*10^(-7), 8), "-2.4e-07")
expect_equal(format_fixedwidth(-2.3824633234*10^(-6), 8), "-2.4e-06")
expect_equal(format_fixedwidth(-2.3824633234*10^(-5), 8), "-2.4e-05")
expect_equal(format_fixedwidth(-2.3824633234*10^(-4), 8), "-0.00024")
expect_equal(format_fixedwidth(-2.3824633234*10^(-3), 8), "-0.00238")
expect_equal(format_fixedwidth(-2.3824633234*10^(-2), 8), "-0.02382")
expect_equal(format_fixedwidth(-2.3824633234*10^(-1), 8), "-0.23825")
expect_equal(format_fixedwidth(-2.3824633234*10^(0), 8), "-2.38246")
expect_equal(format_fixedwidth(-2.3824633234*10^(1), 8), "-23.8246")
expect_equal(format_fixedwidth(-2.3824633234*10^(2), 8), "-238.246")
expect_equal(format_fixedwidth(-2.3824633234*10^(3), 8), "-2382.46")
expect_equal(format_fixedwidth(-2.3824633234*10^(4), 8), "-23824.6")
expect_equal(format_fixedwidth(-2.3824633234*10^(5), 8), " -238246")
expect_equal(format_fixedwidth(-2.3824633234*10^(6), 8), "-2.4e+06")
expect_equal(format_fixedwidth(-2.3824633234*10^(7), 8), "-2.4e+07")
expect_equal(format_fixedwidth(-2.3824633234*10^(8), 8), "-2.4e+08")
expect_equal(format_fixedwidth(-2.3824633234*10^(9), 8), "-2.4e+09")
expect_equal(format_fixedwidth(-2.3824633234*10^(10), 8), "-2.4e+10")
})
test_that("format_fixedwidth does not have trailing zeros", {
expect_equal(format_fixedwidth(50.5, 8), " 50.5")
})
test_that("format_fixedwidth works with 0", {
expect_equal(format_fixedwidth(0), " 0")
})
test_that("format_fixedwidth works with NA", {
expect_equal(format_fixedwidth(NA, 8), " NA")
})
test_that("format_fixedwidth works with factors", {
expect_equal(format_fixedwidth(as.factor("month")), " month")
})
test_that("format_fixedwidth works with factors", {
expect_equal(format_fixedwidth(as.factor("month")), " month")
})
test_that("format_fixedwidth correctly abbreviates", {
expect_equal(format_fixedwidth("very long string"), "very l~g")
})
df <- tibble(
check_rightalign = as.factor(c("Lorem ipsum dolor", "sit amet, consectetur adipiscing elit,", "sed do eiusmod tempor")),
longvarname = c(0, 1, 2)
)
tab(df, check_rightalign)
tab(df, longvarname) |
blues9 <- c("
"
.smoothScatterCalcDensity <- function(x, nbin, bandwidth, range.x)
{
if (length(nbin) == 1)
nbin <- c(nbin, nbin)
if (!is.numeric(nbin) || length(nbin) != 2)
stop("'nbin' must be numeric of length 1 or 2")
if (missing(bandwidth)) {
bandwidth <- diff(apply(x, 2, stats::quantile,
probs = c(0.05, 0.95),
na.rm = TRUE, names = FALSE)) / 25
bandwidth[bandwidth==0] <- 1
}
else {
if(!is.numeric(bandwidth)) stop("'bandwidth' must be numeric")
if(any(bandwidth <= 0)) stop("'bandwidth' must be positive")
}
if(requireNamespace("KernSmooth", quietly=TRUE))
rv <- KernSmooth::bkde2D(x, bandwidth=bandwidth, gridsize=nbin,
range.x=range.x)
else stop("Must have the ('Recommended') package \"KernSmooth\" installed")
rv$bandwidth <- bandwidth
rv
}
densCols <- function(x, y = NULL, nbin = 128, bandwidth,
colramp = colorRampPalette(blues9[-(1:3)]))
{
xy <- xy.coords(x, y, setLab = FALSE)
select <- is.finite(xy$x) & is.finite(xy$y)
x <- cbind(xy$x, xy$y)[select, ]
map <- .smoothScatterCalcDensity(x, nbin, bandwidth)
mkBreaks <- function(u) u - diff(range(u))/(length(u)-1)/2
xbin <- cut(x[,1], mkBreaks(map$x1), labels = FALSE)
ybin <- cut(x[,2], mkBreaks(map$x2), labels = FALSE)
dens <- map$fhat[cbind(xbin, ybin)]
dens[is.na(dens)] <- 0
colpal <- cut(dens, length(dens), labels = FALSE)
cols <- rep(NA_character_, length(select))
cols[select] <- colramp(length(dens))[colpal]
cols
} |
test_that("NIFTI v1 files with FreeSurfer hack can be read.", {
testthat::skip_on_cran();
skip_if(rversion.less.than(vmajor=3, vminor=5), message = "Skipping under R < 3.5.");
skip_if(tests_running_on_cran_under_macos(), message = "Skipping on CRAN under MacOS, required test data cannot be downloaded.");
freesurferformats::download_opt_data();
subjects_dir = freesurferformats::get_opt_data_filepath("subjects_dir");
morph_file_curv = file.path(subjects_dir, "subject1", "surf", "lh.thickness");
morph_file_nii = file.path(subjects_dir, "subject1", "surf", "lh.thickness.nii.gz");
morph_data_curv = read.fs.morph(morph_file_curv);
morph_data_nii = read.nifti1.data(morph_file_nii);
testthat::expect_equal(morph_data_curv, morph_data_nii);
})
test_that("NIFTI v1 files with FreeSurfer hack can be read using read.fs.morph.", {
skip_if(rversion.less.than(vmajor=3, vminor=5), message = "Skipping under R < 3.5.");
skip_if(tests_running_on_cran_under_macos(), message = "Skipping on CRAN under MacOS, required test data cannot be downloaded.");
testthat::skip_on_cran();
freesurferformats::download_opt_data();
subjects_dir = freesurferformats::get_opt_data_filepath("subjects_dir");
morph_file_curv = file.path(subjects_dir, "subject1", "surf", "lh.thickness");
morph_file_nii = file.path(subjects_dir, "subject1", "surf", "lh.thickness.nii.gz");
morph_data_curv = read.fs.morph(morph_file_curv);
morph_data_nii = read.fs.morph(morph_file_nii);
testthat::expect_equal(morph_data_curv, morph_data_nii);
testthat::expect_true(nifti.file.uses.fshack(morph_file_nii));
})
test_that("NIFTI v1 file headers with FreeSurfer hack can be read.", {
skip_if(rversion.less.than(vmajor=3, vminor=5), message = "Skipping under R < 3.5.");
skip_if(tests_running_on_cran_under_macos(), message = "Skipping on CRAN under MacOS, required test data cannot be downloaded.");
testthat::skip_on_cran();
freesurferformats::download_opt_data();
subjects_dir = freesurferformats::get_opt_data_filepath("subjects_dir");
morph_file_nii = file.path(subjects_dir, "subject1", "surf", "lh.thickness.nii.gz");
nh = read.nifti1.header(morph_file_nii);
testthat::expect_equal(nh$endian, 'little');
testthat::expect_equal(nh$glmin, 149244L);
testthat::expect_equal(nh$vox_offset, 352L);
testthat::expect_equal(nh$dim_raw, c(3, -1, 1, 1, 1, 1, 1, 1));
testthat::expect_equal(nh$dim, c(3, 149244, 1, 1, 1, 1, 1, 1));
})
test_that("The NIFTI version can be determined for a file.", {
skip_if(rversion.less.than(vmajor=3, vminor=5), message = "Skipping under R < 3.5.");
skip_if(tests_running_on_cran_under_macos(), message = "Skipping on CRAN under MacOS, required test data cannot be downloaded.");
testthat::skip_on_cran();
freesurferformats::download_opt_data();
subjects_dir = freesurferformats::get_opt_data_filepath("subjects_dir");
nii1_file = file.path(subjects_dir, "subject1", "surf", "lh.thickness.nii.gz");
data_dir = freesurferformats::get_opt_data_filepath("nifti2");
nii2_file = file.path(data_dir, 'avg152T1_LR_nifti2.nii.gz');
testthat::expect_equal(nifti.file.version(nii1_file), 1L);
testthat::expect_equal(nifti.file.version(nii2_file), 2L);
not_a_nifti_file = system.file("extdata", "cube.off", package = "freesurferformats", mustWork = TRUE);
testthat::expect_true(is.null(nifti.file.version(not_a_nifti_file)));
})
test_that("It can be determined whether a NIFTI file uses the FreeSurfer hack.", {
skip_if(rversion.less.than(vmajor=3, vminor=5), message = "Skipping under R < 3.5.");
skip_if(tests_running_on_cran_under_macos(), message = "Skipping on CRAN under MacOS, required test data cannot be downloaded.");
testthat::skip_on_cran();
freesurferformats::download_opt_data();
subjects_dir = freesurferformats::get_opt_data_filepath("subjects_dir");
nii1_file_with_hack = file.path(subjects_dir, "subject1", "surf", "lh.thickness.nii.gz");
nii1_file_without_hack = system.file("extdata", "vol27int.nii.gz", package = "freesurferformats", mustWork = TRUE);
data_dir = freesurferformats::get_opt_data_filepath("nifti2");
nii2_file = file.path(data_dir, 'avg152T1_LR_nifti2.nii.gz');
testthat::expect_true(nifti.file.uses.fshack(nii1_file_with_hack));
testthat::expect_false(nifti.file.uses.fshack(nii1_file_without_hack));
testthat::expect_false(nifti.file.uses.fshack(nii2_file));
not_a_nifti_file = system.file("extdata", "cube.off", package = "freesurferformats", mustWork = TRUE);
testthat::expect_error(nifti.file.uses.fshack(not_a_nifti_file));
}) |
clip.data <- function(data, lower=0.05, upper=0.95){
if(is.hemilist(data)) {
return(lapply(data, clip.data, lower, upper));
} else {
quantiles = stats::quantile(data, c(lower, upper), na.rm = TRUE, names = FALSE);
data[ data < quantiles[1] ] = quantiles[1];
data[ data > quantiles[2] ] = quantiles[2];
}
return(data);
}
clip_fun <- function(lower=0.05, upper=0.95) {
res_fun <- function(data) {
quantiles = stats::quantile(data, c(lower, upper), na.rm = TRUE, names = FALSE);
data[ data < quantiles[1] ] = quantiles[1];
data[ data > quantiles[2] ] = quantiles[2];
return(data);
};
return(res_fun);
}
shift.hemis.rglactions <- function(coloredmeshes, rglactions) {
if(rglactions.has.key(rglactions, 'shift_hemis_apart')) {
shift_hemis = rglactions$shift_hemis_apart;
if(is.logical(shift_hemis)) {
if(shift_hemis) {
return(shift.hemis.apart(coloredmeshes, hemi_order_on_axis='lr'));
}
} else if(is.list(shift_hemis)) {
return(do.call(shift.hemis.apart, utils::modifyList(list(coloredmeshes), shift_hemis)));
} else if(is.character(shift_hemis)) {
if(shift_hemis == 'lr' | shift_hemis == 'lhrh') {
return(shift.hemis.apart(coloredmeshes, hemi_order_on_axis='lr'));
} else if(shift_hemis == 'rl' | shift_hemis == 'rhlh') {
return(shift.hemis.apart(coloredmeshes, hemi_order_on_axis='rl'));
} else if(shift_hemis == 'auto' | shift_hemis == 'auto_flipped') {
return(shift.hemis.apart(coloredmeshes, hemi_order_on_axis=shift_hemis));
} else {
warning("Value in rglactions$shift_hemis_apart is not supported, ignored. Not shifting hemis.");
}
} else {
warning("Value in rglactions$shift_hemis_apart is not supported, ignored. Not shifting hemis.");
}
}
return(coloredmeshes);
}
rglactions.transform <- function(measure_data, rglactions) {
if(is.null(rglactions)) {
return(measure_data);
}
if(is.hemilist(measure_data)) {
return(lapply(measure_data, rglactions.transform, rglactions=rglactions));
}
if(hasIn(rglactions, list('clip_data'))) {
clip_range = rglactions$clip_data;
measure_data = clip.data(measure_data, lower=clip_range[1], upper=clip_range[2]);
}
if(hasIn(rglactions, list('trans_fun'))) {
trans_fun = rglactions$trans_fun;
if(! is.function(trans_fun)) {
stop("The value of rglactions entry 'trans_fun' must be a function.");
}
measure_data = trans_fun(measure_data);
}
return(measure_data);
}
limit_fun <- function(vmin, vmax) {
limit_fun <- function(data) {
data[data < vmin] = vmin;
data[data > vmax] = vmax;
return(data);
};
return(limit_fun);
}
limit_fun_na <- function(vmin, vmax) {
limit_fun <- function(data) {
data[data < vmin] = NA;
data[data > vmax] = NA;
return(data);
};
return(limit_fun);
}
limit_fun_na_inside <- function(vmin, vmax) {
limit_fun <- function(data) {
data[which(data > vmin & data < vmax)] = NA;
return(data);
};
return(limit_fun);
}
rglactions.has.key <- function(rglactions, key) {
if(is.list(rglactions)) {
return(key %in% names(rglactions));
}
return(FALSE);
}
perform.rglactions <- function(rglactions, at_index=NULL, silent=TRUE, ignore = c()) {
if(is.list(rglactions)) {
if("text" %in% names(rglactions)) {
if(!("text" %in% ignore)) {
do.call(rgl::text3d, rglactions$text);
}
}
if("snapshot_png" %in% names(rglactions)) {
if(!("snapshot_png" %in% ignore)) {
if(length(rglactions$snapshot_png) == 1 || is.null(at_index)) {
output_image = path.expand(rglactions$snapshot_png);
} else {
if(length(rglactions$snapshot_png) < at_index) {
warning(sprintf("Requested rglaction at_index '%d' but only %d entries exist for action 'snapshot_png'.\n", at_index, length(rglactions$snapshot_png)));
}
output_image = path.expand(rglactions$snapshot_png[[at_index]]);
}
rgl::rgl.snapshot(output_image, fmt="png");
if(! silent) {
message(sprintf("Bitmap screenshot written to '%s' (current working dir is '%s').\n", output_image, getwd()));
}
}
}
if("snapshot_vec" %in% names(rglactions)) {
if(!("snapshot_vec" %in% ignore)) {
snapshot_vec_format = "eps";
if("snapshot_vec_format" %in% names(rglactions)) {
supported_formats = c("ps", "eps", "tex", "pdf", "svg", "pgf");
if(rglactions$snapshot_vec_format %in% supported_formats) {
snapshot_vec_format = rglactions$snapshot_vec_format;
} else {
stop(sprintf("rglactions: invalid snapshot_vec_format '%s'. Must be one of ''.", rglactions$snapshot_vec_format, paste(supported_formats, collapse = ", ")));
}
}
if(length(rglactions$snapshot_vec) == 1 || is.null(at_index)) {
output_image = path.expand(rglactions$snapshot_vec);
} else {
if(length(rglactions$snapshot_vec) < at_index) {
warning(sprintf("Requested rglaction at_index '%d' but only %d entries exist for action 'snapshot_vec'.\n", at_index, length(rglactions$snapshot_vec)));
}
output_image = path.expand(rglactions$snapshot_vec[[at_index]]);
}
rgl::rgl.postscript(output_image, fmt = snapshot_vec_format);
if(! silent) {
message(sprintf("Vector graphics screenshot written to '%s' in format '%s' (current working dir is '%s').\n", output_image, snapshot_vec_format, getwd()));
}
}
}
if("highlight_points" %in% names(rglactions)) {
if(!("highlight_points" %in% ignore)) {
hp = rglactions$highlight_points;
highlight.points.spheres(hp$coords, color = hp$color, radius = hp$radius);
}
}
}
}
rglactions <- function() {
return(list('snapshot_png'='fsbrain_out.png'));
} |
lattice.t.trellis <-
function (x)
{
stopifnot(length(dim(x)) == 2)
update(x, perm.cond = rev(x$perm.cond))
}
grid.make.yaxis.major <-
function (at, main)
{
if (main)
x <- c(0, 0)
else x <- c(1, 1)
linesGrob(unit(x, "npc"), unit(c(min(at), max(at)), "native"),
name = "major")
}
grid.make.yaxis.ticks <-
function (at, main)
{
if (main) {
tick.x0 <- unit(0, "npc")
tick.x1 <- unit(-0.5, "lines")
}
else {
tick.x0 <- unit(1, "npc")
tick.x1 <- unit(1, "npc") + unit(0.5, "lines")
}
segmentsGrob(tick.x0, unit(at, "native"), tick.x1, unit(at,
"native"), name = "ticks")
}
grid.make.xaxis.major <-
function (at, main)
{
if (main)
y <- c(0, 0)
else y <- c(1, 1)
linesGrob(unit(c(min(at), max(at)), "native"), unit(y, "npc"),
name = "major")
}
grid.make.xaxis.ticks <-
function (at, main)
{
if (main) {
tick.y0 <- unit(0, "npc")
tick.y1 <- unit(-0.5, "lines")
}
else {
tick.y0 <- unit(1, "npc")
tick.y1 <- unit(1, "npc") + unit(0.5, "lines")
}
segmentsGrob(unit(at, "native"), tick.y0, unit(at, "native"),
tick.y1, name = "ticks")
}
multcomp.meanslinfct <-
function (model, focus, mmm.data = model$model, formula.in = terms(model),
contrasts.arg = NULL)
{
mmm.factor <- sapply(mmm.data, inherits, "factor")
mmm.levels <- lapply(mmm.data[mmm.factor], levels)
mmm.rows <- sapply(mmm.levels, length)
n.mmm.rows <- prod(mmm.rows)
mmm.new <- mmm.data[1:n.mmm.rows, ]
mmm.factor.names <- names(mmm.data)[mmm.factor]
mmm.rows.forward <- cumprod(mmm.rows)
mmm.rows.forward.prev <- c(1, mmm.rows.forward)
names(mmm.rows.forward.prev) <- c(names(mmm.rows.forward),
"all")
for (i in mmm.factor.names) mmm.new[[i]] <- gl(mmm.rows[i],
mmm.rows.forward.prev[i], n.mmm.rows, labels = mmm.levels[[i]])
mmm.numeric.names <- names(mmm.data)[!mmm.factor]
for (i in mmm.numeric.names) mmm.new[[i]][] <- mean(mmm.data[[i]])
none.data <- model.matrix(formula.in, data = mmm.new, contrasts.arg = contrasts.arg)
none.linfct <- aggregate(none.data, by = mmm.new[focus],
FUN = mean)[, -1]
rownames(none.linfct) <- levels(mmm.new[[focus]])
data.matrix(none.linfct)
}
lattice.lattice.setStatus <-
function (..., prefix = NULL, clean.first = FALSE)
{
dots <- list(...)
if (is.null(names(dots)) && length(dots) == 1 && is.list(dots[[1]]))
dots <- dots[[1]]
if (length(dots) == 0)
return()
.LatticeEnv <- get(".LatticeEnv", envir=environment(lattice.options))
lattice.status <- if (clean.first)
list()
else get("lattice.status", envir = .LatticeEnv)
if (is.null(prefix))
lattice.status[names(dots)] <- dots
else lattice.status[[prefix]][names(dots)] <- dots
assign("lattice.status", lattice.status, envir = .LatticeEnv)
invisible()
}
lattice.hist.constructor <-
function (x, breaks, include.lowest = TRUE, right = TRUE, ...)
{
if (is.numeric(breaks) && length(breaks) > 1)
hist(as.numeric(x), breaks = breaks, plot = FALSE, include.lowest = include.lowest,
right = right)
else hist(as.numeric(x), breaks = breaks, right = right,
plot = FALSE)
}
lattice.extend.limits <-
function (lim, length = 1, axs = "r", prop = if (axs == "i") 0 else lattice.getOption("axis.padding")$numeric)
{
if (all(is.na(lim)))
NA_real_
else if (is.character(lim)) {
c(1, length(lim)) + c(-1, 1) * if (axs == "i")
0.5
else lattice.getOption("axis.padding")$factor
}
else if (length(lim) == 2) {
if (lim[1] > lim[2]) {
ccall <- match.call()
ccall$lim <- rev(lim)
ans <- eval.parent(ccall)
return(rev(ans))
}
if (!missing(length) && !missing(prop))
stop("'length' and 'prop' cannot both be specified")
if (length <= 0)
stop("'length' must be positive")
if (!missing(length)) {
prop <- (as.numeric(length) - as.numeric(diff(lim)))/(2 *
as.numeric(diff(lim)))
}
if (lim[1] == lim[2])
lim + 0.5 * c(-length, length)
else {
d <- diff(as.numeric(lim))
lim + prop * d * c(-1, 1)
}
}
else {
print(lim)
stop("improper length of 'lim'")
}
}
lattice.chooseFace <-
function (fontface = NULL, font = 1)
{
if (is.null(fontface))
font
else fontface
}
lattice.lattice.getStatus <-
function (name, prefix = NULL)
{
.LatticeEnv <- get(".LatticeEnv", envir=environment(lattice.options))
if (is.null(prefix))
get("lattice.status", envir = .LatticeEnv)[[name]]
else get("lattice.status", envir = .LatticeEnv)[[prefix]][[name]]
} |
corrRect = function(corrRes = NULL, index = NULL, name = NULL, namesMat = NULL,
col = 'black', lwd = 2, ...)
{
if((as.integer(!is.null(index)) + as.integer(!is.null(name)) +
as.integer(!is.null(namesMat))) > 1) {
stop('You should just input one of index, name and namesMat!')
}
if(is.null(corrRes)|!is.list(corrRes)) {
stop('List \'corrRes\' must be inputted!')
}
corr = corrRes$corr
corrPos = corrRes$corrPos
type = corrRes$arg$type
cName = colnames(corr)
rName = rownames(corr)
if(!is.null(name)) {
if(any(cName != rName)) {
stop('colnames and rownames must be same when index or name is inputted!')
}
if(!all(name %in% cName)) {
stop('Non-existent name found!')
}
index = unlist(lapply(name, function(n) which(cName==n)))
}
if(!is.null(index)) {
if(any(cName != rName)) {
stop('colnames and rownames must be same when index or name is inputted!')
}
n = length(index)
index[-n] = index[-n] - 1
x1 = index[-n] + 0.5
y1 = nrow(corr) - index[-n] + 0.5
x2 = index[-1] + 0.5
y2 = nrow(corr) - index[-1] + 0.5
St = S = cbind(c(x1, x1, x2, x2), c(y1, y1, y2, y2),
c(x2, x1, x2, x1), c(y1, y2, y1, y2))
St[, 2] = abs(St[, 2] - nrow(corr) - 1)
St[, 4] = abs(St[, 4] - nrow(corr) - 1)
if(type=='upper') {
i = which((St[, 1] - St[, 2]) > -0.1 & (St[, 3] - St[, 4]) > -0.1)
S = S[i, ]
}
if(type=='lower') {
i = which((St[, 2] - St[, 1]) > -0.1 & (St[, 4] - St[, 3]) > -0.1)
S = S[i, ]
}
segments(S[, 1], S[, 2], S[, 3], S[, 4], col = col, lwd = lwd, ...)
}
if(!is.null(namesMat)) {
if(is.vector(namesMat)) {
namesMat = matrix(namesMat, ncol = 4, nrow = 1)
}
xy1 = getCharXY(namesMat[, 1:2, drop=FALSE], corrPos)
xy2 = getCharXY(namesMat[, 3:4, drop=FALSE], corrPos)
xy = cbind(xy1, xy2)
x1 = apply(xy[, c(1, 3), drop=FALSE], 1, min) - 0.5
y1 = apply(xy[, c(2, 4), drop=FALSE], 1, min) - 0.5
x2 = apply(xy[, c(1, 3), drop=FALSE], 1, max) + 0.5
y2 = apply(xy[, c(2, 4), drop=FALSE], 1, max) + 0.5
rect(x1, y1, x2, y2, border = col, lwd = lwd, ...)
}
invisible(corrRes)
}
getCharXY = function(x, dat) {
res = apply(x, 1, function(n, d=dat) d[d[, 1]==n[1]&d[, 2]==n[2], 3:4])
f = which(unlist(lapply(res, nrow))==0)
if(length(f) > 0) {
error = paste(toString(unique(x[f, ])), 'paired X-Y names were not found!')
stop(error)
}
return(matrix(unlist(res), byrow = TRUE, ncol = 2))
} |
lagthemats<-function(data,lag){
if (lag>0){
for (i in 1:lag){
N<-nrow(data)
mats.temp<-data[-1,]
laggeddata<-rbind(mats.temp,rep(NA,ncol(data)))
data=laggeddata
}
}else if (lag==0){
laggeddata=data
}
laggeddata
} |
context("Reading from workbook is identical to reading from file")
test_that("Reading from loaded workbook", {
wb <- createWorkbook()
for(i in 1:4)
addWorksheet(wb, sprintf('Sheet %s', i))
writeData(wb, sheet = 1, x = mtcars, colNames = TRUE, rowNames = TRUE, startRow = 10, startCol = 5, borders = "all")
writeData(wb, sheet = 2, x = mtcars, colNames = TRUE, rowNames = FALSE, startRow = 10, startCol = 5, borders = "rows")
writeData(wb, sheet = 3, x = mtcars, colNames = FALSE, rowNames = TRUE, startRow = 2, startCol = 2, borders = "columns")
writeData(wb, sheet = 4, x = mtcars, colNames = FALSE, rowNames = FALSE, startRow = 12, startCol = 1, borders = "surrounding")
tempFile <- file.path(tempdir(), "temp.xlsx")
saveWorkbook(wb, tempFile, overwrite = TRUE)
wb <- loadWorkbook(tempFile)
x <- read.xlsx(wb, 1, colNames = TRUE, rowNames = TRUE)
expect_equal(object = mtcars, expected = x, check.attributes = TRUE)
x <- read.xlsx(wb, sheet = 2, colNames = TRUE, rowNames = FALSE)
expect_equal(object = mtcars, expected = x, check.attributes = FALSE)
expect_equal(object = colnames(mtcars), expected = colnames(x), check.attributes = FALSE)
x <- read.xlsx(wb, sheet = 3, colNames = FALSE, rowNames = TRUE)
expect_equal(object = mtcars, expected = x, check.attributes = FALSE)
expect_equal(object = rownames(mtcars), expected = rownames(x))
x <- read.xlsx(wb, sheet = 4, colNames = FALSE, rowNames = FALSE)
expect_equal(object = mtcars, expected = x, check.attributes = FALSE)
unlink(tempFile, recursive = TRUE, force = TRUE)
}) |
myTarGetCampaignList <-
function(auth = NULL,
login = getOption('rmytarget.login'),
token_path = myTarTokenPath(),
request_speed = 1.2){
if (is.null(auth)) {
auth <- myTarAuth(login = login, token_path = token_path)
}
if ( request_speed %in% c("slow", "normal", "fast")) {
request_speed <- switch(EXPR = request_speed,
"slow" = 2,
"normal" = 1.2,
"fast" = 0.8)
}
limit <- 50
offset <- 0
count <- NULL
result <- list()
packageStartupMessage("Loading |",appendLF = F)
while ( is.null(count) || count > offset ) {
camp <- GET(stringr::str_interp("${getOption('rmytarget.url')}api/v2/campaigns.json?fields=id,name,status,mixing,created,date_start,date_end,utm&limit=${limit}&offset=${offset}"),add_headers(Authorization = paste0("Bearer ",auth$access_token)))
stop_for_status(camp)
campRaw <- content(camp, "parsed", "application/json")
if ( ! myTarCheckLimits(campRaw) ) stop("Limit error")
result <- append(result, campRaw$items)
packageStartupMessage("=",appendLF = F)
Sys.sleep(request_speed)
count <- campRaw$count
offset <- offset + limit
}
campList <- map_df(result, flatten)
packageStartupMessage("| Done",appendLF = T)
return(campList)
} |
setConstructorS3("MatSmoothing", function(..., design=NULL, probeWindow=300, nProbes=10, meanTrim=0.1) {
if (!is.null(design)) {
if (!is.matrix(design)) {
throw("Argument 'design' is not a matrix: ", class(design)[1])
}
probeWindow <- Arguments$getNumeric(probeWindow, range=c(0,Inf))
nProbes <- Arguments$getInteger(nProbes, range=c(1,Inf))
meanTrim <- Arguments$getNumeric(meanTrim, range=c(0,0.5))
}
this <- extend(ProbeLevelTransform(...), "MatSmoothing",
.design = design,
.probeWindow = probeWindow,
.nProbes = nProbes,
.meanTrim = meanTrim
)
ds <- getInputDataSet(this)
if (!is.null(ds)) {
nbrOfFiles <- length(ds)
design <- this$.design
dim <- dim(design)
if (dim[1] != nbrOfFiles) {
throw("The number of rows in the 'design' matrix, does not match the number of arrays in the input data set: ", dim[1], " != ", nbrOfFiles)
}
for (cc in seq_len(ncol(design))) {
if (!any(design[,cc] != 0)) {
throw("Column
}
}
outputNames <- colnames(design)
if (is.null(outputNames)) {
throw("Matrix 'design' does not have column names.")
}
outputNames <- Arguments$getCharacters(outputNames)
if (any(duplicated(outputNames))) {
throw("Argument 'design' contains duplicated column names: ",
paste(outputNames[duplicated(outputNames)]), collapse=", ")
}
fullnames <- lapply(outputNames, FUN=function(fullname) {
Arguments$getFilename(fullname)
})
}
this
})
setMethodS3("getAromaCellPositionFile", "MatSmoothing", function(this, ..., force=FALSE) {
acp <- this$.acp
if (force || is.null(acp)) {
dataSet <- getInputDataSet(this)
cdf <- getCdf(dataSet)
chipType <- getChipType(cdf, fullname=FALSE)
nbrOfCells <- nbrOfCells(cdf)
acp <- AromaCellPositionFile$byChipType(chipType, nbrOfCells=nbrOfCells, ...)
this$.acp <- acp
}
acp
}, protected=TRUE)
setMethodS3("getParameters", "MatSmoothing", function(this, ...) {
params <- NextMethod("getParameters")
params2 <- list(
design = this$.design,
probeWindow = this$.probeWindow,
nProbes = this$.nProbes,
meanTrim = this$.meanTrim
)
params <- c(params, params2)
params
}, protected=TRUE)
setMethodS3("getExpectedOutputFullnames", "MatSmoothing", function(this, ..., verbose=FALSE) {
verbose <- Arguments$getVerbose(verbose)
if (verbose) {
pushState(verbose)
on.exit(popState(verbose))
}
verbose && enter(verbose, "Match to the column names of the design matrix")
params <- getParameters(this)
design <- params$design
verbose && cat(verbose, "Expected result names:")
fullnames <- colnames(design)
verbose && str(verbose, fullnames)
stopifnot(!is.null(fullnames))
verbose && exit(verbose)
fullnames
}, protected=TRUE)
setMethodS3("process", "MatSmoothing", function(this, ..., units=NULL, force=FALSE, verbose=FALSE) {
requireNamespace("gsmoothr") || throw("Package not loaded: gsmoothr")
tmeanC <- gsmoothr::tmeanC
gsmoothr_tmeanC <- gsmoothr::tmeanC
calcSmoothed <- function(posVector, dataMatrix, probeWindow, nProbes, meanTrim) {
nc <- ncol(dataMatrix)
posM <- matrix(posVector, nrow=length(posVector), ncol=nc)
o <- order(posM);
smoothedScore <- gsmoothr_tmeanC(posM[o], dataMatrix[o],
probeWindow=probeWindow, nProbes=nProbes*nc, trim=meanTrim)
subsetInd <- seq(from=1, to=length(o), by=nc)
return(smoothedScore[subsetInd])
}
calcNullDist0 <- function(ch, ps, x) {
MIN <- -999999
y <- rep(MIN, times=length(x))
n <- length(ch)
indices <- split(seq_len(n), ch)
nChr <- length(indices)
count <- 0
for (ii in seq_len(nChr)) {
ind <- indices[[ii]]
nInd <- length(ind)
pos <- ind[1]
for (jj in seq_len(nInd)) {
pp <- ps[ ind[jj] ]
if ( (pp-pos) > (probeWindow*2) ) {
count <- count + 1
y[count] <- x[ ind[jj] ]
pos <- pp
}
}
}
y <- y[y > MIN]
md <- median(y)
y <- y[y <= md]
list( m=md, sd = sd( c(y,-y+2*md) ) )
}
calcNullDist <- function(chr, pos, x) {
dblProbeWindow <- 2*probeWindow
n <- length(chr)
indices <- split(seq_len(n), chr)
nbrOfChromosomes <- length(indices)
yList <- list()
for (ii in seq_len(nbrOfChromosomes)) {
ind <- indices[[ii]]
nInd <- length(ind)
posII <- pos[ind]
xII <- x[ind]
o <- order(posII)
posII <- posII[o]
xII <- xII[o]
yII <- rep(-Inf, times=nInd)
lastPos <- posII[1]
for (jj in seq_len(nInd)) {
posJJ <- posII[jj]
if (posJJ-lastPos > dblProbeWindow) {
yII[jj] <- xII[jj]
lastPos <- posJJ
}
}
yList[[ii]] <- yII
}
y <- unlist(yList, use.names=FALSE)
y <- y[y > -Inf]
md <- median(y)
y <- y[y <= md]
list(m=md, sd=sd(c(y,-y+2*md)))
}
calcNullDists <- function(chr, pos, X) {
dblProbeWindow <- 2*probeWindow
K <- ncol(X)
names <- colnames(X)
n <- length(chr)
idxList <- split(seq_len(n), chr)
YList <- list()
for (ii in seq_along(idxList)) {
idxs <- idxList[[ii]]
posII <- pos[idxs]
o <- order(posII)
idxs <- idxs[o]
posII <- posII[o]
XII <- X[idxs,,drop=FALSE]
J <- length(idxs)
YII <- matrix(-Inf, nrow=J, ncol=K)
lastPos <- posII[1]
for (jj in seq_len(J)) {
posJJ <- posII[jj]
if (posJJ-lastPos > dblProbeWindow) {
YII[jj,] <- XII[jj,]
lastPos <- posJJ
}
}
YList[[ii]] <- YII
}
m <- sd <- double(K)
names(m) <- names(sd) <- names
res <- list()
for (kk in seq_len(K)) {
yList <- lapply(YList, FUN=function(Y) Y[,kk, drop=TRUE])
y <- unlist(yList, use.names=FALSE)
y <- y[y > -Inf]
m[kk] <- median(y, na.rm=TRUE)
y <- y[y <= m[kk]]
sd[kk] <- sd(c(y,-y+2*m[kk]), na.rm=TRUE)
}
list(m=m, sd=sd)
}
if (!is.null(units)) {
units <- Arguments$getIndices(units, max=nbrOfUnits(cdf))
}
verbose <- Arguments$getVerbose(verbose)
if (verbose) {
pushState(verbose)
on.exit(popState(verbose))
}
verbose && enter(verbose, "MAT smoothing according to design matrix")
if (!force && isDone(this)) {
verbose && cat(verbose, "Already smoothed")
verbose && exit(verbose)
outputDataSet <- getOutputDataSet(this)
return(invisible(outputDataSet))
}
ds <- getInputDataSet(this)
outputPath <- getPath(this)
cdf <- getCdf(ds)
if (is.null(units)) {
units <- seq_len(nbrOfUnits(cdf))
}
verbose && enter(verbose, "Locating probe position data")
acp <- getAromaCellPositionFile(this, verbose=less(verbose, 5))
verbose && exit(verbose)
params <- getParameters(this, verbose=less(verbose, 50))
probeWindow <- params$probeWindow
design <- params$design
nProbes <- params$nProbes
meanTrim <- params$meanTrim
params <- NULL
nbrGroupsPerUnit <- nbrOfGroupsPerUnit(cdf)
stopifnot(all(nbrGroupsPerUnit == 1))
verbose && enter(verbose, "Loading cell PM indices structured according to the CDF")
cdfCellsList <- getCellIndices(cdf, units=units, stratifyBy="pm")
unitNames <- names(cdfCellsList)
names(cdfCellsList) <- NULL
verbose && exit(verbose)
cellsList <- lapply(cdfCellsList, FUN=function(unit) {
unit$groups[[1]]$indices
})
nRows <- sapply(cellsList, FUN=length)
allInds <- unlist(cellsList, use.names=FALSE)
nbrOfUnits <- length(units)
fullnamesOut <- colnames(design)
stopifnot(!is.null(fullnamesOut))
verbose && cat(verbose, "Result/output names:")
verbose && str(verbose, fullnamesOut)
verbose && enter(verbose, "Preloading genomic positions for all cells")
acpData <- acp[,1:2,drop=FALSE]
verbose && exit(verbose)
for (ii in seq_len(ncol(design))) {
fullname <- fullnamesOut[ii]
verbose && enter(verbose, sprintf("Result file
ii, fullname, ncol(design)))
filename <- sprintf("%s.CEL", fullname)
pathname <- Arguments$getWritablePathname(filename, path=outputPath, ...)
if (!force && isFile(pathname)) {
verbose && cat(verbose, "Already processed.")
verbose && exit(verbose)
next
}
isFile <- (force && isFile(pathname))
pathnameT <- pushTemporaryFile(pathname, isFile=isFile, verbose=verbose)
matScoreNeg <- matScorePos <- outputList <- vector("list", nbrOfUnits)
names(outputList) <- unitNames
sampsKeep <- which(design[,ii] != 0)
stopifnot(length(sampsKeep) > 0)
posOrNeg <- design[sampsKeep,ii]
verbose && enter(verbose, "Reading probe data for the samples needed")
dsII <- extract(ds, sampsKeep)
dataList <- readUnits(dsII, units=cdfCellsList, verbose=verbose)
dsII <- NULL
verbose && exit(verbose)
dataList <- lapply(dataList, FUN=function(u) {
matrix(log2(u[[1]]$intensities), ncol=length(sampsKeep))
})
verbose && enter(verbose, "Computing trimmed means for all units")
for (jj in seq_len(nbrOfUnits)) {
if (is.null(outputList[[jj]])) {
zeroes <- rep(0, times=nRows[jj])
matScorePos[[jj]] <- zeroes
matScoreNeg[[jj]] <- zeroes
outputList[[jj]] <- zeroes
}
if (jj %% 1000 == 0) {
verbose && cat(verbose, sprintf("Completed %d out of %d units...", jj, nbrOfUnits))
}
sampPos <- which(posOrNeg > 0)
sampNeg <- which(posOrNeg < 0)
nPos <- length(sampPos)
nNeg <- length(sampNeg)
cells <- cellsList[[jj]]
pos <- acpData[cells,2,drop=TRUE]
if (nPos > 0) {
matScorePos[[jj]] <- calcSmoothed(pos, dataList[[jj]][,sampPos,drop=FALSE], probeWindow=probeWindow, nProbes=nProbes, meanTrim=meanTrim)
}
if (nNeg > 0) {
matScoreNeg[[jj]] <- calcSmoothed(pos, dataList[[jj]][,sampNeg,drop=FALSE], probeWindow=probeWindow, nProbes=nProbes, meanTrim=meanTrim)
}
}
dataList <- NULL
verbose && exit(verbose)
matScorePos <- unlist(matScorePos, use.names=FALSE)
matScoreNeg <- unlist(matScoreNeg, use.names=FALSE)
if (length(sampNeg) > 0) {
verbose && enter(verbose, "Calculating scale factor via null distributions")
verbose && enter(verbose, "Gathering common info for calculating null distributions")
chr <- acpData[allInds,1,drop=TRUE]
pos <- acpData[allInds,2,drop=TRUE]
verbose && exit(verbose)
verbose && enter(verbose, "Calculating null distributions for controls and treatments in parallel")
nullX <- cbind(neg=matScoreNeg, pos=matScorePos)
nullDists <- calcNullDists(chr, pos, nullX)
chr <- pos <- nullX <- NULL
verbose && str(verbose, nullDists)
verbose && exit(verbose)
scaleFactor <- nullDists$sd["pos"] / nullDists$sd["neg"]
verbose && printf(verbose, "Scale factor: %.4g\n", scaleFactor)
stopifnot(is.finite(scaleFactor))
nullDists <- NULL
verbose && exit(verbose)
} else {
scaleFactor <- 1
}
verbose && enter(verbose, "Calculating MAT scores (on intensity scale)")
matScores <- matScorePos - scaleFactor*matScoreNeg
matScoreNeg <- matScorePos <- NULL
matScores <- 2^matScores
verbose && str(verbose, matScores)
verbose && summary(verbose, matScores)
verbose && exit(verbose)
stopifnot(length(matScores) == length(allInds))
verbose && enter(verbose, "Storing results")
pathnameT <- Arguments$getWritablePathname(pathnameT, mustNotExist=!force)
verbose && enter(verbose, "Creating CEL file for results, if missing")
df <- getOneFile(ds)
createFrom(df, filename=pathnameT, path=NULL, verbose=less(verbose))
verbose && exit(verbose)
verbose && enter(verbose, "Updating data file")
verbose2 <- isVisible(verbose, -50)
.updateCel(pathnameT, indices=allInds, intensities=matScores,
verbose=verbose2)
verbose && exit(verbose)
popTemporaryFile(pathnameT, verbose=verbose)
dfZ <- getChecksumFile(pathname)
filename <- pathnameT <- NULL
verbose && exit(verbose)
matScores <- NULL
gc <- gc()
verbose && print(verbose, gc)
verbose && exit(verbose)
}
cellsList <- allInds <- acpData <- NULL
outputDataSet <- getOutputDataSet(this, force=TRUE)
stopifnot(length(outputDataSet) == ncol(design))
verbose && exit(verbose)
invisible(outputDataSet)
}) |
removeMultiArcs <- function(arcs, directed = TRUE) {
new.arcs <- matrix(ncol = 3)[-1, ]
i <- 1
if (directed) {
while (nrow(arcs) > 0) {
arc <- arcs[i, ]
if (any(arc[1] == arcs[-i, 1] & arc[2] == arcs[-i, 2])) {
coincidence <- which(arc[1] == arcs[, 1] & arc[2] == arcs[, 2])
coincidence.arcs <- arcs[coincidence, ]
k <- which(coincidence.arcs[, 3] == min(coincidence.arcs[, 3]))[1]
min.arc <- coincidence.arcs[k, ]
new.arcs <- rbind(new.arcs, min.arc)
arcs <- matrix(arcs[-coincidence, ], ncol = 3)
} else {
new.arcs <- rbind(new.arcs, arc)
arcs <- matrix(arcs[-i, ], ncol = 3)
}
}
colnames(new.arcs) <- c("head", "tail", "weight")
} else {
while (nrow(arcs) > 0) {
arc <- arcs[i, ]
if (any(arc[1] == arcs[-i, 1] & arc[2] == arcs[-i, 2]) |
any(arc[1] == arcs[-i, 2] & arc[2] == arcs[-i, 1])) {
coincidence <- which(arc[1] == arcs[, 1] & arc[2] == arcs[, 2] |
arc[1] == arcs[, 2] & arc[2] == arcs[, 1])
coincidence.arcs <- arcs[coincidence, ]
k <- which(coincidence.arcs[, 3] == min(coincidence.arcs[, 3]))[1]
min.arc <- coincidence.arcs[k, ]
new.arcs <- rbind(new.arcs, min.arc)
arcs <- matrix(arcs[-coincidence, ], ncol = 3)
} else {
new.arcs <- rbind(new.arcs, arc)
arcs <- matrix(arcs[-i, ], ncol = 3)
}
}
colnames(new.arcs) <- c("ept1", "ept2", "weight")
}
rownames(new.arcs) <- NULL
return(new.arcs)
} |
mnlfa_mstep_item_loglike_2pl_update_parameters <- function(y, y_resp, theta, parms, Xdes_int,
Xdes_slo, post, b_index, a_index, parms_indices, h, N_item,
regular_type, regular_lam, center_group_parms, eps=1E-15, L_max=.25 )
{
res <- mnlfa_mstep_item_loglike_2pl_deriv( y=y, y_resp=y_resp, theta=theta,
parms=parms, Xdes_int=Xdes_int, Xdes_slo=Xdes_slo, post=post, b_index=b_index,
a_index=a_index, parms_indices=parms_indices, h=h, N_item=N_item, eps=eps )
incr <- res$incr
L <- max( res$D2_max, L_max)
ll <- res$ll
parms[ parms_indices ] <- parms[ parms_indices ] + incr
parms <- mnlfa_parameter_regularization( parms=parms, parms_indices=parms_indices,
L=L, regular_type=regular_type, regular_lam=regular_lam, regular_tau=NULL,
regular_alpha=NULL, center_group_parms=center_group_parms )
res <- list( parms=parms, ll=ll)
return(res)
} |
allele.name <- function(x,nr=1) {
lx <- length(x)
vec <- NULL
for (i in 1:lx) {
fa <- substr(x[i],nr,nr)
vec <- c(vec,fa)
}
return(vec)
} |
if(all(sapply(c("testthat", "glmnet", "cvAUC", "rpart", "quadprog", "nloptr"), requireNamespace))){
testthat::context("Meta methods")
set.seed(1)
N <- 200
X <- matrix(rnorm(N * 6), N, 6)
X <- as.data.frame(X)
Y <- rbinom(N, 1, plogis(.2*X[, 1] + .1*X[, 2] + 2*X[, 3] + .1*X[, 3]*X[, 4] - .2*abs(X[, 4])))
table(Y)
SL.library <- c("SL.rpart", "SL.glmnet", "SL.mean")
test.NNLS <- SuperLearner(Y = Y, X = X, SL.library = SL.library, verbose = F,
cvControl = list(V = 2),
method = "method.NNLS", family = binomial())
print(test.NNLS)
testthat::expect_gte(min(test.NNLS$SL.predict), 0)
testthat::expect_lte(max(test.NNLS$SL.predict), 1)
pred = predict(test.NNLS)
summary(pred$pred)
testthat::expect_gte(min(pred$pred), 0)
testthat::expect_lte(max(pred$pred), 1)
SL.bad_algorithm = function(Y, X, newX, ...) { stop("bad algorithm") }
sl_bad <- SuperLearner(Y = Y, X = X, verbose = T,
SL.library = c(SL.library, "SL.bad_algorithm"),
cvControl = list(V = 2),
method = "method.NNLS", family = binomial())
print(sl_bad)
testthat::expect_gte(min(sl_bad$SL.predict), 0)
testthat::expect_lte(max(sl_bad$SL.predict), 1)
pred = predict(sl_bad)
summary(pred$pred)
testthat::expect_gte(min(pred$pred), 0)
testthat::expect_lte(max(pred$pred), 1)
rm(sl_bad)
test.NNLS2 <- SuperLearner(Y = Y, X = X, SL.library = SL.library, verbose = F,
cvControl = list(V = 2),
method = "method.NNLS2", family = binomial())
print(test.NNLS2)
testthat::expect_gte(min(test.NNLS2$SL.predict), 0)
testthat::expect_lte(max(test.NNLS2$SL.predict), 1)
if (FALSE) {
sl_bad <- SuperLearner(Y = Y, X = X, verbose = T,
SL.library = c(SL.library, "SL.bad_algorithm"),
cvControl = list(V = 2),
method = "method.NNLS2", family = binomial())
print(sl_bad)
testthat::expect_gte(min(sl_bad$SL.predict), 0)
testthat::expect_lte(max(sl_bad$SL.predict), 1)
pred = predict(sl_bad)
summary(pred$pred)
testthat::expect_gte(min(pred$pred), 0)
testthat::expect_lte(max(pred$pred), 1)
rm(sl_bad)
}
test.NNloglik <- SuperLearner(Y = Y, X = X, SL.library = SL.library, verbose = F,
cvControl = list(V = 2),
method = "method.NNloglik", family = binomial())
print(test.NNloglik)
testthat::expect_gte(min(test.NNloglik$SL.predict), 0)
testthat::expect_lte(max(test.NNloglik$SL.predict), 1)
sl_bad <- SuperLearner(Y = Y, X = X, verbose = T,
SL.library = c(SL.library, "SL.bad_algorithm"),
cvControl = list(V = 2),
method = "method.NNloglik", family = binomial())
print(sl_bad)
summary(sl_bad$SL.predict)
testthat::expect_gte(min(sl_bad$SL.predict), 0)
testthat::expect_lte(max(sl_bad$SL.predict), 1)
pred = predict(sl_bad)
summary(pred$pred)
testthat::expect_gte(min(pred$pred), 0)
testthat::expect_lte(max(pred$pred), 1)
rm(sl_bad)
test.CC_LS <- SuperLearner(Y = Y, X = X, SL.library = SL.library, verbose = F,
cvControl = list(V = 2),
method = "method.CC_LS", family = binomial())
print(test.CC_LS)
testthat::expect_gte(min(test.CC_LS$SL.predict), 0)
testthat::expect_lte(max(test.CC_LS$SL.predict), 1)
if (FALSE) {
sl_bad <- SuperLearner(Y = Y, X = X, verbose = T,
SL.library = c(SL.library, "SL.bad_algorithm"),
cvControl = list(V = 2),
method = "method.CC_LS", family = binomial())
print(sl_bad)
summary(sl_bad$SL.predict)
testthat::expect_gte(min(sl_bad$SL.predict), 0)
testthat::expect_lte(max(sl_bad$SL.predict), 1)
pred = predict(sl_bad)
summary(pred$pred)
testthat::expect_gte(min(pred$pred), 0)
testthat::expect_lte(max(pred$pred), 1)
rm(sl_bad)
}
test.CC_nloglik <- SuperLearner(Y = Y, X = X, SL.library = SL.library, verbose = F,
cvControl = list(V = 2),
method = "method.CC_nloglik", family = binomial())
print(test.CC_nloglik)
testthat::expect_gte(min(test.CC_nloglik$SL.predict), 0)
testthat::expect_lte(max(test.CC_nloglik$SL.predict), 1)
sl_bad <- SuperLearner(Y = Y, X = X, verbose = T,
SL.library = c(SL.library, "SL.bad_algorithm"),
cvControl = list(V = 2),
method = "method.CC_nloglik", family = binomial())
print(sl_bad)
summary(sl_bad$SL.predict)
testthat::expect_gte(min(sl_bad$SL.predict), 0)
testthat::expect_lte(max(sl_bad$SL.predict), 1)
pred = predict(sl_bad)
summary(pred$pred)
testthat::expect_gte(min(pred$pred), 0)
testthat::expect_lte(max(pred$pred), 1)
rm(sl_bad)
test.AUC <- SuperLearner(Y = Y, X = X, SL.library = SL.library, verbose = FALSE,
cvControl = list(V = 2),
method = "method.AUC", family = binomial())
print(test.AUC)
testthat::expect_gte(min(test.AUC$SL.predict), 0)
testthat::expect_lte(max(test.AUC$SL.predict), 1)
sl_bad <- SuperLearner(Y = Y, X = X, verbose = TRUE,
SL.library = c(SL.library, "SL.bad_algorithm"),
cvControl = list(V = 2),
method = "method.AUC", family = binomial())
print(sl_bad)
summary(sl_bad$SL.predict)
testthat::expect_gte(min(sl_bad$SL.predict), 0)
testthat::expect_lte(max(sl_bad$SL.predict), 1)
pred = predict(sl_bad)
summary(pred$pred)
testthat::expect_gte(min(pred$pred), 0)
testthat::expect_lte(max(pred$pred), 1)
rm(sl_bad)
} |
mail_merge <- function(data, message, to_col = "email", send = c("preview", "draft", "immediately"),
confirm = FALSE,
sleep_preview = 1, sleep_send = 0.1
){
send <- match.arg(send)
preview <- identical(send, "preview")
draft <- identical(send, "draft")
if (send != "preview" && !gmailr::gm_has_token()) {
stop(
"You must authenticate with gmailr first. Use `gmailr::gm_auth()",
call. = FALSE
)
}
if(nrow(data) == 0) {
warning("nothing to email")
return(invisible(data))
}
if(is.null(data[[to_col]])) {
stop("'data' must contain an 'email' column, or specify a 'to_col'")
}
msg <- mm_read_message(message)
if(!preview && !confirm) {
confirm_msg <- paste0("Send ", nrow(data), " emails (", send, ")?")
cat(confirm_msg)
if (yesno()) {
return(invisible())
}
}
z <- data %>%
purrr::pmap(list) %>%
purrr::map(function(x) {
glued_data <- glue_mail(x, msg)
args <- list(
to = x[[to_col]],
body = glued_data[["body"]],
subject = glued_data[["subject"]],
cc = glued_data[["cc"]]
)
if (preview) {
do.call(mm_preview_mail, args)
} else {
Sys.sleep(sleep_send)
args <- append(args, list(draft = draft))
if (draft) {
do.call(mm_send_draft, args)
} else {
do.call(mm_send_mail, args)
}
}
})
if (preview) {
base::message("Sent preview to viewer")
class(z) <- "mailmerge_preview"
attr(z, "sleep") <- sleep_preview
} else {
n_messages <- vapply(z, function(x) isTRUE(x$success), FUN.VALUE = logical(1)) %>% sum()
if (draft) {
base::message("Sent ", n_messages, " messages to your draft folder")
} else {
base::message("Sent ", n_messages, " messages to email")
}
}
z
}
print.mailmerge_preview <- function(x, ...) {
purrr::walk(x, function(xx){
in_viewer(xx)
Sys.sleep(attr(x, "sleep"))
}
)
} |
options(expressions = 5e+05)
preaverage <- function(X, scal = 3) {
if (!(is.numeric(X))) {
stop("The input in `X' should be a numeric matrix which has at each
column the time series that we want to pre-average.")
}
if ((scal <= 0)) {
stop("The scaling constant which is used to define the way we
preaverage the data should be a positive number.")
}
if (abs(scal - round(scal)) > .Machine$double.eps^0.5) {
warning("The input for `scal' should be a positive integer. If it is
a positive real number then the integer part of the given number is
used as the value of `scal'.")
}
scal <- as.integer(scal)
l <- nrow(X)
d <- ncol(X)
l1 <- ceiling(l / scal)
res <- matrix(NA, l1, d)
if (l1 == 1) {
res <- apply(X[((l1 - 1) * scal + 1):l, , drop = FALSE], 2, mean)
} else {
for (i in 1:(l1 - 1)) {
res[i, ] <- apply(X[((i - 1) * scal + 1):(i * scal), , drop = FALSE], 2, mean)
}
res[l1, ] <- apply(X[((l1 - 1) * scal + 1):l, , drop = FALSE], 2, mean)
}
return(res)
}
match.cpt.ts <- function(X, cpt, thr_const = 1,
thr_fin = thr_const * sqrt(2 * log(nrow(X))),
scales = -1, count = 5) {
if (missing(cpt)) {
cpt <- thr_L2(X)
}
lsc <- length(scales)
s_cpt <- sort(cpt)
lx <- nrow(X)
lc <- ncol(X)
lc_i <- lc /lsc
count <- min(lc_i, count)
pdim <- (- lsc + sqrt((lsc^2) + 8 * lc * lsc)) /( 2 * lsc)
if (round(pdim) != pdim){
stop("The input in X of the function match.cpt.ts does not seem to be
the result of a wavelet transformation on the original time series since
the dimensionality does not match")
}
lcpt <- length(cpt)
if (lcpt == 0){
return(list(time_series_indicator = "Matching the time series with the change-points is not possible when no change-points are given."))
}
else{
seb_set <- c(1, s_cpt, lx)
lseb_set <- length(seb_set)
Res <- list()
Res$matches <- list()
Res$most.important <- list()
for (j in 1:lsc){
Res$matches[[j]] <- list()
Res$most.important[[j]] <- list()
CS <- matrix(NA, lc_i, lcpt)
ts1 <- matrix(0, lc_i, 2*lcpt)
ts1[,seq(1, 2*lcpt, 2)] <- seq(1:(lc_i))
X_temp <- X[,((j-1)*lc_i + 1) : (j*lc_i)]
for (i in 1:lc_i) {
CS[i, ] <- cusum_one_multi(X_temp[,i], seb_set[1:(lseb_set - 2)], seb_set[3:(lseb_set)], seb_set[2:(lseb_set - 1)])
}
ts1[, seq(2,2*lcpt,2)] <- CS[, 1:lcpt]
ord <- list()
for(i in 1:lcpt){
ord[[i]] <- order(CS[,i], decreasing=T)
ts1[,(2*i - 1):(2*i)] <- ts1[ord[[i]],(2*i - 1):(2*i)]
}
indic2 <- integer()
for (i in 1:(lcpt)) {
indic2[i] <- which(ts1[,2*i] <= thr_fin)[1]
}
mind <- max(indic2)
if (is.na(mind)){
ts <- ts1[1:(lc_i), ,drop = FALSE]
}
else{
if (mind == 1){
ts <- matrix(0,0,2*lcpt)
}
else{
ts <- ts1[1:(mind - 1), ,drop = FALSE]
}
}
res <- list()
A <- matrix(0, pdim, pdim)
gdata::upperTriangle(A, diag = TRUE, byrow = T) <- 1:lc_i
B <- list()
B$matches <- list()
for (i in 1:lcpt){
res[[i]] <- list()
res[[i]] <- ts[which(ts[,2*i] != 0),(2*i - 1)]
M_temp <- matrix(0,count,2)
for(k in 1:count){
M_temp[k,] <- which(A == ts1[k,(2*i -1)], arr.ind = TRUE)
}
M_temp <- cbind(M_temp,ts1[1:count,(2*i)])
B$most.important[[i]] <- M_temp
if (length(res[[i]]) == 0) {
B$matches[[i]] <- matrix(0,0,2)
}
else{
B$matches[[i]] <- matrix(0,length(res[[i]]),2)
for(k in 1:length(res[[i]])){
B$matches[[i]][k,] <- which(A == res[[i]][k], arr.ind = TRUE)
}
}
}
Res$matches[[j]] <- B$matches
Res$most.important[[j]] <- B$most.important
}
Res_fin <- list()
Res_fin$matches <- list()
Res_fin$most.important <- list()
for (i in 1:lcpt){
Res_fin$matches[[i]] <- matrix(0,1,2)
Res_fin$most.important[[i]] <- matrix(0,1,3)
for (j in 1:lsc){
Res_fin$matches[[i]] <- rbind(Res_fin$matches[[i]], Res$matches[[j]][[i]])
Res_fin$most.important[[i]] <- rbind(Res_fin$most.important[[i]], Res$most.important[[j]][[i]])
}
Res_fin$matches[[i]] <- Res_fin$matches[[i]][-1,]
Res_fin$most.important[[i]] <- Res_fin$most.important[[i]][-1,]
Res_fin$matches[[i]] <- unique(Res_fin$matches[[i]])
ord.temp <- order(Res_fin$most.important[[i]][,3], decreasing=T)
Res_fin$most.important[[i]] <- unique(Res_fin$most.important[[i]][ord.temp,1:2])
Res_fin$most.important[[i]] <- Res_fin$most.important[[i]][1:count,]
}
return(list(time_series_indicator = Res_fin$matches, most_important = Res_fin$most.important))
}
}
detect.th <- function(X, approach = c("euclidean", "infinity"),
th_max = 2.25, th_sum = 0.65,
pointsgen = 10, scales = -1,
preaverage_gen = FALSE, scal_gen = 3,
min_dist = 1) {
approach = as.character(approach)
sgn <- sign(stats::cor(X))
if (!is.null(scales)) {
stopifnot(sum(scales < 0) == length(scales))
scales <- sort(scales, decreasing = TRUE)
}
if (ncol(X) <= 4) {
approach[1] <- "infinity"
}
input <- t(hdbinseg::gen.input(t(X), scales, TRUE, diag = FALSE, sgn))
if (approach[1] == "infinity") {
cpt <- cpt_ts_Linf(input, thr_const_m = th_max,
points_m = pointsgen,
preproc = preaverage_gen, scl = scal_gen,
scale = scales)
} else {
cpt <- cpt_ts_L2(input, thr_const_s = th_sum,
points_s = pointsgen,
preproc = preaverage_gen, scl = scal_gen,
scale = scales)
}
no.of.cpt <- length(cpt$changepoints)
d_cpt <- diff(cpt$changepoints)
if ((min_dist <= 1) | (no.of.cpt <= 1) | (all(d_cpt > min_dist))) {
return(list(changepoints = cpt$changepoints,
no.of.cpts = no.of.cpt,
time_series = cpt$time_series))
} else {
return(prune_cpt(input, cpts = cpt$changepoints,
distance = min_dist))
}
}
detect.ic <- function(X, approach = c("euclidean", "infinity"),
th_max = 2.1, th_sum = 0.5,
pointsgen = 10, scales = -1,
alpha_gen = 0.1, preaverage_gen = FALSE,
scal_gen = 3, min_dist = 1) {
if (!(is.numeric(X))) {
stop("The input in `X' should be a numeric matrix.")
}
sgn <- sign(stats::cor(X))
if (!is.null(scales)) {
stopifnot(sum(scales < 0) == length(scales))
scales <- sort(scales, decreasing = TRUE)
}
if (ncol(X) <= 4) {
approach[1] <- "infinity"
}
input <- t(hdbinseg::gen.input(t(X), scales, TRUE, diag = FALSE, sgn))
input <- input + 10 ^ (-100)
if (approach[1] == "infinity") {
cpt <- ic_Linf(input, th_const = th_max,
points = pointsgen, alpha = alpha_gen,
preproc = preaverage_gen, scl = scal_gen)
} else {
cpt <- ic_L2(input, th_const = th_sum,
points = pointsgen, alpha = alpha_gen,
preproc = preaverage_gen, scl = scal_gen)
}
no.of.cpt <- cpt$no.of.cpts
d_cpt <- diff(cpt$changepoints)
if ((min_dist <= 1) | (no.of.cpt <= 1) | (all(d_cpt > min_dist))) {
return(cpt)
} else {
return(prune_cpt(input, cpt$changepoints, distance = min_dist))
}
} |
sylcount <- function(s, counts.only=TRUE)
{
.Call(R_sylcount, s, counts.only)
} |
interactiveTable <- function(x, ...,
txt.maxlen = 20,
button = getOption("htmlTable.interactiveTable.button", default = FALSE),
minimized.columns,
js.scripts = c()) {
UseMethod("interactiveTable")
}
getButtonDiv <- function(sign = "-") {
template <- system.file("html_components/button.html", package = "htmlTable")
if (template == "") {
stop("Could not find the button template file")
}
template <- readChar(template, nchars = file.info(template)$size)
gsub("%sign%", sign, template) %>%
gsub("[\n\r]", " ", .)
}
interactiveTable.default <- function(x, ...,
txt.maxlen = 20,
button = getOption("htmlTable.interactiveTable.button", default = FALSE),
minimized.columns = NULL,
js.scripts = c()) {
if ("data.frame" %in% class(x)) {
x <- prConvertDfFactors(x)
}
if (!is.null(minimized.columns)) {
if (is.character(minimized.columns)) {
if (minimized.columns != "last") {
stop(
"If you want to provide a character for columns you must",
" provide 'last' - '", minimized.columns, "' has not yet",
" been implemented."
)
}
minimized.columns <- ncol(x)
} else if (is.logical(minimized.columns)) {
minimized.columns <- which(minimized.columns)
} else if (!is.numeric(minimized.columns)) {
stop("Expecting the minimized columns to either be numbers or logical parameters")
} else if (max(minimized.columns) > ncol(x)) {
stop(
"You can't minimize columns larger than the number of columns available.",
"I.e. ", paste(minimized.columns[minimized.columns > ncol(x)], collapse = ", "),
" > ", ncol(x)
)
}
if (!is.null(dim(minimized.columns))) {
stop("Can only handle column vectors for minimization")
}
addon_elements <- paste(
"... ",
"<span class='hidden' style='display: none'>%span_inner_text%</span>"
)
if (button) {
addon_elements <- paste(
addon_elements,
getButtonDiv("+")
)
}
for (col_no in minimized.columns) {
for (row_no in 1:nrow(x)) {
if (nchar(x[row_no, col_no]) > txt.maxlen) {
x[row_no, col_no] <-
paste0(
substr(x[row_no, col_no], 1, txt.maxlen),
gsub("%span_inner_text%", x[row_no, col_no], addon_elements)
)
}
}
}
minimized.columns <- FALSE
}
tbl <- htmlTable(x, escape.html = FALSE, ...)
return(interactiveTable(tbl,
txt.maxlen = 20,
button = button,
minimized.columns = minimized.columns,
js.scripts = js.scripts
))
}
interactiveTable.htmlTable <- function(tbl,
txt.maxlen = 20,
button = getOption("htmlTable.interactiveTable.button", default = FALSE),
minimized.columns = NULL,
js.scripts = c()) {
if (!is.null(minimized.columns) && all(minimized.columns != FALSE)) {
stop(
"Can't minimize columns after creating the htmlTable.",
" Try calling the function directly with the input data that you used for htmlTable"
)
}
class(tbl) <- c("interactiveTable", class(tbl))
if (button) {
template <- system.file("javascript/button.js", package = "htmlTable")
if (template == "") {
stop("Could not find the javascript button template file")
}
template <- readChar(template, nchars = file.info(template)$size)
attr(tbl, "javascript") <- c(
js.scripts,
template %>%
gsub("%txt.maxlen%", txt.maxlen, .) %>%
gsub("%btn%", getButtonDiv(), .)
)
} else {
template <- system.file("javascript/toggler.js", package = "htmlTable")
if (template == "") {
stop("Could not find the javascript toggler template file")
}
template <- readChar(template, nchars = file.info(template)$size)
attr(tbl, "javascript") <- c(
js.scripts,
template %>%
gsub("%txt.maxlen%", txt.maxlen, .)
)
}
return(tbl)
}
knit_print.interactiveTable <- function(x, ...) {
if (getOption("interactiveTable_knitprint", FALSE)) {
asis_output(x)
} else {
options(interactiveTable_knitprint = TRUE)
asis_output(paste(
x,
attr(x, "javascript")
))
}
}
prGetScriptString <- function(x) {
scripts <- attr(x, "javascript")
if (is.null(scripts)) {
stop("You have provided an object of class ", class(x), " that does not contain a javascript attribute")
}
sapply(scripts,
USE.NAMES = FALSE,
FUN = function(s) {
if (s == "") {
return("")
}
paste(
"<script type = \"text/javascript\" language = \"javascript\">",
s,
"</script>"
)
}
) %>%
paste(collapse = "\n\n <!-- *** Next script group *** !-->\n")
}
print.interactiveTable <- function(x, useViewer, ...) {
args <- attr(x, "...")
print_args <- list(...)
for (n in names(print_args)) {
args[[n]] <- print_args[[n]]
}
if (missing(useViewer)) {
if ("useViewer" %in% names(args) &&
(is.logical(args$useViewer) ||
is.function(args$useViewer))) {
useViewer <- args$useViewer
args$useViewer <- NULL
} else {
useViewer <- TRUE
}
}
if (interactive() &&
!getOption("htmlTable.cat", FALSE) &&
(is.function(useViewer) ||
useViewer != FALSE)) {
if (is.null(args$file)) {
args$file <- tempfile(fileext = ".html")
}
htmlPage <- paste("<html>",
"<head>",
"<meta http-equiv=\"Content-type\" content=\"text/html; charset=UTF-8\">",
"<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js\"></script>",
"</head>",
"<body>",
"<div style=\"margin: 0 auto; display: table; margin-top: 1em;\">",
x,
"</div>",
prGetScriptString(x),
"</body>",
"</html>",
sep = "\n"
)
cat_args <- args
cat_args <- cat_args[names(cat_args) %in% names(formals(cat))[-1]]
do.call(cat, c(htmlPage, cat_args))
if (is.function(useViewer)) {
useViewer(args$file)
} else {
viewer <- getOption("viewer")
if (!is.null(viewer) &&
is.function(viewer)) {
viewer(args$file)
} else {
utils::browseURL(args$file)
}
}
} else {
cat_args <- args
cat_args <- cat_args[names(cat_args) %in% names(formals(cat))[-1]]
do.call(cat, c(x, cat_args))
cat(prGetScriptString(x))
}
invisible(x)
} |
extract.local.NLDAS <- function(outfolder, in.path, start_date, end_date, lat.in, lon.in,
overwrite = FALSE, verbose = FALSE, ...){
start_date <- as.POSIXlt(start_date, tz = "GMT")
end_date <- as.POSIXlt(end_date, tz = "GMT")
start_year <- lubridate::year(start_date)
end_year <- lubridate::year(end_date)
lat.in = as.numeric(lat.in)
lon.in = as.numeric(lon.in)
dir.create(outfolder, showWarnings=FALSE, recursive=TRUE)
ylist <- seq(start_year,end_year,by=1)
rows = length(ylist)
results <- data.frame(file=character(rows), host=character(rows),
mimetype=character(rows), formatname=character(rows),
startdate=character(rows), enddate=character(rows),
dbfile.name = "NLDAS",
stringsAsFactors = FALSE
)
var = data.frame(NLDAS.name = c("air_temperature","surface_downwelling_longwave_flux_in_air","air_pressure","downwelling_shortwave_flux_in_air","eastward_wind","northward_wind","specific_humidity","precipitation_amount"),
CF.name = c("air_temperature","surface_downwelling_longwave_flux_in_air","air_pressure","surface_downwelling_shortwave_flux_in_air","eastward_wind","northward_wind","specific_humidity","precipitation_flux"),
units = c('Kelvin',"W/m2","Pascal","W/m2","m/s","m/s","g/g","kg/m2/s")
)
for (i in 1:rows){
y.now = ylist[i]
if(rows>1 & i!=1 & i!=rows){
nday = ifelse(lubridate::leap_year(y.now), 366, 365)
day1 = 1
day2 = nday
days.use = day1:day2
} else if(rows==1){
nday = ifelse(lubridate::leap_year(y.now), 366, 365)
day1 <- lubridate::yday(start_date)
day2 <- lubridate::yday(end_date)
days.use = day1:day2
nday=length(days.use)
} else if(i==1) {
nday = ifelse(lubridate::leap_year(y.now), 366, 365)
day1 <- lubridate::yday(start_date)
day2 = nday
days.use = day1:day2
nday=length(days.use)
} else if(i==rows) {
nday = ifelse(lubridate::leap_year(y.now), 366, 365)
day1 = 1
day2 <- lubridate::yday(end_date)
days.use = day1:day2
nday=length(days.use)
}
ntime = nday*24
loc.file = file.path(outfolder, paste("NLDAS",y.now,"nc",sep="."))
dim.lat <- ncdf4::ncdim_def(name='latitude', units='degree_north', vals=lat.in, create_dimvar=TRUE)
dim.lon <- ncdf4::ncdim_def(name='longitude', units='degree_east', vals=lon.in, create_dimvar=TRUE)
dim.time <- ncdf4::ncdim_def(name='time', units="sec", vals=seq((min(days.use)+1-1/24)*24*360, (max(days.use)+1-1/24)*24*360, length.out=ntime), create_dimvar=TRUE, unlim=TRUE)
nc.dim=list(dim.lat,dim.lon,dim.time)
var.list = list()
dat.list = list()
for(j in 1:nrow(var)){
var.list[[j]] = ncdf4::ncvar_def(name=as.character(var$CF.name[j]), units=as.character(var$units[j]), dim=nc.dim, missval=-999, verbose=verbose)
dat.list[[j]] <- array(NA, dim=c(length(lat.in), length(lon.in), ntime))
}
names(var.list) <- names(dat.list) <- var$CF.name
print("")
print(y.now)
pb <- utils::txtProgressBar(min=1, max=nday, style=3)
pb.index=1
for(j in 1:length(days.use)){
utils::setTxtProgressBar(pb, pb.index)
date.now <- as.Date(days.use[j], origin=as.Date(paste0(y.now-1,"-12-31")))
mo.now <- stringr::str_pad(lubridate::month(date.now), 2, pad="0")
day.mo <- stringr::str_pad(lubridate::day(date.now), 2, pad="0")
doy <- stringr::str_pad(days.use[j], 3, pad="0")
dap_file <- ncdf4::nc_open(file.path(in.path,y.now,mo.now,paste0("NLDAS_FORA0125_H.A",y.now, mo.now,day.mo,".nc")))
lats <- ncdf4::ncvar_get(dap_file, "lat")
lons <- ncdf4::ncvar_get(dap_file, "lon")
x.inc <- mean(abs(diff(lons)))
y.inc <- mean(abs(diff(lats)))
lat.use <- which(lats-y.inc/2<=lat.in & lats+y.inc/2>=lat.in)
lon.use <- which(lons-x.inc/2<=lon.in & lons+x.inc/2>=lon.in)
for (v in 1:nrow(var)) {
v.nldas <- paste(var$NLDAS.name[v])
v.cf <- paste(var$CF.name [v])
if(!v.nldas %in% names(dap_file$var) & v.cf %in% names(dap_file$var)) v.nldas <- v.cf
if(dap_file$var[[v.nldas]]$ndims == 4){
dat.list[[v.cf]][,,(j*24-23):(j*24)] <- ncdf4::ncvar_get(dap_file, v.nldas,
start=c(lon.use,lat.use,1,1),
count=c(1,1,1,24)
)
} else {
dat.list[[v.cf]][,,(j*24-23):(j*24)] <- ncdf4::ncvar_get(dap_file, v.nldas,
start=c(lon.use,lat.use,1),
count=c(1,1,24)
)
}
}
ncdf4::nc_close(dap_file)
pb.index=pb.index+1
}
dat.list[["precipitation_flux"]] = dat.list[["precipitation_flux"]]/(60*60)
loc <- ncdf4::nc_create(filename=loc.file, vars=var.list, verbose=verbose)
for(j in 1:nrow(var)){
ncdf4::ncvar_put(nc=loc, varid=as.character(var$CF.name[j]), vals=dat.list[[j]])
}
ncdf4::nc_close(loc)
results$file[i] <- loc.file
results$startdate[i] <- paste0(as.Date(paste(y.now, day1, sep="-"), format = "%Y-%j"), " 00:00:00")
results$enddate[i] <- paste0(as.Date(paste(y.now, day2, sep="-"), format = "%Y-%j"), " 00:00:00")
results$mimetype[i] <- 'application/x-netcdf'
results$formatname[i] <- 'CF Meteorology'
}
} |
context("to_epochtime")
test_that("to_epochtime with numeric works", {
expect_equal(to_epochtime(1496587909), 1496587909L)
expect_equal(to_epochtime(1496587909L), 1496587909L)
})
test_that("to_epochtime with POSIXct and POSIXlt works", {
x <- structure(1496587909, class = c("POSIXct", "POSIXt"), tzone = "UTC")
expect_equal(to_epochtime(x), 1496587909L)
x <- as.POSIXct(x)
expect_equal(to_epochtime(x), 1496587909L)
})
test_that("to_epochtime with Date works", {
x <- as.Date("2017-06-04", "%Y-%m-%d", tz = "UTC")
expect_equal(to_epochtime(x), 1496534400L)
})
test_that("to_epochtime with character works", {
testthat::skip_if_not(Sys.timezone() == "Asia/Tokyo")
x <- "1970-01-01"
y <- as.integer(lubridate::ymd(x, tz = Sys.timezone()))
expect_equal(to_epochtime(x), to_epochtime(y))
x2 <- "1970-01-01 00:00:00"
expect_equal(to_epochtime(x), to_epochtime(x2))
})
test_that("to_epochtime with NULL throws error", {
expect_error(to_epochtime(NULL))
})
test_that("to_epochtime with elements more than 1 length throws error", {
expect_error(to_epochtime(1:2))
}) |
FKM.pf.noise <- function (X, k, b, delta, RS, stand, startU, index,alpha,conv, maxit, seed = NULL)
{
if (missing(X))
stop("The data set must be given")
if (is.null(X))
stop("The data set X is empty")
X=data.matrix(X)
n=nrow(X)
p=ncol(X)
if(p==1){
stop("Dataset X must contain more than one dimension")
}
if (is.null(rownames(X)))
rn=paste("Obj",1:n,sep=" ")
else
rn=rownames(X)
if (is.null(colnames(X)))
cn=paste("Var",1:p,sep=" ")
else
cn=colnames(X)
if (any(is.na(X)))
stop("The data set X must not contain NA values")
if (!is.numeric(X))
stop("The data set X is not a numeric data.frame or matrix")
if ((missing(startU)) || (is.null(startU)))
{
check=1
checkMiss = missing(k) || is.null(k) || !is.numeric(k)
if (checkMiss)
{
k= 2:6
cat("The default value k=2:6 has been set",fill=TRUE)
}
nk <- length(k)
if(nk != 1){
if(!checkMiss){
checkK = any(k <= 1) | any((k-as.integer(k)) != 0)
if(checkK)
{
k = 2:6
nk <- length(k)
cat("The number of clusters k must be greter than 1, integer and numeric: the default value k=2:6 will be used ",fill=TRUE)
}else{
k <- sort(unique(k))
nk <- length(k)
}
}
if (missing(index))
{
index = "SIL.F"
cat("The default index SIL.F has been set ",fill=TRUE)
}else{
if(length(index) != 1)
{
index = "SIL.F"
cat("The index must be a single value: SIL.F will be used ",fill=TRUE)
}else{
if(all(index!=c("PC","PE","MPC","SIL","SIL.F","XB"))){
index = "SIL.F"
cat("No match found for the index name: SIL.F will be used ", fill = TRUE)
}
}
}
if(index == "SIL.F"){
if (missing(alpha))
{
alpha=1
cat("The default value alpha=1 has been set for computing SIL.F ",fill=TRUE)
}else{
if (!is.numeric(alpha))
{
alpha=1
cat("The weighting coefficient alpha is not numeric: the default value alpha=1 will be used for computing SIL.F ",fill=TRUE)
}
if (alpha<0)
{
alpha=1
cat("The number of clusters k must be non negative: the value alpha=1 will be used for computing SIL.F ",fill=TRUE)
}
}
}else{
alpha = 1
}
}else{
nk <- 1
if (missing(index))
{
index = "SIL.F"
}else{
if(length(index) != 1)
{
index = "SIL.F"
cat("The index must be a single value: SIL.F will be used ",fill=TRUE)
}else{
if(!any(index==c("PC","PE","MPC","SIL","SIL.F","XB"))){
index = "SIL.F"
cat("No match found for the index name: SIL.F will be used ", fill = TRUE)
}
}
}
if(index == "SIL.F"){
if (missing(alpha))
{
alpha=1
}else{
if (!is.numeric(alpha))
{
alpha=1
cat("The weighting coefficient alpha is not numeric: the default value alpha=1 will be used for computing SIL.F ",fill=TRUE)
}
if (alpha<0)
{
alpha=1
cat("The number of clusters k must be non negative: the value alpha=1 will be used for computing SIL.F ",fill=TRUE)
}
}
}else{
alpha = 1
}
if (!is.numeric(k))
{
k=2
cat("The number of clusters k is not numeric: the default value k=2 will be used ",fill=TRUE)
}
if ((k>ceiling(n/2)) || (k<2))
{
k=2
cat("The number of clusters k must be an integer in {2, 3, ..., ceiling(n/2)}: the default value k=2 will be used ",fill=TRUE)
}
if (k%%ceiling(k)>0)
{
k=ceiling(k)
cat("The number of clusters k must be an integer in {2, 3, ..., ceiling(nrow(X)/2)}: the value ceiling(k) will be used ",fill=TRUE)
}
}
}else
{
startU=as.matrix(startU)
ns=nrow(startU)
k=ncol(startU)
check=0
nk = 1
if (any(is.na(startU)))
{
k=2
cat("The rational start must not contain NA values: the default value k=2 and a random start will be used ",fill=TRUE)
check=1
}
if (!is.numeric(startU))
{
k=2
cat("The rational start is not a numeric data.frame or matrix: the default value k=2 and a random start will be used ",fill=TRUE)
check=1
}
if ((k>ceiling(n/2)) || (k<2))
{
k=2
cat("The number of clusters k must be an integer in {2, 3, ..., ceiling(n/2)}: the default value k=2 and a random start will be used ",fill=TRUE)
check=1
}
if ((ns!=n) && (check=0))
{
cat("The number of rows of startU is different from that of X: k=ncol(startU) and a random start will be used ",fill=TRUE)
check=1
}
if (any(apply(startU,1,sum)!=1))
{
startU=startU/apply(startU,1,sum)
cat("The sums of the rows of startU must be equal to 1: the rows of startU will be normalized to unit row-wise sum ",fill=TRUE)
}
if (missing(index))
{
index = "SIL.F"
}else{
if(length(index) != 1)
{
index = "SIL.F"
cat("The index must be a single value: SIL.F will be used ",fill=TRUE)
}else{
if(!any(index==c("PC","PE","MPC","SIL","SIL.F","XB"))){
index = "SIL.F"
cat("No match found for the index name: SIL.F will be used ", fill = TRUE)
}
}
}
if(index == "SIL.F"){
if (missing(alpha))
{
alpha=1
}else{
if (!is.numeric(alpha))
{
alpha=1
cat("The weighting coefficient alpha is not numeric: the default value alpha=1 will be used for computing SIL.F ",fill=TRUE)
}
if (alpha<0)
{
alpha=1
cat("The number of clusters k must be non negative: the value alpha=1 will be used for computing SIL.F ",fill=TRUE)
}
}
}else{
alpha = 1
}
}
if (missing(b))
{
b=0.5
}
if(length(b) != 1){
b = b
cat("The parameter of the polynomial fuzzifier beta must be a single value: the default value beta=0.5 will be used",fill=TRUE)
}
if (!is.numeric(b))
{
b=0.5
cat("The parameter of the polynomial fuzzifier beta is not numeric: the default value beta=0.5 will be used ",fill=TRUE)
}
if ((b>1) || (b<0))
{
b=0.5
cat("The parameter of the polynomial fuzzifier beta must be in [0,1]: the default value beta=0.5 will be used ",fill=TRUE)
}
if (missing(RS))
{
RS=1
}
if (!is.numeric(RS))
{
cat("The number of starts RS is not numeric: the default value RS=1 will be used ",fill=TRUE)
RS=1
}
if (RS<1)
{
cat("The number of starts RS must be an integer >=1: the default value RS=1 will be used ",fill=TRUE)
RS=1
}
if (RS%%ceiling(RS)>0)
{
cat("The number of starts RS must be an integer >=1: the value ceiling(RS) will be used ",fill=TRUE)
RS=ceiling(RS)
}
if (missing(conv))
conv=1e-9
if (conv<=0)
{
cat("The convergence criterion conv must be a (small) value >0: the default value conv=1e-9 will be used ",fill=TRUE)
conv=1e-9
}
if (!is.numeric(conv))
{
cat("The convergence criterion conv is not numeric: the default value conv=1e-9 will be used ",fill=TRUE)
conv=1e-9
}
if (missing(maxit))
maxit=1e+6
if (!is.numeric(maxit))
{
cat("The maximum number of iterations maxit is not numeric: the default value maxit=1e+6 will be used ",fill=TRUE)
maxit=1e+6
}
if (maxit<=0)
{
cat("The maximum number of iterations maxit must be an integer >0: the default value maxit=1e+6 will be used ",fill=TRUE)
maxit=1e+6
}
if (maxit%%ceiling(maxit)>0)
{
cat("The maximum number of iterations maxit must be an integer >0: the value ceiling(maxit) will be used ",fill=TRUE)
maxit=ceiling(maxit)
}
if(!is.null(seed))
{
if (!is.numeric(seed))
{
cat("The seed value is not numeric: set.seed(NULL) will be used ",fill=TRUE)
set.seed(NULL)
}else{
set.seed(seed)
}
}
Xraw=X
rownames(Xraw)=rownames(X)
colnames(Xraw)=colnames(X)
if (missing(stand))
stand=0
if (!is.numeric(stand))
stand=0
if (stand==1)
X=scale(X,center=TRUE,scale=TRUE)[,]
checkDelta = FALSE
if(missing(delta))
{
delta = rep(1,nk)
checkDelta = TRUE
}else{
if(length(delta) != 1)
{
if(is.numeric(delta))
{
if(any(delta < 0)){
cat("The noise distance delta must be non negative: the default value (see ?FKM.noise) will be used ",fill=TRUE)
checkDelta = TRUE
delta = rep(1,nk)
}
if(length(delta) != nk)
{cat("The number of elements of delta is different from the number of elements of k: the default value (see ?FKM.noise) will be used" ,fill=TRUE)
checkDelta = TRUE
delta = rep(1,nk)
}
if (any(delta==0))
{stop("When delta=0, the standard algorithm is applied: run the function FKM")}
}else{
checkDelta = TRUE
delta = rep(1,nk)
cat("The noise distance delta must is not numeric: the default value (see ?FKM.noise) will be used ",fill=TRUE)
}
}else{
if (delta==0)
stop("When delta=0, the standard algorithm is applied: run the function FKM")
if (!is.numeric(delta))
{
cat("The noise distance delta must is not numeric: the default value (see ?FKM.noise) will be used ",fill=TRUE)
checkDelta = TRUE
delta = rep(1,nk)
}
if (delta<0)
{
cat("The noise distance delta must be non negative: the default value (see ?FKM.noise) will be used ",fill=TRUE)
checkDelta = TRUE
delta = rep(1,nk)
}
if(nk != 1 && !checkDelta)
{
delta = rep(delta,nk)
}
}
}
crit.f <- rep(NA,nk)
crit = 0
for(c in 1:nk)
{
if ((check!=1))
{
if(checkDelta)
{
Hd=FKM.pf(X,k[c],b = b,RS=1,stand = stand,conv=1e-6,seed = seed)$H
Dd = euclidean_distance(data = X,H = Hd,n = n,k = k[c])
delta[c] <- sqrt(mean(Dd))
}
main.temp <- mainFKM_pf_noise_U(data = X, b = b, delta = delta[c],
n = n, p = p, k = k[c],index = index,
alpha = alpha, U = startU, conv = conv, maxit = maxit)
}else{
if(checkDelta)
{
Hd=FKM.pf(X,k[c],b = b,RS=1,stand = stand,conv=1e-6,seed = seed)$H
Dd = euclidean_distance(data = X,H = Hd,n = n,k = k[c])
delta[c] <- sqrt(mean(Dd))
}
main.temp <- mainFKM_pf_noise(data = X, b = b, delta = delta[c],
n = n, p = p, k = k[c],
index = index,alpha = alpha,rs = RS, conv = conv, maxit = maxit)
}
crit.temp = main.temp$index_max
crit.f[c] = main.temp$index
if(c == 1 | crit < crit.temp)
{
main = main.temp
crit = crit.temp
}
}
value = as.vector(main$value)
it = as.vector(main$iter)
U.opt = main$U
H.opt = main$H
names(crit.f) = paste(index," ","k=",k,sep="")
names(delta) = paste("Noise distance k=",k)
k = main$k
rownames(H.opt)=paste("Clus",1:k,sep=" ")
colnames(H.opt)=cn
rownames(U.opt)=rn
colnames(U.opt)=rownames(H.opt)
names(value)=paste("Start",1:RS,sep=" ")
names(it)=names(value)
names(k)=c("Number of clusters")
names(b)=c("Parameter of polynomial fuzzifier")
if (stand!=1)
stand=0
names(stand)=c("Standardization (1=Yes, 0=No)")
clus=cl.memb(U.opt)
out = list( U=U.opt,
H=H.opt,
F=NULL,
clus=clus,
medoid=NULL,
value=value,
criterion = crit.f,
iter=it,
k=k,
m=NULL,
ent=NULL,
b=b,
vp=NULL,
delta=delta,
stand=stand,
Xca=X,
X=Xraw,
D=NULL,
call=match.call())
class(out)=c("fclust")
return(out)
} |
decorate<-function(func, content_type="text/html", strict_params=FALSE){
args_allowed<-
names(formals(func))
function(req, res, err){
res$content_type(content_type)
passed_params<-
modifyList(req$params, req$headers)
passed_params$req<-req
passed_params$res<-res
passed_params$err<-err
if(strict_params){
args_present <- sapply(args_allowed, function(p) p %in% names(passed_params))
if(!all(args_present)){
err$set(paste0("Requested arguments not provided: ", paste(args_allowed[!args_present], collapse=", ")))
return(NULL)
}
}
if(!"..." %in% args_allowed){
passed_params<-
passed_params[names(passed_params) %in% args_allowed]
}
do.call(func, passed_params)
}
} |
library(hamcrest)
tanpi.foo <- function(...) 41
Math.bar <- function(...) 44
test.tanpi.1 <- function() assertThat(tanpi(-0.01), identicalTo(-0.0314262660433512, tol = 0.000100))
test.tanpi.2 <- function() assertThat(tanpi(-0.1), identicalTo(-0.324919696232906, tol = 0.000100))
test.tanpi.3 <- function() assertThat(tanpi(-1), identicalTo(0))
test.tanpi.4 <- function() assertThat(tanpi(-1.5), identicalTo(NaN))
test.tanpi.5 <- function() assertThat(tanpi(-2), identicalTo(0))
test.tanpi.6 <- function() assertThat(tanpi(-2.5), identicalTo(NaN))
test.tanpi.7 <- function() assertThat(tanpi(-4), identicalTo(0))
test.tanpi.8 <- function() assertThat(tanpi(-10), identicalTo(0))
test.tanpi.9 <- function() assertThat(tanpi(-100), identicalTo(0))
test.tanpi.10 <- function() assertThat(tanpi(-0.785398), identicalTo(0.799100239047378, tol = 0.000100))
test.tanpi.11 <- function() assertThat(tanpi(-1.5708), identicalTo(4.42151507004952, tol = 0.000100))
test.tanpi.12 <- function() assertThat(tanpi(-3.14159), identicalTo(-0.47667991524202, tol = 0.000100))
test.tanpi.13 <- function() assertThat(tanpi(-6.28319), identicalTo(-1.23376080666909, tol = 0.000100))
test.tanpi.14 <- function() assertThat(tanpi(0.01), identicalTo(0.0314262660433512, tol = 0.000100))
test.tanpi.15 <- function() assertThat(tanpi(0.1), identicalTo(0.324919696232906, tol = 0.000100))
test.tanpi.16 <- function() assertThat(tanpi(1), identicalTo(0))
test.tanpi.17 <- function() assertThat(tanpi(1.5), identicalTo(NaN))
test.tanpi.18 <- function() assertThat(tanpi(2), identicalTo(0))
test.tanpi.19 <- function() assertThat(tanpi(2.5), identicalTo(NaN))
test.tanpi.20 <- function() assertThat(tanpi(4), identicalTo(0))
test.tanpi.21 <- function() assertThat(tanpi(10), identicalTo(0))
test.tanpi.22 <- function() assertThat(tanpi(100), identicalTo(0))
test.tanpi.23 <- function() assertThat(tanpi(0.785398), identicalTo(-0.799100239047378, tol = 0.000100))
test.tanpi.24 <- function() assertThat(tanpi(1.5708), identicalTo(-4.42151507004952, tol = 0.000100))
test.tanpi.25 <- function() assertThat(tanpi(3.14159), identicalTo(0.47667991524202, tol = 0.000100))
test.tanpi.26 <- function() assertThat(tanpi(6.28319), identicalTo(1.23376080666909, tol = 0.000100))
test.tanpi.27 <- function() assertThat(tanpi(NULL), throwsError())
test.tanpi.28 <- function() assertThat(tanpi(c(0.01, 0.1, 1, 1.5)), identicalTo(c(0.0314262660433512, 0.324919696232906, 0, NaN), tol = 0.000100))
test.tanpi.29 <- function() assertThat(tanpi(integer(0)), identicalTo(numeric(0)))
test.tanpi.30 <- function() assertThat(tanpi(numeric(0)), identicalTo(numeric(0)))
test.tanpi.31 <- function() assertThat(tanpi(NaN), identicalTo(NaN))
test.tanpi.32 <- function() assertThat(tanpi(NA_real_), identicalTo(NA_real_))
test.tanpi.33 <- function() assertThat(tanpi(Inf), identicalTo(NaN))
test.tanpi.34 <- function() assertThat(tanpi(-Inf), identicalTo(NaN))
test.tanpi.35 <- function() assertThat(tanpi(c(1L, 4L)), identicalTo(c(0, 0)))
test.tanpi.36 <- function() assertThat(tanpi(structure(1, class = "foo")), identicalTo(41))
test.tanpi.37 <- function() assertThat(tanpi(structure(1, class = "bar")), identicalTo(44))
test.tanpi.38 <- function() assertThat(tanpi(structure(list("a"), class = "foo")), identicalTo(41))
test.tanpi.39 <- function() assertThat(tanpi(structure(list("b"), class = "bar")), identicalTo(44))
test.tanpi.40 <- function() assertThat(tanpi(structure(c(1, 2, 3), .Names = c("a", "b", "c"))), identicalTo(structure(c(0, 0, 0), .Names = c("a", "b", "c"))))
test.tanpi.41 <- function() assertThat(tanpi(structure(c(1, 2), .Names = c("x", ""))), identicalTo(structure(c(0, 0), .Names = c("x", ""))))
test.tanpi.42 <- function() assertThat(tanpi(structure(1:12, .Dim = 3:4)), identicalTo(structure(c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), .Dim = 3:4)))
test.tanpi.43 <- function() assertThat(tanpi(structure(0, rando.attr = 4L)), identicalTo(structure(0, rando.attr = 4L)))
test.tanpi.44 <- function() assertThat(tanpi(structure(0, class = "zinga")), identicalTo(structure(0, class = "zinga"))) |
ggsimrelplot <- function(obj, ncomp = min(obj$p, obj$n, 20), which = 1L:3L,
layout = NULL, print.cov = FALSE, use_population = TRUE) {
nx <- obj$p
ny <- ncol(obj$Y)
xticks <- 1:nx
if (is.null(which)) which <- 1L:3L
if (is.null(layout) & length(which) == 3) layout <- matrix(c(2, 1, 3, 1), 2)
plt1 <- expression({
beta <- `dimnames<-`(
obj$beta, list(c(1:nx), c(paste0("Y", 1:ny))))
beta_stk <- `names<-`(
reshape2::melt(beta), c("Predictor", "Response", "BetaCoef"))
plt1 <- ggplot(
beta_stk,
aes(Predictor, BetaCoef,
color = Response,
group = Response)) +
geom_hline(yintercept = 0,
color = "grey2",
linetype = 2) +
geom_line() +
geom_point() +
scale_x_continuous(breaks = xticks) +
labs(x = "Variable Number",
y = expression(paste("Regression Coefficients (", beta, ")"))) +
ggtitle("True Regression Coefficients") +
theme(legend.position = if (ny == 1) "none" else "bottom") +
scale_color_brewer(palette = 'Set1')
})
plt2 <- expression({
idx <- if (obj$type == "univariate") 1 else ny
covs <- obj$Sigma[-c(1:idx), 1:idx, drop = FALSE]
if (obj$type == "multivariate") {
covs <- obj$SigmaWZ[-c(1:idx), 1:idx, drop = FALSE]
}
covs.sc <- abs(covs)/max(abs(covs))
covs.dt <- as.data.frame(
cbind(
1:ncomp,
obj$lambda[1:ncomp],
covs.sc[1:ncomp, ]
), 1
)
names(covs.dt) <- c("comp", "lambda", paste0("W", 1:ny))
covs.stk <- reshape2::melt(
covs.dt, 1:2,
variable.name = "response",
value.name = "covariance"
)
pjtr <- position_dodge(0.5)
plt2 <- ggplot(
covs.stk,
aes(comp, covariance, color = response, group = response)) +
geom_bar(data = covs.dt,
aes(x = comp, y = lambda),
inherit.aes = FALSE,
stat = "identity",
fill = "lightgrey") +
geom_line(position = pjtr) +
geom_point(position = pjtr) +
labs(x = "Components",
y = "Covariance (absolute value)/ Eigenvalue") +
theme(legend.position = if (ny == 1) "none" else "bottom") +
ggtitle("Relevant Components Plot") +
scale_x_continuous(breaks = xticks) +
coord_cartesian(xlim = c(1, ncomp)) +
scale_color_brewer(ifelse(obj$type == "multivariate",
"Response Component", "Response"),
palette = 'Set1')
})
est.covs <- expression({
covs <- if (use_population) {
eigval <- obj$lambda
eigval.sc <- eigval/eigval[1]
covs <- switch(
obj$type,
univariate = {
m <- 1
rot <- obj$Rotation
covs <- obj$Sigma[-c(1:m), 1:m, drop = FALSE]
covs <- abs(rot %*% covs)
},
bivariate = {
m <- 2
covs <- obj$Sigma[-c(1:m), c(1:m), drop = FALSE]
covs <- abs(covs)
},
multivariate = abs(t(obj$SigmaYZ))
)
} else {
X <- scale(obj$X, center = TRUE, scale = FALSE)
Y <- scale(obj$Y, center = TRUE, scale = FALSE)
svdres <- svd(X)
eigval <- (svdres$d ^ 2)/(obj$n - 1)
eigval.sc <- eigval/eigval[1]
Z <- X %*% svdres$v
covs <- t(abs(cov(Y, Z)))
}
})
plt3 <- expression({
eval(est.covs)
covs.sc <- abs(covs)/max(abs(covs))
covs.dt <- as.data.frame(
cbind(1:ncomp,
eigval.sc[1:ncomp],
covs.sc[1:ncomp, ]),
1)
names(covs.dt) <- c("comp", "lambda", paste0("Y", 1:ny))
covs.stk <- reshape2::melt(
covs.dt, 1:2,
variable.name = "response",
value.name = "covariance"
)
pjtr <- position_dodge(0.5)
plt3 <- ggplot(
covs.stk,
aes(comp, covariance, color = response, group = response)) +
geom_bar(data = covs.dt,
aes(x = comp, y = lambda),
inherit.aes = FALSE,
stat = "identity",
fill = "lightgrey") +
geom_line(position = pjtr) +
geom_point(position = pjtr) +
labs(x = "Components",
y = "Covariance (absolute value)/ Eigenvalue") +
theme(legend.position = if (ny == 1) "none" else "bottom") +
ggtitle("Estimated relevant components plot") +
scale_x_continuous(breaks = xticks) +
coord_cartesian(xlim = c(1, ncomp)) +
scale_color_brewer("Response", palette = 'Set1')
})
est.covs.xy <- expression({
covs <- if (use_population) {
covs <- if(obj$type == "multivariate") {
abs(t(obj$SigmaYX))
} else {
m <- ifelse(obj$type == 'univariate', 1, 2)
p <- obj$p
covs <- obj$Sigma[-c(1:m), c(1:m), drop = FALSE]
covs <- abs(covs)
}
} else {
X <- scale(obj$X, center = TRUE, scale = FALSE)
Y <- scale(obj$Y, center = TRUE, scale = FALSE)
covs <- t(abs(cov(Y, X)))
}
})
plt4 <- expression({
eval(est.covs.xy)
covs.sc <- abs(covs)/max(abs(covs))
covs.dt <- as.data.frame(cbind(1:obj$p, covs.sc[1:ncomp, ]), 1)
names(covs.dt) <- c("predictors", paste0("Y", 1:ny))
covs.stk <- reshape2::melt(
covs.dt, 1,
variable.name = "response",
value.name = "covariance"
)
pjtr <- position_dodge(0.5)
plt4 <- ggplot(
covs.stk,
aes(predictors, covariance, color = response, group = response)) +
geom_line(position = pjtr) +
geom_point(position = pjtr) +
labs(x = "Predictors",
y = "abs(covariance) between Predictor & Response") +
theme(legend.position = if (ny == 1) "none" else "bottom") +
ggtitle("Estimated Covariance plot") +
scale_x_continuous(breaks = xticks) +
coord_cartesian(xlim = c(1, ncomp)) +
scale_color_brewer("Response", palette = 'Set1')
})
plt <- list(
TrueBeta = plt1,
RelComp = plt2,
EstRelComp = plt3,
EstCov = plt4
)
if (length(which) == 1) {
out <- eval(plt[[which]])
} else {
plts <- lapply(which, function(i) eval(plt[[i]]))
names(plts) <- names(plt)[which]
if (length(which) == 2 & is.null(layout)) layout <- matrix(c(1, 2), 2)
if (length(which) > length(layout)) layout <- matrix(1:length(which), length(which))
plts$layout_matrix <- layout
out <- do.call(gridExtra::grid.arrange, plts)
}
if (print.cov) {
eval(est.covs)
covs <- covs[1:min(ncomp, nx), ]
dimnames(covs) <- list(
paste0("Component", 1:min(ncomp, nx)),
paste0("Response", 1:ny)
)
attr(out, "covariance") <- covs
cat("Absolute values of estimated covariances\n")
print(covs)
}
if (length(which) == 1) return(out) else return(invisible(out))
} |
abplotUI = function(){
tagList(
fluidRow(
column(width = 12,
imgSelect("abp_plotbar"))
),
fluidRow(
br(),
column(width = 8,
tags$style(type = "text/css",
".shiny-output-error { visibility: hidden; }",
".shiny-output-error:before { visibility: hidden; }"),
plotOutput(outputId = "abp_plot")
),
column(width = 4,
hidden(selectInput(inputId = "abp_group", label = "Grouping Variable", choices=c('none'), width='100%')),
hidden(multiToggleButton(id = 'abp_stackfacet',
choices = c(stacked= 'Stacked', facetted='Facetted', joy='Joy'), selected = 'stacked')),
hidden(selectInput(inputId = "abp_xvar", label = "x-variable",
choices = c(), width='100%')),
hidden(checkboxInput(inputId = "abp_fill", label = "Fill", value = TRUE)),
hidden(checkboxInput(inputId = "abp_grid", label = "Grid", value = TRUE)),
hidden(tags$input(id = "abp_color", type = 'color', value = '
hidden(checkboxInput(inputId = "abp_linetype", label = "Varying line types", value = FALSE)),
hidden(sliderInput(inputId = "abp_bins", label = "Number of bins",
min = 5, max = 60, value = 30, step = 1, round = TRUE, ticks = FALSE, width='100%')),
hidden(sliderInput(inputId = "abp_trans", label = "Transparency",
min = 0.2, max = 1, value = 0.5, step = 0.05, ticks = FALSE, width='100%')),
hidden(checkboxInput(inputId = "abp_err", label = "Error Bars")),
hidden(checkboxInput(inputId = "abp_dodge", label = "Dodge")),
hidden(checkboxInput(inputId = "abp_marg", label = "Marginal plots")),
hidden(checkboxInput(inputId = "abp_fitlines", label = "Fitline(s)")),
hidden(textInput(inputId = "abp_main",
label = "Title", width='100%')),
fluidRow(
column(width = 6,
hidden(textInput(inputId = "abp_xlab",
label = "Label x-axis"))),
column(width = 6,
hidden(textInput(inputId = "abp_ylab",
label = "Label y-axis")))
),
conditionalPanel(
condition = "$('
tags$h4('Save plot'),
tagAppendAttributes(numericInput('abp_download_width', 'Width (cm)', value = 14, min = 2, max = 50,
width='6em'),style='display:inline-block;'),
tagAppendAttributes(numericInput('abp_download_height', 'Height (cm)', value=8, min = 2, max = 50,
width='6em'),style='display:inline-block;'),
downloadButton('abp_download', 'Download'))
)
))
}
|
library(testthat)
context("PeakSegFPOP")
library(PeakSegOptimal)
data.vec <- as.integer(c(1, 10, 14, 13))
fit <- PeakSegFPOP(data.vec, rep(1L, 4), 0)
test_that("no penalty is OK", {
best.cost <- min(fit$cost.mat[2,4])
mean.vec <- c(1, rep(37/3, 3))
exp.cost <- PoissonLoss(data.vec, mean.vec)
expect_equal(best.cost, exp.cost)
})
data.vec <- as.integer(c(1, 10, 14, 5))
weight.vec <- rep(1L, 4)
pdpa <- PeakSegPDPA(data.vec, weight.vec, 3L)
fpop <- PeakSegFPOP(data.vec, weight.vec, 0)
test_that("FPOP computes same model as PDPA", {
pdpa.cost <- min(pdpa$cost.mat)
fpop.cost <- min(fpop$cost.mat)
expect_equal(fpop.cost, pdpa.cost)
})
fit <- PeakSegFPOP(data.vec, rep(1L, 4), 1e6)
test_that("huge penalty recovers no changes", {
exp.mean <- mean(data.vec)
exp.mean.vec <- c(exp.mean, Inf, Inf, Inf)
expect_equal(fit$mean.vec, exp.mean.vec)
exp.loss <- PoissonLoss(data.vec, exp.mean)
expect_equal(min(fit$cost.mat), exp.loss)
})
data(H3K4me3_XJ_immune_chunk1)
H3K4me3_XJ_immune_chunk1$count <- H3K4me3_XJ_immune_chunk1$coverage
by.sample <- split(
H3K4me3_XJ_immune_chunk1, H3K4me3_XJ_immune_chunk1$sample.id)
one.name <- "McGill0004"
one <- by.sample[[one.name]]
one$bases <- with(one, chromEnd-chromStart)
wmean <- function(df){
with(df, sum(bases*count)/sum(bases))
}
max.peaks <- as.integer((nrow(one)-1)/2)
pdpa <- PeakSegPDPAchrom(one, max.peaks)
segs.by.peaks <- split(pdpa$segments, pdpa$segments$peaks)
test_that("PDPA segment means are feasible", {
for(peaks.str in names(segs.by.peaks)){
pdpa.segs <- segs.by.peaks[[peaks.str]]
rownames(pdpa.segs) <- NULL
sign.diff <- sign(diff(pdpa.segs$mean))*c(1,-1)
right.sign <- sign.diff %in% c(0, 1)
expect_true(all(right.sign))
}
})
some.models <- pdpa$modelSelection.decreasing
test_that("FPOP recovers the same models as PDPA", {
model.i <- 147
for(model.i in 1:nrow(some.models)){
model.row <- some.models[model.i,]
lambda <- with(model.row, if(max.lambda==Inf){
min.lambda+1
}else{
(min.lambda+max.lambda)/2
})
exp.segs <- segs.by.peaks[[paste(model.row$peaks)]]
rownames(exp.segs) <- NULL
fpop <- PeakSegFPOPchrom(one, lambda)
fpop.mean.vec <- with(fpop$segments, rep(mean, last-first+1))
pdpa.mean.vec <- with(exp.segs, rep(mean, last-first+1))
if(sum(abs(fpop.mean.vec-pdpa.mean.vec)) > 1e-6){
print(model.row)
print(sum(abs(fpop.mean.vec-pdpa.mean.vec)))
}
expect_equal(fpop.mean.vec, pdpa.mean.vec)
}
})
test_that("error for less than 3 data points", {
expect_error({
PeakSegFPOP(data.vec[1:2], weight.vec[1:2], 0)
})
expect_error({
PeakSegFPOPchrom(one[1:2,])
})
})
test_that("error for negative data", {
count <- as.integer(c(1, 2, -3))
expect_error({
PeakSegFPOP(count, penalty=0)
})
df <- data.frame(count,chromStart=0:2, chromEnd=1:3)
expect_error({
PeakSegFPOPchrom(df, 0)
})
}) |
crwPredict=function(object.crwFit, predTime=NULL, return.type="minimal", ...)
{
data <- object.crwFit$data
tn <- object.crwFit$Time.name
driftMod <- object.crwFit$random.drift
mov.mf <- object.crwFit$mov.mf
activity <- object.crwFit$activity
err.mfX <- object.crwFit$err.mfX
err.mfY <- object.crwFit$err.mfY
rho = object.crwFit$rho
par <- object.crwFit$par
n.errX <- object.crwFit$n.errX
n.errY <- object.crwFit$n.errY
n.mov <- object.crwFit$n.mov
fixPar = object.crwFit$fixPar
theta = object.crwFit$par[is.na(fixPar)]
return_posix <- ifelse((inherits(predTime,"POSIXct") | inherits(predTime, "character")) &
inherits(data[,tn],"POSIXct"),
TRUE, FALSE)
if(!return_posix) {
if(inherits(predTime,"numeric") && inherits(data[, tn], "POSIXct")) {
stop("predTime provided as numeric and original time data was POSIX!")
}
if(inherits(predTime,"POSIXct") && inherits(data[, tn], "numeric")) {
stop("predTime provided as POSIX and original data was numeric!")
}
}
if(!is.null(predTime)){
if(inherits(predTime,"character")) {
if(!inherits(data[,tn],"POSIXct")) stop("Character specification of predTime can only be used with POSIX times in the original data!")
t_int <- unlist(strsplit(predTime, " "))
if(t_int[2] %in% c("min","mins","hour","hours","day","days")) {
min_dt <- min(data[,tn],na.rm=TRUE)
max_dt <- max(data[,tn],na.rm=TRUE)
min_dt <- lubridate::ceiling_date(min_dt,t_int[2])
max_dt <- lubridate::floor_date(max_dt,t_int[2])
predTime <- seq(min_dt, max_dt, by = predTime)
} else {
stop("predTime not specified correctly. see documentation for seq.POSIXt")
}
}
if(inherits(predTime, "POSIXct")){
ts = attr(object.crwFit, "time.scale")
predTime = as.numeric(predTime)/ts
}
if(min(predTime) < min(data$TimeNum)) {
warning("Predictions times given before first observation!\nOnly those after first observation will be used.")
predTime <- predTime[predTime>=data$TimeNum]
}
origTime <- data$TimeNum
if (is.null(data$locType)) {
data$locType <- "o"
}
predData <- data.frame(predTime, "p")
names(predData) <- c("TimeNum", "locType")
data <- merge(data, predData,
by=c("TimeNum", "locType"), all=TRUE)
dups <- duplicated(data$TimeNum)
data <- data[!dups, ]
mov.mf <- as.matrix(expandPred(x=mov.mf, Time=origTime, predTime=predTime))
if (!is.null(activity)) activity <- as.matrix(expandPred(x=activity, Time=origTime, predTime=predTime))
if (!is.null(err.mfX)) err.mfX <- as.matrix(expandPred(x=err.mfX, Time=origTime, predTime=predTime))
if (!is.null(err.mfY)) err.mfY <- as.matrix(expandPred(x=err.mfY, Time=origTime, predTime=predTime))
if (!is.null(rho)) rho <- as.matrix(expandPred(x=rho, Time=origTime, predTime=predTime))
}
data$locType[data$TimeNum%in%predTime] <- 'p'
delta <- c(diff(data$TimeNum), 1)
y = as.matrix(data[,object.crwFit$coord])
noObs <- as.numeric(is.na(y[,1]) | is.na(y[,2]))
y[noObs==1,] = 0
N = nrow(y)
argslist = par2arglist(theta, fixPar, y, noObs, delta,
mov.mf, err.mfX, err.mfY, rho, activity,
n.errX, n.errY, n.mov, driftMod)
if (driftMod) {
out = CTCRWPREDICT_DRIFT(y, argslist$Hmat, argslist$b, argslist$b.drift, argslist$sig2,
argslist$sig2.drift, delta, noObs, argslist$active, argslist$a, argslist$P)
} else {
out=CTCRWPREDICT(y, argslist$Hmat, argslist$b, argslist$sig2, delta, noObs, argslist$active, argslist$a, argslist$P)
}
pred <- data.frame(t(out$pred))
if (driftMod) {
names(pred) <- c("mu.x", "theta.x", "gamma.x","mu.y", "theta.y", "gamma.y")
} else names(pred) <- c("mu.x", "nu.x", "mu.y","nu.y")
var <- zapsmall(out$predVar)
speed = sqrt(apply(as.matrix(pred[,2:(2+driftMod)]), 1, sum)^2 +
apply(as.matrix(pred[,(4+driftMod):(4+2*driftMod)]), 1, sum)^2)
obsFit <- data.frame(predObs.x=out$predObs[1,],
predObs.y=out$predObs[2,])
obsFit$outlier.chisq <- as.vector(out$chisq)
obsFit$naive.p.val <- 1 - pchisq(obsFit$outlier.chisq, 2)
out <- list(originalData=fillCols(data), alpha.hat=pred,
V.hat=var, speed=speed, loglik=out$ll)
if(return_posix){
out$originalData[,tn] = lubridate::as_datetime(out$originalData$TimeNum*ts)
} else out$originalData[,tn] = out$originalData$TimeNum
if (return.type == "flat") {
out <- fillCols(crawl::flatten(out))
attr(out, "flat") <- TRUE
attr(out, "coord") <- c(x=object.crwFit$coord[1], y=object.crwFit$coord[2])
attr(out, "random.drift") <- driftMod
attr(out, "activity.model") <- !is.null(object.crwFit$activity)
attr(out, "Time.name") <- tn
attr(out, "time.scale") = ts
attr(out,"epsg") <- attr(object.crwFit,"epsg")
attr(out,"proj4") <- attr(object.crwFit,"proj4")
} else if (return.type == "list") {
out <- append(out, list(fit.test=obsFit))
attr(out, "flat") <- FALSE
attr(out, "coord") <- c(x=object.crwFit$coord[1], y=object.crwFit$coord[2])
attr(out, "random.drift") <- driftMod
attr(out, "activity.model") <- !is.null(object.crwFit$activity)
attr(out, "Time.name") <- tn
attr(out, "time.scale") = ts
attr(out,"epsg") <- attr(object.crwFit,"epsg")
attr(out,"proj4") <- attr(object.crwFit,"proj4")
} else if (return.type == "minimal") {
out <- fillCols(out$originalData)
out <- cbind(out, pred)
attr(out, "flat") <- TRUE
attr(out, "coord") <- c(x=object.crwFit$coord[1], y=object.crwFit$coord[2])
attr(out, "random.drift") <- driftMod
attr(out, "activity.model") <- !is.null(object.crwFit$activity)
attr(out, "Time.name") <- tn
attr(out, "time.scale") = ts
attr(out,"epsg") <- attr(object.crwFit,"epsg")
attr(out,"proj4") <- attr(object.crwFit,"proj4")
}
class(out) <- c(class(out),"crwPredict")
return(out)
} |
vmd_colors <- function(n=33, picker=FALSE, ...){
red <- c(0, 1, 0.35, 1, 1, 0.5, 0.6, 0, 1, 1,
0.25, 0.65, 0.5, 0.9, 0.5, 0.5, 0, 0.88, 0.55, 0,
0, 0, 0, 0.02, 0.01, 0.27, 0.45, 0.9, 1, 0.98,
0.81, 0.89, 0.96)
green <- c(0, 0, 0.35, 0.50, 1, 0.5, 0.6, 1, 1, 0.6,
0.75, 0, 0.9, 0.4, 0.3, 0.5, 0, 0.97, 0.9, 0.9,
0.9, 0.88, 0.76, 0.38, 0.04, 0, 0, 0, 0, 0,
0, 0.35, 0.72)
blue <- c(1, 0, 0.35, 0, 0, 0.2, 0.6, 0, 1, 0.6,
0.75, 0.65, 0.4, 0.7, 0, 0.75, 0, 0.02, 0.02, 0.04,
0.5, 1, 1, 0.67, 0.93, 0.98, 0.9, 0.9, 0.66, 0.23,
0, 0, 0)
max.col <- length(red)
inds <- (1:n)
if( n > max.col ) {
inds <- inds %% max.col
inds[inds==0] <- max.col
warning( paste("Colors will be recycled: input 'n' >", max.col) )
}
cols <- rgb(red[inds], green[inds], blue[inds], ...)
names(cols) <- c(1:n)
if(picker) {
if(n > 50) { warning("Chart will likely be crowded, set n=33 to see all colors") }
pie(rep(1, length(cols)), labels=paste(inds, cols), col=cols, cex=0.75)
}
return(cols)
} |
extract_fond_leaflet_joignantes <-
function(map)
{
idx_carte <- NULL
idx_fleche <- NULL
idx_titre <- NULL
idx_source <- NULL
idx_legende <- NULL
for(i in 1:length(map$x$calls))
{
if(map$x$calls[[i]]$method %in% "addPolygons")
{
if(any(map$x$calls[[i]]$args[3][[1]] %in% c("carte_joignantes_init","carte_joignantes"))) idx_carte <- c(idx_carte,i)
}
if(map$x$calls[[i]]$method %in% "addControl")
{
if(map$x$calls[[i]]$args[4]=="map-title") idx_titre <- i
if(map$x$calls[[i]]$args[4]=="map-source") idx_source <- i
}
if(map$x$calls[[i]]$method %in% "addPolygons")
{
if(any(map$x$calls[[i]]$args[3][[1]] %in% c("legende_joignantes"))) idx_legende <- c(idx_legende,i)
}
if(!is.null(idx_legende))
{
if(map$x$calls[[i]]$method %in% "addMarkers")
{
if(any(map$x$calls[[i]]$args[5][[1]] %in% c("legende_joignantes"))) idx_legende <- c(idx_legende,i)
}
}
}
if(is.null(idx_legende))
{
return(NULL)
}else
{
idx_fleche <- idx_carte[length(idx_carte)]
idx_carte <- idx_carte[-length(idx_carte)]
var_flux <- map$x$calls[[idx_fleche]]$args[[2]]$var_flux
code_epsg <- map$x$calls[[idx_fleche]]$args[[2]]$code_epsg
emprise <- map$x$calls[[idx_fleche]]$args[[2]]$emprise
max_var <- map$x$calls[[idx_fleche]]$args[[2]]$max_var
list_fonds <- list()
nom_fonds <- c()
l <- 1
for(i in 1:length(idx_carte))
{
fond <- map$x$calls[[idx_carte[i]]]$args[[2]][1][[1]]
fond <- st_transform(fond,crs=as.numeric(code_epsg))
list_fonds[[l]] <- fond
rm(fond)
nom_fonds <- c(nom_fonds,map$x$calls[[idx_carte[i]]]$args[[2]]$nom_fond)
l <- l+1
}
if(!is.null(idx_fleche))
{
fond <- map$x$calls[[idx_fleche]]$args[[2]]$analyse_WGS84
fond <- st_transform(fond,crs=as.numeric(code_epsg))
list_fonds[[l]] <- fond
rm(fond)
nom_fonds <- c(nom_fonds,map$x$calls[[idx_fleche]]$args[[2]]$nom_fond)
l <- l+1
}
if(!is.null(idx_titre))
{
titre <- substr(map$x$calls[[idx_titre]]$args[1],505,nchar(map$x$calls[[idx_titre]]$args[1])-7)
}else
{
titre <- ""
}
if(!is.null(idx_source))
{
source <- substr(map$x$calls[[idx_source]]$args[1],379,nchar(map$x$calls[[idx_source]]$args[1])-7)
}else
{
source <- ""
}
if(!is.null(idx_legende))
{
large <- map$x$calls[[idx_fleche]]$args[[2]]$distance
long <- large * 1.5
gf <- st_sf(geometry=st_sfc(st_polygon(list(as.matrix(map$x$calls[[idx_legende[2]]]$args[[1]][[1]][[1]][[1]]))),crs=4326))
x <- st_bbox(gf)$xmin
y <- st_bbox(gf)$ymin
flux_leg_pl <- fleche_legende(x,y,long,large,max_var,code_epsg)[[5]]
flux_leg_pl <- cbind(ETI_VAL=c(max_var,max_var/3),flux_leg_pl)
list_fonds[[l]] <- flux_leg_pl
nom_fonds <- c(nom_fonds,map$x$calls[[idx_legende[[2]]]]$args[[2]]$nom_fond)
l <- l+1
}
colFleche <- map$x$calls[[idx_fleche]]$args[4][[1]]$fillColor
colBorder <- map$x$calls[[idx_fleche]]$args[4][[1]]$color
return(list(list_fonds,nom_fonds,titre,source,colFleche,colBorder,emprise))
}
} |
segments.greffe <-
function(cple, bord)
{
ind <- which(bord$id == cple[1] | bord$id == cple[2])
X1 <- bord$X1[ind]
Y1 <- bord$Y1[ind]
X2 <- bord$X2[ind]
Y2 <- bord$Y2[ind]
ind.cl <- c(length(which(bord$id == cple[1])), length(ind))
grf <- rep(0, 4*length(which(bord$id == cple[1]))*length(which(bord$id == cple[2])))
res <- .C("sgmtsGrf",
as.integer(ind.cl), as.double(X1), as.double(Y1), as.double(X2), as.double(Y2),
as.double(grf)
)
grf <- t(matrix(res[[6]], nrow=4))
grf <- grf[which(grf[,1]!=grf[,3] & grf[,2]!=grf[,4]), ]
bord$id[ind] <- rep(max(bord$id)+2, length(ind))
bord <- rbind.data.frame(bord)[c(which(!(1:nrow(bord)%in%ind)), ind),]
return(list(grf=grf, bord=bord))
} |
simulate_trials <- function(selector_factory, num_sims, true_prob_tox,
true_prob_eff = NULL, ...) {
sim_func <- simulation_function(selector_factory)
if(is.null(true_prob_eff)) {
l <- lapply(
1:num_sims,
function(x) sim_func(selector_factory, true_prob_tox, ...)
)
} else {
l <- lapply(
1:num_sims,
function(x) sim_func(selector_factory, true_prob_tox,
true_prob_eff = true_prob_eff, ...)
)
}
simulations(fits = l, true_prob_tox = true_prob_tox,
true_prob_eff = true_prob_eff, ...)
} |
removeDatabase <- function(pps, index=NULL) {
if(is.null(index)) {
choices <- pps@db
if(length(choices) > 20) {
warning('Only showing first 20 databases.')
choices <- choices[1:20]
}
index <- menu(title = 'Choose a database to remove:',
choices = choices)
if(index==0) return(pps)
}
if(max(index) > length(pps@db)) warning('Index too large, no database to remove.')
pps@db <- pps@db[-index]
pps
} |
is_one_dim <- function(x)
{
one_dim = TRUE
if (lacks_dim(x)) {
if (is.list(x)) one_dim = FALSE
} else {
if (dim(x)[1L] > 1 && dim(x)[2L] > 1)
one_dim = FALSE
}
one_dim
} |
require(testthat)
context("read ESDFL")
options(width = 500)
options(useFancyQuotes=FALSE)
source("REF-2-esdfl.R")
test_that("read ESDFL",{
sdf <<- readNAEP(system.file("extdata/data", "M36NT2PM.dat", package = "NAEPprimer"))
sdfA <<- subset(sdf, scrpsu %in% c(5,45,56))
sdfB <- subset(sdf, scrpsu %in% c(75,76,78))
sdfC <- subset(sdf, scrpsu %in% 100:200)
sdfD <<- subset(sdf, scrpsu %in% 201:300)
sdfB$year <- 2002
sdfC$year <- 2003
sdfB <<- sdfB
sdfC <<- sdfC
sdfl <<- edsurvey.data.frame.list(list(sdfA, sdfB, sdfC, sdfD),
labels=c("A locations",
"B locations",
"C locations",
"D locations"))
expect_is(sdfl, "edsurvey.data.frame.list")
})
i <- "invalid level: outside"
context("ESDFL subset and scope")
test_that("ESDFL subset and scope", {
yes <- "Yes"
g1 <- subset(sdfl, ell3 == "Yes")
g2 <- subset(sdfl, ell3 == yes)
expect_equal(dim(g1), dim(g2))
i <- "invalid level: inside"
ssfun <- function(data) {
i <- "Yes"
subset(data, ell3 == i)
}
g3 <- ssfun(sdfl)
expect_equal(dim(g1), dim(g3))
})
context("ESDFL achievementLevels")
test_that("ESDFL achievementLevels", {
expect_known_value(test8 <- achievementLevels(data=sdfl), file="aLevels_test8.rds", update=FALSE)
})
context("ESDFL cor")
test_that("ESDFL cor", {
c1 <- cor.sdf("b017451", "b003501", sdfA,
method="Pearson",
weightVar="origwt")
c3 <- cor.sdf("b017451", "b003501", sdfC,
method="Pearson",
weightVar="origwt")
c1234 <- cor.sdf("b017451", "b003501", sdfl,
method="Pearson",
weightVar="origwt")
expect_equal(c1,c1234[[1]])
expect_equal(c3,c1234[[3]])
})
skip_on_cran()
context("ESDFL edsurveyTable")
test_that("ESDFL edsurveyTable",{
et1 <- edsurveyTable(composite ~ b017451 + dsex, sdfl)
et1c <- withr::with_options(list(digits=7), capture.output(et1))
expect_equal(et1c, et1REF)
etB <- edsurveyTable(composite ~ b017451+ dsex, sdfB)
row.names(et1$data) <- paste(rep(LETTERS[1:4], each=nrow(etB$data)), rep(1:nrow(etB$data), 4))
row.names(etB$data) <- paste("B", 1:nrow(etB$data))
ss <- subset(et1$data, labels=="B locations")[,2:ncol(et1$data)]
for(i in 1:ncol(ss)) {
mostattributes(ss[,i]) <- attributes(et1$data[,i+1])
}
coetB <- withr::with_options(list(digits=7), capture.output(etB$data))
coss <- withr::with_options(list(digits=7), capture.output(ss))
expect_equal(coetB, coss)
})
context("ESDFL edsurveyTable error handling")
test_that("ESDFL error handling",{
skip_on_cran()
expect_warning(edsurveyTable(composite ~ b017451, sdfl,
returnMeans=TRUE, returnSepct=FALSE,
pctAggregationLevel=6),
paste0("Warnings from datasets \"A locations\""))
sdfE <- "String"
sdfl_error <- edsurvey.data.frame.list(list(sdfE, sdfB, sdfC, sdfE),
labels=c("first E locations",
"B locations",
"C locations",
"second E locations"))
expect_warning(edsurveyTable(composite ~ b017451,
sdfl_error, returnMeans=FALSE,
returnSepct=FALSE),
"E locations")
suppressWarnings(et2 <- edsurveyTable(composite ~ b017451, sdfl_error, returnMeans=FALSE, returnSepct=FALSE))
withr::with_options(list(digits=0),
et2c <- capture.output(et2)
)
expect_message(expect_error(g1 <- gap("composite", sdfl_error, groupA= dsex=="Male"), "reference"), "E locations")
sdfl_errorB <- edsurvey.data.frame.list(list(sdfA, sdfB, sdfE, sdfC),
labels=c("A locations",
"B locations",
"E locations",
"C locations"))
expect_message(g2 <- gap("composite", sdfl_errorB, groupA= dsex=="Male"),
"An error occurred while working on a dataset \"E locations\". The results from that dataset will be excluded. Error message:")
g3 <- gap("composite", sdfl, groupA= dsex=="Male")
expect_equivalent(g2$results[2,], g3$results[2,])
expect_equal(et2c, et2REF)
})
context("ESDFL gap")
test_that("ESDFL gap",{
skip_on_cran()
g1 <- gap("composite", sdfl, dsex=="Male", dsex=="Female", returnSimpleDoF=TRUE)
mle <- "Male"
g1p <- gap("composite", sdfl, dsex==mle, dsex=="Female", returnSimpleDoF=TRUE)
expect_equal(g1$results, g1p$results)
g2 <- gap("composite", sdfC, dsex=="Male", dsex=="Female", returnSimpleDoF=TRUE)
mnames <- names(g2$results)
mnames <- mnames[mnames %in% names(g1$results)]
expect_equal(unlist(g2$results[mnames]), unlist(g1$results[3,mnames]))
expect_known_value(g1, "gap_esdfl_mean.rds", update=FALSE)
expect_known_value(g_pct <- gap("composite", sdfl, dsex=="Male", percentiles=c(2,50), pctMethod="symmetric"), "gap_esdfl_pct.rds", update=FALSE)
expect_known_value(g_al <- gap("composite", sdfl, dsex=="Male", achievementLevel="Proficient"), "gap_esdfl_al.rds", update=FALSE)
expect_known_value(g_per <- gap("dsex", sdfl, dsex=="Male", targetLevel="Male"), "gap_esdfl_perct.rds", update=FALSE)
})
context("ESDFL helper functions")
test_that("ESDFL helper functions",{
d1 <- dim(sdfl)
expect_equal(d1$nrow[1], nrow(sdfA))
expect_equal(d1$ncol[3], ncol(sdfC))
pv1 <- getPlausibleValue("composite", sdfl)
expect_equal(pv1[[2]], getPlausibleValue("composite", sdfB))
wr1 <- getWeightJkReplicates("origwt", sdfl)
expect_equal(wr1[[4]], getWeightJkReplicates("origwt", sdfD))
hpv1 <- hasPlausibleValue("algebra", sdfl)
expect_equal(hpv1[[1]], hasPlausibleValue("algebra", sdfA))
hpv2 <- hasPlausibleValue("dsex", sdfl)
expect_equal(hpv2[[2]], hasPlausibleValue("dsex", sdfB))
iw1 <- isWeight("origwt", sdfl)
expect_equal(iw1[[3]], TRUE)
iw2 <- isWeight("composite", sdfl)
expect_equal(iw2[[4]], FALSE)
l1 <- levelsSDF("sdracem", sdfl)
expect_equal(l1[[1]], levelsSDF("sdracem", sdfA))
l2 <- levelsSDF("dsex", sdfl)
expect_equal(l2[[2]], levelsSDF("dsex", sdfB))
n1 <- colnames(sdfl)
expect_equal(n1[[3]], colnames(sdfC))
spvo1 <- capture.output(showPlausibleValues(sdfl))
spvoD <- capture.output(showPlausibleValues(sdfD))
expect_equal(rev(spvo1)[1:length(spvoD)], rev(spvoD))
sw1 <- capture.output(showWeights(sdfl, verbose=TRUE))
swA <- capture.output(showWeights(sdfA, verbose=TRUE))
swB <- capture.output(showWeights(sdfB, verbose=TRUE))
swC <- capture.output(showWeights(sdfC, verbose=TRUE))
swD <- capture.output(showWeights(sdfD, verbose=TRUE))
expect_equal(sw1, c(swA, swB, swC, swD))
})
context("ESDFL cor")
test_that("ESDFL cor", {
skip_on_cran()
c1 <- cor.sdf("b017451", "b003501", sdfA,
method="Pearson",
weightVar="origwt")
c3 <- cor.sdf("b017451", "b003501", sdfC,
method="Pearson",
weightVar="origwt")
c1234 <- cor.sdf("b017451", "b003501", sdfl,
method="Pearson",
weightVar="origwt")
expect_equal(c1,c1234[[1]])
expect_equal(c3,c1234[[3]])
})
context("ESDFL subset and print")
test_that("ESDFL subset and print",{
sdfl2 <- subset(sdfl, dsex=="Male")
expect_equal(capture.output(print(sdfl2)), printREF)
d1 <- dim(sdfl2)
expect_equal(d1$nrow[1], nrow(subset(sdfA, dsex=="Male")))
expect_equal(d1$ncol[3], ncol(subset(sdfC, dsex=="Female")))
expect_equal(d1, dim(subset(sdfl, eval("dsex == \"Male\""), inside = TRUE)))
expect_warning(sdfl_e <- subset(sdfl, dsex1 == "Male"))
expect_equal(sdfl_e, NULL)
sdfE <- "String"
sdfl_error <- edsurvey.data.frame.list(list(sdfE, sdfB, sdfC, sdfE),
labels=c("first E locations",
"B locations",
"C locations",
"second E locations"))
sdfl_ref <- subset(edsurvey.data.frame.list(list(sdfB,sdfC), labels = c("B locations","C locations")), dsex == "Male")
expect_warning(sdfl_error_subset <- subset(sdfl_error, dsex == 'Male'))
expect_equal(dim(sdfl_error_subset), dim(sdfl_ref))
expect_equal(sdfl_error_subset$covs, sdfl_ref$covs)
})
context("ESDFL lm.sdf")
test_that("ESDFL lm.sdf",{
et1 <- lm.sdf(composite ~ b017451 + dsex, sdfl, jrrIMax=Inf)
et1D <- lm.sdf(composite ~ b017451 + dsex, sdfD, jrrIMax=Inf)
et1s <- capture.output(summary(et1))
et1Ds <- capture.output(summary(et1D))
expect_equal(rev(et1s)[1:length(et1Ds)], rev(et1Ds))
expect_equal(coef(et1)[,4], coef(et1D))
et1p <- capture.output(print(et1))
et1Dp <- capture.output(print(et1D))
expect_equal(rev(et1p)[1:2], rev(et1Dp))
})
context("ESDFL percentile")
test_that("ESDFL percentile",{
expect_known_value(pct3 <- percentile("composite", 50, sdfl, pctMethod = 'unbiased'), "pct3.rds", update=FALSE)
pct3C <- percentile("composite", 50, sdfC, pctMethod = 'unbiased')
expect_equal(unlist(pct3C[,,drop=TRUE]), unlist(pct3[3,names(pct3C),drop=TRUE]))
})
context("ESDFL same survey")
test_that("ESDFL same survey",{
expect_true(!EdSurvey:::sameSurvey(sdfA, sdfB))
expect_true(EdSurvey:::sameSurvey(sdf, sdfA))
expect_true(EdSurvey:::sameSurvey(sdfl[[1]][[4]], sdfD))
})
context("ESDFL append")
test_that("ESDFL append", {
sdfl1a <- edsurvey.data.frame.list(list(sdfA, sdfB),
labels=c("A locations",
"B locations"))
sdfl1b <- edsurvey.data.frame.list(list(sdfC, sdfD),
labels=c("C locations",
"D locations"))
sdfl1a_rev<- edsurvey.data.frame.list(list(sdfB, sdfA),
labels=c("B locations",
"A locations"))
sdfl1b_rev <- edsurvey.data.frame.list(list(sdfD, sdfC),
labels=c("D locations",
"C locations"))
sdfl2 <- edsurvey.data.frame.list(list(sdfA, sdfB, sdfC, sdfD),
labels=c("A locations",
"B locations",
"C locations",
"D locations"))
sdfl2_rev <- edsurvey.data.frame.list(list(sdfD, sdfC, sdfB, sdfA),
labels=c("D locations",
"C locations",
"B locations",
"A locations"))
sdfl3 <- append.edsurvey.data.frame.list(
append.edsurvey.data.frame.list(sdfl1a, sdfC, labelsB = "C locations"),
sdfD,
labelsB = "D locations")
sdfl4 <- append.edsurvey.data.frame.list(sdfl1a, sdfl1b)
sdfl5 <- append.edsurvey.data.frame.list(sdfl1b_rev, sdfl1a_rev)
expect_true(identical(sdfl2, sdfl3))
expect_true(identical(sdfl2, sdfl4))
expect_true(identical(sdfl2_rev, sdfl5))
}) |
harvard.dir <- '//mdabam1/bioinfo/Public/prostate-meta/Harvard'
harvard.data <- read.table(file.path(harvard.dir,
'HarvardUpdatedDataAndAnnotation.txt'),
header=TRUE, sep='\t', row.names=2)
harvard.genes <- harvard.data[, 2:3]
harvard.data <- harvard.data[, 4:ncol(harvard.data)]
harvard.clin <- read.table(file.path(harvard.dir, 'Harvard-clinical-new.txt'),
header=TRUE, sep='\t', row.names=NULL,
comment='', quote='')
dimnames(harvard.clin)[[1]] <- as.character(harvard.clin$Sample.ID)
tumor <- dimnames(harvard.data)[[2]][51:102]
harvard.info <- data.frame(sample=factor(dimnames(harvard.data)[[2]]),
status=factor(rep(c('normal', 'cancer'), times=c(50,52))),
gleason=factor(paste('G',
c(rep(0, 50),
as.character(harvard.clin[tumor, 'GS'])),
sep='')))
rm(tumor)
plot(t(harvard.data[1,]))
harvard.tr2 <- TailRankTest(logb(harvard.data, 2),
harvard.info$status=='normal',
direction='two')
summary(harvard.tr2)
x <- gene.info$Cluster.ID[as.logical(tr2)]
y1 <- as.character(gene.info$Cluster.ID)
z1 <- is.element(y1,x) & y1 != ''
y <- as.character(harvard.genes[,1])
z <- is.element(y, x) & y != ''
w <- harvard.genes[as.logical(harvard.tr2), 1]
z2 <- is.element(y1,w) & y1 != '' |
svc <- paws::mturk() |
hasFileSuffix = function(filepath, suffix)
{
if (substr(suffix,1,1) != '.') suffix = paste0('.', suffix)
filepath = tolower(filepath)
suffix = tolower(suffix)
return(suffix == substring(filepath, first = nchar(filepath) - nchar(suffix) + 1))
}
removeSuffix = function(filepath)
{
gsub("(.*)\\..*$", "\\1", filepath)
}
longestCommonPrefix = function(strings) {
strings = as.character(strings)
if (length(strings) == 0) return("")
if (length(strings) == 1) return(strings[1])
min_len = min(sapply(strings, nchar))
if (min_len == 0) return ("")
i = 2
for(i in 1:(min_len+1))
{
if (i > min_len) next;
chars = substring(strings, i, i)
if (length(unique(chars)) > 1) {
break;
}
}
if (i==1) return("")
return(substr(strings[1], 1, i-1))
}
longestCommonSuffix = function(strings)
{
strings_rev = sapply(lapply(strsplit(strings, NULL), rev), paste, collapse="")
r = longestCommonPrefix(strings_rev)
r_rev = sapply(lapply(strsplit(r, NULL), rev), paste, collapse="")
return (r_rev)
}
delLCP <- function(x, min_out_length = 0, add_dots = FALSE)
{
x = as.character(x)
lcp = nchar(longestCommonPrefix( x ))
if (min_out_length > 0)
{
minLen = min(nchar(x))
if (lcp >= minLen - min_out_length)
{
lcp = max(minLen - min_out_length, 0)
if (lcp <= 2 & add_dots) return(x)
}
}
x = sapply(x, substring, lcp+1)
if (add_dots) x = paste0("..", x)
return (x)
}
delLCS <- function(x)
{
lcs = nchar(longestCommonSuffix( x ))
x = sapply(x, function(v) substr(v, 1, nchar(v)-lcs))
return (x)
}
lcpCount <- function(x)
{
lcp = nchar(longestCommonPrefix( x ))
return (lcp)
}
lcsCount <- function(x)
{
lcs = nchar(longestCommonSuffix( x ))
return(lcs)
}
LCS <- function(s1, s2)
{
if (nchar(s1)==0 || nchar(s2)==0) return("")
v1 <- unlist(strsplit(s1,split=""))
v2 <- unlist(strsplit(s2,split=""))
num <- matrix(0, nchar(s1), nchar(s2))
maxlen <- 0
pstart = 0
for (i in 1:nchar(s1)) {
for (j in 1:nchar(s2)) {
if (v1[i] == v2[j]) {
if ((i==1) || (j==1)) {
num[i,j] <- 1
}
else {
num[i,j] <- 1+num[i-1,j-1]
}
if (num[i,j] > maxlen) {
maxlen <- num[i,j]
pstart = i-maxlen+1
}
}
}
}
return (substr(s1, pstart, pstart+maxlen-1))
}
LCSn = function(strings, min_LCS_length = 0)
{
if (min(nchar(strings)) < min_LCS_length) return("");
if (length(strings) <= 1) return (strings)
idx_ref = which(nchar(strings)==min(nchar(strings)))[1]
strings_other = strings[-idx_ref]
candidates = unique(sapply(strings_other, LCS, strings[idx_ref]))
candidates
if (length(candidates) == 1)
{
if (nchar(candidates[1]) < min_LCS_length) return("") else return (candidates[1])
}
cand_short = candidates[nchar(candidates) == min(nchar(candidates))]
solutions = unique(sapply(cand_short, function(cand) LCSn(c(cand, strings_other))))
idx_sol = which(nchar(solutions)==max(nchar(solutions)))[1];
return (solutions[idx_sol])
}
simplifyNames = function(strings, infix_iterations = 2, min_LCS_length = 7, min_out_length = 7)
{
if (min_LCS_length<6) stop( "simplifyNames(): param 'min_LCS_length' must be 6 at least.")
for (it in 1:infix_iterations)
{
lcs = LCSn(strings, min_LCS_length=min_LCS_length)
if (nchar(lcs)==0) return (strings)
strings_i = sub(paste0("(.*)", gsub("([.|()\\^{}+$*?]|\\[|\\])", "\\\\\\1", lcs), "(.*)"),
paste0("\\1"
, ifelse(substring(lcs,1,2) == "..", "", substring(lcs,1,2))
, ".."
, ifelse(substring(lcs, nchar(lcs)-1) == "..", "", substring(lcs, nchar(lcs)-1))
, "\\2"),
strings)
if (min(nchar(strings_i)) < min_out_length) return(strings)
strings = strings_i
}
return (strings)
}
shortenStrings = function(x, max_len = 20, verbose = TRUE, allow_duplicates = FALSE)
{
if (any(duplicated(x)) & !allow_duplicates) stop("Duplicated input given to 'shortenStrings'!\n ", paste(x, collapse="\n "))
idx = nchar(x) > max_len
xr = x
xr[idx] = paste0(substr(x[idx], 1, max_len-2), "..")
if (!allow_duplicates & any(duplicated(xr)))
{
xr[idx] = paste0("..", sapply(x[idx], function(s) substr(s, nchar(s)-max_len+2, nchar(s))))
if (any(duplicated(xr)))
{
warning("Duplicated output produced by 'shortenStrings'!\n ", paste(xr, collapse="\n "), "\nPlease rename your items (make them shorter and less similar)")
return(x)
}
}
if (verbose & any(idx))
{
cat("The following labels will be shortened to ease plotting:\n")
cat(paste0(" ", paste(x[idx], collapse="\n ")))
cat("\n")
}
return (xr)
}
supCount <- function(x, prefix_l=1)
{
max_length = max(nchar(x))
while (prefix_l < max_length)
{
dups = duplicated(sapply(x, substr, 1, prefix_l), NA)
if (sum(dups)==0)
{
break;
}
prefix_l = prefix_l + 1
}
return (prefix_l)
}
correctSetSize = function(item_count, initial_set_size)
{
blocks = seq(from = 1, to = item_count, by = initial_set_size)
blockcount = length(blocks)
lastblocksize = item_count - tail(blocks, n = 1) + 1
if (lastblocksize < initial_set_size * 0.5 & blockcount > 1)
{
blockcount = blockcount - 1
}
set_size = ceiling(item_count / blockcount)
return (set_size)
}
byX <- function(data, indices, subset_size = 5, FUN, sort_indices = TRUE, ...)
{
stopifnot(subset_size > 0)
stopifnot(nrow(data) == length(indices))
groups = unique(indices)
if (sort_indices)
{
groups = sort(groups)
}
blocks = seq(from = 1, to = length(groups), by = subset_size)
result = lapply(blocks, function(x) {
range = x:(min(x+subset_size-1, length(groups)))
lns = indices %in% groups[range];
subset = droplevels(data[lns, , drop = FALSE])
rownames(subset) = rownames(data)[lns]
r = FUN(subset, ...)
flush.console()
return (r)
})
return (result)
}
byXflex <- function(data, indices, subset_size = 5, FUN, sort_indices = TRUE, ...)
{
stopifnot(subset_size>0)
groups = unique(indices)
subset_size = correctSetSize(length(groups), subset_size)
return (byX(data, indices, subset_size, FUN, sort_indices, ...))
}
assignBlocks = function(values, set_size = 5, sort_values = TRUE)
{
groups = unique(values)
set_size = correctSetSize(length(groups), set_size)
if (sort_values)
{
groups = sort(groups)
}
blocks = seq(from=1, to=length(groups), by=set_size)
result = rep(NA, length(values))
for (x in 1:length(blocks))
{
range = blocks[x]:(min(blocks[x]+set_size-1, length(groups)))
lns = values %in% groups[range];
result[lns] = x
}
return (result)
}
grepv = function(reg, data, ...)
{
return (grep(reg, data, value = TRUE, ...))
}
pastet = function(...)
{
paste(..., sep="\t")
}
pasten = function(...)
{
paste(..., sep="\n")
}
CV = function(x){sd(x) / mean(x)}
RSD = function(x){CV(x)*100}
del0 = function(x)
{
x[x==0] = NA
return(x)
}
repEach = function(x, n)
{
stopifnot(length(x) == length(n))
r = unlist(
sapply(1:length(x), function(i) rep(x[i], each=n[i]))
)
return(r)
}
getMaxima = function(x, thresh_rel = 0.2)
{
pos = rep(FALSE, length(x))
thresh_abs = max(x, na.rm = TRUE) * thresh_rel
x_noNA = na.omit(x)
if (length(x_noNA) == 0) return(pos)
last = x_noNA[1]
i = which(last == x)[1]
last_nonNA_i = i
up = TRUE
while (i < length(x))
{
i = i + 1;
if (is.na(x[i])) next;
if (last < x[i] && !up)
{
up = !up
} else if (last > x[i] && up)
{
up = !up
if (x[last_nonNA_i]>=thresh_abs) pos[last_nonNA_i] = TRUE
}
last = x[i]
last_nonNA_i = i
}
if (up) pos[last_nonNA_i] = TRUE
return (pos)
}
mosaicize = function(data)
{
stopifnot(ncol(data)==2)
lev_var1 = length(unique(data[, 1]))
ct.data = as.data.frame(prop.table(table(data[, 1], data[, 2])))
ct.data$Margin_var1 = prop.table(table(data[, 1]))
ct.data$Var2_height = ct.data$Freq / ct.data$Margin_var1
ct.data$Var1_center = c(0, cumsum(ct.data$Margin_var1)[(1:lev_var1) -1]) + ct.data$Margin_var1 / 2
return (ct.data)
}
`%+%` = function(a, b)
{
return (paste(a, b, sep=""))
}
renameFile = function(f_names, mapping)
{
if (all(f_names %in% mapping$from)) {
f_new = mapping$to[match(f_names, mapping$from)]
f_new = factor(f_new, levels=mapping$to)
} else if (all(f_names %in% mapping$to)) {
f_new = mapping$from[match(f_names, mapping$to)]
f_new = factor(f_new, levels=mapping$from)
} else {
stop("Error in renameFile: filenames cannot be found in mapping!")
}
return (f_new)
}
appendEnv = function(env_name, v, v_name = NULL)
{
e = eval.parent(as.name(env_name), n=3)
e$.counter <- e$.counter + 1
e[[sprintf("%04d",e$.counter)]] <- v
return(TRUE)
}
thinOut = function(data, filterColname, binsize)
{
nstart = nrow(data)
data = data[!duplicated(data[, filterColname]), ]
if (is.unsorted(data[, filterColname])) data = data[order(data[, filterColname]), ]
local_deltas = c(0, diff(data[, filterColname]))
ld_cs = cumsum(local_deltas)
data = data[!duplicated(round(ld_cs / binsize)),]
return(data)
}
thinOutBatch = function(data, filterColname, batchColname, binCount = 1000)
{
binsize = (max(data[, filterColname], na.rm=TRUE) - min(data[, filterColname], na.rm=TRUE)) / binCount
r = plyr::ddply(data, batchColname, thinOut, filterColname, binsize)
return (r)
}
getAbundanceClass = function(x) {
r = data.frame(x = x)
r$x_diff = round(r$x - min(r$x))
r$x_diff_fac = as.numeric(factor(r$x_diff))
cc = length(unique(r$x_diff))
if (cc==1) lvls = "mid"
if (cc==2) lvls = c("low", "high")
if (cc==3) lvls = c("low", "mid", "high")
if (cc==4) lvls = c("low", "low-mid", "mid-high", "high")
if (cc>4) {
lvls = 1:max(r$x_diff_fac)
lvls[1] = "low"
lvls[length(lvls)] = "high"
}
r$x_cl = lvls[r$x_diff_fac]
r$x_cl = factor(r$x_cl, levels=lvls, ordered=TRUE)
r
return(r$x_cl)
}
getReportFilenames = function(folder, report_name_has_folder = TRUE, mzTab_filename = NULL)
{
pv = try(utils::packageVersion("PTXQC"))
if (inherits(pv, "try-error")) pv = "_unknown"
report_version = paste0("v", pv)
extra_folderRef = ""
folders = rev(unlist(strsplit(normalizePath(folder, winslash = .Platform$file.sep), split=.Platform$file.sep)))
while (length(folders)){
if (!grepl(":", folders[1]) & folders[1]!="txt") {
extra_folderRef = paste0("_", folders[1])
break;
} else folders = folders[-1]
}
report_file_simple = paste0(folder, .Platform$file.sep, "report_", report_version)
if (!is.null(mzTab_filename) && nchar(mzTab_filename) > 0) {
report_file_simple = paste0(report_file_simple, "_", gsub("\\.mzTab$", "", basename(mzTab_filename), ignore.case = TRUE))
}
if (report_name_has_folder)
report_file_prefix = paste0(report_file_simple, extra_folderRef)
else
report_file_prefix = report_file_simple
fh = list(yaml_file = paste0(report_file_prefix, ".yaml"),
heatmap_values_file = paste0(report_file_prefix, "_heatmap.txt"),
R_plots_file = paste0(report_file_prefix, "_plots.Rdata"),
filename_sorting = paste0(report_file_prefix, "_filename_sort.txt"),
mzQC_file = paste0(report_file_prefix, ".mzQC"),
log_file = paste0(report_file_prefix, ".log"),
report_file_prefix = report_file_prefix,
report_file_PDF = paste0(report_file_prefix, ".pdf"),
report_file_HTML = paste0(report_file_prefix, ".html")
)
return (fh)
}
getProteinCounts = function(df_evd) {
required_cols = c("protein.group.ids", "fc.raw.file", "is.transferred")
if (!all(required_cols %in% colnames(df_evd))) {
stop("getProteinCounts(): Missing columns!")
}
reportMTD = any(df_evd$is.transferred)
prot_counts = plyr::ddply(df_evd, "fc.raw.file", .fun = function(x, reportMTD)
{
x$group_mtdinfo = paste(x$protein.group.ids, x$is.transferred, sep="_")
xpro = x[!duplicated(x$group_mtdinfo),]
p_groups = lapply(as.character(xpro$protein.group.ids), function(x) {
return (strsplit(x, split=";", fixed=TRUE))
})
pg_set_genuineUnique = unique(unlist(p_groups[!xpro$is.transferred]))
pg_set_allMBRunique = unique(unlist(p_groups[xpro$is.transferred]))
pg_count_GenAndMBR = length(intersect(pg_set_allMBRunique, pg_set_genuineUnique))
pg_count_newMBR = length(pg_set_allMBRunique) - pg_count_GenAndMBR
pg_count_onlyGenuine = length(pg_set_genuineUnique) - pg_count_GenAndMBR
if (reportMTD)
{
df = data.frame(counts = c(pg_count_onlyGenuine, pg_count_GenAndMBR, pg_count_newMBR),
category = c("genuine (exclusive)", "genuine + transferred", "transferred (exclusive)"),
MBRgain = c(NA, NA, pg_count_newMBR / (pg_count_onlyGenuine + pg_count_GenAndMBR) * 100))
} else {
df = data.frame(counts = c(pg_count_onlyGenuine),
category = c("genuine"),
MBRgain = NA)
}
return (df)
}, reportMTD = reportMTD)
return (prot_counts)
}
getPeptideCounts = function(df_evd) {
required_cols = c("fc.raw.file", "modified.sequence", "is.transferred")
if (!all(required_cols %in% colnames(df_evd))) {
stop("getPeptideCounts(): Missing columns!")
}
reportMTD = any(df_evd$is.transferred)
pep_counts = plyr::ddply(df_evd, "fc.raw.file", .fun = function(x, reportMTD)
{
x <<- x
pep_set_genuineUnique = unique(x$modified.sequence[!x$is.transferred])
pep_set_allMBRunique = unique(x$modified.sequence[x$is.transferred])
pep_count_GenAndMBR = length(intersect(pep_set_genuineUnique, pep_set_allMBRunique))
pep_count_newMBR = length(pep_set_allMBRunique) - pep_count_GenAndMBR
pep_count_onlyGenuine = length(pep_set_genuineUnique) - pep_count_GenAndMBR
if (reportMTD)
{
df = data.frame(counts = c(pep_count_onlyGenuine, pep_count_GenAndMBR, pep_count_newMBR),
category = c("genuine (exclusive)", "genuine + transferred", "transferred (exclusive)"),
MBRgain = c(NA, NA, pep_count_newMBR / (pep_count_onlyGenuine + pep_count_GenAndMBR) * 100))
} else {
df = data.frame(counts = c(pep_count_onlyGenuine),
category = c("genuine"),
MBRgain = NA)
}
return (df)
}, reportMTD = reportMTD)
return (pep_counts)
}
wait_for_writable = function(filename,
prompt_text = paste0("The file '", filename, "' is not writable. Please close all applications using this file. Press '", abort_answer, "' to abort!"),
abort_answer = "n")
{
while(TRUE)
{
is_writeable = try({
f = file(filename, open="a");
close(f)
}, silent = TRUE
)
if (inherits(is_writeable, "try-error")) {
if (interactive()) {
r = invisible(readline(prompt = prompt_text))
if (r == abort_answer)
{
return (FALSE)
}
} else
{
return(FALSE)
}
} else {
return (TRUE)
}
}
return (FALSE)
}
getECDF = function(samples, y_eval = (1:100)/100)
{
inv_ecdf <- function(f){
x <- environment(f)$x
y <- environment(f)$y
approxfun(y, x)
}
ec = ecdf(samples)
iec = inv_ecdf(ec)
x_eval = iec(y_eval)
r = data.frame(x = x_eval, y = y_eval)
return (r)
}
peakWidthOverTime = function(data, RT_bin_width = 2)
{
r = range(data$retention.time, na.rm = TRUE)
brs = seq(from = r[1], to = r[2] + RT_bin_width, by = RT_bin_width)
data$bin = findInterval(data$retention.time, brs, all.inside = TRUE)
retLStats = plyr::ddply(data, "bin", .fun = function(xb) {
data.frame(RT = brs[xb$bin[1]], peakWidth = median(xb$retention.length, na.rm = TRUE))
})
return(retLStats)
}
getMetricsObjects = function(DEBUG_PTXQC = FALSE)
{
if (DEBUG_PTXQC) {
lst_qcMetrics_str = ls(sys.frame(which = 0), pattern="qcMetric_")
} else {
lst_qcMetrics_str = ls(name = getNamespace("PTXQC"), pattern="qcMetric_")
}
if (length(lst_qcMetrics_str) == 0) stop("getMetricsObjects(): No metrics found! Very weird!")
lst_qcMetrics = sapply(lst_qcMetrics_str, function(m) {
q = get(m)
if (class(q) %in% "refObjectGenerator"){
return(q$new())
}
return(NULL)
})
return(lst_qcMetrics)
}
darken = function(color, factor=0.8){
dark_col = grDevices::rgb(t(grDevices::col2rgb(color) * factor), maxColorValue=255)
return(dark_col)
}
checkEnglishLocale = function(df_evd) {
if (!checkInput(c("charge"), df_evd)) return(TRUE)
if (any(df_evd$charge < 0)){
return (FALSE)
}
else return (TRUE)
} |
GMerrorsar <- function(
formula, data = list(), listw, na.action=na.fail,
zero.policy=NULL, method="nlminb", arnoldWied=FALSE,
control=list(), pars=NULL, scaleU=FALSE, verbose=NULL, legacy=FALSE,
se.lambda=TRUE, returnHcov=FALSE, pWOrder=250, tol.Hcov=1.0e-10) {
if (is.null(verbose)) verbose <- get("verbose", envir = .spatialregOptions)
stopifnot(is.logical(verbose))
if (is.null(zero.policy))
zero.policy <- get("zeroPolicy", envir = .spatialregOptions)
stopifnot(is.logical(zero.policy))
if (!inherits(formula, "formula")) formula <- as.formula(formula)
mt <- terms(formula, data = data)
mf <- lm(formula, data, na.action=na.action, method="model.frame")
na.act <- attr(mf, "na.action")
if (!is.null(na.act)) {
subset <- !(1:length(listw$neighbours) %in% na.act)
listw <- subset(listw, subset, zero.policy=zero.policy)
}
if (!inherits(listw, "listw")) stop("No neighbourhood list")
y <- model.extract(mf, "response")
if (any(is.na(y))) stop("NAs in dependent variable")
x <- model.matrix(mt, mf)
if (any(is.na(x))) stop("NAs in independent variable")
if (NROW(x) != length(listw$neighbours))
stop("Input data and neighbourhood list have different dimensions")
lm.base <- lm(y ~ x - 1)
aliased <- is.na(coefficients(lm.base))
cn <- names(aliased)
names(aliased) <- substr(cn, 2, nchar(cn))
if (any(aliased)) {
nacoef <- which(aliased)
x <- x[,-nacoef]
}
ols <- lm(y ~ x - 1)
ukp <- residuals(ols)
vvo <- .kpwuwu(listw, ukp, zero.policy=zero.policy,
arnoldWied=arnoldWied, X=x)
if (is.null(pars)) {
scorr <- c(crossprod(lag.listw(listw, ukp,
zero.policy=zero.policy), ukp) / crossprod(ukp, ukp))
scorr <- scorr / (sum(unlist(listw$weights)) / length(ukp))
if (scaleU) ukp <- scale(ukp)
pars <- c(scorr, var(ukp))
}
if (length(pars) !=2L || !is.numeric(pars))
stop("invalid starting parameter values")
vv <- .kpwuwu(listw, ukp, zero.policy=zero.policy,
arnoldWied=arnoldWied, X=x)
if (method == "nlminb")
optres <- nlminb(pars, .kpgm, v=vv, verbose=verbose,
control=control)
else
optres <- optim(pars, .kpgm, v=vv, verbose=verbose,
method=method, control=control)
if (optres$convergence != 0)
warning(paste("convergence failure:", optres$message))
lambda <- optres$par[1]
names(lambda) <- "lambda"
GMs2 <- optres$par[2]
lambda.se <- NULL
wy <- lag.listw(listw, y, zero.policy=zero.policy)
if (any(is.na(wy)))
stop("NAs in lagged dependent variable")
n <- NROW(x)
m <- NCOL(x)
xcolnames <- colnames(x)
K <- ifelse(xcolnames[1] == "(Intercept)", 2, 1)
if (any(is.na(wy)))
stop("NAs in lagged dependent variable")
if (m > 1) {
WX <- matrix(nrow=n,ncol=(m-(K-1)))
for (k in K:m) {
wx <- lag.listw(listw, x[,k], zero.policy=zero.policy)
if (any(is.na(wx)))
stop("NAs in lagged independent variable")
WX[,(k-(K-1))] <- wx
}
}
if (K == 2) {
wx1 <- as.double(rep(1, n))
wx <- lag.listw(listw, wx1, zero.policy=zero.policy)
if (m > 1) WX <- cbind(wx, WX)
else WX <- matrix(wx, nrow=n, ncol=1)
}
colnames(WX) <- xcolnames
rm(wx)
lm.target <- lm(I(y - lambda*wy) ~ I(x - lambda*WX) - 1)
coef.lambda <- coefficients(lm.target)
names(coef.lambda) <- xcolnames
if (legacy) {
SSE <- deviance(lm.target)
s2 <- SSE/n
p <- lm.target$rank
rest.se <- (summary(lm.target)$coefficients[,2])*sqrt((n-p)/n)
r <- as.vector(residuals(lm.target))
fit <- as.vector(y - r)
vcov <- vcov(lm.target)
} else {
fit <- as.vector(x %*% coef.lambda)
r <- as.vector(y - fit)
e <- residuals(ols)
et <- e - lambda*lag.listw(listw, e, zero.policy=zero.policy)
SSE <- c(crossprod(et))
s2 <- SSE/n
Bx <- x - lambda*WX
Qr <- qr(Bx/(sqrt(s2)))
invxpx <- chol2inv(Qr$qr)
rest.se <- sqrt(diag(invxpx))
vcov <- invxpx
}
W <- as(listw, "CsparseMatrix")
lambda.se <- NULL
if (!arnoldWied && se.lambda) {
KP04a <- (1/n) * vvo$trwpw
KP04c <- sqrt(1/(1+(KP04a*KP04a)))
KP04se <- vvo$wu
KP04de <- vvo$wwu
KP04eo <- residuals(ols)
J <- matrix(0.0, ncol=2, nrow=2)
J[1,1] <- 2*KP04c*(crossprod(KP04de, KP04se) -
KP04a*crossprod(KP04se, KP04eo))
J[2,1] <- crossprod(KP04de, KP04eo) + crossprod(KP04se)
J[1,2] <- - KP04c*(crossprod(KP04de) - KP04a*crossprod(KP04se))
J[2,2] <- - crossprod(KP04de, KP04se)
J <- (1/n)*J
J1 <- J %*% matrix(c(1, 2*lambda), ncol=1)
A2N <- crossprod(W)
A1N <- KP04c*(A2N - KP04a*as_dsCMatrix_I(n))
A1NA1Np <- A1N+t(A1N)
A2NA2Np <- A2N+t(A2N)
trA1A1 <- sum(colSums(t(A1NA1Np)*A1NA1Np))
trA1A2 <- sum(colSums(crossprod(A2NA2Np, A1NA1Np)))
trA2A2 <- sum(colSums(crossprod(A2NA2Np, A2NA2Np)))
sigh <- s2*s2
phihat <- matrix(0.0, ncol=2, nrow=2)
phihat[1,1] <- (sigh)*trA1A1/(2*n)
phihat[1,2] <- (sigh)*trA1A2/(2*n)
phihat[2,1] <- (sigh)*trA1A2/(2*n)
phihat[2,2] <- (sigh)*trA2A2/(2*n)
JJI <- 1/crossprod(J1)
omega <- JJI * t(J1) %*% phihat %*% J1 * JJI
lambda.se <- sqrt(omega/n)
}
call <- match.call()
names(r) <- names(y)
names(fit) <- names(y)
Hcov <- NULL
if (returnHcov) {
pp <- ols$rank
p1 <- 1L:pp
R <- chol2inv(ols$qr$qr[p1, p1, drop = FALSE])
B <- tcrossprod(R, x)
B <- as(powerWeights(W=W, rho=lambda, order=pWOrder,
X=B, tol=tol.Hcov), "matrix")
C <- x %*% R
C <- as(powerWeights(W=t(W), rho=lambda, order=pWOrder,
X=C, tol=tol.Hcov), "matrix")
Hcov <- B %*% C
attr(Hcov, "method") <- "Matrix"
}
ret <- structure(list(type= "ERROR", lambda=lambda,
coefficients=coef.lambda, rest.se=rest.se,
s2=s2, SSE=SSE, parameters=(m+2), lm.model=ols,
call=call, residuals=r, lm.target=lm.target,
fitted.values=fit, formula=formula, aliased=aliased,
zero.policy=zero.policy, vv=vv, optres=optres,
pars=pars, Hcov=Hcov, legacy=legacy, lambda.se=lambda.se,
arnoldWied=arnoldWied, GMs2=GMs2, scaleU=scaleU, vcov=vcov),
class=c("Gmsar"))
if (zero.policy) {
zero.regs <- attr(listw$neighbours,
"region.id")[which(card(listw$neighbours) == 0)]
if (length(zero.regs) > 0L)
attr(ret, "zero.regs") <- zero.regs
}
if (!is.null(na.act))
ret$na.action <- na.act
ret
}
residuals.Gmsar <- function(object, ...) {
if (is.null(object$na.action))
object$residuals
else napredict(object$na.action, object$residuals)
}
deviance.Gmsar <- function(object, ...) {
deviance(object$lm.target)
}
coef.Gmsar <- function(object, ...) {
ret <- c(object$coefficients, object$lambda)
ret
}
fitted.Gmsar <- function(object, ...) {
if (is.null(object$na.action))
object$fitted.values
else napredict(object$na.action, object$fitted.values)
}
print.Gmsar <- function(x, ...)
{
cat("\nCall:\n")
print(x$call)
cat("\n")
cat("\nCoefficients:\n")
print(coef(x))
invisible(x)
}
summary.Gmsar <- function(object, correlation = FALSE, Hausman=FALSE, ...)
{
object$coeftitle <- "(GM standard errors)"
object$Coef <- cbind(object$coefficients, object$rest.se,
object$coefficients/object$rest.se,
2*(1-pnorm(abs(object$coefficients/object$rest.se))))
colnames(object$Coef) <- c("Estimate", "Std. Error",
"z value", "Pr(>|z|)")
rownames(object$Coef) <- names(object$coefficients)
if (Hausman && !is.null(object$Hcov)) {
object$Haus <- Hausman.test(object)
}
structure(object, class=c("summary.Gmsar", class(object)))
}
coef.summary.Gmsar <- function(object, ...) object$Coef
print.summary.Gmsar<-function (x, digits = max(5, .Options$digits - 3), signif.stars = FALSE,
...)
{
cat("\nCall:", deparse(x$call), sep = "", fill = TRUE)
cat("\nResiduals:\n")
resid <- residuals(x)
nam <- c("Min", "1Q", "Median", "3Q", "Max")
rq <- if (length(dim(resid)) == 2L)
structure(apply(t(resid), 1, quantile), dimnames = list(nam,
dimnames(resid)[[2]]))
else structure(quantile(resid), names = nam)
print(rq, digits = digits, ...)
if(x$type=="SARAR") cat("\nType: GM SARAR estimator")
else cat("\nType: GM SAR estimator")
if (x$arnoldWied) cat(" (Arnold and Wied (2010) moment definitions)\n")
else cat("\n")
if (x$zero.policy) {
zero.regs <- attr(x, "zero.regs")
if (!is.null(zero.regs))
cat("Regions with no neighbours included:\n", zero.regs,
"\n")
}
cat("Coefficients:", x$coeftitle, "\n")
coefs <- x$Coef
if (!is.null(aliased <- x$aliased) && any(x$aliased)) {
cat(" (", table(aliased)["TRUE"], " not defined because of singularities)\n",
sep = "")
cn <- names(aliased)
coefs <- matrix(NA, length(aliased), 4, dimnames = list(cn,
colnames(x$Coef)))
coefs[!aliased, ] <- x$Coef
}
printCoefmat(coefs, signif.stars = signif.stars, digits = digits,
na.print = "NA")
cat("\nLambda:", format(signif(x$lambda, digits)))
if (!is.null(x$lambda.se)) {
cat(" (standard error):", format(signif(x$lambda.se, digits)))
cat(" (z-value):", format(signif(x$lambda/x$lambda.se, digits)))
}
cat("\n")
cat("Residual variance (sigma squared): ", format(signif(x$s2,
digits)), ", (sigma: ", format(signif(sqrt(x$s2), digits)),
")\n", sep = "")
if (x$scaleU) cat("(scaled) ")
cat("GM argmin sigma squared: ", format(signif(x$GMs2,
digits)), "\n", sep = "")
cat("Number of observations:", length(x$residuals), "\n")
cat("Number of parameters estimated:", x$parameters, "\n")
if (!is.null(x$Haus)) {
cat("Hausman test: ", format(signif(x$Haus$statistic,
digits)), ", df: ", format(x$Haus$parameter), ", p-value: ",
format.pval(x$Haus$p.value, digits), "\n", sep = "")
}
cat("\n")
invisible(x)
}
Hausman.test.Gmsar <- function(object, ..., tol=NULL) {
if (!inherits(object, "Gmsar")) stop("not a Gmsar object")
if (is.null(object$Hcov)) stop("Vo not available")
fmeth <- "(approximate)"
s2 <- object$s2
Vo <- s2 * object$Hcov
Vs <- s2 * summary.lm(object$lm.target, correlation = FALSE)$cov.unscaled
d <- coef(object$lm.model) - coef(object$lm.target)
if (!is.null(tol)) VV <- try(solve((Vo - Vs), tol=tol))
else VV <- try(solve(Vo - Vs))
if (inherits(VV, "try-error")) {
warning("(Vo - Vs) inversion failure")
return(NULL)
}
statistic <- t(d) %*% VV %*% d
attr(statistic, "names") <- "Hausman test"
parameter <- length(d)
attr(parameter, "names") <- "df"
p.value <- 1 - pchisq(abs(statistic), parameter)
method <- paste("Spatial Hausman test", fmeth)
data.name <- strwrap(deparse(object$formula), exdent=4)
if (length(data.name) > 1L)
data.name <- paste(data.name, collapse="\n ")
res <- list(statistic = statistic, parameter = parameter,
p.value = p.value, method = method, data.name=data.name)
class(res) <- "htest"
res
}
impacts.Gmsar <- function(obj, ..., n=NULL, tr=NULL, R=NULL, listw=NULL,
evalues=NULL, tol=1e-6, empirical=FALSE, Q=NULL) {
stopifnot(obj$type == "SARAR")
if (is.null(listw) && !is.null(obj$listw_style) &&
obj$listw_style != "W")
stop("Only row-standardised weights supported")
rho <- obj$coefficients[1]
beta <- obj$coefficients[-1]
icept <- grep("(Intercept)", names(beta))
iicept <- length(icept) > 0
if (iicept) {
P <- matrix(beta[-icept], ncol=1)
bnames <- names(beta[-icept])
} else {
P <- matrix(beta, ncol=1)
bnames <- names(beta)
}
p <- length(beta)
if (is.null(n)) n <- length(obj$residuals)
stopifnot(is.integer(n))
stopifnot(length(n) == 1)
stopifnot(is.finite(n))
mu <- c(rho, beta)
Sigma <- obj$secstep_var
irho <- 1
drop2beta <- 1
res <- intImpacts(rho=rho, beta=beta, P=P, n=n, mu=mu, Sigma=Sigma,
irho=irho, drop2beta=drop2beta, bnames=bnames, interval=NULL,
type="lag", tr=tr, R=R, listw=listw, evalues=evalues, tol=tol,
empirical=empirical, Q=Q, icept=icept, iicept=iicept, p=p,
zero_fill=NULL, dvars=NULL)
attr(res, "iClass") <- class(obj)
res
}
.kpgm <- function(rhopar,v,verbose=FALSE) {
vv <- v$bigG %*% c(rhopar[1],rhopar[1]^2,rhopar[2]) - v$litg
value <- sum(vv^2)
if (verbose)
cat("function:", value, "lambda:", rhopar[1], "sig2:", rhopar[2], "\n")
value
}
.kpwuwu <- function(listw, u, zero.policy=FALSE, arnoldWied=FALSE, X=NULL) {
if (arnoldWied) {
stopifnot(!is.null(X))
invXtX <- chol2inv(qr.R(qr(X)))
W <- as(listw, "CsparseMatrix")
WX <- W %*% X
}
n <- length(u)
trwpw <- sum(unlist(listw$weights)^2)
wu <- lag.listw(listw, u, zero.policy=zero.policy)
wwu <- lag.listw(listw, wu, zero.policy=zero.policy)
uu <- crossprod(u,u)
uwu <- crossprod(u,wu)
uwpuw <- crossprod(wu,wu)
uwwu <- crossprod(u,wwu)
wwupwu <- crossprod(wwu,wu)
wwupwwu <- crossprod(wwu,wwu)
bigG <- matrix(0,3,3)
if (arnoldWied) {
k <- ncol(X)
uwpX <- crossprod(wu, X)
upWX <- crossprod(u, WX)
uwpWX <- crossprod(wu, WX)
iXpXXpwu <- invXtX %*% t(uwpX)
c22 <- wwu - WX %*% iXpXXpwu
XiXpX <- X %*% invXtX
WXpW <- t(WX) %*% W
c23 <- trwpw - sum(diag(WXpW %*% XiXpX))
c32 <- crossprod(wu, wwu) - t(wu) %*% WX %*% iXpXXpwu
c32 <- c32 - ((t(wu) %*% XiXpX %*% crossprod(X, wwu)) -
(t(wu) %*% XiXpX %*% crossprod(X, WX) %*% iXpXXpwu))
bigG[,1] <- c(2*uwu, 2*as.vector(wwupwu - (uwpWX %*% iXpXXpwu)),
as.vector(uwwu - (upWX %*% iXpXXpwu)) +
(uwpuw - (uwpX %*% iXpXXpwu)))/n
bigG[,2] <- - c(as.vector(uwpuw - (uwpX %*% iXpXXpwu)), as.vector(crossprod(c22)), as.vector(c32))/n
bigG[,3] <- c(n-k, as.vector(c23), -as.vector(sum(diag(t(X) %*% (WX %*% invXtX)))))/n
} else {
bigG[,1] <- c(2*uwu, 2*wwupwu, (uwwu+uwpuw))/n
bigG[,2] <- - c(uwpuw, wwupwwu, wwupwu) / n
bigG[,3] <- c(1, trwpw/n, 0)
}
litg <- c(uu,uwpuw,uwu) / n
list(bigG=bigG, litg=litg, trwpw=trwpw, wu=wu, wwu=wwu)
}
gstsls<-function (formula, data = list(), listw, listw2=NULL,
na.action = na.fail, zero.policy = NULL, pars=NULL, scaleU=FALSE,
control = list(), verbose = NULL, method = "nlminb", robust = FALSE,
legacy = FALSE, W2X = TRUE )
{
if (is.null(verbose))
verbose <- get("verbose", envir = .spatialregOptions)
stopifnot(is.logical(verbose))
if (is.null(zero.policy))
zero.policy <- get.ZeroPolicyOption()
stopifnot(is.logical(zero.policy))
if (!inherits(listw, "listw"))
stop("The weights matrix is not a listw object")
if (is.null(listw2))
listw2 <- listw
else if (!inherits(listw2, "listw"))
stop("No 2nd neighbourhood list")
if (!inherits(formula, "formula")) formula <- as.formula(formula)
mt <- terms(formula, data = data)
mf <- lm(formula, data, na.action = na.fail, method = "model.frame")
na.act <- attr(mf, "na.action")
cl <- match.call()
if (!is.null(na.act)) {
subset <- !(1:length(listw$neighbours) %in% na.act)
subset2 <- !(1:length(listw2$neighbours) %in% na.act)
listw <- subset(listw, subset, zero.policy = zero.policy)
listw2 <- subset(listw2, subset2, zero.policy = zero.policy)
}
y <- model.extract(mf, "response")
x <- model.matrix(mt, mf)
if (length(y) != nrow(x))
stop("x and y have different length")
if (nrow(x) != length(listw$neighbours))
stop("Input data and weights have different dimension")
if (any(is.na(y)))
stop("NAs in dependent variable")
if (any(is.na(x)))
stop("NAs in independent variable")
n <- nrow(x)
k <- ncol(x)
xcolnames <- colnames(x)
K <- ifelse(xcolnames[1] == "(Intercept)" || all(x[, 1] ==
1), 2, 1)
wy <- lag.listw(listw, y, zero.policy = zero.policy)
wy <- array(wy, c(length(y), 1L))
colnames(wy) <- ("Wy")
if (any(is.na(wy)))
stop("NAs in spatially lagged dependent variable")
if (k > 1) {
WX <- matrix(nrow = n, ncol = (k - (K - 1)))
WWX <- matrix(nrow = n, ncol = (k - (K - 1)))
for (i in K:k) {
wx <- lag.listw(listw, x[, i], zero.policy = zero.policy)
wwx <- lag.listw(listw, wx, zero.policy = zero.policy)
if (any(is.na(wx)))
stop("NAs in lagged independent variable")
WX[, (i - (K - 1))] <- wx
WWX[, (i - (K - 1))] <- wwx
}
}
instr <- cbind(WX, WWX)
firststep <- tsls(y = y, yend = wy, X = x, Zinst = instr, robust = robust, legacy = legacy)
ukp <- residuals(firststep)
if (is.null(pars)) {
scorr <- c(crossprod(lag.listw(listw2, ukp,
zero.policy=zero.policy), ukp)/crossprod(ukp, ukp))
scorr <- scorr/(sum(unlist(listw2$weights))/length(ukp))
if (scaleU) ukp <- scale(ukp)
pars <- c(scorr, var(ukp))
}
if (length(pars) != 2L || !is.numeric(pars))
stop("invalid starting parameter values")
vv <- .kpwuwu(listw2, ukp, zero.policy = zero.policy,
arnoldWied=FALSE, X=x)
if (method == "nlminb")
optres <- nlminb(pars, .kpgm, v = vv, verbose = verbose,
control = control)
else optres <- optim(pars, .kpgm, v = vv, verbose = verbose,
method = method, control = control)
if (optres$convergence != 0)
warning(paste("convergence failure:", optres$message))
lambda <- optres$par[1]
names(lambda) <- "lambda"
GMs2 <- optres$par[2]
lambda.se <- NULL
w2y <- lag.listw(listw2, y)
yt <- y - lambda * w2y
xt <- x - lambda * lag.listw(listw2, x)
wyt <- wy - lambda * lag.listw(listw2, wy)
colnames(xt) <- xcolnames
colnames(wyt) <- c("Rho_Wy")
secstep <- tsls(y = yt, yend = wyt, X = xt, Zinst = instr,
robust = robust, legacy = legacy)
rho<-secstep$coefficients[1]
coef.sac<-secstep$coefficients
rest.se <- sqrt(diag(secstep$var))
rho.se <- sqrt(diag(secstep$var))[1]
s2<-secstep$sse / secstep$df
r<- secstep$residuals
fit<- y - r
SSE<- crossprod(r)
call <- match.call()
ret <- structure(list(type= "SARAR", lambda = lambda,
coefficients = coef.sac,
rest.se = rest.se, s2 = s2, SSE = SSE, parameters = (k +
3), lm.model = NULL, call = call, residuals = r, lm.target = NULL,
fitted.values = fit, formula = formula, aliased = NULL,
zero.policy = zero.policy, vv = vv, optres = optres,
pars = pars, Hcov = NULL, lambda.se=lambda.se,
arnoldWied=FALSE, GMs2=GMs2, scaleU=scaleU,
secstep_var=secstep$var), class = c("Gmsar"))
if (zero.policy) {
zero.regs <- attr(listw$neighbours,
"region.id")[which(card(listw$neighbours) == 0)]
if (length(zero.regs) > 0L)
attr(ret, "zero.regs") <- zero.regs
}
if (!is.null(na.act)) ret$na.action <- na.act
ret
}
GMargminImage <- function(obj, lambdaseq, s2seq) {
if (missing(lambdaseq)) {
lamin <- obj$lambda-0.5
lamin <- ifelse(lamin < -1, -1, lamin)
lamax <- obj$lambda+0.5
lamax <- ifelse(lamax >= 1, (1-.Machine$double.eps), lamax)
lambdaseq <- seq(lamin, lamax, length.out=40)
}
if (missing(s2seq))
s2seq <- seq(0.5*obj$GMs2, 1.5*obj$GMs2, length.out=40)
xy <- as.matrix(expand.grid(lambdaseq, s2seq))
vres <- apply(xy, 1, function(x) .kpgm(rhopar=x, v=obj$vv))
res <- matrix(vres, ncol=length(lambdaseq))
list(x=lambdaseq, y=s2seq, z=res)
} |
setPulse <- function(id = NULL, class = NULL, duration = 1, iteration = 5) {
cssPulse <- paste0(
"animation: pulse ", duration, "s;
animation-iteration-count: ", iteration, ";
"
)
cssPulse <- if (!is.null(id)) {
if (!is.null(class)) {
paste0("
} else {
paste0("
}
} else {
if (!is.null(class)) {
paste0(".", class, " {", cssPulse, "}")
} else {
NULL
}
}
extracss <- paste0(
"@-webkit-keyframes pulse {
0% {
-webkit-box-shadow: 0 0 0 0 rgba(204,169,44, 0.4);
}
70% {
-webkit-box-shadow: 0 0 0 10px rgba(204,169,44, 0);
}
100% {
-webkit-box-shadow: 0 0 0 0 rgba(204,169,44, 0);
}
}
@keyframes pulse {
0% {
-moz-box-shadow: 0 0 0 0 rgba(204,169,44, 0.4);
box-shadow: 0 0 0 0 rgba(204,169,44, 0.4);
}
70% {
-moz-box-shadow: 0 0 0 10px rgba(204,169,44, 0);
box-shadow: 0 0 0 10px rgba(204,169,44, 0);
}
100% {
-moz-box-shadow: 0 0 0 0 rgba(204,169,44, 0);
box-shadow: 0 0 0 0 rgba(204,169,44, 0);
}
}
"
)
css <- paste(cssPulse, extracss)
htmltools::tags$head(
htmltools::tags$style(css)
)
} |
model_get_weights <- function(model) {
UseMethod("model_get_weights")
}
model_get_weights.default <- function(model) {
w <- tryCatch(
stats::weights(model),
error = function(e) {
NULL
}
)
if (is.null(w) | length(w) == 0) {
mf <- model %>% model_get_model_frame()
if (!is.null(mf)) {
if ("(weights)" %in% names(mf)) {
w <- mf %>% purrr::pluck("(weights)")
} else {
w <- rep_len(1L, mf %>% nrow())
}
}
}
if (is.matrix(w)) w <- c(w)
w
}
model_get_weights.svyglm <- function(model) {
stats::weights(model$survey.design)
} |
make.all.branches.mkn.pij <- function(cache, control) {
k <- cache$info$k
f.pij <- make.pij.mkn(cache$info, control)
idx.tip <- cache$idx.tip
n.tip <- cache$n.tip
n <- length(cache$len)
map <- t(sapply(1:k, function(i) (1:k) + (i - 1) * k))
idx.tip <- cbind(c(map[cache$states,]),
rep(seq_len(n.tip), k))
len.uniq <- sort(unique(cache$len))
len.idx <- match(cache$len, len.uniq)
children.C <- toC.int(t(cache$children))
order.C <- toC.int(cache$order)
function(pars, intermediates, preset=NULL) {
if ( !is.null(preset) )
stop("Preset values not allowed")
pij <- f.pij(len.uniq, pars)[,len.idx]
lq <- numeric(n)
branch.init <- branch.base <- matrix(NA, k, n)
storage.mode(branch.init) <- "numeric"
ans <- matrix(pij[idx.tip], n.tip, k)
q <- rowSums(ans)
branch.base[,seq_len(n.tip)] <- t.default(ans/q)
lq[seq_len(n.tip)] <- log(q)
ans <- .C(r_mkn_core,
k = as.integer(k),
n = length(order.C) - 1L,
order = order.C,
children = children.C,
pij = pij,
init = branch.init,
base = branch.base,
lq = lq,
NAOK=TRUE)
list(init=ans$init,
base=ans$base,
lq=ans$lq,
vals=ans$init[,cache$root],
pij=pij)
}
}
pij.mk2 <- function(len, pars) {
q01 <- pars[3]
q10 <- pars[2]
x <- exp(-(q01+q10)*len)
rbind((x*q01 + q10),
(1 - x)*q10,
(1 - x)*q01,
(x*q10 + q01)) / (q01 + q10)
}
make.pij.mkn <- function(info, control) {
if ( control$method == "mk2" )
return(pij.mk2)
control <- check.control.ode(control)
k <- info$k
info <- list(name="mknpij",
ny=k*k, np=k*k,
idx.d=integer(0),
derivs=make.derivs.mkn.pij(k))
pij.ode <- make.ode(info, control)
yi <- diag(k)
function(len, pars)
pij.ode(yi, c(0, len), pars)
}
make.derivs.mkn.pij <- function(k) {
force(k)
function(t, y, pars) {
Q <- matrix(pars, k, k)
y <- matrix(y, k, k)
ret <- Q %*% y
dim(ret) <- NULL
ret
}
} |
initializeShinyInput <- function(shinyInput, elementId){
sprintf(
"Shiny.inputBindings.bindingNames['shiny.%s'].binding.initialize(%s);",
shinyInput, sprintf("document.getElementById('%s')", elementId)
)
}
isSlider <- function(x){
inherits(x, "shiny.tag") &&
length(x[["children"]]) == 2L &&
inherits(x[["children"]][[2L]], "shiny.tag") &&
identical(x[["children"]][[2L]][["attribs"]][["class"]], "js-range-slider")
}
evalHtmlDependencies <- function(x){
lapply(x, function(dep){
if(inherits(dep, "shiny.tag.function")) dep() else dep
})
}
makeScriptTag <- function(script){
if(inherits(script, "shiny.tag")){
shinyTag(
name = "ScriptTag",
attribs = c(
script[["attribs"]],
list(dangerouslySetInnerHTML =
list("__html" = URLencode(script[["children"]][[1L]])))
)
)
}else{
Tag$ScriptTag(
dangerouslySetInnerHTML = list("__html" = URLencode(script))
)
}
}
unclassComponent <- function(component, inputId, call){
if(!is.null(statesGroup <- component[["statesGroup"]])){
if(call == "setReactState"){
stop(
"You cannot use a component with states in `setReactState`.",
call. = FALSE
)
}
states <- component[["states"]]
for(stateName in names(states)){
state <- states[[stateName]]
if(!isJseval(state) && !isHook(state) && !isJSX(state)){
if(inherits(state, "html")){
states[[stateName]] <- list("__html" = URLencode(as.character(state)))
}else if(isShinyTag(state)){
states[[stateName]] <-
unclassComponent(state, inputId, "unclassComponent")[["component"]]
}
}
}
component[["states"]] <-
URLencode(as.character(
toJSON(states, auto_unbox = TRUE, null = "null", digits = NA)
))
x <- vapply(states, function(s){
if(isJseval(s) || isHook(s) || isJSX(s)) "" else statesGroup
}, character(1L))
x <- c(x, statesEnvir[[inputId]])
assign(inputId, x, envir = statesEnvir)
}
if(inherits(component, "shiny.tag.list")){
component <- do.call(Tag$Fragment, component)
}
RadioGroups <- dependencies <- NULL
shinyOutput <- FALSE
if(isSlider(component)){
dependencies <- evalHtmlDependencies(htmlDependencies(component))
id <- component[["children"]][[2L]][["attribs"]][["id"]]
script <- initializeShinyInput("sliderInput", id)
component <- Tag$Fragment(
list("__html" = URLencode(as.character(component))),
makeScriptTag(script)
)
}else if(
isShinyTag(component) &&
"class" %in% names(component[["attribs"]]) &&
grepl("shiny-date-input", component[["attribs"]][["class"]]) &&
!isTRUE(component[["dontprocess"]])
){
dependencies <-
evalHtmlDependencies(component[["children"]][[3L]])
component[["children"]] <- component[["children"]][c(1L,2L)]
script <- initializeShinyInput("dateInput", component[["attribs"]][["id"]])
component[["dontprocess"]] <- TRUE
component <- Tag$Fragment(
component, makeScriptTag(script)
)
}else if(
inherits(component, "shiny.tag") && !is.null(htmlDependencies(component))
){
dependencies <- evalHtmlDependencies(htmlDependencies(component))
depnames <- vapply(dependencies, `[[`, FUN.VALUE = character(1L), "name")
if("selectize" %in% depnames){
id <-
component[["children"]][[2L]][["children"]][[1L]][["attribs"]][["id"]]
script <- initializeShinyInput("selectInput", id)
htmltools::htmlDependencies(component) <- NULL
component <- Tag$Fragment(
component, makeScriptTag(script)
)
}else if(
grepl("shiny-date-range-input", component[["attribs"]][["class"]])
){
script <- initializeShinyInput(
"dateRangeInput", component[["attribs"]][["id"]]
)
htmltools::htmlDependencies(component) <- NULL
component <- Tag$Fragment(
component, makeScriptTag(script)
)
}else{
htmltools::htmlDependencies(component) <- NULL
}
}else if(!isChakraIcon(component) && grepl("Icon$", component[["name"]])){
if(component[["name"]] %notin% allIcons()){
stop(
sprintf("Invalid icon '%s'.", component[["name"]]),
call. = FALSE
)
}
}
if(
"icon" %in% names(component[["attribs"]]) &&
!isChakraIcon(icon <- component[["attribs"]][["icon"]])
){
if(!isReactComponent(icon)){
stop(
sprintf(
"Invalid `icon` attribute in component '%s'.", component[["name"]]
),
call. = FALSE
)
}
if(!grepl("Icon$", icon[["name"]])){
stop(
sprintf(
"Invalid `icon` attribute in component '%s'.", component[["name"]]
),
call. = FALSE
)
}
if(icon[["name"]] %notin% chakraIcons()){
stop(
sprintf(
"Invalid `icon` attribute in component '%s'.", component[["name"]]
),
sprintf("'%s' is not the name of a chakra icon.", icon[["name"]]),
call. = FALSE
)
}
}
for(attribname in names(component[["attribs"]])){
attrib <- component[["attribs"]][[attribname]]
if(isString(attrib)){
component[["attribs"]][[attribname]] <- URLencode(attrib)
}
if(isReactComponent(attrib) && grepl("Icon$", attrib[["name"]])){
if(attrib[["name"]] %notin% allIcons()){
stop(
sprintf("Invalid icon '%s'.", attrib[["name"]]),
call. = FALSE
)
}
}
}
if(!is.null(component[["attribs"]][["children"]])){
component[["children"]] <-
c(component[["children"]], list(component[["attribs"]][["children"]]))
component[["attribs"]][["children"]] <- NULL
}
component[["attribs"]] <- lapply(component[["attribs"]], unclass)
attribs <- component[["attribs"]]
attribsNames <- names(attribs)
if(isReactComponent(component) && "class" %in% attribsNames){
component[["attribs"]][["className"]] <- attribs[["class"]]
component[["attribs"]][["class"]] <- NULL
attribs <- component[["attribs"]]
attribsNames <- names(attribs)
}
if(
component[["name"]] %in% c("Button", "IconButton") &&
"className" %in% attribsNames &&
grepl("action-button", attribs[["className"]])
){
if("id" %notin% attribsNames){
stop(
"Buttons with the 'action-button' class must have an `id` attribute.",
call. = FALSE
)
}
}else if(
component[["name"]] %in% c("Button", "IconButton") &&
"value" %in% attribsNames
){
component[["attribs"]][["data-val"]] <- attribs[["value"]]
component[["attribs"]][["value"]] <- NULL
attribs <- component[["attribs"]]
attribsNames <- names(attribs)
}
if(
component[["name"]] %in% c("Button", "IconButton") &&
"action" %in% attribsNames
){
iconbutton <- component[["name"]] == "IconButton"
component[["name"]] <- switch(
attribs[["action"]],
none = "Button",
open = "OpenButton",
cancel = "CancelButton",
disable = "DisableButton",
unmount = "UnmountingButton",
close = "ClosingButton",
remove = "RemoveButton",
"Button"
)
if(iconbutton)
component[["name"]] <- sub("Button", "IconButton", component[["name"]])
component[["attribs"]][["action"]] <- NULL
attribs <- component[["attribs"]]
attribsNames <- names(attribs)
}else if(
component[["name"]] %in% c("Button", "IconButton") &&
"id" %in% attribsNames &&
"className" %notin% attribsNames
){
component[["attribs"]][["className"]] <- "action-button"
attribs <- component[["attribs"]]
attribsNames <- names(attribs)
}
if(component[["name"]] == "MenuItem"){
if("value" %notin% attribsNames){
stop(
"`MenuItem` requires a `value` attribute.", call. = FALSE
)
}
component[["attribs"]][["data-val"]] <- attribs[["value"]]
component[["attribs"]][["value"]] <- NULL
attribs <- component[["attribs"]]
attribsNames <- names(attribs)
}
if(sum(attribsNames == "class") > 1L){
component[["attribs"]][which(attribsNames == "class")] <- NULL
component[["attribs"]][["class"]] <-
do.call(paste, attribs[attribsNames == "class"])
attribs <- component[["attribs"]]
attribsNames <- names(attribs)
}
if("class" %in% attribsNames && grepl("-output", attribs[["class"]])){
shinyOutput <- TRUE
}else if(
component[["name"]] == "input" &&
attribs[["type"]] %in% c("text", "number") &&
!is.null(attribs[["value"]])
){
script <- sprintf(
'$("
)
component[["attribs"]][["value"]] <- NULL
component <- Tag$Fragment(
component, makeScriptTag(script)
)
}else if(
component[["name"]] == "CheckboxGroup"
){
if(is.null(attribs[["id"]])){
stop(
"Please provide an `id` attribute for the `CheckboxGroup`.",
call. = FALSE
)
}
if(!is.null(defaultValue <- attribs[["defaultValue"]])){
defaultValue <- as.list(defaultValue)
x <- unlist(component[["children"]])
values <- as.list(x[grep("value$", names(x))])
defaultValue <- intersect(defaultValue, values)
if(length(defaultValue)){
component[["attribs"]][["defaultValue"]] <-
defaultValue <- lapply(defaultValue, URLencode)
}else{
component[["attribs"]][["defaultValue"]] <- NULL
}
}
}else if(
component[["name"]] == "RadioGroup" && !is.null(attribs[["value"]])
){
RadioGroups <- list(attribs[["value"]])
names(RadioGroups) <- attribs[["id"]]
component[["attribs"]][["value"]] <- NULL
}else if(
component[["name"]] == "script"
){
component <- makeScriptTag(component)
}else if(component[["name"]] == "Menu"){
children <- vapply(component[["children"]], `[[`, character(1L), "name")
if(!identical(children, c("MenuButton", "MenuList"))){
stop(
"Invalid `Menu` component: ",
"it must have two children, `MenuButton` and `MenuList`.",
call. = FALSE
)
}
if("id" %notin% attribsNames){
stop(
"A `Menu` component must have an `id` attribute.",
call. = FALSE
)
}
}else if(component[["name"]] == "MenuButton" && "text" %in% attribsNames){
text <- attribs[["text"]]
check <- is.list(text) &&
identical(sort(names(text)), c("textWhenClose", "textWhenOpen"))
if(!check){
stop(
"Invalid `text` attribute of `MenuButton`.",
call. = TRUE
)
}
component[["attribs"]][["text"]] <- lapply(text, URLencode)
}
componentChildren <- dropNulls(component[["children"]])
if(length(componentChildren)){
component[["children"]] <- lapply(componentChildren, function(child){
if(isJseval(child)){
child
}else if(isShinyTag(child)){
x <- unclassComponent(child, inputId, call)
shinyOutput <<- x[["shinyOutput"]] || shinyOutput
RadioGroups <<- c(x[["RadioGroups"]], RadioGroups)
dependencies <<- c(x[["dependencies"]], dependencies)
x[["component"]]
}else if(inherits(child, "html")){
list("__html" = URLencode(as.character(child)))
}else if(isString(child)){
URLencode(child)
}else{
child
}
})
}
list(
component = unclass(component),
shinyOutput = shinyOutput,
RadioGroups = RadioGroups,
dependencies = dependencies
)
} |
lm.diallel <- function(formula, Block = NULL, Env = NULL,
fct = "GRIFFING2", data){
cl <- match.call()
mf <- match.call(expand.dots = FALSE)
m <- match(c("formula", "Block", "Env", "data"), names(mf), 0L)
mf <- mf[c(1L, m)]
mf$drop.unused.levels <- TRUE
mf[[1L]] <- quote(stats::model.frame)
mf <- eval(mf, parent.frame())
mt <- attr(mf, "terms")
Y <- model.response(mf, "numeric")
mlm <- is.matrix(Y)
ny <- if (mlm)
nrow(Y)
else length(Y)
bName <- deparse(substitute(Block))
Block <- model.extract(mf, "Block")
eName <- deparse(substitute(Env))
Env <- model.extract(mf, "Env")
pars <- attr(mt, "term.labels")
if(missing(data) == T){
Par1 <- mf[,2]
Par2 <- mf[,3]
} else {
Par1 <- mf[,2]
Par2 <- mf[,3]
}
X <- model.matrixDiallel(~ Par1 + Par2, Block=Block, Env = Env, fct = fct)
z <- lm.fit(X, Y)
class(z) <- c(if (mlm) "mlm", "lm")
z$response <- Y
z$fct <- fct
z$Env <- ifelse(is.null(Env), F, T)
z$Block <- ifelse(is.null(Block), F, T)
z$na.action <- attr(mf, "na.action")
z$offset <- NULL
z$xlevels <- .getXlevels(mt, mf)
z$call <- cl
z$terms <- mt
z$model <- mf
z$namEff <- attr(X, "namEff")
z$modMatrix <- X
class(z) <- c("diallel", "lm")
return(z)
}
summary.diallel <- function (object,
MSE = NULL, dfr = NULL, ...)
{
if(!is.null(MSE) & !is.null(dfr)){
sigma <- sqrt(MSE)
if(any(class(object) == "diallel") == T) {X <- object$modMatrix
} else { X <- model.matrix(object)}
ses <- sqrt(diag(solve( t(X) %*% X ))) * sigma
tab <- data.frame("Estimate" = object$coef, "SE" = ses)
tab$"t value" <- tab[,1]/tab[,2]
tab$"Pr(>|t|)" <- 2 * pt(abs(tab$"t value"), dfr, lower.tail = F)
return(tab)
}else{
z <- object
class(z) <- "lm"
summary(z)
}
}
vcov.diallel <- function(object, MSE = NULL, ...)
{
so <- summary(object)
if(is.na(so$sigma) & is.null(MSE)){
cat("No residual variance estimate is available")
stop()
} else if(is.na(so$sigma) == T & is.null(MSE) == F){
retVal <- MSE * so$cov.unscaled
} else if(is.na(so$sigma) == F & is.null(MSE) == F){
retVal <- MSE * so$cov.unscaled
} else if(is.na(so$sigma) == F & is.null(MSE) == T){
retVal <- so$sigma^2 * so$cov.unscaled
}
retVal
}
anova.diallel <- function(object, MSE = NULL, dfr = NULL, ...)
{
if(is.null(object$Env)) {object$Env <- FALSE }
if(object$Env == F){
w <- object$weights
ssr <- sum(if(is.null(w)) object$residuals^2 else w*object$residuals^2)
mss <- sum(if(is.null(w)) object$fitted.values^2 else w*object$fitted.values^2)
if(ssr < 1e-10*mss & is.null(MSE))
warning("ANOVA F-tests on an essentially perfect fit are unreliable")
if( is.null(dfr) ) dfr <- df.residual(object)
p <- object$rank
if(p > 0L) {
p1 <- 1L:p
comp <- object$effects[p1]
asgn <- object$assign[object$qr$pivot][p1]
nmeffects <- c("(Intercept)", attr(object$terms, "term.labels"))
if(any(class(object) == "diallel") == T) {tlabels <- object$namEff
} else {tlabels <- nmeffects[1 + unique(asgn)]
nmeffects}
ss <- c(unlist(lapply(split(comp^2,asgn), sum)), ssr)
df <- c(lengths(split(asgn, asgn)), dfr)
} else {
ss <- ssr
df <- dfr
tlabels <- character()
}
if(is.null(MSE)){
ms <- ss/df
f <- ms/(ssr/dfr)
P <- pf(f, df, dfr, lower.tail = FALSE)
table <- data.frame(df, ss, ms, f, P)
table[length(P), 3:5] <- NA
} else {
ms <- ss/df
f <- ms/MSE
P <- pf(f, df, dfr, lower.tail = FALSE)
table <- data.frame(df, ss, ms, f, P)
table[length(P), 2:5] <- NA
table[length(P), 3] <- MSE
}
if(all(class(object) != "diallel")) tlabels <- c(tlabels, "Residuals")
dimnames(table) <- list(c(tlabels),
c("Df","Sum Sq", "Mean Sq", "F value", "Pr(>F)"))
if(attr(object$terms,"intercept")) table <- table[-1, ]
structure(table, heading = c("Analysis of Variance Table\n",
paste("Response:", deparse(formula(object)[[2L]]))),
class = c("anova", "data.frame"))
} else if(object$Env == F &
(object$fct == "GE2" | object$fct == "GE2r")) {
ssr <- sum(object$residuals^2)
if(!is.null(MSE)) dfr1 <- dfr
dfr <- df.residual(object)
mss <- sum(object$fitted.values^2)
p <- object$rank
p1 <- 1L:p
comp <- object$effects[p1]
asgn <- object$assign[object$qr$pivot][p1]
nmeffects <- c("(Intercept)", attr(object$terms, "term.labels"))
tlabels <- object$namEff
ss <- c(unlist(lapply(split(comp^2,asgn), sum)), ssr)
df <- c(lengths(split(asgn, asgn)), dfr)
ms <- ss/df
table <- data.frame(df, ss, ms)
row.names(table) <- fit$namEff
if(!is.null(MSE)){
f <- ms/MSE
P <- pf(f, df, dfr1, lower.tail = FALSE)
table <- data.frame(df, ss, ms, dfr1, f, P)
tlabels <- object$namEff
dimnames(table) <- list(c(tlabels),
c("Df","Sum Sq", "Mean Sq", "Den df", "F value", "Pr(>F)"))
if(attr(object$terms,"intercept")) table <- table[-1, ]
structure(table, heading = c("Analysis of Variance Table\n",
paste("Response:", deparse(formula(object)[[2L]]))),
class = c("anova", "data.frame"))
}
} else if(object$Env == T) {
MSEor <- MSE; dfrOr <- dfr
X <- object$modMatrix
Y <- object$response
namEff <- object$namEff
numEff <- length(namEff) - 2
namEff <- namEff[-1]
asgn <- attr(X, "assign")
fct <- object$fct
dataset <- object$model
if(object$Block == T){
names(dataset)[4:5] <- c("Block", "Env")
dataset$Block <- factor(dataset$Block)
dataset$Env <- factor(dataset$Env)
matsOr <- model.matrixDiallel(~dataset[,2] + dataset[,3],
dataset$Block,
fct = fct)
} else {
names(dataset)[4] <- c("Env")
dataset$Env <- factor(dataset$Env)
matsOr <- model.matrixDiallel(~dataset[,2] + dataset[,3],
fct = fct)
}
asgn2 <- attr(matsOr, "assign")
resdf <- object$df.residual
ss <- c()
dfr <- c(); labTab <- c()
rss <- sum(object$residuals^2)
ss[1] <- rss
dfr[1] <- resdf
labTab[1] <- "Residuals"
cont <- 2
for(i in numEff:1){
sel <- asgn2 == i
sel2 <- (asgn >=( i + numEff) & asgn <= 2*numEff) | (asgn >= i & asgn <= numEff)
sel2 <- ifelse(sel2==T, F, T)
df <- matsOr[,sel]
X2 <- as.matrix( cbind(X[, sel2], df) )
if(i != 1){
reg2 <- lm.fit(X2, Y)
ssGE <- sum(reg2$residuals^2)
dfGE <- reg2$df.residual
ss[cont] <- ssGE; dfr[cont] <- dfGE
labTab[cont] <- paste(namEff[i], "Env", sep = ":")
cont <- cont + 1
} else {
if(object$Block == F) {
reg2 <- lm.fit(X2, Y)
ssGE <- sum(reg2$residuals^2)
dfGE <- reg2$df.residual
ss[cont] <- ssGE; dfr[cont] <- dfGE
labTab[cont] <- paste(namEff[i], "Env", sep = ":")
cont <- cont + 1
}
}
X3 <- as.matrix( X[, sel2] )
reg3 <- lm.fit(X3, Y)
ssG <- sum(reg3$residuals^2)
dfG <- reg3$df.residual
ss[cont] <- ssG; dfr[cont] <- dfG; labTab[cont] <- namEff[i]
cont <- cont + 1
}
reg.null <- lm(Y ~ 1)
totss <- deviance(reg.null)
totdf <- reg.null$df.residual
ss[cont] <- totss; dfr[cont] <- totdf
ss <- diff(ss); dfr <- diff(dfr)
ss <- c(rev(ss), rss); dfr <- c(rev(dfr), resdf)
labTab <- c("Environment", rev(labTab))
labTab[labTab=="Block"] <- "Env:Block"
ms <- ss/dfr
if(is.null(MSEor)){
MSE <- ms[length(ms)]
} else {
MSE <- MSEor
ms[length(ms)] <- MSE
}
if(!is.null(dfrOr)){
dfr1 <- dfrOr
dfr[length(dfr)] <- dfrOr
ss[length(ss)] <- NA
} else {
dfr1 <- dfr[length(dfr)]
}
f <- ms/MSE
P <- pf(f, dfr, dfr1, lower.tail = FALSE)
table <- data.frame(dfr, ss, ms, f, P)
table[length(P), 4:5] <- NA
colnames(table) <- c("Df","Sum Sq", "Mean Sq", "F value", "Pr(>F)")
row.names(table) <- labTab
structure(table, heading = c("Analysis of Variance Table\n",
paste("Response:", deparse(formula(object)[[2L]]))),
class = c("anova", "data.frame"))
} else {
rss <- c()
fit <- object
asgn <- fit$assign
X <- fit$modMatrix
coefs <- fit$coefficients
y <- fit$response
ngroup <- length(levels(factor(fit$assign)))
rss[1] <- deviance(lm(y ~ 1))
for(i in 1:ngroup){
val <- fit$assign <= i
exp <- X[,val] %*% as.matrix(coefs[val])
res <- y - exp
rss[i+1] <- sum(res^2)
}
rss[i + 1] <- 0
ss <- rss[1:ngroup] - rss[2:(ngroup+1)]
ss <- c(rss[1], ss)
df <- c(lengths(split(asgn, asgn)), fit$df.residual)
tlabels <- object$namEff
if(fit$df.residual == 0){
ss <- ss[-length(ss)]
df <- df[-length(df)]
tlabels <- object$namEff[-length(object$namEff)]
}
ms <- ss/df
table <- data.frame(df, ss, ms)
f <- ms/MSE
P <- pf(f, df, dfr, lower.tail = FALSE)
table <- data.frame(df, ss, ms, dfr, f, P)
dimnames(table) <- list(c(tlabels),
c("Df","Sum Sq", "Mean Sq", "Den df", "F value", "Pr(>F)"))
if(attr(object$terms,"intercept")) table <- table[-1, ]
structure(table, heading = c("Analysis of Variance Table\n",
paste("Response:", deparse(formula(object)[[2L]]))),
class = c("anova", "data.frame"))
table
}
}
predict.diallel <- function(object, ...){
fitted(object)
} |
LPDMRSortInferenceApprox <- function(performanceTable, criteriaMinMax, categoriesRanks, assignments, majorityRules = c("M","V","D","v","d","dV","Dv","dv"), alternativesIDs = NULL, criteriaIDs = NULL, timeLimit = 60, populationSize = 20, mutationProb = 0.1){
if (!(is.matrix(performanceTable) || is.data.frame(performanceTable)))
stop("performanceTable should be a matrix or a data frame")
if(is.null(colnames(performanceTable)))
stop("performanceTable columns should be named")
if (!(is.vector(assignments)))
stop("assignments should be a vector")
if(is.null(names(assignments)))
stop("assignments should be named")
if (!(is.vector(criteriaMinMax)))
stop("criteriaMinMax should be a vector")
if(!all(sort(colnames(performanceTable)) == sort(names(criteriaMinMax))))
stop("criteriaMinMax should be named as the columns of performanceTable")
if (!(is.vector(categoriesRanks)))
stop("categoriesRanks should be a vector")
if(is.null(names(categoriesRanks)))
stop("categoriesRanks should be named")
if(!all(assignments %in% names(categoriesRanks)))
stop("some of the assignments reference a category which does not exist in categoriesRanks")
if(!all(sort(categoriesRanks) == 1:length(categoriesRanks)))
stop("categoriesRanks should contain a permutation of the category indices (from 1 to the number of categories)")
if (!is.character(majorityRules))
stop("majorityRules should be a character, a string of characters, or a vector of strings of characters")
else if (!(all(majorityRules %in% c("M","V","D","v","d","dV","Dv","dv"))))
stop("majorityRules needs to take values in {'M','V','D','v','d','dV','Dv','dv'}")
if (!(is.null(timeLimit)))
{
if(!is.numeric(timeLimit))
stop("timeLimit should be numeric")
if(timeLimit <= 0)
stop("timeLimit should be strictly positive")
}
if (!(is.null(populationSize)))
{
if(!is.numeric(populationSize))
stop("populationSize should be numeric")
if(populationSize < 10)
stop("populationSize should be at least 10")
}
if (!(is.null(mutationProb)))
{
if(!is.numeric(mutationProb))
stop("mutationProb should be numeric")
if(mutationProb < 0 || mutationProb > 1)
stop("mutationProb should be between 0 and 1")
}
if (!(is.null(alternativesIDs) || is.vector(alternativesIDs)))
stop("alternativesIDs should be a vector")
if (!(is.null(criteriaIDs) || is.vector(criteriaIDs)))
stop("criteriaIDs should be a vector")
if (!is.null(alternativesIDs)){
performanceTable <- performanceTable[alternativesIDs,]
assignments <- assignments[names(assignments) %in% alternativesIDs]
}
if (!is.null(criteriaIDs)){
performanceTable <- performanceTable[,criteriaIDs]
criteriaMinMax <- criteriaMinMax[criteriaIDs]
}
if (is.null(dim(performanceTable)))
stop("less than 2 criteria or 2 alternatives")
if (length(assignments) == 0)
stop("assignments is empty or the provided alternativesIDs have filtered out everything from within")
numAlt <- dim(performanceTable)[1]
numCrit <- dim(performanceTable)[2]
numCat <- length(categoriesRanks)
minEvaluations <- apply(performanceTable, 2, min)
maxEvaluations <- apply(performanceTable, 2, max)
getCategory <- function(alternativePerformances, criteriaWeights, majorityThreshold, profilesPerformances, vetoPerformances, dictatorPerformances, majorityRule, criteriaMinMax){
for (k in (numCat-1):1)
{
weightedSum <- 0
for (crit in names(criteriaMinMax))
{
if (criteriaMinMax[crit] == "min")
{
if (alternativePerformances[crit] %<=% profilesPerformances[k,crit])
weightedSum <- weightedSum + criteriaWeights[crit]
}
else
{
if (alternativePerformances[crit] %>=% profilesPerformances[k,crit])
weightedSum <- weightedSum + criteriaWeights[crit]
}
}
vetoActive <- FALSE
if(majorityRule %in% c("V","v","dV","Dv","dv"))
{
for (crit in names(criteriaMinMax))
{
if (criteriaMinMax[crit] == "min")
{
if (alternativePerformances[crit] %>=% vetoPerformances[k,crit])
{
vetoActive <- TRUE
break
}
}
else
{
if (alternativePerformances[crit] %<=% vetoPerformances[k,crit])
{
vetoActive <- TRUE
break
}
}
}
}
dictatorActive <- FALSE
if(majorityRule %in% c("D","d","dV","Dv","dv"))
{
for (crit in names(criteriaMinMax))
{
if (criteriaMinMax[crit] == "min")
{
if (alternativePerformances[crit] %<=% dictatorPerformances[k,crit])
{
dictatorActive <- TRUE
break
}
}
else
{
if (alternativePerformances[crit] %>=% dictatorPerformances[k,crit])
{
dictatorActive <- TRUE
break
}
}
}
}
if(majorityRule == 'M')
{
if(weightedSum < majorityThreshold)
return(k + 1)
}
else if(majorityRule == 'V')
{
if(weightedSum < majorityThreshold || vetoActive)
return(k + 1)
}
else if(majorityRule == 'D')
{
if(weightedSum < majorityThreshold && !dictatorActive)
return(k + 1)
}
else if(majorityRule == 'v')
{
if(weightedSum < majorityThreshold || (vetoActive && !dictatorActive))
return(k + 1)
}
else if(majorityRule == 'd')
{
if(weightedSum < majorityThreshold && (!dictatorActive || vetoActive))
return(k + 1)
}
if(majorityRule == 'dV')
{
if((weightedSum < majorityThreshold && !dictatorActive) || vetoActive)
return(k + 1)
}
if(majorityRule == 'Dv')
{
if(!dictatorActive && (vetoActive || weightedSum < majorityThreshold))
return(k + 1)
}
if(majorityRule == 'dv')
{
if((vetoActive && !dictatorActive) || (weightedSum < majorityThreshold && ((vetoActive && dictatorActive) || (!vetoActive && !dictatorActive))))
return(k + 1)
}
}
return(1)
}
InitializePopulation <- function()
{
population <- list()
for(i in 1:populationSize)
{
values <- c(0,sort(runif(numCrit-1,0,1)),1)
weights <- sapply(1:numCrit, function(i) return(values[i+1]-values[i]))
names(weights) <- colnames(performanceTable)
majority <- runif(1,0.5,1)
majorityRule <- sample(majorityRules, 1)
profiles <- NULL
for(j in 1:numCrit)
{
if(criteriaMinMax[j] == 'max')
profiles <- cbind(profiles,sort(runif(numCat - 1,minEvaluations[j],maxEvaluations[j]), decreasing = TRUE))
else
profiles <- cbind(profiles,sort(runif(numCat - 1,minEvaluations[j],maxEvaluations[j])))
}
colnames(profiles) <- colnames(performanceTable)
vetoes <- NULL
for(j in 1:numCrit)
{
if(criteriaMinMax[j] == 'max')
vetoes <- cbind(vetoes,rep(minEvaluations[j] - 1, numCat - 1))
else
vetoes <- cbind(vetoes,rep(maxEvaluations[j] + 1, numCat - 1))
}
rownames(vetoes) <- c()
colnames(vetoes) <- colnames(performanceTable)
dictators <- NULL
for(j in 1:numCrit)
{
if(criteriaMinMax[j] == 'max')
dictators <- cbind(dictators,rep(maxEvaluations[j] + 1, numCat - 1))
else
dictators <- cbind(dictators,rep(minEvaluations[j] - 1, numCat - 1))
}
rownames(dictators) <- c()
colnames(dictators) <- colnames(performanceTable)
population[[length(population)+1]] <- list(majorityThreshold = majority, criteriaWeights = weights, majorityRule = majorityRule, profilesPerformances = profiles, vetoPerformances = vetoes, dictatorPerformances = dictators)
}
return(population)
}
Fitness <- function(individual)
{
ok <- 0
for (alternative in names(assignments))
{
category <- getCategory(performanceTable[alternative,],individual$criteriaWeights, individual$majorityThreshold, individual$profilesPerformances, individual$vetoPerformances, individual$dictatorPerformances, individual$majorityRule, criteriaMinMax)
if(category == categoriesRanks[assignments[alternative]])
ok <- ok + 1
}
return(ok/length(assignments))
}
Reproduce <- function(parents){
children <- list()
numPairs <- as.integer(length(parents)/2)
pairings <- matrix(sample(1:length(parents),numPairs*2),numPairs,2)
for(i in 1:numPairs)
{
parent1 <- parents[[pairings[i,1]]]
parent2 <- parents[[pairings[i,2]]]
criteria <- sample(colnames(performanceTable), numCrit)
pivot <- runif(1,1,numCrit - 1)
profiles1 <- matrix(rep(0,numCrit*(numCat - 1)),numCat - 1,numCrit)
profiles2 <- matrix(rep(0,numCrit*(numCat - 1)),numCat - 1,numCrit)
vetoes1 <- matrix(rep(0,numCrit*(numCat - 1)),numCat - 1,numCrit)
vetoes2 <- matrix(rep(0,numCrit*(numCat - 1)),numCat - 1,numCrit)
dictators1 <- matrix(rep(0,numCrit*(numCat - 1)),numCat - 1,numCrit)
dictators2 <- matrix(rep(0,numCrit*(numCat - 1)),numCat - 1,numCrit)
colnames(profiles1) <- colnames(performanceTable)
colnames(profiles2) <- colnames(performanceTable)
colnames(vetoes1) <- colnames(performanceTable)
colnames(vetoes2) <- colnames(performanceTable)
colnames(dictators1) <- colnames(performanceTable)
colnames(dictators2) <- colnames(performanceTable)
for(k in 1:(numCat - 1))
for(j in 1:numCrit)
{
if(j <= pivot)
{
profiles1[k,criteria[j]] <- parent1$profilesPerformances[k,criteria[j]]
profiles2[k,criteria[j]] <- parent2$profilesPerformances[k,criteria[j]]
vetoes1[k,criteria[j]] <- parent1$vetoPerformances[k,criteria[j]]
vetoes2[k,criteria[j]] <- parent2$vetoPerformances[k,criteria[j]]
dictators1[k,criteria[j]] <- parent1$dictatorPerformances[k,criteria[j]]
dictators2[k,criteria[j]] <- parent2$dictatorPerformances[k,criteria[j]]
}
else
{
profiles1[k,criteria[j]] <- parent2$profilesPerformances[k,criteria[j]]
profiles2[k,criteria[j]] <- parent1$profilesPerformances[k,criteria[j]]
vetoes1[k,criteria[j]] <- parent2$vetoPerformances[k,criteria[j]]
vetoes2[k,criteria[j]] <- parent1$vetoPerformances[k,criteria[j]]
dictators1[k,criteria[j]] <- parent2$dictatorPerformances[k,criteria[j]]
dictators2[k,criteria[j]] <- parent1$dictatorPerformances[k,criteria[j]]
}
}
children[[length(children)+1]] <- list(majorityThreshold = parent1$majorityThreshold, criteriaWeights = parent1$criteriaWeights, majorityRule = parent1$majorityRule, profilesPerformances = parent1$profilesPerformances, vetoPerformances = parent1$vetoPerformances, dictatorPerformances = parent1$dictatorPerformances)
children[[length(children)+1]] <- list(majorityThreshold = parent2$majorityThreshold, criteriaWeights = parent2$criteriaWeights, majorityRule = parent2$majorityRule, profilesPerformances = parent2$profilesPerformances, vetoPerformances = parent2$vetoPerformances, dictatorPerformances = parent2$dictatorPerformances)
children[[length(children)+1]] <- list(majorityThreshold = parent1$majorityThreshold, criteriaWeights = parent1$criteriaWeights, majorityRule = parent1$majorityRule, profilesPerformances = parent2$profilesPerformances, vetoPerformances = parent2$vetoPerformances, dictatorPerformances = parent2$dictatorPerformances)
children[[length(children)+1]] <- list(majorityThreshold = parent2$majorityThreshold, criteriaWeights = parent2$criteriaWeights, majorityRule = parent2$majorityRule, profilesPerformances = parent1$profilesPerformances, vetoPerformances = parent1$vetoPerformances, dictatorPerformances = parent1$dictatorPerformances)
children[[length(children)+1]] <- list(majorityThreshold = parent1$majorityThreshold, criteriaWeights = parent1$criteriaWeights, majorityRule = parent1$majorityRule, profilesPerformances = profiles1, vetoPerformances = vetoes1, dictatorPerformances = dictators1)
children[[length(children)+1]] <- list(majorityThreshold = parent1$majorityThreshold, criteriaWeights = parent1$criteriaWeights, majorityRule = parent1$majorityRule, profilesPerformances = profiles2, vetoPerformances = vetoes2, dictatorPerformances = dictators2)
children[[length(children)+1]] <- list(majorityThreshold = parent2$majorityThreshold, criteriaWeights = parent2$criteriaWeights, majorityRule = parent2$majorityRule, profilesPerformances = profiles1, vetoPerformances = vetoes1, dictatorPerformances = dictators1)
children[[length(children)+1]] <- list(majorityThreshold = parent2$majorityThreshold, criteriaWeights = parent2$criteriaWeights, majorityRule = parent2$majorityRule, profilesPerformances = profiles2, vetoPerformances = vetoes2, dictatorPerformances = dictators2)
}
numChildren <- length(children)
for(i in 1:numChildren)
{
if(runif(1,0,1) < mutationProb)
{
choicesMatrix <- list(c("V","D"),c("M","v","dV"),c("M","d","Dv"),c("V","Dv","dv"),c("D","dV","dv"),c("V","d","dv"),c("D","v","dv"),c("d","v","Dv","dV"))
names(choicesMatrix) <- c("M","V","D","v","d","dV","Dv","dv")
oldMajorityRule <- children[[i]]$majorityRule
choices <- choicesMatrix[[oldMajorityRule]][choicesMatrix[[oldMajorityRule]] %in% majorityRules]
if(length(choices) != 0)
children[[i]]$majorityRule <- sample(choices, 1)
}
if(runif(1,0,1) < mutationProb)
{
children[[i]]$majorityThreshold <- runif(1,0.5,1)
}
for(j1 in 1:(numCrit-1))
{
for(j2 in (j1+1):numCrit)
{
if(runif(1,0,1) < mutationProb)
{
criteria <- c(colnames(performanceTable)[j1],colnames(performanceTable)[j2])
minVal <- 0 - children[[i]]$criteriaWeights[criteria[1]]
maxVal <- children[[i]]$criteriaWeights[criteria[2]]
tradeoff <- runif(1,minVal,maxVal)
children[[i]]$criteriaWeights[criteria[1]] <- children[[i]]$criteriaWeights[criteria[1]] + tradeoff
children[[i]]$criteriaWeights[criteria[2]] <- children[[i]]$criteriaWeights[criteria[2]] - tradeoff
}
}
}
for(k in 1:(numCat - 1))
{
for(criterion in colnames(performanceTable))
{
if(runif(1,0,1) < mutationProb)
{
maxVal <- maxEvaluations[criterion]
minVal <- minEvaluations[criterion]
if(k < (numCat - 1))
{
if(criteriaMinMax[criterion] == 'max')
minVal <- children[[i]]$profilesPerformances[k+1,criterion]
else
maxVal <- children[[i]]$profilesPerformances[k+1,criterion]
}
if(k > 1)
{
if(criteriaMinMax[criterion] == 'max')
maxVal <- children[[i]]$profilesPerformances[k-1,criterion]
else
minVal <- children[[i]]$profilesPerformances[k-1,criterion]
}
if(criteriaMinMax[criterion] == 'max')
{
if(children[[i]]$vetoPerformances[k,criterion] %>=% minVal)
minVal <- children[[i]]$vetoPerformances[k,criterion] + 0.0000000001
if(children[[i]]$dictatorPerformances[k,criterion] %<=% maxVal)
maxVal <- children[[i]]$dictatorPerformances[k,criterion] - 0.0000000001
}
else
{
if(children[[i]]$vetoPerformances[k,criterion] %<=% maxVal)
maxVal <- children[[i]]$vetoPerformances[k,criterion] - 0.0000000001
if(children[[i]]$dictatorPerformances[k,criterion] %>=% minVal)
minVal <- children[[i]]$dictatorPerformances[k,criterion] + 0.0000000001
}
children[[i]]$profilesPerformances[k,criterion] <- runif(1,minVal,maxVal)
}
}
}
for(k in 1:(numCat - 1))
{
for(criterion in colnames(performanceTable))
{
if(runif(1,0,1) < mutationProb)
{
maxVal <- maxEvaluations[criterion]
if(criteriaMinMax[criterion] == 'min')
maxVal <- maxEvaluations[criterion] + 1
minVal <- minEvaluations[criterion]
if(criteriaMinMax[criterion] == 'max')
minVal <- minEvaluations[criterion] - 1
if(k < (numCat - 1))
{
if(criteriaMinMax[criterion] == 'max')
minVal <- children[[i]]$vetoPerformances[k+1,criterion]
else
maxVal <- children[[i]]$vetoPerformances[k+1,criterion]
}
if(k > 1)
{
if(criteriaMinMax[criterion] == 'max')
maxVal <- children[[i]]$vetoPerformances[k-1,criterion]
else
minVal <- children[[i]]$vetoPerformances[k-1,criterion]
}
if(criteriaMinMax[criterion] == 'max')
{
if(children[[i]]$profilesPerformances[k,criterion] %<=% maxVal)
maxVal <- children[[i]]$profilesPerformances[k,criterion] - 0.0000000001
}
else
{
if(children[[i]]$profilesPerformances[k,criterion] %>=% minVal)
minVal <- children[[i]]$profilesPerformances[k,criterion] + 0.0000000001
}
children[[i]]$vetoPerformances[k,criterion] <- runif(1,minVal,maxVal)
}
}
}
for(k in 1:(numCat - 1))
{
for(criterion in colnames(performanceTable))
{
if(runif(1,0,1) < mutationProb)
{
maxVal <- maxEvaluations[criterion]
if(criteriaMinMax[criterion] == 'max')
maxVal <- maxEvaluations[criterion] + 1
minVal <- minEvaluations[criterion]
if(criteriaMinMax[criterion] == 'min')
minVal <- minEvaluations[criterion] - 1
if(k < (numCat - 1))
{
if(criteriaMinMax[criterion] == 'max')
minVal <- children[[i]]$dictatorPerformances[k+1,criterion]
else
maxVal <- children[[i]]$dictatorPerformances[k+1,criterion]
}
if(k > 1)
{
if(criteriaMinMax[criterion] == 'max')
maxVal <- children[[i]]$dictatorPerformances[k-1,criterion]
else
minVal <- children[[i]]$dictatorPerformances[k-1,criterion]
}
if(criteriaMinMax[criterion] == 'max')
{
if(children[[i]]$profilesPerformances[k,criterion] %>=% minVal)
minVal <- children[[i]]$profilesPerformances[k,criterion] + 0.0000000001
}
else
{
if(children[[i]]$profilesPerformances[k,criterion] %<=% maxVal)
maxVal <- children[[i]]$profilesPerformances[k,criterion] - 0.0000000001
}
children[[i]]$dictatorPerformances[k,criterion] <- runif(1,minVal,maxVal)
}
}
}
}
return(children)
}
startTime <- Sys.time()
population <- InitializePopulation()
bestIndividual <- list(fitness = 0)
ct <- 0
while(as.double(difftime(Sys.time(), startTime, units = 'secs')) < timeLimit)
{
evaluations <- unlist(lapply(population, Fitness))
maxFitness <- max(evaluations)
if(maxFitness >= bestIndividual$fitness)
{
bestIndividual <- population[[match(maxFitness,evaluations)]]
bestIndividual$fitness <- maxFitness
}
if(as.double(difftime(Sys.time(), startTime, units = 'secs')) / 5 > ct)
{
ct <- ct + 1
}
if(bestIndividual$fitness == 1)
break
if(length(population) > populationSize)
{
evaluations <- evaluations^2
newPopulation <- list()
newPopulation[[length(newPopulation)+1]] <- bestIndividual
i <- 1
while(length(newPopulation) < populationSize)
{
if(runif(1,0,1) <= evaluations[i])
{
evaluations[i] <- -1
newPopulation[[length(newPopulation)+1]] <- population[[i]]
}
i <- i + 1
if(i > length(population))
i <- 1
}
population <- newPopulation
}
population <- Reproduce(population)
}
bestIndividual$profilesPerformances <- rbind(bestIndividual$profilesPerformances,rep(NA,numCrit))
bestIndividual$vetoPerformances <- rbind(bestIndividual$vetoPerformances,rep(NA,numCrit))
bestIndividual$dictatorPerformances <- rbind(bestIndividual$dictatorPerformances,rep(NA,numCrit))
rownames(bestIndividual$profilesPerformances) <- names(sort(categoriesRanks))
rownames(bestIndividual$vetoPerformances) <- rownames(bestIndividual$profilesPerformances)
rownames(bestIndividual$dictatorPerformances) <- rownames(bestIndividual$profilesPerformances)
if(bestIndividual$majorityRule %in% c("V","v","d","dV","Dv","dv"))
{
used <- LPDMRSortIdentifyUsedVetoProfiles(performanceTable, assignments, sort(categoriesRanks), criteriaMinMax, bestIndividual$majorityThreshold, bestIndividual$criteriaWeights, bestIndividual$profilesPerformances, bestIndividual$vetoPerformances, bestIndividual$dictatorPerformances, bestIndividual$majorityRule, alternativesIDs, criteriaIDs)
for (k in (numCat-1):1)
{
cat <- names(categoriesRanks)[categoriesRanks == k]
for (j in 1:numCrit)
{
if (!used[cat,j])
bestIndividual$vetoPerformances[cat,j] <- NA
}
}
}
if(bestIndividual$majorityRule %in% c("D","v","d","dV","Dv","dv"))
{
used <- LPDMRSortIdentifyUsedDictatorProfiles(performanceTable, assignments, sort(categoriesRanks), criteriaMinMax, bestIndividual$majorityThreshold, bestIndividual$criteriaWeights, bestIndividual$profilesPerformances, bestIndividual$dictatorPerformances, bestIndividual$vetoPerformances, bestIndividual$majorityRule, alternativesIDs, criteriaIDs)
for (k in (numCat-1):1)
{
cat <- names(categoriesRanks)[categoriesRanks == k]
for (j in 1:numCrit)
{
if (!used[cat,j])
bestIndividual$dictatorPerformances[cat,j] <- NA
}
}
}
return(bestIndividual)
} |
multilinestring <- function(..., fmt = 16, third = "z") {
UseMethod("multilinestring")
}
multilinestring.character <- function(..., fmt = 16, third = "z") {
pts <- list(...)
if (grepl("empty", pts[[1]], ignore.case = TRUE)) {
return('MULTILINESTRING EMPTY')
} else {
check_str(pts)
}
}
multilinestring.data.frame <- function(..., fmt = 16, third = "z") {
pts <- list(...)
fmtcheck(fmt)
str <- lapply(pts, function(v) {
sprintf("(%s)", paste0(apply(v, 1, function(z){
p0c(str_trim_(format(z, nsmall = fmt, trim = TRUE)))
}), collapse = ", "))
})
len <- unique(vapply(pts, NCOL, numeric(1)))
sprint_multil(str, len, third)
}
multilinestring.matrix <- function(..., fmt = 16, third = "z") {
pts <- list(...)
fmtcheck(fmt)
str <- lapply(pts, function(v) {
sprintf("(%s)", paste0(apply(v, 1, function(z){
p0c(str_trim_(format(z, nsmall = fmt, trim = TRUE)))
}), collapse = ", "))
})
len <- unique(vapply(pts, NCOL, numeric(1)))
sprint_multil(str, len, third)
}
multilinestring.list <- function(..., fmt = 16, third = "z") {
pts <- list(...)
fmtcheck(fmt)
pts <- un_nest(pts)
str <- lapply(pts, function(z) {
if (length(z) > 1 && sapply(z, class)[1] != "numeric") {
inparens(paste0(lapply(z, make1multipoly, fmt = fmt), collapse = ", "))
} else {
make1multilinestr(z, fmt)
}
})
len <- unique(vapply(pts, function(z) unique(vapply(z, length, numeric(1))),
numeric(1)))
sprint_multil(str, len, third)
}
sprint_multil <- function(x, len, third) {
if (len == 3) {
sprintf('MULTILINESTRING %s(%s)', pick3(third), paste0(x, collapse = ", "))
} else if (len == 4) {
sprintf('MULTILINESTRING ZM(%s)', paste0(x, collapse = ", "))
} else {
sprintf('MULTILINESTRING (%s)', paste0(x, collapse = ", "))
}
}
sprint <- function(type, str) {
sprintf('%s (%s)', type, str)
}
make1multilinestr <- function(m, fmt) {
inparens(paste0(lapply(m, function(b) {
paste0(str_trim_(format(b, nsmall = fmt, trim = TRUE)), collapse = " ")
}), collapse = ", ")
)
} |
aiFun <- function(model = NULL, AI.vec = NULL, inverse = TRUE, Dimnames=NULL)
{
if(!is.null(model)){
AI.vec <- model$ai
}
dimAI <- sqrt(length(AI.vec) * 2 + 0.25) - 0.5
AI <- matrix(0, dimAI, dimAI)
AI[which(upper.tri(AI, diag = TRUE) == TRUE)] <- AI.vec
AI[which(lower.tri(AI) == TRUE)]<-t(AI)[which(lower.tri(AI) == TRUE)]
if(inverse == FALSE) AI <- solve(AI)
if(is.null(Dimnames)){Dimnames <- names(model$gammas)}
dimnames(AI) <- list(Dimnames, Dimnames)
AI
} |
gauss.copula <-
function(rho,U,V){
qU <- qnorm(U,0,1)
qV <- qnorm(V,0,1)
exp((-rho^2*(sum(qU^2)+sum(qV^2))+2*rho*sum(qU*qV))/(2*(1-rho^2)))/(sqrt(1-rho^2))
} |
boot.sd2.sub <-
function(x.sub, x, weight.sub, weight, k, alpha, nsim,
boot.index=c("r.cha", "r.fgt"), gamma){
if (boot.index == "r.cha"){
r.cha1 <- r.cha.sub(x.sub, x, weight.sub, weight, k, alpha)
n <- length(x.sub)
Rbb <- NULL
for(i in 1:nsim){
s <- sample(1:n, n, replace=T)
ss <- x.sub[s]
wss <- weight.sub[s]
rownames(ss) <-NULL
R <-r.cha.sub(ss, x,wss, weight, k, alpha)
Rb <-R
Rbb=rbind(Rb,Rbb)
}
r.se <- sd(Rbb)
ci1_up <- r.cha1 + qnorm(gamma)*r.se
ci1_low <- r.cha1 - qnorm(gamma)*r.se
ci2_up <- quantile(Rbb,1-(1-gamma)/2)
ci2_low <- quantile(Rbb,(1-gamma)/2)
tab <- rbind(c(ci1_low, r.cha1, ci1_up), c(ci2_low, r.cha1, ci2_up))
colnames(tab) <- c("ci.low", "r.cha", "ci.up")
rownames(tab) <- c("norm", "quantile")
outlist=list(se.r.cha = r.se, summary = tab, boot.ind = as.vector(Rbb))
}
if (boot.index == "r.fgt"){
r.fgt1 <- r.fgt.sub(x.sub, x, weight.sub, weight, k, alpha)
n <- length(x.sub)
Rbb <- NULL
for(i in 1:nsim){
s <- sample(1:n, n, replace = T)
ss <- x.sub[s]
wss <- weight.sub[s]
rownames(ss) <- NULL
R <- r.fgt.sub(ss, x, wss, weight, k, alpha)
Rb <- R
Rbb <- rbind(Rb,Rbb)
}
r.se <-sd(Rbb)
ci1_up <- r.fgt1 + qnorm(gamma)*r.se
ci1_low <- r.fgt1 - qnorm(gamma)*r.se
ci2_up <- quantile(Rbb,1-(1-gamma)/2)
ci2_low <- quantile(Rbb,(1-gamma)/2)
tab <- rbind(c(ci1_low, r.fgt1, ci1_up), c(ci2_low, r.fgt1, ci2_up))
colnames(tab) <- c("ci.low", "r.fgt", "ci.up")
rownames(tab) <- c("norm", "quantile")
outlist=list(se.r.fgt = r.se, summary = tab, boot.ind = as.vector(Rbb))
}
return(outlist)
} |
test_that("Inverse Gamma distribution", {
dist <- dist_inverse_gamma(3, 2)
expect_equal(format(dist), "InvGamma(3, 0.5)")
skip_if_not_installed("actuar", "2.0.0")
expect_equal(quantile(dist, 0.1), actuar::qinvgamma(0.1, 3, 2))
expect_equal(quantile(dist, 0.5), actuar::qinvgamma(0.5, 3, 2))
expect_equal(density(dist, 0), actuar::dinvgamma(0, 3, 2))
expect_equal(density(dist, 3), actuar::dinvgamma(3, 3, 2))
expect_equal(cdf(dist, 0), actuar::pinvgamma(0, 3, 2))
expect_equal(cdf(dist, 3), actuar::pinvgamma(3, 3, 2))
expect_equal(cdf(dist, quantile(dist, 0.4)), 0.4, tolerance = 1e-3)
expect_equal(mean(dist), (1/2) / (3 - 1))
expect_equal(median(dist), actuar::qinvgamma(0.5, 3, 2))
expect_equal(median(dist[[1]]), actuar::qinvgamma(0.5, 3, 2))
expect_equal(variance(dist), (1/2)^2/((3-1)^2*(3-2)))
}) |
club <- function(X,
dataCols,
core,
time_trim,
HACmethod = c('FQSB', 'AQSB'),
cstar = 0,
cstar_method = c('fixed', 'incremental'),
cstar_increment = 0.1,
cstar_cap = 3){
HACmethod <- match.arg(HACmethod)
cstar_method <- match.arg(cstar_method)
if(cstar_increment <= 0) cstar_method <- 'fixed'
X$row <- seq_len(nrow(X))
unitsNoCore <- X[-core, ]
while(TRUE){
nr <- nrow(unitsNoCore)
tvalue <- vector(length=nr)
for (k in seq_len(nr)){
H <- computeH( X[ c(core, unitsNoCore$row[k]), dataCols ])
tvalue[k] <- estimateMod(H, time_trim, HACmethod = HACmethod)['tvalue']
}
ind <- which(tvalue > cstar)
clubCandidates_id <- unitsNoCore[ind, 'id']
clubCandidates_row <- unitsNoCore[ind, 'row']
clubId <- c(X[core, 'id'], clubCandidates_id)
clubRows <- c(core, clubCandidates_row)
H <- computeH(X[clubRows, dataCols])
mod <- estimateMod(H, time_trim, HACmethod = HACmethod)
if( (mod['tvalue'] > -1.65) | (cstar_method=='fixed') ){
break
} else{
if(cstar<= cstar_cap){
cstar <- cstar + cstar_increment
} else{
clubId <- X[core, 'id']
clubRows <- core
break
}
}
}
return( list(id = clubId,
rows = clubRows,
model = mod,
cstar = cstar) )
} |
topicLasso <- function(formula, data, stmobj=NULL, subset=NULL,
omit.var=NULL, family="gaussian",
main="Topic Effects on Outcome",
xlab=expression("Lower Outcome Higher Outcome"),
labeltype=c("prob", "frex", "lift", "score"),seed=02138,
xlim=c(-4,4), standardize=FALSE, nfolds=20, ...) {
X <- model.matrix(formula, data)
pvarnames <- colnames(X)
p <- ncol(X)
z <- stmobj
X <- cbind(X,z$theta)
if(colnames(X)[1]=="(Intercept)") {
p <- p - 1
X <- X[,-1]
pvarnames <- pvarnames[-1]
}
mframe <- model.frame(formula,data)
y <- model.response(mframe)
if(!is.null(subset)) {
X <- X[subset,]
y <- y[subset]
}
X <- Matrix(X)
if(!is.null(seed)) set.seed(seed)
labeltype <- match.arg(labeltype)
if(!z$settings$kappa$LDAbeta) labeltype <- "topics"
topiclabs <- labelTopics(z)
topiclabs <- apply(topiclabs[[labeltype]], 1, commas)
topiclabs <- sprintf("Topic %i: %s", 1:length(topiclabs), topiclabs)
varnames <- c(pvarnames, topiclabs)
linmod <- glmnet::cv.glmnet(x=X,y=y, family=family, standardize=standardize, nfolds=nfolds, ...)
loadings <- coef(linmod)[-1]
posind <- which(loadings>0)
if(length(posind!=0)) {
cat(c("Positive Effect \n",sprintf("%s \n",
varnames[posind])))
} else {
cat("No Positive Effects. \n")
}
negind <- which(loadings<0)
if(length(negind!=0)) {
cat(c("Negative Effect \n",sprintf("%s \n",
varnames[negind])))
} else {
cat("No Negative Effects. \n")
}
coefind <- which(loadings!=0)
drop <- c()
if(!is.null(omit.var)) {
for(i in 1:length(omit.var)) {
drop <- c(drop,agrep(omit.var[i], varnames))
}
coefind <- coefind[!(coefind %in% drop)]
}
if(length(coefind)!=0) {
coefval <- loadings[coefind]
labels <- varnames[coefind]
labels <- labels[order(coefval)]
values <- sort(coefval)
plot(x=values, y=1:length(values), pch=19, main=main,
xlim=xlim, ylab="", type="p", xlab=xlab,
ylim=c(-1, length(values)+1),yaxt="n", bty="n")
text(values, 1:length(values), labels, pos=2)
segments(0, -1, 0, length(values)+1,lty=2)
} else {
cat("No Non Zero Loadings")
}
return(invisible(linmod))
} |
makeRLearner.multilabel.randomForestSRC = function() {
makeRLearnerMultilabel(
cl = "multilabel.randomForestSRC",
package = "randomForestSRC",
par.set = makeParamSet(
makeIntegerLearnerParam(id = "ntree", default = 1000L, lower = 1L),
makeDiscreteLearnerParam(id = "bootstrap", default = "by.root",
values = c("by.root", "by.node", "none", "by.user")),
makeIntegerLearnerParam(id = "mtry", default = NULL, lower = 1L,
special.vals = list(NULL)),
makeIntegerLearnerParam(id = "nodesize", lower = 1L, default = NULL,
special.vals = list(NULL)),
makeIntegerLearnerParam(id = "nodedepth", default = NULL,
special.vals = list(NULL)),
makeDiscreteLearnerParam(id = "splitrule", default = NULL,
values = list("gini", "gini.unwt", "gini.hvwt", "random", NULL = NULL),
special.vals = list(NULL)),
makeIntegerLearnerParam(id = "nsplit", lower = 0L, default = 0L,
requires = quote(splitrule != "random")),
makeLogicalLearnerParam(id = "split.null", default = FALSE),
makeDiscreteLearnerParam(id = "importance", default = FALSE, tunable = FALSE,
values = list(`FALSE` = FALSE, `TRUE` = TRUE, "none", "permute", "random", "anti",
"permute.ensemble", "random.ensemble", "anti.ensemble")),
makeDiscreteLearnerParam(id = "na.action", default = "na.impute",
values = c("na.omit", "na.impute"), when = "both"),
makeIntegerLearnerParam(id = "nimpute", default = 1L, lower = 1L),
makeDiscreteLearnerParam(id = "proximity", default = FALSE, tunable = FALSE,
values = list("inbag", "oob", "all", `TRUE` = TRUE, `FALSE` = FALSE)),
makeIntegerLearnerParam(id = "sampsize", lower = 1L, default = NULL,
requires = quote(bootstrap == "by.root"), special.vals = list(NULL)),
makeDiscreteLearnerParam(id = "samptype", default = "swr", values = c("swr", "swor"),
requires = quote(bootstrap == "by.root")),
makeUntypedLearnerParam(id = "samp", requires = quote(bootstrap == "by.user")),
makeNumericVectorLearnerParam(id = "xvar.wt", lower = 0, default = NULL,
special.vals = list(NULL)),
makeLogicalLearnerParam(id = "forest", default = TRUE, tunable = FALSE),
makeDiscreteLearnerParam(id = "var.used", default = FALSE, tunable = FALSE,
values = list(`FALSE` = FALSE, "all.trees", "by.tree")),
makeDiscreteLearnerParam(id = "split.depth", default = FALSE, tunable = FALSE,
values = list(`FALSE` = FALSE, "all.trees", "by.tree")),
makeIntegerLearnerParam(id = "seed", default = NULL, upper = 0L,
tunable = FALSE, special.vals = list(NULL)),
makeLogicalLearnerParam(id = "do.trace", default = FALSE, tunable = FALSE, when = "both"),
makeLogicalLearnerParam(id = "membership", default = FALSE, tunable = FALSE),
makeLogicalLearnerParam(id = "statistics", default = FALSE, tunable = FALSE),
makeLogicalLearnerParam(id = "tree.err", default = FALSE, tunable = FALSE),
makeUntypedLearnerParam(id = "coerce.factor", default = NULL, special.vals = list(NULL))
),
par.vals = list(na.action = "na.impute"),
properties = c("missings", "numerics", "factors", "prob", "weights"),
name = "Random Forest",
short.name = "rfsrc",
note = "`na.action` has been set to `na.impute` by default to allow missing data support.",
callees = "rfsrc"
)
}
trainLearner.multilabel.randomForestSRC = function(.learner, .task, .subset, .weights = NULL, ...) {
targets = getTaskTargetNames(.task)
f = as.formula(stri_paste("cbind(", stri_paste(targets, collapse = ",", sep = " "), ") ~ .", sep = ""))
d = getTaskData(.task, .subset, recode.target = "multilabel.factor")
randomForestSRC::rfsrc(f, data = d, case.wt = .weights, ...)
}
predictLearner.multilabel.randomForestSRC = function(.learner, .model, .newdata, ...) {
p = predict(.model$learner.model, newdata = .newdata, importance = "none", ...)
if (.learner$predict.type == "prob") {
return(sapply(p$classOutput, function(x) x$predicted[, 1]))
} else {
return(sapply(p$classOutput, function(x) as.logical(x$class)))
}
} |
read.fs.volume.nii <- function(filepath, flatten = FALSE, with_header=FALSE, drop_empty_dims=FALSE, do_rotate = FALSE, ...) {
nifti_img = filepath;
if (requireNamespace("oro.nifti", quietly = TRUE)) {
if(is.character(nifti_img)) {
nifti_img = oro.nifti::readNIfTI(nifti_img, ...);
}
if(! oro.nifti::is.nifti(nifti_img)) {
stop("Parameter 'nifti_img' is not a nifti instance from oro.nifti.");
}
if(!(nifti_img@magic == "n+1" | nifti_img@magic == "ni1")) {
stop(sprintf("Unknown NIFTI magic code '%s', file format not supported. Expected magic code 'n+1' or 'ni1'.\n", nifti_img@magic));
}
scale_data = FALSE;
if(nifti_img@scl_slope != 0.0) {
if(!(nifti_img@scl_slope == 1.0 & nifti_img@scl_inter == 0.0)) {
scale_data = TRUE;
}
}
if(scale_data) {
warning(sprintf("Detected that Nifti data needs scaling (@scl_slope=%.2f, @scl_inter=%.2f), but scaling not implemented yet.\n", nifti_img@scl_slope, nifti_img@scl_inter));
}
MRI_UCHAR = translate.mri.dtype("MRI_UCHAR");
MRI_INT = translate.mri.dtype("MRI_INT");
MRI_FLOAT = translate.mri.dtype("MRI_FLOAT");
MRI_SHORT = translate.mri.dtype("MRI_SHORT");
dti = nifti.dtype.info(nifti_img@datatype, nifti_img@bitpix);
dtype = dti$mri_dtype;
num_used_dimensions = nifti_img@dim_[1];
byte_swap = FALSE;
if(num_used_dimensions < 1L | num_used_dimensions > 7L) {
byte_swap = TRUE;
stop(sprintf("Byte-swapped Nifti images not supported yet.\n"));
}
num_frames = ifelse(num_used_dimensions < 4L, 1L, nifti_img@dim_[5]);
if(num_used_dimensions > 4L & nifti_img@dim_[6] > 1L) {
stop("Nifti images with more than 4 used dimensions not supported yet.");
}
if(nifti_img@dim_[2] < 0L) {
ncols = nifti_img@glmin;
} else {
ncols = nifti_img@dim_[2];
}
space_info = nifti.space.info(nifti_img@xyzt_units);
space_unit_factor = space_info$scaling;
time_info = nifti.time.info(nifti_img@xyzt_units);
time_unit_factor = time_info$scaling;
header = mghheader(c(ncols, nifti_img@dim_[3], nifti_img@dim_[4], num_frames), dtype);
header$internal$xsize = nifti_img@pixdim[2];
header$internal$ysize = nifti_img@pixdim[3];
header$internal$zsize = nifti_img@pixdim[4];
header$internal$tr = nifti_img@pixdim[5];
if(nifti_img@sform_code != 0L) {
vox2ras = rbind(nifti_img@srow_x, nifti_img@srow_y, nifti_img@srow_z, c(0, 0, 0, 1));
header = mghheader.update.from.vox2ras(header, vox2ras);
header$ras_good_flag = 1L;
} else if(nifti_img@qform_code != 0L) {
qb = nifti_img@quatern_b;
qc = nifti_img@quatern_c;
qd = nifti_img@quatern_d;
qa = 1.0 - (qb*qb + qc*qc + qd*qd);
if (qa < 1.0e-7) {
qa = 1.0 / sqrt(qb*qb + qc*qc + qd*qd);
qb = qa*qb;
qc = qa*qc;
qd = qa*qd;
qa = 0.0;
} else {
qa = sqrt(qa);
}
rot_mat = matrix(rep(0., 9), nrow=3L);
rot_mat[1,1] = qa*qa + qb*qb - qc*qc - qd*qd;
rot_mat[1,2] = 2.0 * qb * qc - 2.0 * qa * qd;
rot_mat[1,3] = 2.0 * qb * qd + 2.0 * qa * qc;
rot_mat[2,1] = 2.0 * qb * qc + 2.0 * qa * qd;
rot_mat[2,2] = qa*qa + qc*qc - qb*qb - qd*qd;
rot_mat[2,3] = 2.0 * qc * qd - 2.0 * qa * qb;
rot_mat[3,1] = 2.0 * qb * qd - 2.0 * qa * qc;
rot_mat[3,2] = 2.0 * qc * qd + 2.0 * qa * qb;
rot_mat[3,3] = qa*qa + qd*qd - qc*qc - qb*qb;
qfac = nifti_img@pixdim[1];
if(!(qfac == -1 | qfac == 1)) {
warning(sprintf("Treating non-standard qfac value '%f' as 1.0\n.", qfac));
qfac = 1;
}
rot_mat[1,3] = rot_mat[1,3] * qfac;
rot_mat[2,3] = rot_mat[2,3] * qfac;
rot_mat[3,3] = rot_mat[3,3] * qfac;
header$internal$x_r = rot_mat[1,1];
header$internal$y_r = rot_mat[1,2];
header$internal$z_r = rot_mat[1,3];
header$internal$x_a = rot_mat[2,1];
header$internal$y_a = rot_mat[2,2];
header$internal$z_a = rot_mat[2,3];
header$internal$x_s = rot_mat[3,1];
header$internal$y_s = rot_mat[3,2];
header$internal$z_s = rot_mat[3,3];
header$internal$c_r = (header$internal$xsize * header$internal$x_r) * (header$internal$width / 2.0) +
(header$internal$ysize * header$internal$y_r) * (header$internal$height / 2.0) +
(header$internal$zsize * header$internal$z_r) * (header$internal$depth / 2.0) + nifti_img@qoffset_x;
header$internal$c_a = (header$internal$xsize * header$internal$x_a) * (header$internal$width / 2.0) +
(header$internal$ysize * header$internal$y_a) * (header$internal$height / 2.0) +
(header$internal$zsize * header$internal$z_a) * (header$internal$depth / 2.0) + nifti_img@qoffset_y;
header$internal$c_s = (header$internal$xsize * header$internal$x_s) * (header$internal$width / 2.0) +
(header$internal$ysize * header$internal$y_s) * (header$internal$height / 2.0) +
(header$internal$zsize * header$internal$z_s) * (header$internal$depth / 2.0) + nifti_img@qoffset_z;
header$ras_good_flag = 1L;
} else {
warning("Nifti image does not contain valid sform or qform, orientation cannot be derived and is arbitrary.");
header$internal$x_r = -1.0;
header$internal$x_a = 0.0;
header$internal$x_s = 0.0;
header$internal$y_r = 0.0;
header$internal$y_a = 1.0;
header$internal$y_s = 0.0;
header$internal$z_r = 0.0;
header$internal$z_a = 0.0;
header$internal$z_s = 1.0;
header$internal$c_r = header$internal$xsize * header$internal$width / 2.0;
header$internal$c_a = header$internal$ysize * header$internal$height / 2.0;
header$internal$c_s = header$internal$zsize * header$internal$depth / 2.0;
header$ras_good_flag = 0L;
}
header$internal$xsize = header$internal$xsize * space_unit_factor;
header$internal$ysize = header$internal$ysize * space_unit_factor;
header$internal$zsize = header$internal$zsize * space_unit_factor;
header$internal$c_r = header$internal$c_r * space_unit_factor;
header$internal$c_a = header$internal$c_a * space_unit_factor;
header$internal$c_s = header$internal$c_s * space_unit_factor;
header$internal$tr = header$internal$tr * time_unit_factor;
header$has_mr_params = 1L;
header$mr = list();
header$mr$tr = header$internal$tr;
x_half_length = header$internal$width / 2.0 * header$internal$xsize;
y_half_length = header$internal$height / 2.0 * header$internal$ysize;
z_half_length = header$internal$depth / 2.0 * header$internal$zsize;
header$internal$xstart = - x_half_length;
header$internal$xend = x_half_length;
header$internal$ystart = - y_half_length;
header$internal$yend = y_half_length;
header$internal$zstart = - z_half_length;
header$internal$zend = z_half_length;
xfov = header$internal$xend - header$internal$xstart;
yfov = header$internal$yend - header$internal$ystart;
zfov = header$internal$zend - header$internal$zstart;
header$internal$fov = ifelse(xfov > yfov, ifelse(xfov > zfov, xfov, zfov), ifelse(yfov > zfov, yfov, zfov));
header$mr$fov = header$internal$fov;
orientation_info = get.slice.orientation(header$internal$Mdc);
header$internal$slice_orientation_string = orientation_info$orientation_string;
header$internal$slice_direction_name = orientation_info$direction_name;
data = [email protected];
if(do_rotate) {
if(length(dim(drop(data))) == 3L) {
data = rotate3D(drop(data), axis=1L, degrees = 90L);
} else {
warning(sprintf("Not rotating: data dimension is '%s'.\n", paste(dim(data), collapse = " ")));
}
}
if(length(dim(data)) != 4) {
dim(data) = c(ncols, nifti_img@dim_[3], nifti_img@dim_[4], num_frames);
}
nv = prod(dim(data));
if(flatten) {
dim(data) = c(nv);
data = as.vector(unlist(data));
header$voldim = c(length(data));
}
if(drop_empty_dims) {
data = drop(data);
}
fsvol = list("header"=header, "data"=data);
class(fsvol) = 'fs.volume';
if(with_header) {
return(fsvol);
} else {
return(data);
}
} else {
stop("The 'oro.nifti' package is required to use this functionality.");
}
}
nifti.space.info <- function(xyzt_units) {
nifti_unit_code = bitwAnd(xyzt_units, 0x07);
nifti_unit_name = "unknown";
scaling = 1.0;
if(nifti_unit_code == 1L) { nifti_unit_name = "m"; scaling = 1000.0; }
if(nifti_unit_code == 2L) { nifti_unit_name = "mm"; scaling = 1.0; }
if(nifti_unit_code == 3L) { nifti_unit_name = "mum"; scaling = 0.001; }
return(list("code"=nifti_unit_code, "name"=nifti_unit_name, "scaling"=scaling));
}
nifti.dtype.info <- function(datatype, bitpix) {
MRI_UCHAR = translate.mri.dtype("MRI_UCHAR");
MRI_INT = translate.mri.dtype("MRI_INT");
MRI_FLOAT = translate.mri.dtype("MRI_FLOAT");
MRI_SHORT = translate.mri.dtype("MRI_SHORT");
if(datatype == 2L & bitpix == 8L) {
return(list('mri_dtype' = MRI_UCHAR, 'r_dtype' = integer()));
} else if(datatype == 4L & bitpix == 16L) {
return(list('mri_dtype' = MRI_SHORT, 'r_dtype' = integer()));
} else if(datatype == 8L & bitpix == 32L) {
return(list('mri_dtype' = MRI_INT, 'r_dtype' = integer()));
} else if(datatype == 512L & bitpix == 16L) {
return(list('mri_dtype' = MRI_INT, 'r_dtype' = integer()));
} else if(datatype == 768L & bitpix == 32L) {
return(list('mri_dtype' = MRI_INT, 'r_dtype' = integer()));
} else if(datatype == 16L & bitpix == 32L) {
return(list('mri_dtype' = MRI_FLOAT, 'r_dtype' = numeric()));
} else if(datatype == 64L & bitpix == 64L) {
return(list('mri_dtype' = MRI_FLOAT, 'r_dtype' = numeric()));
} else {
stop(sprintf("Nifti images with datatype=%d and bitpix=%d not supported yet.\n", datatype, bitpix));
}
}
nifti.transform.type.name <- function(form_code) {
if(form_code == 1L) { return("scanner_anatomical"); }
if(form_code == 2L) { return("reference"); }
if(form_code == 3L) { return("talairach_space"); }
if(form_code == 4L) { return("MNI152_space"); }
return("unknown");
}
nifti.time.info <- function(xyzt_units) {
nifti_unit_code = bitwAnd(xyzt_units, 0x38);
nifti_unit_name = "unknown";
scaling = 1.0;
if(nifti_unit_code == 8L) { nifti_unit_name = "s"; scaling = 1000.0; }
if(nifti_unit_code == 16L) { nifti_unit_name = "ms"; scaling = 1.0; }
if(nifti_unit_code == 24L) { nifti_unit_name = "mus"; scaling = 0.001; }
return(list("code"=nifti_unit_code, "name"=nifti_unit_name, "scaling"=scaling));
} |
boot.transitions <- function(transitions, iterations, by.stage.counts = FALSE, ...) {
t <- iterations
mat <- vector("list", t)
vec <- vector("list", t)
lam <- numeric(t)
for (i in 1:t) {
if (by.stage.counts) {
boot <- do.call(
rbind,
lapply(
split(transitions, transitions$stage, drop = TRUE),
function(x) x[sample(nrow(x), replace = TRUE), ]
)
)
} else {
boot <- transitions[sample(nrow(transitions), replace = TRUE), ]
}
A <- projection.matrix(boot, ...)
vec[[i]] <- table(boot$stage)
mat[[i]] <- as.vector(A)
lam[i] <- lambda(A)
}
n <- dim(A)[1]
boot.stage <- list(
lambda = lam,
matrix = matrix(unlist(mat),
byrow = TRUE, nrow = t,
dimnames = list(1:t, paste("a", 1:n, rep(1:n, each = n), sep = ""))
),
vector = matrix(unlist(vec), byrow = TRUE, nrow = t, dimnames = list(1:t, names(vec[[1]])))
)
boot.stage
} |
write_selection <- function(dist_e , dist_c, type, pe_fixed, pc_fixed, ze_fixed, zc_fixed, ind_fixed, pe_random, pc_random, ze_random, zc_random, ind_random,
model_e_random, model_c_random, model_me_random, model_mc_random) eval.parent(substitute( {
model_string_jags<- "
model {
for(i in 1:N1) {
cost1[i] ~ dnorm(mu_c1[i], tau_c[1])
eff1[i] ~ dnorm(mu_e1[i], tau_e[1])
mu_c1[i] <- inprod(X1_c_fixed[i, ], beta[, 1]) + beta_f[1] * (eff1[i] - mu_e[1]) + inprod(X1_c_random[i, ], b1[, clus1_c[i]]) + b1_f[clus1_c[i]] * (eff1[i] - mu_e[1])
mu_e1[i] <- inprod(X1_e_fixed[i, ], alpha[, 1]) + inprod(X1_e_random[i, ], a1[, clus1_e[i]])
m_eff1[i] ~ dbern(pq_1[i])
logit(pq_1[i]) <- inprod(Z1_e_fixed[i, ], gamma_e[, 1]) + delta_e[1] * eff1[i] + inprod(Z1_e_random[i, ], g1_e[, clus1_me[i]]) + d1_e[clus1_me[i]] * eff1[i]
m_cost1[i] ~ dbern(pc_1[i])
logit(pc_1[i]) <- inprod(Z1_c_fixed[i, ], gamma_c[, 1]) + delta_c[1] * cost1[i] + inprod(Z1_c_random[i, ], g1_c[, clus1_mc[i]]) + d1_c[clus1_mc[i]] * cost1[i]
loglik_e1[i] <- logdensity.norm(eff1[i], mu_e1[i], tau_e[1])
loglik_c1[i] <- logdensity.norm(cost1[i], mu_c1[i], tau_c[1])
loglik_me1[i] <- logdensity.bern(m_eff1[i], pq_1[i])
loglik_mc1[i] <- logdensity.bern(m_cost1[i], pc_1[i])
}
for(i in 1:N2) {
cost2[i] ~ dnorm(mu_c2[i], tau_c[2])
eff2[i] ~ dnorm(mu_e2[i], tau_e[2])
mu_c2[i] <- inprod(X2_c_fixed[i, ], beta[, 2]) + beta_f[2] * (eff2[i] - mu_e[2]) + inprod(X2_c_random[i, ], b2[, clus2_c[i]]) + b2_f[clus2_c[i]] * (eff2[i] - mu_e[2])
mu_e2[i] <- inprod(X2_e_fixed[i, ], alpha[, 2]) + inprod(X2_e_random[i, ], a2[, clus2_e[i]])
m_eff2[i] ~ dbern(pq_2[i])
logit(pq_2[i]) <- inprod(Z2_e_fixed[i, ], gamma_e[, 2]) + delta_e[2] * eff2[i] + inprod(Z2_e_random[i, ], g2_e[, clus2_me[i]]) + d2_e[clus2_me[i]] * eff2[i]
m_cost2[i] ~ dbern(pc_2[i])
logit(pc_2[i]) <- inprod(Z2_c_fixed[i, ], gamma_c[, 2]) + delta_c[2] * cost2[i] + inprod(Z2_c_random[i, ], g2_c[, clus2_mc[i]]) + d2_c[clus2_mc[i]] * cost2[i]
loglik_e2[i] <- logdensity.norm(eff2[i], mu_e2[i], tau_e[2])
loglik_c2[i] <- logdensity.norm(cost2[i], mu_c2[i], tau_c[2])
loglik_me2[i] <- logdensity.bern(m_eff2[i], pq_2[i])
loglik_mc2[i] <- logdensity.bern(m_cost2[i], pc_2[i])
}
for (t in 1:2) {
tau_c[t] <- 1 / ss_c[t]
ss_c[t] <- s_c[t] * s_c[t]
s_c[t] <- exp(ls_c[t])
tau_e[t] <- 1 / ss_e[t]
ss_e[t] <- s_e[t] * s_e[t]
s_e[t] <- exp(ls_e[t])
}
for (t in 1:2) {
for(j in 1:pc_random) {tau_b_hat[j, t] <- 1 / ss_b_hat[j, t]
ss_b_hat[j, t] <- s_b_hat[j, t] * s_b_hat[j, t] }
for(j in 1:pe_random) {tau_a_hat[j, t] <- 1 / ss_a_hat[j, t]
ss_a_hat[j, t] <- s_a_hat[j, t] * s_a_hat[j, t] }
for(j in 1:zc_random) {tau_g_c_hat[j, t] <- 1 / ss_g_c_hat[j, t]
ss_g_c_hat[j, t] <- s_g_c_hat[j, t] * s_g_c_hat[j, t] }
for(j in 1:ze_random) {tau_g_e_hat[j, t] <- 1 / ss_g_e_hat[j, t]
ss_g_e_hat[j, t] <- s_g_e_hat[j, t] * s_g_e_hat[j, t] }
tau_d_c_hat[t] <- 1 / ss_d_c_hat[t]
ss_d_c_hat[t] <- s_d_c_hat[t] * s_d_c_hat[t]
tau_d_e_hat[t] <- 1 / ss_d_e_hat[t]
ss_d_e_hat[t] <- s_d_e_hat[t] * s_d_e_hat[t]
}
p_c[1] <- ilogit(inprod(mean_z_c1_fixed[], gamma_c[, 1]) + delta_c[1] * mean(cost1[]) + inprod(mean_z_c1_random[], mu_g_c_hat[, 1]) + mu_d_c_hat[1] * mean(cost1[]))
p_c[2] <- ilogit(inprod(mean_z_c2_fixed[], gamma_c[, 2]) + delta_c[2] * mean(cost2[]) + inprod(mean_z_c2_random[], mu_g_c_hat[, 2]) + mu_d_c_hat[2] * mean(cost2[]))
p_e[1] <- ilogit(inprod(mean_z_e1_fixed[], gamma_e[, 1]) + delta_e[1] * mean(eff1[]) + inprod(mean_z_e1_random[], mu_g_e_hat[, 1]) + mu_d_e_hat[1] * mean(eff1[]))
p_e[2] <- ilogit(inprod(mean_z_e2_fixed[], gamma_e[, 2]) + delta_e[2] * mean(eff2[]) + inprod(mean_z_e2_random[], mu_g_e_hat[, 2]) + mu_d_e_hat[2] * mean(eff2[]))
mu_c[1] <- inprod(mean_cov_c1_fixed[], beta[, 1]) + inprod(mean_cov_c1_random[], mu_b_hat[, 1])
mu_c[2] <- inprod(mean_cov_c2_fixed[], beta[, 2]) + inprod(mean_cov_c2_random[], mu_b_hat[, 2])
mu_e[1] <- inprod(mean_cov_e1_fixed[], alpha[, 1]) + inprod(mean_cov_e1_random[], mu_a_hat[, 1])
mu_e[2] <- inprod(mean_cov_e2_fixed[], alpha[, 2]) + inprod(mean_cov_e2_random[], mu_a_hat[, 2])
for (j in 2:pe_fixed) {
for(t in 1:2) {alpha[j, t] ~ dnorm(0, 0.0000001) }
}
alpha[1, 1] ~ dnorm(0, 0.0000001)
alpha[1, 2] ~ dnorm(0, 0.0000001)
for (j in 2:pc_fixed) {
for(t in 1:2) {beta[j, t] ~ dnorm(0, 0.0000001) }
}
beta[1, 1] ~ dnorm(0, 0.0000001)
beta[1, 2] ~ dnorm(0, 0.0000001)
for (j in 1:pe_random) {
for(s in 1:n1_clus_e) {a1[j, s] ~ dnorm(mu_a_hat[j, 1], tau_a_hat[j, 1]) }
}
for (j in 1:pe_random) {
for(s in 1:n2_clus_e) {a2[j, s] ~ dnorm(mu_a_hat[j, 2], tau_a_hat[j, 2]) }
}
for (j in 1:pc_random) {
for(s in 1:n1_clus_c) {b1[j, s] ~ dnorm(mu_b_hat[j, 1], tau_b_hat[j, 1]) }
}
for (j in 1:pc_random) {
for(s in 1:n2_clus_c) {b2[j, s] ~ dnorm(mu_b_hat[j, 2], tau_b_hat[j, 2]) }
}
for(t in 1:2) {
ls_c[t] ~ dunif(-5, 10)
ls_e[t] ~ dunif(-5, 10)
beta_f[t] ~ dnorm(0, 0.0000001)
for(j in 1:pc_random) {mu_b_hat[j, t] ~ dnorm(0, 0.001)
s_b_hat[j, t] ~ dunif(0, 100) }
for(j in 1:pe_random) {mu_a_hat[j, t] ~ dnorm(0, 0.001)
s_a_hat[j, t] ~ dunif(0, 100) }
for(j in 1:zc_random) {mu_g_c_hat[j, t] ~ dnorm(0, 0.001)
s_g_c_hat[j, t] ~ dunif(0, 100) }
for(j in 1:ze_random) {mu_g_e_hat[j, t] ~ dnorm(0, 0.001)
s_g_e_hat[j, t] ~ dunif(0, 100) }
}
for(s in 1:n1_clus_c) {b1_f[s] ~ dnorm(mu_b_f_hat[1], tau_b_f_hat[1]) }
for(s in 1:n2_clus_c) {b2_f[s] ~ dnorm(mu_b_f_hat[2], tau_b_f_hat[2]) }
for(t in 1:2) {mu_b_f_hat[t] ~ dnorm(0, 0.001)
tau_b_f_hat[t] <- 1 / ss_b_f_hat[t]
ss_b_f_hat[t] <- s_b_f_hat[t] * s_b_f_hat[t]
s_b_f_hat[t] ~ dunif(0, 100) }
for (j in 2:ze_fixed) {
for(t in 1:2) {gamma_e[j, t] ~ dnorm(0, 0.01) }
}
gamma_e[1, 1] ~ dlogis(0, 1)
gamma_e[1, 2] ~ dlogis(0, 1)
for (j in 2:zc_fixed) {
for(t in 1:2) {gamma_c[j, t] ~ dnorm(0, 0.01) }
}
gamma_c[1, 1] ~ dlogis(0, 1)
gamma_c[1, 2] ~ dlogis(0, 1)
for (j in 1:ze_random) {
for(s in 1:n1_clus_me) {g1_e[j, s] ~ dnorm(mu_g_e_hat[j, 1], tau_g_e_hat[j, 1]) }
}
for (j in 1:ze_random) {
for(s in 1:n2_clus_me) {g2_e[j, s] ~ dnorm(mu_g_e_hat[j, 2], tau_g_e_hat[j, 2]) }
}
for (j in 1:zc_random) {
for(s in 1:n1_clus_mc) {g1_c[j, s] ~ dnorm(mu_g_c_hat[j, 1], tau_g_c_hat[j, 1]) }
}
for (j in 1:zc_random) {
for(s in 1:n2_clus_mc) {g2_c[j, s] ~ dnorm(mu_g_c_hat[j, 2], tau_g_c_hat[j, 2]) }
}
for(t in 1:2) {
delta_e[t] ~ dnorm(0, 1)
delta_c[t] ~ dnorm(0, 1)
}
for(s in 1:n1_clus_me) {d1_e[s] ~ dnorm(mu_d_e_hat[1], tau_d_e_hat[1]) }
for(s in 1:n2_clus_me) {d2_e[s] ~ dnorm(mu_d_e_hat[2], tau_d_e_hat[2]) }
for(s in 1:n1_clus_mc) {d1_c[s] ~ dnorm(mu_d_c_hat[1], tau_d_c_hat[1]) }
for(s in 1:n2_clus_mc) {d2_c[s] ~ dnorm(mu_d_c_hat[2], tau_d_c_hat[2]) }
for(t in 1:2) {
mu_d_e_hat[t] ~ dnorm(0, 1)
mu_d_c_hat[t] ~ dnorm(0, 1)
s_d_e_hat[t] ~ dunif(0, 1)
s_d_c_hat[t] ~ dunif(0, 1)
}
}
"
if(length(model_e_random) == 0) {
model_string_jags <- gsub(" + inprod(X1_e_random[i, ], a1[, clus1_e[i]])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub(" + inprod(X2_e_random[i, ], a2[, clus2_e[i]])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for(j in 1:pe_random) {tau_a_hat[j, t] <- 1 / ss_a_hat[j, t]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("ss_a_hat[j, t] <- s_a_hat[j, t] * s_a_hat[j, t] }", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub(" + inprod(mean_cov_e1_random[], mu_a_hat[, 1])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub(" + inprod(mean_cov_e2_random[], mu_a_hat[, 2])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for (j in 1:pe_random) {
model_string_jags <- gsub("for(s in 1:n1_clus_e) {a1[j, s] ~ dnorm(mu_a_hat[j, 1], tau_a_hat[j, 1]) }", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("}
model_string_jags <- gsub("for (j in 1:pe_random) {
model_string_jags <- gsub("for(s in 1:n2_clus_e) {a2[j, s] ~ dnorm(mu_a_hat[j, 2], tau_a_hat[j, 2]) }", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("}
model_string_jags <- gsub("for(j in 1:pe_random) {mu_a_hat[j, t] ~ dnorm(0, 0.001)", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("s_a_hat[j, t] ~ dunif(0, 100) }", "", model_string_jags, fixed = TRUE)
}
if(length(model_c_random) == 0) {
model_string_jags <- gsub(" + inprod(X1_c_random[i, ], b1[, clus1_c[i]])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub(" + inprod(X2_c_random[i, ], b2[, clus2_c[i]])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for(j in 1:pc_random) {tau_b_hat[j, t] <- 1 / ss_b_hat[j, t]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("ss_b_hat[j, t] <- s_b_hat[j, t] * s_b_hat[j, t] }", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub(" + inprod(mean_cov_c1_random[], mu_b_hat[, 1])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub(" + inprod(mean_cov_c2_random[], mu_b_hat[, 2])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for (j in 1:pc_random) {
model_string_jags <- gsub("for(s in 1:n1_clus_c) {b1[j, s] ~ dnorm(mu_b_hat[j, 1], tau_b_hat[j, 1]) }", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("}
model_string_jags <- gsub("for (j in 1:pc_random) {
model_string_jags <- gsub("for(s in 1:n2_clus_c) {b2[j, s] ~ dnorm(mu_b_hat[j, 2], tau_b_hat[j, 2]) }", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("}
model_string_jags <- gsub("for(j in 1:pc_random) {mu_b_hat[j, t] ~ dnorm(0, 0.001)", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("s_b_hat[j, t] ~ dunif(0, 100) }", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("+ b1_f[clus1_c[i]] * (eff1[i] - mu_e[1])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("+ b2_f[clus2_c[i]] * (eff2[i] - mu_e[2])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for(s in 1:n1_clus_c) {b1_f[s] ~ dnorm(mu_b_f_hat[1], tau_b_f_hat[1]) }", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for(s in 1:n2_clus_c) {b2_f[s] ~ dnorm(mu_b_f_hat[2], tau_b_f_hat[2]) }", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for(t in 1:2) {mu_b_f_hat[t] ~ dnorm(0, 0.001)", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("tau_b_f_hat[t] <- 1 / ss_b_f_hat[t]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("ss_b_f_hat[t] <- s_b_f_hat[t] * s_b_f_hat[t]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("s_b_f_hat[t] ~ dunif(0, 100) }", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("
if(length(model_e_random) == 0) { model_string_jags <- gsub("
} else if(length(model_c_random) != 0 & is_c_random_c == TRUE & is_int_c_random_c == FALSE) {
model_string_jags <- gsub(" + inprod(X1_c_random[i, ], b1[, clus1_c[i]])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub(" + inprod(X2_c_random[i, ], b2[, clus2_c[i]])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for(j in 1:pc_random) {tau_b_hat[j, t] <- 1 / ss_b_hat[j, t]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("ss_b_hat[j, t] <- s_b_hat[j, t] * s_b_hat[j, t] }", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub(" + inprod(mean_cov_c1_random[], mu_b_hat[, 1])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub(" + inprod(mean_cov_c2_random[], mu_b_hat[, 2])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for (j in 1:pc_random) {
model_string_jags <- gsub("for(s in 1:n1_clus_c) {b1[j, s] ~ dnorm(mu_b_hat[j, 1], tau_b_hat[j, 1]) }", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("}
model_string_jags <- gsub("for (j in 1:pc_random) {
model_string_jags <- gsub("for(s in 1:n2_clus_c) {b2[j, s] ~ dnorm(mu_b_hat[j, 2], tau_b_hat[j, 2]) }", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("}
model_string_jags <- gsub("for(j in 1:pc_random) {mu_b_hat[j, t] ~ dnorm(0, 0.001)", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("s_b_hat[j, t] ~ dunif(0, 100) }", "", model_string_jags, fixed = TRUE)
if(length(model_e_random) == 0) { model_string_jags <- gsub("
}
if(length(model_me_random) == 0) {
model_string_jags <- gsub(" + inprod(Z1_e_random[i, ], g1_e[, clus1_me[i]])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub(" + inprod(Z2_e_random[i, ], g2_e[, clus2_me[i]])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for(j in 1:ze_random) {tau_g_e_hat[j, t] <- 1 / ss_g_e_hat[j, t]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("ss_g_e_hat[j, t] <- s_g_e_hat[j, t] * s_g_e_hat[j, t] }", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub(" + inprod(mean_z_e1_random[], mu_g_e_hat[, 1])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub(" + inprod(mean_z_e2_random[], mu_g_e_hat[, 2])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for (j in 1:ze_random) {
model_string_jags <- gsub("for(s in 1:n1_clus_me) {g1_e[j, s] ~ dnorm(mu_g_e_hat[j, 1], tau_g_e_hat[j, 1]) }", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("}
model_string_jags <- gsub("for (j in 1:ze_random) {
model_string_jags <- gsub("for(s in 1:n2_clus_me) {g2_e[j, s] ~ dnorm(mu_g_e_hat[j, 2], tau_g_e_hat[j, 2]) }", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("}
model_string_jags <- gsub("for(j in 1:ze_random) {mu_g_e_hat[j, t] ~ dnorm(0, 0.001)", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("s_g_e_hat[j, t] ~ dunif(0, 100) }", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("+ d1_e[clus1_me[i]] * eff1[i]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("+ d2_e[clus2_me[i]] * eff2[i]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("+ mu_d_e_hat[1] * mean(eff1[])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("+ mu_d_e_hat[2] * mean(eff2[])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("tau_d_e_hat[t] <- 1 / ss_d_e_hat[t]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("ss_d_e_hat[t] <- s_d_e_hat[t] * s_d_e_hat[t]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("mu_d_e_hat[t] ~ dnorm(0, 1)", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("s_d_e_hat[t] ~ dunif(0, 1)", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for(s in 1:n1_clus_me) {d1_e[s] ~ dnorm(mu_d_e_hat[1], tau_d_e_hat[1]) }", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for(s in 1:n2_clus_me) {d2_e[s] ~ dnorm(mu_d_e_hat[2], tau_d_e_hat[2]) }", "", model_string_jags, fixed = TRUE)
if(length(model_mc_random) == 0) {
model_string_jags <- gsub("
model_string_jags <- gsub("
model_string_jags <- gsub("
model_string_jags <- gsub("for(t in 1:2) {
model_string_jags <- gsub("}
if(length(model_c_random) == 0 & length(model_e_random) == 0 | length(model_e_random) == 0 & pc_random == 0) {
model_string_jags <- gsub("
model_string_jags <- gsub("
model_string_jags <- gsub("for (t in 1:2) {
model_string_jags <- gsub("}
}
}
} else if(length(model_me_random) != 0 & is_me_random_e == TRUE & is_int_me_random_e == FALSE) {
model_string_jags <- gsub(" + inprod(Z1_e_random[i, ], g1_e[, clus1_me[i]])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub(" + inprod(Z2_e_random[i, ], g2_e[, clus2_me[i]])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for(j in 1:ze_random) {tau_g_e_hat[j, t] <- 1 / ss_g_e_hat[j, t]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("ss_g_e_hat[j, t] <- s_g_e_hat[j, t] * s_g_e_hat[j, t] }", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub(" + inprod(mean_z_e1_random[], mu_g_e_hat[, 1])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub(" + inprod(mean_z_e2_random[], mu_g_e_hat[, 2])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for (j in 1:ze_random) {
model_string_jags <- gsub("for(s in 1:n1_clus_me) {g1_e[j, s] ~ dnorm(mu_g_e_hat[j, 1], tau_g_e_hat[j, 1]) }", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("}
model_string_jags <- gsub("for (j in 1:ze_random) {
model_string_jags <- gsub("for(s in 1:n2_clus_me) {g2_e[j, s] ~ dnorm(mu_g_e_hat[j, 2], tau_g_e_hat[j, 2]) }", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("}
model_string_jags <- gsub("for(j in 1:ze_random) {mu_g_e_hat[j, t] ~ dnorm(0, 0.001)", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("s_g_e_hat[j, t] ~ dunif(0, 100) }", "", model_string_jags, fixed = TRUE)
}
if(length(model_mc_random) == 0) {
model_string_jags <- gsub(" + inprod(Z1_c_random[i, ], g1_c[, clus1_mc[i]])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub(" + inprod(Z2_c_random[i, ], g2_c[, clus2_mc[i]])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for(j in 1:zc_random) {tau_g_c_hat[j, t] <- 1 / ss_g_c_hat[j, t]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("ss_g_c_hat[j, t] <- s_g_c_hat[j, t] * s_g_c_hat[j, t] }", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub(" + inprod(mean_z_c1_random[], mu_g_c_hat[, 1])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub(" + inprod(mean_z_c2_random[], mu_g_c_hat[, 2])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for (j in 1:zc_random) {
model_string_jags <- gsub("for(s in 1:n1_clus_mc) {g1_c[j, s] ~ dnorm(mu_g_c_hat[j, 1], tau_g_c_hat[j, 1]) }", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("}
model_string_jags <- gsub("for (j in 1:zc_random) {
model_string_jags <- gsub("for(s in 1:n2_clus_mc) {g2_c[j, s] ~ dnorm(mu_g_c_hat[j, 2], tau_g_c_hat[j, 2]) }", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("}
model_string_jags <- gsub("for(j in 1:zc_random) {mu_g_c_hat[j, t] ~ dnorm(0, 0.001)", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("s_g_c_hat[j, t] ~ dunif(0, 100) }", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("+ d1_c[clus1_mc[i]] * cost1[i]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("+ d2_c[clus2_mc[i]] * cost2[i]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("+ mu_d_c_hat[1] * mean(cost1[])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("+ mu_d_c_hat[2] * mean(cost2[])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("tau_d_c_hat[t] <- 1 / ss_d_c_hat[t]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("ss_d_c_hat[t] <- s_d_c_hat[t] * s_d_c_hat[t]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("mu_d_c_hat[t] ~ dnorm(0, 1)", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("s_d_c_hat[t] ~ dunif(0, 1)", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for(s in 1:n1_clus_mc) {d1_c[s] ~ dnorm(mu_d_c_hat[1], tau_d_c_hat[1]) }", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for(s in 1:n2_clus_mc) {d2_c[s] ~ dnorm(mu_d_c_hat[2], tau_d_c_hat[2]) }", "", model_string_jags, fixed = TRUE)
if(length(model_me_random) == 0) {
model_string_jags <- gsub("
model_string_jags <- gsub("
model_string_jags <- gsub("
model_string_jags <- gsub("for(t in 1:2) {
model_string_jags <- gsub("}
if(length(model_e_random) == 0 & length(model_c_random) == 0 | length(model_e_random) == 0 & pc_random == 0) {
model_string_jags <- gsub("
model_string_jags <- gsub("
model_string_jags <- gsub("for (t in 1:2) {
model_string_jags <- gsub("}
}
}
} else if(length(model_mc_random) != 0 & is_mc_random_c == TRUE & is_int_mc_random_c == FALSE) {
model_string_jags <- gsub(" + inprod(Z1_c_random[i, ], g1_c[, clus1_mc[i]])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub(" + inprod(Z2_c_random[i, ], g2_c[, clus2_mc[i]])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for(j in 1:zc_random) {tau_g_c_hat[j, t] <- 1 / ss_g_c_hat[j, t]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("ss_g_c_hat[j, t] <- s_g_c_hat[j, t] * s_g_c_hat[j, t] }", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub(" + inprod(mean_z_c1_random[], mu_g_c_hat[, 1])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub(" + inprod(mean_z_c2_random[], mu_g_c_hat[, 2])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for (j in 1:zc_random) {
model_string_jags <- gsub("for(s in 1:n1_clus_mc) {g1_c[j, s] ~ dnorm(mu_g_c_hat[j, 1], tau_g_c_hat[j, 1]) }", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("}
model_string_jags <- gsub("for (j in 1:zc_random) {
model_string_jags <- gsub("for(s in 1:n2_clus_mc) {g2_c[j, s] ~ dnorm(mu_g_c_hat[j, 2], tau_g_c_hat[j, 2]) }", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("}
model_string_jags <- gsub("for(j in 1:zc_random) {mu_g_c_hat[j, t] ~ dnorm(0, 0.001)", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("s_g_c_hat[j, t] ~ dunif(0, 100) }", "", model_string_jags, fixed = TRUE)
}
if(type == "MAR") {
model_string_jags <- gsub(" + delta_e[1] * mean(eff1[])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub(" + delta_e[2] * mean(eff2[])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub(" + delta_e[1] * eff1[i]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub(" + delta_e[2] * eff2[i]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("delta_e[t] ~ dnorm(0, 1)", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub(" + delta_c[1] * mean(cost1[])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub(" + delta_c[2] * mean(cost2[])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub(" + delta_c[1] * cost1[i]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub(" + delta_c[2] * cost2[i]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("delta_c[t] ~ dnorm(0, 1)", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for(t in 1:2) {
model_string_jags <- gsub("}
model_string_jags <- gsub("
model_string_jags <- gsub("
model_string_jags <- gsub("
model_string_jags <- gsub("for(t in 1:2) {
model_string_jags <- gsub("}
if(length(model_me_random) != 0) {
model_string_jags <- gsub("+ d1_e[clus1_me[i]] * eff1[i]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("+ d2_e[clus2_me[i]] * eff2[i]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("+ mu_d_e_hat[1] * mean(eff1[])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("+ mu_d_e_hat[2] * mean(eff2[])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("tau_d_e_hat[t] <- 1 / ss_d_e_hat[t]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("ss_d_e_hat[t] <- s_d_e_hat[t] * s_d_e_hat[t]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("mu_d_e_hat[t] ~ dnorm(0, 1)", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("s_d_e_hat[t] ~ dunif(0, 1)", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for(s in 1:n1_clus_me) {d1_e[s] ~ dnorm(mu_d_e_hat[1], tau_d_e_hat[1]) }", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for(s in 1:n2_clus_me) {d2_e[s] ~ dnorm(mu_d_e_hat[2], tau_d_e_hat[2]) }", "", model_string_jags, fixed = TRUE)
}
if(length(model_mc_random) != 0) {
model_string_jags <- gsub("+ d1_c[clus1_mc[i]] * cost1[i]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("+ d2_c[clus2_mc[i]] * cost2[i]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("+ mu_d_c_hat[1] * mean(cost1[])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("+ mu_d_c_hat[2] * mean(cost2[])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("tau_d_c_hat[t] <- 1 / ss_d_c_hat[t]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("ss_d_c_hat[t] <- s_d_c_hat[t] * s_d_c_hat[t]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("mu_d_c_hat[t] ~ dnorm(0, 1)", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("s_d_c_hat[t] ~ dunif(0, 1)", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for(s in 1:n1_clus_mc) {d1_c[s] ~ dnorm(mu_d_c_hat[1], tau_d_c_hat[1]) }", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for(s in 1:n2_clus_mc) {d2_c[s] ~ dnorm(mu_d_c_hat[2], tau_d_c_hat[2]) }", "", model_string_jags, fixed = TRUE)
}
} else if(type == "MNAR_eff") {
model_string_jags <- gsub(" + delta_c[1] * mean(cost1[])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub(" + delta_c[2] * mean(cost2[])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub(" + delta_c[1] * cost1[i]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub(" + delta_c[2] * cost2[i]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("delta_c[t] ~ dnorm(0, 1)", "", model_string_jags, fixed = TRUE)
if(length(model_mc_random) != 0) {
model_string_jags <- gsub("+ d1_c[clus1_mc[i]] * cost1[i]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("+ d2_c[clus2_mc[i]] * cost2[i]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("+ mu_d_c_hat[1] * mean(cost1[])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("+ mu_d_c_hat[2] * mean(cost2[])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("tau_d_c_hat[t] <- 1 / ss_d_c_hat[t]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("ss_d_c_hat[t] <- s_d_c_hat[t] * s_d_c_hat[t]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("mu_d_c_hat[t] ~ dnorm(0, 1)", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("s_d_c_hat[t] ~ dunif(0, 1)", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for(s in 1:n1_clus_mc) {d1_c[s] ~ dnorm(mu_d_c_hat[1], tau_d_c_hat[1]) }", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for(s in 1:n2_clus_mc) {d2_c[s] ~ dnorm(mu_d_c_hat[2], tau_d_c_hat[2]) }", "", model_string_jags, fixed = TRUE)
}
if(length(model_me_random) != 0 & !("e" %in% model_me_random)) {
model_string_jags <- gsub("+ d1_e[clus1_me[i]] * eff1[i]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("+ d2_e[clus2_me[i]] * eff2[i]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("+ mu_d_e_hat[1] * mean(eff1[])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("+ mu_d_e_hat[2] * mean(eff2[])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("tau_d_e_hat[t] <- 1 / ss_d_e_hat[t]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("ss_d_e_hat[t] <- s_d_e_hat[t] * s_d_e_hat[t]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("mu_d_e_hat[t] ~ dnorm(0, 1)", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("s_d_e_hat[t] ~ dunif(0, 1)", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for(s in 1:n1_clus_me) {d1_e[s] ~ dnorm(mu_d_e_hat[1], tau_d_e_hat[1]) }", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for(s in 1:n2_clus_me) {d2_e[s] ~ dnorm(mu_d_e_hat[2], tau_d_e_hat[2]) }", "", model_string_jags, fixed = TRUE)
}
if(length(model_mc_random) != 0 & !("c" %in% model_mc_random) & length(model_me_random) != 0 & !("e" %in% model_me_random)) {
model_string_jags <- gsub("
model_string_jags <- gsub("
model_string_jags <- gsub("
model_string_jags <- gsub("for(t in 1:2) {
model_string_jags <- gsub("}
}
} else if(type == "MNAR_cost") {
model_string_jags <- gsub(" + delta_e[1] * mean(eff1[])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub(" + delta_e[2] * mean(eff2[])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub(" + delta_e[1] * eff1[i]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub(" + delta_e[2] * eff2[i]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("delta_e[t] ~ dnorm(0, 1)", "", model_string_jags, fixed = TRUE)
if(length(model_me_random) != 0) {
model_string_jags <- gsub("+ d1_e[clus1_me[i]] * eff1[i]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("+ d2_e[clus2_me[i]] * eff2[i]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("+ mu_d_e_hat[1] * mean(eff1[])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("+ mu_d_e_hat[2] * mean(eff2[])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("tau_d_e_hat[t] <- 1 / ss_d_e_hat[t]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("ss_d_e_hat[t] <- s_d_e_hat[t] * s_d_e_hat[t]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("mu_d_e_hat[t] ~ dnorm(0, 1)", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("s_d_e_hat[t] ~ dunif(0, 1)", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for(s in 1:n1_clus_me) {d1_e[s] ~ dnorm(mu_d_e_hat[1], tau_d_e_hat[1]) }", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for(s in 1:n2_clus_me) {d2_e[s] ~ dnorm(mu_d_e_hat[2], tau_d_e_hat[2]) }", "", model_string_jags, fixed = TRUE)
}
if(length(model_mc_random) != 0 & !("c" %in% model_mc_random)) {
model_string_jags <- gsub("+ d1_c[clus1_mc[i]] * cost1[i]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("+ d2_c[clus2_mc[i]] * cost2[i]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("+ mu_d_c_hat[1] * mean(cost1[])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("+ mu_d_c_hat[2] * mean(cost2[])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("tau_d_c_hat[t] <- 1 / ss_d_c_hat[t]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("ss_d_c_hat[t] <- s_d_c_hat[t] * s_d_c_hat[t]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("mu_d_c_hat[t] ~ dnorm(0, 1)", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("s_d_c_hat[t] ~ dunif(0, 1)", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for(s in 1:n1_clus_mc) {d1_c[s] ~ dnorm(mu_d_c_hat[1], tau_d_c_hat[1]) }", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for(s in 1:n2_clus_mc) {d2_c[s] ~ dnorm(mu_d_c_hat[2], tau_d_c_hat[2]) }", "", model_string_jags, fixed = TRUE)
}
if(length(model_mc_random) != 0 & !("c" %in% model_mc_random) & length(model_me_random) != 0 & !("e" %in% model_me_random)) {
model_string_jags <- gsub("
model_string_jags <- gsub("
model_string_jags <- gsub("
model_string_jags <- gsub("for(t in 1:2) {
model_string_jags <- gsub("}
}
} else if(type == "MNAR") {
if(length(model_me_random) != 0 & !("e" %in% model_me_random)) {
model_string_jags <- gsub("+ d1_e[clus1_me[i]] * eff1[i]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("+ d2_e[clus2_me[i]] * eff2[i]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("+ mu_d_e_hat[1] * mean(eff1[])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("+ mu_d_e_hat[2] * mean(eff2[])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("tau_d_e_hat[t] <- 1 / ss_d_e_hat[t]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("ss_d_e_hat[t] <- s_d_e_hat[t] * s_d_e_hat[t]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("mu_d_e_hat[t] ~ dnorm(0, 1)", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("s_d_e_hat[t] ~ dunif(0, 1)", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for(s in 1:n1_clus_me) {d1_e[s] ~ dnorm(mu_d_e_hat[1], tau_d_e_hat[1]) }", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for(s in 1:n2_clus_me) {d2_e[s] ~ dnorm(mu_d_e_hat[2], tau_d_e_hat[2]) }", "", model_string_jags, fixed = TRUE)
}
if(length(model_mc_random) != 0 & !("c" %in% model_mc_random)) {
model_string_jags <- gsub("+ d1_c[clus1_mc[i]] * cost1[i]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("+ d2_c[clus2_mc[i]] * cost2[i]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("+ mu_d_c_hat[1] * mean(cost1[])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("+ mu_d_c_hat[2] * mean(cost2[])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("tau_d_c_hat[t] <- 1 / ss_d_c_hat[t]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("ss_d_c_hat[t] <- s_d_c_hat[t] * s_d_c_hat[t]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("mu_d_c_hat[t] ~ dnorm(0, 1)", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("s_d_c_hat[t] ~ dunif(0, 1)", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for(s in 1:n1_clus_mc) {d1_c[s] ~ dnorm(mu_d_c_hat[1], tau_d_c_hat[1]) }", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for(s in 1:n2_clus_mc) {d2_c[s] ~ dnorm(mu_d_c_hat[2], tau_d_c_hat[2]) }", "", model_string_jags, fixed = TRUE)
}
if(length(model_mc_random) != 0 & !("c" %in% model_mc_random) & length(model_me_random) != 0 & !("e" %in% model_me_random)) {
model_string_jags <- gsub("
model_string_jags <- gsub("
model_string_jags <- gsub("
model_string_jags <- gsub("for(t in 1:2) {
model_string_jags <- gsub("}
}
}
if(ind_random == TRUE) {
model_string_jags <- gsub("+ b1_f[clus1_c[i]] * (eff1[i] - mu_e[1])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("+ b2_f[clus2_c[i]] * (eff2[i] - mu_e[2])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for(s in 1:n1_clus_c) {b1_f[s] ~ dnorm(mu_b_f_hat[1], tau_b_f_hat[1]) }", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for(s in 1:n2_clus_c) {b2_f[s] ~ dnorm(mu_b_f_hat[2], tau_b_f_hat[2]) }", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for(t in 1:2) {mu_b_f_hat[t] ~ dnorm(0, 0.001)", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("tau_b_f_hat[t] <- 1 / ss_b_f_hat[t]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("ss_b_f_hat[t] <- s_b_f_hat[t] * s_b_f_hat[t]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("s_b_f_hat[t] ~ dunif(0, 100) }", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("
}
if(ind_fixed == TRUE) {
model_string_jags <- gsub(" + beta_f[1] * (eff1[i] - mu_e[1])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub(" + beta_f[2] * (eff2[i] - mu_e[2])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("beta_f[t] ~ dnorm(0, 0.0000001)", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("
}
if(dist_c == "norm") {
model_string_jags <- gsub("
model_string_jags <- gsub("
model_string_jags <- gsub("
}
if(dist_c == "gamma") {
model_string_jags <- gsub("cost1[i] ~ dnorm(mu_c1[i], tau_c[1])", "cost1[i] ~ dgamma(mu_c1[i] * tau_c1[i], tau_c1[i])", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("
model_string_jags <- gsub("mu_c1[i] <- ", "log(mu_c1[i]) <- ", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("cost2[i] ~ dnorm(mu_c2[i], tau_c[2])", "cost2[i] ~ dgamma(mu_c2[i] * tau_c2[i], tau_c2[i])", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("
model_string_jags <- gsub("mu_c2[i] <- ", "log(mu_c2[i]) <- ", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("tau_c[t] <- 1 / ss_c[t]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("ss_c[t] <- s_c[t] * s_c[t]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("s_c[t] <- exp(ls_c[t])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("ls_c[t] ~ dunif(-5, 10)", "s_c[t] ~ dunif(0, 10000)", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("loglik_c1[i] <- logdensity.norm(cost1[i], mu_c1[i], tau_c[1])", "loglik_c1[i] <- logdensity.gamma(cost1[i], mu_c1[i] * tau_c1[i], tau_c1[i])", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("loglik_c2[i] <- logdensity.norm(cost2[i], mu_c2[i], tau_c[2])", "loglik_c2[i] <- logdensity.gamma(cost2[i], mu_c2[i] * tau_c2[i], tau_c2[i])", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("
if(length(model_c_random) == 0) {
model_string_jags <- gsub("mu_c[1] <- inprod(mean_cov_c1_fixed[], beta[, 1])", "mu_c[1] <- exp(inprod(mean_cov_c1_fixed[], beta[, 1]))", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("mu_c[2] <- inprod(mean_cov_c2_fixed[], beta[, 2])", "mu_c[2] <- exp(inprod(mean_cov_c2_fixed[], beta[, 2]))", model_string_jags, fixed = TRUE)
}
if(length(model_c_random) != 0) {
model_string_jags <- gsub("mu_c[1] <- inprod(mean_cov_c1_fixed[], beta[, 1]) + inprod(mean_cov_c1_random[], mu_b_hat[, 1])", "mu_c[1] <- exp(inprod(mean_cov_c1_fixed[], beta[, 1]) + inprod(mean_cov_c1_random[], mu_b_hat[, 1]))", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("mu_c[2] <- inprod(mean_cov_c2_fixed[], beta[, 2]) + inprod(mean_cov_c2_random[], mu_b_hat[, 2])", "mu_c[2] <- exp(inprod(mean_cov_c2_fixed[], beta[, 2]) + inprod(mean_cov_c2_random[], mu_b_hat[, 2]))", model_string_jags, fixed = TRUE)
}
} else if(dist_c == "lnorm") {
model_string_jags <- gsub("cost1[i] ~ dnorm(mu_c1[i], tau_c[1])", "cost1[i] ~ dlnorm(lmu_c1[i], ltau_c[1])", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("
model_string_jags <- gsub("mu_c1[i] <- ", "lmu_c1[i] <- ", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("cost2[i] ~ dnorm(mu_c2[i], tau_c[2])", "cost2[i] ~ dlnorm(lmu_c2[i], ltau_c[2])", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("
model_string_jags <- gsub("mu_c2[i] <- ", "lmu_c2[i] <- ", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("tau_c[t] <- 1 / ss_c[t]", "ltau_c[t] <- 1 / lss_c[t]", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("ss_c[t] <- s_c[t] * s_c[t]", "lss_c[t] <- ls_c[t] * ls_c[t]", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("s_c[t] <- exp(ls_c[t])", "s_c[t] <- sqrt(exp(2 * lmu_c[t] + lss_c[t]) * (exp(lss_c[t]) - 1))", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("ls_c[t] ~ dunif(-5, 10)", "ls_c[t] ~ dunif(0, 100)", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("
model_string_jags <- gsub("loglik_c1[i] <- logdensity.norm(cost1[i], mu_c1[i], tau_c[1])", "loglik_c1[i] <- logdensity.lnorm(cost1[i], lmu_c1[i], ltau_c[1])", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("loglik_c2[i] <- logdensity.norm(cost2[i], mu_c2[i], tau_c[2])", "loglik_c2[i] <- logdensity.lnorm(cost2[i], lmu_c2[i], ltau_c[2])", model_string_jags, fixed = TRUE)
if(length(model_c_random) == 0) {
model_string_jags <- gsub("mu_c[1] <- inprod(mean_cov_c1_fixed[], beta[, 1])", "lmu_c[1] <- inprod(mean_cov_c1_fixed[], beta[, 1])", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("mu_c[2] <- inprod(mean_cov_c2_fixed[], beta[, 2])", "lmu_c[2] <- inprod(mean_cov_c2_fixed[], beta[, 2])", model_string_jags, fixed = TRUE)
}
if(length(model_c_random) != 0) {
model_string_jags <- gsub("mu_c[1] <- inprod(mean_cov_c1_fixed[], beta[, 1]) + inprod(mean_cov_c1_random[], mu_b_hat[, 1])", "lmu_c[1] <- inprod(mean_cov_c1_fixed[], beta[, 1]) + inprod(mean_cov_c1_random[], mu_b_hat[, 1])", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("mu_c[2] <- inprod(mean_cov_c2_fixed[], beta[, 2]) + inprod(mean_cov_c2_random[], mu_b_hat[, 2])", "lmu_c[2] <- inprod(mean_cov_c2_fixed[], beta[, 2]) + inprod(mean_cov_c2_random[], mu_b_hat[, 2])", model_string_jags, fixed = TRUE)
}
}
if(dist_e == "norm") {
model_string_jags <- gsub("
model_string_jags <- gsub("
}
if(dist_e == "beta") {
model_string_jags <- gsub("eff1[i] ~ dnorm(mu_e1[i], tau_e[1])", "eff1[i] ~ dbeta(mu_e1[i] * tau_e1[i], (1 - mu_e1[i]) * tau_e1[i])", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("
model_string_jags <- gsub("mu_e1[i] <- ", "logit(mu_e1[i]) <- ", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("eff2[i] ~ dnorm(mu_e2[i], tau_e[2])", "eff2[i] ~ dbeta(mu_e2[i] * tau_e2[i], (1 - mu_e2[i]) * tau_e2[i])", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("
model_string_jags <- gsub("mu_e2[i] <- ", "logit(mu_e2[i]) <- ", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("tau_e[t] <- 1 / ss_e[t]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("ss_e[t] <- s_e[t] * s_e[t]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("s_e[t] <- exp(ls_e[t])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("ls_e[t] ~ dunif(-5, 10)", "s_e[t] ~ dunif(0, sqrt(mu_e[t] * (1 - mu_e[t])))", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("loglik_e1[i] <- logdensity.norm(eff1[i], mu_e1[i], tau_e[1])", "loglik_e1[i] <- logdensity.beta(eff1[i], mu_e1[i] * tau_e1[i], (1 - mu_e1[i]) * tau_e1[i])", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("loglik_e2[i] <- logdensity.norm(eff2[i], mu_e2[i], tau_e[2])", "loglik_e2[i] <- logdensity.beta(eff2[i], mu_e2[i] * tau_e2[i], (1 - mu_e2[i]) * tau_e2[i])", model_string_jags, fixed = TRUE)
if(length(model_e_random) == 0) {
model_string_jags <- gsub("mu_e[1] <- inprod(mean_cov_e1_fixed[], alpha[, 1])", "mu_e[1] <- ilogit(inprod(mean_cov_e1_fixed[], alpha[, 1]))", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("mu_e[2] <- inprod(mean_cov_e2_fixed[], alpha[, 2])", "mu_e[2] <- ilogit(inprod(mean_cov_e2_fixed[], alpha[, 2]))", model_string_jags, fixed = TRUE)
}
if(length(model_e_random) != 0) {
model_string_jags <- gsub("mu_e[1] <- inprod(mean_cov_e1_fixed[], alpha[, 1]) + inprod(mean_cov_e1_random[], mu_a_hat[, 1])", "mu_e[1] <- ilogit(inprod(mean_cov_e1_fixed[], alpha[, 1]) + inprod(mean_cov_e1_random[], mu_a_hat[, 1]))", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("mu_e[2] <- inprod(mean_cov_e2_fixed[], alpha[, 2]) + inprod(mean_cov_e2_random[], mu_a_hat[, 2])", "mu_e[2] <- ilogit(inprod(mean_cov_e2_fixed[], alpha[, 2]) + inprod(mean_cov_e2_random[], mu_a_hat[, 2]))", model_string_jags, fixed = TRUE)
}
} else if(dist_e == "gamma"){
model_string_jags <- gsub("eff1[i] ~ dnorm(mu_e1[i], tau_e[1])", "eff1[i] ~ dgamma(mu_e1[i] * tau_e1[i], tau_e1[i])", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("
model_string_jags <- gsub("mu_e1[i] <- ", "log(mu_e1[i]) <- ", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("eff2[i] ~ dnorm(mu_e2[i], tau_e[2])", "eff2[i] ~ dgamma(mu_e2[i] * tau_e2[i], tau_e2[i])", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("
model_string_jags <- gsub("mu_e2[i] <- ", "log(mu_e2[i]) <- ", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("tau_e[t] <- 1 / ss_e[t]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("ss_e[t] <- s_e[t] * s_e[t]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("s_e[t] <- exp(ls_e[t])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("ls_e[t] ~ dunif(-5, 10)", "s_e[t] ~ dunif(0, 10000)", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("loglik_e1[i] <- logdensity.norm(eff1[i], mu_e1[i], tau_e[1])", "loglik_e1[i] <- logdensity.gamma(eff1[i], mu_e1[i] * tau_e1[i], tau_e1[i])", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("loglik_e2[i] <- logdensity.norm(eff2[i], mu_e2[i], tau_e[2])", "loglik_e2[i] <- logdensity.gamma(eff2[i], mu_e2[i] * tau_e2[i], tau_e2[i])", model_string_jags, fixed = TRUE)
if(length(model_e_random) == 0) {
model_string_jags <- gsub("mu_e[1] <- inprod(mean_cov_e1_fixed[], alpha[, 1])", "mu_e[1] <- exp(inprod(mean_cov_e1_fixed[], alpha[, 1]))", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("mu_e[2] <- inprod(mean_cov_e2_fixed[], alpha[, 2])", "mu_e[2] <- exp(inprod(mean_cov_e2_fixed[], alpha[, 2]))", model_string_jags, fixed = TRUE)
}
if(length(model_e_random) != 0) {
model_string_jags <- gsub("mu_e[1] <- inprod(mean_cov_e1_fixed[], alpha[, 1]) + inprod(mean_cov_e1_random[], mu_a_hat[, 1])", "mu_e[1] <- exp(inprod(mean_cov_e1_fixed[], alpha[, 1]) + inprod(mean_cov_e1_random[], mu_a_hat[, 1]))", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("mu_e[2] <- inprod(mean_cov_e2_fixed[], alpha[, 2]) + inprod(mean_cov_e2_random[], mu_a_hat[, 2])", "mu_e[2] <- exp(inprod(mean_cov_e2_fixed[], alpha[, 2]) + inprod(mean_cov_e2_random[], mu_a_hat[, 2]))", model_string_jags, fixed = TRUE)
}
} else if(dist_e == "exp"){
model_string_jags <- gsub("eff1[i] ~ dnorm(mu_e1[i], tau_e[1])", "eff1[i] ~ dexp(1 / mu_e1[i])", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("
model_string_jags <- gsub("mu_e1[i] <- ", "log(mu_e1[i]) <- ", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("eff2[i] ~ dnorm(mu_e2[i], tau_e[2])", "eff2[i] ~ dexp(1 / mu_e2[i])", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("
model_string_jags <- gsub("mu_e2[i] <- ", "log(mu_e2[i]) <- ", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("tau_e[t] <- 1 / ss_e[t]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("ss_e[t] <- s_e[t] * s_e[t]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("s_e[t] <- exp(ls_e[t])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("ls_e[t] ~ dunif(-5, 10)", "s_e[t] <- mu_e[t]", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("loglik_e1[i] <- logdensity.norm(eff1[i], mu_e1[i], tau_e[1])", "loglik_e1[i] <- logdensity.exp(eff1[i], 1/mu_e1[i])", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("loglik_e2[i] <- logdensity.norm(eff2[i], mu_e2[i], tau_e[2])", "loglik_e2[i] <- logdensity.exp(eff2[i], 1/mu_e2[i])", model_string_jags, fixed = TRUE)
if(length(model_e_random) == 0) {
model_string_jags <- gsub("mu_e[1] <- inprod(mean_cov_e1_fixed[], alpha[, 1])", "mu_e[1] <- exp(inprod(mean_cov_e1_fixed[], alpha[, 1]))", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("mu_e[2] <- inprod(mean_cov_e2_fixed[], alpha[, 2])", "mu_e[2] <- exp(inprod(mean_cov_e2_fixed[], alpha[, 2]))", model_string_jags, fixed = TRUE)
}
if(length(model_e_random) != 0) {
model_string_jags <- gsub("mu_e[1] <- inprod(mean_cov_e1_fixed[], alpha[, 1]) + inprod(mean_cov_e1_random[], mu_a_hat[, 1])", "mu_e[1] <- exp(inprod(mean_cov_e1_fixed[], alpha[, 1]) + inprod(mean_cov_e1_random[], mu_a_hat[, 1]))", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("mu_e[2] <- inprod(mean_cov_e2_fixed[], alpha[, 2]) + inprod(mean_cov_e2_random[], mu_a_hat[, 2])", "mu_e[2] <- exp(inprod(mean_cov_e2_fixed[], alpha[, 2]) + inprod(mean_cov_e2_random[], mu_a_hat[, 2]))", model_string_jags, fixed = TRUE)
}
} else if(dist_e == "weibull"){
model_string_jags <- gsub("eff1[i] ~ dnorm(mu_e1[i], tau_e[1])", "eff1[i] ~ dweib(tau_e1[i], pow(1 / (mu_e1[i] / exp(loggam(1 + 1/tau_e1[i]))), tau_e1[i]))", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("
model_string_jags <- gsub("mu_e1[i] <- ", "log(mu_e1[i]) <- ", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("eff2[i] ~ dnorm(mu_e2[i], tau_e[2])", "eff2[i] ~ dweib(tau_e2[i], pow(1 / (mu_e2[i] / exp(loggam(1 + 1/tau_e2[i]))), tau_e2[i]))", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("
model_string_jags <- gsub("mu_e2[i] <- ", "log(mu_e2[i]) <- ", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("tau_e[t] <- 1 / ss_e[t]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("ss_e[t] <- s_e[t] * s_e[t]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("s_e[t] <- exp(ls_e[t])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("ls_e[t] ~ dunif(-5, 10)", "s_e[t] ~ dunif(0, 100)", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("loglik_e1[i] <- logdensity.norm(eff1[i], mu_e1[i], tau_e[1])", "loglik_e1[i] <- logdensity.weib(eff1[i], tau_e1[i], pow(1 / (mu_e1[i] / exp(loggam(1 + 1/tau_e1[i]))), tau_e1[i]))", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("loglik_e2[i] <- logdensity.norm(eff2[i], mu_e2[i], tau_e[2])", "loglik_e2[i] <- logdensity.weib(eff2[i], tau_e2[i], pow(1 / (mu_e2[i] / exp(loggam(1 + 1/tau_e2[i]))), tau_e2[i]))", model_string_jags, fixed = TRUE)
if(length(model_e_random) == 0) {
model_string_jags <- gsub("mu_e[1] <- inprod(mean_cov_e1_fixed[], alpha[, 1])", "mu_e[1] <- exp(inprod(mean_cov_e1_fixed[], alpha[, 1]))", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("mu_e[2] <- inprod(mean_cov_e2_fixed[], alpha[, 2])", "mu_e[2] <- exp(inprod(mean_cov_e2_fixed[], alpha[, 2]))", model_string_jags, fixed = TRUE)
}
if(length(model_e_random) != 0) {
model_string_jags <- gsub("mu_e[1] <- inprod(mean_cov_e1_fixed[], alpha[, 1]) + inprod(mean_cov_e1_random[], mu_a_hat[, 1])", "mu_e[1] <- exp(inprod(mean_cov_e1_fixed[], alpha[, 1]) + inprod(mean_cov_e1_random[], mu_a_hat[, 1]))", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("mu_e[2] <- inprod(mean_cov_e2_fixed[], alpha[, 2]) + inprod(mean_cov_e2_random[], mu_a_hat[, 2])", "mu_e[2] <- exp(inprod(mean_cov_e2_fixed[], alpha[, 2]) + inprod(mean_cov_e2_random[], mu_a_hat[, 2]))", model_string_jags, fixed = TRUE)
}
} else if(dist_e == "logis"){
model_string_jags <- gsub("eff1[i] ~ dnorm(mu_e1[i], tau_e[1])", "eff1[i] ~ dlogis(mu_e1[i], tau_e[1])", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("eff2[i] ~ dnorm(mu_e2[i], tau_e[2])", "eff2[i] ~ dlogis(mu_e2[i], tau_e[2])", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("tau_e[t] <- 1 / ss_e[t]", "tau_e[t] <- 1 / sqrt((3 * ss_e[t]) / pow(3.14159265 , 2))", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("s_e[t] <- exp(ls_e[t])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("ls_e[t] ~ dunif(-5, 10)", "s_e[t] ~ dunif(0, 10000)", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("loglik_e1[i] <- logdensity.norm(eff1[i], mu_e1[i], tau_e[1])", "loglik_e1[i] <- logdensity.logis(eff1[i], mu_e1[i], tau_e[1])", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("loglik_e2[i] <- logdensity.norm(eff2[i], mu_e2[i], tau_e[2])", "loglik_e2[i] <- logdensity.logis(eff2[i], mu_e2[i], tau_e[2])", model_string_jags, fixed = TRUE)
} else if(dist_e == "bern"){
model_string_jags <- gsub("eff1[i] ~ dnorm(mu_e1[i], tau_e[1])", "eff1[i] ~ dbern(mu_e1[i])", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("
model_string_jags <- gsub("mu_e1[i] <- ", "logit(mu_e1[i]) <- ", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("eff2[i] ~ dnorm(mu_e2[i], tau_e[2])", "eff2[i] ~ dbern(mu_e2[i])", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("
model_string_jags <- gsub("mu_e2[i] <- ", "logit(mu_e2[i]) <- ", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("tau_e[t] <- 1 / ss_e[t]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("ss_e[t] <- s_e[t] * s_e[t]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("s_e[t] <- exp(ls_e[t])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("ls_e[t] ~ dunif(-5, 10)", "s_e[t] <- sqrt(mu_e[t] * (1 - mu_e[t]))", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("loglik_e1[i] <- logdensity.norm(eff1[i], mu_e1[i], tau_e[1])", "loglik_e1[i] <- logdensity.bern(eff1[i], mu_e1[i])", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("loglik_e2[i] <- logdensity.norm(eff2[i], mu_e2[i], tau_e[2])", "loglik_e2[i] <- logdensity.bern(eff2[i], mu_e2[i])", model_string_jags, fixed = TRUE)
if(length(model_e_random) == 0) {
model_string_jags <- gsub("mu_e[1] <- inprod(mean_cov_e1_fixed[], alpha[, 1])", "mu_e[1] <- ilogit(inprod(mean_cov_e1_fixed[], alpha[, 1]))", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("mu_e[2] <- inprod(mean_cov_e2_fixed[], alpha[, 2])", "mu_e[2] <- ilogit(inprod(mean_cov_e2_fixed[], alpha[, 2]))", model_string_jags, fixed = TRUE)
}
if(length(model_e_random) != 0) {
model_string_jags <- gsub("mu_e[1] <- inprod(mean_cov_e1_fixed[], alpha[, 1]) + inprod(mean_cov_e1_random[], mu_a_hat[, 1])", "mu_e[1] <- ilogit(inprod(mean_cov_e1_fixed[], alpha[, 1]) + inprod(mean_cov_e1_random[], mu_a_hat[, 1]))", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("mu_e[2] <- inprod(mean_cov_e2_fixed[], alpha[, 2]) + inprod(mean_cov_e2_random[], mu_a_hat[, 2])", "mu_e[2] <- ilogit(inprod(mean_cov_e2_fixed[], alpha[, 2]) + inprod(mean_cov_e2_random[], mu_a_hat[, 2]))", model_string_jags, fixed = TRUE)
}
} else if(dist_e == "pois"){
model_string_jags <- gsub("eff1[i] ~ dnorm(mu_e1[i], tau_e[1])", "eff1[i] ~ dpois(mu_e1[i])", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("
model_string_jags <- gsub("mu_e1[i] <- ", "log(mu_e1[i]) <- ", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("eff2[i] ~ dnorm(mu_e2[i], tau_e[2])", "eff2[i] ~ dpois(mu_e2[i])", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("
model_string_jags <- gsub("mu_e2[i] <- ", "log(mu_e2[i]) <- ", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("tau_e[t] <- 1 / ss_e[t]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("ss_e[t] <- s_e[t] * s_e[t]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("s_e[t] <- exp(ls_e[t])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("ls_e[t] ~ dunif(-5, 10)", "s_e[t] <- sqrt(mu_e[t])", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("loglik_e1[i] <- logdensity.norm(eff1[i], mu_e1[i], tau_e[1])", "loglik_e1[i] <- logdensity.pois(eff1[i], mu_e1[i])", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("loglik_e2[i] <- logdensity.norm(eff2[i], mu_e2[i], tau_e[2])", "loglik_e2[i] <- logdensity.pois(eff2[i], mu_e2[i])", model_string_jags, fixed = TRUE)
if(length(model_e_random) == 0) {
model_string_jags <- gsub("mu_e[1] <- inprod(mean_cov_e1_fixed[], alpha[, 1])", "mu_e[1] <- exp(inprod(mean_cov_e1_fixed[], alpha[, 1]))", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("mu_e[2] <- inprod(mean_cov_e2_fixed[], alpha[, 2])", "mu_e[2] <- exp(inprod(mean_cov_e2_fixed[], alpha[, 2]))", model_string_jags, fixed = TRUE)
}
if(length(model_e_random) != 0) {
model_string_jags <- gsub("mu_e[1] <- inprod(mean_cov_e1_fixed[], alpha[, 1]) + inprod(mean_cov_e1_random[], mu_a_hat[, 1])", "mu_e[1] <- exp(inprod(mean_cov_e1_fixed[], alpha[, 1]) + inprod(mean_cov_e1_random[], mu_a_hat[, 1]))", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("mu_e[2] <- inprod(mean_cov_e2_fixed[], alpha[, 2]) + inprod(mean_cov_e2_random[], mu_a_hat[, 2])", "mu_e[2] <- exp(inprod(mean_cov_e2_fixed[], alpha[, 2]) + inprod(mean_cov_e2_random[], mu_a_hat[, 2]))", model_string_jags, fixed = TRUE)
}
} else if(dist_e == "nbinom"){
model_string_jags <- gsub("eff1[i] ~ dnorm(mu_e1[i], tau_e[1])", "eff1[i] ~ dnegbin(tau_e[1] / (tau_e[1] + mu_e1[i]), tau_e[1])", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("
model_string_jags <- gsub("mu_e1[i] <- ", "log(mu_e1[i]) <- ", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("eff2[i] ~ dnorm(mu_e2[i], tau_e[2])", "eff2[i] ~ dnegbin(tau_e[2] / (tau_e[2] + mu_e2[i]), tau_e[2])", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("
model_string_jags <- gsub("mu_e2[i] <- ", "log(mu_e2[i]) <- ", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("tau_e[t] <- 1 / ss_e[t]", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("ss_e[t] <- s_e[t] * s_e[t]", "s_e[t] <- sqrt((tau_e[t] / (tau_e[t] + mu_e[t])) * tau_e[t]) / (1 - (tau_e[t] / (tau_e[t] + mu_e[t])))", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("s_e[t] <- exp(ls_e[t])", "", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("ls_e[t] ~ dunif(-5, 10)", "tau_e[t] ~ dunif(0, 100)", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("loglik_e1[i] <- logdensity.norm(eff1[i], mu_e1[i], tau_e[1])", "loglik_e1[i] <- logdensity.negbin(eff1[i], tau_e[1] / (tau_e[1] + mu_e1[i]), tau_e[1])", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("loglik_e2[i] <- logdensity.norm(eff2[i], mu_e2[i], tau_e[2])", "loglik_e2[i] <- logdensity.negbin(eff2[i], tau_e[2] / (tau_e[2] + mu_e2[i]), tau_e[2])", model_string_jags, fixed = TRUE)
if(length(model_e_random) == 0) {
model_string_jags <- gsub("mu_e[1] <- inprod(mean_cov_e1_fixed[], alpha[, 1])", "mu_e[1] <- exp(inprod(mean_cov_e1_fixed[], alpha[, 1]))", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("mu_e[2] <- inprod(mean_cov_e2_fixed[], alpha[, 2])", "mu_e[2] <- exp(inprod(mean_cov_e2_fixed[], alpha[, 2]))", model_string_jags, fixed = TRUE)
}
if(length(model_e_random) != 0) {
model_string_jags <- gsub("mu_e[1] <- inprod(mean_cov_e1_fixed[], alpha[, 1]) + inprod(mean_cov_e1_random[], mu_a_hat[, 1])", "mu_e[1] <- exp(inprod(mean_cov_e1_fixed[], alpha[, 1]) + inprod(mean_cov_e1_random[], mu_a_hat[, 1]))", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("mu_e[2] <- inprod(mean_cov_e2_fixed[], alpha[, 2]) + inprod(mean_cov_e2_random[], mu_a_hat[, 2])", "mu_e[2] <- exp(inprod(mean_cov_e2_fixed[], alpha[, 2]) + inprod(mean_cov_e2_random[], mu_a_hat[, 2]))", model_string_jags, fixed = TRUE)
}
}
if(dist_e %in% c("beta", "gamma", "weibull", "bern", "pois", "exp")) {
if(dist_c == "gamma"){
model_string_jags <- gsub("for (t in 1:2) {
model_string_jags <- gsub("}
model_string_jags <- gsub("
}
}
if(pe_fixed == 1) {
inprod_e1 <- "X1_e_fixed[i] * alpha[1]"
inprod_e2 <- "X2_e_fixed[i] * alpha[2]"
inprod_mean_e1 <- "mean_cov_e1_fixed * alpha[1]"
inprod_mean_e2 <- "mean_cov_e2_fixed * alpha[2]"
begin_prior_beta <- "
prior_beta <- "
end_prior_beta <- "
prior_beta_e1 <- "alpha[1] ~ dnorm(0, 0.0000001)"
prior_beta_e2 <- "alpha[2] ~ dnorm(0, 0.0000001)"
model_string_jags <- gsub("inprod(X1_e_fixed[i, ], alpha[, 1])", inprod_e1, model_string_jags, fixed = TRUE)
model_string_jags <- gsub("inprod(X2_e_fixed[i, ], alpha[, 2])", inprod_e2, model_string_jags, fixed = TRUE)
model_string_jags <- gsub("inprod(mean_cov_e1_fixed[], alpha[, 1])", inprod_mean_e1, model_string_jags, fixed = TRUE)
model_string_jags <- gsub("inprod(mean_cov_e2_fixed[], alpha[, 2])", inprod_mean_e2, model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for (j in 2:pe_fixed) {
model_string_jags <- gsub("for(t in 1:2) {alpha[j, t] ~ dnorm(0, 0.0000001) }", prior_beta, model_string_jags, fixed = TRUE)
model_string_jags <- gsub("}
model_string_jags <- gsub("alpha[1, 1] ~ dnorm(0, 0.0000001)", prior_beta_e1, model_string_jags, fixed = TRUE)
model_string_jags <- gsub("alpha[1, 2] ~ dnorm(0, 0.0000001)", prior_beta_e2, model_string_jags, fixed = TRUE)
}
if(length(model_e_random) != 0 & pe_random == 1) {
model_string_jags <- gsub("inprod(X1_e_random[i, ], a1[, clus1_e[i]])", "X1_e_random[i] * a1[clus1_e[i]]", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("inprod(X2_e_random[i, ], a2[, clus2_e[i]])", "X2_e_random[i] * a2[clus2_e[i]]", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("inprod(mean_cov_e1_random[], mu_a_hat[, 1])", "mean_cov_e1_random * mu_a_hat[1]", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("inprod(mean_cov_e2_random[], mu_a_hat[, 2])", "mean_cov_e2_random * mu_a_hat[2]", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for (j in 1:pe_random) {
model_string_jags <- gsub("for(s in 1:n1_clus_e) {a1[j, s] ~ dnorm(mu_a_hat[j, 1], tau_a_hat[j, 1]) }", "for(s in 1:n1_clus_e) {a1[s] ~ dnorm(mu_a_hat[1], tau_a_hat[1]) }", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("}
model_string_jags <- gsub("for (j in 1:pe_random) {
model_string_jags <- gsub("for(s in 1:n2_clus_e) {a2[j, s] ~ dnorm(mu_a_hat[j, 2], tau_a_hat[j, 2]) }", "for(s in 1:n2_clus_e) {a2[s] ~ dnorm(mu_a_hat[2], tau_a_hat[2]) }", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("}
model_string_jags <- gsub("for(j in 1:pe_random) {mu_a_hat[j, t] ~ dnorm(0, 0.001)", "mu_a_hat[t] ~ dnorm(0, 0.001)", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("s_a_hat[j, t] ~ dunif(0, 100) }", "s_a_hat[t] ~ dunif(0, 100)", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for(j in 1:pe_random) {tau_a_hat[j, t] <- 1 / ss_a_hat[j, t]", "tau_a_hat[t] <- 1 / ss_a_hat[t]", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("ss_a_hat[j, t] <- s_a_hat[j, t] * s_a_hat[j, t] }", "ss_a_hat[t] <- s_a_hat[t] * s_a_hat[t]", model_string_jags, fixed = TRUE)
}
if(pc_fixed == 1) {
inprod_c1 <- "X1_c_fixed[i] * beta[1]"
inprod_c2 <- "X2_c_fixed[i] * beta[2]"
inprod_mean_c1 <- "mean_cov_c1_fixed * beta[1]"
inprod_mean_c2 <- "mean_cov_c2_fixed * beta[2]"
begin_prior_beta <- "
prior_beta <- "
end_prior_beta <- "
prior_beta_c1 <- "beta[1] ~ dnorm(0, 0.0000001)"
prior_beta_c2 <- "beta[2] ~ dnorm(0, 0.0000001)"
model_string_jags <- gsub("inprod(X1_c_fixed[i, ], beta[, 1])", inprod_c1, model_string_jags, fixed = TRUE)
model_string_jags <- gsub("inprod(X2_c_fixed[i, ], beta[, 2])", inprod_c2, model_string_jags, fixed = TRUE)
model_string_jags <- gsub("inprod(mean_cov_c1_fixed[], beta[, 1])", inprod_mean_c1, model_string_jags, fixed = TRUE)
model_string_jags <- gsub("inprod(mean_cov_c2_fixed[], beta[, 2])", inprod_mean_c2, model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for (j in 2:pc_fixed) {
model_string_jags <- gsub("for(t in 1:2) {beta[j, t] ~ dnorm(0, 0.0000001) }", prior_beta, model_string_jags, fixed = TRUE)
model_string_jags <- gsub("}
model_string_jags <- gsub("beta[1, 1] ~ dnorm(0, 0.0000001)", prior_beta_c1, model_string_jags, fixed = TRUE)
model_string_jags <- gsub("beta[1, 2] ~ dnorm(0, 0.0000001)", prior_beta_c2, model_string_jags, fixed = TRUE)
}
if(length(model_c_random) != 0 & pc_random == 1) {
model_string_jags <- gsub("inprod(X1_c_random[i, ], b1[, clus1_c[i]])", "X1_c_random[i] * b1[clus1_c[i]]", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("inprod(X2_c_random[i, ], b2[, clus2_c[i]])", "X2_c_random[i] * b2[clus2_c[i]]", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("inprod(mean_cov_c1_random[], mu_b_hat[, 1])", "mean_cov_c1_random * mu_b_hat[1]", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("inprod(mean_cov_c2_random[], mu_b_hat[, 2])", "mean_cov_c2_random * mu_b_hat[2]", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for (j in 1:pc_random) {
model_string_jags <- gsub("for(s in 1:n1_clus_c) {b1[j, s] ~ dnorm(mu_b_hat[j, 1], tau_b_hat[j, 1]) }", "for(s in 1:n1_clus_c) {b1[s] ~ dnorm(mu_b_hat[1], tau_b_hat[1]) }", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("}
model_string_jags <- gsub("for (j in 1:pc_random) {
model_string_jags <- gsub("for(s in 1:n2_clus_c) {b2[j, s] ~ dnorm(mu_b_hat[j, 2], tau_b_hat[j, 2]) }", "for(s in 1:n2_clus_c) {b2[s] ~ dnorm(mu_b_hat[2], tau_b_hat[2]) }", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("}
model_string_jags <- gsub("for(j in 1:pc_random) {mu_b_hat[j, t] ~ dnorm(0, 0.001)", "mu_b_hat[t] ~ dnorm(0, 0.001)", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("s_b_hat[j, t] ~ dunif(0, 100) }", "s_b_hat[t] ~ dunif(0, 100)", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for(j in 1:pc_random) {tau_b_hat[j, t] <- 1 / ss_b_hat[j, t]", "tau_b_hat[t] <- 1 / ss_b_hat[t]", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("ss_b_hat[j, t] <- s_b_hat[j, t] * s_b_hat[j, t] }", "ss_b_hat[t] <- s_b_hat[t] * s_b_hat[t]", model_string_jags, fixed = TRUE)
}
if(ze_fixed == 1) {
inprod_e1 <- "Z1_e_fixed[i] * gamma_e[1]"
inprod_e2 <- "Z2_e_fixed[i] * gamma_e[2]"
if(type == "MAR" | type == "MNAR_cost") {
inprod_mean_e1 <- "mean_z_e1_fixed * gamma_e[1]"
inprod_mean_e2 <- "mean_z_e2_fixed * gamma_e[2]"
model_string_jags <- gsub("inprod(mean_z_e1_fixed[], gamma_e[, 1])", inprod_mean_e1, model_string_jags, fixed = TRUE)
model_string_jags <- gsub("inprod(mean_z_e2_fixed[], gamma_e[, 2])", inprod_mean_e2, model_string_jags, fixed = TRUE)
}
if(type == "MNAR_eff" | type == "MNAR") {
inprod_mean_e1 <- "mean_z_e1_fixed * gamma_e[1] + delta_e[1] * mean(eff1[])"
inprod_mean_e2 <- "mean_z_e2_fixed * gamma_e[2] + delta_e[2] * mean(eff2[])"
model_string_jags <- gsub("inprod(mean_z_e1_fixed[], gamma_e[, 1]) + delta_e[1] * mean(eff1[])", inprod_mean_e1, model_string_jags, fixed = TRUE)
model_string_jags <- gsub("inprod(mean_z_e2_fixed[], gamma_e[, 2]) + delta_e[2] * mean(eff2[])", inprod_mean_e2, model_string_jags, fixed = TRUE)
}
begin_prior_gamma <- "
begin_prior_gamma2 <- "
prior_gamma_e1 <- "gamma_e[1] ~ dlogis(0, 1)"
prior_gamma_e2 <- "gamma_e[2] ~ dlogis(0, 1)"
end_prior_gamma <- "
model_string_jags <- gsub("inprod(Z1_e_fixed[i, ], gamma_e[, 1])", inprod_e1, model_string_jags, fixed = TRUE)
model_string_jags <- gsub("inprod(Z2_e_fixed[i, ], gamma_e[, 2])", inprod_e2, model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for (j in 2:ze_fixed) {
model_string_jags <- gsub("for(t in 1:2) {gamma_e[j, t] ~ dnorm(0, 0.01) }", begin_prior_gamma2, model_string_jags, fixed = TRUE)
model_string_jags <- gsub("gamma_e[1, 1] ~ dlogis(0, 1)", prior_gamma_e1, model_string_jags, fixed = TRUE)
model_string_jags <- gsub("gamma_e[1, 2] ~ dlogis(0, 1)", prior_gamma_e2, model_string_jags, fixed = TRUE)
model_string_jags <- gsub("}
}
if(ze_random == 1 & length(model_me_random) != 0) {
if(type == "MAR" | type == "MNAR_cost") {
model_string_jags <- gsub("inprod(mean_z_e1_random[], mu_g_e_hat[, 1])", "mean_z_e1_random * mu_g_e_hat[1]", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("inprod(mean_z_e2_random[], mu_g_e_hat[, 2])", "mean_z_e2_random * mu_g_e_hat[2]", model_string_jags, fixed = TRUE)
}
if(type == "MNAR_eff" | type == "MNAR") {
model_string_jags <- gsub("inprod(mean_z_e1_random[], mu_g_e_hat[, 1]) + mu_d_e_hat[1] * mean(eff1[])", "mean_z_e1_random * mu_g_e_hat[1] + mu_d_e_hat[1] * mean(eff1[])", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("inprod(mean_z_e2_random[], mu_g_e_hat[, 2]) + mu_d_e_hat[2] * mean(eff2[])", "mean_z_e2_random * mu_g_e_hat[2] + mu_d_e_hat[2] * mean(eff2[])", model_string_jags, fixed = TRUE)
}
model_string_jags <- gsub("inprod(Z1_e_random[i, ], g1_e[, clus1_me[i]])", "Z1_e_random[i] * g1_e[clus1_me[i]]", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("inprod(Z2_e_random[i, ], g2_e[, clus2_me[i]])", "Z2_e_random[i] * g2_e[clus2_me[i]]", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for(j in 1:ze_random) {tau_g_e_hat[j, t] <- 1 / ss_g_e_hat[j, t]", "tau_g_e_hat[t] <- 1 / ss_g_e_hat[t]", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("ss_g_e_hat[j, t] <- s_g_e_hat[j, t] * s_g_e_hat[j, t] }", "ss_g_e_hat[t] <- s_g_e_hat[t] * s_g_e_hat[t]", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("inprod(mean_z_e1_random[], mu_g_e_hat[, 1])", "mean_z_e1_random * mu_g_e_hat[1]", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("inprod(mean_z_e2_random[], mu_g_e_hat[, 2])", "mean_z_e2_random * mu_g_e_hat[2]", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for (j in 1:ze_random) {
model_string_jags <- gsub("for(s in 1:n1_clus_me) {g1_e[j, s] ~ dnorm(mu_g_e_hat[j, 1], tau_g_e_hat[j, 1]) }", "for(s in 1:n1_clus_me) {g1_e[s] ~ dnorm(mu_g_e_hat[1], tau_g_e_hat[1]) }", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("}
model_string_jags <- gsub("for (j in 1:ze_random) {
model_string_jags <- gsub("for(s in 1:n2_clus_me) {g2_e[j, s] ~ dnorm(mu_g_e_hat[j, 2], tau_g_e_hat[j, 2]) }", "for(s in 1:n2_clus_me) {g2_e[s] ~ dnorm(mu_g_e_hat[2], tau_g_e_hat[2]) }", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("}
model_string_jags <- gsub("for(j in 1:ze_random) {mu_g_e_hat[j, t] ~ dnorm(0, 0.001)", "mu_g_e_hat[t] ~ dnorm(0, 0.001)", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("s_g_e_hat[j, t] ~ dunif(0, 100) }", "s_g_e_hat[t] ~ dunif(0, 100)", model_string_jags, fixed = TRUE)
}
if(zc_fixed == 1) {
inprod_c1 <- "Z1_c_fixed[i] * gamma_c[1]"
inprod_c2 <- "Z2_c_fixed[i] * gamma_c[2]"
if(type == "MAR" | type == "MNAR_eff") {
inprod_mean_c1 <- "mean_z_c1_fixed * gamma_c[1]"
inprod_mean_c2 <- "mean_z_c2_fixed * gamma_c[2]"
model_string_jags <- gsub("inprod(mean_z_c1_fixed[], gamma_c[, 1])", inprod_mean_c1, model_string_jags, fixed = TRUE)
model_string_jags <- gsub("inprod(mean_z_c2_fixed[], gamma_c[, 2])", inprod_mean_c2, model_string_jags, fixed = TRUE)
}
if(type == "MNAR_cost" | type == "MNAR") {
inprod_mean_c1 <- "mean_z_c1_fixed * gamma_c[1] + delta_c[1] * mean(cost1[])"
inprod_mean_c2 <- "mean_z_c2_fixed * gamma_c[2] + delta_c[2] * mean(cost2[])"
model_string_jags <- gsub("inprod(mean_z_c1_fixed[], gamma_c[, 1]) + delta_c[1] * mean(cost1[])", inprod_mean_c1, model_string_jags, fixed = TRUE)
model_string_jags <- gsub("inprod(mean_z_c2_fixed[], gamma_c[, 2]) + delta_c[2] * mean(cost2[])", inprod_mean_c2, model_string_jags, fixed = TRUE)
}
begin_prior_gamma <- "
begin_prior_gamma2 <- "
prior_gamma_c1 <- "gamma_c[1] ~ dlogis(0, 1)"
prior_gamma_c2 <- "gamma_c[2] ~ dlogis(0, 1)"
end_prior_gamma <- "
model_string_jags <- gsub("inprod(Z1_c_fixed[i, ], gamma_c[, 1])", inprod_c1, model_string_jags, fixed = TRUE)
model_string_jags <- gsub("inprod(Z2_c_fixed[i, ], gamma_c[, 2])", inprod_c2, model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for (j in 2:zc_fixed) {
model_string_jags <- gsub("for(t in 1:2) {gamma_c[j, t] ~ dnorm(0, 0.01) }", begin_prior_gamma2, model_string_jags, fixed = TRUE)
model_string_jags <- gsub("gamma_c[1, 1] ~ dlogis(0, 1)", prior_gamma_c1, model_string_jags, fixed = TRUE)
model_string_jags <- gsub("gamma_c[1, 2] ~ dlogis(0, 1)", prior_gamma_c2, model_string_jags, fixed = TRUE)
model_string_jags <- gsub("}
}
if(zc_random == 1 & length(model_mc_random) != 0) {
if(type == "MAR" | type == "MNAR_eff") {
model_string_jags <- gsub("inprod(mean_z_c1_random[], mu_g_c_hat[, 1])", "mean_z_c1_random * mu_g_c_hat[1]", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("inprod(mean_z_c2_random[], mu_g_c_hat[, 2])", "mean_z_c2_random * mu_g_c_hat[2]", model_string_jags, fixed = TRUE)
}
if(type == "MNAR_cost" | type == "MNAR") {
model_string_jags <- gsub("inprod(mean_z_c1_random[], mu_g_c_hat[, 1]) + mu_d_c_hat[1] * mean(cost1[])", "mean_z_c1_random * mu_g_c_hat[1] + mu_d_c_hat[1] * mean(cost1[])", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("inprod(mean_z_c2_random[], mu_g_c_hat[, 2]) + mu_d_c_hat[2] * mean(cost2[])", "mean_z_c2_random * mu_g_c_hat[2] + mu_d_c_hat[2] * mean(cost2[])", model_string_jags, fixed = TRUE)
}
model_string_jags <- gsub("inprod(Z1_c_random[i, ], g1_c[, clus1_mc[i]])", "Z1_c_random[i] * g1_c[clus1_mc[i]]", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("inprod(Z2_c_random[i, ], g2_c[, clus2_mc[i]])", "Z2_c_random[i] * g2_c[clus2_mc[i]]", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for(j in 1:zc_random) {tau_g_c_hat[j, t] <- 1 / ss_g_c_hat[j, t]", "tau_g_c_hat[t] <- 1 / ss_g_c_hat[t]", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("ss_g_c_hat[j, t] <- s_g_c_hat[j, t] * s_g_c_hat[j, t] }", "ss_g_c_hat[t] <- s_g_c_hat[t] * s_g_c_hat[t]", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("inprod(mean_z_c1_random[], mu_g_c_hat[, 1])", "mean_z_c1_random * mu_g_c_hat[1]", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("inprod(mean_z_c2_random[], mu_g_c_hat[, 2])", "mean_z_c2_random * mu_g_c_hat[2]", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("for (j in 1:zc_random) {
model_string_jags <- gsub("for(s in 1:n1_clus_mc) {g1_c[j, s] ~ dnorm(mu_g_c_hat[j, 1], tau_g_c_hat[j, 1]) }", "for(s in 1:n1_clus_mc) {g1_c[s] ~ dnorm(mu_g_c_hat[1], tau_g_c_hat[1]) }", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("}
model_string_jags <- gsub("for (j in 1:zc_random) {
model_string_jags <- gsub("for(s in 1:n2_clus_mc) {g2_c[j, s] ~ dnorm(mu_g_c_hat[j, 2], tau_g_c_hat[j, 2]) }", "for(s in 1:n2_clus_mc) {g2_c[s] ~ dnorm(mu_g_c_hat[2], tau_g_c_hat[2]) }", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("}
model_string_jags <- gsub("for(j in 1:zc_random) {mu_g_c_hat[j, t] ~ dnorm(0, 0.001)", "mu_g_c_hat[t] ~ dnorm(0, 0.001)", model_string_jags, fixed = TRUE)
model_string_jags <- gsub("s_g_c_hat[j, t] ~ dunif(0, 100) }", "s_g_c_hat[t] ~ dunif(0, 100)", model_string_jags, fixed = TRUE)
}
model_string_jags <- prior_selection(type = type, dist_e = dist_e, dist_c = dist_c, pe_fixed = pe_fixed, pc_fixed = pc_fixed, ze_fixed = ze_fixed, zc_fixed = zc_fixed,
model_e_random = model_e_random, model_c_random = model_c_random, model_me_random = model_me_random, model_mc_random = model_mc_random,
pe_random = pe_random, pc_random = pc_random, ze_random = ze_random, zc_random = zc_random)
writeLines(model_string_jags, "selection.txt")
model_string <- "selection.txt"
return(model_string)
})) |
"riskfactors" |
remove_all_na_cols <- function(df){
Filter(function(x)!all(is.na(x)),df)
} |
gpLogLikelihood <-
function(model) {
if (model$approx == "ftc") {
if ("S" %in% names(model)) {
ll = -0.5*(model$d*model$logDetK_uu + sum(model$invK_uu * model$S))
return (ll)
}
ll = 0
for (i in 1:dim(model$m)[2]) {
if ((!"isSpherical" %in% names(model)) || model$isSpherical)
ll = ll -.5*model$logDetK_uu - .5*t(model$m[, i,drop=FALSE])%*%model$invK_uu%*%model$m[, i,drop=FALSE]
else {
if (model$isMissingData)
m = model$m[model$indexPresent[[i]], i]
else
m = model$m[, i]
ll = ll - .5*model$logDetK_uu[i] - .5*t(m)%*%model$invK_uu[[i]]%*%m
}
}
} else if (model$approx %in% c("dtc", "dtcvar")) {
if ((!"isSpherical" %in% names(model)) || model$isSpherical) {
E = model$K_uf%*%model$m
EET = E %*% t(E)
if (length(model$beta)==1) {
ll = -0.5*(model$d*(-(model$N-model$k)*log(model$beta)
- model$logDetK_uu + model$logDetA) - (sum(model$Ainv*EET)
-sum(model$m * model$m))*model$beta)
if (model$approx == "dtcvar")
ll = ll - model$d * 0.5*sum(model$diagD)
} else
stop("Not implemented variable length beta yet.")
} else {
ll = 0
for (i in 1:model$d) {
ind = gpDataIndices(model, i)
e = model$K_uf[, ind,drop=FALSE]%*%model$m[ind, i,drop=FALSE]
if (length(model$beta)==1) {
ll = ll - 0.5*((-(model$N-model$k)*log(model$beta)
- model$logDetK_uu + model$logDetA[i]) - (t(e)%*%model$Ainv[[i]]%*%e
- t(model$m[ind, i,drop=FALSE])%*%model$m[ind, i,drop=FALSE])*model$beta)
if(is.nan(ll))
stop("Log likelihood is NaN")
if (model$approx == "dtcvar")
stop("Not implemented dtcvar for non-spherical yet.")
} else
stop("Not implemented variable length beta yet.")
}
}
} else if (model$approx == "fitc") {
if ((!"isSpherical" %in% names(model)) || model$isSpherical) {
if (length(model$beta)==1) {
if (FALSE) {
Dinvm = model$Dinv %*% model$m
K_ufDinvm = model$K_uf %*% Dinvm
ll = -0.5*(model$d * (sum(log(model$diagD))
-(model$N-model$k)*log(model$beta) + model$detDiff)
+ (sum(Dinvm * model$m)
- sum((model$Ainv%*%K_ufDinvm) * K_ufDinvm))*model$beta)
ll = ll - 0.5*model$N*model$d*log(2*pi)
} else {
ll = - model$d*(sum(log(diag(model$Lm)))
+ 0.5*(-(model$N - model$k)*log(model$beta)
+(model$N*log(2*pi) + sum(log(model$diagD)))))
for (i in 1:model$d)
ll = ll - 0.5*model$beta*(t(model$scaledM[, i,drop=FALSE])%*%model$scaledM[, i,drop=FALSE]
- t(model$bet[, i,drop=FALSE])%*%model$bet[, i,drop=FALSE])
}
} else
stop("Variable length Beta not implemented yet.")
} else {
if (length(model$beta)==1) {
if (FALSE) {
ll = 0
for (i in 1:model$d) {
ind = gpDataIndices(model, i)
Dinvm = model$Dinv[[i]]%*%model$m[ind, i,drop=FALSE]
K_ufDinvm = model$K_uf[, ind,drop=FALSE]%*%Dinvm
ll = ll -0.5*(sum(log(model$diagD[[i]]))
- (length(ind) - model$k)*log(model$beta)
+ model$detDiff[i] + (sum(Dinvm * model$m[ind, i,drop=FALSE])
- sum((model$Ainv[[i]]%*%K_ufDinvm) * K_ufDinvm))*model$beta
+ length(ind)*log(2*pi))
}
} else {
ll = 0
for (i in 1:model$d) {
ind = gpDataIndices(model, i)
ll = ll - (sum(log(diag(model$Lm[[i]])))
+ 0.5*(-(length(ind) - model$k)*log(model$beta)
+(length(ind)*log(2*pi)+sum(log(model$diagD[[i]])))))
ll = ll - 0.5*model$beta*(t(model$scaledM[[i]])%*%model$scaledM[[i]]
- t(model$bet[[i]])%*%model$bet[[i]])
}
}
} else
stop("Variable length Beta not implemented yet.")
}
} else if (model$approx == "pitc") {
if ((!"isSpherical" %in% names(model)) || model$isSpherical) {
if (length(model$beta)==1) {
ll = model$d*(model$logDetA-model$logDetK_uu + model$k*log(model$beta))
K_ufDinvm = matrix(0, model$k, model$d)
Dinvm = list()
for (i in 1:length(model$blockEnd)) {
ind = gpBlockIndices(model, i)
Dinvm[[i]] = model$Dinv[[i]]%*%model$m[ind, ,drop=FALSE]
K_ufDinvm = K_ufDinvm + model$K_uf[, ind,drop=FALSE]%*%Dinvm[[i]]
}
ll = ll - model$beta*sum((model$Ainv%*%K_ufDinvm) * K_ufDinvm)
for (i in 1:length(model$blockEnd)) {
ind = gpBlockIndices(model, i)
ll = ll + model$d*(model$logDetD[i] - length(ind)*log(model$beta))
+ model$beta*sum(Dinvm[[i]] * model$m[ind, ,drop=FALSE])
}
ll = -0.5*ll
ll = ll - 0.5*model$N*model$d*log(2*pi)
} else
stop("Variable Length Beta not implemented yet.")
} else {
if (length(model$beta)==1) {
ll = 0
Dinvm = matrix(0, model$blockEnd, model$d)
Dinvm = lapply(split(Dinvm,row(Dinvm)), split, 1:model$d)
for (j in 1:model$d) {
ll = ll + model$logDetA[j]-model$logDetK_uu + model$k*log(model$beta)
K_ufDinvm = matrix(0, model$k, 1)
for (i in 1:length(model$blockEnd)) {
ind = gpDataIndices(model, j, i)
Dinvm[[i]][[j]] = model$Dinv[[i]][[j]]%*%model$m[ind, j,drop=FALSE]
K_ufDinvm = K_ufDinvm + model$K_uf[, ind]%*%Dinvm[[i]][[j]]
}
ll = ll - model$beta*sum((model$Ainv[[i]]%*%K_ufDinvm) * K_ufDinvm)
for (i in 1:length(model$blockEnd)) {
ind = gpDataIndices(model, j, i)
ll = ll + model$logDetD[i, j] - length(ind)*log(model$beta)
+ model$beta*sum(Dinvm[[i]][[j]] * model$m[ind, j,drop=FALSE])
ll = ll + length(ind)*log(2*pi)
}
}
ll = -0.5*ll
} else
stop("Variable Length Beta not implemented yet.")
}
}
if (model$learnScales)
ll = ll - sum(log(model$scale))
ll = ll - model$d * model$N/2 * log(2*pi)
return (ll)
} |
gsCP <- function(x, theta = NULL, i = 1, zi = 0, r = 18) {
if (!(methods::is(x, "gsProbability") || methods::is(x, "gsDesign"))) {
stop("gsCP must be called with class of x either gsProbability or gsDesign")
}
if (i < 1 || i >= x$k) {
stop("gsCP must be called with i from 1 to x$k-1")
}
test.type <- ifelse(methods::is(x, "gsProbability"), 3, x$test.type)
if (zi > x$upper$bound[i]) {
stop("gsCP must have x$lower$bound[i] <= zi <= x$upper$bound[i]")
}
else if (test.type > 1 && zi < x$lower$bound[i]) {
stop("gsCP must have x$lower$bound[i]<=zi<=x$upper$bound[i]")
}
if (is.null(theta)) theta <- c(zi/sqrt(x$n.I[i]), 0, x$delta)
knew <- x$k - i
Inew <- x$n.I[(i + 1):x$k] - x$n.I[i]
if (is.null(x$timing)) x$timing <- x$n.I/x$n.I[x$k]
bnew <- (x$upper$bound[(i+1):x$k]*sqrt(x$timing[(i+1):x$k]) - zi*sqrt(x$timing[i]))/
sqrt(x$timing[(i+1):x$k]-x$timing[i])
if (test.type > 1) {
anew <- (x$lower$bound[(i+1):x$k]*sqrt(x$timing[(i+1):x$k]) - zi*sqrt(x$timing[i]))/
sqrt(x$timing[(i+1):x$k]-x$timing[i])
}
else {
anew <- rep(-20, knew)
}
gsProbability(k = knew, theta = theta, n.I = Inew, a = anew, b = bnew, r = r, overrun = 0)
}
gsPP <- function(x, i = 1, zi = 0, theta = c(0, 3), wgts = c(.5, .5), r = 18, total = TRUE) {
if (!(methods::is(x, "gsProbability") || methods::is(x, "gsDesign"))) {
stop("gsPP: class(x) must be gsProbability or gsDesign")
}
test.type <- ifelse(methods::is(x, "gsProbability"), 3, x$test.type)
checkScalar(i, "integer", c(1, x$k - 1))
checkScalar(zi, "numeric", c(-Inf, Inf), c(FALSE, FALSE))
checkVector(wgts, "numeric", c(0, Inf), c(TRUE, FALSE))
checkVector(theta, "numeric", c(-Inf, Inf), c(FALSE, FALSE))
checkLengths(theta, wgts)
checkScalar(r, "integer", c(1, 80))
cp <- gsCP(x = x, i = i, theta = theta, zi = zi, r = r)
gsDen <- stats::dnorm(zi, mean = sqrt(x$n.I[i]) * theta) * wgts
pp <- cp$upper$prob %*% gsDen / sum(gsDen)
if (total) {
return(sum(pp))
} else {
return(pp)
}
}
gsPI <- function(x, i = 1, zi = 0, j = 2, level = .95, theta = c(0, 3), wgts = c(.5, .5)) {
if (!(methods::is(x, "gsProbability") || methods::is(x, "gsDesign"))) {
stop("gsPI: class(x) must be gsProbability or gsDesign")
}
checkScalar(i, "integer", c(1, x$k - 1))
checkScalar(j, "integer", c(i + 1, x$k))
checkScalar(zi, "numeric", c(-Inf, Inf), c(FALSE, FALSE))
checkVector(wgts, "numeric", c(0, Inf), c(TRUE, FALSE))
checkVector(theta, "numeric", c(-Inf, Inf), c(FALSE, FALSE))
checkLengths(theta, wgts)
post <- stats::dnorm(zi, mean = sqrt(x$n.I[i]) * theta) * wgts
post <- post / sum(post)
lower <- stats::uniroot(
f = postfn, interval = c(-20, 20), PP = 1 - (1 - level) / 2,
d = x, i = i, zi = zi, j = j, theta = theta, wgts = post
)$root
if (level == 0) return(lower)
upper <- stats::uniroot(
f = postfn, interval = c(-20, 20), PP = (1 - level) / 2,
d = x, i = i, zi = zi, j = j, theta = theta, wgts = post
)$root
c(lower, upper)
}
gsBoundCP <- function(x, theta = "thetahat", r = 18) {
if (!(methods::is(x, "gsProbability") || methods::is(x, "gsDesign"))) {
stop("gsPI: class(x) must be gsProbability or gsDesign")
}
checkScalar(r, "integer", c(1, 70))
if (!is.character(theta)) {
checkVector(theta, "numeric", c(-Inf, Inf), c(FALSE, FALSE))
}
len <- x$k - 1
test.type <- ifelse(methods::is(x, "gsProbability"), 3, x$test.type)
if (theta != "thetahat") {
thetahi <- rep(theta, len)
if (test.type > 1) thetalow <- thetahi
} else {
if (test.type > 1) thetalow <- x$lower$bound[1:len] / sqrt(x$n.I[1:len])
thetahi <- x$upper$bound[1:len] / sqrt(x$n.I[1:len])
}
CPhi <- rep(0, len)
if (test.type > 1) CPlo <- CPhi
for (i in 1:len)
{
if (test.type > 1) {
xlow <- gsCP(x, thetalow[i], i, x$lower$bound[i])
CPlo[i] <- sum(xlow$upper$prob)
}
xhi <- gsCP(x, thetahi[i], i, x$upper$bound[i])
CPhi[i] <- sum(xhi$upper$prob)
}
if (test.type > 1) cbind(CPlo, CPhi) else CPhi
}
gsPosterior <- function(x = gsDesign(), i = 1, zi = NULL, prior = normalGrid(), r = 18) {
if (is.null(prior$gridwgts)) prior$gridwgts <- rep(1, length(prior$z))
checkLengths(prior$z, prior$density, prior$gridwgts)
checkVector(prior$gridwgts, "numeric", c(0, Inf), c(TRUE, FALSE))
checkVector(prior$density, "numeric", c(0, Inf), c(TRUE, FALSE))
checkVector(prior$z, "numeric", c(-Inf, Inf), c(FALSE, FALSE))
if (!(methods::is(x, "gsProbability") || methods::is(x, "gsDesign"))) {
stop("gsPosterior: x must have class gsDesign or gsProbability")
}
test.type <- ifelse(methods::is(x, "gsProbability"), 3, x$test.type)
checkScalar(i, "integer", c(1, x$k - 1))
if (is.null(zi)) {
zi <- c(x$lower$bound[i], x$upper$bound[i])
} else {
checkVector(zi, "numeric", c(-Inf, Inf), c(FALSE, FALSE))
}
if (length(zi) > 2) stop("gsPosterior: length of zi must be 1 or 2")
if (length(zi) > 1) {
if (zi[2] <= zi[1]) {
stop("gsPosterior: when length of zi is 2, must have zi[2] > zi[1]")
}
xa <- x
if (zi[1] != x$lower$bound[i] || zi[2] != x$upper$bound[i]) {
xa$lower$bound[i] <- zi[1]
xa$upper$bound[i] <- zi[2]
}
xa <- gsProbability(d = xa, theta = prior$z, r = r)
prob <- xa$lower$prob + xa$upper$prob
for (j in 1:ncol(prob)) prob[, j] <- 1 - cumsum(prob[, j])
marg <- sum(prob[i, ] * prior$gridwgts * prior$density)
posterior <- prob[i, ] * prior$density
}
else {
y <- gsZ(x, theta = prior$z, i = i, zi = zi)
marg <- sum(as.vector(y$density) * prior$gridwgts * prior$density)
posterior <- as.vector(y$density) * prior$density
}
posterior <- posterior / marg
return(list(
z = prior$z, density = posterior,
gridwgts = prior$gridwgts, wgts = prior$gridwgts * posterior
))
}
gsZ <- function(x, theta, i, zi) {
mu <- sqrt(x$n.I[i]) * theta
xx <- matrix(0, nrow = length(zi), ncol = length(theta))
for (j in 1:length(theta)) xx[, j] <- stats::dnorm(zi - mu[j])
list(zi = zi, theta = theta, density = xx)
}
postfn <- function(x, PP, d, i, zi, j, theta, wgts) {
newmean <- (d$timing[j] - d$timing[i]) * theta * sqrt(d$n.I[d$k])
newsd <- sqrt(d$timing[j] - d$timing[i])
pprob <- stats::pnorm(x * sqrt(d$timing[j]) - zi * sqrt(d$timing[i]),
mean = newmean,
sd = newsd, lower.tail = FALSE
)
sum(pprob * wgts) - PP
}
gsPOS <- function(x, theta, wgts) {
if (!methods::is(x, c("gsProbability", "gsDesign"))) {
stop("x must have class gsProbability or gsDesign")
}
checkVector(theta, "numeric")
checkVector(wgts, "numeric")
checkLengths(theta, wgts)
x <- gsProbability(theta = theta, d = x)
one <- rep(1, x$k)
as.double(one %*% x$upper$prob %*% wgts)
}
gsCPOS <- function(i, x, theta, wgts) {
if (!methods::is(x, c("gsProbability", "gsDesign"))) {
stop("x must have class gsProbability or gsDesign")
}
checkScalar(i, "integer", c(1, x$k), c(TRUE, FALSE))
checkVector(theta, "numeric")
checkVector(wgts, "numeric")
checkLengths(theta, wgts)
x <- gsProbability(theta = theta, d = x)
v <- c(rep(1, i), rep(0, (x$k - i)))
pAi <- 1 - as.double(v %*% (x$upper$prob + x$lower$prob) %*% wgts)
v <- 1 - v
pAiB <- as.double(v %*% x$upper$prob %*% wgts)
pAiB / pAi
} |
IF.SD <- function(returns = NULL, evalShape = FALSE, retVals = NULL, nuisPars = NULL, k = 4,
IFplot = FALSE, IFprint = TRUE,
prewhiten = FALSE, ar.prewhiten.order = 1,
cleanOutliers = FALSE, cleanMethod = c("locScaleRob")[1], eff = 0.99,
...){
DataCheck(returns = returns, evalShape = evalShape, retVals = retVals, nuisPars = nuisPars, k = k,
IFplot = IFplot, IFprint = IFprint,
prewhiten = prewhiten, ar.prewhiten.order = ar.prewhiten.order,
cleanOutliers = cleanOutliers, cleanMethod = cleanMethod, eff = eff)
nuisPars <- NuisanceData(nuisPars)
if(xts::is.xts(returns))
returns.dates <- zoo::index(returns)
if(cleanOutliers){
temp.returns <- robust.cleaning(returns, cleanMethod, eff)
if(xts::is.xts(returns))
returns <- xts::xts(temp.returns, returns.dates) else
returns <- temp.returns
}
if(evalShape){
IFvals <- EvaluateShape(estimator = "SD",
retVals = retVals, returns = returns, k = k, nuisPars = nuisPars,
IFplot = IFplot, IFprint = IFprint)
if(IFprint)
return(IFvals) else{
opt <- options(show.error.messages = FALSE)
on.exit(options(opt))
stop()
}
}
mu.hat <- mean(returns)
sd.hat <- sd(returns)
IF.SD.vector <- IF.SD.fn(x = returns, returns = returns)
if(prewhiten)
IF.SD.vector <- as.numeric(arima(x = IF.SD.vector, order = c(ar.prewhiten.order,0,0), include.mean = TRUE)$residuals)
if(xts::is.xts(returns))
IF.SD.vector <- xts::xts(IF.SD.vector, returns.dates)
if(isTRUE(IFplot)){
print(plot(IF.SD.vector, type = "l", main = "SD Estimator Influence Function Transformed Returns", ylab = "IF"))
}
if(!IFprint){
opt <- options(show.error.messages = FALSE)
on.exit(options(opt))
stop()
}
if(xts::is.xts(returns))
return(xts::xts(IF.SD.vector, returns.dates)) else
return(IF.SD.vector)
} |
bgigvp <- function(x, t = 24) {
if(dim(x)[1] == 0) {
stop("Dimension of data-set must be higher than 0.")
}
names <- c("date", "time", "glucose")
names <- match(names, names(x))
if(any(is.na(names))) {
stop("Names of data-set must be date, time and glucose.")
}
if(any(is.na(as.character(x$date))) || any(is.na(as.character(x$time)))) {
stop("Variables date and time must be non-NA values.")
}
date.time <- as.POSIXct(paste(as.character(x$date), as.character(x$time)), format = "%Y/%m/%d %H:%M:%S")
if(any(is.na(date.time))) {
stop("Variable date and time must have yyyy/mm/dd and hh:mm:ss format.")
}
if(all(is.na(x$glucose))) {
stop("Variable glucose must be non-NA value.")
}
if(!is.numeric(x$glucose)) {
stop("Variable glucose must be numeric.")
}
if(!is.numeric(t)) {
stop("t must be numeric.")
}
if(all(t != c(4, 6, 8, 12, 24))) {
stop("t must be 4, 6, 8, 12 or 24.")
}
xt <- data.frame(matrix(nrow = 24, ncol = 6))
names(xt) <- c("hour", "4h", "6h", "8h", "12h", "24h")
xt$hour <- 0:23
xt$"4h" <- c(rep(1, 4), rep(2, 4), rep(3, 4), rep(4, 4), rep(5, 4), rep(6, 4))
xt$"6h" <- c(rep(1, 6), rep(2, 6), rep(3, 6), rep(4, 6))
xt$"8h" <- c(rep(1, 8), rep(2, 8), rep(3, 8))
xt$"12h" <- c(rep(1, 12), rep(2, 12))
xt$"24h" <- 1
t <- paste(t, "h", sep = "")
x$serie <- NA
date <- levels(as.factor(as.character(x$date)))
for(i in 1:length(date)) {
position <- which(x$date == date[i])
x$serie[position] <- as.numeric(i)
}
hour <- separate(x, time, into = c("hour", "minutes", "seconds"), ":")
hour <- as.numeric(hour$hour)
for(i in 1:length(hour)) {
for(j in 0:23) {
if(hour[i] == j) {
x$serie[i] <- paste(x$serie[i], ".", xt[j + 1, t], sep = "")
}
}
}
serie <- levels(as.factor(as.numeric(as.character(x$serie))))
x$lbgi <- x$hbgi <- x$bgi <- 0
for(i in 1:length(serie)) {
position <- which(x$serie == serie[i])
aux <- x[position, ]
if(!all(is.na(aux$glucose))) {
f <- 1.509 * ((log(as.numeric(as.character(aux$glucose))) ^ 1.084) - 5.381)
r <- 10 * (f ^ 2)
rh <- c()
rl <- c()
for(j in 1:length(f)) {
if(is.na(f[j])) {
rh <- c(rh, 0)
rl <- c(rl, 0)
} else {
if(f[j] > 0) {
rh <- c(rh, r[j])
rl <- c(rl, 0)
} else if(f[j] < 0) {
rl <- c(rl, r[j])
rh <- c(rh, 0)
} else {
rh <- c(rh, 0)
rl <- c(rl, 0)
}
}
}
if(length(rl) == 0) rl <- 0
if(length(rh) == 0) rh <- 0
x$lbgi[position] <- round(mean(rl, na.rm = TRUE), digits = 2)
x$hbgi[position] <- round(mean(rh, na.rm = TRUE), digits = 2)
x$bgi[position] <- round(mean(c(x$lbgi[position], x$hbgi[position]), na.rm = TRUE), digits = 2)
}
}
if(any(is.na(x$lbgi))) {
position <- is.na(x$lbgi)
x$lbgi[position] <- 0
}
if(any(is.na(x$hbgi))) {
position <- is.na(x$hbgi)
x$hbgi[position] <- 0
}
if(any(is.na(x$bgi))) {
position <- is.na(x$bgi)
x$bgi[position] <- 0
}
x <- x[,-which(names(x) == "serie")]
return(x)
} |
lm1 <- lm(wt ~ disp + drat + hp, mtcars)
BF1 <- BF(lm1)
PHPexplo <- matrix(
c(0.065, 0.003, 0.931,
0.001, 0.000, 0.999,
0.612, 0.342, 0.046,
0.742, 0.178, 0.080),nrow=4,byrow=T)
test_that("BF.lm exploratory hypotheses correctly evaluated", {
expect_equivalent(
PHPexplo,round(BF1$PHP_exploratory,3)
)})
BF2 <- BF(lm1,hypothesis="disp=drat=0;disp>drat>0;disp>drat=0")
test_that("BF.lm multiple confirmatory hypotheses correctly evaluated", {
expect_equivalent(
round(BF2$PHP_confirmatory,5),c(0.00000,0.53382,0.40265,0.06353)
)})
BF2 <- BF(lm1,hypothesis="disp=drat=0;disp>drat>0;disp>drat=0",complement=FALSE)
test_that("BF.lm multiple confirmatory hypotheses correctly evaluated", {
expect_equivalent(
round(BF2$PHP_confirmatory,5),c(0.00000,0.57003,0.42997)
)})
BF3 <- BF(lm1,hypothesis="disp=hp=0")
test_that("BF.lm one equality hypothesis correctly evaluated", {
expect_equivalent(
round(BF3$PHP_confirmatory,5),c(0.00003,0.99997)
)})
BF4 <- BF(lm1,hypothesis="drat<hp<disp")
test_that("BF.lm one order hypothesis correctly evaluated", {
expect_equivalent(
round(BF4$PHP_confirmatory,5),c(0.96872,0.03128)
)})
BF5 <- BF(lm1,hypothesis="drat<hp=disp")
test_that("BF.lm one equal/order hypothesis correctly evaluated", {
expect_equivalent(
round(BF5$PHP_confirmatory,5),c(0.47961,0.52039)
)}) |
simcode<-function (dataset, myformula, iv, ctime, nsamp = 10000, add = NULL,
nobs = NA, half = FALSE, verbose = FALSE) {
bad <- NULL
gg <- as.formula(paste("Surv(newt,nc)~", deparse(myformula[[3]])))
sr1 <- survreg(formula = myformula, data = dataset, x = TRUE, y = TRUE)
if (is.na(nobs)) nobs <- dim(sr1$x)[1]
use <- seq(nobs)
csr1 <- coefficients(sr1)
ivl <- (names(csr1) == iv)[-1]
if (half) csr1 <- csr1/2
csr1[iv] <- 0
randdat <- cbind(as.data.frame(list(newt = rep(NA, nobs))), sr1$x[use, ])
start<-0
if (is.null(add)) {
set.seed(202043125)
} else {
outout <- rbind(add$out, array(NA, c(nsamp, dim(add$out)[2])))
start <- dim(add$out)[1]
set.seed(add$seed)
}
d1 <- Sys.time()
for (kk in seq(nsamp)) {
if (verbose) {
d2 <- Sys.time()
if (verbose)
message("kk=", kk, " of ", nsamp,
". Completion time ", (d2 - d1) * (nsamp -
kk)/kk + d2)
}
if (nobs < dim(sr1$x)[1])
use <- sample(dim(sr1$x)[1], nobs)
for (j in seq(nobs)) {
elpred <- exp(sr1$x[use, ] %*% csr1)
randdat$newt[j] <- rweibull(1, shape = 1/sr1$scale,
scale = elpred[j])
}
randdat$nc <- randdat$newt < ctime
randdat$newt[randdat$newt >= ctime] <- ctime
randdat$y <- Surv(randdat$newt, randdat$nc)
xxx <- sr1$x[use, -1]
randdat$x <- xxx
repairedfit <- fixcoxph(randdat, xxx, iv, verbose = verbose)
penalizedout <- coxphf(gg, randdat, maxit = 200, maxstep = 0.1)
hh<-update(as.formula(gg),paste("~. -",iv))
penalizedoutsmaller <- coxphf(hh, randdat, maxit = 200, maxstep = 0.1)
myout<-summarizefits(repairedfit,penalizedout,penalizedoutsmaller,iv)
if((start+kk)==1){
outout <- array(NA, c(nsamp, length(myout)))
dimnames(outout)<-list(NULL,names(myout))
}
outout[start + kk,]<-myout
}
return(list(out = outout, seed = .Random.seed, bad = bad, srreg = sr1))
} |
emSNMoE <- function(X, Y, K, p = 3, q = 1, n_tries = 1, max_iter = 1500, threshold = 1e-6, verbose = FALSE, verbose_IRLS = FALSE) {
top <- 0
try_EM <- 0
best_loglik <- -Inf
while (try_EM < n_tries) {
try_EM <- try_EM + 1
if (n_tries > 1 && verbose) {
message("EM try number: ", try_EM, "\n")
}
param <- ParamSNMoE(X = X, Y = Y, K = K, p = p, q = q)
param$initParam(segmental = TRUE)
iter <- 0
converge <- FALSE
prev_loglik <- -Inf
stat <- StatSNMoE(paramSNMoE = param)
while (!converge && (iter <= max_iter)) {
stat$EStep(param)
reg_irls <- param$MStep(stat, verbose_IRLS)
stat$computeLikelihood(reg_irls)
iter <- iter + 1
if (verbose) {
message("EM - SNMoE: Iteration: ", iter, " | log-likelihood: " , stat$loglik)
}
if (prev_loglik - stat$loglik > 1e-5) {
if (verbose) {
warning("EM log-likelihood is decreasing from ", prev_loglik, "to ", stat$loglik, "!")
}
top <- top + 1
if (top > 20)
break
}
converge <- abs((stat$loglik - prev_loglik) / prev_loglik) <= threshold
if (is.na(converge)) {
converge <- FALSE
}
prev_loglik <- stat$loglik
stat$stored_loglik <- c(stat$stored_loglik, stat$loglik)
}
if (stat$loglik > best_loglik) {
statSolution <- stat$copy()
paramSolution <- param$copy()
best_loglik <- stat$loglik
}
if (n_tries > 1 && verbose) {
message("Max value of the log-likelihood: ", stat$loglik, "\n\n")
}
}
statSolution$MAP()
if (n_tries > 1 && verbose) {
message("Max value of the log-likelihood: ", statSolution$loglik, "\n")
}
statSolution$computeStats(paramSolution)
return(ModelSNMoE(param = paramSolution, stat = statSolution))
} |
MICA.ContCont <- function(Trial.R, D.aa, D.bb, T0S0, T1S1, T0T0=1, T1T1=1, S0S0=1, S1S1=1, T0T1=seq(-1, 1, by=.1), T0S1=seq(-1, 1, by=.1), T1S0=seq(-1, 1, by=.1), S0S1=seq(-1, 1, by=.1)) {
Results <- na.exclude(matrix(NA, 1, 8))
colnames(Results) <- c("T0T1", "T0S0", "T0S1", "T1S0", "T1S1", "S0S1", "ICA", "MICA")
T0S0_hier <- T0S0[1]
T1S1_hier <- T1S1[1]
combins <- expand.grid(T0T1, T0S0_hier, T0S1, T1S0, T1S1_hier, S0S1)
lengte <- dim(combins)[1]
if (length(T0S0)>1){
if (length(T0S0)<lengte){stop("The specified vector for T0S0 should be larger than ", lengte) }
T0S0_vector <- T0S0[1:lengte]
combins[,2] <- T0S0_vector
}
if (length(T1S1)>1){
if (length(T1S1)<lengte){stop("The specified vector for T1S1 should be larger than ", lengte) }
T1S1_vector <- T1S1[1:lengte]
combins[,5] <- T1S1_vector
}
for (i in 1: nrow(combins)) {
T0T1 <- combins[i, 1]
T0S0 <- combins[i, 2]
T0S1 <- combins[i, 3]
T1S0 <- combins[i, 4]
T1S1 <- combins[i, 5]
S0S1 <- combins[i, 6]
Sigma_c <- diag(4)
Sigma_c[2,1] <- Sigma_c[1,2] <- T0T1 * (sqrt(T0T0)*sqrt(T1T1))
Sigma_c[3,1] <- Sigma_c[1,3] <- T0S0 * (sqrt(T0T0)*sqrt(S0S0))
Sigma_c[4,1] <- Sigma_c[1,4] <- T0S1 * (sqrt(T0T0)*sqrt(S1S1))
Sigma_c[3,2] <- Sigma_c[2,3] <- T1S0 * (sqrt(T1T1)*sqrt(S0S0))
Sigma_c[4,2] <- Sigma_c[2,4] <- T1S1 * (sqrt(T1T1)*sqrt(S1S1))
Sigma_c[4,3] <- Sigma_c[3,4] <- S0S1 * (sqrt(S0S0)*sqrt(S1S1))
Sigma_c[1,1] <- T0T0
Sigma_c[2,2] <- T1T1
Sigma_c[3,3] <- S0S0
Sigma_c[4,4] <- S1S1
Cor_c <- cov2cor(Sigma_c)
Min.Eigen.Cor <- try(min(eigen(Cor_c)$values), TRUE)
if (Min.Eigen.Cor > 0) {
ICA <- ((sqrt(S0S0*T0T0)*Cor_c[3,1])+(sqrt(S1S1*T1T1)*Cor_c[4,2])-(sqrt(S0S0*T1T1)*Cor_c[3,2])-(sqrt(S1S1*T0T0)*Cor_c[4,1]))/(sqrt((T0T0+T1T1-(2*sqrt(T0T0*T1T1)*Cor_c[2,1]))*(S0S0+S1S1-(2*sqrt(S0S0*S1S1)*Cor_c[4,3]))))
Var_eps_t <- T0T0 + T1T1 - (2*sqrt(T0T0*T1T1)*Cor_c[2,1])
Var_eps_s <- S0S0 + S1S1 - (2*sqrt(S0S0*S1S1)*Cor_c[4,3])
Var_delt_t <- D.bb + T0T0 + T1T1 - (2*sqrt(T0T0*T1T1)*Cor_c[2,1])
Var_delt_s <- D.aa + S0S0 + S1S1 - (2*sqrt(S0S0*S1S1)*Cor_c[4,3])
MICA <- ((sqrt(D.bb*D.aa)*Trial.R) + (sqrt(Var_eps_t*Var_eps_s)*ICA)) / sqrt(Var_delt_t*Var_delt_s)
if ((is.finite(ICA))==TRUE){
results.part <- as.vector(cbind(T0T1, T0S0, T0S1, T1S0, T1S1, S0S1, ICA, MICA))
Results <- rbind(Results, results.part)
rownames(Results) <- NULL}
}
}
Results <- data.frame(Results, stringsAsFactors = TRUE)
rownames(Results) <- NULL
Total.Num.Matrices <- nrow(combins)
fit <-
list(Total.Num.Matrices=Total.Num.Matrices, Pos.Def=Results[,1:6], ICA=Results$ICA, MICA=Results$MICA, Call=match.call())
class(fit) <- "MICA.ContCont"
fit
}
plot.MICA.ContCont <- function(x, ICA=TRUE, MICA=TRUE, Type="Percent", Labels=FALSE, Xlab.ICA, Main.ICA, Xlab.MICA, Main.MICA,
Par=par(oma=c(0, 0, 0, 0), mar=c(5.1, 4.1, 4.1, 2.1)), col, ...){
Object <- x
if (MICA==TRUE){
dev.new()
par=Par
if (missing(Xlab.MICA)) {Xlab.MICA <- expression(rho[M])}
if (missing(col)) {col <- c(8)}
if (missing(Main.MICA)) {Main.MICA="MICA"}
if (Type=="Freq"){
h <- hist(Object$MICA, ...)
h$density <- h$counts/sum(h$counts)
cumulMidPoint <- ecdf(x=Object$MICA)(h$mids)
labs <- paste(round((1-cumulMidPoint), digits=4)*100, "%", sep="")
if (Labels==FALSE){
plot(h,freq=T, xlab=Xlab.MICA, ylab="Frequency", col=col, main=Main.MICA)
}
if (Labels==TRUE){
plot(h,freq=T, xlab=Xlab.MICA, ylab="Frequency", col=col, main=Main.MICA, labels=labs)
}
}
if (Type=="Percent"){
h <- hist(Object$MICA, ...)
h$density <- h$counts/sum(h$counts)
cumulMidPoint <- ecdf(x=Object$MICA)(h$mids)
labs <- paste(round((1-cumulMidPoint), digits=4)*100, "%", sep="")
if (Labels==FALSE){
plot(h,freq=F, xlab=Xlab.MICA, ylab="Percentage", col=col, main=Main.MICA)
}
if (Labels==TRUE){
plot(h,freq=F, xlab=Xlab.MICA, ylab="Percentage", col=col, main=Main.MICA, labels=labs)
}
}
if (Type=="CumPerc"){
h <- hist(Object$MICA, breaks=length(Object$MICA), ...)
h$density <- h$counts/sum(h$counts)
cumulative <- cumsum(h$density)
plot(x=h$mids, y=cumulative, xlab=Xlab.MICA, ylab="Cumulative percentage", col=0, main=Main.MICA)
lines(x=h$mids, y=cumulative)
}
}
if (ICA==TRUE){
dev.new()
par=Par
if (missing(Xlab.ICA)) {Xlab.ICA <- expression(rho[Delta])}
if (missing(col)) {col <- c(8)}
if (missing(Main.ICA)) {Main.ICA="ICA"}
if (Type=="Freq"){
h <- hist(Object$ICA, ...)
h$density <- h$counts/sum(h$counts)
cumulMidPoint <- ecdf(x=Object$ICA)(h$mids)
labs <- paste(round((1-cumulMidPoint), digits=4)*100, "%", sep="")
if (Labels==FALSE){
plot(h,freq=T, xlab=Xlab.ICA, ylab="Frequency", col=col, main=Main.ICA)
}
if (Labels==TRUE){
plot(h,freq=T, xlab=Xlab.ICA, ylab="Frequency", col=col, main=Main.ICA, labels=labs)
}
}
if (Type=="Percent"){
h <- hist(Object$ICA, ...)
h$density <- h$counts/sum(h$counts)
cumulMidPoint <- ecdf(x=Object$ICA)(h$mids)
labs <- paste(round((1-cumulMidPoint), digits=4)*100, "%", sep="")
if (Labels==FALSE){
plot(h,freq=F, xlab=Xlab.ICA, ylab="Percentage", col=col, main=Main.ICA)
}
if (Labels==TRUE){
plot(h,freq=F, xlab=Xlab.ICA, ylab="Percentage", col=col, main=Main.ICA, labels=labs)
}
}
if (Type=="CumPerc"){
h <- hist(Object$ICA, breaks=length(Object$ICA), ...)
h$density <- h$counts/sum(h$counts)
cumulative <- cumsum(h$density)
plot(x=h$mids, y=cumulative, xlab=Xlab.ICA, ylab="Cumulative percentage", col=0, main=Main.ICA)
lines(x=h$mids, y=cumulative)
}
}
}
summary.MICA.ContCont <- function(object, ..., Object){
if (missing(Object)){Object <- object}
mode <- function(data) {
x <- data
z <- density(x)
mode_val <- z$x[which.max(z$y)]
fit <- list(mode_val= mode_val)
}
cat("\nFunction call:\n\n")
print(Object$Call)
cat("\n\n
cat("\n
cat("\n
cat(Object$Total.Num.Matrices)
cat("\n\n
cat("\n
cat(nrow(Object$Pos.Def))
cat("\n\n\n
cat("\n
cat("Mean (SD) MICA: ", format(round(mean(Object$MICA), 4), nsmall = 4), " (", format(round(sd(Object$MICA), 4), nsmall = 4), ")",
" [min: ", format(round(min(Object$MICA), 4), nsmall = 4), "; max: ", format(round(max(Object$MICA), 4), nsmall = 4), "]", sep="")
cat("\nMode MICA: ", format(round(mode(Object$MICA)$mode_val, 4), nsmall = 4))
cat("\n\nQuantiles of the MICA distribution: \n\n")
quant <- quantile(Object$MICA, probs = c(.05, .10, .20, .50, .80, .90, .95))
print(quant)
} |
x.cod <-
structure(list(N = structure(list(Sex = c("Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex"), Year = c(1971L, 1971L, 1971L, 1971L, 1971L,
1971L, 1971L, 1971L, 1971L, 1971L, 1972L, 1972L, 1972L, 1972L,
1972L, 1972L, 1972L, 1972L, 1972L, 1972L, 1973L, 1973L, 1973L,
1973L, 1973L, 1973L, 1973L, 1973L, 1973L, 1973L, 1974L, 1974L,
1974L, 1974L, 1974L, 1974L, 1974L, 1974L, 1974L, 1974L, 1975L,
1975L, 1975L, 1975L, 1975L, 1975L, 1975L, 1975L, 1975L, 1975L,
1976L, 1976L, 1976L, 1976L, 1976L, 1976L, 1976L, 1976L, 1976L,
1976L, 1977L, 1977L, 1977L, 1977L, 1977L, 1977L, 1977L, 1977L,
1977L, 1977L, 1978L, 1978L, 1978L, 1978L, 1978L, 1978L, 1978L,
1978L, 1978L, 1978L, 1979L, 1979L, 1979L, 1979L, 1979L, 1979L,
1979L, 1979L, 1979L, 1979L, 1980L, 1980L, 1980L, 1980L, 1980L,
1980L, 1980L, 1980L, 1980L, 1980L, 1981L, 1981L, 1981L, 1981L,
1981L, 1981L, 1981L, 1981L, 1981L, 1981L, 1982L, 1982L, 1982L,
1982L, 1982L, 1982L, 1982L, 1982L, 1982L, 1982L, 1983L, 1983L,
1983L, 1983L, 1983L, 1983L, 1983L, 1983L, 1983L, 1983L, 1984L,
1984L, 1984L, 1984L, 1984L, 1984L, 1984L, 1984L, 1984L, 1984L,
1985L, 1985L, 1985L, 1985L, 1985L, 1985L, 1985L, 1985L, 1985L,
1985L, 1986L, 1986L, 1986L, 1986L, 1986L, 1986L, 1986L, 1986L,
1986L, 1986L, 1987L, 1987L, 1987L, 1987L, 1987L, 1987L, 1987L,
1987L, 1987L, 1987L, 1988L, 1988L, 1988L, 1988L, 1988L, 1988L,
1988L, 1988L, 1988L, 1988L, 1989L, 1989L, 1989L, 1989L, 1989L,
1989L, 1989L, 1989L, 1989L, 1989L, 1990L, 1990L, 1990L, 1990L,
1990L, 1990L, 1990L, 1990L, 1990L, 1990L, 1991L, 1991L, 1991L,
1991L, 1991L, 1991L, 1991L, 1991L, 1991L, 1991L, 1992L, 1992L,
1992L, 1992L, 1992L, 1992L, 1992L, 1992L, 1992L, 1992L, 1993L,
1993L, 1993L, 1993L, 1993L, 1993L, 1993L, 1993L, 1993L, 1993L,
1994L, 1994L, 1994L, 1994L, 1994L, 1994L, 1994L, 1994L, 1994L,
1994L, 1995L, 1995L, 1995L, 1995L, 1995L, 1995L, 1995L, 1995L,
1995L, 1995L, 1996L, 1996L, 1996L, 1996L, 1996L, 1996L, 1996L,
1996L, 1996L, 1996L, 1997L, 1997L, 1997L, 1997L, 1997L, 1997L,
1997L, 1997L, 1997L, 1997L, 1998L, 1998L, 1998L, 1998L, 1998L,
1998L, 1998L, 1998L, 1998L, 1998L, 1999L, 1999L, 1999L, 1999L,
1999L, 1999L, 1999L, 1999L, 1999L, 1999L, 2000L, 2000L, 2000L,
2000L, 2000L, 2000L, 2000L, 2000L, 2000L, 2000L, 2001L, 2001L,
2001L, 2001L, 2001L, 2001L, 2001L, 2001L, 2001L, 2001L, 2002L,
2002L, 2002L, 2002L, 2002L, 2002L, 2002L, 2002L, 2002L, 2002L,
2003L, 2003L, 2003L, 2003L, 2003L, 2003L, 2003L, 2003L, 2003L,
2003L, 2004L, 2004L, 2004L, 2004L, 2004L, 2004L, 2004L, 2004L,
2004L, 2004L), Age = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L,
1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L,
6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L,
1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L,
6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L,
1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L,
6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L,
1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L,
6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L,
1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L,
6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L,
1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L,
6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L,
1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L,
6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L,
1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L,
6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L,
1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L,
6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L,
1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L,
6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L,
1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L,
6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L),
N = c(472457, 172835, 162647, 135592, 112548, 51297.2, 41974.6,
27548.5, 12444.9, 17569.8, 262806, 386744, 140900, 127383,
89481, 57003.5, 25276.4, 20682.7, 13574.4, 14789.6, 425777,
215126, 315234, 110164, 83310, 44279.4, 27395.7, 12147.8,
9940.07, 13631.7, 628953, 348515, 175177, 243911, 68056.4,
35289.4, 17986.6, 11128.3, 4934.5, 9575.04, 207659, 514819,
283750, 135313, 149252, 28043.6, 13910.1, 7089.79, 4386.47,
5719.29, 360187, 169979, 419340, 220242, 85064.5, 66414.1,
12017.7, 5960.96, 3038.23, 4330.7, 401021, 294838, 138537,
327544, 143288, 41522.2, 31452.5, 5691.34, 2823, 3489.8,
229905, 328279, 240556, 109431, 225994, 81035.3, 23020, 17437.3,
3155.29, 3499.83, 234366, 188208, 268022, 191374, 78262.4,
139010, 49119.3, 13953.5, 10569.6, 4033.99, 186469, 191858,
153635, 212839, 135635, 47150.4, 82426.3, 29125.4, 8273.75,
8659.21, 328677, 152646, 156559, 121550, 148043, 78200.3,
26682.1, 46644.4, 16481.8, 9582.26, 213028, 269049, 124446,
122667, 80396.6, 75417.8, 38773.5, 13229.6, 23127.4, 12923.2,
185820, 174379, 219301, 97299, 80223.1, 39780.6, 36242.2,
18632.7, 6357.52, 17324.3, 530062, 152109, 142176, 171976,
64652.2, 41347.5, 19972.3, 18195.8, 9354.78, 11889.8, 510445,
433905, 124050, 111789, 115866, 34500.1, 21545.5, 10407.2,
9481.53, 11070.2, 277039, 417840, 353751, 97211.5, 74005.2,
59157.3, 17146.8, 10708.3, 5172.47, 10214.4, 117558, 226770,
340337, 274491, 61009.1, 32776.5, 25222.2, 7310.69, 4565.57,
6560.36, 192850, 96225.4, 184656, 263295, 169428, 25779.4,
13278.4, 10218, 2961.71, 4507.36, 146381, 157860, 78414.3,
144007, 169858, 80880.4, 11919.2, 6139.31, 4724.34, 3453.36,
260156, 119826, 128727, 61586.9, 96463.6, 89343.5, 41500.5,
6115.85, 3150.14, 4196.07, 232307, 212955, 97654.7, 100481,
39924.8, 46644.9, 41884.4, 19455.5, 2867.13, 3443.94, 103293,
190152, 173406, 75546.5, 62012.4, 16863.4, 18888.4, 16960.7,
7878.34, 2555.62, 242279, 84547.9, 154780, 133613, 45581.6,
24510, 6350.95, 7113.6, 6387.62, 3929.58, 301904, 198312,
68823.3, 119317, 80830.9, 18159.7, 9311.52, 2412.77, 2702.51,
3919.59, 112824, 247134, 161698, 54003.2, 79529.8, 41990.2,
9194.56, 4714.58, 1221.63, 3352.89, 226670, 92358.2, 201626,
127672, 37178.2, 44739.6, 23148.4, 5068.78, 2599.06, 2521.85,
66566.4, 185554, 75361.1, 159420, 88524.1, 21274.9, 25116.6,
12995.4, 2845.6, 2874.86, 265870, 54492.4, 151433, 59697.5,
111593, 51809.5, 12232.8, 14441.7, 7472.2, 3289.2, 255701,
217641, 44450.3, 119350, 40716.8, 61373.9, 27881.6, 6583.15,
7771.91, 5791.32, 263285, 209311, 177419, 34796.1, 78562.4,
20488.1, 30030.4, 13642.5, 3221.15, 6636.54, 343564, 215516,
170582, 138482, 22551.7, 37964.7, 9598.29, 14068.7, 6391.29,
4618.17, 87727.6, 281228, 175601, 132845, 88662.9, 10549.2,
17172.8, 4341.67, 6363.81, 4980.01, 310215, 71812.9, 229330,
137941, 89063.6, 46737, 5425.48, 8832.03, 2232.93, 5834.17,
378867, 253943, 58587.1, 181008, 94794.7, 49886.8, 25646.8,
2977.22, 4846.56, 4426.82)), class = "data.frame", row.names = c(NA,
-340L)), B = structure(list(Year = 1971:2004, VB = c(1140000,
964964, 761019, 722716, 778435, 825133, 1050000, 1270000, 1330000,
1410000, 1190000, 940285, 775779, 780698, 827749, 769197, 776460,
868580, 953567, 784715, 610520, 495860, 470127, 468598, 518647,
577960, 682386, 708012, 646309, 550857, 525343, 561627, 636831,
734505), SB = c(1370000, 1170000, 894552, 999547, 966587, 1060000,
1480000, 1500000, 1630000, 1750000, 1410000, 1130000, 918667,
1e+06, 1020000, 900452, 1090000, 1190000, 1200000, 912646, 762816,
598591, 630708, 642020, 613469, 737990, 906160, 828555, 817466,
623002, 700825, 737061, 808611, 982954), Y = c(453052, 398528,
383446, 374770, 370991, 347849, 340050, 330390, 368064, 434344,
468659, 388387, 300056, 283822, 325267, 368633, 392257, 378076,
355954, 335390, 308560, 267767, 251979, 178809, 169424, 181658,
203153, 242632, 260052, 235654, 235098, 208830, 210000, NA),
R = c(262806, 425777, 628953, 207659, 360187, 401021, 229905,
234366, 186469, 328677, 213028, 185820, 530062, 510445, 277039,
117558, 192850, 146381, 260156, 232307, 103293, 242279, 301904,
112824, 226670, 66566.4, 265870, 255701, 263285, 343564,
87727.6, 310215, 378867, NA)), row.names = c(NA, -34L), class = "data.frame"),
Sel = structure(list(Series = c("Gear 1", "Gear 1", "Gear 1",
"Gear 1", "Gear 1", "Gear 1", "Gear 1", "Gear 1", "Gear 1",
"Gear 1", "Survey 1", "Survey 1", "Survey 1", "Survey 1",
"Survey 1", "Survey 1", "Survey 1", "Survey 1", "Survey 1",
"Survey 1", "Maturity", "Maturity", "Maturity", "Maturity",
"Maturity", "Maturity", "Maturity", "Maturity", "Maturity",
"Maturity"), Sex = c("Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex"), Age = c(1L, 2L, 3L, 4L, 5L, 6L, 7L,
8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L,
2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L), P = c(0.000465918,
0.0107437, 0.109044, 0.487138, 0.957858, 1, 0.999999, 0.999998,
0.999996, 0.999993, 0.093353, 0.30199, 0.656636, 0.959678,
1, 0.999999, 0.999998, 0.999996, 0.999994, 0.999991, 0, 0,
0, 1, 1, 1, 1, 1, 1, 1)), class = "data.frame", row.names = c(NA,
-30L)), Dev = list(sigmaR = c(Initial = 0.5, Annual = 1),
Initial = c(`2` = -0.276004, `3` = -0.133551, `4` = -0.08248,
`5` = 0.0879693, `6` = -0.161992, `7` = 0.19093, `8` = 0.323306,
`9` = 0.082165), Annual = c(`1971` = 0.904468, `1972` = 0.0370796,
`1973` = 0.544025, `1974` = 0.98496, `1975` = -0.145333,
`1976` = 0.411873, `1977` = 0.501718, `1978` = -0.107777,
`1979` = -0.0903785, `1980` = -0.329944, `1981` = 0.228531,
`1982` = -0.176938, `1983` = -0.278815, `1984` = 0.808412,
`1985` = 0.753572, `1986` = 0.138847, `1987` = -0.693534,
`1988` = -0.235523, `1989` = -0.526445, `1990` = 0.0482014,
`1991` = -0.0151754, `1992` = -0.786165, `1993` = 0.129073,
`1994` = 0.334609, `1995` = -0.654477, `1996` = 0.0556041,
`1997` = -1.21763, `1998` = 0.121238, `1999` = 0.101377,
`2000` = 0.133603, `2001` = 0.467231, `2002` = -0.928844,
`2003` = 0.321739)), Survey = structure(list(Series = c(1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L), Year = 1971:2004, Obs = c(NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, 548.4, 402.2, 493.1,
561.3, 522, 307, 291.9, 203.8, 220.3, 177.8, 224.2, 325.9,
347, 422.6, 282.2, 251.9, 236.1, 310, 344.5, NA), CV = c(NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 0.2,
0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2,
0.2, 0.2, 0.2, 0.2, 0.2, 0.2, NA), Fit = c(509.758, 436.334,
375.37, 376.073, 395.967, 482.794, 535.93, 578.928, 636.372,
638.789, 519.153, 410.725, 364.678, 378.4, 384.105, 419.75,
464.846, 459.498, 424.87, 346.746, 285.949, 252.182, 259.693,
237.64, 256.392, 313.859, 329.732, 322.584, 288.12, 263.397,
292.159, 298.522, 342.267, 348.371)), row.names = c(NA, -34L
), class = "data.frame"), CAc = structure(list(Series = c(1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L), Year = c(1971L, 1971L, 1971L, 1971L, 1971L,
1971L, 1971L, 1971L, 1971L, 1971L, 1972L, 1972L, 1972L, 1972L,
1972L, 1972L, 1972L, 1972L, 1972L, 1972L, 1973L, 1973L, 1973L,
1973L, 1973L, 1973L, 1973L, 1973L, 1973L, 1973L, 1974L, 1974L,
1974L, 1974L, 1974L, 1974L, 1974L, 1974L, 1974L, 1974L, 1975L,
1975L, 1975L, 1975L, 1975L, 1975L, 1975L, 1975L, 1975L, 1975L,
1976L, 1976L, 1976L, 1976L, 1976L, 1976L, 1976L, 1976L, 1976L,
1976L, 1977L, 1977L, 1977L, 1977L, 1977L, 1977L, 1977L, 1977L,
1977L, 1977L, 1978L, 1978L, 1978L, 1978L, 1978L, 1978L, 1978L,
1978L, 1978L, 1978L, 1979L, 1979L, 1979L, 1979L, 1979L, 1979L,
1979L, 1979L, 1979L, 1979L, 1980L, 1980L, 1980L, 1980L, 1980L,
1980L, 1980L, 1980L, 1980L, 1980L, 1981L, 1981L, 1981L, 1981L,
1981L, 1981L, 1981L, 1981L, 1981L, 1981L, 1982L, 1982L, 1982L,
1982L, 1982L, 1982L, 1982L, 1982L, 1982L, 1982L, 1983L, 1983L,
1983L, 1983L, 1983L, 1983L, 1983L, 1983L, 1983L, 1983L, 1984L,
1984L, 1984L, 1984L, 1984L, 1984L, 1984L, 1984L, 1984L, 1984L,
1985L, 1985L, 1985L, 1985L, 1985L, 1985L, 1985L, 1985L, 1985L,
1985L, 1986L, 1986L, 1986L, 1986L, 1986L, 1986L, 1986L, 1986L,
1986L, 1986L, 1987L, 1987L, 1987L, 1987L, 1987L, 1987L, 1987L,
1987L, 1987L, 1987L, 1988L, 1988L, 1988L, 1988L, 1988L, 1988L,
1988L, 1988L, 1988L, 1988L, 1989L, 1989L, 1989L, 1989L, 1989L,
1989L, 1989L, 1989L, 1989L, 1989L, 1990L, 1990L, 1990L, 1990L,
1990L, 1990L, 1990L, 1990L, 1990L, 1990L, 1991L, 1991L, 1991L,
1991L, 1991L, 1991L, 1991L, 1991L, 1991L, 1991L, 1992L, 1992L,
1992L, 1992L, 1992L, 1992L, 1992L, 1992L, 1992L, 1992L, 1993L,
1993L, 1993L, 1993L, 1993L, 1993L, 1993L, 1993L, 1993L, 1993L,
1994L, 1994L, 1994L, 1994L, 1994L, 1994L, 1994L, 1994L, 1994L,
1994L, 1995L, 1995L, 1995L, 1995L, 1995L, 1995L, 1995L, 1995L,
1995L, 1995L, 1996L, 1996L, 1996L, 1996L, 1996L, 1996L, 1996L,
1996L, 1996L, 1996L, 1997L, 1997L, 1997L, 1997L, 1997L, 1997L,
1997L, 1997L, 1997L, 1997L, 1998L, 1998L, 1998L, 1998L, 1998L,
1998L, 1998L, 1998L, 1998L, 1998L, 1999L, 1999L, 1999L, 1999L,
1999L, 1999L, 1999L, 1999L, 1999L, 1999L, 2000L, 2000L, 2000L,
2000L, 2000L, 2000L, 2000L, 2000L, 2000L, 2000L, 2001L, 2001L,
2001L, 2001L, 2001L, 2001L, 2001L, 2001L, 2001L, 2001L, 2002L,
2002L, 2002L, 2002L, 2002L, 2002L, 2002L, 2002L, 2002L, 2002L
), SS = c(50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50,
50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50,
50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50,
50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50,
50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50,
50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50,
50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50,
50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50,
50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50,
50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50,
50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50,
50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50,
50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50,
50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50,
50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50,
50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50,
50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50,
50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50,
50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50,
50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50,
50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50,
50, 50, 50, 50, 50, 50, 50, 50), Sex = c("Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex"
), Age = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L,
3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L,
7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L,
1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L,
5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L,
9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L,
3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L,
7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L,
1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L,
5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L,
9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L,
3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L,
7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L,
1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L,
5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L,
9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L,
3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L,
7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L,
1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L,
5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L,
9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L,
3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L,
7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L),
Obs = c(0, 0, 0.0845488, 0.232127, 0.29506, 0.136825,
0.112257, 0.0707206, 0.0388497, 0.0296115, 0, 0, 0.0695204,
0.229131, 0.239544, 0.177074, 0.0859766, 0.0758038, 0.0816456,
0.0413032, 0, 0, 0.270907, 0.189378, 0.203087, 0.126378,
0.0943184, 0.027322, 0.0349811, 0.0536282, 0, 0, 0.110408,
0.459793, 0.162302, 0.107188, 0.0667386, 0.0462276, 0.0122485,
0.0350946, 0, 0, 0.221055, 0.222473, 0.332989, 0.0911951,
0.0726362, 0.0278459, 0.0154733, 0.0163333, 0, 0, 0.192654,
0.325122, 0.172341, 0.19933, 0.0474159, 0.0436573, 0.0105977,
0.00888181, 0, 0, 0.0241952, 0.394852, 0.300496, 0.112572,
0.120485, 0.0260001, 0.0164109, 0.00498898, 0, 0, 0.0610734,
0.165811, 0.447244, 0.179443, 0.0888665, 0.0419339, 0.00995663,
0.0056706, 0, 0, 0.0688281, 0.272276, 0.131909, 0.329898,
0.135338, 0.0423926, 0.0137158, 0.00564149, 0, 0, 0.0366357,
0.24039, 0.273841, 0.127391, 0.228257, 0.0661179, 0.0187729,
0.00859439, 0, 0, 0.0170211, 0.10686, 0.314986, 0.186822,
0.102143, 0.212603, 0.0386068, 0.0209589, 0, 0, 0.0292021,
0.185009, 0.217455, 0.252027, 0.12456, 0.0681471, 0.102381,
0.0212193, 0, 0, 0.0398909, 0.122456, 0.272805, 0.212632,
0.1951, 0.0940702, 0.0230546, 0.0399919, 0, 0, 0.0729588,
0.341047, 0.209905, 0.165654, 0.087356, 0.0792927, 0.0289673,
0.0148187, 0, 0, 0.0636176, 0.241899, 0.3487, 0.179976,
0.0858252, 0.0413904, 0.0223061, 0.0162862, 0, 0, 0.175677,
0.173021, 0.226757, 0.26246, 0.0971319, 0.0377957, 0.0150723,
0.0120851, 0, 0, 0.0798062, 0.450678, 0.197245, 0.109728,
0.113848, 0.0301685, 0.0106123, 0.00791388, 0, 0, 0.0496263,
0.290698, 0.413208, 0.137967, 0.047305, 0.0434461, 0.009943,
0.00780655, 0, 0, 0.0214635, 0.230561, 0.412453, 0.259168,
0.0495184, 0.0157783, 0.00725885, 0.00379833, 0, 0, 0.0523269,
0.111374, 0.245841, 0.402822, 0.154104, 0.0232735, 0.00550857,
0.00474877, 0, 0, 0.0826881, 0.242931, 0.149745, 0.207967,
0.242032, 0.0615182, 0.00872894, 0.00438864, 0, 0, 0.131937,
0.234435, 0.286446, 0.123255, 0.108783, 0.0896789, 0.0216638,
0.00380142, 0, 0, 0.221507, 0.357415, 0.164185, 0.143504,
0.038715, 0.0300925, 0.0292497, 0.0153326, 0, 0, 0.0961764,
0.37693, 0.307046, 0.108792, 0.0685881, 0.0196256, 0.00935222,
0.0134897, 0, 0, 0.191263, 0.161659, 0.298863, 0.232037,
0.0730776, 0.0283431, 0.00555852, 0.00919908, 0, 0, 0.10153,
0.282183, 0.139746, 0.233295, 0.178739, 0.0408887, 0.0158664,
0.00775311, 0, 0, 0.0300199, 0.286636, 0.301559, 0.116994,
0.128639, 0.103867, 0.0199958, 0.0122904, 0, 0, 0.0492431,
0.10975, 0.361619, 0.287185, 0.0839184, 0.0549108, 0.0420233,
0.0113496, 0, 0, 0.0315137, 0.244047, 0.19003, 0.307299,
0.161824, 0.0348834, 0.0185587, 0.0118441, 0, 0, 0.137208,
0.0860543, 0.380255, 0.146806, 0.148938, 0.0734488, 0.0144361,
0.0128539, 0, 0, 0.146257, 0.323012, 0.120108, 0.251174,
0.0724961, 0.050684, 0.0260196, 0.0102478, 0, 0, 0.0855117,
0.266334, 0.350131, 0.0990576, 0.128873, 0.0320921, 0.0194974,
0.018503), Fit = c(0.000638965, 0.00539005, 0.0514821,
0.19173, 0.312928, 0.148901, 0.12184, 0.0799654, 0.036124,
0.0509998, 0.000409886, 0.0139091, 0.051432, 0.207722,
0.286914, 0.190819, 0.0846123, 0.0692351, 0.0454399,
0.0495077, 0.000714247, 0.00832158, 0.123764, 0.193218,
0.287313, 0.159426, 0.0986369, 0.0437373, 0.0357886,
0.04908, 0.0010244, 0.0130894, 0.0667764, 0.415362, 0.227884,
0.123364, 0.0628768, 0.0389019, 0.0172498, 0.0334719,
0.00031764, 0.0181587, 0.101581, 0.216404, 0.46935, 0.0920679,
0.0456671, 0.023276, 0.0144009, 0.0187765, 0.000511249,
0.00556349, 0.139304, 0.326849, 0.248225, 0.202328, 0.0366113,
0.0181598, 0.00925581, 0.0131932, 0.000466816, 0.00791425,
0.0377433, 0.398649, 0.342911, 0.103741, 0.0785823, 0.0142195,
0.00705309, 0.00871902, 0.000250395, 0.00824454, 0.0613179,
0.124613, 0.506018, 0.189427, 0.0538112, 0.0407611, 0.00737574,
0.00818112, 0.000262341, 0.00485798, 0.070216, 0.223974,
0.180101, 0.333972, 0.118009, 0.0335232, 0.0253933, 0.00969158,
0.000202924, 0.00481452, 0.03913, 0.24217, 0.303453,
0.110129, 0.192523, 0.0680279, 0.0193249, 0.0202252,
0.000385277, 0.00412606, 0.0429512, 0.14897, 0.356766,
0.196744, 0.0671295, 0.117353, 0.0414666, 0.0241079,
0.000313304, 0.00912447, 0.0428358, 0.188625, 0.243086,
0.238065, 0.122393, 0.0417606, 0.0730039, 0.0407933,
0.000322505, 0.00697885, 0.0890798, 0.176561, 0.286243,
0.148186, 0.135005, 0.0694081, 0.0236821, 0.0645338,
0.000936013, 0.00619379, 0.0587591, 0.317516, 0.234709,
0.15671, 0.0756961, 0.0689631, 0.035455, 0.0450626, 0.000878002,
0.0172103, 0.0499387, 0.201043, 0.409728, 0.127367, 0.0795414,
0.0384212, 0.0350037, 0.0408686, 0.000489238, 0.0170151,
0.146208, 0.179489, 0.268679, 0.224222, 0.0649908, 0.0405871,
0.019605, 0.038715, 0.000177721, 0.00790534, 0.120418,
0.43387, 0.189616, 0.106351, 0.0818394, 0.0237212, 0.014814,
0.0212865, 0.000243797, 0.00280508, 0.0546344, 0.348011,
0.440339, 0.0699475, 0.0360284, 0.0277246, 0.00803601,
0.0122298, 0.000194704, 0.00484183, 0.0244107, 0.200271,
0.464482, 0.2309, 0.0340273, 0.0175267, 0.0134872, 0.00985872,
0.000429596, 0.00456273, 0.0497497, 0.106331, 0.327478,
0.316651, 0.147086, 0.0216757, 0.0111647, 0.0148716,
0.000504525, 0.0106648, 0.0496371, 0.228163, 0.17826,
0.217427, 0.195237, 0.0906885, 0.0133646, 0.0160532,
0.000266852, 0.0113279, 0.104848, 0.20406, 0.32936, 0.0935051,
0.104733, 0.0940447, 0.0436842, 0.0141705, 0.000645264,
0.00519243, 0.0964787, 0.37206, 0.249576, 0.140106, 0.0363037,
0.0406631, 0.0365132, 0.0224624, 0.000773592, 0.0117176,
0.0412736, 0.31966, 0.425806, 0.0998716, 0.0512099, 0.0132693,
0.0148627, 0.0215562, 0.00028678, 0.0144853, 0.0961941,
0.143519, 0.415595, 0.22908, 0.0501615, 0.0257206, 0.00666464,
0.0182918, 0.000530789, 0.00498713, 0.110502, 0.312583,
0.178982, 0.224859, 0.116343, 0.0254754, 0.0130627, 0.0126746,
0.000130421, 0.00838321, 0.0345569, 0.326571, 0.356571,
0.0894646, 0.10562, 0.0546478, 0.0119662, 0.0120892,
0.000510948, 0.00241485, 0.0681118, 0.119952, 0.440896,
0.213702, 0.0504572, 0.0595685, 0.0308209, 0.013567,
0.000557106, 0.0109344, 0.022666, 0.271876, 0.182378,
0.286999, 0.130381, 0.0307844, 0.0363432, 0.0270815,
0.000652707, 0.0119655, 0.102941, 0.0901916, 0.400405,
0.109015, 0.159788, 0.0725902, 0.0171393, 0.035312, 0.000875772,
0.0126681, 0.101768, 0.36908, 0.118183, 0.207708, 0.0525131,
0.0769709, 0.0349672, 0.0252663, 0.000189883, 0.0140363,
0.0889552, 0.300633, 0.394533, 0.0490072, 0.0797777,
0.0201695, 0.0295635, 0.0231349)), row.names = c(NA,
-320L), class = "data.frame"), CAs = structure(list(Series = c(1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), Year = c(1985L, 1985L,
1985L, 1985L, 1985L, 1985L, 1985L, 1985L, 1985L, 1985L, 1986L,
1986L, 1986L, 1986L, 1986L, 1986L, 1986L, 1986L, 1986L, 1986L,
1987L, 1987L, 1987L, 1987L, 1987L, 1987L, 1987L, 1987L, 1987L,
1987L, 1988L, 1988L, 1988L, 1988L, 1988L, 1988L, 1988L, 1988L,
1988L, 1988L, 1989L, 1989L, 1989L, 1989L, 1989L, 1989L, 1989L,
1989L, 1989L, 1989L, 1990L, 1990L, 1990L, 1990L, 1990L, 1990L,
1990L, 1990L, 1990L, 1990L, 1991L, 1991L, 1991L, 1991L, 1991L,
1991L, 1991L, 1991L, 1991L, 1991L, 1992L, 1992L, 1992L, 1992L,
1992L, 1992L, 1992L, 1992L, 1992L, 1992L, 1993L, 1993L, 1993L,
1993L, 1993L, 1993L, 1993L, 1993L, 1993L, 1993L, 1994L, 1994L,
1994L, 1994L, 1994L, 1994L, 1994L, 1994L, 1994L, 1994L, 1995L,
1995L, 1995L, 1995L, 1995L, 1995L, 1995L, 1995L, 1995L, 1995L,
1996L, 1996L, 1996L, 1996L, 1996L, 1996L, 1996L, 1996L, 1996L,
1996L, 1997L, 1997L, 1997L, 1997L, 1997L, 1997L, 1997L, 1997L,
1997L, 1997L, 1998L, 1998L, 1998L, 1998L, 1998L, 1998L, 1998L,
1998L, 1998L, 1998L, 1999L, 1999L, 1999L, 1999L, 1999L, 1999L,
1999L, 1999L, 1999L, 1999L, 2000L, 2000L, 2000L, 2000L, 2000L,
2000L, 2000L, 2000L, 2000L, 2000L, 2001L, 2001L, 2001L, 2001L,
2001L, 2001L, 2001L, 2001L, 2001L, 2001L, 2002L, 2002L, 2002L,
2002L, 2002L, 2002L, 2002L, 2002L, 2002L, 2002L, 2003L, 2003L,
2003L, 2003L, 2003L, 2003L, 2003L, 2003L, 2003L, 2003L),
SS = c(30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
30, 30, 30, 30, 30, 30, 30, 30, 30, 30), Sex = c("Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex", "Unisex", "Unisex", "Unisex",
"Unisex", "Unisex", "Unisex"), Age = c(1L, 2L, 3L, 4L,
5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 7L,
8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L,
1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L,
4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L,
7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L,
10L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L,
3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L,
6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L,
9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L,
2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L,
5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 7L,
8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L,
1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L,
4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L,
7L, 8L, 9L, 10L), Obs = c(0.0512773, 0.344339, 0.108042,
0.149089, 0.199343, 0.0699715, 0.0460689, 0.015036, 0.00995164,
0.00688244, 0.0597677, 0.240022, 0.37874, 0.0888986,
0.0841425, 0.104475, 0.0263168, 0.00982918, 0.0032896,
0.00451825, 0.0136367, 0.107823, 0.38519, 0.306471, 0.0787566,
0.0456549, 0.0449077, 0.00960173, 0.00336248, 0.00459538,
0.0126568, 0.0270797, 0.26377, 0.373855, 0.245594, 0.0287354,
0.0216344, 0.022591, 0.002134, 0.00195003, 0.017625,
0.0717651, 0.0958468, 0.338976, 0.29487, 0.149202, 0.018323,
0.0063258, 0.00497339, 0.00209406, 0.0415639, 0.0881364,
0.195485, 0.105181, 0.201615, 0.242057, 0.106302, 0.011288,
0.00396202, 0.00441056, 0.030792, 0.126832, 0.139772,
0.235189, 0.118803, 0.14102, 0.163159, 0.0329747, 0.00623636,
0.00522295, 0.00684215, 0.162786, 0.31607, 0.179321,
0.154614, 0.0621496, 0.0541671, 0.0485603, 0.0122589,
0.00323102, 0.0342315, 0.0462173, 0.294947, 0.349123,
0.126954, 0.0952153, 0.0204238, 0.0167801, 0.0112187,
0.00489021, 0.14657, 0.152992, 0.091428, 0.271736, 0.223219,
0.0588115, 0.0368974, 0.00713485, 0.00489247, 0.00631944,
0.0105395, 0.259289, 0.221329, 0.0802965, 0.21329, 0.158003,
0.0337621, 0.0157199, 0.00312612, 0.00464452, 0.0290375,
0.0427757, 0.332527, 0.229803, 0.100226, 0.114121, 0.109203,
0.0297401, 0.00819608, 0.00437124, 0.00815309, 0.150866,
0.0914359, 0.378546, 0.195742, 0.0638771, 0.0586888,
0.044404, 0.00377333, 0.00451452, 0.048751, 0.0336297,
0.181334, 0.0971391, 0.373616, 0.171354, 0.0393758, 0.0314522,
0.018448, 0.00489929, 0.0520459, 0.23227, 0.0493697,
0.297697, 0.0916966, 0.166631, 0.0783154, 0.0165505,
0.00929643, 0.00612719, 0.117496, 0.174462, 0.342296,
0.0433967, 0.187594, 0.0517759, 0.0511506, 0.0258879,
0.00318909, 0.00275138, 0.0901008, 0.160937, 0.272525,
0.278601, 0.0363812, 0.112922, 0.024674, 0.0145969, 0.00585359,
0.00340842, 0.00527583, 0.218316, 0.235807, 0.230302,
0.207363, 0.0407157, 0.0477692, 0.00854456, 0.00412891,
0.00177773, 0.0691984, 0.0275059, 0.287201, 0.238818,
0.195205, 0.118263, 0.0254615, 0.0291785, 0.00669062,
0.00247801), Fit = c(0.0835561, 0.229767, 0.142831, 0.188116,
0.203169, 0.0604952, 0.0377795, 0.0182488, 0.0166256,
0.0194112, 0.0395434, 0.192933, 0.355162, 0.142642, 0.113153,
0.0904507, 0.0262172, 0.0163727, 0.00790859, 0.0156175,
0.015593, 0.0973032, 0.317529, 0.374286, 0.0866851, 0.0465706,
0.035837, 0.0103874, 0.00648697, 0.00932123, 0.0278185,
0.0449021, 0.187358, 0.390438, 0.261801, 0.0398343, 0.0205177,
0.0157888, 0.00457641, 0.00696471, 0.0258808, 0.0902879,
0.0975178, 0.261743, 0.3217, 0.153182, 0.0225741, 0.0116274,
0.00894752, 0.00654037, 0.0545917, 0.0813407, 0.190002,
0.132855, 0.216834, 0.200829, 0.0932861, 0.0137474, 0.00708096,
0.00943199, 0.0541123, 0.160467, 0.160001, 0.24061, 0.0996202,
0.116388, 0.10451, 0.0485452, 0.00715401, 0.00859322,
0.02547, 0.151679, 0.30076, 0.191501, 0.163798, 0.0445425,
0.0498912, 0.0447994, 0.0208095, 0.00675029, 0.0608188,
0.0686576, 0.273297, 0.3448, 0.12257, 0.0659078, 0.0170778,
0.0191285, 0.0171763, 0.0105666, 0.077193, 0.164029,
0.123777, 0.313623, 0.22139, 0.049738, 0.0255035, 0.00660837,
0.00740193, 0.0107354, 0.0274876, 0.194775, 0.277101,
0.135255, 0.207557, 0.109586, 0.0239959, 0.0123041, 0.00318819,
0.00875031, 0.0504747, 0.0665303, 0.315808, 0.292262,
0.088683, 0.106719, 0.0552168, 0.0120908, 0.00619962,
0.00601543, 0.0148537, 0.133942, 0.118284, 0.365696,
0.211599, 0.0508534, 0.0600361, 0.0310628, 0.00680178,
0.00687172, 0.0622297, 0.04126, 0.249313, 0.143642, 0.279793,
0.1299, 0.0306708, 0.0362091, 0.0187347, 0.00824681,
0.0622535, 0.17141, 0.0761208, 0.298711, 0.106188, 0.160061,
0.0727143, 0.0171686, 0.0202688, 0.0151035, 0.0629793,
0.161967, 0.298517, 0.0855658, 0.201307, 0.0524982, 0.0769491,
0.0349572, 0.00825378, 0.0170052, 0.0733498, 0.148845,
0.256165, 0.303936, 0.0515754, 0.0868244, 0.0219511,
0.0321747, 0.0146167, 0.0105616, 0.0174999, 0.181477,
0.24639, 0.272421, 0.189458, 0.0225419, 0.0366954, 0.00927738,
0.0135983, 0.0106413, 0.0588922, 0.0441024, 0.306234,
0.269207, 0.18112, 0.0950447, 0.0110333, 0.0179608, 0.00454088,
0.0118643)), row.names = c(NA, -190L), class = "data.frame")), call = quote(importCol(res.file = "~/r/library/scape/example/cod.res",
Dev = TRUE, Survey = TRUE, CAc = TRUE, CAs = TRUE)), class = "scape") |
library(testthat)
library(RBesT)
cat("TEST RUN DATE:", date(), "\n")
cat("TESTING PACKAGE:\n")
print(packageDescription("RBesT"))
Sys.setenv(NOT_CRAN="true")
cat("RUNNING PACKAGE TESTS:\n")
for(test in c("gMAP", "EM", "oc1S", "oc2S", "mixdist", "mixdiff", "preddist", "postmix", "utils", "pos1S", "pos2S")) {
test_package("RBesT", filter=test, reporter="tap")
}
test_package("RBesT", reporter="stop")
cat("\n\nR SESSION INFO:\n")
print(sessionInfo())
cat("\nTEST FINISH DATE:", date(), "\n")
cat("\n\nALL TESTS SUCCESSFUL\n") |
context("lapply")
test_that("eply and evals can be passed to functions like lapply", {
e <- split(example.expr(), f = seq_len(nrow(example.expr())))
expect_silent(o <- lapply(e, eply,
.fun = example.fun, .with = example.with()
))
expect_silent(o <- lapply(c("1+1", "a+2"), evals, .with = list(a = 1)))
}) |
print.robustlm <- function(x, ...){
out <- list(
beta = x[["beta"]],
alpha = x[["alpha"]],
gamma = x[["gamma"]],
weight = x[["weight"]],
loss = x[["loss"]]
)
print(out)
} |
foo <- function (x, ...) 123 |
plotgaps <- function(X, code.type = .code.type[1],
main = "Gaps Plot", xlab = "Sites", ylab = "Proportion", ...){
if(sum(code.type %in% .code.type) != 1){
stop("The code.type is not found.")
}
if(code.type == .code.type[1]){
GAP <- .nucleotide$nid[.nucleotide$code == "-"]
} else if(code.type == .code.type[2]){
GAP <- .snp$sid[.snp$code == "-"]
} else{
stop("code.type is not implemented.")
}
my.col <- "gray"
N <- nrow(X)
L <- ncol(X)
xlim <- c(1, L)
ylim <- c(0, 1)
prop <- colSums(X == GAP) / N
plot(1:L, prop, type = "l",
xlim = xlim, ylim = ylim, col = my.col,
main = main, xlab = xlab, ylab = ylab)
} |
setConstructorS3("AffymetrixTsvFile", function(...) {
this <- extend(AffymetrixFile(...), "AffymetrixTsvFile",
"cached:.cdf" = NULL,
"cached:.data" = NULL
)
if (isFile(this)) verify(this)
this
})
setMethodS3("getChipType", "AffymetrixTsvFile", function(this, ...) {
getName(this)
})
setMethodS3("getDefaultExtension", "AffymetrixTsvFile", function(static, ...) {
"tsv"
}, static=TRUE, protected=TRUE)
setMethodS3("getExtensionPattern", "AffymetrixTsvFile", function(static, ...) {
ext <- getDefaultExtension(static, ...)
pattern <- sprintf("[.](%s|%s)$", tolower(ext), toupper(ext))
pattern
}, static=TRUE, protected=TRUE)
setMethodS3("findByChipType", "AffymetrixTsvFile", function(static, chipType, ...) {
pattern <- sprintf("^%s%s", chipType, getExtensionPattern(static))
pathname <- findAnnotationDataByChipType(chipType, pattern)
pathname
}, static=TRUE, protected=TRUE)
setMethodS3("byChipType", "AffymetrixTsvFile", function(static, chipType, ...) {
pathname <- findByChipType(static, chipType, ...)
if (is.null(pathname))
throw("Failed to located Affymetrix TSV file: ", chipType)
newInstance(static, pathname)
})
setMethodS3("verify", "AffymetrixTsvFile", function(this, ...) {
tryCatch({
df <- readDataFrame(this, nrows=10)
}, error = function(ex) {
throw("File format error of the Affymetrix TSV file: ",
getPathname(this))
})
invisible(TRUE)
}, private=TRUE)
setMethodS3("getData", "AffymetrixTsvFile", function(this, force=FALSE, ...) {
data <- this$.data
if (force || is.null(data)) {
data <- readDataFrame(this, ...)
this$.data <- data
}
data
})
setMethodS3("readDataFrame", "AffymetrixTsvFile", function(this, ..., verbose=FALSE) {
pathname <- getPathname(this)
colClasses <- c(
"probeset_id"="character",
"chr"="character",
"snp_pos"="integer",
"len"="integer",
"GC"="double",
"gc_count"="integer"
)
df <- readTable(pathname, colClasses=colClasses, header=TRUE, sep="\t", ...)
names <- colnames(df)
names <- gsub("probeset_id", "unit", names)
names <- gsub("chr", "chromosome", names)
names <- gsub("GC", "gc", names)
names <- gsub("snp_pos", "physical position", names)
names <- gsub("_", " ", names)
names <- toCamelCase(names)
colnames(df) <- names
df[["gc"]] <- df[["gc"]]/100
chr <- df[["chromosome"]]
chr[chr == "X"] <- 23
chr[chr == "Y"] <- 24
suppressWarnings({
chr <- as.integer(chr)
})
df[["chromosome"]] <- chr
chr <- NULL
df <- unique(df)
gc()
unf <- getUnitNamesFile(this)
unitNames <- getUnitNames(unf)
units <- match(df[["unit"]], unitNames)
if (any(is.na(units))) {
throw("File format error: Identified units that do not exist in the annotation unit names file: ", getChipType(unf))
}
df[["unit"]] <- units
o <- order(units)
df <- df[o,]
df
})
setMethodS3("getField", "AffymetrixTsvFile", function(this, units=NULL, field, ...) {
if (is.null(units)) {
unf <- getUnitNamesFile(this)
units <- seq_len(nbrOfUnits(unf))
}
data <- getData(this, ...)
if (!field %in% colnames(data))
throw("No such field: ", field)
idxs <- match(units, data$unit)
data[[field]][idxs]
})
setMethodS3("getPosition", "AffymetrixTsvFile", function(this, ...) {
getField(this, field="physicalPosition", ...)
})
setMethodS3("getFragmentLengths", "AffymetrixTsvFile", function(this, ...) {
getField(this, field="len", ...)
})
setMethodS3("getGc", "AffymetrixTsvFile", function(this, ...) {
getField(this, field="gc", ...)
})
setMethodS3("getCdf", "AffymetrixTsvFile", function(this, ...) {
cdf <- this$.cdf
if (is.null(cdf)) {
chipType <- getChipType(this)
cdf <- AffymetrixCdfFile$byChipType(chipType)
this$.cdf <- cdf
}
cdf
}) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.