code
stringlengths 1
13.8M
|
---|
glm.fsreg_2 <- function(target, dataset, iniset = NULL, wei = NULL, threshold = 0.05, tol = 2, ncores = 1) {
dm <- dim(dataset)
if ( is.null(dm) ) {
n <- length(target)
p <- 1
} else {
n <- dm[1]
p <- dm[2]
}
devi <- dof <- numeric( p )
moda <- list()
k <- 1
tool <- numeric( min(n, p) )
threshold <- log(threshold)
pa <- NCOL(iniset)
da <- 1:pa
dataset <- cbind(iniset, dataset)
dataset <- as.data.frame(dataset)
if ( is.matrix(target) & NCOL(target) == 2 ) {
ci_test <- "testIndBinom"
y <- target[, 1]
wei <- target[, 2]
ywei <- y / wei
runtime <- proc.time()
devi = dof = numeric(p)
if ( pa == 0 ) {
mi <- glm( ywei ~ 1, weights = wei, family = binomial, y = FALSE, model = FALSE )
do <- 1
ini <- mi$deviance
} else
mi <- glm(ywei ~., data = as.data.frame( iniset ), weights = wei, family = binomial, y = FALSE, model = FALSE )
do <- length( coef(mi) )
ini <- mi$deviance
if (ncores <= 1) {
for (i in 1:p) {
mi <- glm( ywei ~ . , as.data.frame( dataset[, c(da, pa + i)] ), weights = wei, family = binomial, y = FALSE, model = FALSE )
devi[i] <- mi$deviance
dof[i] = length( coef( mi ) )
}
stat = ini - devi
pval = pchisq( stat, dof - do, lower.tail = FALSE, log.p = TRUE )
} else {
cl <- makePSOCKcluster(ncores)
registerDoParallel(cl)
mod <- foreach( i = 1:p, .combine = rbind) %dopar% {
ww <- glm( ywei ~., data = as.data.frame( dataset[, c(da, pa + i)] ), weights = wei, family = binomial )
return( c( ww$deviance, length( coef( ww ) ) ) )
}
stopCluster(cl)
stat <- ini - mod[, 1]
pval <- pchisq( stat, mod[, 2] - 1, lower.tail = FALSE, log.p = TRUE )
}
mat <- cbind(1:p, pval, stat)
colnames(mat)[1] <- "variables"
rownames(mat) <- 1:p
sel <- which.min(pval)
info <- matrix( c( 1e300, 0, 0 ), ncol = 3 )
sela <- sel
if ( mat[sel, 2] < threshold ) {
info[k, ] <- mat[sel, ]
mat <- mat[-sel, , drop = FALSE]
mi <- glm( ywei ~., data = as.data.frame( dataset[, c(da, sel) ] ), weights = wei, family = binomial, y = FALSE, model = FALSE )
tool[k] <- BIC( mi )
moda[[ k ]] <- mi
}
if ( info[k, 2] < threshold & nrow(mat) > 0 ) {
k <- k + 1
pn <- p - k + 1
ini <- moda[[ 1 ]]$deviance
do <- length( coef( moda[[ 1 ]] ) )
devi <- dof <- numeric( pn )
if ( ncores <= 1 ) {
for ( i in 1:pn ) {
ww <- glm( ywei ~., data = as.data.frame( dataset[, c(da, sela, mat[pa + i, 1]) ] ), weights = wei, family = binomial, y = FALSE, model = FALSE )
devi[i] <- ww$deviance
dof[i] <- length( coef( ww ) )
}
stat <- ini - devi
pval <- pchisq( stat, dof - do, lower.tail = FALSE, log.p = TRUE )
} else {
cl <- makePSOCKcluster(ncores)
registerDoParallel(cl)
mod <- foreach( i = 1:pn, .combine = rbind) %dopar% {
ww <- glm( ywei ~., data = as.data.frame( dataset[, c(da, sela, mat[pa + i, 1]) ] ), weights = wei, family = binomial )
return( c( ww$deviance, length( coef( ww ) ) ) )
}
stopCluster(cl)
stat <- ini - mod[, 1]
pval <- pchisq( stat, mod[, 2] - do, lower.tail = FALSE, log.p = TRUE )
}
mat[, 2:3] <- cbind(pval, stat)
ina <- which.min(mat[, 2])
sel <- mat[ina, 1]
if ( mat[ina, 2] < threshold ) {
ma <- glm( ywei ~., data=as.data.frame( dataset[, c(da, sela, sel) ] ), weights = wei, family = binomial, y = FALSE, model = FALSE )
tool[k] <- BIC( ma )
if ( tool[ k - 1 ] - tool[ k ] <= tol ) {
info <- info
} else {
info <- rbind(info, c( mat[ina, ] ) )
sela <- info[, 1]
mat <- mat[-ina , , drop = FALSE]
moda[[ k ]] <- ma
}
} else info <- info
}
if ( nrow(info) > 1 & nrow(mat) > 0 ) {
while ( info[k, 2] < threshold & k < n - 15 & tool[ k - 1 ] - tool[ k ] > tol & nrow(mat) > 0 ) {
ini <- moda[[ k ]]$deviance
do <- length( coef( moda[[ k ]] ) )
k <- k + 1
pn <- p - k + 1
devi <- dof <- numeric( pn )
if (ncores <= 1) {
for ( i in 1:pn ) {
ma <- glm( ywei ~., data = as.data.frame( dataset[, c(da, sela, mat[pa + i, 1] ) ] ), weights = wei, family = binomial, y = FALSE, model = FALSE )
devi[i] <- ma$deviance
dof[i] <- length( coef( ma ) )
}
stat <- ini - devi
pval <- pchisq( stat, dof - do, lower.tail = FALSE, log.p = TRUE )
} else {
cl <- makePSOCKcluster(ncores)
registerDoParallel(cl)
mod <- foreach( i = 1:pn, .combine = rbind) %dopar% {
ww <- glm( ywei ~., data = as.data.frame( dataset[, c(da, sela, mat[pa + i, 1]) ] ), weights = wei, family = binomial, y = FALSE, model = FALSE )
return( c( ww$deviance, length( coef( ww ) ) ) )
}
stopCluster(cl)
stat <- ini - mod[, 1]
pval <- pchisq( stat, mod[, 2] - do, lower.tail = FALSE, log.p = TRUE )
}
mat[, 2:3] <- cbind(pval, stat)
ina <- which.min(mat[, 2])
sel <- mat[ina, 1]
if ( mat[ina, 2] < threshold ) {
ma <- glm( ywei ~., data = as.data.frame( dataset[, c(da, sela, sel) ] ), weights = wei, family = binomial, y = FALSE, model = FALSE )
tool[k] <- BIC( ma )
if ( tool[ k - 1 ] - tool[ k ] < tol ) {
info <- rbind(info, c( 1e300, 0, 0 ) )
} else {
info <- rbind( info, mat[ina, ] )
sela <- info[, 1]
mat <- mat[-ina , , drop = FALSE]
moda[[ k ]] <- ma
}
} else info <- rbind(info, c( 1e300, 0, 0 ) )
}
}
runtime <- proc.time() - runtime
d <- length(moda)
final <- NULL
if ( d >= 1 ) {
final <- glm( ywei ~., data = as.data.frame( dataset[, c(da, sela) ] ), weights = wei, family = binomial, y = FALSE, model = FALSE )
info <- info[1:d, , drop = FALSE]
info <- cbind( info, tool[ 1:d ] )
colnames(info) <- c( "variables", "log.p-value", "stat", "BIC" )
rownames(info) <- info[, 1]
}
result <- list(mat = t(mat), info = info, final = final, runtime = runtime )
} else {
if ( length( unique(target) ) == 2 ) {
oiko <- binomial(logit)
ci_test <- "testIndLogistic"
} else {
ci_test <- "testIndPois"
oiko <- poisson(log)
}
runtime <- proc.time()
devi = dof = numeric(p)
mi <- glm(target ~., data = data.frame( iniset ), family = oiko, y = FALSE, model = FALSE )
ini <- mi$deviance
do <- length( coef(mi) )
if (ncores <= 1) {
for (i in 1:p) {
mi <- glm( target ~ ., data.frame( dataset[, c(da, pa + i)] ), family = oiko, weights= wei, y = FALSE, model = FALSE )
devi[i] <- mi$deviance
dof[i] <- length( coef( mi ) )
}
stat <- ini - devi
pval <- pchisq( stat, dof - do, lower.tail = FALSE, log.p = TRUE )
} else {
cl <- makePSOCKcluster(ncores)
registerDoParallel(cl)
mod <- foreach( i = 1:p, .combine = rbind) %dopar% {
ww <- glm( target ~., data = data.frame( dataset[, c(da, pa + i)] ), family = oiko, weights = wei, y = FALSE, model = FALSE )
return( c( ww$deviance, length( coef(ww) ) ) )
}
stopCluster(cl)
stat <- ini - mod[, 1]
pval <- pchisq( stat, mod[, 2] - 1, lower.tail = FALSE, log.p = TRUE )
}
mat <- cbind(1:p, pval, stat)
colnames(mat)[1] <- "variables"
rownames(mat) <- 1:p
sel <- which.min(pval)
info <- matrix( c( 1e300, 0, 0 ), ncol = 3 )
sela <- sel
if ( mat[sel, 2] < threshold ) {
info[k, ] <- mat[sel, ]
mat <- mat[-sel, , drop= FALSE]
mi <- glm( target ~., data = as.data.frame( dataset[, c(da, sel) ] ), family = oiko, weights = wei, y = FALSE, model = FALSE )
tool[k] <- BIC( mi )
moda[[ k ]] <- mi
}
if ( info[k, 2] < threshold & nrow(mat) > 0 ) {
k <- k + 1
pn <- p - k + 1
ini <- mi$deviance
do <- length( coef( mi ) )
if ( ncores <= 1 ) {
devi <- dof <- numeric(pn)
for ( i in 1:pn ) {
ww <- glm( target ~., data = as.data.frame( dataset[, c(da, sela, mat[pa + i, 1]) ] ), family = oiko, weights = wei, y = FALSE, model = FALSE )
devi[i] <- ww$deviance
dof[i] <- length( coef( ww ) )
}
stat <- ini - devi
pval <- pchisq( stat, dof - do, lower.tail = FALSE, log.p = TRUE )
} else {
cl <- makePSOCKcluster(ncores)
registerDoParallel(cl)
mod <- foreach( i = 1:pn, .combine = rbind) %dopar% {
ww <- glm( target ~., data = as.data.frame( dataset[, c(da, sela, mat[pa + i, 1]) ] ), family = oiko, weights = wei, y = FALSE, model = FALSE )
return( c( ww$deviance, length( coef( ww ) ) ) )
}
stopCluster(cl)
stat <- ini - mod[, 1]
pval <- pchisq( stat, mod[, 2] - do, lower.tail = FALSE, log.p = TRUE )
}
mat[, 2:3] <- cbind(pval, stat)
ina <- which.min(mat[, 2])
sel <- mat[ina, 1]
if ( mat[ina, 2] < threshold ) {
ma <- glm( target ~., data=as.data.frame( dataset[, c(da, sela, sel) ] ), family = oiko, weights = wei, y = FALSE, model = FALSE )
tool[k] <- BIC( ma )
if ( tool[ k - 1 ] - tool[ k ] <= tol ) {
info <- rbind(info, c( 1e300, 0, 0 ) )
} else {
info <- rbind(info, c( mat[ina, ] ) )
sela <- info[, 1]
mat <- mat[-ina , , drop = FALSE]
moda[[ k ]] <- ma
}
} else info <- info
}
if ( nrow(info) > 1 & nrow(mat) > 0 ) {
while ( ( info[k, 2] < threshold ) & ( k < n ) & ( tool[ k - 1 ] - tool[ k ] > tol ) & ( nrow(mat) > 0 ) ) {
ini <- moda[[ k ]]$deviance
do <- length( coef( moda[[ k ]] ) )
k <- k + 1
pn <- p - k + 1
if (ncores <= 1) {
devi <- dof <- numeric(pn)
for ( i in 1:pn ) {
ma <- glm( target ~., data = as.data.frame( dataset[, c(da, sela, mat[pa + i, 1] ) ] ), family = oiko, weights = wei, y = FALSE, model = FALSE )
devi[i] <- ma$deviance
dof[i] <- length( coef( ma ) )
}
stat <- ini - devi
pval <- pchisq( stat, dof - do, lower.tail = FALSE, log.p = TRUE )
} else {
cl <- makePSOCKcluster(ncores)
registerDoParallel(cl)
devi <- dof <- numeric(pn)
mod <- foreach( i = 1:pn, .combine = rbind) %dopar% {
ww <- glm( target ~., data = as.data.frame( dataset[, c(da, sela, mat[pa + i, 1]) ] ), family = oiko, weights = wei, y = FALSE, model = FALSE )
return( c( ww$deviance, length( coef( ww ) ) ) )
}
stopCluster(cl)
stat <- ini - mod[, 1]
pval <- pchisq( stat, mod[, 2] - do, lower.tail = FALSE, log.p = TRUE )
}
mat[, 2:3] <- cbind(pval, stat)
ina <- which.min(mat[, 2])
sel <- mat[ina, 1]
if ( mat[ina, 2] < threshold ) {
ma <- glm( target ~., data = as.data.frame( dataset[, c(da, sela, sel) ] ), family = oiko, weights = wei, y = FALSE, model = FALSE )
tool[k] <- BIC( ma )
if ( tool[ k - 1 ] - tool[ k ] <= tol ) {
info <- rbind(info, c( 1e300, 0, 0 ) )
} else {
info <- rbind( info, mat[ina, ] )
sela <- info[, 1]
mat <- mat[-ina , , drop = FALSE]
moda[[ k ]] <- ma
}
} else info <- rbind(info, c( 1e300, 0, 0 ) )
}
}
runtime <- proc.time() - runtime
d <- length(moda)
final <- glm( target ~., data = as.data.frame( dataset[, c(da, sela) ] ), family = oiko, weights = wei, y = FALSE, model = FALSE )
info <- info[1:d, , drop = FALSE]
info <- cbind( info, tool[ 1:d ] )
colnames(info) <- c( "variables", "log.p-value", "stat", "BIC" )
rownames(info) <- info[, 1]
result <- list(runtime = runtime, mat = t(mat), info = info, ci_test = ci_test, final = final )
}
result
} |
mlsjunkgenv <- function(n = 1, w, x, y, z, round = 5) {
if (is.numeric(n)) { mls <- numeric()
for (i in 1:n) { ri <- junkgen(w, x, y, z)
mls <- c(mls, round(ri, round))
w <- x
x <- y
y <- z
z <- ri
}
return(mls)
}
else { stop("Invalid input. Please ensure n is numeric.") }
} |
plot.dwt <- function (x, levels = NULL, draw.boundary = FALSE,
type = "stack", col.plot = "black", col.boundary = "red",
X.xtick.at = NULL, X.ytick.at = NULL, Stack.xtick.at = NULL,
Stack.ytick.at = NULL, X.xlab = "t", y.rlabs = TRUE,
plot.X = TRUE, plot.W = TRUE, plot.V = TRUE, ...)
{
stackplot.dwt <- function ( x , w.range, v.range, col.plot, col.boundary,
draw.boundary = FALSE, X.xtick.at = NULL, X.ytick.at = NULL,
Stack.xtick.at = NULL, Stack.ytick.at = NULL, X.xlab = "t",
plot.X = TRUE)
{
innerplot <- function(x, y, type = "l", xtick.at, ytick.at)
{
if(is.null(xtick.at) == FALSE || is.null(ytick.at) == FALSE) {
plot(x, y, type = "l", axes = FALSE, frame.plot = TRUE)
if(is.null(xtick.at) == FALSE) {
axis(1, at = axTicks(1, xtick.at))
xtickrate <- xtick.at
}
else {
axis(1)
xtickrate <- par("xaxp")
}
if(is.null(ytick.at) == FALSE) {
axis(2, at = axTicks(2, ytick.at))
ytickrate <- ytick.at
}
else {
axis(2)
ytickrate <- par("yaxp")
}
}
else {
plot(x, y, type = "l")
xtickrate <- par("xaxp")
ytickrate <- par("yaxp")
}
tickrate <- list(xtick = xtickrate, ytick = ytickrate)
tickrate
}
if(plot.X) {
nf <- layout(matrix(c(2,2,1,1), 2, 2, byrow=TRUE), c(1,2), c(2,1), TRUE)
par(mai = c(.6, .4, .1, .6))
if( x @class.X == "ts" || x @class.X == "mts") {
x.range <- x @attr.X$tsp[1]: x @attr.X$tsp[2]
}
else{
x.range <- 1:dim( x @series)[1]
}
tickrate <- innerplot(x.range, x @series[,1], type = "l", X.xtick.at, X.ytick.at)
right.usrplotrange <- par()$usr[2] - par()$usr[1]
NDCplotrange <- par()$plt[2] - par()$plt[1]
marginpos <- (1-par()$plt[2])/2
right.usrlabelpos <- ((marginpos*right.usrplotrange)/NDCplotrange) + par()$usr[2]
text(right.usrlabelpos, 0, "X", xpd = TRUE)
mtext(X.xlab, side = 1, line = 2)
par(mai = c(0, .4, .1, .6))
}
if(plot.X == FALSE) {
par(mai = c(.4, .4, .1, .6))
if(is.null(Stack.xtick.at) == FALSE) {
xtickrate <- Stack.xtick.at
}
else {
xtickrate <- NULL
}
if(is.null(Stack.ytick.at) == FALSE) {
ytickrate <- Stack.ytick.at
}
else {
ytickrate <- NULL
}
tickrate <- list(xtick = xtickrate, ytick = ytickrate)
}
if (draw.boundary) {
matrixlist <- list(dwt = as.matrix.dwt( x , w.range, v.range), posbound = boundary.as.matrix.dwt( x , w.range, v.range, positive = TRUE), negbound = boundary.as.matrix.dwt( x , w.range, v.range, positive = FALSE))
col <- c(col.plot, col.boundary, col.boundary)
}
else {
matrixlist <- list(dwt = as.matrix.dwt( x , w.range, v.range))
col <- col.plot
}
if(is.null(w.range) == FALSE) {
gammawave <- wt.filter.shift( x @filter, w.range, wavelet = TRUE)
}
if(is.null(v.range) == FALSE) {
gammascale <- wt.filter.shift( x @filter, v.range, wavelet = FALSE)
}
if(y.rlabs) {
rightlabels <- labels.dwt(w.range = w.range, v.range = v.range, gammah = gammawave, gammag = gammascale)
}
else {
rightlabels <- NULL
}
stackplot(matrixlist, y = NULL, y.rlabs = rightlabels, col = col, xtick.at = tickrate$xtick, ytick.at = tickrate$ytick)
}
boundary.as.matrix.dwt <- function( x , w.range, v.range, positive = TRUE)
{
Lprimej <- x @n.boundary
if(is.null(w.range) == FALSE) {
wavecoefmatrix <- array(NA, c(2*dim( x @series)[1], length(w.range)))
Wjplot <- rep(NA, 2*dim( x @series)[1])
wavecoefmatrix.index <- 0
for (j in w.range)
{
wavecoefmatrix.index <- wavecoefmatrix.index + 1
levelshift <- waveletshift.dwt( x @filter@L, j, dim( x @series)[1])%%(2^j)
rightgamma <- wt.filter.shift( x @filter, j, wavelet = TRUE)
leftgamma <- Lprimej[j] - rightgamma
if(positive) {
boundaryheight <- max( x @W[[j]])
}
else {
boundaryheight <- min( x @W[[j]])
}
if(leftgamma != 0) {
leftboundarypos <- leftgamma*(2^j) + .5*(2^j) - levelshift
}
else {
leftboundarypos <- 0
}
if(rightgamma != 0) {
rightboundarypos <- dim( x @series)[1] - rightgamma*(2^j) + .5*(2^j) - levelshift
}
else {
rightboundarypos <- 0
}
if(leftboundarypos != 0 && rightboundarypos != 0) {
leftspace <- rep(NA, 2*leftboundarypos - 1)
middlespace <- rep(NA, 2*(rightboundarypos - leftboundarypos) - 1)
rightspace <- rep(NA, 2*(dim( x @series)[1] - rightboundarypos))
Wjplot <- c(leftspace, boundaryheight, middlespace, boundaryheight, rightspace)
}
if(leftboundarypos == 0 && rightboundarypos != 0) {
middlespace <- rep(NA, 2*rightboundarypos - 1)
rightspace <- rep(NA, 2*(dim( x @series)[1] - rightboundarypos))
Wjplot <- c(middlespace, boundaryheight, rightspace)
}
if(leftboundarypos != 0 && rightboundarypos == 0) {
leftspace <- rep(NA, 2*leftboundarypos - 1)
middlespace <- rep(NA, 2*(dim( x @series)[1] - leftboundarypos))
Wjplot <- c(leftspace, boundaryheight, middlespace)
}
wavecoefmatrix[,wavecoefmatrix.index] <- Wjplot
}
}
if(is.null(v.range) == FALSE) {
scalecoefmatrix <- array(NA, c(2*dim( x @series)[1], length(v.range)))
Vjplot <- rep(NA, 2*dim( x @series)[1])
scalecoefmatrix.index <- 0
for(j in v.range)
{
scalecoefmatrix.index <- scalecoefmatrix.index + 1
levelshift <- scalingshift.dwt( x @filter@L, j, dim( x @series)[1])%%(2^j)
rightgamma <- wt.filter.shift( x @filter, j, wavelet = FALSE)
leftgamma <- Lprimej[j] - rightgamma
Vj <- x @V[[j]][,1] - mean( x @V[[j]][,1])
if(positive) {
boundaryheight <- max(Vj)
}
else {
boundaryheight <- min(Vj)
}
if(leftgamma != 0) {
leftboundarypos <- leftgamma*(2^j) + .5*(2^j) - levelshift
}
else {
leftboundarypos <- 0
}
if(rightgamma != 0) {
rightboundarypos <- dim( x @series)[1] - rightgamma*(2^j) + .5*(2^j) - levelshift
}
else {
rightboundarypos <- 0
}
if(leftboundarypos != 0 && rightboundarypos != 0) {
leftspace <- rep(NA, 2*leftboundarypos - 1)
middlespace <- rep(NA, 2*(rightboundarypos - leftboundarypos) - 1)
rightspace <- rep(NA, 2*(dim( x @series)[1] - rightboundarypos))
Vjplot <- c(leftspace, boundaryheight, middlespace, boundaryheight, rightspace)
}
if(leftboundarypos == 0 && rightboundarypos != 0) {
middlespace <- rep(NA, 2*rightboundarypos - 1)
rightspace <- rep(NA, 2*(dim( x @series)[1] - rightboundarypos))
Vjplot <- c(middlespace, boundaryheight, rightspace)
}
if(leftboundarypos != 0 && rightboundarypos == 0) {
leftspace <- rep(NA, 2*leftboundarypos - 1)
rightspace <- rep(NA, 2*(dim( x @series)[1] - leftboundarypos))
Vjplot <- c(leftspace, boundaryheight, rightspace)
}
scalecoefmatrix[,scalecoefmatrix.index] <- Vjplot
}
}
if(is.null(w.range) == FALSE && is.null(v.range) == FALSE) {
if( x @class.X == "ts" || x @class.X == "mts") {
rownames(wavecoefmatrix) <- seq( x @attr.X$tsp[1]-.5, x @attr.X$tsp[2], by = .5)
rownames(scalecoefmatrix) <- seq( x @attr.X$tsp[1]-.5, x @attr.X$tsp[2], by = .5)
}
else {
rownames(wavecoefmatrix) <- seq(.5, dim( x @series)[1], by = .5)
rownames(scalecoefmatrix) <- seq(.5, dim( x @series)[1], by = .5)
}
results <- cbind(wavecoefmatrix, scalecoefmatrix)
}
if(!is.null(w.range) && is.null(v.range)) {
if( x @class.X == "ts" || x @class.X == "mts") {
rownames(wavecoefmatrix) <- seq( x @attr.X$tsp[1]-.5, x @attr.X$tsp[2], by = .5)
}
else {
rownames(wavecoefmatrix) <- seq(.5, dim( x @series)[1], by = .5)
}
results <- wavecoefmatrix
}
if(is.null(w.range) && !is.null(v.range)) {
if( x @class.X == "ts" || x @class.X == "mts") {
rownames(scalecoefmatrix) <- seq( x @attr.X$tsp[1]-.5, x @attr.X$tsp[2], by = .5)
}
else {
rownames(scalecoefmatrix) <- seq(.5, dim( x @series)[1], by = .5)
}
results <- scalecoefmatrix
}
results
}
as.matrix.dwt <- function ( x , w.range, v.range)
{
if( x @aligned) {
x <- align( x , inverse = TRUE)
}
if(is.null(w.range) == FALSE) {
wavecoefmatrix <- array(NA, c(dim( x @series)[1], length(w.range)))
Wjplot <- rep(NA, dim( x @series)[1])
wavecoefmatrix.index <- 0
for (j in w.range) {
Wjplot <- rep(NA, dim( x @series)[1])
wavecoefmatrix.index <- wavecoefmatrix.index + 1
Wj <- x @W[[j]][,1]
Wjplot[(2^j)*(1:length(Wj))] <- Wj
Wjplot <- levelshift.dwt(Wjplot, waveletshift.dwt( x @filter@L, j, dim( x @series)[1]))
wavecoefmatrix[,wavecoefmatrix.index] <- Wjplot
}
}
if(is.null(v.range) == FALSE) {
scalecoefmatrix <- array(NA, c(dim( x @series)[1], length(v.range)))
Vjplot <- rep(NA, dim( x @series)[1])
scalecoefmatrix.index <- 0
for(k in v.range) {
scalecoefmatrix.index <- scalecoefmatrix.index + 1
Vj <- x @V[[k]][,1] - mean( x @V[[k]][,1])
Vjplot[(2^k)*(1:length(Vj))] <- Vj
Vjplot <- levelshift.dwt(Vjplot, scalingshift.dwt( x @filter@L, k, dim( x @series)[1]))
scalecoefmatrix[,scalecoefmatrix.index] <- Vjplot
}
}
if(is.null(w.range) == FALSE && is.null(v.range) == FALSE) {
if( x @class.X == "ts" || x @class.X == "mts") {
rownames(wavecoefmatrix) <- x @attr.X$tsp[1]: x @attr.X$tsp[2]
rownames(scalecoefmatrix) <- x @attr.X$tsp[1]: x @attr.X$tsp[2]
}
else {
rownames(wavecoefmatrix) <- 1:dim( x @series)[1]
rownames(scalecoefmatrix) <- 1:dim( x @series)[1]
}
results <- cbind(wavecoefmatrix, scalecoefmatrix)
}
if(is.null(w.range) == FALSE && is.null(v.range)) {
if( x @class.X == "ts" || x @class.X == "mts") {
rownames(wavecoefmatrix) <- x @attr.X$tsp[1]: x @attr.X$tsp[2]
}
else {
rownames(wavecoefmatrix) <- 1:dim( x @series)[1]
}
results <- wavecoefmatrix
}
if(is.null(w.range) && is.null(v.range) == FALSE) {
if( x @class.X == "ts" || x @class.X == "mts") {
rownames(scalecoefmatrix) <- x @attr.X$tsp[1]: x @attr.X$tsp[2]
}
else {
rownames(scalecoefmatrix) <- 1:dim( x @series)[1]
}
results <- scalecoefmatrix
}
results
}
labels.dwt <- function (w.range = NULL, v.range = NULL, gammah = NULL, gammag = NULL)
{
verticallabel <- list()
if(is.null(w.range) == FALSE) {
for (j in 1:length(w.range)) {
label <- substitute(paste(T^-gamma,W[level]), list(gamma = gammah[j], level = w.range[j]))
verticallabel <- c(verticallabel, label)
}
}
if(is.null(v.range) == FALSE) {
for (i in 1:length(v.range)) {
label <- substitute(paste(T^-gamma,V[level]), list(gamma = gammag[i], level = v.range[i]))
verticallabel <- c(verticallabel, label)
}
}
results <- verticallabel
results
}
levelshift.dwt <- function (level, shift)
{
if(shift != 0) {
level <- c(level[(shift+1):length(level)], level[1:shift])
}
level
}
if (type == "stack") {
if(class( x ) != "dwt") {
stop("Invalid argument: 'dwt' object must be of class dwt.")
}
if(is.null(levels)) {
w.range <- 1: x @level
v.range <- max(w.range)
}
if(class(levels) == "numeric") {
if(length(levels) == 1) {
w.range <- 1:levels
v.range <- max(w.range)
}
else {
w.range <- levels
v.range <- max(w.range)
}
}
if(class(levels) == "list") {
if(length(levels) < 1) {
w.range <- 1: x @level
v.range <- max(w.range)
}
if(length(levels) == 1) {
w.range <- levels[[1]]
v.range <- max(w.range)
}
else {
w.range <- levels[[1]]
v.range <- levels[[2]]
}
}
if(class(levels) != "list" && class(levels) != "vector" && class(levels) != "numeric" && is.null(levels) == FALSE) {
stop("Invalid argument: Levels must be numeric, vector, or list.")
}
if(plot.W == FALSE) {
w.range <- NULL
}
if(plot.V == FALSE) {
v.range <- NULL
}
if(plot.W == FALSE && plot.V == FALSE) {
stop("Invalid argument: At least one of plot.W or plot.V must be TRUE")
}
if(is.null(w.range) == FALSE) {
if(min(w.range) < 1 || x @level < max(w.range)) {
stop("Invalid argument: Elements of 'levels' must be compatible with the level of decomposition of the 'dwt' object.")
}
}
if(is.null(v.range) == FALSE) {
if(min(v.range) < 1 || x @level < max(v.range)) {
stop("Invalid argument: Elements of 'levels' must be compatible with the level of decomposition of the 'dwt' object.")
}
}
stackplot.dwt( x , w.range, v.range, col.plot, col.boundary, draw.boundary = draw.boundary, X.xtick.at = X.xtick.at, X.ytick.at = X.ytick.at, Stack.xtick.at = Stack.xtick.at, Stack.ytick.at = Stack.ytick.at, X.xlab = X.xlab, plot.X = plot.X)
}
else {
stop("Only the stackplot is currently implemented.")
}
} |
test_that("range is expanded", {
df <- rbind(
data_frame(x = "a", y = c(0, runif(10), 1)),
data_frame(x = "b", y = c(0, runif(10), 2))
)
p <- ggplot(df, aes(1, y)) +
geom_violin(trim = FALSE) +
facet_grid(x ~ ., scales = "free") +
coord_cartesian(expand = FALSE)
expand_a <- stats::bw.nrd0(df$y[df$x == "a"]) * 3
expand_b <- stats::bw.nrd0(df$y[df$x == "b"]) * 3
expect_equal(layer_scales(p, 1)$y$dimension(), c(0 - expand_a, 1 + expand_a))
expect_equal(layer_scales(p, 2)$y$dimension(), c(0 - expand_b, 2 + expand_b))
})
test_that("geom_violin works in both directions", {
p <- ggplot(mpg) + geom_violin(aes(drv, hwy))
x <- layer_data(p)
expect_false(x$flipped_aes[1])
p <- ggplot(mpg) + geom_violin(aes(hwy, drv))
y <- layer_data(p)
expect_true(y$flipped_aes[1])
x$flipped_aes <- NULL
y$flipped_aes <- NULL
expect_identical(x, flip_data(y, TRUE)[,names(x)])
})
test_that("create_quantile_segment_frame functions for 3 quantiles", {
density.data <- data_frame(y = (1:256)/256, density = 1/256)
qs <- c(0.25, 0.5, 0.75)
expect_equal(create_quantile_segment_frame(density.data, qs)$y,
rep(qs, each = 2))
})
test_that("quantiles do not fail on zero-range data", {
zero.range.data <- data_frame(y = rep(1,3))
p <- ggplot(zero.range.data) + geom_violin(aes(1, y), draw_quantiles = 0.5)
expect_equal(length(layer_grob(p)), 1)
})
test_that("geom_violin draws correctly", {
set.seed(111)
dat <- data_frame(x = rep(factor(LETTERS[1:3]), 30), y = rnorm(90))
dat <- dat[dat$x != "C" | c(T, F),]
expect_doppelganger("basic",
ggplot(dat, aes(x = x, y = y)) + geom_violin()
)
expect_doppelganger("scale area to sample size (C is smaller)",
ggplot(dat, aes(x = x, y = y)) + geom_violin(scale = "count"),
)
expect_doppelganger("narrower (width=.5)",
ggplot(dat, aes(x = x, y = y)) + geom_violin(width = .5)
)
expect_doppelganger("with tails and points",
ggplot(dat, aes(x = x, y = y)) + geom_violin(trim = FALSE) + geom_point(shape = 21)
)
expect_doppelganger("with smaller bandwidth and points",
ggplot(dat, aes(x = x, y = y)) + geom_violin(adjust = .3) + geom_point(shape = 21)
)
expect_doppelganger("dodging",
ggplot(dat, aes(x = "foo", y = y, fill = x)) + geom_violin()
)
expect_doppelganger("coord_polar",
ggplot(dat, aes(x = x, y = y)) + geom_violin() + coord_polar()
)
expect_doppelganger("coord_flip",
ggplot(dat, aes(x = x, y = y)) + geom_violin() + coord_flip()
)
expect_doppelganger("dodging and coord_flip",
ggplot(dat, aes(x = "foo", y = y, fill = x)) + geom_violin() + coord_flip()
)
expect_doppelganger("continuous x axis, many groups (center should be at 2.0)",
ggplot(dat, aes(x = as.numeric(x), y = y)) + geom_violin()
)
expect_doppelganger("continuous x axis, single group (center should be at 1.0)",
ggplot(dat, aes(x = as.numeric(1), y = y)) + geom_violin()
)
expect_doppelganger("quantiles",
ggplot(dat, aes(x=x, y=y)) + geom_violin(draw_quantiles=c(0.25,0.5,0.75))
)
dat2 <- data_frame(x = rep(factor(LETTERS[1:3]), 30), y = rnorm(90), g = rep(factor(letters[5:6]), 45))
expect_doppelganger("grouping on x and fill",
ggplot(dat2, aes(x = x, y = y, fill = g)) + geom_violin()
)
expect_doppelganger("grouping on x and fill, dodge width = 0.5",
ggplot(dat2, aes(x = x, y = y, fill = g)) +
geom_violin(position = position_dodge(width = .5))
)
}) |
include_2015 <- read.delim(file='include_2015.txt', comment.char=' |
runPower <- function(countsMatrix,
designMatrix,
depth = c(10, 100, 1000),
N = c(3, 6, 10, 20),
FDR = c(0.05, 0.1),
effectSize = c(1.2, 1.5, 2),
includePlots = FALSE) {
assertthat::assert_that(requireNamespace("RNASeqPower", quietly = TRUE),
msg = "RNASeqPower package is required to run power analysis on the given counts matrix and design matrix.")
assertthat::assert_that(requireNamespace("statmod", quietly = TRUE),
msg = "'statmod' package is required to run estimate dispersion calculations")
assertthat::assert_that(!missing(countsMatrix),
!is.null(countsMatrix),
class(countsMatrix)[[1]] %in% c("matrix","data.frame"),
msg = "countsMatrix must be specified and must be of class matrix or dataframe.")
assertthat::assert_that(!missing(designMatrix),
!is.null(designMatrix),
class(designMatrix)[[1]] %in% c("matrix","data.frame"),
msg = "designMatrix must be specified and must be of class matrix or dataframe.")
if (any(is.null(depth),
!is.numeric(depth),
length(depth) != 3)) {
warning("depth must be a vector of 3 integer values. Assigning default values 10, 100, 1000.")
depth <- c(10, 100, 1000)
}
if (any(is.null(N),
!is.numeric(N),
length(N) != 4)) {
warning("N must be a vector of 4 integer values. Assigning default values 3, 6, 10, 20.")
N <- c(3, 6, 10, 20)
}
if (any(is.null(FDR),
!is.numeric(FDR),
length(FDR) != 2)) {
warning("FDR must be a vector of 2 integer values. Assigning default values 0.05, 0.1.")
FDR <- c(0.05, 0.1)
}
if (any(is.null(effectSize),
!is.numeric(effectSize),
length(effectSize) != 3)) {
warning("effectiveSize must be a vector of 3 integer values. Assigning default values 1.2, 1.5, 2.")
effectSize <- c(1.2, 1.5, 2)
}
dgelist <- countsMatrix %>%
as.matrix() %>%
edgeR::DGEList() %>%
edgeR::calcNormFactors() %>%
edgeR::estimateDisp(design = designMatrix, robust = TRUE)
GeoMeanLibSize <- dgelist$samples$lib.size %>% log %>% mean %>% exp
depth_avelogcpm <- edgeR::aveLogCPM(depth, GeoMeanLibSize)
depthBCV <- sqrt(approx(dgelist$AveLogCPM, dgelist$trended.dispersion,
xout = depth_avelogcpm, rule = 2, ties = mean)$y)
n <- seq(min(N),max(N),1)
alpha <- seq(0.05, 0.9, 0.05)
pdat <- data.frame(depth = double(),
n = double(),
effect = double(),
alpha = double(),
powerVal = double(),
stringsAsFactors = FALSE)
for (D in depth) {
cv <- depthBCV[D == depth]
for (Nf in n) {
for (E in effectSize) {
for (A in alpha) {
do.call("require", list("RNASeqPower"))
P <- do.call("rnapower", list(depth = D, n = Nf, cv = cv, effect = E, alpha = A))
pdat <- rbind(pdat, c(depth = D, n = Nf, effect = E, alpha = A, powerVal = P))
}
}
}
}
colnames(pdat) <- c("depth", "n", "effect", "alpha", "power")
if (is.null(includePlots)) {
plot_type <- "none"
} else if (is.logical(includePlots) && length(includePlots) == 1) {
plot_type <- ifelse(includePlots, "canvasxpress", "none")
} else if (is.character(includePlots) && length(includePlots) == 1) {
if (tolower(includePlots) %in% c("canvasxpress", "ggplot")) {
plot_type <- tolower(includePlots)
} else {
warning("includePlots must be only one of the following values TRUE, FALSE, 'canvasXpress' or 'ggplot'. Assigning default value FALSE.")
plot_type <- "none"
}
} else {
warning("includePlots must be only one of the following values TRUE, FALSE, 'canvasXpress' or 'ggplot'. Assigning default value FALSE.")
plot_type <- "none"
}
rocdat <- dplyr::filter(pdat, n %in% N)
rocdat$depth <- as.factor(rocdat$depth)
ndat <- dplyr::filter(pdat, alpha %in% FDR)
ndat$depth <- as.factor(ndat$depth)
ndat$FDR <- ndat$alpha
result <- pdat
if (plot_type == "canvasxpress") {
if ("canvasXpress" %in% .packages(all.available = T)) {
do.call("require", list("canvasXpress"))
do.call("require", list("htmlwidgets"))
rocdat <- rocdat %>%
dplyr::arrange(alpha)
cx_data <- rocdat %>%
dplyr::select(alpha, power)
var_data <- rocdat %>%
dplyr::select(depth, n, effect)
var_data$n <- paste0("n:", var_data$n)
var_data$effect <- paste0("effect: ", var_data$effect)
events <- do.call("JS",
list("{'mousemove' : function(o, e, t) {
if (o != null && o != false) {
t.showInfoSpan(e, '<b>Alpha</b>: ' + o.y.data[0][0] +
'<br><b>Power</b>: ' + o.y.data[0][1]);
};}}"))
roc <- do.call("canvasXpress", list(data = cx_data,
varAnnot = var_data,
segregateVariablesBy = list("effect", "n"),
layoutType = "rows",
dataPointSize = 5,
spiderBy = "depth",
shapeBy = "depth",
colorBy = "depth",
title = "ROC curves",
xAxisTitle = "FDR",
yAxisTitle = "Power",
events = events,
afterRender = list(list("switchNumericToString",
list("depth",FALSE)))))
ndat <- ndat %>%
dplyr::arrange(n)
cx_data <- ndat %>%
dplyr::select(n, power)
var_data <- ndat %>%
dplyr::select(depth, FDR, effect)
var_data$FDR <- paste0("FDR:", var_data$FDR)
var_data$effect <- paste0("effect: ", var_data$effect)
events <- do.call("JS",
list("{'mousemove' : function(o, e, t) {
if (o != null && o != false) {
t.showInfoSpan(e, '<b>N</b>: ' + o.y.data[0][0] +
'<br><b>Power</b>: ' + o.y.data[0][1]);
};}}"))
NvP <- do.call("canvasXpress", list(data = cx_data,
varAnnot = var_data,
segregateVariablesBy = list("FDR", "effect"),
layoutType = "rows",
dataPointSize = 5,
spiderBy = "depth",
shapeBy = "depth",
colorBy = "depth",
title = "N vs Power",
xAxisTitle = "N",
yAxisTitle = "Power",
events = events,
afterRender = list(list("switchNumericToString",
list("depth",FALSE)))))
result <- list(PowerData = pdat, ROC = roc, NvP = NvP)
} else {
message('The canvasXpress package is not available, unable to create plots.')
}
} else if (plot_type == "ggplot") {
if ("ggplot2" %in% .packages(all.available = T)) {
do.call("require", list("ggplot2"))
ggplot = aes = geom_line = scale_x_continuous = scale_y_continuous = facet_grid <- NULL
label_both = ggtitle = xlab = ylab = expand_limits = theme = element_text = theme_gray <- NULL
effect <- NULL
roc <- ggplot(rocdat, aes(x = alpha, y = power, fill = depth, shape = depth, color = depth)) +
geom_line(size = 1) +
scale_x_continuous(breaks = seq(0, 1, 0.2)) +
scale_y_continuous(breaks = seq(0, 1, 0.2)) +
facet_grid(effect ~ n, labeller = label_both) +
ggtitle("ROC curves") +
xlab("\nFDR") +
ylab("Power") +
expand_limits(x = 0, y = 0) +
theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
theme_gray(18)
NvP <- ggplot(ndat, aes(x = n, y = power, fill = depth, shape = depth, color = depth)) +
geom_line(size = 1) +
scale_y_continuous(breaks = seq(0, 1, 0.2)) +
facet_grid(FDR ~ effect, labeller = label_both) +
ggtitle("N vs Power") +
xlab("\nN") +
ylab("Power") +
expand_limits(x = 0, y = 0) +
theme_gray()
result <- list(PowerData = pdat, ROC = roc, NvP = NvP)
} else {
message('The canvasXpress package is not available, unable to create plots.')
}
}
result
} |
mersenne <- function(p) {
stopifnot(is.numeric(p), length(p) == 1)
if (!isNatural(p) || !isPrime(p))
stop("Argument 'p' must be a prime number for 2^p-1 to be prime.")
if (p == 2)
return(TRUE)
if (!requireNamespace("gmp", quietly = TRUE)) {
stop("Package 'gmp' needed: Please install separately.", call. = FALSE)
}
z2 <- gmp::as.bigz(2)
z4 <- z2 * z2
zp <- gmp::as.bigz(p)
zm <- z2^zp - 1
S <- rep(z4, p - 1)
for (n in 1:(p-2))
S[n+1] <- gmp::mod.bigz(S[n]*S[n] - z2, zm)
if (S[p-1] == 0) tf <- TRUE
else tf <- FALSE
return(tf)
} |
buttons2 <-
function() {
if (KTSEnv$activMenu != "gapsetmenu") {
subMenu2But <- function(parent = NULL, text = "Load",
command = loadAllTypes) {
buttonSM2 <- tcltk::tkbutton(parent = parent, text = text, width = 5,
command = command,
background = "darkolivegreen3",
foreground = "white",
font = KTSEnv$KTSFonts$subBt)
tcltk::tkpack(buttonSM2, side = "left", expand = TRUE, fill = "both")
}
try(tcltk::tkdestroy(KTSEnv$row231), silent = TRUE)
try(tcltk::tkdestroy(KTSEnv$row232), silent = TRUE)
row231 <- tcltk::ttkframe(KTSEnv$rows2and3,
borderwidth = 0, relief = "raised")
subMenu2But(parent = row231, text = "Load", command = loadAllTypes)
subMenu2But(parent = row231, text = "Remove",
command = removeAllTypes)
subMenu2But(parent = row231, text = "Save", command = saveAllTypes)
subMenu2But(parent = row231, text = "Export", command = exportall)
subMenu2But(parent = row231, text = "Rename",
command = renameAllTypes)
subMenu2But(parent = row231, text = "Merge", command = mergeTsOrGap)
subMenu2But(parent = row231, text = "List",
command = refreshDataSetsList)
tcltk::tkpack(row231, anchor = "nw", fill = "both")
row232 <- tcltk::ttkframe(KTSEnv$rows2and3,
borderwidth = 0, relief = "raised")
subMenu2But(parent = row232, text = "Gap selection",
command = selectionGaps)
subMenu2But(parent = row232, text = "Artificial random gaps",
command = createRandGaps)
subMenu2But(parent = row232, text = "Artificial specific gaps",
command = createSpecGaps)
subMenu2But(parent = row232, text = "Apply gaps to series",
command = applyGap2TSer)
subMenu2But(parent = row232, text = "Upsample",
command = NAs4Resamp)
tcltk::tkpack(row232, anchor = "nw", fill = "both")
assign("row231", row231, envir = KTSEnv)
assign("row232", row232, envir = KTSEnv)
assign("activMenu", "gapsetmenu", envir = KTSEnv)
loadAllTypes()
}
} |
plot.gradientDist <- function(x, orderBy,
flipAxes = FALSE,
main = NULL,
xlab = NULL,
ylab = "Distance along gradient",
xlim = NULL, ylim = NULL, ...) {
X <- as.numeric(x)
if(missing(orderBy)) {
orderBy <- seq_along(X)
if(is.null(xlab))
xlab <- "Sample"
} else {
if(is.null(xlab))
xlab <- deparse(substitute(orderBy))
}
xlim <- if(is.null(xlim))
range(orderBy[is.finite(orderBy)])
else xlim
ylim <- if(is.null(ylim))
range(X[is.finite(X)])
else ylim
if(flipAxes)
plot.default(x = X, y = orderBy, xlab = ylab, ylab = xlab,
main = main, ylim = xlim, xlim = ylim, ...)
else
plot.default(x = orderBy, y = X, xlab = xlab, ylab = ylab,
main = main, ylim = ylim, xlim = xlim, ...)
invisible(x)
}
lines.gradientDist <- function(x, orderBy, flipAxes = FALSE,
type = "l", ...) {
X <- as.numeric(x)
if(missing(orderBy)) {
orderBy <- seq_along(X)
}
if(flipAxes)
lines.default(x = X, y = orderBy, type = type, ...)
else
lines.default(x = orderBy, y = X, type = type, ...)
}
points.gradientDist <- function(x, orderBy, flipAxes = FALSE, type = "p",
...) {
X <- as.numeric(x)
if(missing(orderBy)) {
orderBy <- seq_along(X)
}
if(flipAxes)
points.default(x = X, y = orderBy, type = type, ...)
else
points.default(x = orderBy, y = X, type = type, ...)
} |
treedisc.ada<-function(lst, pcf, ngrid=NULL, r=NULL, type=NULL, lowest="dens")
{
if (lowest=="dens") lowest<-0 else lowest<-min(lst$level)
if (is.null(type)){
if (is.null(lst$refe)) type<-"lst"
else type<-"shape"
}
if (is.null(r)){
if (type=="shape"){
stepsi<-lst$maxdis/ngrid
r<-seq(0,lst$maxdis,stepsi)
}
else{
stepsi<-lst$maxdis/(ngrid+1)
r<-seq(lowest+stepsi,lst$maxdis-stepsi,stepsi)
}
}
mt<-multitree(lst$parent)
child<-mt$child
sibling<-mt$sibling
d<-dim(lst$center)[1]
itemnum<-length(lst$parent)
parent<-matrix(NA,itemnum,1)
pino<-matrix(0,itemnum,1)
pinoparent<-matrix(0,itemnum,1)
pinorad<-matrix(0,itemnum,1)
pino[1]<-1
pinoparent[1]<-0
pinorad[1]<-1
pinin<-1
curradind<-1
while (pinin>0){
cur<-pino[pinin]
curpar<-pinoparent[pinin]
curradind<-pinorad[pinin]
pinin<-pinin-1
if (sibling[cur]>0){
pinin<-pinin+1
pino[pinin]<-sibling[cur]
pinoparent[pinin]<-curpar
pinorad[pinin]<-curradind
}
note<-lst$infopointer[cur]
if (type=="lst")
etai<-pcf$value[note]
else{
recci<-matrix(0,2*d,1)
downi<-pcf$down[lst$infopointer[note],]
highi<-pcf$high[lst$infopointer[note],]
for (jj in 1:d){
recci[2*jj-1]<-pcf$grid[downi[jj],jj]
recci[2*jj]<-pcf$grid[highi[jj],jj]
}
etai<-sqrt(etaisrec(lst$refe,recci))
}
if (curradind<=length(r)) currad<-r[curradind] else currad<-1000000
if (etai>currad){
parent[cur]<-curpar
curpar<-cur
curradind<-curradind+1
}
while (child[cur]>0){
cur<-child[cur]
if (sibling[cur]>0){
pinin<-pinin+1
pino[pinin]<-sibling[cur]
pinoparent[pinin]<-curpar
pinorad[pinin]<-curradind
}
note<-lst$infopointer[cur]
if (type=="lst")
etai<-pcf$value[note]
else{
recci<-matrix(0,2*d,1)
downi<-pcf$down[lst$infopointer[note],]
highi<-pcf$high[lst$infopointer[note],]
for (jj in 1:d){
recci[2*jj-1]<-pcf$grid[downi[jj],jj]
recci[2*jj]<-pcf$grid[highi[jj],jj]
}
etai<-sqrt(etaisrec(lst$refe,recci))
}
if (curradind<=length(r)) currad<-r[curradind] else currad<-1000000
if (etai>currad){
parent[cur]<-curpar
curpar<-cur
curradind<-curradind+1
}
}
}
newparent<-matrix(0,itemnum,1)
newcenter<-matrix(0,d,itemnum)
newvolume<-matrix(0,itemnum,1)
newlevel<-matrix(0,itemnum,1)
newpointer<-matrix(0,itemnum,1)
i<-1
newlkm<-0
while (i<=itemnum){
if (!is.na(parent[i])){
newlkm<-newlkm+1
newpointer[i]<-newlkm
if (parent[i]==0) newparent[newlkm]<-0
else newparent[newlkm]<-newpointer[parent[i]]
newcenter[,newlkm]<-lst$center[,i]
newlevel[newlkm]<-lst$level[i]
newvolume[newlkm]<-lst$volume[i]
}
i<-i+1
}
newparent<-newparent[1:newlkm]
if (newlkm<=1) newcenter<-matrix(newcenter[,1],d,1)
else newcenter<-newcenter[,1:newlkm]
newvolume<-newvolume[1:newlkm]
newlevel<-newlevel[1:newlkm]
newpointer<-newpointer[1:newlkm]
return(list(parent=newparent,level=newlevel,volume=newvolume,center=newcenter,
refe=lst$refe,bary=lst$bary,root=1,infopointer=newpointer))
} |
data("rent", package = "catdata")
rent$area <- as.factor(rent$area)
rent$year <- as.factor(floor(rent$year / 10) * 10)
rent$rooms <- as.factor(rent$rooms)
rent$quality <- as.factor(rent$good + 2 * rent$best)
levels(rent$quality) <- c("fair", "good", "excellent")
sizeClasses <- c(0, seq(30, 140, 10))
rent$size <- as.factor(sizeClasses[findInterval(rent$size, sizeClasses)])
rent$warm <- factor(rent$warm, labels = c("yes", "no"))
rent$central <- factor(rent$central, labels = c("yes", "no"))
rent$tiles <- factor(rent$tiles, labels = c("yes", "no"))
rent$bathextra <- factor(rent$bathextra, labels = c("no", "yes"))
rent$kitchen <- factor(rent$kitchen, labels = c("no", "yes"))
formu <- rentm ~ p(area, pen = "gflasso") +
p(year, pen = "flasso", refcat = 2000) + p(rooms, pen = "flasso") +
p(quality, pen = "flasso") + p(size, pen = "flasso") +
p(warm, pen = "grouplasso", group = 1) + p(central, pen = "grouplasso", group = 1) +
p(tiles, pen = "none") + bathextra +
p(kitchen, pen = "lasso")
munich.fit <- glmsmurf(formula = formu, family = gaussian(), data = rent,
pen.weights = "glm.stand", lambda = 0.1)
summary(munich.fit) |
get_lto_file_info_tbl <- function() {
lto_file_info_tbl <- tibble(
type = c("collection", "themeset"),
extension = c(".st.txt", ".thset.txt"),
header_fragment = c("Collection:", "Themeset:")
)
lto_file_info_tbl
}
lto_file_to_lines <- function(file, type) {
if (is_missing(file)) {
message <- get_missing_arg_msg(variable_name = "file")
abort(message, class = "missing_argument")
}
if (length(file) != 1 || !is.character(file)) {
message <- get_single_string_msg(string = file, variable_name = type)
abort(message, class = "function_argument_type_check_fail")
}
if (isTRUE(!(type %in% get_lto_file_info_tbl()$type))) {
abort(
str_glue(
"The `type` specified LTO file type is invalid.\n",
"{col_red(symbol$cross)} {type} is an invalid LTO file type.\n",
"{col_yellow(symbol$info)} Valid LTO file types are:\n",
"{str_c(get_lto_file_info_tbl()$type, collapse = \"\n\")}"
)
)
}
if (isTRUE(!is_url(file) && !grepl("\n", file))) {
if (is_absolute_path(file)) {
file_name <- basename(file)
file_path <- file
} else {
file_name <- file
file_path <- file.path(getwd(), file)
}
if (all(str_ends(file, get_lto_file_info_tbl()$extension, negate = TRUE))) {
if (isTRUE(type == "collection")) {
extension <- get_lto_file_info_tbl() %>%
filter(.data$type == "collection") %>%
pull(.data$extension)
} else if (isTRUE(type == "themeset")) {
extension <- get_lto_file_info_tbl() %>%
filter(.data$type == "themeset") %>%
pull(.data$extension)
}
cli_text("file_name: {.val {file}}")
cli_text("extension: {.val {extension}}")
message <- get_invalid_file_extension_msg(file_name = file, valid_file_extension = extension)
abort(message, class = "invalid_file_extension")
}
if (!file.exists(file)) {
message <- get_file_not_found_msg(file)
abort(message, class = "file_not_found")
}
if (is_file_empty(file)) {
message <- get_empty_file_msg(file)
abort(message, class = "file_empty")
}
}
lines <- readr::read_lines(file)
lines
}
lto_file_to_tbl <- function(lines, verbose = TRUE) {
if (is_missing(lines)) {
message <- get_missing_arg_msg(variable_name = "lines")
abort(message, class = "missing_argument")
}
info1 <- "{col_yellow(symbol$info)} Run `cat(readr::read_file(system.file(\"extdata\", \"rolling-stone-best-ttz1959-episodes.st.txt\", package = \"stoRy\")))` to view an example collection file.\n"
info2 <- "{col_yellow(symbol$info)} Run `cat(readr::read_file(system.file(\"extdata\", \"immortality.thset.txt\", package = \"stoRy\")))` to view an example themeset file."
lto_file_types_tbl <- get_lto_file_info_tbl()
field_def_tbl <- get_field_def_tbl()
parsed_fields_tbl <- tibble(
name = character(0),
contents = list(tibble(contents = character(0))))
if (last(lines) != "") lines <- append(lines, "")
if (!str_starts(lines[2], pattern = "===")) {
abort(
str_glue(
"`file` contains an invalid header.\n",
"{col_red(symbol$cross)} The second line must start with \"===\".\n",
info1,
info2
),
class = "invalid_lto_file_format"
)
}
header <- lines[1]
if (!any(str_starts(header, pattern = lto_file_types_tbl$header_fragment))) {
abort(
str_glue(
"`file` contains an invalid header.\n",
"{col_red(symbol$cross)} The first line must start with one of the prefixes\n",
"{str_c(lto_file_types_tbl$header_fragment, collapse = \"\n)}\"\n",
info1,
info2
),
class = "invalid_lto_file_format"
)
}
if (str_detect(header, ",")) {
abort(
str_glue(
"`file` contains an invalid header.\n",
"{col_red(symbol$cross)} The first line must not contain any \",\" characters.\n",
info1,
info2
),
class = "invalid_lto_file_format"
)
}
parsed_fields_tbl <- parsed_fields_tbl %>%
add_row(tibble(name = "header", contents = list(tibble(contents = header))))
field_line_numbers <- str_which(lines, "^::")
field_content_start_line_numbers <- field_line_numbers + 1
field_content_end_line_numbers <- append(field_line_numbers[-1] - 1, length(lines))
number_of_fields <- length(field_line_numbers)
for (field_number in seq_len(number_of_fields)) {
field_literal <- lines[field_line_numbers[field_number]]
if (!isTRUE(field_literal %in% field_def_tbl$literal)) {
if (verbose) cli_alert_warning("Discarding unrecognized field: \"{field_literal}\"")
} else if (isTRUE(field_def_tbl %>% filter(.data$literal == field_literal) %>% pull(.data$status) == "unsupported")) {
if (verbose) cli_alert_warning("Discarding unsupported field: \"{field_literal}\"")
} else {
name <- field_def_tbl %>%
filter(.data$literal == field_literal) %>%
pull(.data$name)
text <- str_c(lines[field_content_start_line_numbers[field_number] : field_content_end_line_numbers[field_number]], collapse = "\n")
format <- field_def_tbl %>%
filter(.data$literal == field_literal) %>%
pull(.data$format)
contents <- parse_field_contents(text, format, field_literal)
parsed_fields_tbl <- parsed_fields_tbl %>%
add_row(tibble(name = name, contents = list(contents)))
}
}
header <- parsed_fields_tbl %>%
filter(.data$name == "header") %>%
pull(.data$contents) %>%
unlist(use.names = FALSE)
lto_file_type <- get_lto_file_type(string = header)
expected_field_name <- "description"
if (!any(str_detect(parsed_fields_tbl$name, pattern = expected_field_name))) {
abort(
str_glue(
"`file` is missing a required field.\n",
"{col_red(symbol$cross)} The required field \":: Description\" is missing.\n",
info1,
info2
),
class = "invalid_lto_file_format"
)
}
if (isTRUE(lto_file_type == "themeset")) {
expected_field_name <- "component_theme_names"
if (!any(str_detect(parsed_fields_tbl$name, pattern = expected_field_name))) {
abort(
str_glue(
"`file` is missing a required field.\n",
"{col_red(symbol$cross)} The required field \":: Component Themes\" is missing.\n",
info2
),
class = "invalid_lto_file_format"
)
}
valid_theme_names <- get_themes_tbl() %>% pull(.data$theme_name)
candidate_component_theme_names <- parsed_fields_tbl %>%
filter(.data$name == expected_field_name) %>%
pull(.data$contents) %>%
unlist(use.names = FALSE)
invalid_component_theme_names <- setdiff(candidate_component_theme_names, valid_theme_names)
if (!identical(invalid_component_theme_names, character(0))) {
if (verbose) cli_alert_warning("Discarding invalid themes:\n", "{str_c(invalid_component_theme_names, collapse = \"\n\")}")
component_theme_names <- intersect(candidate_component_theme_names, valid_theme_names)
parsed_fields_tbl$contents[[which(parsed_fields_tbl$name == expected_field_name)]] <- tibble(contents = component_theme_names)
}
} else if (isTRUE(lto_file_type == "collection")) {
expected_field_name <- "title"
if (!any(str_detect(parsed_fields_tbl$name, pattern = expected_field_name))) {
abort(
str_glue(
"`file` is missing a required field.\n",
"{col_red(symbol$cross)} The required field \":: Title\" is missing.\n",
info1
),
class = "invalid_lto_file_format"
)
}
expected_field_name <- "date"
if (!any(str_detect(parsed_fields_tbl$name, pattern = expected_field_name))) {
abort(
str_glue(
"`file` is missing a required field.\n",
"{col_red(symbol$cross)} The required field \":: Date\" is missing.\n",
info1
),
class = "invalid_lto_file_format"
)
}
expected_field_name <- "collection_ids"
if (!any(str_detect(parsed_fields_tbl$name, pattern = expected_field_name))) {
abort(
str_glue(
"`file` is missing a required field.\n",
"{col_red(symbol$cross)} The required field \":: Collections\" is missing.\n",
info1
),
class = "invalid_lto_file_format"
)
}
field_name <- "header"
reserved_collection_ids <- get_collections_tbl() %>%
pull(.data$collection_id)
candidate_collection_id <- parsed_fields_tbl %>%
filter(.data$name == field_name) %>%
pull(.data$contents) %>%
unlist(use.names = FALSE)
if (candidate_collection_id %in% reserved_collection_ids) {
abort(
str_glue(
"`file` contains an invalid collection.\n",
"{col_red(symbol$cross)} The collection ID \"{collection_id}\" is reserved.\n",
info1
),
class = "invalid_lto_file_format"
)
}
expected_field_name <- "component_story_ids"
if (!any(str_detect(parsed_fields_tbl$name, pattern = expected_field_name))) {
abort(
str_glue(
"`file` is missing a required field.\n",
"{col_red(symbol$cross)} The required field \":: Component Stories\" is missing.\n",
info1
),
class = "invalid_lto_file_format"
)
}
valid_story_ids <- get_stories_tbl() %>% pull(.data$story_id)
candidate_component_story_ids <- parsed_fields_tbl %>%
filter(.data$name == expected_field_name) %>%
pull(.data$contents) %>%
unlist(use.names = FALSE)
invalid_story_ids <- setdiff(candidate_component_story_ids, valid_story_ids)
if (!identical(invalid_story_ids, character(0))) {
if (verbose) cli_alert_warning("Discarding invalid story IDs:\n", "{str_c(invalid_story_ids, collapse = \"\n\")}")
component_story_ids <- intersect(candidate_component_story_ids, valid_story_ids)
parsed_fields_tbl$contents[[which(parsed_fields_tbl$name == expected_field_name)]] <- tibble(contents = component_story_ids)
}
}
field_names <- parsed_fields_tbl$name
description <- parsed_fields_tbl %>%
filter(.data$name == "description") %>%
pull(.data$contents) %>%
unlist(use.names = FALSE)
if (isTRUE(lto_file_type == "themeset")) {
themeset_name <- parsed_fields_tbl %>%
filter(.data$name == "name") %>%
pull(.data$contents) %>%
unlist(use.names = FALSE)
component_theme_names <- parsed_fields_tbl %>%
filter(.data$name == "component_theme_names") %>%
pull(.data$contents) %>%
unlist(use.names = FALSE)
lto_tbl <- tibble(
themeset_index = NA,
themeset_id = header,
themeset_name = themeset_name,
description = description,
component_theme_names = list(component_theme_names)
)
} else if (isTRUE(lto_file_type == "collection")) {
title <- parsed_fields_tbl %>%
filter(.data$name == "title") %>%
pull(.data$contents) %>%
unlist(use.names = FALSE)
date <- parsed_fields_tbl %>%
filter(.data$name == "date") %>%
pull(.data$contents) %>%
unlist(use.names = FALSE)
component_story_ids <- parsed_fields_tbl %>%
filter(.data$name == "component_story_ids") %>%
pull(.data$contents) %>%
unlist(use.names = FALSE)
if (isTRUE("references" %in% field_names)) {
references <- parsed_fields_tbl %>%
filter(.data$name == "references") %>%
pull(.data$contents) %>%
unlist(use.names = FALSE)
} else {
references <- tibble(references = character(0))
}
lto_tbl <- tibble(
collection_index = NA,
collection_id = header,
title = title,
description = description,
date = date,
component_story_ids = list(component_story_ids),
references = list(references),
themes = list(tibble(data.frame(theme_name = character(0), level = character(0), motivation = character(0)))),
source = NA
)
} else {
lto_tbl <- tibble()
}
lto_tbl
}
parse_field_contents <- function(text, format, field_literal) {
if (is_missing(text)) {
message <- get_missing_arg_msg(variable_name = "text")
abort(message, class = "missing_argument")
}
if (is_missing(format)) {
message <- get_missing_arg_msg(variable_name = "format")
abort(message, class = "missing_argument")
}
if (is_missing(field_literal)) {
message <- get_missing_arg_msg(variable_name = "field_literal")
abort(message, class = "missing_argument")
}
if (format == "text blocks") {
return(tibble(contents = remove_wordwrap(text)))
} else if (format == "multiline") {
return(tibble(contents = text %>% str_trim() %>% str_split(pattern = "\n") %>% unlist()))
} else if (format == "single term") {
text <- str_trim(text)
return(tibble(contents = text))
}
abort(
str_glue(
"`format` must be a recognized string or NA.\n",
"{col_red(symbol$cross)} You supplied the unrecognized value {format}.\n",
"{col_yellow(symbol$info)} Run `unique(get_field_def_tbl() %>% dplyr::select(format))` to view recognized values."
)
)
}
get_lto_file_type <- function(string) {
if (is_missing(string)) {
message <- get_missing_arg_msg(variable_name = "string")
abort(message, class = "missing_argument")
}
lto_file_types_tbl <- get_lto_file_info_tbl()
if (!any(str_starts(string, pattern = lto_file_types_tbl$header_fragment))) {
abort(
str_glue(
"`string` corresponds to an invalid file type.\n",
"{symbol$cross} The file's first line must start with one of the prefixes\n",
"{str_c(lto_file_types_tbl$header_fragment, collapse = \"\n)}\""
),
class = "invalid_file_type"
)
}
lto_file_types_tbl$type[str_which(string, pattern = lto_file_types_tbl$header_fragment)]
}
get_field_def_tbl <- function() {
field_names <- c(
"choice_themes",
"collection_ids",
"component_story_ids",
"component_theme_names",
"date",
"description",
"major_themes",
"minor_themes",
"notes",
"references",
"title"
)
field_literals <- c(
":: Choice Themes",
":: Collections",
":: Component Stories",
":: Component Themes",
":: Date",
":: Description",
":: Major Themes",
":: Minor Themes",
":: Notes",
":: References",
":: Title"
)
field_formats <- c(
NA,
"multiline",
"multiline",
"multiline",
"single term",
"text blocks",
NA,
NA,
"text blocks",
"multiline",
"single term"
)
field_statuses <- c(
"unsupported",
"supported",
"supported",
"supported",
"supported",
"supported",
"unsupported",
"unsupported",
"supported",
"supported",
"supported"
)
field_def_tbl <- tibble(
name = field_names,
literal = field_literals,
format = field_formats,
status = field_statuses
)
field_def_tbl
} |
ts_wfs_nnetar_reg <- function(.model_type = "nnetar",
.recipe_list,
.non_seasonal_ar = 0,
.seasonal_ar = 0,
.hidden_units = 5,
.num_networks = 10,
.penalty = .1,
.epochs = 10
){
model_type = .model_type
recipe_list = .recipe_list
non_seasonal_ar = .non_seasonal_ar
seasonal_ar = .seasonal_ar
hidden_units = .hidden_units
num_networks = .num_networks
penalty = .penalty
epochs = .epochs
if (!is.character(model_type)) {
stop(call. = FALSE, "(.model_type) must be a character like 'nnetar'")
}
if (!model_type %in% c("nnetar")){
stop(call. = FALSE, "(.model_type) must be one of the following, 'nnetar'")
}
if (!is.list(recipe_list)){
stop(call. = FALSE, "(.recipe_list) must be a list of recipe objects")
}
model_spec_nnetar <- modeltime::nnetar_reg(
seasonal_period = "auto"
, non_seasonal_ar = non_seasonal_ar
, seasonal_ar = seasonal_ar
, hidden_units = hidden_units
, num_networks = num_networks
, penalty = penalty
, epochs = epochs
) %>%
parsnip::set_engine("nnetar")
final_model_list <- list(
model_spec_nnetar
)
wf_sets <- workflowsets::workflow_set(
preproc = recipe_list,
models = final_model_list,
cross = TRUE
)
return(wf_sets)
} |
is.error <- function(Zt,
Zp)
{
if (length(Zt) == 0) {
error <- array(data = 0, dim = length(Zp))
}
else {
error <- array(data = 1, dim = length(Zp))
zt <- as.numeric(names(table(Zt))); zp <- unique(Zp)
iset <- 1:length(zt)
while (1) {
imax <- 0; jmax <- 0; which.not.error <- NULL; Pmax <- 0.0
for (i in iset) {
Zti <- Zt[which(Zt == zt[i])]
Zpi <- Zp[which(Zt == zt[i])]
j <- as.numeric(names(sort(table(Zpi), decreasing = TRUE)))
k <- match(j, zp); k <- k[!is.na(k)]
if (length(k) > 0) {
j <- zp[k[1]]; which.not.error <- which(Zt == zt[i] & Zp == j)
P.n <- length(which.not.error); P.d <- length(Zti)
if (P.n == P.d) {
P <- P.d
}
else {
P <- P.n / P.d
}
if (P > Pmax) {
imax <- i; jmax <- j; which.not.errormax <- which.not.error; Pmax <- P
}
}
}
if (imax == 0) {
break
}
else {
error[which.not.errormax] <- 0
zp <- zp[which(zp != jmax)]; iset <- iset[which(iset != imax)]
}
}
}
error
} |
"are.parrevgum.valid" <-
function(para,nowarn=FALSE) {
if(! is.revgum(para)) return(FALSE)
if(any(is.na(para$para))) return(FALSE)
A <- para$para[2]
op <- options()
GO <- TRUE
if(nowarn == TRUE) options(warn=-1)
options(op)
if(GO) return(TRUE)
return(FALSE)
} |
find_esgrid = function(my_data, my_cov, treatment, outcome, my_estimand){
obs_cors = rep(NA, ncol(data.frame(my_data[,my_cov])))
for(i in 1:length(obs_cors)){
if(is.factor(my_data[,my_cov[i]])){
obs_cors[i] = abs(stats::cor(as.numeric(my_data[,my_cov[i]]),
my_data[,outcome],"pairwise.complete.obs"))
} else {
obs_cors[i] = abs(stats::cor(as.numeric(as.character(my_data[,my_cov[i]])),
my_data[,outcome],"pairwise.complete.obs"))
}
}
mean_noNA = function(x){return(mean(x, na.rm=T))}
sd_noNA = function(x){return(stats::sd(x, na.rm=T))}
mean_sd_bygroup = my_data %>%
dplyr::select(.data[[treatment]], my_cov) %>%
dplyr::mutate_if(is.factor, as.numeric) %>%
dplyr::group_by(.data[[treatment]]) %>%
dplyr::summarize_all(list(mean_noNA, sd_noNA)) %>%
data.frame()
es_cov = rep(NA, length(my_cov))
if(my_estimand == "ATE"){
if(length(my_cov) > 1){
for(i in 1:length(my_cov)){
diff_means = diff(mean_sd_bygroup[,colnames(mean_sd_bygroup)[grep(paste0("^", my_cov[i], "_fn1$"), colnames(mean_sd_bygroup))]])
denom_ATE = sqrt(sum(mean_sd_bygroup[,colnames(mean_sd_bygroup)[grep(paste0("^", my_cov[i], "_fn2$"), colnames(mean_sd_bygroup))]]^2)/2)
es_cov[i] = abs(diff_means/denom_ATE)
}
} else{
diff_means = diff(mean_sd_bygroup$fn1)
denom_ATE = sqrt(sum(mean_sd_bygroup$fn2^2)/2)
es_cov[i] = abs(diff_means/denom_ATE)
}
} else if(my_estimand == "ATT"){
if(length(my_cov) > 1){
for(i in 1:length(my_cov)){
diff_means = diff(mean_sd_bygroup[,colnames(mean_sd_bygroup)[grep(paste0("^", my_cov[i], "_fn1$"), colnames(mean_sd_bygroup))]])
treat_only = mean_sd_bygroup %>% dplyr::filter(.data[[treatment]] == 1) %>% data.frame()
denom_ATT = treat_only[,colnames(treat_only)[grep(paste0("^", my_cov[i], "_fn2$"),
colnames(treat_only))]]
es_cov[i] = abs(diff_means/denom_ATT)
}
} else{
diff_means = diff(mean_sd_bygroup$fn1)
denom_ATT = mean_sd_bygroup$fn2[mean_sd_bygroup[,treatment]==1]
es_cov[i] = abs(diff_means/denom_ATT)
}
}
obs_cors = cbind(obs_cors, es_cov)
obs_cors = obs_cors %>%
data.frame() %>%
dplyr::mutate(cov=my_cov)
colnames(obs_cors) = c("Cor_Outcome", "ES", "cov")
return(obs_cors)
} |
chainSummary = function(chain, HDPIntervalValue){
nChains = length(chain)
if (class(chain) == "list"){
if (nChains > 1){
stackedModelChain = coda::mcmc(do.call("rbind", lapply(
X = chain,
FUN = function(x)
return(as.matrix(x))
)))
modelChain = coda::mcmc.list(lapply(X = chain, FUN = coda::mcmc))
} else {
stackedModelChain = chain
modelChain = coda::mcmc(modelChain)
stackedModelChain = coda::mcmc(modelChain)
}
}
chainSummary = summary(modelChain)
chainSummary = cbind(chainSummary$statistics, chainSummary$quantiles)
HPDIval = HDPIntervalValue
HDPI = coda::HPDinterval(stackedModelChain, prob = HPDIval)
colnames(HDPI) = c(paste0("lowerHDPI", HPDIval), paste0("upperHDPI95", HPDIval))
chainSummary = cbind(chainSummary, HDPI)
if (nChains > 1){
convergenceDiagnostics = coda::gelman.diag(modelChain, multivariate = FALSE)
colnames(convergenceDiagnostics$psrf) = c("PSRF", "PSRF Upper C.I.")
chainSummary = cbind(chainSummary, convergenceDiagnostics$psrf)
} else {
convergenceDiagnostics = coda::heidel.diag(modelChain)
temp = convergenceDiagnostics[, c(3,4)]
colnames(temp) = c("Heidel.Diag p-value", "Heidel.Diag Htest")
chainSummary = cbind(chainSummary, temp)
}
return(chainSummary)
} |
context('Testing \'console\'')
test_that('.onAttach() works', {
expect_true(outsider.base:::.onAttach())
})
test_that('char() works', {
expect_true(is.character(outsider.base:::char('char')))
})
test_that('stat() works', {
expect_true(is.character(outsider.base:::stat('stat')))
})
test_that('cat_line() works', {
expect_null(outsider.base:::cat_line('cat this'))
}) |
.doSortWrap <- local({
INCR_NA_1ST <- 2
INCR <- 1
DECR <- -1
DECR_NA_1ST <- -2
UNSORTED <- 0
UNKNOWN <- NA_integer_
.makeSortEnum <- function(decr, na.last) {
if(decr) {
if (is.na(na.last) || na.last) DECR
else DECR_NA_1ST
} else {
if (is.na(na.last) || na.last) INCR
else INCR_NA_1ST
}
}
function(vec, decr, nalast, noNA = NA) {
if (length(vec) > 0 && is.numeric(vec)) {
sorted <- .makeSortEnum(decr, nalast)
if (is.na(noNA)) {
if(is.na(nalast))
noNA <- TRUE
else if(nalast)
noNA <- !is.na(vec[length(vec)])
else
noNA <- !is.na(vec[1L])
}
.Internal(wrap_meta(vec, sorted, noNA))
}
else vec
}
})
.doWrap <- .doSortWrap
sort <- function(x, decreasing = FALSE, ...)
{
if(!is.logical(decreasing) || length(decreasing) != 1L)
stop("'decreasing' must be a length-1 logical vector.\nDid you intend to set 'partial'?")
UseMethod("sort")
}
sort.default <- function(x, decreasing = FALSE, na.last = NA, ...)
{
if(is.object(x))
x[order(x, na.last = na.last, decreasing = decreasing)]
else
sort.int(x, na.last = na.last, decreasing = decreasing, ...)
}
sort.int <-
function(x, partial = NULL, na.last = NA, decreasing = FALSE,
method = c("auto", "shell", "quick", "radix"),
index.return = FALSE)
{
decreasing <- as.logical(decreasing)
if (is.null(partial) && !index.return && is.numeric(x)) {
if (.Internal(sorted_fpass(x, decreasing, na.last))) {
attr <- attributes(x)
if (! is.null(attr) && ! identical(names(attr), "names"))
attributes(x) <- list(names = names(x))
return(x)
}
}
method <- match.arg(method)
if (method == "auto" && is.null(partial) &&
(is.numeric(x) || is.factor(x) || is.logical(x)) &&
is.integer(length(x)))
method <- "radix"
if (method == "radix") {
if (!is.null(partial)) {
stop("'partial' sorting not supported by radix method")
}
if (index.return && is.na(na.last)) {
x <- x[!is.na(x)]
na.last <- TRUE
}
o <- order(x, na.last = na.last, decreasing = decreasing,
method = "radix")
y <- x[o]
y <- .doSortWrap(y, decreasing, na.last)
return(if (index.return) list(x = y, ix = o) else y)
}
else if (method == "auto" || !is.numeric(x))
method <- "shell"
if(isfact <- is.factor(x)) {
if(index.return) stop("'index.return' only for non-factors")
lev <- levels(x)
nlev <- nlevels(x)
isord <- is.ordered(x)
x <- c(x)
} else if(!is.atomic(x))
stop("'x' must be atomic")
if(has.na <- any(ina <- is.na(x))) {
nas <- x[ina]
x <- x[!ina]
}
if(index.return && !is.na(na.last))
stop("'index.return' only for 'na.last = NA'")
if(!is.null(partial)) {
if(index.return || decreasing || isfact || method != "shell")
stop("unsupported options for partial sorting")
if(!all(is.finite(partial))) stop("non-finite 'partial'")
y <- if(length(partial) <= 10L) {
partial <- .Internal(qsort(partial, FALSE))
.Internal(psort(x, partial))
} else if (is.double(x)) .Internal(qsort(x, FALSE))
else .Internal(sort(x, FALSE))
} else {
nms <- names(x)
switch(method,
"quick" = {
if(!is.null(nms)) {
if(decreasing) x <- -x
y <- .Internal(qsort(x, TRUE))
if(decreasing) y$x <- -y$x
names(y$x) <- nms[y$ix]
if (!index.return) y <- y$x
} else {
if(decreasing) x <- -x
y <- .Internal(qsort(x, index.return))
if(decreasing)
if(index.return) y$x <- -y$x else y <- -y
}
},
"shell" = {
if(index.return || !is.null(nms)) {
o <- sort.list(x, decreasing = decreasing)
y <- if (index.return) list(x = x[o], ix = o) else x[o]
}
else
y <- .Internal(sort(x, decreasing))
})
}
if (!is.na(na.last) && has.na)
y <- if (!na.last) c(nas, y) else c(y, nas)
if (isfact)
y <- (if (isord) ordered else factor)(y, levels = seq_len(nlev),
labels = lev)
if (is.null(partial)) {
y <- .doSortWrap(y, decreasing, na.last)
}
y
}
order <- function(..., na.last = TRUE, decreasing = FALSE,
method = c("auto", "shell", "radix"))
{
z <- list(...)
decreasing <- as.logical(decreasing)
if (length(z) == 1L && is.numeric(x <- z[[1L]]) && !is.object(x) && length(x) > 0) {
if (.Internal(sorted_fpass(x, decreasing, na.last)))
return(seq_along(x))
}
method <- match.arg(method)
if(any(vapply(z, is.object, logical(1L)))) {
z <- lapply(z, function(x) if(is.object(x)) as.vector(xtfrm(x)) else x)
return(do.call("order", c(z, list(na.last = na.last, decreasing = decreasing,
method = method))))
}
if (method == "auto") {
useRadix <- all(vapply(z, function(x) {
(is.numeric(x) || is.factor(x) || is.logical(x)) &&
is.integer(length(x))
}, logical(1L)))
method <- if (useRadix) "radix" else "shell"
}
if(method != "radix" && !is.na(na.last)) {
if(length(decreasing) > 1L)
stop("'decreasing' of length > 1 is only for method = \"radix\"")
return(.Internal(order(na.last, decreasing, ...)))
}
if (method == "radix") {
decreasing <- rep_len(as.logical(decreasing), length(z))
return(.Internal(radixsort(na.last, decreasing, FALSE, TRUE, ...)))
}
if(any(diff((l.z <- lengths(z)) != 0L)))
stop("argument lengths differ")
na <- vapply(z, is.na, rep.int(NA, l.z[1L]))
ok <- if(is.matrix(na)) rowSums(na) == 0L else !any(na)
if(all(!ok)) return(integer())
z[[1L]][!ok] <- NA
ans <- do.call("order", c(z, list(decreasing = decreasing)))
ans[ok[ans]]
}
sort.list <- function(x, partial = NULL, na.last = TRUE, decreasing = FALSE,
method = c("auto", "shell", "quick", "radix"))
{
decreasing <- as.logical(decreasing)
if(is.null(partial) && is.numeric(x) && !is.object(x) && length(x) > 0) {
if (.Internal(sorted_fpass(x, decreasing, na.last)))
return(seq_along(x))
}
method <- match.arg(method)
if (method == "auto" &&
(is.numeric(x) || is.factor(x) || is.logical(x) ||
(is.object(x) && !is.atomic(x))) && is.integer(length(x)))
method <- "radix"
if(!is.null(partial))
.NotYetUsed("partial != NULL")
if(method == "quick") {
if(is.factor(x)) x <- as.integer(x)
if(is.numeric(x))
return(sort(x, na.last = na.last, decreasing = decreasing,
method = "quick", index.return = TRUE)$ix)
else stop("method = \"quick\" is only for numeric 'x'")
}
if (is.na(na.last)) {
x <- x[!is.na(x)]
na.last <- TRUE
}
if(method == "radix") {
return(order(x, na.last=na.last, decreasing=decreasing, method="radix"))
}
if(!is.atomic(x))
stop("'x' must be atomic for 'sort.list', method \"shell\" and \"quick\"
Have you called 'sort' on a list?")
.Internal(order(na.last, decreasing, x))
}
xtfrm.default <- function(x) {
y <- if(is.numeric(x))
unclass(x)
else as.vector(rank(x, ties.method = "min", na.last = "keep"))
if(!is.numeric(y) ||
((length(y) != length(x)) && !inherits(x, "data.frame")))
stop("cannot xtfrm 'x'")
y
}
xtfrm.factor <- function(x) as.integer(x)
xtfrm.AsIs <- function(x)
{
if(length(cl <- class(x)) > 1) oldClass(x) <- cl[-1L]
NextMethod("xtfrm")
}
.gt <- function(x, i, j)
{
xi <- x[i]; xj <- x[j]
if (xi == xj) 0L else if(xi > xj) 1L else -1L;
}
.gtn <- function(x, strictly)
{
n <- length(x)
if(strictly) !all(x[-1L] > x[-n]) else !all(x[-1L] >= x[-n])
}
grouping <- function(...) {
z <- list(...)
if(any(vapply(z, is.object, logical(1L)))) {
z <- lapply(z, function(x) if(is.object(x)) as.vector(xtfrm(x)) else x)
return(do.call("grouping", z))
}
nalast <- TRUE
decreasing <- rep_len(FALSE, length(z))
group <- TRUE
sortStr <- FALSE
return(.Internal(radixsort(nalast, decreasing, group, sortStr, ...)))
} |
DFPCA <-
function(y)
{
mu<- colMeans(y)
sub_mean<-matrix(rep(mu,nrow(y)),nrow(y),ncol(y), byrow=TRUE)
resd<-y-sub_mean
G <- long_run_covariance_estimation(t(resd))
e1 <- eigen(G)
fpca.value <- e1$values
fpca.value <- ifelse(fpca.value>=0, fpca.value, 0)
percent <- (fpca.value)/sum(fpca.value)
ratio<- fpca.value[1]/fpca.value
K <- max(min(which(cumsum(percent) > 0.9)), min(which(ratio>sqrt(nrow(y))/log10(nrow(y))))-1, 2)
fpca.vectors <- e1$vectors
FPCS<-resd%*%fpca.vectors
return(list(score=FPCS,lambda=fpca.value, phi=fpca.vectors,mu=mu, npc.select=K, mean=sub_mean))
} |
justDoItDoE <- function (command)
{
Message()
if (!getRcmdr("suppress.X11.warnings")) {
messages.connection <- file(open = "w+")
sink(messages.connection, type = "message")
on.exit({
sink(type = "message")
close(messages.connection)
})
}
else messages.connection <- getRcmdr("messages.connection")
result <- try(eval(parse(text = command),envir = .GlobalEnv))
if (!class(result)[1]=="try-error") checkWarnings(readLines(messages.connection))
if (getRcmdr("RStudio"))
Sys.sleep(0)
result
} |
scores3D=function(true.dens,
est.dens,
npoints, eps)
{
check.true=rect.integrate(density=true.dens,
npoints=npoints,eps=eps)
check.est=rect.integrate(density=est.dens,
npoints=npoints,eps=eps)
L2.score= ( rect.integrate(density= (est.dens - true.dens)^2,
npoints=npoints,eps=eps) )^(1/2)
KL.score= rect.integrate(
density= (log(true.dens+(true.dens==0))-log(check.true)-
log(est.dens+ (est.dens==0))+
log(check.est) ) * true.dens/check.true,
npoints=npoints,eps=eps)
return(list(check.true=check.true,
check.est=check.est,
L2score=L2.score,
KLscore=KL.score))
} |
discretize_cutp <- function(cont_test_set, disc_train_set, cont_train_set) {
d <- ncol(cont_train_set)
data_validation <- matrix(0, nrow = nrow(cont_test_set), ncol = d)
cutoff <- get_cutp(disc_train_set, cont_train_set)
for (k in 1:d) {
if (nlevels(as.factor(disc_train_set[, k])) > 1) {
data_validation[, k] <- cut(cont_test_set[, k], cutoff[[k]], include.lowest = FALSE, labels = seq(1:(length(cutoff[[k]]) - 1)))
data_validation[, k] <- factor(data_validation[, k])
} else {
data_validation[, k] <- rep(factor(1), nrow(cont_test_set))
}
}
return(data_validation)
} |
mod_estimation_dicent_ui <- function(id, label) {
ns <- NS(id)
tabItem(
class = "tabitem-container",
tabName = label,
h2("Dicentrics: Dose estimation"),
fluidRow(
box(
width = 5,
title = span(
"Curve fitting data options",
help_modal_button(
ns("help_fit_data"),
ns("help_fit_data_modal")
)
),
status = "info",
collapsible = TRUE,
bsplus::bs_modal(
id = ns("help_fit_data_modal"),
title = "Help: Fitting data input",
size = "large",
body = tagList(
radioGroupButtons(
inputId = ns("help_fit_data_option"),
label = NULL,
choices = c(
"Manual input" = "manual",
"Load data" = "load"
),
selected = "load"
),
conditionalPanel(
condition = "input.help_fit_data_option == 'manual'",
ns = ns,
include_help("estimation/fit_data_input.md")
),
conditionalPanel(
condition = "input.help_fit_data_option == 'load'",
ns = ns,
include_help("estimation/fit_data_load.md")
)
)
),
fluidRow(
col_12(
awesomeCheckbox(
inputId = ns("load_fit_data_check"),
status = "info",
label = "Load fit data from RDS file",
value = TRUE
),
conditionalPanel(
condition = "!input.load_fit_data_check",
ns = ns,
div(
class = "side-widget-tall",
selectInput(
ns("formula_select"),
width = 165,
label = "Fitting formula",
choices = list_fitting_formulas(),
selected = "lin-quad"
)
),
widget_sep(),
actionButton(
ns("button_gen_table"),
class = "options-button",
style = "margin-left: -10px; margin-bottom: 0px;",
label = "Generate tables"
),
br(),
br(),
widget_label("Coefficients"),
div(
class = "hot-improved",
rHandsontableOutput(ns("fit_coeffs_hot"))
),
br(),
awesomeCheckbox(
inputId = ns("use_var_cov_matrix"),
status = "info",
label = "Provide variance-covariance matrix",
value = FALSE
)
),
conditionalPanel(
condition = "input.use_var_cov_matrix",
ns = ns,
widget_label("Variance-covariance matrix"),
div(
class = "hot-improved",
rHandsontableOutput(ns("fit_var_cov_mat_hot"))
),
br()
),
conditionalPanel(
condition = "input.load_fit_data_check",
ns = ns,
fileInput(
ns("load_fit_data"),
label = "File input",
accept = c(".rds")
)
),
actionButton(
ns("button_view_fit_data"),
class = "options-button",
label = "Preview data"
)
)
)
),
tabBox(
id = ns("fit_results_tabs"),
width = 7,
side = "left",
tabPanel(
title = "Result of curve fit",
h5("Fit formula"),
uiOutput(ns("fit_formula_tex")),
h5("Coefficients"),
div(
class = "hot-improved",
rHandsontableOutput(ns("fit_coeffs"))
)
),
tabPanel(
title = "Summary statistics",
conditionalPanel(
condition = "input.load_fit_data_check",
ns = ns,
h5("Model-level statistics"),
div(
class = "hot-improved",
rHandsontableOutput(ns("fit_model_statistics"))
),
br()
),
h5("Correlation matrix"),
div(
class = "hot-improved",
rHandsontableOutput(ns("fit_cor_mat"))
),
br(),
h5("Variance-covariance matrix"),
div(
class = "hot-improved",
rHandsontableOutput(ns("fit_var_cov_mat"))
)
)
)
),
fluidRow(
box(
width = 5,
title = span(
"Data input options",
help_modal_button(
ns("help_cases_data"),
ns("help_cases_data_modal")
)
),
status = "info",
collapsible = TRUE,
bsplus::bs_modal(
id = ns("help_cases_data_modal"),
title = "Help: Cases data input",
size = "large",
body = tagList(
radioGroupButtons(
inputId = ns("help_cases_data_option"),
label = NULL,
choices = c(
"Manual input" = "manual",
"Load data" = "load"
)
),
conditionalPanel(
condition = "input.help_cases_data_option == 'manual'",
ns = ns,
include_help("estimation/cases_data_input.md")
),
conditionalPanel(
condition = "input.help_cases_data_option == 'load'",
ns = ns,
include_help("estimation/cases_data_load.md")
)
)
),
fluidRow(
col_12(
awesomeCheckbox(
inputId = ns("load_case_data_check"),
status = "info",
label = "Load data from file",
value = FALSE
),
conditionalPanel(
condition = "!input.load_case_data_check",
ns = ns,
numericInput(
ns("num_aberrs"),
label = "Maximum number of dicentrics per cell",
value = 5
)
),
conditionalPanel(
condition = "input.load_case_data_check",
ns = ns,
fileInput(
ns("load_case_data"),
label = "File input",
accept = c("txt/csv", "text/comma-separated-values", "text/plain", ".csv", ".txt", ".dat")
)
),
textAreaInput(
inputId = ns("case_description"),
label = "Case description",
placeholder = "Short summary of the case"
),
actionButton(
ns("button_upd_table"),
class = "options-button",
label = "Generate table"
)
)
)
),
col_7_inner(
box(
width = 12,
title = "Data input",
status = "primary",
collapsible = TRUE,
div(
class = "hot-improved",
rHandsontableOutput(ns("case_data_hot"))
),
br(),
actionButton(
ns("button_upd_params"),
class = "inputs-button",
label = "Calculate parameters"
)
),
box(
width = 12,
title = span(
"Dose estimation options",
help_modal_button(
ns("help_estimation_options"),
ns("help_estimation_options_modal")
)
),
status = "info",
collapsible = TRUE,
bsplus::bs_modal(
id = ns("help_estimation_options_modal"),
title = "Help: Dose estimation options",
size = "large",
body = tagList(
radioGroupButtons(
inputId = ns("help_estimation_options_option"),
label = NULL,
choices = c(
"Exposure" = "exposure",
"Assessment" = "assess",
"Error calculation" = "error",
"Survival coefficient" = "surv_coeff"
)
),
conditionalPanel(
condition = "input.help_estimation_options_option == 'exposure'",
ns = ns,
include_help("estimation/dose_exposure.md")
),
conditionalPanel(
condition = "input.help_estimation_options_option == 'assess'",
ns = ns,
include_help("estimation/dose_assessment.md")
),
conditionalPanel(
condition = "input.help_estimation_options_option == 'error'",
ns = ns,
include_help("estimation/dose_error.md"),
include_help("dicent/dose_error_methods.md")
),
conditionalPanel(
condition = "input.help_estimation_options_option == 'surv_coeff'",
ns = ns,
include_help("estimation/fraction_coeff_select.md")
)
)
),
div(
class = "side-widget-tall",
selectInput(
ns("exposure_select"),
label = "Exposure",
width = "175px",
choices = list(
"Acute" = "acute",
"Protracted" = "protracted",
"Highly protracted" = "protracted_high"
),
selected = "acute"
)
),
widget_sep(),
div(
class = "side-widget-tall",
selectInput(
ns("assessment_select"),
label = "Assessment",
width = "175px",
choices = list(
"Whole-body" = "whole-body",
"Partial-body" = "partial-body",
"Heterogeneous" = "hetero"
),
selected = "whole-body"
)
),
br(),
br(),
div(
class = "side-widget-tall",
selectInput(
ns("error_method_whole_select"),
label = "Whole-body error method",
width = "250px",
choices = list(
"Merkle's method (83%-83%)" = "merkle-83",
"Merkle's method (95%-95%)" = "merkle-95",
"Delta method (95%)" = "delta"
),
selected = "merkle-83"
)
),
widget_sep(),
div(
class = "side-widget-tall",
conditionalPanel(
condition = "input.assessment_select == 'partial-body'",
ns = ns,
selectInput(
ns("error_method_partial_select"),
label = "Partial-body error method",
width = "250px",
choices = list(
"Dolphin (95%)" = "dolphin"
),
selected = "dolphin"
)
)
),
div(
class = "side-widget-tall",
conditionalPanel(
condition = "input.assessment_select == 'hetero'",
ns = ns,
selectInput(
ns("error_method_hetero_select"),
label = "Heterogeneous error method",
width = "250px",
choices = list(
"Delta method (95%)" = "delta"
),
selected = "delta"
)
)
),
conditionalPanel(
condition = "input.exposure_select == 'protracted'",
ns = ns,
br(),
div(
class = "side-widget-tall",
numericInput(
ns("protracted_time"),
label = "Irradiation time (h)",
width = "175px",
value = 0.5,
step = 0.1,
min = 0
)
),
widget_sep(),
div(
class = "side-widget-tall",
numericInput(
ns("protracted_life_time"),
label = "Rejoining time (h)",
width = "175px",
value = 2,
step = 0.1,
min = 2,
max = 5
)
)
),
conditionalPanel(
condition = "input.assessment_select != 'whole-body'",
ns = ns,
br(),
div(
class = "side-widget-tall",
selectInput(
ns("fraction_coeff_select"),
label = "Survival coefficient",
width = "175px",
choices = list(
"D0" = "d0",
"Gamma" = "gamma"
),
selected = "d0"
)
),
widget_sep(),
div(
class = "side-widget",
conditionalPanel(
condition = "input.fraction_coeff_select == 'gamma'",
ns = ns,
div(
class = "side-widget-tall",
numericInput(
width = "175px",
ns("gamma_coeff"), "Gamma",
value = 0.3706479, step = 0.01
)
),
div(
class = "side-widget-tall",
numericInput(
width = "150px",
ns("gamma_error"), "Error of gamma",
value = 0.009164707, step = 0.0001
)
)
),
conditionalPanel(
condition = "input.fraction_coeff_select == 'd0'",
ns = ns,
div(
class = "side-widget-tall",
numericInput(
width = "150px",
ns("d0_coeff"), "D0",
value = 2.7, step = 0.01,
min = 2.7, max = 3.5
)
)
)
)
),
conditionalPanel(
condition = "input.assessment_select == 'whole-body'",
ns = ns,
br()
),
conditionalPanel(
condition = "input.assessment_select != 'whole-body'",
ns = ns,
br()
),
actionButton(
ns("button_estimate"),
class = "options-button",
label = "Estimate dose"
)
)
)
),
fluidRow(
col_6_inner(
uiOutput(ns("estimation_results_ui")),
box(
width = 12,
title = span(
"Save results",
help_modal_button(
ns("help_fit_data_save"),
ns("help_fit_data_save_modal")
)
),
status = "warning",
collapsible = TRUE,
bsplus::bs_modal(
id = ns("help_fit_data_save_modal"),
title = "Help: Export results",
size = "large",
body = tagList(
include_help("save/estimation_data_save_report.md")
)
),
textAreaInput(
inputId = ns("results_comments"),
label = "Comments",
placeholder = "Comments to be included on report"
),
downloadButton(
ns("save_report"),
class = "export-button side-widget-download",
label = "Download report"
),
div(
class = "side-widget-format",
selectInput(
ns("save_report_format"),
label = NULL,
width = "85px",
choices = list(".pdf", ".docx"),
selected = ".pdf"
)
)
)
),
box(
width = 6,
title = "Curve plot",
status = "success",
collapsible = TRUE,
plotOutput(ns("plot")),
downloadButton(
ns("save_plot"),
class = "results-button side-widget-download",
label = "Save plot"
),
div(
class = "side-widget-format",
selectInput(
ns("save_plot_format"),
label = NULL,
width = "75px",
choices = list(".png", ".pdf"),
selected = ".png"
)
)
)
)
)
} |
"E0vect" <-
function(xbar) {
i1 <- -0.05043133; i2 <- 0.003383146
E0 <- matrix(c(i1*xbar,i2),ncol=1)
E0} |
fit.independence <- function(Master, LambdaNames, LambdaName, ItemNames) {
master.mlogit <- dfidx::dfidx(Master, choice="y", idx=c("CaseID","alt"))
fstack <- stats::as.formula(paste("choice ~ ", paste(LambdaNames,
collapse = "+"), "| 0 | 0", sep=" ") )
fit.stack <- mlogit::mlogit(fstack, master.mlogit)
estimates <- matrix(fit.stack$coefficients,
nrow=length(unique(Master$Item)),
ncol=(length(unique(Master$Category))-1),
byrow=TRUE)
e1 <- -(rowSums(estimates))
estimates <- cbind(e1,estimates)
rownames(estimates) <- ItemNames
colnames(estimates) <- c("lam1", LambdaName)
mlpl.phi <- as.numeric(fit.stack$logLik)
AIC <- -1*mlpl.phi - length(LambdaNames)
BIC <- -2*mlpl.phi - length(LambdaNames)*log(length(unique(Master$PersonID)))
summary.stack <- summary(fit.stack)
results <- list(phi.mlogit = summary.stack,
fstack = fstack,
estimates = estimates,
mlpl.phi = mlpl.phi[1],
AIC = AIC[1],
BIC = BIC[1]
)
return(results)
} |
print.ICA <-
function(x, ...) {
with(x, {
cat(" Call:\n")
print(call)
cat("\n Best solution: ", position, "\n",
"Best value: ", value, "\n",
"No. of Imperialists: ", nimp, "\n",
"Timings:\n")
print(time)
})
invisible(x)
} |
test_that("Mod arg accepts single numeric value", {
moderated_mediation_model <-
ho_et_al %>%
dplyr::mutate(condition_c =
build_contrast(condition,
"High discrimination",
"Low discrimination"),
linkedfate_c =
scale(linkedfate, scale = FALSE),
sdo_c =
scale(sdo, scale = FALSE)) %>%
mdt_moderated(
condition_c,
hypodescent,
linkedfate_c,
sdo_c
)
expect_error(
moderated_mediation_model %>% compute_indirect_effect_for(Mod = "foo")
)
expect_error(
moderated_mediation_model %>% compute_indirect_effect_for(Mod = c(1, 2))
)
expect_error(
moderated_mediation_model %>% compute_indirect_effect_for(Mod = 0),
NA
)
})
test_that("JSmediation approach is consistent with the {mediation} approach (Mod = 1)", {
withr::local_seed(123)
dataset <-
ho_et_al %>%
dplyr::mutate(condition_c = build_contrast(condition,
"Low discrimination",
"High discrimination")) %>%
dplyr::mutate(dplyr::across(c(linkedfate, sdo),
~ as.numeric(scale(.))))
model_1 <- lm(linkedfate ~ condition_c * sdo, dataset)
model_2 <- lm(hypodescent ~ (condition_c + linkedfate) * sdo, dataset)
mediation_model <-
mediation::mediate(model_1, model_2,
covariates = list(sdo = 1),
boot = TRUE,
boot.ci.type = "perc",
sims = 5000,
treat = "condition_c",
mediator = "linkedfate")
JSmediation_model <-
dataset %>%
mdt_moderated(DV = hypodescent,
IV = condition_c,
M = linkedfate,
Mod = sdo) %>%
compute_indirect_effect_for(Mod = 1)
JSmediation_estimate <- purrr::chuck(JSmediation_model, "estimate")
mediation_estimate <- purrr::chuck(mediation_model, "d0")
expect_equal(JSmediation_estimate, mediation_estimate, tolerance = 5e-2)
})
test_that("JSmediation approach is consistent with the {processR} approach (Mod = -1, 0, 1)", {
withr::local_seed("123")
dataset <-
ho_et_al %>%
dplyr::mutate(condition_c = build_contrast(condition,
"Low discrimination",
"High discrimination")) %>%
dplyr::mutate(dplyr::across(c(linkedfate, sdo),
~ as.numeric(scale(.))))
moderated_mediation_eqn <-
processR::tripleEquation(X = "condition_c",
M = "linkedfate",
Y = "hypodescent",
moderator = list(name = "sdo",
site = list(c("a", "b", "c"))))
moderated_mediation_fit <-
withr::with_options(list(warn = -1),
lavaan::sem(moderated_mediation_eqn,
dataset))
moderated_mediation_indirect_indices <-
processR::modmedSummary(moderated_mediation_fit)
JSmediation_model <-
dataset %>%
mdt_moderated(condition_c,
hypodescent,
linkedfate,
sdo)
processR_estimates <-
purrr::chuck(moderated_mediation_indirect_indices, "indirect")
JSmediation_estimate <-
purrr::chuck(moderated_mediation_indirect_indices, "values") %>%
purrr::map_dbl(~ JSmediation_model %>%
compute_indirect_effect_for(.x) %>%
purrr::chuck("estimate"))
expect_equal(processR_estimates, JSmediation_estimate,
tolerance = 5e-2)
}) |
.doTime <- function(x, nc, zvar, dim3) {
dodays <- TRUE
dohours <- FALSE
doseconds <- FALSE
un <- nc$var[[zvar]]$dim[[dim3]]$units
if (substr(un, 1, 10) == "days since") {
startDate = as.Date(substr(un, 12, 22))
} else if (substr(un, 1, 11) == "hours since") {
dohours <- TRUE
dodays <- FALSE
startTime <- substr(un, 13, 30)
mult <- 3600
} else if (substr(un, 1, 13) == "seconds since") {
doseconds <- TRUE
dodays <- FALSE
startTime = as.Date(substr(un, 15, 31))
mult <- 1
} else if (substr(un, 1, 12) == "seconds from") {
doseconds <- TRUE
dodays <- FALSE
startTime = as.Date(substr(un, 14, 31))
mult <- 1
} else {
return(x)
}
if (!dodays) {
start <- strptime(startTime, "%Y-%m-%d %H:%M:%OS", tz = "UTC")
if (is.na(start)) start <- strptime(startTime, "%Y-%m-%d", tz = "UTC")
if (is.na(start)) return(x)
startTime <- start
time <- startTime + as.numeric(getZ(x)) * mult
time <- as.character(time)
if (!is.na(time[1])) {
x@z <- list(time)
names(x@z) <- as.character('Date/time')
}
} else if (dodays) {
cal <- ncdf4::ncatt_get(nc, "time", "calendar")
if (! cal$hasatt ) {
greg <- TRUE
} else {
cal <- cal$value
if (cal =='gregorian' | cal =='proleptic_gregorian' | cal=='standard') {
greg <- TRUE
} else if (cal == 'noleap' | cal == '365 day' | cal == '365_day') {
greg <- FALSE
nday <- 365
} else if (cal == '360_day') {
greg <- FALSE
nday <- 360
} else {
greg <- TRUE
warning('assuming a standard calender:', cal)
}
}
time <- getZ(x)
if (greg) {
time <- as.Date(time, origin=startDate)
} else {
startyear <- as.numeric( format(startDate, "%Y") )
startmonth <- as.numeric( format(startDate, "%m") )
startday <- as.numeric( format(startDate, "%d") )
year <- trunc( as.numeric(time)/nday )
doy <- (time - (year * nday))
origin <- paste(year+startyear, "-", startmonth, "-", startday, sep='')
time <- as.Date(doy, origin=origin)
}
x@z <- list(time)
names(x@z) <- 'Date'
}
return(x)
}
.dimNames <- function(nc) {
n <- nc$dim
nams <- vector(length=n)
if (n > 0) {
for (i in 1:n) {
nams[i] <- nc$dim[[i]]$name
}
}
return(nams)
}
.varName <- function(nc, varname='', warn=TRUE) {
n <- nc$nvars
dims <- vars <- vector(length=n)
if (n > 0) {
for (i in 1:n) {
vars[i] <- nc$var[[i]]$name
dims[i] <- nc$var[[i]]$ndims
}
vars <- vars[dims > 1]
dims <- dims[dims > 1]
}
if (varname=='') {
nv <- length(vars)
if (nv == 0) {
return('z')
}
if (nv == 1) {
varname <- vars
} else {
varname <- vars[which.max(dims)]
if (warn) {
if (sum(dims == max(dims)) > 1) {
vars <- vars[dims==max(dims)]
warning('varname used is: ', varname, '\nIf that is not correct, you can set it to one of: ', paste(vars, collapse=", ") )
}
}
}
}
zvar <- which(varname == vars)
if (length(zvar) == 0) {
stop('varname: ', varname, ' does not exist in the file. Select one from:\n', paste(vars, collapse=", ") )
}
return(varname)
}
.rasterObjectFromCDF <- function(filename, varname='', band=NA, type='RasterLayer', lvar, level=0, warn=TRUE, dims=1:3, crs="", stopIfNotEqualSpaced=TRUE, ...) {
stopifnot(requireNamespace("ncdf4"))
stopifnot(type %in% c('RasterLayer', "RasterBrick"))
nc <- ncdf4::nc_open(filename, readunlim=FALSE, suppress_dimvals = TRUE)
on.exit( ncdf4::nc_close(nc) )
conv <- ncdf4::ncatt_get(nc, 0, "Conventions")
zvar <- .varName(nc, varname, warn=warn)
dim3 <- dims[3]
ndims <- nc$var[[zvar]]$ndims
if (ndims== 1) {
return(.rasterObjectFromCDF_GMT(nc))
} else if (ndims == 4) {
if (missing(lvar)) {
nlevs3 <- nc$var[[zvar]]$dim[[3]]$len
nlevs4 <- nc$var[[zvar]]$dim[[4]]$len
if (nlevs3 > 1 & nlevs4 == 1) {
lvar <- 4
} else {
lvar <- 3
}
}
nlevs <- nc$var[[zvar]]$dim[[lvar]]$len
if (level <=0 ) {
level <- 1
if (nlevs > 1) {
warning('"level" set to 1 (there are ', nlevs, ' levels)')
}
} else {
oldlevel <- level <- round(level)
level <- max(1, min(level, nlevs))
if (oldlevel != level) {
warning('level set to: ', level)
}
}
if (lvar == 4) {
dim3 <- 3
} else {
dim3 <- 4
}
} else if (ndims > 4) {
warning(zvar, ' has more than 4 dimensions, I do not know what to do with these data')
}
ncols <- nc$var[[zvar]]$dim[[dims[1]]]$len
nrows <- nc$var[[zvar]]$dim[[dims[2]]]$len
xx <- try(ncdf4::ncvar_get(nc, nc$var[[zvar]]$dim[[dims[1]]]$name), silent = TRUE)
if (inherits(xx, "try-error")) {
xx <- seq_len(nc$var[[zvar]]$dim[[dims[1]]]$len)
}
rs <- xx[-length(xx)] - xx[-1]
if (! isTRUE ( all.equal( min(rs), max(rs), tolerance=0.025, scale= abs(min(rs))) ) ) {
if (is.na(stopIfNotEqualSpaced)) {
warning('cells are not equally spaced; you should extract values as points')
} else if (stopIfNotEqualSpaced) {
stop('cells are not equally spaced; you should extract values as points')
}
}
xrange <- c(min(xx), max(xx))
resx <- (xrange[2] - xrange[1]) / (ncols-1)
rm(xx)
yy <- try(ncdf4::ncvar_get(nc, nc$var[[zvar]]$dim[[dims[2]]]$name), silent = TRUE)
if (inherits(yy, "try-error")) {
yy <- seq_len(nc$var[[zvar]]$dim[[dims[2]]]$len)
}
rs <- yy[-length(yy)] - yy[-1]
if (! isTRUE ( all.equal( min(rs), max(rs), tolerance=0.025, scale= abs(min(rs))) ) ) {
if (is.na(stopIfNotEqualSpaced)) {
warning('cells are not equally spaced; you should extract values as points')
} else if (stopIfNotEqualSpaced) {
stop('cells are not equally spaced; you should extract values as points')
}
}
yrange <- c(min(yy), max(yy))
resy <- (yrange[2] - yrange[1]) / (nrows-1)
if (yy[1] > yy[length(yy)]) { toptobottom <- FALSE
} else { toptobottom <- TRUE }
rm(yy)
xrange[1] <- xrange[1] - 0.5 * resx
xrange[2] <- xrange[2] + 0.5 * resx
yrange[1] <- yrange[1] - 0.5 * resy
yrange[2] <- yrange[2] + 0.5 * resy
long_name <- zvar
unit <- ''
natest <- ncdf4::ncatt_get(nc, zvar, "_FillValue")
natest2 <- ncdf4::ncatt_get(nc, zvar, "missing_value")
prj <- NA
minv <- maxv <- NULL
a <- ncdf4::ncatt_get(nc, zvar, "min")
if (a$hasatt) { minv <- a$value }
a <- ncdf4::ncatt_get(nc, zvar, "max")
if (a$hasatt) { maxv <- a$value }
a <- ncdf4::ncatt_get(nc, zvar, "long_name")
if (a$hasatt) { long_name <- a$value }
a <- ncdf4::ncatt_get(nc, zvar, "units")
if (a$hasatt) { unit <- a$value }
a <- ncdf4::ncatt_get(nc, zvar, "grid_mapping")
if ( a$hasatt ) {
gridmap <- a$value
try(atts <- ncdf4::ncatt_get(nc, gridmap), silent=TRUE)
try(prj <- .getCRSfromGridMap4(atts), silent=TRUE)
}
if (is.na(prj)) {
if ((tolower(substr(nc$var[[zvar]]$dim[[dims[1]]]$name, 1, 3)) == 'lon') &
( tolower(substr(nc$var[[zvar]]$dim[[dims[2]]]$name, 1, 3)) == 'lat' ) ) {
if ( yrange[1] > -91 | yrange[2] < 91 ) {
if ( xrange[1] > -181 | xrange[2] < 181 ) {
prj <- '+proj=longlat +datum=WGS84'
} else if ( xrange[1] > -1 | xrange[2] < 361 ) {
prj <- '+proj=longlat +lon_wrap=180 +datum=WGS84'
}
}
}
}
crs <- .getProj(prj, crs)
if (type == 'RasterLayer') {
r <- raster(xmn=xrange[1], xmx=xrange[2], ymn=yrange[1], ymx=yrange[2], ncols=ncols, nrows=nrows, crs=crs)
names(r) <- long_name
} else if (type == 'RasterBrick') {
r <- brick(xmn=xrange[1], xmx=xrange[2], ymn=yrange[1], ymx=yrange[2], ncols=ncols, nrows=nrows, crs=crs)
r@title <- long_name
} else {
stop("unknown object type")
}
r@file@name <- filename
r@file@toptobottom <- toptobottom
r@data@unit <- unit
attr(r@data, "zvar") <- zvar
attr(r@data, "dim3") <- dim3
attr(r@data, "level") <- level
r@file@driver <- "netcdf"
if (natest$hasatt) {
r@file@nodatavalue <- as.numeric(natest$value)
} else if (natest2$hasatt) {
r@file@nodatavalue <- as.numeric(natest2$value)
}
r@data@fromdisk <- TRUE
if (ndims == 2) {
nbands <- 1
} else {
nbands <- nc$var[[zvar]]$dim[[dim3]]$len
r@file@nbands <- nbands
dim3_vals <- try(ncdf4::ncvar_get(nc, nc$var[[zvar]]$dim[[dim3]]$name), silent = TRUE)
if (inherits(dim3_vals, "try-error")) {
dim3_vals <- seq_len(nc$var[[zvar]]$dim[[dim3]]$len)
}
r@z <- list(dim3_vals)
if ( nc$var[[zvar]]$dim[[dim3]]$name == 'time' ) {
try( r <- .doTime(r, nc, zvar, dim3) )
} else {
vname <- nc$var[[zvar]]$dim[[dim3]]$name
vunit <- nc$var[[zvar]]$dim[[dim3]]$units
names(r@z) <- paste0(vname, " (", vunit, ")")
}
}
if (length(ndims)== 2 & type != 'RasterLayer') {
warning('cannot make a RasterBrick from data that has only two dimensions (no time step), returning a RasterLayer instead')
}
if (type == 'RasterLayer') {
if (is.null(band) | is.na(band)) {
if (ndims > 2) {
stop(zvar, ' has multiple layers, provide a "band" value between 1 and ', nc$var[[zvar]]$dim[[dim3]]$len)
}
} else {
if (length(band) > 1) {
stop('A RasterLayer can only have a single band. You can use a RasterBrick instead')
}
if (is.na(band)) {
r@data@band <- as.integer(1)
} else {
band <- as.integer(band)
if ( band > nbands(r) ) {
stop(paste("The band number is too high. It should be between 1 and", nbands))
}
if ( band < 1) {
stop(paste("band should be 1 or higher"))
}
r@data@band <- band
}
r@z <- list( getZ(r)[r@data@band] )
if (!(is.null(minv) | is.null(maxv))) {
r@data@min <- minv[band]
r@data@max <- maxv[band]
r@data@haveminmax <- TRUE
}
}
} else {
r@data@nlayers <- r@file@nbands
try( names(r) <- as.character(r@z[[1]]), silent=TRUE )
if (!(is.null(minv) | is.null(maxv))) {
r@data@min <- minv
r@data@max <- maxv
r@data@haveminmax <- TRUE
} else {
r@data@min <- rep(Inf, r@file@nbands)
r@data@max <- rep(-Inf, r@file@nbands)
}
}
return(r)
} |
setup_weight_plot <- function(object, ...) UseMethod("setup_weight_plot")
setup_weight_plot.test_mediation <- function(object, ...) {
setup_weight_plot(object$fit, ...)
}
setup_weight_plot.reg_fit_mediation <- function(object,
outcome = NULL,
npoints = 1000,
...) {
have_robust <- is_robust(object)
if (!(have_robust && object$robust == "MM")) {
stop("weight plot only meaningful for MM-regression")
}
y <- object$y
m <- object$m
if (is.null(outcome)) outcome <- c(m, y)
else {
if (!(is.character(outcome) && length(outcome) > 0L)) {
stop("outcome variables must be specified as character strings")
}
if (!all(outcome %in% c(m, y))) {
stop("outcome variables must be the dependent variable or a mediator")
}
}
if (length(outcome) == 1L) {
data <- get_weight_percentages(object, outcome = outcome, npoints = npoints)
} else {
tmp <- lapply(outcome, function(current) {
current_data <- get_weight_percentages(object, outcome = current,
npoints = npoints)
data.frame(Outcome = current, current_data, stringsAsFactors = TRUE)
})
data <- do.call(rbind, tmp)
}
out <- list(data = data, outcome = outcome)
class(out) <- "setup_weight_plot"
out
}
get_weight_percentages <- function(object, outcome, npoints = 1000) {
y <- object$y
m <- object$m
p_m <- length(m)
if (outcome == y) fit <- object$fit_ymx
else if (p_m == 1L) fit <- object$fit_mx
else fit <- object$fit_mx[[outcome]]
residuals <- residuals(fit)
weights <- weights(fit, type = "robustness")
n <- length(weights)
psi <- fit$control$psi
tuning <- fit$control$tuning.psi
thresholds <- seq(0, 1, length.out = npoints)
expected <- sapply(thresholds, function(threshold) {
x <- tuning * sqrt(1 - sqrt(threshold))
pnorm(x, lower.tail = FALSE)
})
tails <- c("negative", "positive")
out_list <- lapply(tails, function(tail) {
if (tail == "negative") {
in_tail <- residuals <= 0
} else {
in_tail <- residuals > 0
}
r <- residuals[in_tail]
w <- weights[in_tail]
empirical <- sapply(thresholds, function(threshold) {
sum(w <= threshold) / n
})
if (tail == "negative") {
rbind(
data.frame(Tail = "Negative residuals", Weights = "Expected",
Threshold = thresholds, Percentage = expected,
stringsAsFactors = TRUE),
data.frame(Tail = "Negative residuals", Weights = "Empirical",
Threshold = thresholds, Percentage = empirical,
stringsAsFactors = TRUE)
)
} else {
rbind(
data.frame(Tail = "Positive residuals", Weights = "Expected",
Threshold = thresholds, Percentage = expected,
stringsAsFactors = TRUE),
data.frame(Tail = "Positive residuals", Weights = "Empirical",
Threshold = thresholds, Percentage = empirical,
stringsAsFactors = TRUE)
)
}
})
do.call(rbind, out_list)
} |
abline(h=yvalues, v=xvalues)
Other graphical parameters (such as line type, color, and width) can also be specified in the abline( ) function.
abline(h=c(1,5,7))
abline(v=seq(1,10,2),lty=2,col="blue")
Note: You can also use the grid( ) function to add reference lines. |
list(coefficients1 = c(0.3816510853963, 0.0326773607065429, -0.0215376835487049,
-0.000972392445321585, -0.00712539864947305, 0.00520993461673147,
0.0325107246949657, -0.0351272068811341, 0.0365909352294855,
0.0187983469090532, -0.0261362398116196, 0.0240074928979442,
0.009473821301171, -0.0100826908786456, 0.0459705733883285, 0.0293458515825391,
0.0124533500914112, 0.0330238754882282, 0.0273958578453473, 0.00301863902482515,
-0.0472994866699436, 0.0394375845809032, 0.0118402113508717,
0.0151885220127493, 0.050593165180987, 0.030461099855424, -0.0160406019560156,
0.0323289250402233, -0.064822565117969, -0.0105945435207054,
0.00137210030512961, -0.000873662810908485, -0.0119019205008463,
0.0113038758866042, 0.0221059822083867, -0.019258081661804, -0.00437273843851046,
0.0293095563250024, -0.0109784262530217, -0.0089145500285173,
0.0357290753738689, 0.0210588490023928, 0.0105208621355446, 0.0477795479874507,
-0.033698922912952, -0.00683586057926902, 0.0393531758187854,
-0.0115179213429775, -0.00383977207148539, 0.0242844559125082,
0.0313155996004055), opt1 = 27.9063081481767, coefficients2a = c(x1 = 0.381651390799115,
x2 = 0.0326827154576504, x3 = -0.0215419102387141, x4 = -0.000977429825837963,
x5 = -0.00712757813977363, x6 = 0.00520617111704016, x7 = 0.0325110284327129,
x8 = -0.0351269431393525, x9 = 0.0365880172936484, x10 = 0.0187935850166332,
x11 = -0.0261346717936101, x12 = 0.0239989184688237, x13 = 0.0094741928793818,
x14 = -0.0100812329643096, x15 = 0.045969735760914, x16 = 0.029343538702431,
x17 = 0.0124518715443752, x18 = 0.0330242657801954, x19 = 0.0273942844381617,
x20 = 0.00301963875576265, x21 = -0.0473044239644383, x22 = 0.0394380177472302,
x23 = 0.0118422943926443, x24 = 0.0151806963574622, x25 = 0.0505942738758857,
x26 = 0.0304645879119146, x27 = -0.0160381278843077, x28 = 0.0323349725509669,
x29 = -0.0648290268961756, x30 = -0.0105985196903622, x31 = 0.0013732696328036,
x32 = -0.000876623643227784, x33 = -0.0119016904818061, x34 = 0.0113040876659727,
x35 = 0.0221064397821272, x36 = -0.0192556577873593, x37 = -0.0043718282988513,
x38 = 0.0293093084849596, x39 = -0.0109782716026442, x40 = -0.00891553777673756,
x41 = 0.0357307714279319, x42 = 0.0210530389965313, x43 = 0.010521398791892,
x44 = 0.0477824596294653, x45 = -0.0336955626616204, x46 = -0.00683672601130845,
x47 = 0.0393497973316163, x48 = -0.0115195154467358, x49 = -0.00384181166056642,
x50 = 0.024284654636736, x51 = 0.0313176464344522), opt2a = 27.9062756598428,
coefficients2b = c(x1 = 0.381651341743556, x2 = 0.0326821354939513,
x3 = -0.0215414087393219, x4 = -0.000976926233775292, x5 = -0.00712736691909117,
x6 = 0.00520660835590255, x7 = 0.0325109980768012, x8 = -0.0351267702854618,
x9 = 0.0365882131630035, x10 = 0.0187945408272744, x11 = -0.0261344735512399,
x12 = 0.0239997465796883, x13 = 0.00947405132329673, x14 = -0.0100811252570328,
x15 = 0.0459699564058498, x16 = 0.0293434386611666, x17 = 0.0124523133435645,
x18 = 0.0330244169251543, x19 = 0.0273943336151615, x20 = 0.00301953357794376,
x21 = -0.0473039724886181, x22 = 0.0394380633589978, x23 = 0.0118424795611846,
x24 = 0.0151818095395241, x25 = 0.0505941745034349, x26 = 0.0304641985575007,
x27 = -0.0160380525740208, x28 = 0.0323346805969823, x29 = -0.0648285572498546,
x30 = -0.0105979965109583, x31 = 0.0013732604084724, x32 = -0.000876280129639669,
x33 = -0.0119017165777442, x34 = 0.0113041601708157, x35 = 0.0221064407598559,
x36 = -0.0192560322885035, x37 = -0.00437193864210694, x38 = 0.0293092448717099,
x39 = -0.0109784763129622, x40 = -0.00891521151608254, x41 = 0.0357306990241541,
x42 = 0.0210536439808172, x43 = 0.0105210207409851, x44 = 0.0477824491736937,
x45 = -0.0336959805998197, x46 = -0.00683663226786749, x47 = 0.039350213384209,
x48 = -0.0115192030638305, x49 = -0.003841756346144, x50 = 0.0242847671457174,
x51 = 0.0313175707598224), opt2b = 27.9062775445648, coefficients = c(x1 = 0.381651390799115,
x2 = 0.0326827154576504, x3 = -0.0215419102387141, x4 = -0.000977429825837963,
x5 = -0.00712757813977363, x6 = 0.00520617111704016, x7 = 0.0325110284327129,
x8 = -0.0351269431393525, x9 = 0.0365880172936484, x10 = 0.0187935850166332,
x11 = -0.0261346717936101, x12 = 0.0239989184688237, x13 = 0.0094741928793818,
x14 = -0.0100812329643096, x15 = 0.045969735760914, x16 = 0.029343538702431,
x17 = 0.0124518715443752, x18 = 0.0330242657801954, x19 = 0.0273942844381617,
x20 = 0.00301963875576265, x21 = -0.0473044239644383, x22 = 0.0394380177472302,
x23 = 0.0118422943926443, x24 = 0.0151806963574622, x25 = 0.0505942738758857,
x26 = 0.0304645879119146, x27 = -0.0160381278843077, x28 = 0.0323349725509669,
x29 = -0.0648290268961756, x30 = -0.0105985196903622, x31 = 0.0013732696328036,
x32 = -0.000876623643227784, x33 = -0.0119016904818061, x34 = 0.0113040876659727,
x35 = 0.0221064397821272, x36 = -0.0192556577873593, x37 = -0.0043718282988513,
x38 = 0.0293093084849596, x39 = -0.0109782716026442, x40 = -0.00891553777673756,
x41 = 0.0357307714279319, x42 = 0.0210530389965313, x43 = 0.010521398791892,
x44 = 0.0477824596294653, x45 = -0.0336955626616204, x46 = -0.00683672601130845,
x47 = 0.0393497973316163, x48 = -0.0115195154467358, x49 = -0.00384181166056642,
x50 = 0.024284654636736, x51 = 0.0313176464344522), opt = 27.9062756598428) |
layout_functions <- function(name = NULL, graph = NULL, intitial_coords = NULL, effort = 1, ...) {
funcs <- list("automatic" = igraph::nicely,
"reingold-tilford" = igraph::as_tree,
"davidson-harel" = igraph::with_dh,
"gem" = igraph::with_gem,
"graphopt" = igraph::with_graphopt,
"mds" = igraph::with_mds(),
"fruchterman-reingold" = igraph::with_fr,
"kamada-kawai" = igraph::with_kk,
"large-graph" = igraph::with_lgl,
"drl" = igraph::with_drl)
return_names <- is.null(name) && is.null(graph) && is.null(intitial_coords)
if (return_names) {
return(names(funcs))
} else {
v_weight <- igraph::V(graph)$weight_factor
e_weight <- igraph::E(graph)$weight_factor
e_density <- igraph::edge_density(graph)
defaults <- list("automatic" = list(),
"reingold-tilford" = list(circular = TRUE,
mode = "out"),
"davidson-harel" = list(coords = intitial_coords,
maxiter = 10 * effort,
fineiter = max(10, log2(igraph::vcount(graph))) * effort,
cool.fact = 0.75 - effort * 0.1,
weight.node.dist = 13,
weight.border = 0,
weight.edge.lengths = 0.5,
weight.edge.crossings = 100,
weight.node.edge.dist = 1),
"gem" = list(coords = intitial_coords,
maxiter = 40 * igraph::vcount(graph)^2 * effort,
temp.max = igraph::vcount(graph) * (1 + effort * 0.1),
temp.min = 1/10,
temp.init = sqrt(igraph::vcount(graph))),
"graphopt" = list(start = intitial_coords,
niter = 500 * effort,
charge = 0.0005,
mass = 30,
spring.length = 0,
spring.constant = 1,
max.sa.movement = 5),
"mds" = list(),
"fruchterman-reingold" = list(coords = intitial_coords,
niter = 500 * effort,
start.temp = sqrt(igraph::vcount(graph)) * (1 + effort * 0.1) ,
grid = "nogrid",
weights = e_weight),
"kamada-kawai" = list(coords = intitial_coords,
maxiter = 100 * igraph::vcount(graph),
epsilon = 0,
kkconst = igraph::vcount(graph),
weights = NULL),
"large-graph" = list(maxiter = 200,
maxdelta = igraph::vcount(graph),
area = igraph::vcount(graph)^2,
coolexp = 1.5 - effort * 0.1,
repulserad = igraph::vcount(graph)^2 * igraph::vcount(graph),
cellsize = sqrt(sqrt(igraph::vcount(graph)^2)),
root = 1),
"drl" = list(use.seed = ! is.null(intitial_coords),
seed = ifelse(is.null(intitial_coords),
matrix(stats::runif(igraph::vcount(graph) * 2), ncol = 2),
intitial_coords),
options = igraph::drl_defaults$default,
weights = NULL,
fixed = NULL))
arguments <- utils::modifyList(defaults[[name]], list(...))
coords <- igraph::layout_(graph = graph, layout = do.call(funcs[[name]], arguments))
return(coords)
}
} |
Res_stom_SO2 <- function(x, m2=1, m3=4){
db <- x
db <- x
LAI_Total <- db$BAI + db$LAI
theta <- 60
m <- 1 / (cos(theta*pi/180))
antilog<-function(lx,base) {
lbx<-lx/log(exp(1),base=base)
result<-exp(lbx)
result
}
lx <- (-1.195) + 0.4459 * log(m, base = 10) - 0.0345 * (log(m, base = 10))^2
W <- 1320 * antilog(lx = lx ,base = 10)
P <- db$Pres
P0 <- 101.325
R_DV <- 600 * exp(-0.185 * (P/P0) * m) * cos(theta * pi / 180)
R_dv <- 0.4 * (600 - R_DV) * cos(theta * pi / 180)
R_DN <- (720 * exp(-0.06 * (P/P0) * m) - W) * cos(theta * pi / 180)
R_dn <-0.6 * (720 - R_DN - W) * cos(theta * pi / 180)
R_V <- R_DV + R_dv
R_N <- R_DN + R_dn
R_T <- db$Rad
A <- 0.9
B <- 0.7
C <- 0.88
D <- 0.68
RATIO0 <- R_T / (R_V + R_N)
RATIO1<- replace(RATIO0, RATIO0>A , A)
RATIO<- replace(RATIO1, RATIO1>C , C)
f_V0 <- (R_DV / R_V) * (1 - ((A - RATIO) / B)^(2 / 3))
f_V<- replace(f_V0, f_V0<0 , 0)
f_N0 <- (R_DN / R_N) * (1 - ((C - RATIO) / D)^(2 / 3))
f_N<- replace(f_N0, f_N0<0 , 0)
Fc <- 4.6
PAR_dir <- f_V * (0.46 * R_T) * Fc
PAR_diff <- (1 - f_V) * (0.46 * R_T) * Fc
Resistance_out_of_leaf <- NA
theta <- 60
E <- 0.185
m <- 1 / (cos(theta * pi / 180))
F_j <- LAI_Total
beta <- 90 - theta
C_j = 0.07 * PAR_dir * (1.1 - 0.1 * (F_j - (F_j / 2))) * (exp(-sin(beta * pi / 180)))
PAR_shade_j <- PAR_diff * exp(-0.5 * (LAI_Total^0.7))+ C_j
alpha <- 60
PAR_sun_j <- PAR_dir * ((cos(alpha * pi / 180))/(sin(beta * pi / 180))) + PAR_shade_j
Temp_K <- db$Temp + 273.15
T_leaf_limit <- 25 + 273.15
T_leaf_hot <- rep(NA, length(Temp_K))
T_leaf_cold <- rep(NA, length(Temp_K))
Selec_T_leaf_hot <- Temp_K >= T_leaf_limit
Selec_T_leaf_cold <- Temp_K < T_leaf_limit
T_leaf_hot[Selec_T_leaf_hot & !is.na(Temp_K)] <- (log(1+
Temp_K[Selec_T_leaf_hot & !is.na(Temp_K)] -
T_leaf_limit))^2 + T_leaf_limit
T_leaf_cold[Selec_T_leaf_cold & !is.na(Temp_K)] <- T_leaf_limit -
(log(1+T_leaf_limit - Temp_K[Selec_T_leaf_cold & !is.na(Temp_K)]))^2
T_leaf_df <- cbind.data.frame(T_leaf_hot, T_leaf_cold)
T_leaf <- rowSums(T_leaf_df, na.rm=T)
T_leaf[is.na(Temp_K)] <- NA
T_leaf_df$T_leafdf <- T_leaf
T_leaf_df$Air_temp <- Temp_K
m1 <- m2 * m3
Vcmax25 <- 90
rh <- db$Hum / 100
b1 <- 0.02
P_O2 <- 210
R <- 8.3144598
S <- 710
H <- 220000
kc25 <- 33.3
E_rae_kc <- 65120
kc <- kc25 * (exp(((T_leaf - 298) * E_rae_kc) / (298 * R * T_leaf)))
ko25 <- 29.5
E_rae_ko <- 13990
ko <- ko25 * (exp(((T_leaf - 298) * E_rae_ko) / (298 * R * T_leaf)))
Vcmax25 <- 90
E_rae_Vc <- 64637
Vcmax <- (Vcmax25 * exp(((T_leaf - 298) * E_rae_Vc) / (298 * R * T_leaf))) /
(1 + exp(((S * T_leaf) - H) / (R * T_leaf)))
Jmax25 <- 171
E_rae_J <- 37000
Jmax <- (Jmax25 * exp(((T_leaf - 298) * E_rae_J) / (298 * R * T_leaf))) /
(1 + exp(((S * T_leaf) - H) / (R * T_leaf)))
E_rae_Rd <- 51176
Rd <- (Vcmax25 * 0.015 * exp(((T_leaf - 298) * E_rae_Rd) / (298 * R * T_leaf))) /
(1 + exp(1.3 * (T_leaf - 328)))
Gamma <- (0.105 * kc * P_O2) / (ko)
alpha0 <- 0.22
J_sun <- (alpha0 * PAR_sun_j) / (sqrt(1 + (((alpha0^2) * (PAR_sun_j^2)) / (Jmax^2))))
J_shade <- (alpha0 * PAR_shade_j) / (sqrt(1 + (((alpha0^2) * (PAR_shade_j^2)) / (Jmax^2))))
J <- (J_sun + J_shade) / 2
c_a <- 400
g_b0 <- 1 / (Res_aero(db)[,"Resist_aero"] + Res_boun_CO2(db)[,"Resist_bound_CO2"])
Converting_factor_conductance <- (P * 1e3) / (R * Temp_K)
g_b <- g_b0 * Converting_factor_conductance
g_b[LAI_Total <= median(db$BAI)] <- 0
alpha2 <- 1 + (b1 / g_b) - (m1 * rh)
beta2 <- c_a * (g_b * m1 * rh - (2 * b1) - g_b)
gamma2 <- (c_a^2) * b1 * g_b
theta2 <- (g_b * m1 * rh) - b1
a2 <- Vcmax
b2 <- kc * (1 + (P_O2 / ko))
d2 <- Gamma
e2 <- 1
p2 <- (e2 * beta2 + b2 * theta2 - a2 * alpha2 + e2 * alpha2 * Rd) / (e2 * alpha2)
q2 <- (e2 * gamma2 + b2 * (gamma2 / c_a) - a2 * beta2 + a2 * d2 * theta2 +
e2 * Rd * beta2 + b2 * theta2 * Rd) / (e2 * alpha2)
r2 <- ((-a2 * gamma2) + a2 * d2 * (gamma2 / c_a) + e2 * gamma2 * Rd +
Rd * b2 * (gamma2 / c_a)) / (e2 * alpha2)
Q2_1 <- ((p2^2) - 3 * q2) / 9
Q2_1[Q2_1 <= 0] <- 0
R2_1 <- (2 * (p2^3) - 9 * p2 * q2 + 27 * r2) / 54
Q2_2 <- Q2_1^3
Q2_2[Q2_2 <= 0] <- 0
Q2_3 <- R2_1 / (sqrt(Q2_2))
Q2_3[Q2_3 > 1] <- NA
Q2_3[Q2_3 < -1] <- NA
Theta2_1 <- acos(Q2_3)
A_photo <- (-2) * sqrt(Q2_1) * cos((Theta2_1 + 4 * pi) / 3) - (p2 / 3)
A_photo[A_photo < 0] <- 0
A_photo[LAI_Total <= median(db$BAI)] <- 0
A_photo[db$Daylight=="Night"&!is.na(A_photo)] <- 0
c_s <- c_a - ((A_photo) / g_b)
c_s[c_s < 0 ] <- c_a
g_s0 <- ((m1 * A_photo * rh) / (c_s)) + b1
g_s0[g_s0 <= 0] <- b1
g_s <- g_s0 / Converting_factor_conductance
g_s[LAI_Total <= median(db$BAI)] <- 1 / Resistance_out_of_leaf
r_s <- cbind.data.frame(Dates = db$Dates, Resist_stom = 1 / g_s)
return(r_s)
} |
test_that("ConvertFishbaseDiet function works", {
all.diets <- try(ConvertFishbaseDiet(ExcludeStage = NULL),silent = TRUE)
if ("try-error"%in%class(all.diets)) {
skip("could not connect to remote database")
}else{
filtered.diets <- ConvertFishbaseDiet(ExcludeStage = "larvae")
expect_true(nrow(filtered.diets$DietItems)<nrow(all.diets$DietItems))
expect_length(filtered.diets,2)
expect_equal(ncol(filtered.diets$Taxonomy),2)
}
}) |
library(ggplot2)
(p1 <- ggplot(mtcars, aes(x=cyl)) + geom_bar())
library(dplyr)
(p2 <- mtcars %>% group_by(cyl) %>% tally %>% ggplot(., aes(x=cyl, y=n)) + geom_bar(stat='identity'))
library(gridExtra)
grid.arrange(p1,p2, ncol=2)
mtcars %>% group_by(cyl) %>% tally %>% ggplot(., aes(x=factor(cyl), y=n)) + geom_bar(stat='identity') + labs(title="Main Title", x='Cylinders', y='Nos') + coord_flip()
ggplot(mtcars, aes(x=wt, y=mpg, color=cyl)) + geom_point() + geom_smooth()
ggplot(mtcars, aes(x=wt, y=mpg, color=cyl)) + geom_point() + geom_smooth() + theme(legend.position="none") + labs(title="legend.position='none'")
ggplot(mtcars, aes(x=cyl)) + geom_bar(fill='darkgoldenrod2') +
theme(panel.background = element_rect(fill = 'steelblue'),
panel.grid.major = element_line(colour = "firebrick", size=2),
panel.grid.minor = element_line(colour = "blue", size=1))
ggplot(mtcars, aes(x=cyl)) + geom_bar(fill="firebrick") + theme(plot.background=element_rect(fill="steelblue"), plot.margin = unit(c(2, 4, 1, 3), "cm")) |
taxid2name <- function(x, db='ncbi', verbose=TRUE, warn=TRUE, ...){
result <- ap_vector_dispatch(
x = x,
db = db,
cmd = 'taxid2name',
verbose = verbose,
warn = warn,
empty = character(0),
...
)
if(warn && any(is.na(result))){
msg <- "No name found for %s of %s taxon IDs"
msg <- sprintf(msg, sum(is.na(result)), length(result))
if(verbose){
msg <- paste0(msg, ". The followings are left unnamed: ",
paste0(x[is.na(result)], collapse=', ')
)
}
warning(msg)
}
result
}
itis_taxid2name <- function(src, x, ...){
if (length(x) == 0) return(character(0))
query <- "SELECT tsn,complete_name FROM taxonomic_units WHERE tsn IN ('%s')"
query <- sprintf(query, paste0(x, collapse = "','"))
tbl <- sql_collect(src, query)
tbl$complete_name[match(x, tbl$tsn)]
}
wfo_taxid2name <- function(src, x, ...){
if (length(x) == 0) return(character(0))
query <- "SELECT taxonID,scientificName FROM wfo WHERE taxonID IN ('%s')"
query <- sprintf(query, paste0(x, collapse = "','"))
tbl <- sql_collect(src, query)
tbl$scientificName[match(x, tbl$taxonID)]
}
tpl_taxid2name <- function(src, x, ...){
if (length(x) == 0) return(character(0))
query <- "SELECT id,scientificname FROM tpl WHERE id IN ('%s')"
query <- sprintf(query, paste0(x, collapse = "','"))
tbl <- sql_collect(src, query)
tbl$scientificname[match(x, tbl$id)]
}
col_taxid2name <- function(src, x, ...){
if (length(x) == 0) return(character(0))
query <- "SELECT taxonID,scientificName FROM taxa WHERE taxonID IN ('%s')"
query <- sprintf(query, paste0(x, collapse = "','"))
tbl <- sql_collect(src, query)
tbl$scientificName[match(x, tbl$taxonID)]
}
gbif_taxid2name <- function(src, x, ...){
if (length(x) == 0) return(character(0))
query <- "SELECT taxonID,canonicalName FROM gbif WHERE taxonID IN ('%s')"
query <- sprintf(query, paste0(x, collapse = "','"))
tbl <- sql_collect(src, query)
tbl$canonicalName[match(x, tbl$taxonID)]
}
ncbi_taxid2name <- function(src, x, ...){
if (length(x) == 0) return(character(0))
query <- "SELECT tax_id, name_txt FROM names WHERE name_class == 'scientific name' AND tax_id IN (%s)"
query <- sprintf(query, sql_integer_list(x))
tbl <- sql_collect(src, query)
as.character(tbl$name_txt[match(x, tbl$tax_id)])
} |
gr.survWB <-
function (thetas) {
thetas <- relist(thetas, skeleton = list.thetas)
gammas <- thetas$gammas
alpha <- thetas$alpha
Dalpha <- thetas$Dalpha
sigma.t <- if (is.null(scaleWB)) exp(thetas$log.sigma.t) else scaleWB
eta.tw <- as.vector(WW %*% gammas)
eta.t <- switch(parameterization,
"value" = eta.tw + c(WintF.vl %*% alpha) * Y,
"slope" = eta.tw + c(WintF.sl %*% Dalpha) * Y.deriv,
"both" = eta.tw + c(WintF.vl %*% alpha) * Y + c(WintF.sl %*% Dalpha) * Y.deriv)
eta.s <- switch(parameterization,
"value" = c(Ws.intF.vl %*% alpha) * Ys,
"slope" = c(Ws.intF.sl %*% Dalpha) * Ys.deriv,
"both" = c(Ws.intF.vl %*% alpha) * Ys + c(Ws.intF.sl %*% Dalpha) * Ys.deriv)
exp.eta.tw.P <- exp(eta.tw) * P
Int <- wk * exp(log(sigma.t) + (sigma.t - 1) * log.st + eta.s)
ki <- exp.eta.tw.P * rowsum(Int, id.GK, reorder = FALSE)
kii <- c((p.byt * ki) %*% wGH)
scgammas <- - colSums(WW * (d - kii), na.rm = TRUE)
scalpha <- if (parameterization %in% c("value", "both")) {
rr <- numeric(ncol(WintF.vl))
for (k in seq_along(rr))
rr[k] <- - sum((p.byt * (d * WintF.vl[, k] * Y - exp.eta.tw.P *
rowsum(Int * Ws.intF.vl[, k] * Ys, id.GK, reorder = FALSE))) %*% wGH, na.rm = TRUE)
rr
} else NULL
scalpha.D <- if (parameterization %in% c("slope", "both")) {
rr <- numeric(ncol(WintF.sl))
for (k in seq_along(rr))
rr[k] <- - sum((p.byt * (d * WintF.sl[, k] * Y.deriv - exp.eta.tw.P *
rowsum(Int * Ws.intF.sl[, k] * Ys.deriv, id.GK, reorder = FALSE))) %*% wGH, na.rm = TRUE)
rr
} else NULL
scsigmat <- if (is.null(scaleWB)) {
Int2 <- st^(sigma.t - 1) * (1 + sigma.t * log.st) * exp(eta.s)
- sigma.t * sum((p.byt * (d * (1/sigma.t + logT) - exp.eta.tw.P *
rowsum(wk * Int2, id.GK, reorder = FALSE))) %*% wGH, na.rm = TRUE)
} else NULL
c(scgammas, scalpha, scalpha.D, scsigmat)
} |
varcast <- function(x, a.v = 0.99, a.e = 0.975,
model = c("sGARCH", "lGARCH", "eGARCH", "apARCH", "fiGARCH",
"filGARCH"),
garchOrder = c(1, 1), n.out = 250, smooth = "none", ...) {
if (length(x) <= 1 || !all(!is.na(x)) || !is.numeric(x)) {
stop("A numeric vector of length > 1 and without NAs must be passed to",
" 'x'.")
}
if (length(a.v) != 1 || is.na(a.v) || !is.numeric(a.v) || a.v <= 0 || a.v >= 1) {
stop("A single numeric value that satisfies >0 and <1 must be passed to",
" 'a.v'")
}
if (length(a.e) != 1 || is.na(a.e) || !is.numeric(a.e) || a.e <= 0 || a.e >= 1) {
stop("A single numeric value that satisfies >0 and <1 must be passed to",
" 'a.e'")
}
if (!(length(model) %in% c(1, 6)) || !all(!is.na(model)) || !is.character(model)) {
stop("A single character value must be passed to 'model'.")
}
if (all(model == c("sGARCH", "lGARCH", "eGARCH", "apARCH", "fiGARCH", "filGARCH"))) {
model <- "sGARCH"
}
if (length(garchOrder) != 2 || !all(!is.na(garchOrder)) || !is.numeric(garchOrder) ||
(garchOrder[[1]] == 0 && garchOrder[[2]] == 0)) {
stop("A vector of length 2 must be passed to 'garchOrder' giving the",
" first and second order of the GARCH-type model.")
}
garchOrder <- floor(garchOrder)
if (length(n.out) != 1 || is.na(n.out) || !is.numeric(n.out) || n.out <= 0) {
stop("A single positive integer must be passed to 'n.out'.")
}
n.out <- floor(n.out)
if (!(length(smooth) %in% c(1, 2)) || !all(!is.na(smooth)) ||
!is.character(smooth)) {
stop("The input to the argument 'smooth' must be a single character ",
"value.")
}
if (all(smooth == c("none", "lpr"))) smooth <- "none"
if (length(smooth) != 1 || !(smooth) %in% c("none", "lpr")) {
stop("The input to the argument 'smooth' must be a single character ",
"value.")
}
if (smooth == "lpr" && model %in% c("sGARCH", "lGARCH", "eGARCH", "apARCH")) {
smooth.method = "smoots"
}
if (smooth == "lpr" && model %in% c("fiGARCH", "filGARCH")) {
smooth.method = "esemifar"
}
dots <- list(...)
ret <- diff(log(x))
n.ret <- length(ret)
n.in <- n.ret - n.out
ret.in.t <- ret[1:n.in]
mean.ret.in <- mean(ret.in.t)
ret.in <- ret.in.t - mean.ret.in
ret.out.t <- ret[(n.in + 1):n.ret]
ret.out <- ret.out.t - mean.ret.in
p.true <- p <- garchOrder[1]
q.true <- q <- garchOrder[2]
if (p.true == 0) p <- 1
if (q.true == 0) q <- 1
l <- max(p, q)
if (is.null(dots[["p"]])) {
dots[["p"]] <- 3
}
dots[["y"]] <- log(ret.in^2)
switch(smooth,
none = {
np.est <- NA
zeta.in <- ret.in
zeta.out <- ret.out
res.in <- log(ret.in^2)
res.out <- log(ret.out^2)
sxt <- 1
sfc <- 1
mule <- mean(res.in)
Csig <- 1
},
lpr = {
switch(smooth.method,
smoots = {
if (is.null(dots[["alg"]])) {
dots[["alg"]] <- "A"
}
np.est <- suppressMessages(do.call(what = smoots::msmooth,
args = dots))
res.in <- np.est[["res"]]
res.out <- log(ret.out^2) - np.est[["ye"]][n.in]
mule <- -log(mean(exp(res.in)))
sxt <- exp(0.5 * (np.est[["ye"]] - mule))
sfc <- sxt[n.in]
zeta.in <- ret.in / sxt
zeta.out <- ret.out / sfc
},
esemifar = {
np.est <- suppressMessages(do.call(what = esemifar::tsmoothlm,
args = dots))
res.in <- np.est[["res"]]
res.out <- log(ret.out^2) - np.est[["ye"]][n.in]
Csig <- sd(ret.in / exp(0.5 * np.est[["ye"]]))
sxt <- exp(0.5 * np.est[["ye"]]) * Csig
sfc <- sxt[n.in]
zeta.in <- ret.in / sxt
zeta.out <- ret.out / sfc
})
}
)
zeta.n <- tail(zeta.in, n = l)
zeta.fc <- c(zeta.n, zeta.out[1:n.out])
if (model %in% c("sGARCH", "eGARCH", "apARCH", "fiGARCH")) {
spec <- rugarch::ugarchspec(variance.model =
list(model = model,
garchOrder = c(p.true, q.true)),
mean.model = list(armaOrder = c(0, 0),
include.mean = FALSE),
distribution.model = "std")
model_fit <- rugarch::ugarchfit(spec = spec, data = zeta.in)
c.sig <- as.numeric(rugarch::sigma(model_fit))
sig.n <- tail(c.sig, n = l)
alpha <- 0
beta <- 0
sig.in <- c.sig * sxt
}
switch(model,
lGARCH = {
if (p.true < q.true) {
stop("p >= q must be satisfied for the estimation of a Log-GARCH
model ", "via its ARMA representation.")
}
model_fit <- arima(res.in,
order = c(p.true, 0, q.true),
include.mean = FALSE)
y.cent <- c(res.in, res.out) - mule * isTRUE(smooth == "none")
mulz <- -log(mean(exp(model_fit[["residuals"]])))
ar <- model_fit$model$phi
ma <- -model_fit$model$theta
k <- 50
d <- 0
coef.all <- arfilt(ar, ma, d, k)
pre0 <- c()
add0 <- 0
if (n.in < k) {
add0 <- k - n.in
pre0 <- rep(0, add0)
}
y.fc.out <- (1:n.out) * 0
y.cent <- c(pre0, y.cent)
for (i in (add0 + n.in + 1):(add0 + n.ret)) {
y.fc.out[i - (add0 + n.in)] <- coef.all %*%
y.cent[(i - 1):(i - k)]
}
sig.fc <- exp(0.5 * (y.fc.out + mule - mulz))
sig.fc.in <- exp(0.5 * (y.cent[1:n.in] - model_fit[["residuals"]]
+ mule - mulz))
sig.fc <- sig.fc * sfc
sig.in <- sig.fc.in * sxt
ret.sd <- zeta.in / sig.in
df <- as.numeric(rugarch::fitdist("std", ret.sd)$pars[[3]])
},
filGARCH = {
if (p.true < q.true) {
stop("p >= q must be satisfied for the estimation of a Log-GARCH
model ", "via its ARMA representation.")
}
model_fit <- suppressWarnings(fracdiff::fracdiff(res.in,
nar = p.true,
nma = q.true))
ar <- model_fit[["ar"]]
ma <- model_fit[["ma"]]
d <- model_fit[["d"]]
k <- 50
coef.all <- arfilt(ar, ma, d, k)
pre0 <- c()
add0 <- 0
y.cent <- c(res.in, res.out)
y.cent <- y.cent - mean(res.in)
if (n.in < k) {
add0 <- k - n.in
pre0 <- rep(0, add0)
}
y.fc.out <- (1:n.out) * 0
y.cent <- c(pre0, y.cent)
for (i in (add0 + n.in + 1):(add0 + n.ret)) {
y.fc.out[i - (add0 + n.in)] <- coef.all %*% y.cent[(i - 1):(i - k)]
}
sig.fc <- exp(0.5 * (y.fc.out + mean(res.in)))
y.fc.in <- model_fit[["fitted"]]
sig.fc.in <- exp(0.5 * y.fc.in)
ret.sd <- zeta.in / (sig.fc.in * sxt)
df <- as.numeric(rugarch::fitdist("std", ret.sd)$pars[3])
if (smooth == "lpr") {
sd.c <- 1
}
else {
sd.c <- sd(ret.sd)
}
sig.fc <- sig.fc * sfc * sd.c
sig.in <- sig.fc.in * sxt * sd.c
},
sGARCH = {
pars.general <- unname(rugarch::coef(model_fit))
omega <- pars.general[[1]]
if (p.true > 0) alpha = pars.general[2:(1 + p.true)]
if (q.true > 0) beta = pars.general[(p.true + 2):(1 + p.true + q.true)]
df <- pars.general[[p.true + q.true + 2]]
vol.fc <- c(sig.n^2, rep(NA, times = n.out))
for (i in (1 + l):(n.out + l)) {
vol.fc[i] <- omega + alpha %*% zeta.fc[(i - 1):(i - p)]^2 +
beta %*% vol.fc[(i - 1):(i - q)]
}
sig.fc <- sqrt(vol.fc[(1 + l):(n.out + l)]) * sfc
},
eGARCH = {
pars.general <- unname(rugarch::coef(model_fit))
omega <- pars.general[[1]]
gamma <- 0
if (p.true > 0) {
alpha <- pars.general[2:(1 + p.true)]
gamma <- pars.general[(p + q + 2):(2 * p + q + 1) ]
}
if (q.true > 0) {
beta <- pars.general[(p.true + 2):(1 + p.true + q.true)]
}
df <- pars.general[[2 * p.true + q.true + 2]]
eps.in <- zeta.in / c.sig
mae <- mean(abs(eps.in))
eps <- c(tail(eps.in, n = l), rep(NA, n.out ))
lnsig2 <- c(log(tail(c.sig, n = l)^2), rep(NA, n.out))
sig.fc <- rep(NA, n.out)
for (i in (1 + l):(n.out + l)) {
lnsig2[i] <- omega + alpha %*% eps[(i - 1):(i - p)] +
gamma %*% (abs(eps[(i - 1):(i - p)]) - mae) +
beta %*% lnsig2[(i - 1):(i - q)]
sig.fc[i - l] <- exp(0.5 * lnsig2[i])
eps[i] <- zeta.fc[i] / sig.fc[i - l]
}
sig.fc <- sig.fc * sfc
},
apARCH = {
pars.general <- unname(rugarch::coef(model_fit))
omega <- pars.general[[1]]
gamma <- 0
if (p.true > 0) {
alpha <- pars.general[2:(1 + p.true)]
gamma <- pars.general[(p + q + 2):(2 * p + q + 1) ]
}
if (q.true > 0) {
beta <- pars.general[(p.true + 2):(1 + p.true + q.true)]
}
d1 <- pars.general[[2 * p.true + q.true + 2]]
df <- pars.general[[2 * p.true + q.true + 3]]
sig.d <- c(tail(c.sig, n = l)^d1, rep(NA, times = n.out))
for (i in (1 + l):(n.out + l)) {
sig.d[i] <- omega + alpha %*% (abs(zeta.fc[(i - 1):(i - p)]) -
gamma * zeta.fc[(i - 1):(i - p)])^d1 +
beta %*% sig.d[(i - 1):(i - q)]
}
sig.fc <- sig.d[(1 + l):(n.out + l)]^(1 / d1) * sfc
},
fiGARCH = {
pars.general <- unname(rugarch::coef(model_fit))
omega <- pars.general[[1]]
if (p.true > 0) {
alpha <- pars.general[2:(1 + p.true)]
}
if (q.true > 0) {
beta <- pars.general[(p.true + 2):(1 + p.true + q.true)]
}
d <- pars.general[[p.true + q.true + 2]]
df <- pars.general[[p.true + q.true + 3]]
zeta.all <- c(zeta.in, zeta.out)
k <- n.in
coef.all <- arfilt(ar = alpha, ma = beta, d = d, k = k)
vol.fc <- omega / (1 - sum(beta)) +
sum(coef.all * zeta.all[n.in:(n.in - k + 1)]^2)
sig.fc <- c(sqrt(vol.fc), rep(0, (n.out - 1)))
for (i in 2:n.out) {
vol.fc <- omega / (1 - sum(beta)) +
sum(coef.all * zeta.all[(n.in + i - 1):(n.in + i - k)]^2)
sig.fc[i] <- sqrt(vol.fc)
}
sig.fc <- sig.fc * sfc
}
)
sdev <- sqrt(df / (df - 2))
VaR.fc <- -mean.ret.in + sig.fc * qt(a.v, df)/sdev
VaR.e.fc <- -mean.ret.in + sig.fc * qt(a.e, df)/sdev
ES0 <- dt(qt(a.e, df), df)/(1 - a.e) * (df + qt(a.e, df)^2)/(df - 1)/sdev
Esfc <- -mean.ret.in + sig.fc * ES0
if (smooth == "lpr") {
model <- paste0("Semi-", model)
}
results <- list(model = model, mean = mean.ret.in,
model.fit = model_fit, ret.in = ret.in.t,
ret.out = ret.out.t, sig.in = sig.in,
sig.fc = sig.fc, scale = sxt, scale.fc = sfc, VaR.e = VaR.e.fc,
VaR.v = VaR.fc, ES = Esfc, df = df, a.v = 1 - a.v, a.e = 1 - a.e,
garchOrder = garchOrder, np.est = np.est)
class(results) <- "ufRisk"
attr(results, "function") <- "varcast"
results
} |
fillUpDecimals <- function(numVec, howManyToFill=NULL, fill = "0"){
numStr = as.character(numVec)
noWholeNum = gsub("^[-+ ]*[0-9a-zA-Z]*$", "", numStr, perl=TRUE)
decimChar = gsub("^[-+ ]*[0-9a-zA-Z]*\\.", "", noWholeNum)
if(is.null(howManyToFill)){
howManyToFill = max(nchar(decimChar[!is.na(decimChar)]))
}
if(howManyToFill != 0){
numToFill = pmax(0, howManyToFill - nchar(decimChar))
fills = sapply(numToFill, function(x) {if(is.na(x)) "" else paste(rep(fill, x), collapse="")} )
dPoints = sapply(nchar(noWholeNum), function(x){if(!is.na(x) & x==0) "." else ""})
res = paste(numStr, dPoints, fills, sep="")
res[res == "NA"] = NA
}else{
res = numStr
}
res
} |
wm_records_common <- function(name, fuzzy = FALSE, offset = 1,
...) {
assert(name, "character")
assert(fuzzy, "logical")
assert(offset, c('numeric', 'integer'))
assert_len(name, 1)
if (length(name) > 1) stop("'name' must be of length 1", call. = FALSE)
args <- cc(list(
like = as_log(fuzzy),
offset = offset
))
wm_GET(file.path(wm_base(), "AphiaRecordsByVernacular", name),
query = args, ...)
}
wm_records_common_ <- function(name, fuzzy = FALSE, offset = 1, ...) {
run_bind(name, wm_records_common, fuzzy = fuzzy, offset = offset,
on_error = warning, ...)
} |
context(".monoisotopic")
test_that(".pseudoCluster", {
x <- c(1, 2, 3, 5, 8, 9, 10, 12, 15)
m1s2 <- matrix(c(1, 2, 2, 3, 5, 6, 6, 7), nrow=2)
m1s3 <- matrix(c(1, 2, 3, 5, 6, 7), nrow=3)
m3s3 <- matrix(c(2, 4, 5, 6, 8, 9), nrow=3)
m5s4 <- matrix(NA_real_, nrow=4, ncol=0)
m12s3 <- matrix(c(1:3, 5:7, 1, 3, 4, 5, 7, 8), nrow=3)
expect_error(MALDIquant:::.pseudoCluster(x, size=1),
"The .*size.* of a cluster has to be at least 2")
expect_equal(MALDIquant:::.pseudoCluster(x, size=2, distance=1), m1s2)
expect_equal(MALDIquant:::.pseudoCluster(x, size=3, distance=1), m1s3)
expect_equal(MALDIquant:::.pseudoCluster(x, size=3, distance=3), m3s3)
expect_equal(MALDIquant:::.pseudoCluster(x, size=4, distance=5), m5s4)
expect_equal(MALDIquant:::.pseudoCluster(x, size=3, distance=1:2), m12s3)
})
test_that(".F", {
x <- seq(1000, 5000, by=10)
expect_equal(MALDIquant:::.F(x), 0.000594 * x + 0.03091)
})
test_that(".P", {
x <- seq(1000, 5000, by=10)
expect_equal(MALDIquant:::.P(x, 0:3), dpois(0:3, MALDIquant:::.F(x)))
})
test_that(".Psum", {
x <- c(1000, 2000)
isotopes <- 0:3
p <- sapply(x, function(xx) {
pp <- MALDIquant:::.P(xx, isotopes=isotopes)
pp/sum(pp)
})
expect_equal(MALDIquant:::.Psum(x, isotopes), p)
})
test_that(".monoisotopicPattern", {
x <- c(1, 2, 3, 5, 8, 9, 10, 12, 15)
y <- c(96, 3, 1, 5, 78, 20, 2, 12, 15)
expect_equal(MALDIquant:::.monoisotopicPattern(1:10, 1:10),
matrix(NA_real_, nrow=3, ncol=0))
expect_equal(MALDIquant:::.monoisotopicPattern(x, y, distance=1, size=3),
cbind(1:3, 5:7))
expect_equal(MALDIquant:::.monoisotopicPattern(x, y, distance=1:2, size=3),
cbind(1:3, 5:7))
expect_equal(MALDIquant:::.monoisotopicPattern(x, y, distance=2:1, size=3),
cbind(c(1, 3, 4), c(5, 7, 8)))
expect_equal(MALDIquant:::.monoisotopicPattern(x, y, distance=1, size=2),
cbind(1:2, 5:6))
expect_equal(MALDIquant:::.monoisotopicPattern(x, y, distance=1, minCor=0.99), as.matrix(1:3))
})
test_that(".monoisotopic", {
x <- c(1, 2, 3, 5, 8, 9, 10, 12, 15)
y <- c(96, 3, 1, 5, 78, 20, 2, 12, 15)
expect_equal(MALDIquant:::.monoisotopic(double(), double()), numeric())
expect_equal(MALDIquant:::.monoisotopic(1:10, 1:5), numeric())
expect_equal(MALDIquant:::.monoisotopic(1:10, 1:10), numeric())
expect_equal(MALDIquant:::.monoisotopic(x, y, distance=1, size=2:5), c(1, 5))
expect_equal(MALDIquant:::.monoisotopic(x, y, distance=1, minCor=0.99), 1)
}) |
context("qtl2")
test_that("fst_genoprob works with qtl2 functions", {
library(qtl2)
iron <- read_cross2(system.file("extdata", "iron.zip", package="qtl2"))
iron <- iron[,c(18,19,"X")]
map <- insert_pseudomarkers(iron$gmap, step=1)
probs <- calc_genoprob(iron, map, error_prob=0.002)
dir <- tempdir()
fprobs <- fst_genoprob(probs, "iron_probs", dir)
expect_equal(fprobs[["18"]], probs[["18"]])
expect_equal(fprobs[[1]], probs[["18"]])
expect_equal(fprobs[["X"]], probs[["X"]])
expect_equal(fprobs[[3]], probs[["X"]])
expect_equal(calc_kinship(probs), calc_kinship(fprobs))
expect_equal(calc_kinship(probs, "loco"), calc_kinship(fprobs, "loco"))
expect_equal(calc_kinship(probs, "chr"), calc_kinship(fprobs, "chr"))
expect_equal(genoprob_to_alleleprob(probs), genoprob_to_alleleprob(fprobs))
grid <- calc_grid(iron$gmap, step=1)
expect_equal(probs_to_grid(probs, grid), probs_to_grid(fprobs, grid))
seed <- 47220527
set.seed(seed)
imp <- maxmarg(probs)
set.seed(seed)
fimp <- maxmarg(fprobs)
expect_equal(imp, fimp)
set.seed(seed)
imp <- maxmarg(probs, map, chr="19", pos=10.3)
set.seed(seed)
fimp <- maxmarg(fprobs, map, chr="19", pos=10.3)
expect_equal(imp, fimp)
set.seed(seed)
imp <- maxmarg(probs, map, chr="19", pos=10.3, return_char=TRUE)
set.seed(seed)
fimp <- maxmarg(fprobs, map, chr="19", pos=10.3, return_char=TRUE)
expect_equal(imp, fimp)
set.seed(seed)
imp <- maxmarg(probs, map, chr="X", pos=57.9)
set.seed(seed)
fimp <- maxmarg(fprobs, map, chr="X", pos=57.9)
expect_equal(imp, fimp)
set.seed(seed)
imp <- maxmarg(probs, map, chr="X", pos=57.9, return_char=TRUE)
set.seed(seed)
fimp <- maxmarg(fprobs, map, chr="X", pos=57.9, return_char=TRUE)
expect_equal(imp, fimp)
set.seed(seed)
imp <- maxmarg(probs[19])
set.seed(seed)
fimp <- maxmarg(fprobs[19])
expect_equal(imp, fimp)
set.seed(seed)
imp <- maxmarg(probs[,"X"])
set.seed(seed)
fimp <- maxmarg(fprobs[,"X"])
expect_equal(imp, fimp)
Xcovar <- get_x_covar(iron)
sex <- Xcovar[,"sex",drop=FALSE]
expect_equal(scan1(probs, iron$pheno, Xcovar=Xcovar),
scan1(fprobs, iron$pheno, Xcovar=Xcovar))
expect_equal(scan1(probs, iron$pheno, Xcovar=Xcovar, addcovar=sex),
scan1(fprobs, iron$pheno, Xcovar=Xcovar, addcovar=sex))
expect_equal(scan1(probs, iron$pheno, Xcovar=Xcovar, addcovar=sex, intcovar=sex),
scan1(fprobs, iron$pheno, Xcovar=Xcovar, addcovar=sex, intcovar=sex))
k <- calc_kinship(probs)
fk <- calc_kinship(fprobs)
expect_equal(scan1(probs, iron$pheno, k, Xcovar=Xcovar),
scan1(fprobs, iron$pheno, fk, Xcovar=Xcovar))
expect_equal(scan1(probs, iron$pheno, k, Xcovar=Xcovar, addcovar=sex),
scan1(fprobs, iron$pheno, fk, Xcovar=Xcovar, addcovar=sex))
expect_equal(scan1(probs, iron$pheno, k, Xcovar=Xcovar, addcovar=sex, intcovar=sex),
scan1(fprobs, iron$pheno, fk, Xcovar=Xcovar, addcovar=sex, intcovar=sex))
k <- calc_kinship(probs, "loco")
fk <- calc_kinship(fprobs, "loco")
expect_equal(scan1(probs, iron$pheno, k, Xcovar=Xcovar),
scan1(fprobs, iron$pheno, fk, Xcovar=Xcovar))
expect_equal(scan1(probs, iron$pheno, k, Xcovar=Xcovar, addcovar=sex),
scan1(fprobs, iron$pheno, fk, Xcovar=Xcovar, addcovar=sex))
expect_equal(scan1(probs, iron$pheno, k, Xcovar=Xcovar, addcovar=sex, intcovar=sex),
scan1(fprobs, iron$pheno, fk, Xcovar=Xcovar, addcovar=sex, intcovar=sex))
phe <- iron$pheno[,1,drop=FALSE]
expect_equal(scan1coef(subset(probs, chr="18"), phe, addcovar=sex),
scan1coef(subset(fprobs, chr="18"), phe, addcovar=sex))
expect_equal(scan1coef(subset(probs, chr="X"), phe, addcovar=Xcovar),
scan1coef(subset(fprobs, chr="X"), phe, addcovar=Xcovar))
phe <- iron$pheno[,1,drop=FALSE]
expect_equal(scan1coef(subset(probs, chr="18"), phe, k[["18"]], addcovar=sex),
scan1coef(subset(fprobs, chr="18"), phe, fk[["18"]], addcovar=sex))
expect_equal(scan1coef(subset(probs, chr="X"), phe, k[["X"]], addcovar=Xcovar),
scan1coef(subset(fprobs, chr="X"), phe, fk[["X"]], addcovar=Xcovar))
expect_equal(scan1blup(subset(probs, chr="18"), phe, addcovar=sex),
scan1blup(subset(fprobs, chr="18"), phe, addcovar=sex))
expect_equal(scan1blup(subset(probs, chr="X"), phe, addcovar=Xcovar),
scan1blup(subset(fprobs, chr="X"), phe, addcovar=Xcovar))
expect_equal(scan1blup(subset(probs, chr="18"), phe, k[["18"]], addcovar=sex),
scan1blup(subset(fprobs, chr="18"), phe, fk[["18"]], addcovar=sex))
expect_equal(scan1blup(subset(probs, chr="X"), phe, k[["X"]], addcovar=Xcovar),
scan1blup(subset(fprobs, chr="X"), phe, fk[["X"]], addcovar=Xcovar))
n_perm <- 3
seed <- 65418959
set.seed(seed)
operm <- scan1perm(probs, phe, n_perm=n_perm)
set.seed(seed)
foperm <- scan1perm(fprobs, phe, n_perm=n_perm)
expect_equal(operm, foperm)
set.seed(seed)
operm <- scan1perm(probs, iron$pheno, n_perm=n_perm, addcovar=sex)
set.seed(seed)
foperm <- scan1perm(fprobs, iron$pheno, n_perm=n_perm, addcovar=sex)
expect_equal(operm, foperm)
set.seed(seed)
operm <- scan1perm(probs, iron$pheno, n_perm=n_perm, addcovar=sex, Xcovar=Xcovar,
perm_Xsp=TRUE, chr_lengths=chr_lengths(map))
set.seed(seed)
foperm <- scan1perm(fprobs, iron$pheno, n_perm=n_perm, addcovar=sex, Xcovar=Xcovar,
perm_Xsp=TRUE, chr_lengths=chr_lengths(map))
expect_equal(operm, foperm)
set.seed(seed)
operm <- scan1perm(probs, iron$pheno, k, n_perm=n_perm, addcovar=sex)
set.seed(seed)
foperm <- scan1perm(fprobs, iron$pheno, fk, n_perm=n_perm, addcovar=sex)
expect_equal(operm, foperm)
set.seed(seed)
operm <- scan1perm(probs, iron$pheno, k, n_perm=n_perm, addcovar=sex,
perm_Xsp=TRUE, chr_lengths=chr_lengths(map))
set.seed(seed)
foperm <- scan1perm(fprobs, iron$pheno, fk, n_perm=n_perm, addcovar=sex,
perm_Xsp=TRUE, chr_lengths=chr_lengths(map))
expect_equal(operm, foperm)
unlink(fst_files(fprobs))
}) |
lambda0=function(x,y,weights=rep(1,N),exclude=NULL){
if(length(exclude))x=x[,-exclude]
N=length(y)
ybar=weighted.mean(y,weights)
yvar=weighted.mean((y-ybar)^2,weights)
y=(y-ybar)/sqrt(yvar)
weights=weights/N
xbar=t(weights)%*%x
xvar=t(weights)%*%(x^2)-xbar^2
grad= abs(t(y*weights)%*%x)/sqrt(xvar)
max(grad)
} |
test_that("SetHITTypeNotification", {
skip_if_not(CheckAWSKeys())
hittype <- RegisterHITType(title="10 Question Survey",
description = "Complete a 10-question survey",
reward = ".20",
duration = seconds(hours = 1),
keywords = "survey, questionnaire, politics")
a <- GenerateNotification("[email protected]", event.type = "HITExpired")
SetHITTypeNotification(hit.type = hittype$HITTypeId,
notification = a,
active = TRUE)
SendTestEventNotification(a, test.event.type = "HITExpired") -> result
expect_type(result, "list")
try(SendTestEventNotification(a, test.event.type = "X"), TRUE) -> result
}) |
CatDynBSD <-
function(x,method,multi,mbw.sd)
{
if(multi)
{
if(class(x)!="catdyn")
{
stop("In multi-annual models 'x' must be a single object of class 'catdyn' run at monthly time steps")
}
if(x$Data$Properties$Units[3] == "ind")
{
stop("This function is used to calculate standard deviation of annual biomass when the catch is recorded in weight")
}
if(x$Data$Properties$Units["Time Step"]!="month")
{
stop("In multi-annual models 'x' must be a single object of class 'catdyn' run at monthly time steps")
}
Thou.scaler <- 1e6*(x$Data$Properties$Units[4]=="bill") +
1e3*(x$Data$Properties$Units[4]=="mill") +
1e0*(x$Data$Properties$Units[4]=="thou") +
1e-1*(x$Data$Properties$Units[4]=="hund")
PopDyn <- data.frame(M=x$Model[[method]]$bt.par$M,
SE.M=x$Model[[method]]$bt.stdev["M"],
N0=Thou.scaler*x$Model[[method]]$bt.par$N0,
SE.N0=Thou.scaler*x$Model[[method]]$bt.stdev["N0"])
if(is.na(PopDyn[2]))
{
PopDyn[2] <- PopDyn[1]*mean(unlist(x$Model[[method]]$bt.stdev[which(!is.na(x$Model[[method]]$bt.stdev))])/
unlist(x$Model[[method]]$bt.par[which(!is.na(x$Model[[method]]$bt.stdev))]))
}
if(is.na(PopDyn[4]))
{
PopDyn[4] <- PopDyn[3]*mean(unlist(x$Model[[method]]$bt.stdev[which(!is.na(x$Model[[method]]$bt.stdev))])/
unlist(x$Model[[method]]$bt.par[which(!is.na(x$Model[[method]]$bt.stdev))]))
}
Perts <- data.frame(Pest=unlist(x$Model[[method]]$bt.par[grep("P",names(x$Model[[method]]$bt.par))])*Thou.scaler,
SE.Pest=unlist(x$Model[[method]]$bt.stdev[grep("P.",names(x$Model[[method]]$bt.par))])*Thou.scaler,
tsteps=x$Model[[method]]$Dates[grep("ts.P",names(x$Model[[method]]$Dates))])
if(any(is.na(Perts$SE.Pest)))
{
Perts$SE.Pest[which(is.na(Perts$SE.Pest))] <- Perts$Pest[which(is.na(Perts$SE.Pest))]*mean(Perts$SE.Pest[which(!is.na(Perts$SE.Pest))]/Perts$Pest[which(!is.na(Perts$SE.Pest))])
}
if(length(x$Data$Properties$Fleets$Fleet)==1)
{
mt <- x$Model[[method]]$Type
Timing <- matrix(0,12*mt,1)
Timing[1:12] <- ifelse(row(Timing)[1:12] >= Perts$tsteps[1],1,0)
Timing[13:24] <- ifelse(row(Timing)[13:24] >= Perts$tsteps[2],1,0)
Timing[25:36] <- ifelse(row(Timing)[25:36] >= Perts$tsteps[3],1,0)
Timing[37:48] <- ifelse(row(Timing)[37:48] >= Perts$tsteps[4],1,0)
Timing[49:60] <- ifelse(row(Timing)[49:60] >= Perts$tsteps[5],1,0)
Timing[61:72] <- ifelse(row(Timing)[61:72] >= Perts$tsteps[6],1,0)
Timing[73:84] <- ifelse(row(Timing)[73:84] >= Perts$tsteps[7],1,0)
Timing[85:96] <- ifelse(row(Timing)[85:96] >= Perts$tsteps[8],1,0)
Timing[97:108] <- ifelse(row(Timing)[97:108] >= Perts$tsteps[9],1,0)
Timing[109:120] <- ifelse(row(Timing)[109:120] >= Perts$tsteps[10],1,0)
Timing[121:132] <- ifelse(row(Timing)[121:132] >= Perts$tsteps[11],1,0)
Timing[133:144] <- ifelse(row(Timing)[133:144] >= Perts$tsteps[12],1,0)
Timing[145:156] <- ifelse(row(Timing)[145:156] >= Perts$tsteps[13],1,0)
Timing[157:168] <- ifelse(row(Timing)[157:168] >= Perts$tsteps[14],1,0)
Timing[169:180] <- ifelse(row(Timing)[169:180] >= Perts$tsteps[15],1,0)
fleet1 <- x$Data$Properties$Fleets[1,1]
if(mt <= 14)
{
stop("This function is intended to be used to calculate the standard deviation of annual biomass \n to fit a biomass dynamic model from the output of a multi-annual generalized depletion model (MAGD) \n with the catch recorded in biomass. At least 15 years of data must have been used in fitting \n the MAGD for its outputs to be used in this manner.")
}
Cov.Mat <- cor2cov(cor.mat=x$Model[[method]]$Cor[c(1:(mt+2)),
c(1:(mt+2))],
sd=c(PopDyn$SE.M,PopDyn$SE.N0,Perts$SE.Pest))
if(length(mbw.sd) != 12 & length(mbw.sd) != 12*mt)
{stop("mbw.sd must be a vector of length 12 (monthly mean weight) or 12*number of years (in kg)")}
yr1 <- as.numeric(format(as.Date(x$Data$Properties$Dates[1]),"%Y"))
yr2 <- as.numeric(format(as.Date(x$Data$Properties$Dates[2]),"%Y"))
z <- CatDynPred(x,method)
PredStock <- data.frame(Year=sort(rep(yr1:yr2,12)),
Month=c("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"),
TimeStep=1:((yr2-yr1+1)*12),
Mmw.kg=x$Data$Data[[fleet1]]$obsmbw.kg,
SDmw.kg=mbw.sd,
N.thou=z$Model$Results[,10],
N.thou.SE=0,
B.ton=z$Model$Results[,11],
B.ton.SE=0)
for(m in 1:12)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PopDyn$N0,Timing[m]*Perts$Pest[1]),
cov=Cov.Mat[c(1:3),c(1:3)])
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
for(m in 13:24)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[12],Timing[m]*Perts$Pest[2]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,4],
0,PredStock$N.thou.SE[12]^2,0,
Cov.Mat[4,1],0,Cov.Mat[4,4]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
for(m in 25:36)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[24],Timing[m]*Perts$Pest[3]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,5],
0,PredStock$N.thou.SE[24]^2,0,
Cov.Mat[5,1],0,Cov.Mat[5,5]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
for(m in 37:48)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[36],Timing[m]*Perts$Pest[4]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,6],
0,PredStock$N.thou.SE[36]^2,0,
Cov.Mat[6,1],0,Cov.Mat[6,6]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
for(m in 49:60)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[48],Timing[m]*Perts$Pest[5]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,7],
0,PredStock$N.thou.SE[48]^2,0,
Cov.Mat[7,1],0,Cov.Mat[7,7]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
for(m in 61:72)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[60],Timing[m]*Perts$Pest[6]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,8],
0,PredStock$N.thou.SE[60]^2,0,
Cov.Mat[8,1],0,Cov.Mat[8,8]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
for(m in 73:84)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[72],Timing[m]*Perts$Pest[7]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,9],
0,PredStock$N.thou.SE[72]^2,0,
Cov.Mat[9,1],0,Cov.Mat[9,9]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
for(m in 85:96)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[84],Timing[m]*Perts$Pest[8]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,10],
0,PredStock$N.thou.SE[84]^2,0,
Cov.Mat[10,1],0,Cov.Mat[10,10]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
for(m in 97:108)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[96],Timing[m]*Perts$Pest[9]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,11],
0,PredStock$N.thou.SE[96]^2,0,
Cov.Mat[11,1],0,Cov.Mat[11,11]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
for(m in 109:120)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[108],Timing[m]*Perts$Pest[10]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,12],
0,PredStock$N.thou.SE[108]^2,0,
Cov.Mat[12,1],0,Cov.Mat[12,12]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
for(m in 121:132)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[120],Timing[m,1]*Perts$Pest[11]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,13],
0,PredStock$N.thou.SE[120]^2,0,
Cov.Mat[13,1],0,Cov.Mat[13,13]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
for(m in 133:144)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[132],Timing[m]*Perts$Pest[12]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,14],
0,PredStock$N.thou.SE[132]^2,0,
Cov.Mat[14,1],0,Cov.Mat[14,14]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
for(m in 145:156)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[144],Timing[m]*Perts$Pest[13]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,15],
0,PredStock$N.thou.SE[144]^2,0,
Cov.Mat[15,1],0,Cov.Mat[15,15]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
for(m in 157:168)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[156],Timing[m]*Perts$Pest[14]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,16],
0,PredStock$N.thou.SE[156]^2,0,
Cov.Mat[16,1],0,Cov.Mat[16,16]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
for(m in 169:180)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[168],Timing[m]*Perts$Pest[15]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,17],
0,PredStock$N.thou.SE[168]^2,0,
Cov.Mat[17,1],0,Cov.Mat[17,17]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
if(mt == 16)
{
Timing[181:192] <- ifelse(row(Timing)[181:192] >= Perts$tsteps[16],1,0)
for(m in 181:192)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[180],Timing[m]*Perts$Pest[16]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,18],
0,PredStock$N.thou.SE[180]^2,0,
Cov.Mat[18,1],0,Cov.Mat[18,18]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
}
if(mt == 17)
{
Timing[181:192] <- ifelse(row(Timing)[181:192] >= Perts$tsteps[16],1,0)
for(m in 181:192)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[180],Timing[m]*Perts$Pest[16]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,18],
0,PredStock$N.thou.SE[180]^2,0,
Cov.Mat[18,1],0,Cov.Mat[18,18]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[193:204] <- ifelse(row(Timing)[193:204] >= Perts$tsteps[17],1,0)
for(m in 193:204)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[192],Timing[m]*Perts$Pest[17]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,19],
0,PredStock$N.thou.SE[192]^2,0,
Cov.Mat[19,1],0,Cov.Mat[19,19]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
}
if(mt == 18)
{
Timing[181:192] <- ifelse(row(Timing)[181:192] >= Perts$tsteps[16],1,0)
for(m in 181:192)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[180],Timing[m]*Perts$Pest[16]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,18],
0,PredStock$N.thou.SE[180]^2,0,
Cov.Mat[18,1],0,Cov.Mat[18,18]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[193:204] <- ifelse(row(Timing)[193:204] >= Perts$tsteps[17],1,0)
for(m in 193:204)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[192],Timing[m]*Perts$Pest[17]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,19],
0,PredStock$N.thou.SE[192]^2,0,
Cov.Mat[19,1],0,Cov.Mat[19,19]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[205:216] <- ifelse(row(Timing)[205:216] >= Perts$tsteps[18],1,0)
for(m in 205:216)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[204],Timing[m]*Perts$Pest[18]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,20],
0,PredStock$N.thou.SE[204]^2,0,
Cov.Mat[20,1],0,Cov.Mat[20,20]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
}
if(mt == 19)
{
Timing[181:192] <- ifelse(row(Timing)[181:192] >= Perts$tsteps[16],1,0)
for(m in 181:192)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[180],Timing[m]*Perts$Pest[16]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,18],
0,PredStock$N.thou.SE[180]^2,0,
Cov.Mat[18,1],0,Cov.Mat[18,18]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[193:204] <- ifelse(row(Timing)[193:204] >= Perts$tsteps[17],1,0)
for(m in 193:204)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[192],Timing[m]*Perts$Pest[17]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,19],
0,PredStock$N.thou.SE[192]^2,0,
Cov.Mat[19,1],0,Cov.Mat[19,19]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[205:216] <- ifelse(row(Timing)[205:216] >= Perts$tsteps[18],1,0)
for(m in 205:216)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[204],Timing[m]*Perts$Pest[18]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,20],
0,PredStock$N.thou.SE[204]^2,0,
Cov.Mat[20,1],0,Cov.Mat[20,20]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[217:228] <- ifelse(row(Timing)[217:228] >= Perts$tsteps[19],1,0)
for(m in 217:228)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[216],Timing[m]*Perts$Pest[19]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,21],
0,PredStock$N.thou.SE[216]^2,0,
Cov.Mat[21,1],0,Cov.Mat[21,21]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
}
if(mt == 20)
{
Timing[181:192] <- ifelse(row(Timing)[181:192] >= Perts$tsteps[16],1,0)
for(m in 181:192)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[180],Timing[m]*Perts$Pest[16]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,18],
0,PredStock$N.thou.SE[180]^2,0,
Cov.Mat[18,1],0,Cov.Mat[18,18]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[193:204] <- ifelse(row(Timing)[193:204] >= Perts$tsteps[17],1,0)
for(m in 193:204)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[192],Timing[m]*Perts$Pest[17]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,19],
0,PredStock$N.thou.SE[192]^2,0,
Cov.Mat[19,1],0,Cov.Mat[19,19]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[205:216] <- ifelse(row(Timing)[205:216] >= Perts$tsteps[18],1,0)
for(m in 205:216)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[204],Timing[m]*Perts$Pest[18]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,20],
0,PredStock$N.thou.SE[204]^2,0,
Cov.Mat[20,1],0,Cov.Mat[20,20]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[217:228] <- ifelse(row(Timing)[217:228] >= Perts$tsteps[19],1,0)
for(m in 217:228)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[216],Timing[m]*Perts$Pest[19]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,21],
0,PredStock$N.thou.SE[216]^2,0,
Cov.Mat[21,1],0,Cov.Mat[21,21]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[229:240] <- ifelse(row(Timing)[229:240] >= Perts$tsteps[20],1,0)
for(m in 229:240)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[228],Timing[m]*Perts$Pest[20]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,22],
0,PredStock$N.thou.SE[228]^2,0,
Cov.Mat[22,1],0,Cov.Mat[22,22]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
}
if(mt == 21)
{
Timing[181:192] <- ifelse(row(Timing)[181:192] >= Perts$tsteps[16],1,0)
for(m in 181:192)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[180],Timing[m]*Perts$Pest[16]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,18],
0,PredStock$N.thou.SE[180]^2,0,
Cov.Mat[18,1],0,Cov.Mat[18,18]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[193:204] <- ifelse(row(Timing)[193:204] >= Perts$tsteps[17],1,0)
for(m in 193:204)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[192],Timing[m]*Perts$Pest[17]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,19],
0,PredStock$N.thou.SE[192]^2,0,
Cov.Mat[19,1],0,Cov.Mat[19,19]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[205:216] <- ifelse(row(Timing)[205:216] >= Perts$tsteps[18],1,0)
for(m in 205:216)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[204],Timing[m]*Perts$Pest[18]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,20],
0,PredStock$N.thou.SE[204]^2,0,
Cov.Mat[20,1],0,Cov.Mat[20,20]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[217:228] <- ifelse(row(Timing)[217:228] >= Perts$tsteps[19],1,0)
for(m in 217:228)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[216],Timing[m]*Perts$Pest[19]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,21],
0,PredStock$N.thou.SE[216]^2,0,
Cov.Mat[21,1],0,Cov.Mat[21,21]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[229:240] <- ifelse(row(Timing)[229:240] >= Perts$tsteps[20],1,0)
for(m in 229:240)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[228],Timing[m]*Perts$Pest[20]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,22],
0,PredStock$N.thou.SE[228]^2,0,
Cov.Mat[22,1],0,Cov.Mat[22,22]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[241:252] <- ifelse(row(Timing)[241:252] >= Perts$tsteps[21],1,0)
for(m in 241:252)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[240],Timing[m]*Perts$Pest[21]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,23],
0,PredStock$N.thou.SE[240]^2,0,
Cov.Mat[23,1],0,Cov.Mat[23,23]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
}
if(mt == 22)
{
Timing[181:192] <- ifelse(row(Timing)[181:192] >= Perts$tsteps[16],1,0)
for(m in 181:192)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[180],Timing[m]*Perts$Pest[16]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,18],
0,PredStock$N.thou.SE[180]^2,0,
Cov.Mat[18,1],0,Cov.Mat[18,18]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[193:204] <- ifelse(row(Timing)[193:204] >= Perts$tsteps[17],1,0)
for(m in 193:204)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[192],Timing[m]*Perts$Pest[17]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,19],
0,PredStock$N.thou.SE[192]^2,0,
Cov.Mat[19,1],0,Cov.Mat[19,19]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[205:216] <- ifelse(row(Timing)[205:216] >= Perts$tsteps[18],1,0)
for(m in 205:216)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[204],Timing[m]*Perts$Pest[18]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,20],
0,PredStock$N.thou.SE[204]^2,0,
Cov.Mat[20,1],0,Cov.Mat[20,20]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[217:228] <- ifelse(row(Timing)[217:228] >= Perts$tsteps[19],1,0)
for(m in 217:228)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[216],Timing[m]*Perts$Pest[19]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,21],
0,PredStock$N.thou.SE[216]^2,0,
Cov.Mat[21,1],0,Cov.Mat[21,21]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[229:240] <- ifelse(row(Timing)[229:240] >= Perts$tsteps[20],1,0)
for(m in 229:240)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[228],Timing[m]*Perts$Pest[20]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,22],
0,PredStock$N.thou.SE[228]^2,0,
Cov.Mat[22,1],0,Cov.Mat[22,22]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[241:252] <- ifelse(row(Timing)[241:252] >= Perts$tsteps[21],1,0)
for(m in 241:252)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[240],Timing[m]*Perts$Pest[21]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,23],
0,PredStock$N.thou.SE[240]^2,0,
Cov.Mat[23,1],0,Cov.Mat[23,23]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[253:264] <- ifelse(row(Timing)[253:264] >= Perts$tsteps[22],1,0)
for(m in 253:264)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[252],Timing[m]*Perts$Pest[22]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,24],
0,PredStock$N.thou.SE[252]^2,0,
Cov.Mat[24,1],0,Cov.Mat[24,24]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
}
if(mt == 23)
{
Timing[181:192] <- ifelse(row(Timing)[181:192] >= Perts$tsteps[16],1,0)
for(m in 181:192)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[180],Timing[m]*Perts$Pest[16]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,18],
0,PredStock$N.thou.SE[180]^2,0,
Cov.Mat[18,1],0,Cov.Mat[18,18]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[193:204] <- ifelse(row(Timing)[193:204] >= Perts$tsteps[17],1,0)
for(m in 193:204)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[192],Timing[m]*Perts$Pest[17]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,19],
0,PredStock$N.thou.SE[192]^2,0,
Cov.Mat[19,1],0,Cov.Mat[19,19]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[205:216] <- ifelse(row(Timing)[205:216] >= Perts$tsteps[18],1,0)
for(m in 205:216)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[204],Timing[m]*Perts$Pest[18]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,20],
0,PredStock$N.thou.SE[204]^2,0,
Cov.Mat[20,1],0,Cov.Mat[20,20]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[217:228] <- ifelse(row(Timing)[217:228] >= Perts$tsteps[19],1,0)
for(m in 217:228)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[216],Timing[m]*Perts$Pest[19]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,21],
0,PredStock$N.thou.SE[216]^2,0,
Cov.Mat[21,1],0,Cov.Mat[21,21]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[229:240] <- ifelse(row(Timing)[229:240] >= Perts$tsteps[20],1,0)
for(m in 229:240)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[228],Timing[m]*Perts$Pest[20]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,22],
0,PredStock$N.thou.SE[228]^2,0,
Cov.Mat[22,1],0,Cov.Mat[22,22]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[241:252] <- ifelse(row(Timing)[241:252] >= Perts$tsteps[21],1,0)
for(m in 241:252)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[240],Timing[m]*Perts$Pest[21]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,23],
0,PredStock$N.thou.SE[240]^2,0,
Cov.Mat[23,1],0,Cov.Mat[23,23]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[253:264] <- ifelse(row(Timing)[253:264] >= Perts$tsteps[22],1,0)
for(m in 253:264)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[252],Timing[m]*Perts$Pest[22]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,24],
0,PredStock$N.thou.SE[252]^2,0,
Cov.Mat[24,1],0,Cov.Mat[24,24]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[265:276] <- ifelse(row(Timing)[265:276] >= Perts$tsteps[23],1,0)
for(m in 265:276)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[264],Timing[m]*Perts$Pest[23]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,25],
0,PredStock$N.thou.SE[264]^2,0,
Cov.Mat[25,1],0,Cov.Mat[25,25]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
}
if(mt == 24)
{
Timing[181:192] <- ifelse(row(Timing)[181:192] >= Perts$tsteps[16],1,0)
for(m in 181:192)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[180],Timing[m]*Perts$Pest[16]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,18],
0,PredStock$N.thou.SE[180]^2,0,
Cov.Mat[18,1],0,Cov.Mat[18,18]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[193:204] <- ifelse(row(Timing)[193:204] >= Perts$tsteps[17],1,0)
for(m in 193:204)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[192],Timing[m]*Perts$Pest[17]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,19],
0,PredStock$N.thou.SE[192]^2,0,
Cov.Mat[19,1],0,Cov.Mat[19,19]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[205:216] <- ifelse(row(Timing)[205:216] >= Perts$tsteps[18],1,0)
for(m in 205:216)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[204],Timing[m]*Perts$Pest[18]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,20],
0,PredStock$N.thou.SE[204]^2,0,
Cov.Mat[20,1],0,Cov.Mat[20,20]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[217:228] <- ifelse(row(Timing)[217:228] >= Perts$tsteps[19],1,0)
for(m in 217:228)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[216],Timing[m]*Perts$Pest[19]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,21],
0,PredStock$N.thou.SE[216]^2,0,
Cov.Mat[21,1],0,Cov.Mat[21,21]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[229:240] <- ifelse(row(Timing)[229:240] >= Perts$tsteps[20],1,0)
for(m in 229:240)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[228],Timing[m]*Perts$Pest[20]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,22],
0,PredStock$N.thou.SE[228]^2,0,
Cov.Mat[22,1],0,Cov.Mat[22,22]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[241:252] <- ifelse(row(Timing)[241:252] >= Perts$tsteps[21],1,0)
for(m in 241:252)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[240],Timing[m]*Perts$Pest[21]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,23],
0,PredStock$N.thou.SE[240]^2,0,
Cov.Mat[23,1],0,Cov.Mat[23,23]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[253:264] <- ifelse(row(Timing)[253:264] >= Perts$tsteps[22],1,0)
for(m in 253:264)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[252],Timing[m]*Perts$Pest[22]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,24],
0,PredStock$N.thou.SE[252]^2,0,
Cov.Mat[24,1],0,Cov.Mat[24,24]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[265:276] <- ifelse(row(Timing)[265:276] >= Perts$tsteps[23],1,0)
for(m in 265:276)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[264],Timing[m]*Perts$Pest[23]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,25],
0,PredStock$N.thou.SE[264]^2,0,
Cov.Mat[25,1],0,Cov.Mat[25,25]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[277:288] <- ifelse(row(Timing)[277:288] >= Perts$tsteps[24],1,0)
for(m in 277:288)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[276],Timing[m]*Perts$Pest[24]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,26],
0,PredStock$N.thou.SE[276]^2,0,
Cov.Mat[26,1],0,Cov.Mat[26,26]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
}
if(mt == 25)
{
Timing[181:192] <- ifelse(row(Timing)[181:192] >= Perts$tsteps[16],1,0)
for(m in 181:192)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[180],Timing[m]*Perts$Pest[16]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,18],
0,PredStock$N.thou.SE[180]^2,0,
Cov.Mat[18,1],0,Cov.Mat[18,18]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[193:204] <- ifelse(row(Timing)[193:204] >= Perts$tsteps[17],1,0)
for(m in 193:204)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[192],Timing[m]*Perts$Pest[17]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,19],
0,PredStock$N.thou.SE[192]^2,0,
Cov.Mat[19,1],0,Cov.Mat[19,19]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[205:216] <- ifelse(row(Timing)[205:216] >= Perts$tsteps[18],1,0)
for(m in 205:216)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[204],Timing[m]*Perts$Pest[18]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,20],
0,PredStock$N.thou.SE[204]^2,0,
Cov.Mat[20,1],0,Cov.Mat[20,20]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[217:228] <- ifelse(row(Timing)[217:228] >= Perts$tsteps[19],1,0)
for(m in 217:228)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[216],Timing[m]*Perts$Pest[19]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,21],
0,PredStock$N.thou.SE[216]^2,0,
Cov.Mat[21,1],0,Cov.Mat[21,21]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[229:240] <- ifelse(row(Timing)[229:240] >= Perts$tsteps[20],1,0)
for(m in 229:240)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[228],Timing[m]*Perts$Pest[20]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,22],
0,PredStock$N.thou.SE[228]^2,0,
Cov.Mat[22,1],0,Cov.Mat[22,22]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[241:252] <- ifelse(row(Timing)[241:252] >= Perts$tsteps[21],1,0)
for(m in 241:252)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[240],Timing[m]*Perts$Pest[21]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,23],
0,PredStock$N.thou.SE[240]^2,0,
Cov.Mat[23,1],0,Cov.Mat[23,23]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[253:264] <- ifelse(row(Timing)[253:264] >= Perts$tsteps[22],1,0)
for(m in 253:264)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[252],Timing[m]*Perts$Pest[22]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,24],
0,PredStock$N.thou.SE[252]^2,0,
Cov.Mat[24,1],0,Cov.Mat[24,24]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[265:276] <- ifelse(row(Timing)[265:276] >= Perts$tsteps[23],1,0)
for(m in 265:276)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[264],Timing[m]*Perts$Pest[23]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,25],
0,PredStock$N.thou.SE[264]^2,0,
Cov.Mat[25,1],0,Cov.Mat[25,25]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[277:288] <- ifelse(row(Timing)[277:288] >= Perts$tsteps[24],1,0)
for(m in 277:288)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[276],Timing[m]*Perts$Pest[24]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,26],
0,PredStock$N.thou.SE[276]^2,0,
Cov.Mat[26,1],0,Cov.Mat[26,26]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[289:300] <- ifelse(row(Timing)[289:300] >= Perts$tsteps[25],1,0)
for(m in 289:300)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[288],Timing[m]*Perts$Pest[25]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,27],
0,PredStock$N.thou.SE[288]^2,0,
Cov.Mat[27,1],0,Cov.Mat[27,27]),3,3))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
}
}
if(length(x$Data$Properties$Fleets$Fleet)==2)
{
mt <- x$Model[[method]]$Type[1]
Timing <- matrix(0,12*mt,2)
Timing[1:12,1] <- ifelse(row(Timing)[1:12,1] >= Perts$tsteps[1],1,0)
Timing[1:12,2] <- ifelse(row(Timing)[1:12,2] >= Perts$tsteps[mt+1],1,0)
Timing[13:24,1] <- ifelse(row(Timing)[13:24,1] >= Perts$tsteps[2],1,0)
Timing[13:24,2] <- ifelse(row(Timing)[13:24,2] >= Perts$tsteps[mt+2],1,0)
Timing[25:36,1] <- ifelse(row(Timing)[25:36,1] >= Perts$tsteps[3],1,0)
Timing[25:36,2] <- ifelse(row(Timing)[25:36,2] >= Perts$tsteps[mt+3],1,0)
Timing[37:48,1] <- ifelse(row(Timing)[37:48,1] >= Perts$tsteps[4],1,0)
Timing[37:48,2] <- ifelse(row(Timing)[37:48,2] >= Perts$tsteps[mt+4],1,0)
Timing[49:60,1] <- ifelse(row(Timing)[49:60,1] >= Perts$tsteps[5],1,0)
Timing[49:60,2] <- ifelse(row(Timing)[49:60,2] >= Perts$tsteps[mt+5],1,0)
Timing[61:72,1] <- ifelse(row(Timing)[61:72,1] >= Perts$tsteps[6],1,0)
Timing[61:72,2] <- ifelse(row(Timing)[61:72,2] >= Perts$tsteps[mt+6],1,0)
Timing[73:84,1] <- ifelse(row(Timing)[73:84,1] >= Perts$tsteps[7],1,0)
Timing[73:84,2] <- ifelse(row(Timing)[73:84,2] >= Perts$tsteps[mt+7],1,0)
Timing[85:96,1] <- ifelse(row(Timing)[85:96,1] >= Perts$tsteps[8],1,0)
Timing[85:96,2] <- ifelse(row(Timing)[85:96,2] >= Perts$tsteps[mt+8],1,0)
Timing[97:108,1] <- ifelse(row(Timing)[97:108,1] >= Perts$tsteps[9],1,0)
Timing[97:108,2] <- ifelse(row(Timing)[97:108,2] >= Perts$tsteps[mt+9],1,0)
Timing[109:120,1] <- ifelse(row(Timing)[109:120,1] >= Perts$tsteps[10],1,0)
Timing[109:120,2] <- ifelse(row(Timing)[109:120,2] >= Perts$tsteps[mt+10],1,0)
Timing[121:132,1] <- ifelse(row(Timing)[121:132,1] >= Perts$tsteps[11],1,0)
Timing[121:132,2] <- ifelse(row(Timing)[121:132,2] >= Perts$tsteps[mt+11],1,0)
Timing[133:144,1] <- ifelse(row(Timing)[133:144,1] >= Perts$tsteps[12],1,0)
Timing[133:144,2] <- ifelse(row(Timing)[133:144,2] >= Perts$tsteps[mt+12],1,0)
Timing[145:156,1] <- ifelse(row(Timing)[145:156,1] >= Perts$tsteps[13],1,0)
Timing[145:156,2] <- ifelse(row(Timing)[145:156,2] >= Perts$tsteps[mt+13],1,0)
Timing[157:168,1] <- ifelse(row(Timing)[157:168,1] >= Perts$tsteps[14],1,0)
Timing[157:168,2] <- ifelse(row(Timing)[157:168,2] >= Perts$tsteps[mt+14],1,0)
Timing[169:180,1] <- ifelse(row(Timing)[169:180,1] >= Perts$tsteps[15],1,0)
Timing[169:180,2] <- ifelse(row(Timing)[169:180,2] >= Perts$tsteps[mt+15],1,0)
fleet1 <- x$Data$Properties$Fleets[1,1]
fleet2 <- x$Data$Properties$Fleets[2,1]
if(mt <= 14)
{
stop("This function is intended to be used to calculate the standard deviation of annual biomass \n to fit a biomass dynamic model from the output of a multi-annual generalized depletion model (MAGD) \n with the catch recorded in biomass. At least 15 years of data must have been used in fitting \n the MAGD for its outputs to be used in this manner.")
}
Cov.Mat <- cor2cov(cor.mat=x$Model[[method]]$Cor[c(1:(mt+2),(mt+6):(2*(mt)+5)),
c(1:(mt+2),(mt+6):(2*(mt)+5))],
sd=c(PopDyn$SE.M,PopDyn$SE.N0,Perts$SE.Pest))
if(length(mbw.sd) != 12 & length(mbw.sd) != 12*mt)
{stop("mbw.sd must be a vector of length 12 (monthly mean weight) or 12*number of years, all in kg")}
yr1 <- as.numeric(format(as.Date(x$Data$Properties$Dates[1]),"%Y"))
yr2 <- as.numeric(format(as.Date(x$Data$Properties$Dates[2]),"%Y"))
z <- CatDynPred(x,method)
PredStock <- data.frame(Year=sort(rep(yr1:yr2,12)),
Month=c("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"),
TimeStep=1:((yr2-yr1+1)*12),
Mmw.kg=(x$Data$Data[[fleet1]]$obsmbw.kg+x$Data$Data[[fleet2]]$obsmbw.kg)/2,
SDmw.kg=mbw.sd,
N.thou=z$Model$Results[,18],
N.thou.SE=0,
B.ton=z$Model$Results[,19],
B.ton.SE=0)
for(m in 1:12)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PopDyn$N0,Timing[m,1]*Perts$Pest[1],Timing[m,2]*Perts$Pest[mt+1]),
cov=Cov.Mat[c(1:3,23),c(1:3,23)])
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
for(m in 13:24)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[12],Timing[m,1]*Perts$Pest[2],Timing[m,2]*Perts$Pest[mt+2]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,4],Cov.Mat[1,24],
0,PredStock$N.thou.SE[12]^2,0,0,
Cov.Mat[4,1],0,Cov.Mat[4,4],Cov.Mat[4,24],
Cov.Mat[24,1],0,Cov.Mat[24,4],Cov.Mat[24,24]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
for(m in 25:36)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[24],Timing[m,1]*Perts$Pest[3],Timing[m,2]*Perts$Pest[mt+3]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,5],Cov.Mat[1,25],
0,PredStock$N.thou.SE[24]^2,0,0,
Cov.Mat[5,1],0,Cov.Mat[5,5],Cov.Mat[5,25],
Cov.Mat[25,1],0,Cov.Mat[25,5],Cov.Mat[25,25]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
for(m in 37:48)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[36],Timing[m,1]*Perts$Pest[4],Timing[m,2]*Perts$Pest[mt+4]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,6],Cov.Mat[1,26],
0,PredStock$N.thou.SE[36]^2,0,0,
Cov.Mat[6,1],0,Cov.Mat[6,6],Cov.Mat[6,26],
Cov.Mat[26,1],0,Cov.Mat[26,6],Cov.Mat[26,26]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
for(m in 49:60)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[48],Timing[m,1]*Perts$Pest[5],Timing[m,2]*Perts$Pest[mt+5]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,7],Cov.Mat[1,27],
0,PredStock$N.thou.SE[48]^2,0,0,
Cov.Mat[7,1],0,Cov.Mat[7,7],Cov.Mat[7,27],
Cov.Mat[27,1],0,Cov.Mat[27,7],Cov.Mat[27,27]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
for(m in 61:72)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[60],Timing[m,1]*Perts$Pest[6],Timing[m,2]*Perts$Pest[mt+6]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,8],Cov.Mat[1,28],
0,PredStock$N.thou.SE[60]^2,0,0,
Cov.Mat[8,1],0,Cov.Mat[8,8],Cov.Mat[8,28],
Cov.Mat[28,1],0,Cov.Mat[28,8],Cov.Mat[28,28]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
for(m in 73:84)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[72],Timing[m,1]*Perts$Pest[7],Timing[m,2]*Perts$Pest[mt+7]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,9],Cov.Mat[1,29],
0,PredStock$N.thou.SE[72]^2,0,0,
Cov.Mat[9,1],0,Cov.Mat[9,9],Cov.Mat[9,29],
Cov.Mat[29,1],0,Cov.Mat[29,9],Cov.Mat[29,29]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
for(m in 85:96)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[84],Timing[m,1]*Perts$Pest[8],Timing[m,2]*Perts$Pest[mt+8]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,10],Cov.Mat[1,30],
0,PredStock$N.thou.SE[84]^2,0,0,
Cov.Mat[10,1],0,Cov.Mat[10,10],Cov.Mat[10,30],
Cov.Mat[30,1],0,Cov.Mat[30,10],Cov.Mat[30,30]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
for(m in 97:108)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[96],Timing[m,1]*Perts$Pest[9],Timing[m,2]*Perts$Pest[mt+9]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,11],Cov.Mat[1,31],
0,PredStock$N.thou.SE[96]^2,0,0,
Cov.Mat[11,1],0,Cov.Mat[11,11],Cov.Mat[11,31],
Cov.Mat[31,1],0,Cov.Mat[31,11],Cov.Mat[31,31]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
for(m in 109:120)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[108],Timing[m,1]*Perts$Pest[10],Timing[m,2]*Perts$Pest[mt+10]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,12],Cov.Mat[1,32],
0,PredStock$N.thou.SE[108]^2,0,0,
Cov.Mat[12,1],0,Cov.Mat[12,12],Cov.Mat[12,32],
Cov.Mat[32,1],0,Cov.Mat[32,12],Cov.Mat[32,32]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
for(m in 121:132)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[120],Timing[m,1]*Perts$Pest[11],Timing[m,2]*Perts$Pest[mt+11]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,13],Cov.Mat[1,33],
0,PredStock$N.thou.SE[120]^2,0,0,
Cov.Mat[13,1],0,Cov.Mat[13,13],Cov.Mat[13,33],
Cov.Mat[33,1],0,Cov.Mat[33,13],Cov.Mat[33,33]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
for(m in 133:144)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[132],Timing[m,1]*Perts$Pest[12],Timing[m,2]*Perts$Pest[mt+12]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,14],Cov.Mat[1,34],
0,PredStock$N.thou.SE[132]^2,0,0,
Cov.Mat[14,1],0,Cov.Mat[14,14],Cov.Mat[14,34],
Cov.Mat[34,1],0,Cov.Mat[34,14],Cov.Mat[34,34]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
for(m in 145:156)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[144],Timing[m,1]*Perts$Pest[13],Timing[m,2]*Perts$Pest[mt+13]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,15],Cov.Mat[1,35],
0,PredStock$N.thou.SE[144]^2,0,0,
Cov.Mat[15,1],0,Cov.Mat[15,15],Cov.Mat[15,35],
Cov.Mat[35,1],0,Cov.Mat[35,15],Cov.Mat[35,35]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
for(m in 157:168)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[156],Timing[m,1]*Perts$Pest[14],Timing[m,2]*Perts$Pest[mt+14]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,16],Cov.Mat[1,36],
0,PredStock$N.thou.SE[156]^2,0,0,
Cov.Mat[16,1],0,Cov.Mat[16,16],Cov.Mat[16,36],
Cov.Mat[36,1],0,Cov.Mat[36,16],Cov.Mat[36,36]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
for(m in 169:180)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[168],Timing[m,1]*Perts$Pest[15],Timing[m,2]*Perts$Pest[mt+15]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,17],Cov.Mat[1,37],
0,PredStock$N.thou.SE[168]^2,0,0,
Cov.Mat[17,1],0,Cov.Mat[17,17],Cov.Mat[17,37],
Cov.Mat[37,1],0,Cov.Mat[37,17],Cov.Mat[37,37]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
if(mt == 16)
{
Timing[181:192,1] <- ifelse(row(Timing)[181:192,1] >= Perts$tsteps[16],1,0)
Timing[181:192,2] <- ifelse(row(Timing)[181:192,2] >= Perts$tsteps[mt+16],1,0)
for(m in 181:192)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[180],Timing[m,1]*Perts$Pest[16],Timing[m,2]*Perts$Pest[mt+16]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,18],Cov.Mat[1,38],
0,PredStock$N.thou.SE[180]^2,0,0,
Cov.Mat[18,1],0,Cov.Mat[18,18],Cov.Mat[18,38],
Cov.Mat[38,1],0,Cov.Mat[38,18],Cov.Mat[38,38]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
}
if(mt == 17)
{
Timing[181:192,1] <- ifelse(row(Timing)[181:192,1] >= Perts$tsteps[16],1,0)
Timing[181:192,2] <- ifelse(row(Timing)[181:192,2] >= Perts$tsteps[mt+16],1,0)
for(m in 181:192)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[180],Timing[m,1]*Perts$Pest[16],Timing[m,2]*Perts$Pest[mt+16]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,18],Cov.Mat[1,38],
0,PredStock$N.thou.SE[180]^2,0,0,
Cov.Mat[18,1],0,Cov.Mat[18,18],Cov.Mat[18,38],
Cov.Mat[38,1],0,Cov.Mat[38,18],Cov.Mat[38,38]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[193:204,1] <- ifelse(row(Timing)[193:204,1] >= Perts$tsteps[17],1,0)
Timing[193:204,2] <- ifelse(row(Timing)[193:204,2] >= Perts$tsteps[mt+17],1,0)
for(m in 193:204)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[192],Timing[m,1]*Perts$Pest[17],Timing[m,2]*Perts$Pest[mt+17]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,19],Cov.Mat[1,39],
0,PredStock$N.thou.SE[192]^2,0,0,
Cov.Mat[19,1],0,Cov.Mat[19,19],Cov.Mat[19,39],
Cov.Mat[39,1],0,Cov.Mat[39,19],Cov.Mat[39,39]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
}
if(mt == 18)
{
Timing[181:192,1] <- ifelse(row(Timing)[181:192,1] >= Perts$tsteps[16],1,0)
Timing[181:192,2] <- ifelse(row(Timing)[181:192,2] >= Perts$tsteps[mt+16],1,0)
for(m in 181:192)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[180],Timing[m,1]*Perts$Pest[16],Timing[m,2]*Perts$Pest[mt+16]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,18],Cov.Mat[1,38],
0,PredStock$N.thou.SE[180]^2,0,0,
Cov.Mat[18,1],0,Cov.Mat[18,18],Cov.Mat[18,38],
Cov.Mat[38,1],0,Cov.Mat[38,18],Cov.Mat[38,38]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[193:204,1] <- ifelse(row(Timing)[193:204,1] >= Perts$tsteps[17],1,0)
Timing[193:204,2] <- ifelse(row(Timing)[193:204,2] >= Perts$tsteps[mt+17],1,0)
for(m in 193:204)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[192],Timing[m,1]*Perts$Pest[17],Timing[m,2]*Perts$Pest[mt+17]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,19],Cov.Mat[1,39],
0,PredStock$N.thou.SE[192]^2,0,0,
Cov.Mat[19,1],0,Cov.Mat[19,19],Cov.Mat[19,39],
Cov.Mat[39,1],0,Cov.Mat[39,19],Cov.Mat[39,39]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[205:216,1] <- ifelse(row(Timing)[205:216,1] >= Perts$tsteps[18],1,0)
Timing[205:216,2] <- ifelse(row(Timing)[205:216,2] >= Perts$tsteps[mt+18],1,0)
for(m in 205:216)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[204],Timing[m,1]*Perts$Pest[18],Timing[m,2]*Perts$Pest[mt+18]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,20],Cov.Mat[1,40],
0,PredStock$N.thou.SE[204]^2,0,0,
Cov.Mat[20,1],0,Cov.Mat[20,20],Cov.Mat[20,40],
Cov.Mat[40,1],0,Cov.Mat[40,20],Cov.Mat[40,40]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
}
if(mt == 19)
{
Timing[181:192,1] <- ifelse(row(Timing)[181:192,1] >= Perts$tsteps[16],1,0)
Timing[181:192,2] <- ifelse(row(Timing)[181:192,2] >= Perts$tsteps[mt+16],1,0)
for(m in 181:192)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[180],Timing[m,1]*Perts$Pest[16],Timing[m,2]*Perts$Pest[mt+16]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,18],Cov.Mat[1,38],
0,PredStock$N.thou.SE[180]^2,0,0,
Cov.Mat[18,1],0,Cov.Mat[18,18],Cov.Mat[18,38],
Cov.Mat[38,1],0,Cov.Mat[38,18],Cov.Mat[38,38]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[193:204,1] <- ifelse(row(Timing)[193:204,1] >= Perts$tsteps[17],1,0)
Timing[193:204,2] <- ifelse(row(Timing)[193:204,2] >= Perts$tsteps[mt+17],1,0)
for(m in 193:204)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[192],Timing[m,1]*Perts$Pest[17],Timing[m,2]*Perts$Pest[mt+17]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,19],Cov.Mat[1,39],
0,PredStock$N.thou.SE[192]^2,0,0,
Cov.Mat[19,1],0,Cov.Mat[19,19],Cov.Mat[19,39],
Cov.Mat[39,1],0,Cov.Mat[39,19],Cov.Mat[39,39]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[205:216,1] <- ifelse(row(Timing)[205:216,1] >= Perts$tsteps[18],1,0)
Timing[205:216,2] <- ifelse(row(Timing)[205:216,2] >= Perts$tsteps[mt+18],1,0)
for(m in 205:216)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[204],Timing[m,1]*Perts$Pest[18],Timing[m,2]*Perts$Pest[mt+18]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,20],Cov.Mat[1,40],
0,PredStock$N.thou.SE[204]^2,0,0,
Cov.Mat[20,1],0,Cov.Mat[20,20],Cov.Mat[20,40],
Cov.Mat[40,1],0,Cov.Mat[40,20],Cov.Mat[40,40]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[217:228,1] <- ifelse(row(Timing)[217:228,1] >= Perts$tsteps[19],1,0)
Timing[217:228,2] <- ifelse(row(Timing)[217:228,2] >= Perts$tsteps[mt+19],1,0)
for(m in 217:228)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[216],Timing[m,1]*Perts$Pest[19],Timing[m,2]*Perts$Pest[mt+19]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,21],Cov.Mat[1,41],
0,PredStock$N.thou.SE[216]^2,0,0,
Cov.Mat[21,1],0,Cov.Mat[21,21],Cov.Mat[21,41],
Cov.Mat[41,1],0,Cov.Mat[41,21],Cov.Mat[41,41]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
}
if(mt == 20)
{
Timing[181:192,1] <- ifelse(row(Timing)[181:192,1] >= Perts$tsteps[16],1,0)
Timing[181:192,2] <- ifelse(row(Timing)[181:192,2] >= Perts$tsteps[mt+16],1,0)
for(m in 181:192)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[180],Timing[m,1]*Perts$Pest[16],Timing[m,2]*Perts$Pest[mt+16]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,18],Cov.Mat[1,38],
0,PredStock$N.thou.SE[180]^2,0,0,
Cov.Mat[18,1],0,Cov.Mat[18,18],Cov.Mat[18,38],
Cov.Mat[38,1],0,Cov.Mat[38,18],Cov.Mat[38,38]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[193:204,1] <- ifelse(row(Timing)[193:204,1] >= Perts$tsteps[17],1,0)
Timing[193:204,2] <- ifelse(row(Timing)[193:204,2] >= Perts$tsteps[mt+17],1,0)
for(m in 193:204)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[192],Timing[m,1]*Perts$Pest[17],Timing[m,2]*Perts$Pest[mt+17]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,19],Cov.Mat[1,39],
0,PredStock$N.thou.SE[192]^2,0,0,
Cov.Mat[19,1],0,Cov.Mat[19,19],Cov.Mat[19,39],
Cov.Mat[39,1],0,Cov.Mat[39,19],Cov.Mat[39,39]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[205:216,1] <- ifelse(row(Timing)[205:216,1] >= Perts$tsteps[18],1,0)
Timing[205:216,2] <- ifelse(row(Timing)[205:216,2] >= Perts$tsteps[mt+18],1,0)
for(m in 205:216)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[204],Timing[m,1]*Perts$Pest[18],Timing[m,2]*Perts$Pest[mt+18]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,20],Cov.Mat[1,40],
0,PredStock$N.thou.SE[204]^2,0,0,
Cov.Mat[20,1],0,Cov.Mat[20,20],Cov.Mat[20,40],
Cov.Mat[40,1],0,Cov.Mat[40,20],Cov.Mat[40,40]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[217:228,1] <- ifelse(row(Timing)[217:228,1] >= Perts$tsteps[19],1,0)
Timing[217:228,2] <- ifelse(row(Timing)[217:228,2] >= Perts$tsteps[mt+19],1,0)
for(m in 217:228)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[216],Timing[m,1]*Perts$Pest[19],Timing[m,2]*Perts$Pest[mt+19]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,21],Cov.Mat[1,41],
0,PredStock$N.thou.SE[216]^2,0,0,
Cov.Mat[21,1],0,Cov.Mat[21,21],Cov.Mat[21,41],
Cov.Mat[41,1],0,Cov.Mat[41,21],Cov.Mat[41,41]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[229:240,1] <- ifelse(row(Timing)[229:240,1] >= Perts$tsteps[20],1,0)
Timing[229:240,2] <- ifelse(row(Timing)[229:240,2] >= Perts$tsteps[mt+20],1,0)
for(m in 229:240)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[228],Timing[m,1]*Perts$Pest[20],Timing[m,2]*Perts$Pest[mt+20]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,22],Cov.Mat[1,42],
0,PredStock$N.thou.SE[228]^2,0,0,
Cov.Mat[22,1],0,Cov.Mat[22,22],Cov.Mat[22,42],
Cov.Mat[42,1],0,Cov.Mat[42,22],Cov.Mat[42,42]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
}
if(mt == 21)
{
Timing[181:192,1] <- ifelse(row(Timing)[181:192,1] >= Perts$tsteps[16],1,0)
Timing[181:192,2] <- ifelse(row(Timing)[181:192,2] >= Perts$tsteps[mt+16],1,0)
for(m in 181:192)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[180],Timing[m,1]*Perts$Pest[16],Timing[m,2]*Perts$Pest[mt+16]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,18],Cov.Mat[1,38],
0,PredStock$N.thou.SE[180]^2,0,0,
Cov.Mat[18,1],0,Cov.Mat[18,18],Cov.Mat[18,38],
Cov.Mat[38,1],0,Cov.Mat[38,18],Cov.Mat[38,38]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[193:204,1] <- ifelse(row(Timing)[193:204,1] >= Perts$tsteps[17],1,0)
Timing[193:204,2] <- ifelse(row(Timing)[193:204,2] >= Perts$tsteps[mt+17],1,0)
for(m in 193:204)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[192],Timing[m,1]*Perts$Pest[17],Timing[m,2]*Perts$Pest[mt+17]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,19],Cov.Mat[1,39],
0,PredStock$N.thou.SE[192]^2,0,0,
Cov.Mat[19,1],0,Cov.Mat[19,19],Cov.Mat[19,39],
Cov.Mat[39,1],0,Cov.Mat[39,19],Cov.Mat[39,39]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[205:216,1] <- ifelse(row(Timing)[205:216,1] >= Perts$tsteps[18],1,0)
Timing[205:216,2] <- ifelse(row(Timing)[205:216,2] >= Perts$tsteps[mt+18],1,0)
for(m in 205:216)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[204],Timing[m,1]*Perts$Pest[18],Timing[m,2]*Perts$Pest[mt+18]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,20],Cov.Mat[1,40],
0,PredStock$N.thou.SE[204]^2,0,0,
Cov.Mat[20,1],0,Cov.Mat[20,20],Cov.Mat[20,40],
Cov.Mat[40,1],0,Cov.Mat[40,20],Cov.Mat[40,40]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[217:228,1] <- ifelse(row(Timing)[217:228,1] >= Perts$tsteps[19],1,0)
Timing[217:228,2] <- ifelse(row(Timing)[217:228,2] >= Perts$tsteps[mt+19],1,0)
for(m in 217:228)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[216],Timing[m,1]*Perts$Pest[19],Timing[m,2]*Perts$Pest[mt+19]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,21],Cov.Mat[1,41],
0,PredStock$N.thou.SE[216]^2,0,0,
Cov.Mat[21,1],0,Cov.Mat[21,21],Cov.Mat[21,41],
Cov.Mat[41,1],0,Cov.Mat[41,21],Cov.Mat[41,41]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[229:240,1] <- ifelse(row(Timing)[229:240,1] >= Perts$tsteps[20],1,0)
Timing[229:240,2] <- ifelse(row(Timing)[229:240,2] >= Perts$tsteps[mt+20],1,0)
for(m in 229:240)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[228],Timing[m,1]*Perts$Pest[20],Timing[m,2]*Perts$Pest[mt+20]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,22],Cov.Mat[1,42],
0,PredStock$N.thou.SE[228]^2,0,0,
Cov.Mat[22,1],0,Cov.Mat[22,22],Cov.Mat[22,42],
Cov.Mat[42,1],0,Cov.Mat[42,22],Cov.Mat[42,42]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[241:252,1] <- ifelse(row(Timing)[241:252,1] >= Perts$tsteps[21],1,0)
Timing[241:252,2] <- ifelse(row(Timing)[241:252,2] >= Perts$tsteps[mt+21],1,0)
for(m in 241:252)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[240],Timing[m,1]*Perts$Pest[21],Timing[m,2]*Perts$Pest[mt+21]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,23],Cov.Mat[1,43],
0,PredStock$N.thou.SE[240]^2,0,0,
Cov.Mat[23,1],0,Cov.Mat[23,23],Cov.Mat[23,43],
Cov.Mat[43,1],0,Cov.Mat[43,23],Cov.Mat[43,43]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
}
if(mt == 22)
{
Timing[181:192,1] <- ifelse(row(Timing)[181:192,1] >= Perts$tsteps[16],1,0)
Timing[181:192,2] <- ifelse(row(Timing)[181:192,2] >= Perts$tsteps[mt+16],1,0)
for(m in 181:192)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[180],Timing[m,1]*Perts$Pest[16],Timing[m,2]*Perts$Pest[mt+16]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,18],Cov.Mat[1,38],
0,PredStock$N.thou.SE[180]^2,0,0,
Cov.Mat[18,1],0,Cov.Mat[18,18],Cov.Mat[18,38],
Cov.Mat[38,1],0,Cov.Mat[38,18],Cov.Mat[38,38]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[193:204,1] <- ifelse(row(Timing)[193:204,1] >= Perts$tsteps[17],1,0)
Timing[193:204,2] <- ifelse(row(Timing)[193:204,2] >= Perts$tsteps[mt+17],1,0)
for(m in 193:204)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[192],Timing[m,1]*Perts$Pest[17],Timing[m,2]*Perts$Pest[mt+17]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,19],Cov.Mat[1,39],
0,PredStock$N.thou.SE[192]^2,0,0,
Cov.Mat[19,1],0,Cov.Mat[19,19],Cov.Mat[19,39],
Cov.Mat[39,1],0,Cov.Mat[39,19],Cov.Mat[39,39]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[205:216,1] <- ifelse(row(Timing)[205:216,1] >= Perts$tsteps[18],1,0)
Timing[205:216,2] <- ifelse(row(Timing)[205:216,2] >= Perts$tsteps[mt+18],1,0)
for(m in 205:216)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[204],Timing[m,1]*Perts$Pest[18],Timing[m,2]*Perts$Pest[mt+18]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,20],Cov.Mat[1,40],
0,PredStock$N.thou.SE[204]^2,0,0,
Cov.Mat[20,1],0,Cov.Mat[20,20],Cov.Mat[20,40],
Cov.Mat[40,1],0,Cov.Mat[40,20],Cov.Mat[40,40]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[217:228,1] <- ifelse(row(Timing)[217:228,1] >= Perts$tsteps[19],1,0)
Timing[217:228,2] <- ifelse(row(Timing)[217:228,2] >= Perts$tsteps[mt+19],1,0)
for(m in 217:228)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[216],Timing[m,1]*Perts$Pest[19],Timing[m,2]*Perts$Pest[mt+19]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,21],Cov.Mat[1,41],
0,PredStock$N.thou.SE[216]^2,0,0,
Cov.Mat[21,1],0,Cov.Mat[21,21],Cov.Mat[21,41],
Cov.Mat[41,1],0,Cov.Mat[41,21],Cov.Mat[41,41]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[229:240,1] <- ifelse(row(Timing)[229:240,1] >= Perts$tsteps[20],1,0)
Timing[229:240,2] <- ifelse(row(Timing)[229:240,2] >= Perts$tsteps[mt+20],1,0)
for(m in 229:240)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[228],Timing[m,1]*Perts$Pest[20],Timing[m,2]*Perts$Pest[mt+20]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,22],Cov.Mat[1,42],
0,PredStock$N.thou.SE[228]^2,0,0,
Cov.Mat[22,1],0,Cov.Mat[22,22],Cov.Mat[22,42],
Cov.Mat[42,1],0,Cov.Mat[42,22],Cov.Mat[42,42]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[241:252,1] <- ifelse(row(Timing)[241:252,1] >= Perts$tsteps[21],1,0)
Timing[241:252,2] <- ifelse(row(Timing)[241:252,2] >= Perts$tsteps[mt+21],1,0)
for(m in 241:252)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[240],Timing[m,1]*Perts$Pest[21],Timing[m,2]*Perts$Pest[mt+21]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,23],Cov.Mat[1,43],
0,PredStock$N.thou.SE[240]^2,0,0,
Cov.Mat[23,1],0,Cov.Mat[23,23],Cov.Mat[23,43],
Cov.Mat[43,1],0,Cov.Mat[43,23],Cov.Mat[43,43]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[253:264,1] <- ifelse(row(Timing)[253:264,1] >= Perts$tsteps[22],1,0)
Timing[253:264,2] <- ifelse(row(Timing)[253:264,2] >= Perts$tsteps[mt+22],1,0)
for(m in 253:264)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[252],Timing[m,1]*Perts$Pest[22],Timing[m,2]*Perts$Pest[mt+22]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,24],Cov.Mat[1,44],
0,PredStock$N.thou.SE[252]^2,0,0,
Cov.Mat[24,1],0,Cov.Mat[24,24],Cov.Mat[24,44],
Cov.Mat[44,1],0,Cov.Mat[44,24],Cov.Mat[44,44]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
}
if(mt == 23)
{
Timing[181:192,1] <- ifelse(row(Timing)[181:192,1] >= Perts$tsteps[16],1,0)
Timing[181:192,2] <- ifelse(row(Timing)[181:192,2] >= Perts$tsteps[mt+16],1,0)
for(m in 181:192)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[180],Timing[m,1]*Perts$Pest[16],Timing[m,2]*Perts$Pest[mt+16]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,18],Cov.Mat[1,38],
0,PredStock$N.thou.SE[180]^2,0,0,
Cov.Mat[18,1],0,Cov.Mat[18,18],Cov.Mat[18,38],
Cov.Mat[38,1],0,Cov.Mat[38,18],Cov.Mat[38,38]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[193:204,1] <- ifelse(row(Timing)[193:204,1] >= Perts$tsteps[17],1,0)
Timing[193:204,2] <- ifelse(row(Timing)[193:204,2] >= Perts$tsteps[mt+17],1,0)
for(m in 193:204)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[192],Timing[m,1]*Perts$Pest[17],Timing[m,2]*Perts$Pest[mt+17]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,19],Cov.Mat[1,39],
0,PredStock$N.thou.SE[192]^2,0,0,
Cov.Mat[19,1],0,Cov.Mat[19,19],Cov.Mat[19,39],
Cov.Mat[39,1],0,Cov.Mat[39,19],Cov.Mat[39,39]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[205:216,1] <- ifelse(row(Timing)[205:216,1] >= Perts$tsteps[18],1,0)
Timing[205:216,2] <- ifelse(row(Timing)[205:216,2] >= Perts$tsteps[mt+18],1,0)
for(m in 205:216)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[204],Timing[m,1]*Perts$Pest[18],Timing[m,2]*Perts$Pest[mt+18]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,20],Cov.Mat[1,40],
0,PredStock$N.thou.SE[204]^2,0,0,
Cov.Mat[20,1],0,Cov.Mat[20,20],Cov.Mat[20,40],
Cov.Mat[40,1],0,Cov.Mat[40,20],Cov.Mat[40,40]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[217:228,1] <- ifelse(row(Timing)[217:228,1] >= Perts$tsteps[19],1,0)
Timing[217:228,2] <- ifelse(row(Timing)[217:228,2] >= Perts$tsteps[mt+19],1,0)
for(m in 217:228)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[216],Timing[m,1]*Perts$Pest[19],Timing[m,2]*Perts$Pest[mt+19]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,21],Cov.Mat[1,41],
0,PredStock$N.thou.SE[216]^2,0,0,
Cov.Mat[21,1],0,Cov.Mat[21,21],Cov.Mat[21,41],
Cov.Mat[41,1],0,Cov.Mat[41,21],Cov.Mat[41,41]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[229:240,1] <- ifelse(row(Timing)[229:240,1] >= Perts$tsteps[20],1,0)
Timing[229:240,2] <- ifelse(row(Timing)[229:240,2] >= Perts$tsteps[mt+20],1,0)
for(m in 229:240)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[228],Timing[m,1]*Perts$Pest[20],Timing[m,2]*Perts$Pest[mt+20]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,22],Cov.Mat[1,42],
0,PredStock$N.thou.SE[228]^2,0,0,
Cov.Mat[22,1],0,Cov.Mat[22,22],Cov.Mat[22,42],
Cov.Mat[42,1],0,Cov.Mat[42,22],Cov.Mat[42,42]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[241:252,1] <- ifelse(row(Timing)[241:252,1] >= Perts$tsteps[21],1,0)
Timing[241:252,2] <- ifelse(row(Timing)[241:252,2] >= Perts$tsteps[mt+21],1,0)
for(m in 241:252)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[240],Timing[m,1]*Perts$Pest[21],Timing[m,2]*Perts$Pest[mt+21]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,23],Cov.Mat[1,43],
0,PredStock$N.thou.SE[240]^2,0,0,
Cov.Mat[23,1],0,Cov.Mat[23,23],Cov.Mat[23,43],
Cov.Mat[43,1],0,Cov.Mat[43,23],Cov.Mat[43,43]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[253:264,1] <- ifelse(row(Timing)[253:264,1] >= Perts$tsteps[22],1,0)
Timing[253:264,2] <- ifelse(row(Timing)[253:264,2] >= Perts$tsteps[mt+22],1,0)
for(m in 253:264)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[252],Timing[m,1]*Perts$Pest[22],Timing[m,2]*Perts$Pest[mt+22]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,24],Cov.Mat[1,44],
0,PredStock$N.thou.SE[252]^2,0,0,
Cov.Mat[24,1],0,Cov.Mat[24,24],Cov.Mat[24,44],
Cov.Mat[44,1],0,Cov.Mat[44,24],Cov.Mat[44,44]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[265:276,1] <- ifelse(row(Timing)[265:276,1] >= Perts$tsteps[23],1,0)
Timing[265:276,2] <- ifelse(row(Timing)[265:276,2] >= Perts$tsteps[mt+23],1,0)
for(m in 265:276)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[264],Timing[m,1]*Perts$Pest[23],Timing[m,2]*Perts$Pest[mt+23]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,25],Cov.Mat[1,45],
0,PredStock$N.thou.SE[264]^2,0,0,
Cov.Mat[25,1],0,Cov.Mat[25,25],Cov.Mat[25,45],
Cov.Mat[45,1],0,Cov.Mat[45,25],Cov.Mat[45,45]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
}
if(mt == 24)
{
Timing[181:192,1] <- ifelse(row(Timing)[181:192,1] >= Perts$tsteps[16],1,0)
Timing[181:192,2] <- ifelse(row(Timing)[181:192,2] >= Perts$tsteps[mt+16],1,0)
for(m in 181:192)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[180],Timing[m,1]*Perts$Pest[16],Timing[m,2]*Perts$Pest[mt+16]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,18],Cov.Mat[1,38],
0,PredStock$N.thou.SE[180]^2,0,0,
Cov.Mat[18,1],0,Cov.Mat[18,18],Cov.Mat[18,38],
Cov.Mat[38,1],0,Cov.Mat[38,18],Cov.Mat[38,38]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[193:204,1] <- ifelse(row(Timing)[193:204,1] >= Perts$tsteps[17],1,0)
Timing[193:204,2] <- ifelse(row(Timing)[193:204,2] >= Perts$tsteps[mt+17],1,0)
for(m in 193:204)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[192],Timing[m,1]*Perts$Pest[17],Timing[m,2]*Perts$Pest[mt+17]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,19],Cov.Mat[1,39],
0,PredStock$N.thou.SE[192]^2,0,0,
Cov.Mat[19,1],0,Cov.Mat[19,19],Cov.Mat[19,39],
Cov.Mat[39,1],0,Cov.Mat[39,19],Cov.Mat[39,39]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[205:216,1] <- ifelse(row(Timing)[205:216,1] >= Perts$tsteps[18],1,0)
Timing[205:216,2] <- ifelse(row(Timing)[205:216,2] >= Perts$tsteps[mt+18],1,0)
for(m in 205:216)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[204],Timing[m,1]*Perts$Pest[18],Timing[m,2]*Perts$Pest[mt+18]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,20],Cov.Mat[1,40],
0,PredStock$N.thou.SE[204]^2,0,0,
Cov.Mat[20,1],0,Cov.Mat[20,20],Cov.Mat[20,40],
Cov.Mat[40,1],0,Cov.Mat[40,20],Cov.Mat[40,40]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[217:228,1] <- ifelse(row(Timing)[217:228,1] >= Perts$tsteps[19],1,0)
Timing[217:228,2] <- ifelse(row(Timing)[217:228,2] >= Perts$tsteps[mt+19],1,0)
for(m in 217:228)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[216],Timing[m,1]*Perts$Pest[19],Timing[m,2]*Perts$Pest[mt+19]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,21],Cov.Mat[1,41],
0,PredStock$N.thou.SE[216]^2,0,0,
Cov.Mat[21,1],0,Cov.Mat[21,21],Cov.Mat[21,41],
Cov.Mat[41,1],0,Cov.Mat[41,21],Cov.Mat[41,41]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[229:240,1] <- ifelse(row(Timing)[229:240,1] >= Perts$tsteps[20],1,0)
Timing[229:240,2] <- ifelse(row(Timing)[229:240,2] >= Perts$tsteps[mt+20],1,0)
for(m in 229:240)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[228],Timing[m,1]*Perts$Pest[20],Timing[m,2]*Perts$Pest[mt+20]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,22],Cov.Mat[1,42],
0,PredStock$N.thou.SE[228]^2,0,0,
Cov.Mat[22,1],0,Cov.Mat[22,22],Cov.Mat[22,42],
Cov.Mat[42,1],0,Cov.Mat[42,22],Cov.Mat[42,42]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[241:252,1] <- ifelse(row(Timing)[241:252,1] >= Perts$tsteps[21],1,0)
Timing[241:252,2] <- ifelse(row(Timing)[241:252,2] >= Perts$tsteps[mt+21],1,0)
for(m in 241:252)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[240],Timing[m,1]*Perts$Pest[21],Timing[m,2]*Perts$Pest[mt+21]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,23],Cov.Mat[1,43],
0,PredStock$N.thou.SE[240]^2,0,0,
Cov.Mat[23,1],0,Cov.Mat[23,23],Cov.Mat[23,43],
Cov.Mat[43,1],0,Cov.Mat[43,23],Cov.Mat[43,43]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[253:264,1] <- ifelse(row(Timing)[253:264,1] >= Perts$tsteps[22],1,0)
Timing[253:264,2] <- ifelse(row(Timing)[253:264,2] >= Perts$tsteps[mt+22],1,0)
for(m in 253:264)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[252],Timing[m,1]*Perts$Pest[22],Timing[m,2]*Perts$Pest[mt+22]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,24],Cov.Mat[1,44],
0,PredStock$N.thou.SE[252]^2,0,0,
Cov.Mat[24,1],0,Cov.Mat[24,24],Cov.Mat[24,44],
Cov.Mat[44,1],0,Cov.Mat[44,24],Cov.Mat[44,44]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[265:276,1] <- ifelse(row(Timing)[265:276,1] >= Perts$tsteps[23],1,0)
Timing[265:276,2] <- ifelse(row(Timing)[265:276,2] >= Perts$tsteps[mt+23],1,0)
for(m in 265:276)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[264],Timing[m,1]*Perts$Pest[23],Timing[m,2]*Perts$Pest[mt+23]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,25],Cov.Mat[1,45],
0,PredStock$N.thou.SE[264]^2,0,0,
Cov.Mat[25,1],0,Cov.Mat[25,25],Cov.Mat[25,45],
Cov.Mat[45,1],0,Cov.Mat[45,25],Cov.Mat[45,45]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[277:288,1] <- ifelse(row(Timing)[277:288,1] >= Perts$tsteps[24],1,0)
Timing[277:288,2] <- ifelse(row(Timing)[277:288,2] >= Perts$tsteps[mt+24],1,0)
for(m in 277:288)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[276],Timing[m,1]*Perts$Pest[24],Timing[m,2]*Perts$Pest[mt+24]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,26],Cov.Mat[1,46],
0,PredStock$N.thou.SE[276]^2,0,0,
Cov.Mat[26,1],0,Cov.Mat[26,26],Cov.Mat[26,46],
Cov.Mat[46,1],0,Cov.Mat[46,26],Cov.Mat[46,46]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
}
if(mt == 25)
{
Timing[181:192,1] <- ifelse(row(Timing)[181:192,1] >= Perts$tsteps[16],1,0)
Timing[181:192,2] <- ifelse(row(Timing)[181:192,2] >= Perts$tsteps[mt+16],1,0)
for(m in 181:192)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[180],Timing[m,1]*Perts$Pest[16],Timing[m,2]*Perts$Pest[mt+16]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,18],Cov.Mat[1,38],
0,PredStock$N.thou.SE[180]^2,0,0,
Cov.Mat[18,1],0,Cov.Mat[18,18],Cov.Mat[18,38],
Cov.Mat[38,1],0,Cov.Mat[38,18],Cov.Mat[38,38]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[193:204,1] <- ifelse(row(Timing)[193:204,1] >= Perts$tsteps[17],1,0)
Timing[193:204,2] <- ifelse(row(Timing)[193:204,2] >= Perts$tsteps[mt+17],1,0)
for(m in 193:204)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[192],Timing[m,1]*Perts$Pest[17],Timing[m,2]*Perts$Pest[mt+17]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,19],Cov.Mat[1,39],
0,PredStock$N.thou.SE[192]^2,0,0,
Cov.Mat[19,1],0,Cov.Mat[19,19],Cov.Mat[19,39],
Cov.Mat[39,1],0,Cov.Mat[39,19],Cov.Mat[39,39]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[205:216,1] <- ifelse(row(Timing)[205:216,1] >= Perts$tsteps[18],1,0)
Timing[205:216,2] <- ifelse(row(Timing)[205:216,2] >= Perts$tsteps[mt+18],1,0)
for(m in 205:216)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[204],Timing[m,1]*Perts$Pest[18],Timing[m,2]*Perts$Pest[mt+18]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,20],Cov.Mat[1,40],
0,PredStock$N.thou.SE[204]^2,0,0,
Cov.Mat[20,1],0,Cov.Mat[20,20],Cov.Mat[20,40],
Cov.Mat[40,1],0,Cov.Mat[40,20],Cov.Mat[40,40]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[217:228,1] <- ifelse(row(Timing)[217:228,1] >= Perts$tsteps[19],1,0)
Timing[217:228,2] <- ifelse(row(Timing)[217:228,2] >= Perts$tsteps[mt+19],1,0)
for(m in 217:228)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[216],Timing[m,1]*Perts$Pest[19],Timing[m,2]*Perts$Pest[mt+19]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,21],Cov.Mat[1,41],
0,PredStock$N.thou.SE[216]^2,0,0,
Cov.Mat[21,1],0,Cov.Mat[21,21],Cov.Mat[21,41],
Cov.Mat[41,1],0,Cov.Mat[41,21],Cov.Mat[41,41]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[229:240,1] <- ifelse(row(Timing)[229:240,1] >= Perts$tsteps[20],1,0)
Timing[229:240,2] <- ifelse(row(Timing)[229:240,2] >= Perts$tsteps[mt+20],1,0)
for(m in 229:240)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[228],Timing[m,1]*Perts$Pest[20],Timing[m,2]*Perts$Pest[mt+20]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,22],Cov.Mat[1,42],
0,PredStock$N.thou.SE[228]^2,0,0,
Cov.Mat[22,1],0,Cov.Mat[22,22],Cov.Mat[22,42],
Cov.Mat[42,1],0,Cov.Mat[42,22],Cov.Mat[42,42]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[241:252,1] <- ifelse(row(Timing)[241:252,1] >= Perts$tsteps[21],1,0)
Timing[241:252,2] <- ifelse(row(Timing)[241:252,2] >= Perts$tsteps[mt+21],1,0)
for(m in 241:252)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[240],Timing[m,1]*Perts$Pest[21],Timing[m,2]*Perts$Pest[mt+21]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,23],Cov.Mat[1,43],
0,PredStock$N.thou.SE[240]^2,0,0,
Cov.Mat[23,1],0,Cov.Mat[23,23],Cov.Mat[23,43],
Cov.Mat[43,1],0,Cov.Mat[43,23],Cov.Mat[43,43]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[253:264,1] <- ifelse(row(Timing)[253:264,1] >= Perts$tsteps[22],1,0)
Timing[253:264,2] <- ifelse(row(Timing)[253:264,2] >= Perts$tsteps[mt+22],1,0)
for(m in 253:264)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[252],Timing[m,1]*Perts$Pest[22],Timing[m,2]*Perts$Pest[mt+22]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,24],Cov.Mat[1,44],
0,PredStock$N.thou.SE[252]^2,0,0,
Cov.Mat[24,1],0,Cov.Mat[24,24],Cov.Mat[24,44],
Cov.Mat[44,1],0,Cov.Mat[44,24],Cov.Mat[44,44]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[265:276,1] <- ifelse(row(Timing)[265:276,1] >= Perts$tsteps[23],1,0)
Timing[265:276,2] <- ifelse(row(Timing)[265:276,2] >= Perts$tsteps[mt+23],1,0)
for(m in 265:276)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[264],Timing[m,1]*Perts$Pest[23],Timing[m,2]*Perts$Pest[mt+23]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,25],Cov.Mat[1,45],
0,PredStock$N.thou.SE[264]^2,0,0,
Cov.Mat[25,1],0,Cov.Mat[25,25],Cov.Mat[25,45],
Cov.Mat[45,1],0,Cov.Mat[45,25],Cov.Mat[45,45]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[277:288,1] <- ifelse(row(Timing)[277:288,1] >= Perts$tsteps[24],1,0)
Timing[277:288,2] <- ifelse(row(Timing)[277:288,2] >= Perts$tsteps[mt+24],1,0)
for(m in 277:288)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[276],Timing[m,1]*Perts$Pest[24],Timing[m,2]*Perts$Pest[mt+24]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,26],Cov.Mat[1,46],
0,PredStock$N.thou.SE[276]^2,0,0,
Cov.Mat[26,1],0,Cov.Mat[26,26],Cov.Mat[26,46],
Cov.Mat[46,1],0,Cov.Mat[46,26],Cov.Mat[46,46]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
Timing[289:300,1] <- ifelse(row(Timing)[289:300,1] >= Perts$tsteps[25],1,0)
Timing[289:300,2] <- ifelse(row(Timing)[289:300,2] >= Perts$tsteps[mt+25],1,0)
for(m in 289:300)
{
PredStock$N.thou.SE[m] <- deltamethod(g=list(~x2*exp(-x1)+x3*exp(-x1)+x4*exp(-x1)),
mean=c(PopDyn$M,PredStock$N.thou[288],Timing[m,1]*Perts$Pest[25],Timing[m,2]*Perts$Pest[mt+25]),
cov=matrix(c(Cov.Mat[1,1],0,Cov.Mat[1,27],Cov.Mat[1,47],
0,PredStock$N.thou.SE[288]^2,0,0,
Cov.Mat[27,1],0,Cov.Mat[27,27],Cov.Mat[27,47],
Cov.Mat[47,1],0,Cov.Mat[47,27],Cov.Mat[47,47]),4,4))
PredStock$B.ton.SE[m] <- sqrt((1e3*PredStock$N.thou.SE[m])^2*(PredStock$Mmw.kg[m]*1e-3)^2 +
(1e3*PredStock$N.thou[m])^2*(PredStock$SDmw.kg[m]*1e-3)^2)
}
}
}
}
if(!multi)
{
if(length(unique(sapply(1:length(x), function(u) length(x[[u]]$Data$Properties$Fleets$Fleet)))) > 1)
{stop("All catdyn objects in the list 'x' must be either 1-fleet or 2-fleets, not some 1-fleet and some 2-fleets")}
if(length(unique(as.vector(sapply(1:length(x), function(u) x[[u]]$Data$Properties$Fleets$Fleet)))) == 1)
{
if(length(unique(sapply(1:length(x), function(u) x[[u]]$Data$Properties$Fleets$Fleet))) > 1)
{stop("All catdyn objects in the list 'x' must have the same name of fleet")}
if(class(x) != "list" | length(x) < 15)
{stop("For intra-annual models (time step is daily or weekly) x must be a list of objects of class 'catdyn' \n from succesful fit of models using CatDynFit, and the number of objects in the list (intra-annual fits) must be 15 consecutive years or more")}
ny <- length(x)
if(sum(dim(mbw.sd) != c(ny,3)) != 0)
{stop(" 'mbw.sd' must be a data.frame with as many rows as the length of 'x' and three columns: \n year, mean weight, and standard deviation of mean weight")}
if(length(method) != ny)
{stop("One numerical method must be supplied for each catdyn object in 'x' ")}
if(any(sapply(1:length(x), function(u) x[[u]]$Model[[method[u]]]$Type)>5))
{stop("The maximum number of perturbations in any of the elements of 'x' must not be higher than 5")}
PredStock <- data.frame(Year=as.numeric(format(as.Date(x[[1]]$Data$Properties$Dates[1]),"%Y")):as.numeric(format(as.Date(x[[ny]]$Data$Properties$Dates[1]),"%Y")),
Mw.kg=mbw.sd[,2],
SDmw.kg=mbw.sd[,3],
N0Tot.thou=0,
N0Tot.thou.SE=0,
B0Tot.ton=0,
B0Tot.ton.SE=0)
for(i in 1:ny)
{
if(any(is.na(x[[i]]$Model[[method[i]]]$bt.stdev)))
{
x[[i]]$Model[[method[i]]]$bt.stdev[which(is.na(x[[i]]$Model[[method[i]]]$bt.stdev))] <-
x[[i]]$Model[[method[i]]]$bt.par[which(is.na(x[[i]]$Model[[method[i]]]$bt.stdev))]*
mean(unlist(x[[i]]$Model[[method[i]]]$bt.stdev[which(!is.na(x[[i]]$Model[[method[i]]]$bt.stdev))])/
unlist(x[[i]]$Model[[method[i]]]$bt.par[which(!is.na(x[[i]]$Model[[method[i]]]$bt.stdev))]))
}
mt <- x[[i]]$Model[[method[i]]]$Type
Thou.scaler <- 1e6*(x[[i]]$Data$Properties$Units[4]=="bill") +
1e3*(x[[i]]$Data$Properties$Units[4]=="mill") +
1e0*(x[[i]]$Data$Properties$Units[4]=="thou") +
1e-1*(x[[i]]$Data$Properties$Units[4]=="hund")
M <- unlist(x[[i]]$Model[[method[i]]]$bt.par["M"])
SE.M <- unlist(x[[i]]$Model[[method[i]]]$bt.stdev["M"])
N0 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par["N0"])
SE.N0 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev["N0"])
if(mt == 0)
{
PredStock$N0Tot.thou[i] <- N0
PredStock$N0Tor.thou.SE[i] <- SE.N0
PredStock$B0Tot.ton[i] <- N0*mbw.sd[i,2]
PredStock$B0Tot.ton.SE[i] <- sqrt((SE.N0)^2*(mbw.sd[i,2])^2+(N0)^2*(mbw.sd[i,3])^2)
}
if(mt == 1)
{
P1 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[3])
P1.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[3])
P1.back <- x[[i]]$Model[[method[i]]]$Dates[2]-x[[i]]$Model[[method[i]]]$Dates[1]+1
cov <- cor2cov(x[[i]]$Model[[method[i]]]$Cor[1:3,1:3],sd=c(SE.M,SE.N0,P1.SE))
PredStock$N0Tot.thou[i] <- N0 + P1*exp(M*P1.back)
form <- sprintf("~x2 + x3*exp(x1*%i)",
P1.back)
PredStock$N0Tot.thou.SE[i] <- deltamethod(g=as.formula(form),
mean=c(M,N0,P1),
cov=cov)
PredStock$B0Tot.ton[i] <- PredStock$N0Tot.thou[i]*mbw.sd[i,2]
PredStock$B0Tot.ton.SE[i] <- sqrt((PredStock$N0Tot.thou.SE[i])^2*(mbw.sd[i,2])^2+(PredStock$N0Tot.thou[i])^2*(mbw.sd[i,3])^2)
}
if(mt == 2)
{
P1 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[3])
P1.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[3])
P1.back <- x[[i]]$Model[[method[i]]]$Dates[2]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[4])
P2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[4])
P2.back <- x[[i]]$Model[[method[i]]]$Dates[3]-x[[i]]$Model[[method[i]]]$Dates[1]+1
cov <- cor2cov(x[[i]]$Model[[method[i]]]$Cor[1:4,1:4],sd=c(SE.M,SE.N0,P1.SE,P2.SE))
PredStock$N0Tot.thou[i] <- N0 + P1*exp(M*P1.back) +
P2*exp(M*P2.back)
form <- sprintf("~x2+x3*exp(x1*%i)+x4*exp(x1*%i)",
P1.back,P2.back)
PredStock$N0Tot.thou.SE[i] <- deltamethod(g=as.formula(form),
mean=c(M,N0,P1,P2),
cov=cov)
PredStock$B0Tot.ton[i] <- PredStock$N0Tot.thou[i]*mbw.sd[i,2]
PredStock$B0Tot.ton.SE[i] <- sqrt((PredStock$N0Tot.thou.SE[i])^2*(mbw.sd[i,2])^2+(PredStock$N0Tot.thou[i])^2*(mbw.sd[i,3])^2)
}
if(mt == 3)
{
P1 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[3])
P1.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[3])
P1.back <- x[[i]]$Model[[method[i]]]$Dates[2]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[4])
P2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[4])
P2.back <- x[[i]]$Model[[method[i]]]$Dates[3]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P3 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[5])
P3.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[5])
P3.back <- x[[i]]$Model[[method[i]]]$Dates[4]-x[[i]]$Model[[method[i]]]$Dates[1]+1
cov <- cor2cov(x[[i]]$Model[[method[i]]]$Cor[1:5,1:5],sd=c(SE.M,SE.N0,P1.SE,P2.SE,P3.SE))
PredStock$N0Tot.thou[i] <- N0 + P1*exp(M*P1.back) +
P2*exp(M*P2.back) +
P3*exp(M*P3.back)
form <- sprintf("~x2+x3*exp(x1*%i)+x4*exp(x1*%i)+x5*exp(x1*%i)",
P1.back,P2.back,P3.back)
PredStock$N0Tot.thou.SE[i] <- deltamethod(g=as.formula(form),
mean=c(M,N0,P1,P2,P3),
cov=cov)
PredStock$B0Tot.ton[i] <- PredStock$N0Tot.thou[i]*mbw.sd[i,2]
PredStock$B0Tot.ton.SE[i] <- sqrt((PredStock$N0Tot.thou.SE[i])^2*(mbw.sd[i,2])^2+(PredStock$N0Tot.thou[i])^2*(mbw.sd[i,3])^2)
}
if(mt == 4)
{
P1 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[3])
P1.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[3])
P1.back <- x[[i]]$Model[[method[i]]]$Dates[2]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[4])
P2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[4])
P2.back <- x[[i]]$Model[[method[i]]]$Dates[3]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P3 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[5])
P3.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[5])
P3.back <- x[[i]]$Model[[method[i]]]$Dates[4]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P4 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[6])
P4.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[6])
P4.back <- x[[i]]$Model[[method[i]]]$Dates[5]-x[[i]]$Model[[method[i]]]$Dates[1]+1
cov <- cor2cov(x[[i]]$Model[[method[i]]]$Cor[1:6,1:6],sd=c(SE.M,SE.N0,P1.SE,P2.SE,P3.SE,P4.SE))
PredStock$N0Tot.thou[i] <- N0 + P1*exp(M*P1.back) +
P2*exp(M*P2.back) +
P3*exp(M*P3.back) +
P4*exp(M*P4.back)
form <- sprintf("~x2+x3*exp(x1*%i)+x4*exp(x1*%i)+x5*exp(x1*%i)+x6*exp(x1*%i)",
P1.back,P2.back,P3.back,P4.back)
PredStock$N0Tot.thou.SE[i] <- deltamethod(g=as.formula(form),
mean=c(M,N0,P1,P2,P3,P4),
cov=cov)
PredStock$B0Tot.ton[i] <- PredStock$N0Tot.thou[i]*mbw.sd[i,2]
PredStock$B0Tot.ton.SE[i] <- sqrt((PredStock$N0Tot.thou.SE[i])^2*(mbw.sd[i,2])^2+(PredStock$N0Tot.thou[i])^2*(mbw.sd[i,3])^2)
}
if(mt == 5)
{
P1 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[3])
P1.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[3])
P1.back <- x[[i]]$Model[[method[i]]]$Dates[2]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[4])
P2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[4])
P2.back <- x[[i]]$Model[[method[i]]]$Dates[3]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P3 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[5])
P3.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[5])
P3.back <- x[[i]]$Model[[method[i]]]$Dates[4]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P4 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[6])
P4.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[6])
P4.back <- x[[i]]$Model[[method[i]]]$Dates[5]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P5 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[7])
P5.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[7])
P5.back <- x[[i]]$Model[[method[i]]]$Dates[6]-x[[i]]$Model[[method[i]]]$Dates[1]+1
cov <- cor2cov(x[[i]]$Model[[method[i]]]$Cor[1:7,1:7],sd=c(SE.M,SE.N0,P1.SE,P2.SE,P3.SE,P4.SE,P5.SE))
PredStock$N0Tot.thou[i] <- N0 + P1*exp(M*P1.back) +
P2*exp(M*P2.back) +
P3*exp(M*P3.back) +
P4*exp(M*P4.back) +
P5*exp(M*P5.back)
form <- sprintf("~x2+x3*exp(x1*%i)+x4*exp(x1*%i)+x5*exp(x1*%i)+x6*exp(x1*%i)+x7*exp(x1*%i)",
P1.back,P2.back,P3.back,P4.back,P5.back)
PredStock$N0Tot.thou.SE[i] <- deltamethod(g=as.formula(form),
mean=c(M,N0,P1,P2,P3,P4,P5),
cov=cov)
PredStock$B0Tot.ton[i] <- PredStock$N0Tot.thou[i]*mbw.sd[i,2]
PredStock$B0Tot.ton.SE[i] <- sqrt((PredStock$N0Tot.thou.SE[i])^2*(mbw.sd[i,2])^2+(PredStock$N0Tot.thou[i])^2*(mbw.sd[i,3])^2)
}
}
}
if(length(unique(as.vector(sapply(1:length(x), function(u) x[[u]]$Data$Properties$Fleets$Fleet)))) == 2)
{
if(length(unique(as.vector(sapply(1:length(x), function(u) x[[u]]$Data$Properties$Fleets$Fleet)))) != 2)
{stop("All catdyn objects in the list 'x' must have the same two fleets")}
if(class(x) != "list" | length(x) < 15)
{stop("For intra-annual models (time step is daily or weekly) x must be a list of objects of class 'catdyn' \n from succesful fit of models using CatDynFit, and the number of objects in the list (intra-annual fits) must be 15 consecutive years or more")}
ny <- length(x)
if(sum(dim(mbw.sd) != c(ny,3)) != 0)
{stop(" 'mbw.sd' must be a data.frame with as many rows as the length of 'x' and three columns: \n year, mean weight, and standard deviation of mean length ")}
if(length(method) != ny)
{stop("One numerical method must be supplied for each catdyn object in 'x' ")}
if(max(as.vector(sapply(1:length(x), function(u) x[[u]]$Model[[method[u]]]$Type)))>5)
{stop("The maximum number of perturbations in any of the elements and fleets of 'x' must not be higher than 5; \n any of the models in 'x' can go from a minimum of c(0,0) (pure depletion both fleets) to a maximum of c(5,5)")}
PredStock <- data.frame(Year=as.numeric(format(as.Date(x[[1]]$Data$Properties$Dates[1]),"%Y")):as.numeric(format(as.Date(x[[ny]]$Data$Properties$Dates[1]),"%Y")),
Mw.kg=mbw.sd[,2],
SDmw.kg=mbw.sd[,3],
N0Tot.thou=0,
N0Tot.thou.SE=0,
B0Tot.ton=0,
B0Tot.ton.SE=0)
for(i in 1:ny)
{
if(any(is.na(x[[i]]$Model[[method[i]]]$bt.stdev)))
{
x[[i]]$Model[[method[i]]]$bt.stdev[which(is.na(x[[i]]$Model[[method[i]]]$bt.stdev))] <-
x[[i]]$Model[[method[i]]]$bt.par[which(is.na(x[[i]]$Model[[method[i]]]$bt.stdev))]*
mean(unlist(x[[i]]$Model[[method[i]]]$bt.stdev[which(!is.na(x[[i]]$Model[[method[i]]]$bt.stdev))])/
unlist(x[[i]]$Model[[method[i]]]$bt.par[which(!is.na(x[[i]]$Model[[method[i]]]$bt.stdev))]))
}
mt <- x[[i]]$Model[[method[i]]]$Type
Thou.scaler <- 1e6*(x[[i]]$Data$Properties$Units[4]=="bill") +
1e3*(x[[i]]$Data$Properties$Units[4]=="mill") +
1e0*(x[[i]]$Data$Properties$Units[4]=="thou") +
1e-1*(x[[i]]$Data$Properties$Units[4]=="hund")
M <- unlist(x[[i]]$Model[[method[i]]]$bt.par["M"])
SE.M <- unlist(x[[i]]$Model[[method[i]]]$bt.stdev["M"])
N0 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par["N0"])
SE.N0 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev["N0"])
if(sum(mt == c(0,0))==2)
{
PredStock$N0Tot.thou[i] <- N0
PredStock$N0Tor.thou.SE[i] <- SE.N0
PredStock$B0Tot.ton[i] <- N0*mbw.sd[i,2]
PredStock$B0Tot.ton.SE[i] <- sqrt((SE.N0)^2*(mbw.sd[i,2])^2+(N0)^2*(mbw.sd[i,3])^2)
}
if(sum(mt == c(0,1))==2)
{
P1F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[6])
P1F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[6])
P1F2.back <- x[[i]]$Model[[method[i]]]$Dates[2]-x[[i]]$Model[[method[i]]]$Dates[1]+1
ts1 <- x[[i]]$Model[[method[i]]]$Dates[1]
cov <- cor2cov(x[[i]]$Model[[method[i]]]$Cor[c(1,2,6),c(1,2,6)],sd=c(SE.M,SE.N0,P1F2.SE))
PredStock$N0Tot.thou[i] <- N0 + P1F2*exp(M*P1F2.back)
form <- sprintf("~x2+x3*exp(x1*%i)",
P1F2.back)
PredStock$N0Tot.thou.SE[i] <- deltamethod(g=as.formula(form),
mean=c(M,N0,P1F2),
cov=cov)
PredStock$B0Tot.ton[i] <- PredStock$N0Tot.thou[i]*mbw.sd[i,2]
PredStock$B0Tot.ton.SE[i] <- sqrt((PredStock$N0Tot.thou.SE[i])^2*(mbw.sd[i,2])^2+(PredStock$N0Tot.thou[i])^2*(mbw.sd[i,3])^2)
}
if(sum(mt == c(0,2))==2)
{
P1F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[6])
P1F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[6])
P1F2.back <- x[[i]]$Model[[method[i]]]$Dates[2]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P2F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[7])
P2F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[7])
P2F2.back <- x[[i]]$Model[[method[i]]]$Dates[3]-x[[i]]$Model[[method[i]]]$Dates[1]+1
cov <- cor2cov(x[[i]]$Model[[method[i]]]$Cor[c(1,2,6,7),c(1,2,6,7)],sd=c(SE.M,SE.N0,P1F2.SE,P2F2.SE))
PredStock$N0Tot.thou[i] <- N0 + P1F2*exp(M*P1F2.back) +
P2F2*exp(M*P2F2.back)
form <- sprintf("~x2+x3*exp(x1*%i)+x4*exp(x1*%i)",
P1F2.back,P2F2.back)
PredStock$N0Tot.thou.SE[i] <- deltamethod(g=as.formula(form),
mean=c(M,N0,P1F2,P2F2),
cov=cov)
PredStock$B0Tot.ton[i] <- PredStock$N0Tot.thou[i]*mbw.sd[i,2]
PredStock$B0Tot.ton.SE[i] <- sqrt((PredStock$N0Tot.thou.SE[i])^2*(mbw.sd[i,2])^2+(PredStock$N0Tot.thou[i])^2*(mbw.sd[i,3])^2)
}
if(sum(mt == c(0,3))==2)
{
P1F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[6])
P1F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[6])
P1F2.back <- x[[i]]$Model[[method[i]]]$Dates[2]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P2F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[7])
P2F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[7])
P2F2.back <- x[[i]]$Model[[method[i]]]$Dates[3]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P3F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[8])
P3F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[8])
P3F2.back <- x[[i]]$Model[[method[i]]]$Dates[4]-x[[i]]$Model[[method[i]]]$Dates[1]+1
cov <- cor2cov(x[[i]]$Model[[method[i]]]$Cor[c(1,2,6,7,8),c(1,2,6,7,8)],sd=c(SE.M,SE.N0,P1F2.SE,P2F2.SE,P3F2.SE))
PredStock$N0Tot.thou[i] <- N0 + P1F2*exp(M*P1F2.back) +
P2F2*exp(M*P2F2.back) +
P3F2*exp(M*P3F2.back)
form <- sprintf("~x2+x3*exp(x1*%i)+x4*exp(x1*%i)+x5*exp(x1*%i)",
P1F2.back,P2F2.back,P3F2.back)
PredStock$N0Tot.thou.SE[i] <- deltamethod(g=as.formula(form),
mean=c(M,N0,P1F2,P2F2,P3F2),
cov=cov)
PredStock$B0Tot.ton[i] <- PredStock$N0Tot.thou[i]*mbw.sd[i,2]
PredStock$B0Tot.ton.SE[i] <- sqrt((PredStock$N0Tot.thou.SE[i])^2*(mbw.sd[i,2])^2+(PredStock$N0Tot.thou[i])^2*(mbw.sd[i,3])^2)
}
if(sum(mt == c(0,4))==2)
{
P1F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[6])
P1F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[6])
P1F2.back <- x[[i]]$Model[[method[i]]]$Dates[2]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P2F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[7])
P2F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[7])
P2F2.back <- x[[i]]$Model[[method[i]]]$Dates[3]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P3F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[8])
P3F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[8])
P3F2.back <- x[[i]]$Model[[method[i]]]$Dates[4]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P4F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[9])
P4F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[9])
P4F2.back <- x[[i]]$Model[[method[i]]]$Dates[5]-x[[i]]$Model[[method[i]]]$Dates[1]+1
ts1 <- x[[i]]$Model[[method[i]]]$Dates[1]
cov <- cor2cov(x[[i]]$Model[[method[i]]]$Cor[c(1,2,6:9),c(1,2,6:9)],sd=c(SE.M,SE.N0,P1F2.SE,P2F2.SE,P3F2.SE,P4F2.SE))
PredStock$N0Tot.thou[i] <- N0 + P1F2*exp(M*P1F2.back) +
P2F2*exp(M*P2F2.back) +
P3F2*exp(M*P3F2.back) +
P4F2*exp(M*P4F2.back)
form <- sprintf("~x2+x3*exp(x1*%i)+x4*exp(x1*%i)+x5*exp(x1*%i)+x6*exp(x1*%i)",
P1F2.back,P2F2.back,P3F2.back,P4F2.back)
PredStock$N0Tot.thou.SE[i] <- deltamethod(g=as.formula(form),
mean=c(M,N0,P1F2,P2F2,P3F2,P4F2),
cov=cov)
PredStock$B0Tot.ton[i] <- PredStock$N0Tot.thou[i]*mbw.sd[i,2]
PredStock$B0Tot.ton.SE[i] <- sqrt((PredStock$N0Tot.thou.SE[i])^2*(mbw.sd[i,2])^2+(PredStock$N0Tot.thou[i])^2*(mbw.sd[i,3])^2)
}
if(sum(mt == c(0,5))==2)
{
P1F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[6])
P1F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[6])
P1F2.back <- x[[i]]$Model[[method[i]]]$Dates[2]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P2F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[7])
P2F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[7])
P2F2.back <- x[[i]]$Model[[method[i]]]$Dates[3]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P3F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[8])
P3F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[8])
P3F2.back <- x[[i]]$Model[[method[i]]]$Dates[4]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P4F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[9])
P4F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[9])
P4F2.back <- x[[i]]$Model[[method[i]]]$Dates[5]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P5F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[10])
P5F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[10])
P5F2.back <- x[[i]]$Model[[method[i]]]$Dates[6]-x[[i]]$Model[[method[i]]]$Dates[1]+1
cov <- cor2cov(x[[i]]$Model[[method[i]]]$Cor[c(1,2,6:10),c(1,2,6:10)],sd=c(SE.M,SE.N0,P1F2.SE,P2F2.SE,P3F2.SE,P4F2.SE,P5F2.SE))
PredStock$N0Tot.thou[i] <- N0 + P1F2*exp(M*P1F2.back) +
P2F2*exp(M*P2F2.back) +
P3F2*exp(M*P3F2.back) +
P4F2*exp(M*P4F2.back) +
P5F2*exp(M*P5F2.back)
form <- sprintf("~x2+x3*exp(x1*%i)+x4*exp(x1*%i)+x5*exp(x1*%i)+x6*exp(x1*%i)+x7*exp(x1*%i)",
P1F2.back,P2F2.back,P3F2.back,P4F2.back,P5F2.back)
PredStock$N0Tot.thou.SE[i] <- deltamethod(g=as.formula(form),
mean=c(M,N0,P1F2,P2F2,P3F2,P4F2,P5F2),
cov=cov)
PredStock$B0Tot.ton[i] <- PredStock$N0Tot.thou[i]*mbw.sd[i,2]
PredStock$B0Tot.ton.SE[i] <- sqrt((PredStock$N0Tot.thou.SE[i])^2*(mbw.sd[i,2])^2+(PredStock$N0Tot.thou[i])^2*(mbw.sd[i,3])^2)
}
if(sum(mt == c(1,1))==2)
{
P1F1 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[3])
P1F1.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[3])
P1F1.back <- x[[i]]$Model[[method[i]]]$Dates[2]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P1F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[7])
P1F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[7])
P1F2.back <- x[[i]]$Model[[method[i]]]$Dates[3]-x[[i]]$Model[[method[i]]]$Dates[1]+1
cov <- cor2cov(x[[i]]$Model[[method[i]]]$Cor[c(1,2,3,7),c(1,2,3,7)],sd=c(SE.M,SE.N0,P1F1.SE,P1F2.SE))
PredStock$N0Tot.thou[i] <- N0 + P1F1*exp(M*P1F1.back) +
P1F2*exp(M*P1F2.back)
form <- sprintf("~x2+x3*exp(x1*%i)+x4*exp(x1*%i)",
P1F1.back,P1F2.back)
PredStock$N0Tot.thou.SE[i] <- deltamethod(g=as.formula(form),
mean=c(M,N0,P1F1,P1F2),
cov=cov)
PredStock$B0Tot.ton[i] <- PredStock$N0Tot.thou[i]*mbw.sd[i,2]
PredStock$B0Tot.ton.SE[i] <- sqrt((PredStock$N0Tot.thou.SE[i])^2*(mbw.sd[i,2])^2+(PredStock$N0Tot.thou[i])^2*(mbw.sd[i,3])^2)
}
if(sum(mt == c(1,2))==2)
{
P1F1 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[3])
P1F1.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[3])
P1F1.back <- x[[i]]$Model[[method[i]]]$Dates[2]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P1F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[7])
P1F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[7])
P1F2.back <- x[[i]]$Model[[method[i]]]$Dates[3]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P2F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[8])
P2F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[8])
P2F2.back <- x[[i]]$Model[[method[i]]]$Dates[4]-x[[i]]$Model[[method[i]]]$Dates[1]+1
cov <- cor2cov(x[[i]]$Model[[method[i]]]$Cor[c(1,2,3,7,8),c(1,2,3,7,8)],sd=c(SE.M,SE.N0,P1F1.SE,P1F2.SE,P2F2.SE))
PredStock$N0Tot.thou[i] <- N0 + P1F1*exp(M*P1F1.back) +
P1F2*exp(M*P1F2.back) +
P2F2*exp(M*P2F2.back)
form <- sprintf("~x2+x3*exp(x1*%i)+x4*exp(x1*%i)+x5*exp(x1*%i)",
P1F1.back,P1F2.back,P2F2.back)
PredStock$N0Tot.thou.SE[i] <- deltamethod(g=as.formula(form),
mean=c(M,N0,P1F1,P1F2,P2F2),
cov=cov)
PredStock$B0Tot.ton[i] <- PredStock$N0Tot.thou[i]*mbw.sd[i,2]
PredStock$B0Tot.ton.SE[i] <- sqrt((PredStock$N0Tot.thou.SE[i])^2*(mbw.sd[i,2])^2+(PredStock$N0Tot.thou[i])^2*(mbw.sd[i,3])^2)
}
if(sum(mt == c(1,3))==2)
{
P1F1 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[3])
P1F1.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[3])
P1F1.back <- x[[i]]$Model[[method[i]]]$Dates[2]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P1F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[7])
P1F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[7])
P1F2.back <- x[[i]]$Model[[method[i]]]$Dates[3]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P2F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[8])
P2F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[8])
P2F2.back <- x[[i]]$Model[[method[i]]]$Dates[4]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P3F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[9])
P3F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[9])
P3F2.back <- x[[i]]$Model[[method[i]]]$Dates[5]-x[[i]]$Model[[method[i]]]$Dates[1]+1
cov <- cor2cov(x[[i]]$Model[[method[i]]]$Cor[c(1,2,3,7:9),c(1,2,3,7:9)],sd=c(SE.M,SE.N0,P1F1.SE,P1F2.SE,P2F2.SE,P3F2.SE))
PredStock$N0Tot.thou[i] <- N0 + P1F1*exp(M*P1F1.back) +
P1F2*exp(M*P1F2.back) +
P2F2*exp(M*P2F2.back) +
P3F2*exp(M*P3F2.back)
form <- sprintf("~x2+x3*exp(x1*%i)+x4*exp(x1*%i)+x5*exp(x1*%i)+x6*exp(x1*%i)",
P1F1.back,P1F2.back,P2F2.back,P3F2.back)
PredStock$N0Tot.thou.SE[i] <- deltamethod(g=as.formula(form),
mean=c(M,N0,P1F1,P1F2,P2F2,P3F2),
cov=cov)
PredStock$B0Tot.ton[i] <- PredStock$N0Tot.thou[i]*mbw.sd[i,2]
PredStock$B0Tot.ton.SE[i] <- sqrt((PredStock$N0Tot.thou.SE[i])^2*(mbw.sd[i,2])^2+(PredStock$N0Tot.thou[i])^2*(mbw.sd[i,3])^2)
}
if(sum(mt == c(1,4))==2)
{
P1F1 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[3])
P1F1.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[3])
P1F1.back <- x[[i]]$Model[[method[i]]]$Dates[2]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P1F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[7])
P1F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[7])
P1F2.back <- x[[i]]$Model[[method[i]]]$Dates[3]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P2F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[8])
P2F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[8])
P2F2.back <- x[[i]]$Model[[method[i]]]$Dates[4]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P3F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[9])
P3F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[9])
P3F2.back <- x[[i]]$Model[[method[i]]]$Dates[5]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P4F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[10])
P4F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[10])
P4F2.back <- x[[i]]$Model[[method[i]]]$Dates[6]-x[[i]]$Model[[method[i]]]$Dates[1]+1
cov <- cor2cov(x[[i]]$Model[[method[i]]]$Cor[c(1,2,3,7:10),c(1,2,3,7:10)],sd=c(SE.M,SE.N0,P1F1.SE,P1F2.SE,P2F2.SE,P3F2.SE,P4F2.SE))
PredStock$N0Tot.thou[i] <- N0 + P1F1*exp(M*P1F1.back) +
P1F2*exp(M*P1F2.back) +
P2F2*exp(M*P2F2.back) +
P3F2*exp(M*P3F2.back) +
P4F2*exp(M*P4F2.back)
form <- sprintf("~x2+x3*exp(x1*%i)+x4*exp(x1*%i)+x5*exp(x1*%i)+x6*exp(x1*%i)+x7*exp(x1*%i)",
P1F1.back,P1F2.back,P2F2.back,P3F2.back,P4F2.back)
PredStock$N0Tot.thou.SE[i] <- deltamethod(g=as.formula(form),
mean=c(M,N0,P1F1,P1F2,P2F2,P3F2,P4F2),
cov=cov)
PredStock$B0Tot.ton[i] <- PredStock$N0Tot.thou[i]*mbw.sd[i,2]
PredStock$B0Tot.ton.SE[i] <- sqrt((PredStock$N0Tot.thou.SE[i])^2*(mbw.sd[i,2])^2+(PredStock$N0Tot.thou[i])^2*(mbw.sd[i,3])^2)
}
if(sum(mt == c(1,5))==2)
{
P1F1 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[3])
P1F1.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[3])
P1F1.back <- x[[i]]$Model[[method[i]]]$Dates[2]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P1F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[7])
P1F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[7])
P1F2.back <- x[[i]]$Model[[method[i]]]$Dates[3]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P2F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[8])
P2F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[8])
P2F2.back <- x[[i]]$Model[[method[i]]]$Dates[4]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P3F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[9])
P3F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[9])
P3F2.back <- x[[i]]$Model[[method[i]]]$Dates[5]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P4F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[10])
P4F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[10])
P4F2.back <- x[[i]]$Model[[method[i]]]$Dates[6]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P5F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[11])
P5F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[11])
P5F2.back <- x[[i]]$Model[[method[i]]]$Dates[7]-x[[i]]$Model[[method[i]]]$Dates[1]+1
ts1 <-
cov <- cor2cov(x[[i]]$Model[[method[i]]]$Cor[c(1,2,3,7:11),c(1,2,3,7:11)],
sd=c(SE.M,SE.N0,P1F1.SE,P1F2.SE,P2F2.SE,P3F2.SE,P4F2.SE,P5F2.SE))
PredStock$N0Tot.thou[i] <- N0 + P1F1*exp(M*P1F1.back) +
P1F2*exp(M*P1F2.back) +
P2F2*exp(M*P2F2.back) +
P3F2*exp(M*P3F2.back) +
P4F2*exp(M*P4F2.back) +
P5F2*exp(M*P5F2.back)
form <- sprintf("~x2+x3*exp(x1*%i)+x4*exp(x1*%i)+x5*exp(x1*%i)+x6*exp(x1*%i)+x7*exp(x1*%i)+x8*exp(x1*%i)",
P1F1.back,P1F2.back,P2F2.back,P3F2.back,P4F2.back,P5F2.back)
PredStock$N0Tot.thou.SE[i] <- deltamethod(g=as.formula(form),
mean=c(M,N0,P1F1,P1F2,P2F2,P3F2,P4F2,P5F2),
cov=cov)
PredStock$B0Tot.ton[i] <- PredStock$N0Tot.thou[i]*mbw.sd[i,2]
PredStock$B0Tot.ton.SE[i] <- sqrt((PredStock$N0Tot.thou.SE[i])^2*(mbw.sd[i,2])^2+(PredStock$N0Tot.thou[i])^2*(mbw.sd[i,3])^2)
}
if(sum(mt == c(2,2))==2)
{
P1F1 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[3])
P1F1.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[3])
P1F1.back <- x[[i]]$Model[[method[i]]]$Dates[2]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P2F1 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[4])
P2F1.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[4])
P2F1.back <- x[[i]]$Model[[method[i]]]$Dates[3]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P1F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[8])
P1F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[8])
P1F2.back <- x[[i]]$Model[[method[i]]]$Dates[4]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P2F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[9])
P2F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[9])
P2F2.back <- x[[i]]$Model[[method[i]]]$Dates[5]-x[[i]]$Model[[method[i]]]$Dates[1]+1
cov <- cor2cov(x[[i]]$Model[[method[i]]]$Cor[c(1,2,3,4,8,9),c(1,2,3,4,8,9)],
sd=c(SE.M,SE.N0,P1F1.SE,P2F1.SE,P1F2.SE,P2F2.SE))
PredStock$N0Tot.thou[i] <- N0 + P1F1*exp(M*P1F1.back) +
P2F1*exp(M*P1F1.back) +
P1F2*exp(M*P1F2.back) +
P2F2*exp(M*P2F2.back)
form <- sprintf("~x2+x3*exp(x1*%i)+x4*exp(x1*%i)+x5*exp(x1*%i)+x6*exp(x1*%i)",
P1F1.back,P2F1.back,P1F2.back,P2F2.back)
PredStock$N0Tot.thou.SE[i] <- deltamethod(g=as.formula(form),
mean=c(M,N0,P1F1,P2F1,P1F2,P2F2),
cov=cov)
PredStock$B0Tot.ton[i] <- PredStock$N0Tot.thou[i]*mbw.sd[i,2]
PredStock$B0Tot.ton.SE[i] <- sqrt((PredStock$N0Tot.thou.SE[i])^2*(mbw.sd[i,2])^2+(PredStock$N0Tot.thou[i])^2*(mbw.sd[i,3])^2)
}
if(sum(mt == c(2,3))==2)
{
P1F1 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[3])
P1F1.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[3])
P1F1.back <- x[[i]]$Model[[method[i]]]$Dates[2]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P2F1 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[4])
P2F1.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[4])
P2F1.back <- x[[i]]$Model[[method[i]]]$Dates[3]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P1F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[8])
P1F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[8])
P1F2.back <- x[[i]]$Model[[method[i]]]$Dates[4]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P2F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[9])
P2F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[9])
P2F2.back <- x[[i]]$Model[[method[i]]]$Dates[5]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P3F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[10])
P3F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[10])
P3F2.back <- x[[i]]$Model[[method[i]]]$Dates[6]-x[[i]]$Model[[method[i]]]$Dates[1]+1
cov <- cor2cov(x[[i]]$Model[[method[i]]]$Cor[c(1,2,3,4,8:10),c(1,2,3,4,8:10)],
sd=c(SE.M,SE.N0,P1F1.SE,P2F1.SE,P1F2.SE,P2F2.SE,P3F2.SE))
PredStock$N0Tot.thou[i] <- N0 + P1F1*exp(M*P1F1.back) +
P2F1*exp(M*P2F1.back) +
P1F2*exp(M*P1F2.back) +
P2F2*exp(M*P2F2.back) +
P3F2*exp(M*P3F2.back)
form <- sprintf("~x2+x3*exp(x1*%i)+x4*exp(x1*%i)+x5*exp(x1*%i)+x6*exp(x1*%i)+x7*exp(x1*%i)",
P1F1.back,P2F1.back,P1F2.back,P2F2.back,P3F2.back)
PredStock$N0Tot.thou.SE[i] <- deltamethod(g=as.formula(form),
mean=c(M,N0,P1F1,P2F1,P1F2,P2F2,P3F2),
cov=cov)
PredStock$B0Tot.ton[i] <- PredStock$N0Tot.thou[i]*mbw.sd[i,2]
PredStock$B0Tot.ton.SE[i] <- sqrt((PredStock$N0Tot.thou.SE[i])^2*(mbw.sd[i,2])^2+(PredStock$N0Tot.thou[i])^2*(mbw.sd[i,3])^2)
}
if(sum(mt == c(2,4))==2)
{
P1F1 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[3])
P1F1.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[3])
P1F1.back <- x[[i]]$Model[[method[i]]]$Dates[2]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P2F1 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[4])
P2F1.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[4])
P2F1.back <- x[[i]]$Model[[method[i]]]$Dates[3]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P1F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[8])
P1F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[8])
P1F2.back <- x[[i]]$Model[[method[i]]]$Dates[4]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P2F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[9])
P2F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[9])
P2F2.back <- x[[i]]$Model[[method[i]]]$Dates[5]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P3F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[10])
P3F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[10])
P3F2.back <- x[[i]]$Model[[method[i]]]$Dates[6]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P4F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[11])
P4F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[11])
P4F2.back <- x[[i]]$Model[[method[i]]]$Dates[7]-x[[i]]$Model[[method[i]]]$Dates[1]+1
cov <- cor2cov(x[[i]]$Model[[method[i]]]$Cor[c(1,2,3,4,8:11),c(1,2,3,4,8:11)],
sd=c(SE.M,SE.N0,P1F1.SE,P2F1.SE,P1F2.SE,P2F2.SE,P3F2.SE,P4F2.SE))
PredStock$N0Tot.thou[i] <- N0 + P1F1*exp(M*P1F1.back) +
P2F1*exp(M*P2F1.back) +
P1F2*exp(M*P1F2.back) +
P2F2*exp(M*P2F2.back) +
P3F2*exp(M*P3F2.back) +
P4F2*exp(M*P4F2.back)
form <- sprintf("~x2+x3*exp(x1*%i)+x4*exp(x1*%i)+x5*exp(x1*%i)+x6*exp(x1*%i)+x7*exp(x1*%i)+x8*exp(x1*%i)",
P1F1.back,P2F1.back,P1F2.back,P2F2.back,P3F2.back,P4F2.back)
PredStock$N0Tot.thou.SE[i] <- deltamethod(g=as.formula(form),
mean=c(M,N0,P1F1,P2F1,P1F2,P2F2,P3F2,P4F2),
cov=cov)
PredStock$B0Tot.ton[i] <- PredStock$N0Tot.thou[i]*mbw.sd[i,2]
PredStock$B0Tot.ton.SE[i] <- sqrt((PredStock$N0Tot.thou.SE[i])^2*(mbw.sd[i,2])^2+(PredStock$N0Tot.thou[i])^2*(mbw.sd[i,3])^2)
}
if(sum(mt == c(2,5))==2)
{
P1F1 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[3])
P1F1.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[3])
P1F1.back <- x[[i]]$Model[[method[i]]]$Dates[2]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P2F1 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[4])
P2F1.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[4])
P2F1.back <- x[[i]]$Model[[method[i]]]$Dates[3]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P1F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[8])
P1F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[8])
P1F2.back <- x[[i]]$Model[[method[i]]]$Dates[4]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P2F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[9])
P2F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[9])
P2F2.back <- x[[i]]$Model[[method[i]]]$Dates[5]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P3F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[10])
P3F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[10])
P3F2.back <- x[[i]]$Model[[method[i]]]$Dates[6]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P4F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[11])
P4F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[11])
P4F2.back <- x[[i]]$Model[[method[i]]]$Dates[7]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P5F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[12])
P5F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[12])
P5F2.back <- x[[i]]$Model[[method[i]]]$Dates[8]-x[[i]]$Model[[method[i]]]$Dates[1]+1
cov <- cor2cov(x[[i]]$Model[[method[i]]]$Cor[c(1,2,3,4,8:12),c(1,2,3,4,8:12)],
sd=c(SE.M,SE.N0,P1F1.SE,P2F1.SE,P1F2.SE,P2F2.SE,P3F2.SE,P4F2.SE,P5F2.SE))
PredStock$N0Tot.thou[i] <- N0 + P1F1*exp(M*P1F1.back) +
P2F1*exp(M*P2F2.back) +
P1F2*exp(M*P1F2.back) +
P2F2*exp(M*P2F2.back) +
P3F2*exp(M*P3F2.back) +
P4F2*exp(M*P4F2.back) +
P5F2*exp(M*P5F2.back)
form <- sprintf("~x2+x3*exp(x1*%i)+x4*exp(x1*%i)+x5*exp(x1*%i)+x6*exp(x1*%i)+x7*exp(x1*%i)+x8*exp(x1*%i)+x9*exp(x1*%i)",
P1F1.back,P2F1.back,P1F2.back,P2F2.back,P3F2.back,P4F2.back,P5F2.back)
PredStock$N0Tot.thou.SE[i] <- deltamethod(g=as.formula(form),
mean=c(M,N0,P1F1,P2F1,P1F2,P2F2,P3F2,P4F2,P5F2),
cov=cov)
PredStock$B0Tot.ton[i] <- PredStock$N0Tot.thou[i]*mbw.sd[i,2]
PredStock$B0Tot.ton.SE[i] <- sqrt((PredStock$N0Tot.thou.SE[i])^2*(mbw.sd[i,2])^2+(PredStock$N0Tot.thou[i])^2*(mbw.sd[i,3])^2)
}
if(sum(mt == c(3,3))==2)
{
P1F1 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[3])
P1F1.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[3])
P1F1.back <- x[[i]]$Model[[method[i]]]$Dates[2]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P2F1 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[4])
P2F1.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[4])
P2F1.back <- x[[i]]$Model[[method[i]]]$Dates[3]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P3F1 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[5])
P3F1.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[5])
P3F1.back <- x[[i]]$Model[[method[i]]]$Dates[4]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P1F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[9])
P1F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[9])
P1F2.back <- x[[i]]$Model[[method[i]]]$Dates[5]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P2F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[10])
P2F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[10])
P2F2.back <- x[[i]]$Model[[method[i]]]$Dates[6]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P3F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[11])
P3F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[11])
P3F2.back <- x[[i]]$Model[[method[i]]]$Dates[7]-x[[i]]$Model[[method[i]]]$Dates[1]+1
cov <- cor2cov(x[[i]]$Model[[method[i]]]$Cor[c(1:5,9:11),c(1:5,9:11)],
sd=c(SE.M,SE.N0,P1F1.SE,P2F1.SE,P3F1.SE,P1F2.SE,P2F2.SE,P3F2.SE))
PredStock$N0Tot.thou[i] <- N0 + P1F1*exp(M*P1F1.back) +
P2F1*exp(M*P2F1.back) +
P3F1*exp(M*P3F1.back) +
P1F2*exp(M*P1F2.back) +
P2F2*exp(M*P2F2.back) +
P3F2*exp(M*P3F2.back)
form <- sprintf("~x2+x3*exp(x1*%i)+x4*exp(x1*%i)+x5*exp(x1*%i)+x6*exp(x1*%i)+x7*exp(x1*%i)+x8*exp(x1*%i)",
P1F1.back,P2F1.back,P3F1.back,P1F2.back,P2F2.back,P3F2.back)
PredStock$N0Tot.thou.SE[i] <- deltamethod(g=as.formula(form),
mean=c(M,N0,P1F1,P2F1,P3F1,P1F2,P2F2,P3F2),
cov=cov)
PredStock$B0Tot.ton[i] <- PredStock$N0Tot.thou[i]*mbw.sd[i,2]
PredStock$B0Tot.ton.SE[i] <- sqrt((PredStock$N0Tot.thou.SE[i])^2*(mbw.sd[i,2])^2+(PredStock$N0Tot.thou[i])^2*(mbw.sd[i,3])^2)
}
if(sum(mt == c(3,4))==2)
{
P1F1 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[3])
P1F1.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[3])
P1F1.back <- x[[i]]$Model[[method[i]]]$Dates[2]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P2F1 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[4])
P2F1.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[4])
P2F1.back <- x[[i]]$Model[[method[i]]]$Dates[3]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P3F1 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[5])
P3F1.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[5])
P3F1.back <- x[[i]]$Model[[method[i]]]$Dates[4]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P1F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[9])
P1F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[9])
P1F2.back <- x[[i]]$Model[[method[i]]]$Dates[5]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P2F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[10])
P2F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[10])
P2F2.back <- x[[i]]$Model[[method[i]]]$Dates[6]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P3F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[11])
P3F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[11])
P3F2.back <- x[[i]]$Model[[method[i]]]$Dates[7]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P4F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[12])
P4F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[12])
P4F2.back <- x[[i]]$Model[[method[i]]]$Dates[8]-x[[i]]$Model[[method[i]]]$Dates[1]+1
cov <- cor2cov(x[[i]]$Model[[method[i]]]$Cor[c(1:5,9:12),c(1:5,9:12)],
sd=c(SE.M,SE.N0,P1F1.SE,P2F1.SE,P3F1.SE,P1F2.SE,P2F2.SE,P3F2.SE,P4F2.SE))
PredStock$N0Tot.thou[i] <- N0 + P1F1*exp(M*P1F1.back) +
P2F1*exp(M*P2F1.back) +
P3F1*exp(M*P3F1.back) +
P1F2*exp(M*P1F2.back) +
P2F2*exp(M*P2F2.back) +
P3F2*exp(M*P3F2.back) +
P4F2*exp(M*P4F2.back)
form <- sprintf("~x2+x3*exp(x1*%i)+x4*exp(x1*%i)+x5*exp(x1*%i)+x6*exp(x1*%i)+x7*exp(x1*%i)+x8*exp(x1*%i)+x9*exp(x1*%i)",
P1F1.back,P2F1.back,P3F1.back,P1F2.back,P2F2.back,P3F2.back,P4F2.back)
PredStock$N0Tot.thou.SE[i] <- deltamethod(g=as.formula(form),
mean=c(M,N0,P1F1,P2F1,P3F1,P1F2,P2F2,P3F2,P4F2),
cov=cov)
PredStock$B0Tot.ton[i] <- PredStock$N0Tot.thou[i]*mbw.sd[i,2]
PredStock$B0Tot.ton.SE[i] <- sqrt((PredStock$N0Tot.thou.SE[i])^2*(mbw.sd[i,2])^2+(PredStock$N0Tot.thou[i])^2*(mbw.sd[i,3])^2)
}
if(sum(mt == c(3,5))==2)
{
P1F1 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[3])
P1F1.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[3])
P1F1.back <- x[[i]]$Model[[method[i]]]$Dates[2]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P2F1 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[4])
P2F1.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[4])
P2F1.back <- x[[i]]$Model[[method[i]]]$Dates[3]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P3F1 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[5])
P3F1.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[5])
P3F1.back <- x[[i]]$Model[[method[i]]]$Dates[4]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P1F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[9])
P1F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[9])
P1F2.back <- x[[i]]$Model[[method[i]]]$Dates[5]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P2F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[10])
P2F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[10])
P2F2.back <- x[[i]]$Model[[method[i]]]$Dates[6]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P3F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[11])
P3F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[11])
P3F2.back <- x[[i]]$Model[[method[i]]]$Dates[7]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P4F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[12])
P4F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[12])
P4F2.back <- x[[i]]$Model[[method[i]]]$Dates[8]-x[[i]]$Model[[method[i]]]$Dates[1]+1
P5F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[13])
P5F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[13])
P5F2.back <- x[[i]]$Model[[method[i]]]$Dates[9]-x[[i]]$Model[[method[i]]]$Dates[1]+1
cov <- cor2cov(x[[i]]$Model[[method[i]]]$Cor[c(1:5,9:13),c(1:5,9:13)],
sd=c(SE.M,SE.N0,P1F1.SE,P2F1.SE,P3F1.SE,P1F2.SE,P2F2.SE,P3F2.SE,P4F2.SE,P5F2.SE))
PredStock$N0Tot.thou[i] <- N0 + P1F1*exp(M*P1F1.back) +
P2F1*exp(M*P2F1.back) +
P3F1*exp(M*P3F1.back) +
P1F2*exp(M*P1F2.back) +
P2F2*exp(M*P2F2.back) +
P3F2*exp(M*P3F2.back) +
P4F2*exp(M*P4F2.back) +
P5F2*exp(M*P5F2.back)
form <- sprintf("~x2+x3*exp(x1*%i)+x4*exp(x1*%i)+x5*exp(x1*%i)+x6*exp(x1*%i)+x7*exp(x1*%i)+x8*exp(x1*%i)+x9*exp(x1*%i)+x10*exp(x1*%i)",
P1F1.back,P2F1.back,P3F1.back,P1F2.back,P2F2.back,P3F2.back,P4F2.back,P5F2.back)
PredStock$N0Tot.thou.SE[i] <- deltamethod(g=as.formula(form),
mean=c(M,N0,P1F1,P2F1,P3F1,P1F2,P2F2,P3F2,P4F2,P5F2),
cov=cov)
PredStock$B0Tot.ton[i] <- PredStock$N0Tot.thou[i]*mbw.sd[i,2]
PredStock$B0Tot.ton.SE[i] <- sqrt((PredStock$N0Tot.thou.SE[i])^2*(mbw.sd[i,2])^2+(PredStock$N0Tot.thou[i])^2*(mbw.sd[i,3])^2)
}
if(sum(mt == c(4,4))==2)
{
P1F1 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[3])
P1F1.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[3])
P1F1.ts <- x[[i]]$Model[[method[i]]]$Dates[2]
P2F1 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[4])
P2F1.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[4])
P2F1.ts <- x[[i]]$Model[[method[i]]]$Dates[3]
P3F1 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[5])
P3F1.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[5])
P3F1.ts <- x[[i]]$Model[[method[i]]]$Dates[4]
P4F1 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[6])
P4F1.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[6])
P4F1.ts <- x[[i]]$Model[[method[i]]]$Dates[5]
P1F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[10])
P1F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[10])
P1F2.ts <- x[[i]]$Model[[method[i]]]$Dates[6]
P2F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[11])
P2F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[11])
P2F2.ts <- x[[i]]$Model[[method[i]]]$Dates[7]
P3F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[12])
P3F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[12])
P3F2.ts <- x[[i]]$Model[[method[i]]]$Dates[8]
P4F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[13])
P4F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[13])
P4F2.ts <- x[[i]]$Model[[method[i]]]$Dates[9]
ts1 <- x[[i]]$Model[[method[i]]]$Dates[1]
cov <- cor2cov(x[[i]]$Model[[method[i]]]$Cor[c(1:6,10:13),c(1:6,10:13)],
sd=c(SE.M,SE.N0,P1F1.SE,P2F1.SE,P3F1.SE,P4F1.SE,P1F2.SE,P2F2.SE,P3F2.SE,P4F2.SE))
PredStock$N0Tot.thou[i] <- N0 + P1F1*exp(M*(P1F1.ts-ts1+1)) + P2F1*exp(M*(P2F1.ts-ts1+1)) + P3F1*exp(M*(P3F1.ts-ts1+1)) + P4F1*exp(M*(P4F1.ts-ts1+1)) +
P1F2*exp(M*(P1F2.ts-ts1+1)) + P2F2*exp(M*(P2F2.ts-ts1+1)) + P3F2*exp(M*(P3F2.ts-ts1+1)) + P4F2*exp(M*(P4F2.ts-ts1+1))
PredStock$N0Tot.thou.SE[i] <- deltamethod(g=list(~x2 + x3*exp(x1*(P1F1.ts-ts1+1)) + x4*exp(x1*(P2F1.ts-ts1+1)) + x5*exp(x1*(P3F1.ts-ts1+1)) + x6*exp(x1*(P4F1.ts-ts1+1)) +
x7*exp(x1*(P1F2.ts-ts1+1)) + x7*exp(x1*(P2F2.ts-ts1+1)) + x9*exp(x1*(P3F2.ts-ts1+1)) + x10*exp(x1*(P4F2.ts-ts1+1))),
mean=c(M,N0,P1F1,P2F1,P3F1,P4F1,P1F2,P2F2,P3F2,P4F2),
cov=cov)
PredStock$B0Tot.ton[i] <- PredStock$N0Tot.thou[i]*mbw.sd[i,2]
PredStock$B0Tot.ton.SE[i] <- sqrt((PredStock$N0Tot.thou.SE[i])^2*(mbw.sd[i,2])^2+(PredStock$N0Tot.thou[i])^2*(mbw.sd[i,3])^2)
}
if(sum(mt == c(4,5))==2)
{
P1F1 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[3])
P1F1.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[3])
P1F1.ts <- x[[i]]$Model[[method[i]]]$Dates[2]
P2F1 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[4])
P2F1.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[4])
P2F1.ts <- x[[i]]$Model[[method[i]]]$Dates[3]
P3F1 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[5])
P3F1.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[5])
P3F1.ts <- x[[i]]$Model[[method[i]]]$Dates[4]
P4F1 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[6])
P4F1.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[6])
P4F1.ts <- x[[i]]$Model[[method[i]]]$Dates[5]
P1F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[10])
P1F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[10])
P1F2.ts <- x[[i]]$Model[[method[i]]]$Dates[6]
P2F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[11])
P2F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[11])
P2F2.ts <- x[[i]]$Model[[method[i]]]$Dates[7]
P3F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[12])
P3F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[12])
P3F2.ts <- x[[i]]$Model[[method[i]]]$Dates[8]
P4F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[13])
P4F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[13])
P4F2.ts <- x[[i]]$Model[[method[i]]]$Dates[9]
P5F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[14])
P5F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[14])
P5F2.ts <- x[[i]]$Model[[method[i]]]$Dates[10]
ts1 <- x[[i]]$Model[[method[i]]]$Dates[1]
cov <- cor2cov(x[[i]]$Model[[method[i]]]$Cor[c(1:6,10:14),c(1:6,10:14)],
sd=c(SE.M,SE.N0,P1F1.SE,P2F1.SE,P3F1.SE,P4F1.SE,P1F2.SE,P2F2.SE,P3F2.SE,P4F2.SE,P5F2.SE))
PredStock$N0Tot.thou[i] <- N0 + P1F1*exp(M*(P1F1.ts-ts1+1)) + P2F1*exp(M*(P2F1.ts-ts1+1)) + P3F1*exp(M*(P3F1.ts-ts1+1)) + P4F1*exp(M*(P4F1.ts-ts1+1)) +
P1F2*exp(M*(P1F2.ts-ts1+1)) + P2F2*exp(M*(P2F2.ts-ts1+1)) + P3F2*exp(M*(P3F2.ts-ts1+1)) + P4F2*exp(M*(P4F2.ts-ts1+1)) + P5F2*exp(M*(P5F2.ts-ts1+1))
PredStock$N0Tot.thou.SE[i] <- deltamethod(g=list(~x2 + x3*exp(x1*(P1F1.ts-ts1+1)) + x4*exp(x1*(P2F1.ts-ts1+1)) + x5*exp(x1*(P3F1.ts-ts1+1)) + x6*exp(x1*(P4F1.ts-ts1+1)) +
x7*exp(x1*(P1F2.ts-ts1+1)) + x7*exp(x1*(P2F2.ts-ts1+1)) + x9*exp(x1*(P3F2.ts-ts1+1)) + x10*exp(x1*(P4F2.ts-ts1+1)) + x11*exp(x1*(P5F2.ts-ts1+1))),
mean=c(M,N0,P1F1,P2F1,P3F1,P4F1,P1F2,P2F2,P3F2,P4F2,P5F2),
cov=cov)
PredStock$B0Tot.ton[i] <- PredStock$N0Tot.thou[i]*mbw.sd[i,2]
PredStock$B0Tot.ton.SE[i] <- sqrt((PredStock$N0Tot.thou.SE[i])^2*(mbw.sd[i,2])^2+(PredStock$N0Tot.thou[i])^2*(mbw.sd[i,3])^2)
}
if(sum(mt == c(5,5))==2)
{
P1F1 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[3])
P1F1.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[3])
P1F1.ts <- x[[i]]$Model[[method[i]]]$Dates[2]
P2F1 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[4])
P2F1.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[4])
P2F1.ts <- x[[i]]$Model[[method[i]]]$Dates[3]
P3F1 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[5])
P3F1.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[5])
P3F1.ts <- x[[i]]$Model[[method[i]]]$Dates[4]
P4F1 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[6])
P4F1.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[6])
P4F1.ts <- x[[i]]$Model[[method[i]]]$Dates[5]
P5F1 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[7])
P5F1.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[7])
P5F1.ts <- x[[i]]$Model[[method[i]]]$Dates[6]
P1F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[11])
P1F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[11])
P1F2.ts <- x[[i]]$Model[[method[i]]]$Dates[7]
P2F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[12])
P2F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[12])
P2F2.ts <- x[[i]]$Model[[method[i]]]$Dates[8]
P3F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[13])
P3F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[13])
P3F2.ts <- x[[i]]$Model[[method[i]]]$Dates[9]
P4F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[14])
P4F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[14])
P4F2.ts <- x[[i]]$Model[[method[i]]]$Dates[10]
P5F2 <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.par[15])
P5F2.SE <- Thou.scaler*unlist(x[[i]]$Model[[method[i]]]$bt.stdev[15])
P5F2.ts <- x[[i]]$Model[[method[i]]]$Dates[11]
ts1 <- x[[i]]$Model[[method[i]]]$Dates[1]
cov <- cor2cov(x[[i]]$Model[[method[i]]]$Cor[c(1:7,11:15),c(1:7,11:15)],
sd=c(SE.M,SE.N0,P1F1.SE,P2F1.SE,P3F1.SE,P4F1.SE,P5F1.SE,P1F2.SE,P2F2.SE,P3F2.SE,P4F2.SE,P5F2.SE))
PredStock$N0Tot.thou[i] <- N0 + P1F1*exp(M*(P1F1.ts-ts1+1)) + P2F1*exp(M*(P2F1.ts-ts1+1)) + P3F1*exp(M*(P3F1.ts-ts1+1)) + P4F1*exp(M*(P4F1.ts-ts1+1)) + P5F1*exp(M*(P5F1.ts-ts1+1)) +
P1F2*exp(M*(P1F2.ts-ts1+1)) + P2F2*exp(M*(P2F2.ts-ts1+1)) + P3F2*exp(M*(P3F2.ts-ts1+1)) + P4F2*exp(M*(P4F2.ts-ts1+1)) + P5F2*exp(M*(P5F2.ts-ts1+1))
PredStock$N0Tot.thou.SE[i] <- deltamethod(g=list(~x2 + x3*exp(x1*(P1F1.ts-ts1+1)) + x4*exp(x1*(P2F1.ts-ts1+1)) + x5*exp(x1*(P3F1.ts-ts1+1)) + x6*exp(x1*(P4F1.ts-ts1+1)) + x7*exp(x1*(P5F1.ts-ts1+1)) +
x8*exp(x1*(P1F2.ts-ts1+1)) + x9*exp(x1*(P2F2.ts-ts1+1)) + x10*exp(x1*(P3F2.ts-ts1+1)) + x11*exp(x1*(P4F2.ts-ts1+1)) + x12*exp(x1*(P5F2.ts-ts1+1))),
mean=c(M,N0,P1F1,P2F1,P3F1,P4F1,P1F2,P2F2,P3F2,P4F2,P5F2),
cov=cov)
PredStock$B0Tot.ton[i] <- PredStock$N0Tot.thou[i]*mbw.sd[i,2]
PredStock$B0Tot.ton.SE[i] <- sqrt((PredStock$N0Tot.thou.SE[i])^2*(mbw.sd[i,2])^2+(PredStock$N0Tot.thou[i])^2*(mbw.sd[i,3])^2)
}
}
}
}
return(PredStock)
} |
pred <- function(model=NULL,n.ahead=20,tserie=NULL,predictions=NULL){
if(!is.null(model)){
if(!methods::is(model,"modl")) stop("Not a modl object")
predictions <- NULL
if(model$method=='arima') predictions <- pred.arima(model$model,n.ahead=n.ahead)
else if(model$method=='dataMining') predictions <- pred.dataMining(model,n.ahead=n.ahead)
obj <- list()
class(obj) <- "pred"
obj$tserie <- model$tserie
obj$predictions <- predictions
return (obj)
}else{
if(!stats::is.ts(tserie)) stop('Tserie not a ts object')
if(!stats::is.ts(predictions)) stop('Predictions not a ts object')
obj <- list()
class(obj) <- "pred"
obj$tserie <- tserie
obj$predictions <- predictions
return (obj)
}
}
pred.arima <- function(model,n.ahead){
if(!methods::is(model,"Arima")) stop("Not an Arima object")
if(n.ahead > 100) stop("n.ahead must be lower than 100")
return (stats::predict(model,n.ahead=n.ahead,se.fit=FALSE))
}
pred.dataMining <- function(model,n.ahead){
if(!methods::is(model,"modl")) stop("Not a modl object")
if(model$method != "dataMining") stop("model method has to be dataMining.")
if(n.ahead > 100) stop("n.ahead must be lower than 100")
data <- model$tserieDF
index <- length(data[,1]) - model$horizon
obs <- data[index,]
predictions <- NULL
for(i in 1:(n.ahead+model$horizon)){
for(j in 1:(ncol(obs))){
colnames(obs)[j] <- paste0('c_',j)
}
predictions[i] <- caret::predict.train(model$model,obs)
obs <- data.frame(c(obs[nrow(obs),2:ncol(obs)],predictions[i]))
}
predictionsTS <- stats::ts(predictions,start=end(model$tserie)-c(0,model$horizon),frequency=frequency(model$tserie))
return (predictionsTS)
}
pred.compareModels <- function(originalTS,p_1,p_2,p_3=NULL,p_4=NULL,p_5=NULL,
legendNames=NULL,colors=NULL,legend=TRUE,legendPosition=NULL,yAxis="Values",title="Predictions"){
if(!is.ts(originalTS) || !is.ts(p_1) || !is.ts(p_2)) stop('Not a ts object')
n <- 2
maxX <- max(end(p_1)[1],end(p_2)[1])
if(!is.null(p_3)) {
if(!is.ts(p_3)) stop('Not a ts object')
if(end(p_3)[1] > maxX) maxX <- end(p_3)[1]
n <- n+1
}
if(!is.null(p_4)) {
if(!is.ts(p_4)) stop('Not a ts object')
if(end(p_4)[1] > maxX) maxX <- end(p_4)[1]
n <- n+1
}
if(!is.null(p_5)) {
if(!is.ts(p_5)) stop('Not a ts object')
if(end(p_5)[1] > maxX) maxX <- end(p_5)[1]
n <- n+1
}
maxX <- maxX+1
minY <- min(originalTS,p_1,p_2,p_3,p_4,p_5)
maxY <- max(originalTS,p_1,p_2,p_3,p_4,p_5)
xlim <- c(start(originalTS)[1],maxX)
ylim <- c(minY,maxY)
if(is.null(colors)){
colors <- c('black','green','blue','darkgoldenrod1','aquamarine3','darkorchid' )
colors <- c(colors[1:(n+1)])
}else if(length(colors) != (n+1)) stop('Vector "colors" wrong size. Has to contain colors for every time serie (including the original one)')
if(is.null(legendNames)){
legendNames <- c('Original TS','Predictions','Predictions','Predictions','Predictions','Predictions')
legendNames <- c(legendNames[1:(n+1)])
}else if(length(legendNames) != (n+1)) stop('Vector "legendNames" wrong size. Has to contain legend names for every time serie (including the original one)')
graphics::plot(originalTS,xlim=xlim,ylim=ylim,col=colors[1],ylab=yAxis)
title(main=paste0(title))
graphics::lines(p_1,col=colors[2])
graphics::lines(p_2,col=colors[3])
colorCounter <- 4
if(!is.null(p_3)) {
graphics::lines(p_3,col=colors[colorCounter])
colorCounter <- colorCounter+1
}
if(!is.null(p_4)) {
graphics::lines(p_4,col=colors[colorCounter])
colorCounter <- colorCounter+1
}
if(!is.null(p_5)) {
graphics::lines(p_5,col=colors[colorCounter])
colorCounter <- colorCounter+1
}
if(legend){
if(is.null(legendPosition))
legendPosition <- "bottomright"
legend(legendPosition,lty=c(1,1),col=colors,legend=legendNames)
}
}
plot.pred <- function(x,ylab="Values",main="Predictions",...){
maxX <- end(x$predictions)
minY <- min(x$tserie,x$predictions)
maxY <- max(x$tserie,x$predictions)
xlim <- c(start(x$tserie)[1],maxX[1])
ylim <- c(minY,maxY)
colors <- c('black','green')
graphics::plot(x$tserie,xlim=xlim,ylim=ylim,col=colors[1],ylab=ylab,main=main)
graphics::lines(x$predictions,col=colors[2])
}
summary.pred <- function(object,...){
cat("Predicted time serie object\n\n")
cat("~Original time serie:\n")
utils::str(object$tserie)
cat("\n")
cat("~Predictions (n=",length(object$predictions),"):\n")
utils::str(object$predictions)
}
print.pred <- function(x,...){
cat("Predicted time serie object\n\n")
cat("Class: pred\n\n")
cat("Attributes: \n")
cat("$tserie: \n")
print(x$tserie)
cat("\n")
cat("$predictions: \n")
print(x$predictions)
} |
wrcc_loadDaily <- function(
parameter = 'PM2.5',
baseUrl = 'https://haze.airfire.org/monitoring/latest/RData',
dataDir = NULL
) {
validParams <- c("PM2.5")
if ( !parameter %in% validParams ) {
paramsString <- paste(validParams, collapse=", ")
stop(paste0("'", parameter,
"' is not a supported parameter. Use 'parameter = ",
paramsString, "'"), call.=FALSE)
}
filename <- paste0("wrcc_", parameter, "_latest45.RData")
ws_monitor <- MazamaCoreUtils::loadDataFile(filename, baseUrl, dataDir)
return(ws_monitor)
} |
.GlobalEnv <- globalenv()
attach(NULL, name = "Autoloads")
.AutoloadEnv <- as.environment(2)
assign(".Autoloaded", NULL, envir = .AutoloadEnv)
T <- TRUE
F <- FALSE
R.version <- structure(R.Version(), class = "simple.list")
version <- R.version
R.version.string <- R.version$version.string
options(keep.source = interactive())
options(warn = 0)
options(timeout = 60)
options(encoding = "native.enc")
options(show.error.messages = TRUE)
options(scipen = 0)
options(max.print = 99999)
options(add.smooth = TRUE)
options(stringsAsFactors = TRUE)
if(!interactive() && is.null(getOption("showErrorCalls")))
options(showErrorCalls = TRUE)
local({dp <- Sys.getenv("R_DEFAULT_PACKAGES")
if(identical(dp, ""))
dp <- c("datasets", "utils", "grDevices", "graphics",
"stats", "methods")
else if(identical(dp, "NULL")) dp <- character(0)
else dp <- strsplit(dp, ",")[[1]]
dp <- sub("[[:blank:]]*([[:alnum:]]+)", "\\1", dp)
options(defaultPackages = dp)
})
Sys.setenv(R_LIBS_SITE =
.expand_R_libs_env_var(Sys.getenv("R_LIBS_SITE")))
Sys.setenv(R_LIBS_USER =
.expand_R_libs_env_var(Sys.getenv("R_LIBS_USER")))
.First.sys <- function()
{
for(pkg in getOption("defaultPackages")) {
res <- require(pkg, quietly = TRUE, warn.conflicts = FALSE,
character.only = TRUE)
if(!res)
warning(gettextf('package %s in options("defaultPackages") was not found', sQuote(pkg)),
call. = FALSE, domain = NA)
}
}
.OptRequireMethods <- function()
{
pkg <- "methods"
if(pkg %in% getOption("defaultPackages"))
if(!require(pkg, quietly = TRUE, warn.conflicts = FALSE,
character.only = TRUE))
warning('package "methods" in options("defaultPackages") was not found',
call. = FALSE)
}
if(nzchar(Sys.getenv("R_BATCH"))) {
.Last.sys <- function()
{
cat("> proc.time()\n")
print(proc.time())
}
try(Sys.setenv(R_BATCH=""))
} |
msBP.nrvTrees <- function(sh, maxS = max(sh[,1]))
{
N <- nrow(sh)
veclen <- 2^(maxS+1) - 1
empty <- rep(0, veclen)
res <- .C("allTrees_C", as.integer(sh[,1]), as.integer(sh[,2]), as.integer(maxS), as.integer(N), n=as.double(empty), r=as.double(empty), v=as.double(empty), PACKAGE = "msBP")
n <- vec2tree(res$n)
r <- vec2tree(res$r)
v <- vec2tree(res$v)
list(n=n, r=r, v=v)
} |
alfapcr.tune <- function(y, x, model = "gaussian", nfolds = 10, maxk = 50, a = seq(-1, 1, by = 0.1),
folds = NULL, ncores = 1, graph = TRUE, col.nu = 15, seed = FALSE) {
n <- dim(x)[1]
d <- dim(x)[2] - 1
if ( min(x) == 0 ) a <- a[ a > 0 ]
da <- length(a)
ina <- 1:n
if ( is.null(folds) ) folds <- Compositional::makefolds(ina, nfolds = nfolds,
stratified = FALSE, seed = seed)
nfolds <- length(folds)
mspe2 <- array( dim = c( nfolds, d, da) )
if ( model == 'gaussian' ) {
tic <- proc.time()
for ( i in 1:da ) {
z <- Compositional::alfa(x, a[i])$aff
mod <- Compositional::pcr.tune(y, z, nfolds = nfolds, maxk = maxk, folds = folds, ncores = ncores, seed = seed, graph = FALSE)
mspe2[, , i] <- mod$msp
}
toc <- proc.time() - tic
} else if ( model == "multinomial" ) {
tic <- proc.time()
for ( i in 1:da ) {
z <- Compositional::alfa(x, a[i])$aff
mod <- Compositional::multinompcr.tune(y, z, nfolds = nfolds, maxk = maxk, folds = folds, ncores = ncores, seed = seed, graph = FALSE)
mspe2[, , i] <- mod$msp
}
toc <- proc.time() - tic
} else if ( model == "binomial" | model == "poisson" ) {
tic <- proc.time()
for ( i in 1:da ) {
z <- Compositional::alfa(x, a[i])$aff
mod <- Compositional::glmpcr.tune(y, z, nfolds = nfolds, maxk = maxk, folds = folds, ncores = ncores, seed = seed, graph = FALSE)
mspe2[, , i] <- mod$msp
}
toc <- proc.time() - tic
}
dimnames(mspe2) <- list(folds = 1:nfolds, PC = paste("PC", 1:d, sep = ""), a = a)
mspe <- array( dim = c(da, d, nfolds) )
for (i in 1:nfolds) mspe[, , i] <- t( mspe2[i, , 1:da] )
dimnames(mspe) <- list(a = a, PC = paste("PC", 1:d, sep = ""), folds = 1:nfolds )
mean.mspe <- t( colMeans( aperm(mspe) ) )
if ( model == "multinomial" ) {
best.par <- which(mean.mspe == max(mean.mspe), arr.ind = TRUE)[1, ]
} else best.par <- which(mean.mspe == min(mean.mspe), arr.ind = TRUE)[1, ]
performance <- mean.mspe[ best.par[1], best.par[2] ]
names(performance) <- "mspe"
rownames(mean.mspe) <- a
colnames(mspe) <- paste("PC", 1:d, sep = "")
if ( graph ) filled.contour(a, 1:d, mean.mspe, xlab = expression( paste(alpha, " values") ),
ylab = "Number of PCs", cex.lab = 1.2, cex.axis = 1.2)
best.par <- c( a[ best.par[1] ], best.par[2] )
names(best.par) <- c("alpha", "PC")
list(mspe = mean.mspe, best.par = best.par, performance = performance, runtime = toc)
} |
r2_efron <- function(model) {
UseMethod("r2_efron")
}
r2_efron.default <- function(model) {
.r2_efron(model)
}
.r2_efron <- function(model) {
y_hat <- stats::predict(model, type = "response")
y <- .factor_to_numeric(insight::get_response(model, verbose = FALSE), lowest = 0)
(1 - (sum((y - y_hat)^2)) / (sum((y - mean(y))^2)))
} |
context("setClasses")
test_that("setClasses", {
x = list(a=1)
expect_equal(setClasses(x, "foo"), structure(list(a=1), class="foo"))
expect_equal(setClasses(x, c("foo1", "foo2")), structure(list(a=1), class=c("foo1", "foo2")))
}) |
read_sparse_csv <- function(input, iterfeature, nfeatures = NA, colClasses = NA, RDS = NA, compress_RDS = TRUE, NA_sparse = FALSE) {
columns <- fread(input = input,
nrows = 0,
stringsAsFactors = FALSE,
colClasses = colClasses,
data.table = FALSE)
colClasses <- rep("numeric", nfeatures)
if (is.na(nfeatures[1]) == TRUE) {
nfeatures <- ncol(columns)
}
features <- split(nfeatures, ceiling(seq_along(nfeatures) / iterfeature))
for (i in 1:length(features)) {
cat("Loading ", i, "th part.\n", sep = "")
data_temp <- fread(input = input,
select = features[[i]],
stringsAsFactors = FALSE,
colClasses = colClasses,
data.table = TRUE)
gc(verbose = FALSE)
if (i > 1) {
if (NA_sparse == TRUE) {
cat("Coercing to matrix.\n", sep = "")
data_temp <- as.matrix(data_temp)
gc(verbose = FALSE)
cat("Coercing into dgCMatrix with NA as blank.\n", sep = "")
data_temp <- dropNA(data_temp)
gc(verbose = FALSE)
cat("Column binding the full matrix with the newly created matrix.\n\n", sep = "")
data <- cbind(data, data_temp)
rm(data_temp)
} else {
cat("Coercing to sparse matrix.\n", sep = "")
data_temp <- Matrix(as.matrix(data_temp), sparse = TRUE)
gc(verbose = FALSE)
cat("Column binding the full matrix with the newly created matrix.\n\n", sep = "")
data <- cbind(data, data_temp)
rm(data_temp)
}
gc(verbose = FALSE)
} else {
if (NA_sparse == TRUE) {
cat("Coercing to matrix.\n", sep = "")
data_temp <- as.matrix(data_temp)
gc(verbose = FALSE)
cat("Coercing into dgCMatrix with NA as blank.\n\n", sep = "")
data <- dropNA(data_temp)
} else {
cat("Coercing to sparse matrix.\n", sep = "")
data <- Matrix(as.matrix(data_temp), sparse = TRUE)
rm(data_temp)
}
gc(verbose = FALSE)
}
}
if (is.na(RDS) == FALSE) {
cat("Saving to RDS format.\n")
saveRDS(data, file = RDS, compress = compress_RDS)
}
return(data)
} |
NULL
setClass(
Class = "ClippedFT",
contains = "FreqRep"
)
setMethod(
f = "initialize",
signature = "ClippedFT",
definition = function(.Object, Y, isRankBased, levels, frequencies, positions.boot, B) {
.Object@Y <- Y
.Object@isRankBased <- isRankBased
.Object@levels <- levels
.Object@frequencies <- frequencies
[email protected] <- positions.boot
.Object@B <- B
T <- dim(Y)[1]
D <- dim(Y)[2]
K <- length(levels)
J <- length(frequencies)
if (isRankBased) {
data <- apply(Y,2,rank) / T
} else {
data <- Y
}
IndMatrix <- matrix(0, nrow=T, ncol=K*D*(B+1))
levels <- sort(levels)
for (d in 1:D) {
sortedData <- sort(data[,d])
t <- 1
for (i in 1:K) {
while (t <= T && sortedData[t] <= levels[i]) {t <- t+1}
if (t > 1) {
IndMatrix[1:(t-1),(d-1)*K+i] <- 1
}
}
IndMatrix[,(d-1)*K+1:K] <- IndMatrix[rank(data[,d]),(d-1)*K+1:K]
}
if (B > 0) {
pos.boot <- getPositions([email protected],B)
for (b in 1:B) {
IndMatrix[,(b*(K*D)+1):((b+1)*(K*D))] <- IndMatrix[pos.boot[,b],1:(K*D)]
}
}
cfft <- mvfft(IndMatrix)
.Object@values <- array(cfft[unique(round(T*frequencies/(2*pi)))+1,], dim=c(J,K,D,B+1))
.Object@values <- aperm(.Object@values, perm=c(1,3,2,4))
return(.Object)
}
)
clippedFT <- function( Y,
frequencies=2*pi/lenTS(Y) * 0:(lenTS(Y)-1),
levels = 0.5,
isRankBased=TRUE,
B = 0,
l = 0,
type.boot = c("none","mbb")) {
Y <- timeSeriesValidator(Y)
if (!(is.vector(frequencies) && is.numeric(frequencies))) {
stop("'frequencies' needs to be specified as a vector of real numbers")
}
if (!(is.vector(levels) && is.numeric(levels))) {
stop("'levels' needs to be specified as a vector of real numbers")
}
if (isRankBased && !(prod(levels >= 0) && prod(levels <=1))) {
stop("'levels' need to be from [0,1] when isRankBased==TRUE")
}
frequencies <- frequenciesValidator(frequencies, lenTS(Y))
type.boot <- match.arg(type.boot, c("none","mbb"))[1]
switch(type.boot,
"none" = {
bootPos <- movingBlocks(lenTS(Y),lenTS(Y))},
"mbb" = {
bootPos <- movingBlocks(l,lenTS(Y))}
)
freqRep <- new(
Class = "ClippedFT",
Y = Y,
isRankBased = isRankBased,
levels = sort(levels),
B = B,
positions.boot = bootPos,
frequencies = frequencies
)
return(freqRep)
} |
context("table_updateColumn")
test_that("table_updateColumn() works with no data", {
locationTbl <- get(data("wa_monitors_500"))
testTbl <- table_updateColumn(locationTbl, "siteName")
expect_equal(c(names(locationTbl),"siteName"), names(testTbl))
})
test_that("table_updateColumn() works with data", {
locationTbl <- get(data("wa_monitors_500"))
wa <- get(data("wa_airfire_meta"))
wa_indices <- seq(5,65,5)
wa_sub <- wa[wa_indices,]
locationID <- table_getLocationID(locationTbl, wa_sub$longitude, wa_sub$latitude, distanceThreshold = 1000)
locationData <- wa_sub$siteName
testTbl <- table_updateColumn(locationTbl, "siteName", locationID, locationData)
testTbl_indices <- table_getRecordIndex(testTbl, locationID)
locationTbl_siteName <- testTbl$siteName[testTbl_indices]
wa_siteName <- wa$siteName[wa_indices]
mask <- !is.na(locationTbl_siteName)
expect_equal(locationTbl_siteName[mask], wa_siteName[mask])
}) |
packageStatus <- function(lib.loc = NULL, repositories = NULL, method,
type = getOption("pkgType"), ...)
{
newestVersion <- function(x)
{
vers <- package_version(x)
max <- vers[1L]
for (i in seq_along(vers)) if (max < vers[i]) max <- vers[i]
which.max(vers == max)
}
if(is.null(lib.loc))
lib.loc <- .libPaths()
if(is.null(repositories))
repositories <- contrib.url(getOption("repos"), type = type)
char2df <- function(x)
{
y <- list()
for(k in 1L:ncol(x)) y[[k]] <- x[,k]
attr(y, "names") <- colnames(x)
attr(y, "row.names") <- make.unique(y[[1L]])
class(y) <- "data.frame"
y
}
y <- char2df(installed.packages(lib.loc = lib.loc, ...))
y[, "Status"] <- rep("ok", nrow(y))
z <- available.packages(repositories, method, ...)
ztab <- table(z[,"Package"])
for(pkg in names(ztab)[ztab>1]){
zrow <- which(z[,"Package"] == pkg)
znewest <- newestVersion(z[zrow,"Version"])
z <- z[-zrow[-znewest],]
}
z <- cbind(z, Status = "not installed")
z[z[,"Package"] %in% y$Package, "Status"] <- "installed"
z <- char2df(z)
attr(z, "row.names") <- z$Package
for(k in seq_len(nrow(y))){
pkg <- y[k, "Package"]
if(pkg %in% z$Package) {
if(package_version(y[k, "Version"]) <
package_version(z[pkg, "Version"])) {
y[k, "Status"] <- "upgrade"
}
} else {
if(!(y[k, "Priority"] %in% "base")) y[k, "Status"] <- "unavailable"
}
}
y$LibPath <- factor(y$LibPath, levels=lib.loc)
y$Status <- factor(y$Status, levels=c("ok", "upgrade", "unavailable"))
z$Repository <- factor(z$Repository, levels=repositories)
z$Status <- factor(z$Status, levels=c("installed", "not installed"))
retval <- list(inst=y, avail=z)
class(retval) <- "packageStatus"
retval
}
summary.packageStatus <- function(object, ...)
{
Libs <- levels(object$inst$LibPath)
Repos <- levels(object$avail$Repository)
Libs <- lapply(split(object$inst, object$inst$LibPath),
function(x) tapply(x$Package, x$Status,
function(x) sort(as.character(x)),
simplify = FALSE))
Repos <- lapply(split(object$avail, object$avail$Repository),
function(x) tapply(x$Package, x$Status,
function(x) sort(as.character(x)),
simplify = FALSE))
object$Libs <- Libs
object$Repos <- Repos
class(object) <- c("summary.packageStatus", "packageStatus")
object
}
print.summary.packageStatus <- function(x, ...)
{
cat("\nInstalled packages:\n")
cat( "-------------------\n")
for(k in seq_along(x$Libs)) {
cat("\n*** Library ", names(x$Libs)[k], "\n", sep = "")
print(x$Libs[[k]], ...)
}
cat("\n\nAvailable packages:\n")
cat( "-------------------\n")
cat("(each package appears only once)\n")
for(k in seq_along(x$Repos)){
cat("\n*** Repository ", names(x$Repos)[k], "\n", sep = "")
print(x$Repos[[k]], ...)
}
invisible(x)
}
print.packageStatus <- function(x, ...)
{
cat("Number of installed packages:\n")
print(table(x$inst$LibPath, x$inst$Status), ...)
cat("\nNumber of available packages (each package counted only once):\n")
print(table(x$avail$Repository, x$avail$Status), ...)
invisible(x)
}
update.packageStatus <-
function(object, lib.loc=levels(object$inst$LibPath),
repositories=levels(object$avail$Repository),
...)
{
packageStatus(lib.loc=lib.loc, repositories=repositories)
}
upgrade <- function(object, ...)
UseMethod("upgrade")
upgrade.packageStatus <- function(object, ask = TRUE, ...)
{
update <- NULL
old <- which(object$inst$Status == "upgrade")
if(length(old) == 0L) {
cat("Nothing to do!\n")
return(invisible())
}
askprint <- function(x)
write.table(x, row.names = FALSE, col.names = FALSE, quote = FALSE,
sep = " at ")
haveasked <- character()
if(ask) {
for(k in old) {
pkg <- object$inst[k, "Package"]
tmpstring <- paste(pkg, as.character(object$inst[k, "LibPath"]))
if(tmpstring %in% haveasked) next
haveasked <- c(haveasked, tmpstring)
cat("\n")
cat(pkg, ":\n")
askprint(object$inst[k,c("Version", "LibPath")])
askprint(object$avail[pkg, c("Version", "Repository")])
answer <- askYesNo("Update?")
if(is.na(answer)) {
cat("cancelled by user\n")
return(invisible())
}
if(isTRUE(answer))
update <-
rbind(update,
c(pkg, as.character(object$inst[k, "LibPath"]),
as.character(object$avail[pkg, "Repository"])))
}
} else {
pkgs <- object$inst[ ,"Package"]
update <- cbind(pkgs, as.character(object$inst[ , "LibPath"]),
as.character(object$avail[pkgs, "Repository"]))
update <- update[old, , drop = FALSE]
}
if(length(update)) {
for(repo in unique(update[,3])) {
ok <- update[, 3] == repo
install.packages(update[ok, 1], update[ok, 2], contriburl = repo,
...)
}
}
} |
toleranceBound <- function(psi, gamma, N) {
zg <- qnorm(1-gamma)
zp <- qnorm(psi)
a <- 1 - zg^2/(2*N-2)
b <- zp^2 - zg^2/N
k1 <- (zp + sqrt(zp^2-a*b))/a
k1
} |
initialize_states <- function(num.states = NULL, num.samples = NULL,
method = c("random", "KmeansPLC", "KmeansFLC",
"KmeansPLCFLC", "KmeansFLCPLC"),
LCs = list(PLC = NULL, FLC = NULL)) {
if (is.null(num.states)) {
stop("You must provide the number of clusters.")
}
if (is.null(num.samples)) {
if (is.null(unlist(LCs))) {
stop("You must either provide the total number of samples or data 'LCs'.")
} else {
num.samples <- nrow(LCs$PLC)
}
}
method <- match.arg(method)
if (method == "random") {
states <- sample.int(n = num.states, size = num.samples, replace = TRUE)
states[sample.int(num.samples, num.states, replace = FALSE)] <-
seq_len(num.states)
} else if (method == "KmeansPLC") {
states <- kmeanspp(LCs$PLC, num.states, iter.max = 100, nstart = 10)$cluster
} else if (method == "KmeansFLC") {
states <- kmeanspp(LCs$FLC, num.states, iter.max = 100, nstart = 10)$cluster
} else if (any(method == c("KmeansPLCFLC", "KmeansFLCPLC"))) {
first.stage.num.states <- ceiling(num.states^(1/3))
second.stage.num.states <- floor(num.states/first.stage.num.states)
second.stage.last.run.num.states <-
num.states - first.stage.num.states * second.stage.num.states + second.stage.num.states
if (method == "KmeansFLCPLC") {
first.stage.data <- rbind(LCs$FLC)
second.stage.data <- rbind(LCs$PLC)
} else {
first.stage.data <- rbind(LCs$PLC)
second.stage.data <- rbind(LCs$FLC)
}
first.stage.labels <- kmeanspp(first.stage.data, first.stage.num.states,
iter.max = 100, nstart = 10)$cluster
second.stage.labels <- rep(NA, num.samples)
for (ll in seq_len(first.stage.num.states - 1)) {
second.stage.labels[first.stage.labels == ll] <- (ll - 1) * first.stage.num.states +
kmeanspp(second.stage.data[first.stage.labels == ll,],
second.stage.num.states,
iter.max = 100, nstart = 10)$cluster
}
second.stage.labels[first.stage.labels == first.stage.num.states] = (first.stage.num.states - 1) * first.stage.num.states +
kmeanspp(second.stage.data[first.stage.labels == first.stage.num.states,],
second.stage.last.run.num.states,
iter.max = 100, nstart = 10)$cluster
states <- second.stage.labels
}
invisible(states)
} |
ggscatterstats <- function(data,
x,
y,
type = "parametric",
conf.level = 0.95,
bf.prior = 0.707,
bf.message = TRUE,
tr = 0.2,
k = 2L,
results.subtitle = TRUE,
label.var = NULL,
label.expression = NULL,
marginal = TRUE,
xfill = "
yfill = "
point.args = list(
size = 3,
alpha = 0.4,
stroke = 0,
na.rm = TRUE
),
point.width.jitter = 0,
point.height.jitter = 0,
point.label.args = list(size = 3, max.overlaps = 1e6),
smooth.line.args = list(
size = 1.5,
color = "blue",
method = "lm",
formula = y ~ x,
na.rm = TRUE
),
xsidehistogram.args = list(
fill = xfill,
color = "black",
na.rm = TRUE
),
ysidehistogram.args = list(
fill = yfill,
color = "black",
na.rm = TRUE
),
xlab = NULL,
ylab = NULL,
title = NULL,
subtitle = NULL,
caption = NULL,
ggtheme = ggstatsplot::theme_ggstatsplot(),
ggplot.component = NULL,
output = "plot",
...) {
c(x, y) %<-% c(ensym(x), ensym(y))
data %<>% filter(!is.na({{ x }}), !is.na({{ y }}))
if (results.subtitle) {
type <- stats_type_switch(type)
.f.args <- list(
data = data,
x = {{ x }},
y = {{ y }},
conf.level = conf.level,
k = k,
tr = tr,
bf.prior = bf.prior,
top.text = caption
)
subtitle_df <- eval_f(corr_test, !!!.f.args, type = type)
subtitle <- if (!is.null(subtitle_df)) subtitle_df$expression[[1]]
if (type == "parametric" && bf.message) {
caption_df <- eval_f(corr_test, !!!.f.args, type = "bayes")
caption <- if (!is.null(caption_df)) caption_df$expression[[1]]
}
}
if (output != "plot") {
return(switch(output,
"caption" = caption,
subtitle
))
}
pos <- position_jitter(width = point.width.jitter, height = point.height.jitter)
plot <- ggplot(data, mapping = aes({{ x }}, {{ y }})) +
exec(geom_point, position = pos, !!!point.args) +
exec(geom_smooth, level = conf.level, !!!smooth.line.args)
if (!quo_is_null(enquo(label.var))) {
label.var <- ensym(label.var)
if (!quo_is_null(enquo(label.expression))) {
label_data <- filter(data, !!enexpr(label.expression))
} else {
label_data <- data
}
plot <- plot +
exec(
ggrepel::geom_label_repel,
data = label_data,
mapping = aes(label = {{ label.var }}),
min.segment.length = 0,
position = pos,
!!!point.label.args
)
}
plot <- plot +
labs(
x = xlab %||% as_name(x),
y = ylab %||% as_name(y),
title = title,
subtitle = subtitle,
caption = caption
) +
ggtheme +
ggplot.component
if (marginal) {
check_if_installed("ggside", minimum_version = "0.1.2")
plot <- plot +
exec(ggside::geom_xsidehistogram, mapping = aes(y = after_stat(count)), !!!xsidehistogram.args) +
exec(ggside::geom_ysidehistogram, mapping = aes(x = after_stat(count)), !!!ysidehistogram.args) +
ggside::scale_ysidex_continuous() +
ggside::scale_xsidey_continuous()
}
plot
}
grouped_ggscatterstats <- function(data,
...,
grouping.var,
output = "plot",
plotgrid.args = list(),
annotation.args = list()) {
data %<>% grouped_list({{ grouping.var }})
p_ls <- purrr::pmap(
.l = list(data = data, title = names(data), output = output),
.f = ggstatsplot::ggscatterstats,
...
)
if (output == "plot") p_ls <- combine_plots(p_ls, plotgrid.args, annotation.args)
p_ls
} |
setClassUnion(name = "spatialClasses",
members = c("RasterLayer", "RasterLayerSparse", "RasterStack", "RasterBrick",
"SpatialLines", "SpatialLinesDataFrame",
"SpatialPixels", "SpatialPixelsDataFrame",
"SpatialPoints", "SpatialPointsDataFrame",
"SpatialPolygons", "SpatialPolygonsDataFrame")
) |
gapDetect <-
function() {
isTrueGap <- function(oneListName) {
oneList <- get(oneListName, envir = KTSEnv)
listNames <- names(oneList)
if (is.null(listNames)) {
result <- NA
} else if (length(listNames) != 6) {
result <- NA
} else if (listNames[1] == "gaps" & listNames[2] == "tsIni"
& listNames[3] == "tsEnd" & listNames[4] == "samPerMin"
& listNames[5] == "tsLength" & listNames[6] == "tsName") {
result <- oneListName
} else {
result <- NA
}
result
}
listsInGE <- getClassEnvir(classGet = "list", envir = KTSEnv)
if (length(listsInGE) == 0) {
loadedGaps <- NULL
} else {
loadedGaps <- apply(as.matrix(listsInGE), 1, FUN = isTrueGap)
loadedGaps <- loadedGaps[which(is.na(loadedGaps) == FALSE)]
if (length(loadedGaps) == 0) {
loadedGaps <- NULL
}
}
loadedGaps
} |
set.seed(888)
data <- dreamer_data_linear(
n_cohorts = c(20, 20, 20),
dose = c(0, 3, 10),
b1 = 1,
b2 = 3,
sigma = 5
)
output <- dreamer_mcmc(
data = data,
n_adapt = 1e3,
n_burn = 1e3,
n_iter = 1e4,
n_chains = 2,
silent = FALSE,
mod_linear = model_linear(
mu_b1 = 0,
sigma_b1 = 1,
mu_b2 = 0,
sigma_b2 = 1,
shape = 1,
rate = .001,
w_prior = 1 / 2
),
mod_quad = model_quad(
mu_b1 = 0,
sigma_b1 = 1,
mu_b2 = 0,
sigma_b2 = 1,
mu_b3 = 0,
sigma_b3 = 1,
shape = 1,
rate = .001,
w_prior = 1 / 2
)
)
diagnostics(output)
diagnostics(output$mod_quad) |
species.richness.cv <-
function(dataset.all.species, landwatermask, fold=5, loocv.limit=10,
distances=3:10, weight=0.5, dimension, shift, resolution=1,
upperbound, all.species=-1, silent=TRUE, do.parallel=FALSE){
if (all.species[1]==-1){
all.species <- unique(dataset.all.species$speciesID)
} else {
all.species.tmp <- c()
for (species in all.species){
if (length(which(dataset.all.species$speciesID == species)==TRUE) > 0){
all.species.tmp <- c(all.species.tmp, species)
}
}
all.species <- all.species.tmp
}
number.of.species <- length(all.species)
distances <- c(min(distances)-1, distances)
message <- ""
species.richness.weighted.cv <- matrix(0,dimension[1],dimension[2])
requireNamespace("foreach")
if (do.parallel){
if(!foreach::getDoParRegistered()) {
if (!silent) {cat("No parallel backend detected! Problem will be solved sequential.\n",sep="")}
foreach::registerDoSEQ()
} else {
if (!silent) {cat("Parallel backend detected.\n",sep="")}
}
species.richness.weighted.cv <- foreach::foreach(species=all.species, .combine="+", .inorder=FALSE) %dopar% {
species.richness.weighted.one.species <- matrix(0,dimension[1],dimension[2])
species.range.all.subs <- array(0, dim=c(length(distances),dimension[1],dimension[2]))
dataset.one.species <- extract.species(dataset.all.species, species)
number.of.occurrences <- dim(dataset.one.species)[1]
if (number.of.occurrences > 2){
subsamples <- generate.subsamples(number.of.occurrences, fold, loocv.limit)
for (distance in distances){
for (subsample.id in 1:dim(subsamples)[1]){
subsample <- subsamples[subsample.id,]
subsample <- subsample[which(subsample != 0)]
dataset.one.subsample <- dataset.one.species[subsample,]
species.range.sub <- species.range(dataset.one.subsample, distance, dimension,
shift, resolution, landwatermask, upperbound, cross.validation=TRUE)
species.range.all.subs[which(distance == distances),,] <- species.range.all.subs[which(distance == distances),,] + species.range.sub
}
species.range.sub.tmp <- species.range.all.subs[which(distance == distances),,] / matrix(dim(subsamples)[1],dimension[1],dimension[2])
species.range.sub.tmp[which(is.na(species.range.sub.tmp)==TRUE)] <- 0
species.range.all.subs[which(distance == distances),,] <- species.range.sub.tmp
if (which(distance==distances)==1){
species.richness.weighted.one.species <- species.range.all.subs[1,,]
} else {
species.richness.weighted.one.species <- species.richness.weighted.one.species +
(distance^(-weight) * (species.range.all.subs[which(distance == distances),,] - species.range.all.subs[which(distance == distances)-1,,]))
}
}
if (!silent){
cat(rep("\b", nchar(message)),sep="")
message <- paste("Species ",which(species==all.species)," of ",number.of.species," done!", sep="")
cat(message)
flush.console()
}
}
return(species.richness.weighted.one.species)
}
} else {
for (species in all.species){
species.richness.weighted.one.species <- matrix(0,dimension[1],dimension[2])
species.range.all.subs <- array(0, dim=c(length(distances),dimension[1],dimension[2]))
dataset.one.species <- extract.species(dataset.all.species, species)
number.of.occurrences <- dim(dataset.one.species)[1]
if (number.of.occurrences > 2){
subsamples <- generate.subsamples(number.of.occurrences, fold, loocv.limit)
for (distance in distances){
for (subsample.id in 1:dim(subsamples)[1]){
subsample <- subsamples[subsample.id,]
subsample <- subsample[which(subsample != 0)]
dataset.one.subsample <- dataset.one.species[subsample,]
species.range.sub <- species.range(dataset.one.subsample, distance, dimension,
shift, resolution, landwatermask, upperbound, cross.validation=TRUE)
species.range.all.subs[which(distance == distances),,] <- species.range.all.subs[which(distance == distances),,] + species.range.sub
}
species.range.sub.tmp <- species.range.all.subs[which(distance == distances),,] / matrix(dim(subsamples)[1],dimension[1],dimension[2])
species.range.sub.tmp[which(is.na(species.range.sub.tmp)==TRUE)] <- 0
species.range.all.subs[which(distance == distances),,] <- species.range.sub.tmp
if (which(distance==distances)==1){
species.richness.weighted.one.species <- species.range.all.subs[1,,]
} else {
species.richness.weighted.one.species <- species.richness.weighted.one.species +
(distance^(-weight) * (species.range.all.subs[which(distance == distances),,] - species.range.all.subs[which(distance == distances)-1,,]))
}
}
species.richness.weighted.cv <- species.richness.weighted.cv + species.richness.weighted.one.species
if (!silent){
cat(rep("\b", nchar(message)),sep="")
message <- paste("Species ",which(species==all.species)," of ",number.of.species," done!", sep="")
cat(message)
flush.console()
}
}
}
}
if (!silent)
cat("\n")
return(species.richness.weighted.cv)
} |
sim2.bd.mrca.reconst <-
function(mrca,numbsim,lambda,mu,frac,K){
treearray<- list()
for (j in 1:numbsim) {
temp <- 0
while (temp == 0) {
phy <- 0
phy <- sim2.bd.mrca(mrca,1,lambda,mu,K)
phy <- reconstructed.age(phy,frac)
if (class(phy[[1]])=="phylo"){
if (max(branching.times.complete(phy[[1]]))>(mrca-0.0001)){
treearray <- c(treearray,list(phy[[1]]))
temp = 1
}
}
}
}
treearray
} |
PeakSegFPOP_dir <- structure(function
(problem.dir,
penalty.param,
db.file=NULL
){
megabytes <- NULL
if(!(
is.character(problem.dir) &&
length(problem.dir)==1 &&
dir.exists(problem.dir))){
stop(
"problem.dir=", problem.dir,
" must be the name of a directory",
" containing a file named coverage.bedGraph")
}
if(!(
(is.numeric(penalty.param) || is.character(penalty.param)) &&
length(penalty.param)==1 &&
(!is.na(penalty.param))
)){
stop("penalty.param must be numeric or character, length 1, not missing")
}
penalty.str <- paste(penalty.param)
prob.cov.bedGraph <- file.path(problem.dir, "coverage.bedGraph")
pre <- paste0(prob.cov.bedGraph, "_penalty=", penalty.str)
penalty_segments.bed <- paste0(pre, "_segments.bed")
penalty_loss.tsv <- paste0(pre, "_loss.tsv")
penalty_timing.tsv <- paste0(pre, "_timing.tsv")
already.computed <- tryCatch({
timing <- fread(
file=penalty_timing.tsv,
col.names=c("penalty", "megabytes", "seconds"))
first.seg.line <- fread.first(penalty_segments.bed, col.name.list$segments)
last.seg.line <- fread.last(penalty_segments.bed, col.name.list$segments)
first.cov.line <- fread.first(prob.cov.bedGraph, col.name.list$coverage)
last.cov.line <- fread.last(prob.cov.bedGraph, col.name.list$coverage)
penalty.loss <- fread(file=penalty_loss.tsv, col.names=col.name.list$loss)
nrow.ok <- nrow(timing)==1 && nrow(penalty.loss)==1 &&
nrow(first.seg.line)==1 && nrow(last.seg.line)==1 &&
nrow(first.cov.line)==1 && nrow(last.cov.line)==1
loss.segments.consistent <-
first.seg.line$chromEnd-last.seg.line$chromStart == penalty.loss$bases
start.ok <- first.cov.line$chromStart == last.seg.line$chromStart
end.ok <- last.cov.line$chromEnd == first.seg.line$chromEnd
nrow.ok && loss.segments.consistent && start.ok && end.ok
}, error=function(e){
FALSE
})
if(!already.computed){
seconds <- system.time({
result <- PeakSegFPOP_file(prob.cov.bedGraph, penalty.str, db.file)
})[["elapsed"]]
timing <- data.table(
penalty=as.numeric(penalty.str),
megabytes=result$megabytes,
seconds)
write.table(
timing,
penalty_timing.tsv,
row.names=FALSE, col.names=FALSE,
quote=FALSE, sep="\t")
penalty.loss <- fread(file=penalty_loss.tsv, col.names=col.name.list$loss)
}
penalty.segs <- fread(
file=penalty_segments.bed, col.names=col.name.list$segments)
L <- list(
segments=penalty.segs,
loss=data.table(
penalty.loss,
timing[, list(megabytes, seconds)]))
class(L) <- c("PeakSegFPOP_dir", "list")
L
}, ex=function(){
data(Mono27ac, package="PeakSegDisk", envir=environment())
data.dir <- file.path(
tempfile(),
"H3K27ac-H3K4me3_TDHAM_BP",
"samples",
"Mono1_H3K27ac",
"S001YW_NCMLS",
"problems",
"chr11-60000-580000")
dir.create(data.dir, recursive=TRUE, showWarnings=FALSE)
write.table(
Mono27ac$coverage, file.path(data.dir, "coverage.bedGraph"),
col.names=FALSE, row.names=FALSE, quote=FALSE, sep="\t")
(fit <- PeakSegDisk::PeakSegFPOP_dir(data.dir, 1952.6))
summary(fit)
ann.colors <- c(
noPeaks="
peakStart="
peakEnd="
peaks="
library(ggplot2)
lab.min <- Mono27ac$labels[1, chromStart]
lab.max <- Mono27ac$labels[.N, chromEnd]
plist <- coef(fit)
gg <- ggplot()+
theme_bw()+
geom_rect(aes(
xmin=chromStart/1e3, xmax=chromEnd/1e3,
ymin=-Inf, ymax=Inf,
fill=annotation),
color="grey",
alpha=0.5,
data=Mono27ac$labels)+
scale_fill_manual("label", values=ann.colors)+
geom_step(aes(
chromStart/1e3, count),
color="grey50",
data=Mono27ac$coverage)+
geom_segment(aes(
chromStart/1e3, mean,
xend=chromEnd/1e3, yend=mean),
color="green",
size=1,
data=plist$segments)+
geom_vline(aes(
xintercept=chromEnd/1e3, linetype=constraint),
color="green",
data=plist$changes)+
scale_linetype_manual(
values=c(
inequality="dotted",
equality="solid"))
gg
gg+
coord_cartesian(xlim=c(lab.min, lab.max)/1e3, ylim=c(0, 10))
(gg <- plot(fit))
gg+
geom_step(aes(
chromStart, count),
color="grey50",
data=Mono27ac$coverage)
})
coef.PeakSegFPOP_dir <- function(object, ...){
chromEnd <- status <- NULL
object$changes <- object$segments[, list(
type="segmentation",
constraint=ifelse(
diff(mean)==0, "equality", "inequality"),
chromEnd=chromEnd[-1])]
object$peaks <- data.table(
type="peaks",
object$segments[status=="peak"])
object$segments <- data.table(type="segmentation", object$segments)
object
}
summary.PeakSegFPOP_dir <- function(object, ...){
object$loss
}
plot.PeakSegFPOP_dir <- function(x, ...){
chromStart <- type <- chromEnd <- constraint <- NULL
if(!requireNamespace("ggplot2")){
stop("install ggplot2 for plotting functionality")
}
L <- coef(x)
ggplot2::ggplot()+
ggplot2::theme_bw()+
ggplot2::scale_color_manual(values=c(
data="grey50",
peaks="deepskyblue",
segmentation="green"
))+
ggplot2::geom_segment(ggplot2::aes(
chromStart+0.5, mean,
color=type,
xend=chromEnd+0.5, yend=mean),
size=1,
data=L$segments)+
ggplot2::geom_segment(ggplot2::aes(
chromStart+0.5, Inf,
color=type,
xend=chromEnd+0.5, yend=Inf),
size=2,
data=L$peaks)+
ggplot2::geom_point(ggplot2::aes(
chromStart+0.5, Inf,
color=type),
shape=1,
size=2,
data=L$peaks)+
ggplot2::geom_vline(ggplot2::aes(
xintercept=chromEnd+0.5,
color=type,
linetype=constraint),
data=L$changes)+
ggplot2::scale_linetype_manual(
values=c(
inequality="dotted",
equality="solid"))+
ggplot2::xlab("position")
} |
quantile.ff <- function(x, probs = seq(0, 1, 0.25), na.rm = FALSE, names = TRUE, ...){
N <- length(x)
nms <- if (names) paste(100*probs, "%", sep="")
NULL
qnt <- 1L + as.integer(probs * (N-1))
idx <- ffordered(x)
ql <- x[idx[qnt]]
names(ql) <- nms
ql
} |
context("generate_args_setup_script")
describe("generate_args_setup_script", {
source("helper.R")
it("no env", {
script <- scriptexec::generate_args_setup_script()
length <- length(script)
expect_equal(length, 0)
})
it("multiple env vars", {
script <- scriptexec::generate_args_setup_script(c("t1", "t2"))
length <- length(script)
expect_equal(length, 2)
prefix <- get_os_string("", "SET ")
expected_result <- c(paste(prefix, "ARG1=t1", sep = ""), paste(prefix,
"ARG2=t2", sep = ""))
expect_equal(expected_result, script)
})
}) |
logLikHessian <- function(model){
hess <- hessian(func = logLikH, x = model$theta, g = model$g, X0 = model$X0, Z0 = model$Z0,
Z = model$Z, mult = model$mult, beta0 = model$beta0,
Delta = model$Delta, k_theta_g = model$k_theta_g, theta_g = model$theta_g,
logN = model$logN)
if(!isSymmetric(hess)) hess <- (hess + t(hess))/2
return(hess)
}
C_GP_ci <- function(model, B = 100) {
ll_func <- function(logtheta) logLikH(X0 = model$X0, Z0 = model$Z0, Z = model$Z, mult = model$mult, theta = exp(logtheta), g = model$g,
covtype = model$covtype, logN = TRUE)
hess <- hessian(ll_func, log(model$theta))
if(!isSymmetric(hess)) hess <- (hess + t(hess))/2
SIG_THETA <- -solve(hess)
R <- chol(SIG_THETA)
sn_draws <- matrix(rnorm(B*ncol(SIG_THETA)), ncol = B)
t_draws <- t(t(R) %*% sn_draws)
lmodeltheta <- log(model$theta)
t_draws <- t(apply(t_draws, 1, function(x) x + lmodeltheta))
eigen_draws <- matrix(NA, nrow = B, ncol = length(model$theta))
for (b in 1:B) {
modeli <- model
modeli$theta <- exp(t_draws[b,])
modeli <- rebuild(modeli)
C <- C_GP(modeli)
if (sum(is.nan(C$mat)) > 0) {
warning("NaN Encountered in C_GP.")
} else {
eigen_draws[b,] <- eigen(C$mat)$values
}
}
return(list(ci = apply(eigen_draws, 2, quantile, probs = c(0.025, 0.975)),
eigen_draws = eigen_draws))
} |
library(ontologyIndex)
library(ontologyPlot)
data(go)
genes <- list(
A0A087WUJ7=c("GO:0004553", "GO:0005975"),
CTAGE8=c("GO:0016021"),
IFRD2=c("GO:0003674", "GO:0005515", "GO:0005634"),
OTOR=c("GO:0001502", "GO:0005576", "GO:0007605"),
TAMM41=c("GO:0004605", "GO:0016024", "GO:0031314", "GO:0032049"),
ZZEF1=c("GO:0005509", "GO:0008270")
)
plot_annotation_grid(go, term_sets=genes) |
context("Check the equivalence between numeric SOM and relational SOM for a
four-dimensional numeric dataset and the square Euclidean distance
used as a dissimilarity")
test_that("'euclidean' and 'relational' give identical results on toy data", {
set.seed(123)
nsom <- trainSOM(iris[1:30, 1:4], init.proto = "obs", scaling = "none",
maxit = 50)
set.seed(123)
iris.dist <- dist(iris[1:30, 1:4], method = "euclidian", diag = TRUE,
upper = TRUE)^2
rsom <- trainSOM(x.data = iris.dist, type = "relational", scaling = "none",
maxit = 50)
expect_equal(nsom$clustering, rsom$clustering)
}) |
`MVP.FaSTLMM.LL` <- function(pheno, snp.pool, X0=NULL, ncpus=2){
y=pheno
p=0
deltaExpStart = -5
deltaExpEnd = 5
snp.pool=snp.pool[,]
if(!is.null(snp.pool)&&var(snp.pool)==0){
deltaExpStart = 100
deltaExpEnd = deltaExpStart
}
if(is.null(X0)) {
X0 = matrix(1, nrow(snp.pool), 1)
}
X=X0
K.X.svd <- svd(snp.pool)
d=K.X.svd$d
d=d[d>1e-08]
d=d^2
U1=K.X.svd$u
U1=U1[,1:length(d)]
if(is.null(dim(U1))) U1=matrix(U1,ncol=1)
n=nrow(U1)
U1TX=crossprod(U1,X)
U1TY=crossprod(U1,y)
yU1TY <- y-U1%*%U1TY
XU1TX<- X-U1%*%U1TX
IU = -tcrossprod(U1)
diag(IU) = rep(1,n) + diag(IU)
IUX=crossprod(IU,X)
IUY=crossprod(IU,y)
delta.range <- seq(deltaExpStart,deltaExpEnd,by=0.1)
m <- length(delta.range)
beta.optimize.parallel <- function(ii){
delta <- exp(delta.range[ii])
beta1=0
for(i in 1:length(d)){
one=matrix(U1TX[i,], nrow=1)
beta=crossprod(one,(one/(d[i]+delta)))
beta1= beta1+beta
}
beta2=0
for(i in 1:nrow(U1)){
one=matrix(IUX[i,], nrow=1)
beta = crossprod(one)
beta2= beta2+beta
}
beta2<-beta2/delta
beta3=0
for(i in 1:length(d)){
one1=matrix(U1TX[i,], nrow=1)
one2=matrix(U1TY[i,], nrow=1)
beta=crossprod(one1,(one2/(d[i]+delta)))
beta3= beta3+beta
}
beta4=0
for(i in 1:nrow(U1)){
one1=matrix(IUX[i,], nrow=1)
one2=matrix(IUY[i,], nrow=1)
beta=crossprod(one1,one2)
beta4= beta4+beta
}
beta4<-beta4/delta
zw1 <- ginv(beta1+beta2)
zw2=(beta3+beta4)
beta=crossprod(zw1,zw2)
part11<-n*log(2*3.14)
part12<-0
for(i in 1:length(d)){
part12_pre=log(d[i]+delta)
part12= part12+part12_pre
}
part13<- (nrow(U1)-length(d))*log(delta)
part1<- -1/2*(part11+part12+part13)
part21<-nrow(U1)
part221=0
for(i in 1:length(d)){
one1=U1TX[i,]
one2=U1TY[i,]
part221_pre=(one2-one1%*%beta)^2/(d[i]+delta)
part221 = part221+part221_pre
}
part222=0
for(i in 1:n){
one1=XU1TX[i,]
one2=yU1TY[i,]
part222_pre=((one2-one1%*%beta)^2)/delta
part222= part222+part222_pre
}
part22<-n*log((1/n)*(part221+part222))
part2<- -1/2*(part21+part22)
LL<-part1+part2
part1<-0
part2<-0
return(list(beta=beta,delta=delta,LL=LL))
}
llresults <- lapply(1:m, beta.optimize.parallel)
for(i in 1:m){
if(i == 1){
beta.save = llresults[[i]]$beta
delta.save = llresults[[i]]$delta
LL.save = llresults[[i]]$LL
}else{
if(llresults[[i]]$LL > LL.save){
beta.save = llresults[[i]]$beta
delta.save = llresults[[i]]$delta
LL.save = llresults[[i]]$LL
}
}
}
beta=beta.save
delta=delta.save
LL=LL.save
sigma_a1=0
for(i in 1:length(d)){
one1=matrix(U1TX[i,], ncol=1)
one2=matrix(U1TY[i,], nrow=1)
sigma_a1_pre=(one2-crossprod(one1,beta))^2/(d[i]+delta)
sigma_a1= sigma_a1+sigma_a1_pre
}
sigma_a2=0
for(i in 1:nrow(U1)){
one1=matrix(IUX[i,], ncol=1)
one2=matrix(IUY[i,], nrow=1)
sigma_a2_pre<-(one2-crossprod(one1,beta))^2
sigma_a2= sigma_a2+sigma_a2_pre
}
sigma_a2<-sigma_a2/delta
sigma_a<- 1/n*(sigma_a1+sigma_a2)
sigma_e<-delta*sigma_a
return(list(beta=beta, delta=delta, LL=LL, vg=sigma_a, ve=sigma_e))
} |
cache_runion <- R6::R6Class(
"cache_runion",
cloneable = FALSE,
public = list(
initialize = function(rschedules, rdates, exdates)
cache_runion__initialize(self, private, rschedules, rdates, exdates),
get_events = function()
cache_runion__get_events(self, private)
),
private = list(
rschedules = list(),
rdates = new_date(),
exdates = new_date(),
events = NULL,
built = FALSE,
cache_build = function()
cache_runion__cache_build(self, private)
)
)
cache_runion__cache_build <- function(self, private) {
if (all_are_rrules(private$rschedules)) {
cache_runion__cache_build_rrules(self, private)
} else {
cache_runion__cache_build_impl(self, private)
}
}
cache_runion__cache_build_impl <- function(self, private) {
rschedules <- private$rschedules
rdates <- private$rdates
exdates <- private$exdates
rschedules_events <- map(rschedules, rschedule_events)
if (!vec_is_empty(rdates)) {
rschedules_events <- c(rschedules_events, list(rdates))
}
events <- vec_unchop(rschedules_events, ptype = new_date())
events <- vec_unique(events)
events <- vec_sort(events)
if (!vec_is_empty(exdates)) {
events <- vec_set_diff(events, exdates)
}
private$events <- events
private$built <- TRUE
invisible(self)
}
cache_runion__cache_build_rrules <- function(self, private) {
rrules <- private$rschedules
rdates <- private$rdates
exdates <- private$exdates
call <- cache_runion_build_call(rrules, rdates, exdates)
events <- almanac_global_context$call(call)
events <- parse_js_date(events)
private$events <- events
private$built <- TRUE
invisible(self)
}
cache_runion_build_call <- function(rrules, rdates, exdates) {
body <- cache_runion_build_call_body(rrules, rdates, exdates)
glue2("
function() {
[[body]]
return ruleset.all()
}
")
}
cache_runion_build_call_body <- function(rrules, rdates, exdates) {
body <- "var ruleset = new rrule.RRuleSet()"
for(rrule in rrules) {
rules <- rrule$rules
body <- append_rrule(body, rules)
}
for(i in seq_along(rdates)) {
rdate <- rdates[i]
body <- append_rdate(body, rdate)
}
for(i in seq_along(exdates)) {
exdate <- exdates[i]
body <- append_exdate(body, exdate)
}
body
}
cache_runion__get_events <- function(self, private) {
if (!private$built) {
private$cache_build()
}
private$events
}
cache_runion__initialize <- function(self, private, rschedules, rdates, exdates) {
private$rschedules <- rschedules
private$rdates <- rdates
private$exdates <- exdates
self
} |
condNumLimit <- 1e7
calcCondNum <- function(hess) {
d <- try(svd(hess, nu=0, nv=0)$d)
if (is(d, "try-error")) return(1e16)
if (all(d > 0)) {
max(d)/min(d)
} else {
1e16
}
}
MCphase <- function(modelGen, reps=500, verbose=TRUE, maxCondNum) {
emcycles <- rep(NA, reps)
condnum <- rep(NA, reps)
est <- matrix()
for (rep in 1:reps) {
set.seed(rep)
model <- modelGen()
em <- model$compute
getCondNum <- list(mxComputeOnce('fitfunction', 'information', 'meat'),
mxComputeReportDeriv())
plan <- mxComputeSequence(c(em, getCondNum))
model$compute <- plan
fit <- try(mxRun(model, silent=TRUE, suppressWarnings = TRUE), silent=TRUE)
if (inherits(fit, "try-error")) {
print(fit)
condnum[rep] <- 1e16
next
} else if (fit$output$status$code != 0) {
print(paste("status code", fit$output$status$code))
next
}
emstat <- fit$compute$steps[[1]]$output
emcycles[rep] <- emstat$EMcycles
condnum[rep] <- calcCondNum(fit$output$hessian)
par <- omxGetParameters(fit)
if (any(is.na(par))) {
print(par)
condnum[rep] <- 1e16
next
}
if (verbose) print(paste(c(rep, emstat, round(condnum[rep])), collapse=" "))
if (all(dim(est) == 1)) {
est <- matrix(NA, length(par), reps)
rownames(est) <- names(par)
}
est[,rep] <- par
}
list(condnum=condnum, est=est)
}
getMCdata <- function(name, modelGen, correct, recompute=FALSE, reps=500,
envir=parent.frame(), maxCondNum) {
if (missing(maxCondNum)) stop("Provide a maxCondNum")
correct <- c(correct)
rda <- paste("data/", name, ".rda", sep="")
if (!recompute) {
if (file.exists(rda)) {
load(rda, envir=envir)
} else if (file.exists(paste("models/enormous/", rda, sep=""))) {
load(paste("models/enormous/", rda, sep=""), envir=envir)
} else {
recompute <- TRUE
}
}
if (recompute) {
got <- MCphase(modelGen, reps, maxCondNum=maxCondNum)
mcMask <- rep(TRUE, reps)
if (!is.na(maxCondNum)) {
mcMask <- !is.na(got$condnum) & got$condnum < maxCondNum
}
est <- got$est
mcEst <- apply(est[,mcMask], 1, mean)
bias <- mcEst - correct
if (reps < length(correct)) stop("Not enough replications to estimate the Hessian")
mcCov <- cov(t(est))
mcHessian <- solve(mcCov/2)
mcBias <- bias
mcSE <- sqrt(2*diag(solve(mcHessian)))
save(mcMask, mcBias, mcSE, mcHessian, file=rda)
if (!is.na(maxCondNum)) {
cat(paste("Note:", sum(!mcMask), "excluded due to condition number\n"))
}
cat("Monte-Carlo study complete. Proceeding with accuracy benchmark.\n")
load(rda, envir=envir)
}
}
mvn_KL_D <- function(invH, H) {
pcm <- solve(mcHessian)
.5*(tr(invH %*% pcm) - nrow(H) - log(det(pcm)/det(H)))
}
summarizeInfo1 <- function(condnum, emstat=list(EMcycles=NA, semProbeCount=NA),
H, standardErrors, cputime, method) {
numReturn <- 6
if (!is.na(condnum) && condnum > condNumLimit) return(rep(NA, numReturn))
normH <- NA
if (!is.null(H) && all(eigen(H, only.values =TRUE)$val > 0)) {
iH <- try(solve(H), silent=TRUE)
if (is(iH, "try-error")) return(rep(NA, numReturn))
normH <- mvn_KL_D(H, iH)
}
normRd <- NA
rd <- (standardErrors - mcSE) / mcSE
if (!is.na(condnum)) {
if (all(is.finite(rd))) {
normRd <- norm(rd, "2")
} else {
print(paste("Method", method,"condition number", condnum, "but some SEs are NA"))
condnum <- NA
}
}
got <- c(cputime, emstat$EMcycles, emstat$semProbeCount, condnum, normH, normRd)
if (length(got) != numReturn) {
print('wrong length')
print(got)
return(rep(NA, numReturn))
} else {
return(got)
}
}
summarizeInfo <- function(fitModel, method) {
emstat <- list(EMcycles=NA, semProbeCount=NA)
if (length(intersect(c('mr', 'tian', 'agile'), method))) {
emstat <- fitModel$compute$steps[[1]]$output
}
if (fitModel$output$status$code != 0) {
summarizeInfo1(NA, emstat, NULL, NULL,
fitModel$output$cpuTime, method)
return()
}
H <- fitModel$output$hessian
if (is.null(H)) H <- fitModel$output$ihessian
condnum <- calcCondNum(H)
H <- NULL
if (!is.na(condnum) && condnum < 1e12) {
if (!is.null(fitModel$output[['hessian']])) {
H <- fitModel$output[['hessian']]
}
if (is.null(H) && !is.null(fitModel$output[['ihessian']])) {
H <- solve(fitModel$output[['ihessian']])
}
}
summarizeInfo1(condnum, emstat, H, fitModel$output$standardErrors,
fitModel$output$cpuTime, method)
}
summarizeDetail <- function(detail, maxCondNum=NA) {
mask <- rep(TRUE, dim(detail)[3])
if (!is.na(maxCondNum)) {
mask <- apply(is.na(detail['condnum',,]) | detail['condnum',,] < maxCondNum, 2, all)
detail <- detail[,,mask]
}
excluded <- 0
if (dim(detail)[3] > 1) {
excluded <- apply(detail['condnum',,], 1, function (c) sum(is.na(c)))
}
print(round(rbind(excluded, apply(detail, 1:2, mean, na.rm=TRUE)), 4))
cat(paste(" N=", sum(mask), "\n", sep=""))
}
testPhase <- function(modelGen, reps = 500, verbose=TRUE, methods=c('agile', 'meat')) {
rec <- c('cputime', 'emcycles', 'probes', 'condnum', 'hNorm', 'rdNorm')
detail <- array(NA, dim=c(length(rec), length(methods), reps),
dimnames=list(rec, methods, NULL))
for (rep in 1:reps) {
warnings()
set.seed(rep)
model <- modelGen()
em <- model$compute
fit <- NULL
fitfun <- c()
if (is(em$mstep, "MxComputeSequence")) {
fitfun <- sapply(em$mstep$steps, function(step) step$fitfunction)
} else {
fitfun <- em$mstep$fitfunction
}
sem <- intersect(c('mr', 'tian'), methods)
if (length(sem)) {
em$accel <- ""
em$tolerance <- 1e-11
em$maxIter <- 750L
for (semType in sem) {
em$information <- "mr1991"
em$infoArgs <- list(fitfunction=fitfun, semMethod=semType, semTolerance=sqrt(1e-6))
plan <- mxComputeSequence(list(
em,
mxComputeStandardError(),
mxComputeReportDeriv()
))
model$compute <- plan
fit <- try(mxRun(model, silent=TRUE, suppressWarnings=TRUE), silent=TRUE)
if (inherits(fit, "try-error")) {
print(paste("error in", semType))
print(fit)
next
} else if (fit$output$status$code != 0) {
print(paste("status code", fit$output$status$code, "without acceleration"))
break
} else {
detail[,semType,rep] <- summarizeInfo(fit, semType)
}
}
}
if (is.null(fit) || inherits(fit, "try-error")) {
em$tolerance <- 1e-11
model$compute <- em
fit <- try(mxRun(model, silent=TRUE, suppressWarnings = TRUE), silent=TRUE)
if (inherits(fit, "try-error")) {
print(paste("error finding MLE"))
print(fit)
next
} else if (fit$output$status$code != 0) {
print(paste("status code", fit$output$status$code))
next
}
}
if (length(intersect(methods, "agile"))) {
em$accel <- 'ramsay1975'
em$tolerance <- 1e-11
em$information <- "mr1991"
em$infoArgs <- list(fitfunction=fitfun, semMethod="agile")
plan <- mxComputeSequence(list(
em,
mxComputeStandardError(),
mxComputeReportDeriv()
))
if (is.null(fit)) fit <- model
fit$compute <- plan
fit <- try(mxRun(fit, silent=TRUE, suppressWarnings = TRUE), silent=TRUE)
if (inherits(fit, "try-error")) {
print(paste("error in agile"))
print(fit)
next
} else if (fit$output$status$code != 0) {
print(paste("status code", fit$output$status$code, "in agile"))
next
} else {
detail[,"agile",rep] <- summarizeInfo(fit, "agile")
}
}
if (length(intersect(methods, "meat"))) {
meat <- mxModel(fit,
mxComputeSequence(steps=list(
mxComputeOnce('fitfunction', 'information', "meat"),
mxComputeStandardError(),
mxComputeReportDeriv())))
meat <- mxRun(meat, silent=TRUE)
detail[,"meat",rep] <- summarizeInfo(meat, "meat")
}
if (length(intersect(methods, "sandwich"))) {
sandwich <- mxModel(fit,
mxComputeSequence(steps=list(
mxComputeOnce('fitfunction', 'information', "sandwich"),
mxComputeStandardError(),
mxComputeReportDeriv())))
sandwich <- mxRun(sandwich, silent=TRUE)
detail[,"sandwich",rep] <- summarizeInfo(sandwich, "sandwich")
}
if (length(intersect(methods, c("oakes")))) {
em$information <- "oakes1999"
em$infoArgs <- list(fitfunction=fitfun)
plan <- mxComputeSequence(list(
em,
mxComputeStandardError(),
mxComputeReportDeriv()
))
fit$compute <- plan
fit <- try(mxRun(fit, silent=TRUE, suppressWarnings = TRUE), silent=TRUE)
if (inherits(fit, "try-error")) {
print(paste("error in agile"))
print(fit)
next
} else if (fit$output$status$code != 0) {
print(paste("status code",fit$output$status$code,"in agile"))
next
} else {
detail[,"oakes",rep] <- summarizeInfo(fit, "oakes")
}
}
if (length(intersect(methods, "estepH"))) {
estepH <- mxModel(fit,
mxComputeSequence(steps=list(
mxComputeOnce(em$expectation, 'scores'),
mxComputeOnce(fitfun, 'information', "hessian"),
mxComputeStandardError(),
mxComputeReportDeriv())))
estepH <- mxRun(estepH, silent=TRUE)
detail[,"estepH",rep] <- summarizeInfo(estepH, "estepH")
}
if (length(intersect(methods, "re"))) {
re <- mxModel(fit,
mxComputeSequence(steps=list(
mxComputeNumericDeriv(stepSize = 1e-3, iterations = 2),
mxComputeStandardError(),
mxComputeReportDeriv())))
re <- mxRun(re, silent=TRUE)
detail[,"re",rep] <- summarizeInfo(re, "re")
}
if (verbose) {
summarizeDetail(detail)
}
}
detail
}
quantifyAsymmetry <- function(info) {
sym1 <- (info + t(info))/2
sym2 <- try(chol(solve(sym1)), silent=TRUE)
if (inherits(sym2, "try-error")) return(NA)
asymV <- (info - t(info))/2
norm(sym2 %*% asymV %*% sym2, type="2")
}
summarizeAgile <- function(fit) {
numReturn <- 4
condnum <- calcCondNum(fit$output$ihessian)
if (is.null(condnum)) condnum <- NA
if (is.na(condnum) || (!is.na(condnum) && condnum > condNumLimit)) return(rep(NA, numReturn))
H <- fit$compute$steps[[1]]$debug$outputInfo
if (is.null(H)) return(rep(NA, numReturn))
asym <- quantifyAsymmetry(solve(H))
H <- (H + t(H))/2
normH <- NA
if (!is.null(H) && all(eigen(H, only.values =TRUE)$val > 0)) {
iH <- try(solve(H), silent=TRUE)
if (is(iH, "try-error")) return(rep(NA, numReturn))
normH <- mvn_KL_D(H, iH)
}
normRd <- NA
rd <- (fit$output$standardErrors - mcSE) / mcSE
if (all(is.finite(rd))) {
normRd <- norm(rd, "2")
}
c(condnum, asym, normH, normRd)
}
summarizeASEM <- function(detail) {
excluded <- apply(detail[,'condnum',], 1, function (c) sum(is.na(c)))
grid <- cbind(excluded,
apply(detail, 1:2, mean, na.rm=TRUE),
apply(detail, 1:2, var, na.rm=TRUE))
cperm <- c(1, 2,6, 3,7, 4,8, 5,9)
print(round(grid[,cperm], 4))
}
studyASEM <- function(modelGen, reps = 100, verbose=TRUE) {
targets=c(seq(-8.1, -3.9, .2), seq(-5.8, -4.4, .2))
targets <- targets[order(runif(length(targets)))]
rec <- c('condnum', 'asym', 'hNorm', 'rdNorm')
detail <- array(NA, dim=c(length(targets), length(rec), reps),
dimnames=list(targets, rec, NULL))
for (rep in 1:reps) {
set.seed(rep)
model <- modelGen()
em <- model$compute
em$tolerance <- 1e-10
em$information <- "mr1991"
fitfun <- c()
if (is(em$mstep, "MxComputeSequence")) {
fitfun <- sapply(em$mstep$steps, function(step) step$fitfunction)
} else {
fitfun <- em$mstep$fitfunction
}
fit <- NULL
for (tx in 1:length(targets)) {
if (is.null(fit) || inherits(fit, "try-error")) fit <- model
em$infoArgs=list(fitfunction=fitfun, semMethod="agile", semDebug=TRUE,
noiseTarget=exp(targets[tx]), semFixSymmetry=TRUE)
plan <- mxComputeSequence(list(
em,
mxComputeStandardError(),
mxComputeReportDeriv()
))
fit$compute <- plan
fit <- try(mxRun(fit, silent=TRUE), silent=TRUE)
if (inherits(fit, "try-error")) {
next
} else {
detail[tx,,rep] <- summarizeAgile(fit)
}
}
if (verbose) summarizeASEM(detail)
}
detail
}
checkSmoothness <- function(mkmodel, probePoints=50) {
set.seed(which(mcMask)[1])
model <- mkmodel()
em <- model$compute
fitfun <- c()
if (is(em$mstep, "MxComputeSequence")) {
fitfun <- sapply(em$mstep$steps, function(step) step$fitfunction)
} else {
fitfun <- em$mstep$fitfunction
}
em$information <- "mr1991"
em$tolerance <- 1e-9
em$infoArgs <- list(fitfunction='fitfunction', semDebug=TRUE,
semMethod=seq(.0005, .01, length.out=probePoints))
model$compute <- em
model <- mxRun(model, silent=TRUE)
em <- model$compute
phl <- em$debug$paramHistLen
probeOffset <- em$debug$probeOffset
semDiff <- em$debug$semDiff
upper <- 20
modelfit <- list()
result <- data.frame()
for (vx in 1:length(model$output$estimate)) {
len <- phl[vx]
offset <- probeOffset[1:len, vx]
dd <- semDiff[1:(len-1), vx]
mid <- offset[1:(len-1)] + diff(offset)/2
mask <- abs(diff(offset)) < .01 & dd < upper
df <- data.frame(mid=mid[mask], diff=dd[mask])
m1 <- lm(diff ~ 0 + I(1/mid^2), data=df)
modelfit[[vx]] <- m1
df$model <- predict(m1)
result <- rbind(result, cbind(vx=vx, vname=names(model$output$estimate)[vx], df))
}
list(result=result, fits=modelfit, modelfit=sapply(modelfit, function(m) summary(m)$r.squ))
}
if (0) {
ggplot(subset(smooth$result, vx %in% order(smooth$modelfit)[1:4])) +
geom_point(aes(mid, diff), size=2) + geom_line(aes(mid, model), color="green") +
facet_wrap(~vname) + labs(x="x midpoint")
} |
Granger.inference.conditional<-function (x, y, z, ic.chosen = "SC", max.lag = min(4, length(x) -
1), plot = F, type.chosen = "none", p1=0, p2=0, nboots = 1000, conf = 0.95,
bp = NULL,ts_boot=1)
{
if (length(x) == 1) {
return("The length of x is only 1")
}
if (length(x) != length(y)) {
return("x and y do not have the same length")
}
if (length(x) != length(z)) {
return("x and z do not have the same length")
}
if (max.lag > length(x) - 1) {
return("The chosen number of lags is larger than or equal to the time length")
}
if(!requireNamespace("vars")){
return("The packages 'vars' could not be found. Please install it to
proceed.")
}
if(!requireNamespace("tseries")){
return("The packages 'tseries' could not be found. Please install it to
proceed.")
}
requireNamespace("vars")
requireNamespace("tseries")
if (p1==0){
model1=VAR(cbind(x,z),ic=ic.chosen,lag.max=max.lag,type.chosen)
}
if (p1>0){
model1=VAR(cbind(x,z),p=p1,type.chosen)
}
if (p2==0){
model2=VAR(cbind(x,y,z),ic=ic.chosen,lag.max=max.lag,type.chosen)
}
if (p2>0){
model2=VAR(cbind(x,y,z),p=p2,type.chosen)
}
if(ts_boot==1){
freq.good = spec.pgram(y, plot = F)$freq/frequency(y)
if (is.array(bp) != TRUE) {
x_bp <- tsbootstrap(x, nb = nboots)
y_bp <- tsbootstrap(y, nb = nboots)
z_bp <- tsbootstrap(z, nb = nboots)
}
if (is.array(bp) == TRUE) {
x_bp <- bp[, , 1]
y_bp <- bp[, , 2]
z_bp <- bp[, , 3]
}
freq.good = spec.pgram(y, plot = F)$freq/frequency(y)
}
delay1_bp <- vector("numeric", nboots)
delay2_bp <- vector("numeric", nboots)
test_stationarity_1 <- vector("numeric", nboots)
test_stationarity_2 <- vector("numeric", nboots)
top_bp_y.to.x.on.z <- vector("numeric", nboots)
freq.curr.l<-vector("numeric", nboots)
stat_rate <- vector("numeric", nboots)
cause_bp_y.to.x.on.z <- array(0, dim = c(nboots, length(freq.good)))
for (w in 1:nboots) {
if(ts_boot==1){
xz_mat<-as.data.frame(cbind(x_bp[, w], z_bp[, w]));
xyz_mat<-as.data.frame(cbind(x_bp[, w],y_bp[, w], z_bp[, w]));
colnames(xz_mat)<-c("x_bp","z_bp")
colnames(xyz_mat)<-c("x2_bp","y2_bp","z2_bp")
if(p1>0 && p2>0){
model1_bp<-VAR(xz_mat, type.chosen,p=model1$p)
model2_bp<-VAR(xyz_mat, type.chosen,p=model2$p)
G.xy <- Granger.conditional(xyz_mat[, 1], xyz_mat[, 2], xyz_mat[, 3], plot=F, type.chosen, p1=model1$p,p2=model2$p)
}
if(p1==0 && p2==0){
model1_bp<-VAR(xz_mat, ic=ic.chosen,
lag.max=max.lag, type.chosen)
model2_bp<-VAR(xyz_mat, ic=ic.chosen,
lag.max=max.lag, type.chosen)
G.xy <- Granger.conditional(xyz_mat[, 1], xyz_mat[, 2], xyz_mat[, 3], ic.chosen,
max.lag, F, type.chosen)
}
}
delay1_bp[w]<-model1_bp$p
delay2_bp[w]<-model2_bp$p
freq.curr.l[w]<-length(G.xy$Conditional_causality_y.to.x.on.z)
cause_bp_y.to.x.on.z[w,] <- G.xy$Conditional_causality_y.to.x.on.z
if (length(which(abs(G.xy$roots_1) >= 1)) > 0) {
test_stationarity_1[w] = 1
}
if (length(which(abs(G.xy$roots_2) >= 1)) > 0) {
test_stationarity_2[w] = 1
}
}
cause_bp_y.to.x.on.z<-cause_bp_y.to.x.on.z[,1:min(freq.curr.l)]
for (w in 1:(nboots)) {
top_bp_y.to.x.on.z[w] <- median(cause_bp_y.to.x.on.z[w, ])
}
stationary <- intersect(which(test_stationarity_1 == 0),
which(test_stationarity_2 == 0))
q_x.on.z <- quantile(top_bp_y.to.x.on.z[stationary], conf)
alpha_bonf<-(1-conf)/length(freq.good)
conf_bonf<-1-alpha_bonf
q_max_x.on.z <- quantile(top_bp_y.to.x.on.z[stationary], conf_bonf)
non_stationarity_rate_1 <- sum(test_stationarity_1)/nboots
non_stationarity_rate_2 <- sum(test_stationarity_2)/nboots
stat_rate<-length(stationary)/nboots
if (length(stationary)>=nboots/nboots){
stat_yes=1;
n <- G.xy$n
GG_x.on.z<-Granger.conditional(x,y,z,ic.chosen,max.lag,F)$Conditional_causality_y.to.x.on.z
signif_x.on.z<-which(GG_x.on.z>q_x.on.z)
signif_max_x.on.z<-which(GG_x.on.z>q_max_x.on.z)
GG <- list(freq.good, n, nboots, conf, stat_yes, non_stationarity_rate_1,
non_stationarity_rate_2, mean(delay1_bp[test_stationarity_1==0]),mean(delay2_bp[test_stationarity_2==0]), q_x.on.z, freq.good[signif_x.on.z],q_max_x.on.z,freq.good[signif_max_x.on.z])
names(GG) <- c("frequency", "n", "nboots","confidence_level","stat_yes", "non_stationarity_rate_1", "non_stationarity_rate_2", "delay1_mean","delay2_mean","quantile_conditional_causality_y.to.x.on.z", "freq_y.to.x.on.z","q_max_x.on.z","freq_max_y.to.x.on.z")
}
if (length(stationary)<nboots/nboots){
stat_yes=0;
GG<-list(stat_yes)
names(GG)<-c("stat_yes")
}
if (plot == F) {
return(GG)
}
if (plot == T) {
par(mfrow = c(1, 1))
plot(freq.good, GG_x.on.z, type = "l", main = "Conditional Granger-causality y to x on z")
abline(h = q_x.on.z)
abline(h = q_max_x.on.z)
}
} |
AutoCatBoostHurdleCARMA <- function(data,
NonNegativePred = FALSE,
Threshold = NULL,
RoundPreds = FALSE,
TrainOnFull = FALSE,
TargetColumnName = 'Target',
DateColumnName = 'DateTime',
HierarchGroups = NULL,
GroupVariables = NULL,
TimeWeights = 1,
FC_Periods = 30,
TimeUnit = 'week',
TimeGroups = c('weeks','months'),
NumOfParDepPlots = 10L,
TargetTransformation = FALSE,
Methods = c('BoxCox', 'Asinh', 'Log', 'LogPlus1', 'Sqrt', 'Asin', 'Logit'),
AnomalyDetection = NULL,
XREGS = NULL,
Lags = c(1L:5L),
MA_Periods = c(2L:5L),
SD_Periods = NULL,
Skew_Periods = NULL,
Kurt_Periods = NULL,
Quantile_Periods = NULL,
Quantiles_Selected = c('q5','q95'),
Difference = TRUE,
FourierTerms = 6L,
CalendarVariables = c('second', 'minute', 'hour', 'wday', 'mday', 'yday', 'week', 'wom', 'isoweek', 'month', 'quarter', 'year'),
HolidayVariable = c('USPublicHolidays','EasterGroup','ChristmasGroup','OtherEcclesticalFeasts'),
HolidayLookback = NULL,
HolidayLags = 1L,
HolidayMovingAverages = 1L:2L,
TimeTrendVariable = FALSE,
ZeroPadSeries = NULL,
DataTruncate = FALSE,
SplitRatios = c(0.7, 0.2, 0.1),
PartitionType = 'timeseries',
Timer = TRUE,
DebugMode = FALSE,
TaskType = 'GPU',
NumGPU = 1,
EvalMetric = 'RMSE',
GridTune = FALSE,
PassInGrid = NULL,
ModelCount = 100,
MaxRunsWithoutNewWinner = 50,
MaxRunMinutes = 24L*60L,
NTrees = list('classifier' = 200, 'regression' = 200),
Depth = list('classifier' = 9, 'regression' = 9),
LearningRate = list('classifier' = NULL, 'regression' = NULL),
L2_Leaf_Reg = list('classifier' = NULL, 'regression' = NULL),
RandomStrength = list('classifier' = 1, 'regression' = 1),
BorderCount = list('classifier' = 254, 'regression' = 254),
BootStrapType = list('classifier' = 'Bayesian', 'regression' = 'Bayesian')) {
if(DebugMode) print('Load catboost----')
loadNamespace(package = 'catboost')
if(DebugMode) print('
Args <- CARMA_Define_Args(TimeUnit=TimeUnit, TimeGroups=TimeGroups, HierarchGroups=HierarchGroups, GroupVariables=GroupVariables, FC_Periods=FC_Periods, PartitionType=PartitionType, TrainOnFull=TrainOnFull, SplitRatios=SplitRatios, SD_Periods=SD_Periods, Skew_Periods=Skew_Periods, Kurt_Periods=Kurt_Periods, Quantile_Periods=Quantile_Periods, TaskType=TaskType, BootStrapType=BootStrapType, GrowPolicy=NULL, TimeWeights=NULL, HolidayLookback=HolidayLookback, Difference=Difference, NonNegativePred=NonNegativePred)
IndepentVariablesPass <- Args$IndepentVariablesPass
NonNegativePred <- Args$NonNegativePred
HolidayLookback <- Args$HolidayLookback
HoldOutPeriods <- Args$HoldOutPeriods
HierarchGroups <- Args$HierarchGroups
GroupVariables <- Args$GroupVariables
BootStrapType <- Args$BootStrapType
TimeWeights <- Args$TimeWeights
TimeGroups <- Args$TimeGroups
FC_Periods <- Args$FC_Periods
GrowPolicy <- Args$GrowPolicy
Difference <- Args$Difference
TimeGroup <- Args$TimeGroupPlaceHolder
TimeUnit <- Args$TimeUnit
TaskType <- Args$TaskType; rm(Args)
ArgsListtt <- c(as.list(environment()))
if(!data.table::is.data.table(data)) data.table::setDT(data)
if(!is.null(XREGS) && !data.table::is.data.table(XREGS)) data.table::setDT(XREGS)
if(!TrainOnFull) HoldOutPeriods <- round(SplitRatios[2L] * length(unique(data[[eval(DateColumnName)]])), 0L)
if(DebugMode) print('Feature Engineering: Add Zero Padding for missing dates----')
if(data[, .N] != unique(data)[, .N]) stop('There is duplicates in your data')
if(!is.null(ZeroPadSeries)) {
data <- TimeSeriesFill(data, DateColumnName=eval(DateColumnName), GroupVariables=GroupVariables, TimeUnit=TimeUnit, FillType=ZeroPadSeries, MaxMissingPercent=0.0, SimpleImpute=FALSE)
data <- ModelDataPrep(data=data, Impute=TRUE, CharToFactor=FALSE, FactorToChar=FALSE, IntToNumeric=FALSE, LogicalToBinary=FALSE, DateToChar=FALSE, RemoveDates=FALSE, MissFactor='0', MissNum=0, IgnoreCols=NULL)
} else {
temp <- TimeSeriesFill(data, DateColumnName=eval(DateColumnName), GroupVariables=GroupVariables, TimeUnit=TimeUnit, FillType='maxmax', MaxMissingPercent=0.25, SimpleImpute=FALSE)
if(temp[,.N] != data[,.N]) stop('There are missing dates in your series. You can utilize the ZeroPadSeries argument to handle this or manage it before running the function')
}
if(DebugMode) print('
Output <- CarmaFCHorizon(data.=data, XREGS.=XREGS, TrainOnFull.=TrainOnFull, Difference.= Difference, FC_Periods.=FC_Periods, HoldOutPeriods.=HoldOutPeriods, DateColumnName.=DateColumnName)
FC_Periods <- Output$FC_Periods
HoldOutPeriods <- Output$HoldOutPeriods; rm(Output)
if(DebugMode) print('merging xregs to data')
if(!is.null(XREGS)) {
Output <- CarmaMergeXREGS(data.=data, XREGS.=XREGS, TargetColumnName.=TargetColumnName, GroupVariables.=GroupVariables, DateColumnName.=DateColumnName)
data <- Output$data; Output$data <- NULL
XREGS <- Output$XREGS; rm(Output)
}
if(DebugMode) print('
if(!is.null(GroupVariables)) {
data.table::setkeyv(x = data, cols = c(eval(GroupVariables), eval(DateColumnName)))
if(!is.null(XREGS)) data.table::setkeyv(x = XREGS, cols = c('GroupVar', eval(DateColumnName)))
} else {
data.table::setkeyv(x = data, cols = c(eval(DateColumnName)))
if(!is.null(XREGS)) data.table::setkeyv(x = XREGS, cols = c(eval(DateColumnName)))
}
if(DebugMode) print('Data Wrangling: Remove Unnecessary Columns ----')
data <- CarmaSubsetColumns(data.=data, XREGS.=XREGS, GroupVariables.=GroupVariables, DateColumnName.=DateColumnName, TargetColumnName.=TargetColumnName)
if(DebugMode) print('Feature Engineering: Concat Categorical Columns - easier to deal with this way ----')
if(!is.null(GroupVariables)) {
data[, GroupVar := do.call(paste, c(.SD, sep = ' ')), .SDcols = GroupVariables]
if(length(GroupVariables) > 1L) data[, eval(GroupVariables) := NULL] else if(GroupVariables != 'GroupVar') data[, eval(GroupVariables) := NULL]
}
if(DebugMode) print('Variables for Program: Store unique values of GroupVar in GroupVarVector ----')
if(!is.null(GroupVariables)) {
GroupVarVector <- data.table::as.data.table(x = unique(as.character(data[['GroupVar']])))
data.table::setnames(GroupVarVector, 'V1', 'GroupVar')
}
if(DebugMode) print('Data Wrangling: Standardize column ordering ----')
if(!is.null(GroupVariables)) data.table::setcolorder(data, c('GroupVar', eval(DateColumnName), eval(TargetColumnName))) else data.table::setcolorder(data, c(eval(DateColumnName), eval(TargetColumnName)))
if(DebugMode) print('Data Wrangling: Convert DateColumnName to Date or POSIXct ----')
Output <- CarmaDateStandardize(data.=data, XREGS.=NULL, DateColumnName.=DateColumnName, TimeUnit.=TimeUnit)
data <- Output$data; Output$data <- NULL
XREGS <- Output$XREGS; rm(Output)
if(DebugMode) print('Data Wrangling: Ensure TargetColumnName is Numeric ----')
if(!is.numeric(data[[eval(TargetColumnName)]])) data[, eval(TargetColumnName) := as.numeric(get(TargetColumnName))]
if(DebugMode) print('Variables for Program: Store number of data partitions in NumSets ----')
NumSets <- length(SplitRatios)
if(DebugMode) print('Variables for Program: Store Maximum Value of TargetColumnName in val ----')
if(!is.null(Lags)) {
if(is.list(Lags) && is.list(MA_Periods)) val <- max(unlist(Lags), unlist(MA_Periods)) else val <- max(Lags, MA_Periods)
}
if(DebugMode) print('Data Wrangling: Sort data by GroupVar then DateColumnName ----')
if(!is.null(GroupVariables)) data <- data[order(GroupVar, get(DateColumnName))] else data <- data[order(get(DateColumnName))]
if(DebugMode) print('Feature Engineering: Fourier Features ----')
Output <- CarmaFourier(data.=data, XREGS.=XREGS, FourierTerms.=FourierTerms, TimeUnit.=TimeUnit, TargetColumnName.=TargetColumnName, GroupVariables.=GroupVariables, DateColumnName.=DateColumnName, HierarchGroups.=HierarchGroups)
FourierTerms <- Output$FourierTerms; Output$FourierTerms <- NULL
FourierFC <- Output$FourierFC; Output$FourierFC <- NULL
data <- Output$data; rm(Output)
if(DebugMode) print('Feature Engineering: Add Create Calendar Variables ----')
if(!is.null(CalendarVariables)) data <- CreateCalendarVariables(data=data, DateCols=eval(DateColumnName), AsFactor=FALSE, TimeUnits=CalendarVariables)
if(DebugMode) print('Feature Engineering: Add Create Holiday Variables ----')
if(!is.null(HolidayVariable)) {
data <- CreateHolidayVariables(data, DateCols = eval(DateColumnName), LookbackDays = if(!is.null(HolidayLookback)) HolidayLookback else LB(TimeUnit), HolidayGroups = HolidayVariable, Holidays = NULL)
if(!(tolower(TimeUnit) %chin% c('1min','5min','10min','15min','30min','hour'))) {
data[, eval(DateColumnName) := lubridate::as_date(get(DateColumnName))]
} else {
data[, eval(DateColumnName) := as.POSIXct(get(DateColumnName))]
}
}
if(DebugMode) print('Anomaly detection by Group and Calendar Vars ----')
if(!is.null(AnomalyDetection)) {
data <- GenTSAnomVars(
data = data, ValueCol = eval(TargetColumnName),
GroupVars = if(!is.null(CalendarVariables) && !is.null(GroupVariables)) c('GroupVar', paste0(DateColumnName, '_', CalendarVariables[1])) else if(!is.null(GroupVariables)) 'GroupVar' else NULL,
DateVar = eval(DateColumnName), KeepAllCols = TRUE, IsDataScaled = FALSE,
HighThreshold = AnomalyDetection$tstat_high,
LowThreshold = AnomalyDetection$tstat_low)
data[, paste0(eval(TargetColumnName), '_zScaled') := NULL]
data[, ':=' (RowNumAsc = NULL, CumAnomHigh = NULL, CumAnomLow = NULL, AnomHighRate = NULL, AnomLowRate = NULL)]
}
if(DebugMode) print('Feature Engineering: Add Target Transformation ----')
if(TargetTransformation) {
TransformResults <- AutoTransformationCreate(data, ColumnNames=TargetColumnName, Methods=Methods, Path=NULL, TransID='Trans', SaveOutput=FALSE)
data <- TransformResults$Data; TransformResults$Data <- NULL
TransformObject <- TransformResults$FinalResults; rm(TransformResults)
} else {
TransformObject <- NULL
}
if(DebugMode) print('Copy data for non grouping + difference ----')
if(is.null(GroupVariables) && Difference) antidiff <- data.table::copy(data[, .SD, .SDcols = c(eval(TargetColumnName),eval(DateColumnName))])
if(DebugMode) print('Feature Engineering: Add Difference Data ----')
Output <- CarmaDifferencing(GroupVariables.=GroupVariables, Difference.=Difference, data.=data, TargetColumnName.=TargetColumnName, FC_Periods.=FC_Periods)
data <- Output$data; Output$data <- NULL
dataStart <- Output$dataStart; Output$dataStart <- NULL
FC_Periods <- Output$FC_Periods; Output$FC_Periods <- NULL
Train <- Output$Train; rm(Output)
if(DebugMode) print('Feature Engineering: Lags and Rolling Stats ----')
Output <- CarmaTimeSeriesFeatures(data.=data, TargetColumnName.=TargetColumnName, DateColumnName.=DateColumnName, GroupVariables.=GroupVariables, HierarchGroups.=HierarchGroups, Difference.=Difference, TimeGroups.=TimeGroups, TimeUnit.=TimeUnit, Lags.=Lags, MA_Periods.=MA_Periods, SD_Periods.=SD_Periods, Skew_Periods.=Skew_Periods, Kurt_Periods.=Kurt_Periods, Quantile_Periods.=Quantile_Periods, Quantiles_Selected.=Quantiles_Selected, HolidayVariable.=HolidayVariable, HolidayLags.=HolidayLags, HolidayMovingAverages.=HolidayMovingAverages, DebugMode.=DebugMode)
IndependentSupplyValue <- Output$IndependentSupplyValue; Output$IndependentSupplyValue <- NULL
HierarchSupplyValue <- Output$HierarchSupplyValue; Output$HierarchSupplyValue <- NULL
GroupVarVector <- Output$GroupVarVector; Output$GroupVarVector <- NULL
Categoricals <- Output$Categoricals; Output$Categoricals <- NULL
data <- Output$data; rm(Output)
if(!is.null(GroupVariables) && !'GroupVar' %chin% names(data)) data[, GroupVar := do.call(paste, c(.SD, sep = ' ')), .SDcols = c(GroupVariables)]
if(DebugMode) print('Data Wrangling: ModelDataPrep() to prepare data ----')
data <- ModelDataPrep(data=data, Impute=TRUE, IntToNumeric=TRUE, DateToChar=FALSE, FactorToChar=FALSE, CharToFactor=TRUE, LogicalToBinary=FALSE, RemoveDates=FALSE, MissFactor='0', MissNum=-1, IgnoreCols=NULL)
if(DebugMode) print('Data Wrangling: Remove dates with imputed data from the DT_GDL_Feature_Engineering() features ----')
if(DataTruncate && !is.null(Lags)) data <- CarmaTruncateData(data.=data, DateColumnName.=DateColumnName, TimeUnit.=TimeUnit)
if(DebugMode) print('Feature Engineering: Add TimeTrend Variable----')
if(TimeTrendVariable) {
if(!is.null(GroupVariables)) data[, TimeTrend := seq_len(.N), by = 'GroupVar'] else data[, TimeTrend := seq_len(.N)]
}
if(DebugMode) print('Create TimeWeights ----')
train <- CarmaTimeWeights(train.=data, TimeWeights.=TimeWeights, GroupVariables.=GroupVariables, DateColumnName.=DateColumnName)
FutureDateData <- unique(data[, get(DateColumnName)])
if(DebugMode) print('Data Wrangling: Partition data with AutoDataPartition()----')
Output <- CarmaPartition(data.=data, SplitRatios.=SplitRatios, TrainOnFull.=TrainOnFull, NumSets.=NumSets, PartitionType.=PartitionType, GroupVariables.=GroupVariables, DateColumnName.=DateColumnName)
train <- Output$train; Output$train <- NULL
valid <- Output$valid; Output$valid <- NULL
data <- Output$data; Output$data <- NULL
test <- Output$test; rm(Output)
if(DebugMode) print('Variables for CARMA function:IDcols----')
IDcols <- names(data)[which(names(data) %chin% DateColumnName)]
IDcols <- c(IDcols, names(data)[which(names(data) == TargetColumnName)])
if(DebugMode) print('Data Wrangling: copy data or train for later in function since AutoRegression will modify data and train ----')
if(!is.null(GroupVariables)) data.table::setorderv(x = data, cols = c('GroupVar',eval(DateColumnName)), order = c(1,1)) else data.table::setorderv(x = data, cols = c(eval(DateColumnName)), order = c(1))
Step1SCore <- data.table::copy(data)
if(DebugMode) print('Define ML args ----')
Output <- CarmaFeatures(data.=data, train.=train, XREGS.=XREGS, Difference.=Difference, TargetColumnName.=TargetColumnName, DateColumnName.=DateColumnName, GroupVariables.=GroupVariables)
ModelFeatures <- Output$ModelFeatures
TargetVariable <- Output$TargetVariable; rm(Output)
if(!is.null(SplitRatios) || !TrainOnFull) TOF <- FALSE else TOF <- TRUE
if(DebugMode) print('Run AutoCatBoostHurdleModel() and return list of ml objects ----')
TestModel <- AutoCatBoostHurdleModel(
task_type = TaskType,
ModelID = 'ModelTest',
SaveModelObjects = FALSE,
ReturnModelObjects = TRUE,
data = data.table::copy(train),
TrainOnFull = TrainOnFull,
ValidationData = data.table::copy(valid),
TestData = data.table::copy(test),
Buckets = 0L,
TargetColumnName = TargetVariable,
FeatureColNames = ModelFeatures,
PrimaryDateColumn = eval(DateColumnName),
WeightsColumnName = if('Weights' %chin% names(train)) 'Weights' else NULL,
IDcols = IDcols,
DebugMode = DebugMode,
Paths = normalizePath('./'),
MetaDataPaths = NULL,
TransformNumericColumns = NULL,
Methods = NULL,
ClassWeights = c(1,1),
SplitRatios = c(0.70, 0.20, 0.10),
NumOfParDepPlots = NumOfParDepPlots,
PassInGrid = PassInGrid,
GridTune = GridTune,
BaselineComparison = 'default',
MaxModelsInGrid = 500L,
MaxRunsWithoutNewWinner = 100L,
MaxRunMinutes = 60*60,
MetricPeriods = 10L,
Trees = NTrees,
Depth = Depth,
RandomStrength = RandomStrength,
BorderCount = BorderCount,
LearningRate = LearningRate,
L2_Leaf_Reg = L2_Leaf_Reg,
RSM = list('classifier' = c(1.0), 'regression' = c(1.0)),
BootStrapType = BootStrapType,
GrowPolicy = list('classifier' = 'SymmetricTree', 'regression' = 'SymmetricTree'))
if(!is.null(Threshold)) {
threshold <- TestModel$ClassifierModel$EvaluationMetrics
col <- names(threshold)[grep(pattern = Threshold, x = names(threshold))]
Threshold <- threshold[, .SD, .SDcols = c('Threshold', eval(col))][order(-get(col))][1,1][[1]]
}
if(!TrainOnFull) return(TestModel)
if(DebugMode) options(warn = 2)
if(DebugMode) print('Variable for interation counts: max number of rows in Step1SCore data.table across all group ----')
N <- CarmaRecordCount(GroupVariables.=GroupVariables,Difference.=Difference, Step1SCore.=Step1SCore)
if(DebugMode) print('ARMA PROCESS FORECASTING----')
for(i in seq_len(FC_Periods+1L)) {
if(DebugMode) print('Row counts----')
if(i != 1) N <- as.integer(N + 1L)
if(DebugMode) print('Machine Learning: Generate predictions----')
if(i == 1L) {
if(!is.null(GroupVariables)) {
Preds <- RemixAutoML::AutoCatBoostHurdleModelScoring(
TestData = data.table::copy(Step1SCore),
Path = NULL,
ModelID = 'ModelTest',
ModelList = TestModel$ModelList,
ArgsList = TestModel$ArgsList,
Threshold = Threshold,
CARMA = TRUE)
Preds[, (names(Preds)[2L:5L]) := NULL]
data.table::set(Preds, j = eval(DateColumnName), value = NULL)
data.table::setnames(Preds, 'UpdatedPrediction', 'Predictions')
data.table::setcolorder(Preds, c(2L,1L,3L:ncol(Preds)))
if(RoundPreds) Preds[, Predictions := round(Predictions)]
} else {
Preds <- AutoCatBoostHurdleModelScoring(
TestData = data.table::copy(Step1SCore),
Path = NULL,
ModelID = 'ModelTest',
ModelList = TestModel$ModelList,
ArgsList = TestModel$ArgsList,
Threshold = Threshold,
CARMA = TRUE)
Preds[, (names(Preds)[2L:5L]) := NULL]
if(DateColumnName %chin% names(Preds)) data.table::set(Preds, j = eval(DateColumnName), value = NULL)
data.table::setnames(Preds, 'UpdatedPrediction', 'Predictions')
data.table::setcolorder(Preds, c(2L,1L,3L:ncol(Preds)))
if(RoundPreds) Preds[, Predictions := round(Predictions)]
}
if(Difference) {
if(eval(TargetColumnName) %chin% names(Step1SCore) && eval(TargetColumnName) %chin% names(Preds)) {
data.table::set(Preds, j = eval(TargetColumnName), value = NULL)
}
if(eval(DateColumnName) %chin% names(Step1SCore)) data.table::set(Step1SCore, j = eval(DateColumnName), value = NULL)
if(eval(DateColumnName) %chin% names(Preds)) data.table::set(Preds, j = eval(DateColumnName), value = NULL)
if(!is.null(GroupVariables)) {
UpdateData <- cbind(FutureDateData, Step1SCore[, .SD, .SDcols = eval(TargetColumnName)],Preds)
} else {
UpdateData <- cbind(FutureDateData[2L:(nrow(Step1SCore)+1L)], Step1SCore[, .SD, .SDcols = eval(TargetColumnName)],Preds)
}
data.table::setnames(UpdateData, 'FutureDateData', eval(DateColumnName))
} else {
if(NonNegativePred) Preds[, Predictions := data.table::fifelse(Predictions < 0.5, 0, Predictions)]
UpdateData <- cbind(FutureDateData[1L:N],Preds)
data.table::setnames(UpdateData,c('V1'),c(eval(DateColumnName)))
}
} else {
if(!is.null(GroupVariables)) {
if(Difference) IDcols = 'ModTarget' else IDcols <- eval(TargetColumnName)
if(!is.null(HierarchGroups)) {
temp <- data.table::copy(UpdateData[, ID := 1:.N, by = c(eval(GroupVariables))])
temp <- temp[ID == N][, ID := NULL]
} else {
temp <- data.table::copy(UpdateData[, ID := 1:.N, by = 'GroupVar'])
temp <- temp[ID == N][, ID := NULL]
}
Preds <- RemixAutoML::AutoCatBoostHurdleModelScoring(
TestData = temp,
Path = NULL,
ModelID = 'ModelTest',
ModelList = TestModel$ModelList,
ArgsList = TestModel$ArgsList,
Threshold = Threshold,
CARMA = TRUE)
Preds[, (setdiff(names(Preds),'UpdatedPrediction')) := NULL]
data.table::setnames(Preds, 'UpdatedPrediction', 'Predictions')
if(RoundPreds) Preds[, Predictions := round(Predictions)]
if(DebugMode) print('Update data group case----')
data.table::setnames(Preds, 'Predictions', 'Preds')
if(NonNegativePred & !Difference) Preds[, Preds := data.table::fifelse(Preds < 0.5, 0, Preds)]
Preds <- cbind(UpdateData[ID == N], Preds)
if(Difference) Preds[, ModTarget := Preds][, eval(TargetColumnName) := Preds] else Preds[, eval(TargetColumnName) := Preds]
Preds[, Predictions := Preds][, Preds := NULL]
UpdateData <- UpdateData[ID != N]
if(any(class(UpdateData$Date) %chin% c('POSIXct','POSIXt')) & any(class(Preds$Date) == 'Date')) UpdateData[, eval(DateColumnName) := as.Date(get(DateColumnName))]
UpdateData <- data.table::rbindlist(list(UpdateData, Preds))
if(Difference) UpdateData[ID %in% c(N-1,N), eval(TargetColumnName) := cumsum(get(TargetColumnName)), by = 'GroupVar']
UpdateData[, ID := NULL]
} else {
Preds <- RemixAutoML::AutoCatBoostHurdleModelScoring(
TestData = UpdateData[.N],
Path = NULL,
ModelID = 'ModelTest',
ModelList = TestModel$ModelList,
ArgsList = TestModel$ArgsList,
Threshold = Threshold,
CARMA = TRUE)
Preds[, (setdiff(names(Preds),'UpdatedPrediction')) := NULL]
data.table::setnames(Preds, 'UpdatedPrediction', 'Predictions')
if(RoundPreds) Preds[, Predictions := round(Predictions)]
if(DebugMode) print('Update data non-group case----')
data.table::set(UpdateData, i = UpdateData[, .N], j = which(names(UpdateData) %chin% c(TargetColumnName, "Predictions")), value = Preds[[1L]])
}
}
if(i != FC_Periods+1L) {
if(DebugMode) print('Timer----')
if(Timer) if(i != 1) print(paste('Forecast future step: ', i-1))
if(Timer) starttime <- Sys.time()
if(DebugMode) print('Create single future record ----')
CalendarFeatures <- NextTimePeriod(UpdateData.=UpdateData, TimeUnit.=TimeUnit, DateColumnName.=DateColumnName)
if(DebugMode) print('Update feature engineering ----')
UpdateData <- UpdateFeatures(UpdateData.=UpdateData, GroupVariables.=GroupVariables, CalendarFeatures.=CalendarFeatures, CalendarVariables.=CalendarVariables, GroupVarVector.=GroupVarVector, DateColumnName.=DateColumnName, XREGS.=XREGS, FourierTerms.=FourierTerms, FourierFC.=FourierFC, TimeGroups.=TimeGroups, TimeTrendVariable.=TimeTrendVariable, N.=N, TargetColumnName.=TargetColumnName, HolidayVariable.=HolidayVariable, HolidayLookback.=HolidayLookback, TimeUnit.=TimeUnit, AnomalyDetection.=AnomalyDetection, i.=i)
if(DebugMode) print('Update Lags and MAs ----')
UpdateData <- CarmaRollingStatsUpdate(ModelType='catboost', DebugMode.=DebugMode, UpdateData.=UpdateData, GroupVariables.=GroupVariables, Difference.=Difference, CalendarVariables.=CalendarVariables, HolidayVariable.=HolidayVariable, IndepVarPassTRUE.=IndepentVariablesPass, data.=data, CalendarFeatures.=CalendarFeatures, XREGS.=XREGS, HierarchGroups.=HierarchGroups, GroupVarVector.=GroupVarVector, TargetColumnName.=TargetColumnName, DateColumnName.=DateColumnName, Preds.=Preds, HierarchSupplyValue.=HierarchSupplyValue, IndependentSupplyValue.=IndependentSupplyValue, TimeUnit.=TimeUnit, TimeGroups.=TimeGroups, Lags.=Lags, MA_Periods.=MA_Periods, SD_Periods.=SD_Periods, Skew_Periods.=Skew_Periods, Kurt_Periods.=Kurt_Periods, Quantile_Periods.=Quantile_Periods, Quantiles_Selected.=Quantiles_Selected, HolidayLags.=HolidayLags, HolidayMovingAverages.=HolidayMovingAverages)
if(Timer) endtime <- Sys.time()
if(Timer && i != 1) print(endtime - starttime)
}
}
gc()
if(DebugMode) print('Return data prep ----')
Output <- CarmaReturnDataPrep(UpdateData.=UpdateData, FutureDateData.=FutureDateData, dataStart.=dataStart, DateColumnName.=DateColumnName, TargetColumnName.=TargetColumnName, GroupVariables.=GroupVariables, Difference.=Difference, TargetTransformation.=TargetTransformation, TransformObject.=TransformObject, NonNegativePred.=NonNegativePred)
UpdateData <- Output$UpdateData; Output$UpdateData <- NULL
TransformObject <- Output$TransformObject; rm(Output)
if(is.null(GroupVariables) && "Predictions0" %chin% names(UpdateData)) data.table::set(UpdateData, j = 'Predictions0', value = NULL)
return(list(
Forecast = UpdateData,
ModelInformation = TestModel,
TransformationDetail = if(exists('TransformObject') && !is.null(TransformObject)) TransformObject else NULL,
ArgsList = ArgsListtt))
} |
"U15" |
'%+%' <- function(x,y) { merge.semforest(x,y) } |
contemporaryPhy <- function(phy, maxBin, minBin, reScale=0, allTraits, closest.min=TRUE, traits.from.tip=TRUE) {
node.in <- match(unique(phy$edge[,1]), phy$edge[,1])
node.times <- nodeTimes(phy)[node.in,1]
names(node.times) <- unique(phy$edge[,1])
startBin <- maxBin - reScale
endBin <- minBin - reScale
nodePreBin <- as.numeric(names(node.times)[which(node.times < endBin)])
tip.times <- nodeTimes(phy)[which(phy$edge[,2] <= Ntip(phy)), 2]
tipsInBin <- intersect(which(tip.times >= endBin), which(tip.times <= startBin))
int.node <- which(phy$edge[,2] > Ntip(phy))
descendantAsTrait <- rep(0, dim(phy$edge)[1])
for(rr in int.node) descendantAsTrait[rr] <- length(node.descendents(phy$edge[rr,2], phy, T)[[2]])
tipsInMat <- which(phy$edge[,2] <= Ntip(phy))
terminalTips <- which(descendantAsTrait == 0)
loseTips <- match(tipsInMat[tipsInBin], terminalTips)
descendantAsTrait[terminalTips[-loseTips]] <- 1
names(descendantAsTrait) <- phy$edge[,2]
success <- timeTravelPhy(phy=phy, node=nodePreBin, nodeEstimate=descendantAsTrait, timeCut=endBin)
suc <- removeNonBin(success$phy, success$tipData, keepByTime=startBin - endBin)
out <- list()
out <- suc
names(out) <- c("phy", "descendants")
if(!is.null(allTraits)) {
first.times <- nodeTimes(phy)
new.phylo <- suc$prunedPhy
time.new.phylo <- nodeTimes(new.phylo) + reScale
new.tip.names <- new.phylo$tip.label
identify.tip <- regexpr("node_", new.phylo$tip.label)
original.tip <- which(identify.tip == -1)
same.as.original <- new.tip.names[original.tip]
which.tips <- match(match(same.as.original, phy$tip.label), phy$edge[,2])
new.spp <- which(identify.tip != -1)
location.new.spp <- match(new.spp, new.phylo$edge[,2])
node.original <- as.numeric(gsub("node_", "", new.phylo$tip.label[new.spp]))
which.nodes <- match(node.original, phy$edge[,2])
on.orig <- sort(c(which.nodes, which.tips))
if (closest.min) closest.bin <- minBin else closest.bin <- maxBin
trait.mat.new <- sapply(1:length(on.orig), function(i) {
here.node <- on.orig[i]
diff.age <- abs(first.times[here.node, ] - closest.bin)
smallest.distance <- which.min(diff.age)
if(smallest.distance == 2) {
allTraits[here.node]
} else {
older.node <- match(phy$edge[here.node,1], phy$edge[,2])
allTraits[older.node]
}
}
)
if(traits.from.tip) trait.mat.new[original.tip] <- allTraits[which.tips]
out$traits <- trait.mat.new
}
return(out)
} |
label_parse <- function() {
function(text) {
text <- as.character(text)
out <- vector("expression", length(text))
for (i in seq_along(text)) {
expr <- parse(text = text[[i]])
out[[i]] <- if (length(expr) == 0) NA else expr[[1]]
}
out
}
}
label_math <- function(expr = 10^.x, format = force) {
.x <- NULL
quoted <- substitute(expr)
subs <- function(x) {
do.call("substitute", list(quoted, list(.x = x)))
}
function(x) {
x <- format(x)
ret <- lapply(x, subs)
ret <- as.expression(ret)
ret[is.na(x)] <- NA
names(ret) <- names(x)
ret
}
}
parse_format <- label_parse
math_format <- label_math |
context("test-nnetar")
airmiles <- as_tsibble(airmiles)
test_that("Automatic NNETAR selection", {
air_fit <- airmiles %>% model(NNETAR(box_cox(value, 0.15)))
expect_equal(model_sum(air_fit[[1]][[1]]), "NNAR(1,1)")
air_fit <- airmiles %>% model(NNETAR(box_cox(value, 0.15) ~ trend() + rnorm(length(index))))
air_fit <- airmiles %>% model(NNETAR(box_cox(value, 0.15) ~ trend()))
air_fit %>%
generate(h = 10, times = 5)
fc_sim <- air_fit %>%
forecast(h = 10, times = 5)
fc_boot <- air_fit %>%
forecast(h = 10, times = 5, bootstrap = TRUE)
expect_equal(
fc_sim$value,
fc_boot$value,
tolerance = 100
)
expect_output(
UKLungDeaths[1:24, ] %>%
model(NNETAR(mdeaths)) %>%
report(),
"NNAR\\(4,1,3\\)\\[12\\]"
)
})
test_that("Manual NNETAR selection", {
fit <- UKLungDeaths %>%
model(NNETAR(mdeaths ~ AR(p = 3, P = 2)))
expect_equal(model_sum(fit[[1]][[1]]), "NNAR(3,2,3)[12]")
expect_equal(
with(augment(fit), .fitted + .resid)[-(1:24)],
UKLungDeaths$mdeaths[-(1:24)]
)
expect_warning(
airmiles[1:5, ] %>%
model(NNETAR(value ~ AR(10))),
"Reducing number of lagged inputs due to short series"
)
})
test_that("NNETAR with bad inputs", {
expect_warning(
airmiles[1:2, ] %>%
model(NNETAR(value)),
"Not enough data to fit a model"
)
expect_warning(
airmiles %>%
model(NNETAR(resp(rep_along(value, NA)))),
"All observations are missing, a model cannot be estimated without data"
)
expect_warning(
airmiles %>%
model(NNETAR(resp(rep_along(value, 1)))),
"Constant data, setting `AR\\(p=1, P=0\\)`, and `scale_inputs=FALSE`"
)
expect_warning(
airmiles %>%
model(NNETAR(value ~ rep_along(value, 1))),
"Constant xreg column, setting `scale_inputs=FALSE`"
)
}) |
bindEvents <-
function(
rec,
file,
by.species=TRUE,
parallel=FALSE,
return.times=FALSE
) {
if(class(file) != "data.frame") events <- read.csv(file=file)
else events <- file
events['duration'] <- events[, 'end.time']-events[, 'start.time']
if(by.species) {
spp <- events$name
events <- split(events, events$name)
events <- lapply(events, function(x) data.frame(x, start.time.collapsed=cumsum(x$duration)-x$duration, end.time.collapsed=cumsum(x$duration)))
} else {
events$start.time.collapsed=cumsum(events$duration)-events$duration
events$end.time.collapsed=cumsum(events$duration)
}
if(parallel && by.species) {
collapsed <- parallel::mclapply(X=events, FUN=function(x) collapseClips(rec=rec, start.times=x$start.time, end.times=x$end.time), max(1, parallel::detectCores()-1))
} else if(by.species) {
collapsed <- lapply(X=events, FUN=function(x) collapseClips(rec=rec, start.times=x$start.time, end.times=x$end.time))
} else {
collapsed <- list(collapseClips(rec=rec, start.times=events$start.time, end.times=events$end.time))
}
if(return.times) return(list(times=events, wave=collapsed)) else return(collapsed)
} |
structure(list(url = "https://api.twitter.com/2/tweets?tweet.fields=attachments%2Cauthor_id%2Cconversation_id%2Ccreated_at%2Centities%2Cgeo%2Cid%2Cin_reply_to_user_id%2Clang%2Cpublic_metrics%2Cpossibly_sensitive%2Creferenced_tweets%2Csource%2Ctext%2Cwithheld&user.fields=created_at%2Cdescription%2Centities%2Cid%2Clocation%2Cname%2Cpinned_tweet_id%2Cprofile_image_url%2Cprotected%2Cpublic_metrics%2Curl%2Cusername%2Cverified%2Cwithheld&expansions=author_id%2Centities.mentions.username%2Cgeo.place_id%2Cin_reply_to_user_id%2Creferenced_tweets.id%2Creferenced_tweets.id.author_id&place.fields=contained_within%2Ccountry%2Ccountry_code%2Cfull_name%2Cgeo%2Cid%2Cname%2Cplace_type&ids=1%2C1266868259925737474%2C1266867327079002121%2C1266866660713127936%2C1266864490446012418%2C1266860737244336129%2C1266859737615826944%2C1266859455586676736%2C1266858090143588352%2C1266857669157097473%2C1266856357954756609%2C1266855807699861506%2C1266855344086663169%2C1266854627758276608%2C1266854586188476421",
status_code = 200L, headers = structure(list(date = "Sun, 19 Dec 2021 20:49:05 UTC",
server = "tsa_o", `api-version` = "2.32", `content-type` = "application/json; charset=utf-8",
`cache-control` = "no-cache, no-store, max-age=0", `content-length` = "7714",
`x-access-level` = "read", `x-frame-options` = "SAMEORIGIN",
`content-encoding` = "gzip", `x-xss-protection` = "0",
`x-rate-limit-limit` = "300", `x-rate-limit-reset` = "1639947531",
`content-disposition` = "attachment; filename=json.json",
`x-content-type-options` = "nosniff", `x-rate-limit-remaining` = "275",
`strict-transport-security` = "max-age=631138519", `x-response-time` = "401",
`x-connection-hash` = "a8dd0b91b56c071e60ae4b83ca064c192d64678a1e03c31011044170217df8ed"), class = c("insensitive",
"list")), all_headers = list(list(status = 200L, version = "HTTP/2",
headers = structure(list(date = "Sun, 19 Dec 2021 20:49:05 UTC",
server = "tsa_o", `api-version` = "2.32", `content-type` = "application/json; charset=utf-8",
`cache-control` = "no-cache, no-store, max-age=0",
`content-length` = "7714", `x-access-level` = "read",
`x-frame-options` = "SAMEORIGIN", `content-encoding` = "gzip",
`x-xss-protection` = "0", `x-rate-limit-limit` = "300",
`x-rate-limit-reset` = "1639947531", `content-disposition` = "attachment; filename=json.json",
`x-content-type-options` = "nosniff", `x-rate-limit-remaining` = "275",
`strict-transport-security` = "max-age=631138519",
`x-response-time` = "401", `x-connection-hash` = "a8dd0b91b56c071e60ae4b83ca064c192d64678a1e03c31011044170217df8ed"), class = c("insensitive",
"list")))), cookies = structure(list(domain = c(".twitter.com",
".twitter.com", ".twitter.com", ".twitter.com"), flag = c(TRUE,
TRUE, TRUE, TRUE), path = c("/", "/", "/", "/"), secure = c(TRUE,
TRUE, TRUE, TRUE), expiration = structure(c(1702744284, 1702744284,
1702744284, 1702744284), class = c("POSIXct", "POSIXt")),
name = c("guest_id_marketing", "guest_id_ads", "personalization_id",
"guest_id"), value = c("REDACTED", "REDACTED", "REDACTED",
"REDACTED")), row.names = c(NA, -4L), class = "data.frame"),
content = charToRaw("{\"data\":[{\"author_id\":\"1239879547409006592\",\"referenced_tweets\":[{\"type\":\"retweeted\",\"id\":\"1266816466512297984\"}],\"created_at\":\"2020-05-30T23:05:05.000Z\",\"text\":\"RT @TheReal32492440:
date = structure(1639946945, class = c("POSIXct", "POSIXt"
), tzone = "GMT"), times = c(redirect = 0, namelookup = 3.4e-05,
connect = 3.5e-05, pretransfer = 0.000126, starttransfer = 0.413385,
total = 0.414157)), class = "response") |
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
out.width = "100%"
)
library(sdcSpatial)
library(sdcSpatial)
data("enterprises")
head(enterprises)
summary(enterprises)
sp::plot(enterprises)
production <- sdc_raster(enterprises, "production", r = 500)
plot(production, value="mean", sensitive=FALSE, main="mean production")
raster::plot(production$value[[1:3]])
print(production)
production$min_count <- 5
production$max_risk <- 0.9
production <- sdc_raster(enterprises, "production"
, r = 500, min_count = 5, max_risk = 0.9)
sensitivity_score(production)
plot(production)
sensitive_cells <- is_sensitive(production)
production_smoothed <- protect_smooth(production, bw = 500)
plot(production_smoothed)
production_safe <- remove_sensitive(production_smoothed)
sensitivity_score(production_safe)
mean_production <- mean(production_safe)
mean_production <- raster::disaggregate(mean_production, 10, "bilinear")
col <- c("
"
raster::plot(mean_production, col=col)
fined <- sdc_raster(enterprises, "fined", min_count = 5, r = 200, max_risk = 0.8)
print(fined)
col <- c("
, "
plot(fined, "mean", col=col)
fined_qt <- protect_quadtree(fined)
plot(fined_qt, col=col)
fined_smooth <- protect_smooth(fined, bw = 500)
plot(fined_smooth, col = col)
sensitivity_score(fined_smooth) |
basepredict = function(model, values, sim.count = 1000, conf.int = 0.95, sigma=NULL, set.seed=NULL,
type = c("any", "simulation", "bootstrap"), summary = TRUE){
UseMethod("basepredict")
} |
gmdh.combi.twice_3 <- function(X, y, G) {
fin.1 <- Inf
fin.2 <- 0
lap <- 0
modelos <- vector(mode = "list", length = 2)
names(modelos) <- c("results", "G")
modelos$G <- G
prune <- ncol(X)
while(fin.1 >= fin.2) {
lap <- lap + 1
message(paste("Layer ", lap, sep = ""))
regressors <- fun.poly(X, G = G)
regressors <- fun.filter(regressors)
combs <- do.call(expand.grid, rep(list(c(FALSE, TRUE)), ncol(regressors)))[-1, ]
results <- apply(combs, 1, function(x){fun.svd_3(y = y, x = regressors[, x, drop = FALSE])})
names(results) <- paste(lap, c("."), 1:length(results), sep = "")
Z <- lapply(results, predict.svd, regressors)
Z <- matrix(data = unlist(Z), nrow = nrow(X), ncol = length(Z))
colnames(Z) <- names(results)
Z <- fun.filter(Z)
nombres.Z <- colnames(Z)
cv <- unlist(lapply(results, function(x){x$CV}))
cv <- cv[nombres.Z]
ndx <- sort(na.omit(order(cv)[1:prune]))
cv <- cv[ndx, drop = FALSE]
results <- results[names(cv)]
Z <- Z[, names(cv)]
fin.1 <- min(cv, na.rm = TRUE)
message(paste(" Error ", fin.1, sep = ""))
lap <- lap + 1
message(paste("Layer ", lap, sep = ""))
regressors <- fun.poly(Z, G = G)
regressors <- fun.filter(regressors)
combs <- do.call(expand.grid, rep(list(c(FALSE, TRUE)), ncol(regressors)))[-1, ]
results.2 <- apply(combs, 1, function(x){fun.svd_3(y = y, x = regressors[, x, drop = FALSE])})
names(results.2) <- paste(lap, c("."), 1:length(results.2), sep = "")
X <- lapply(results.2, predict.svd, regressors)
X <- matrix(data = unlist(X), nrow = nrow(Z), ncol = length(X))
colnames(X) <- names(results.2)
X <- fun.filter(X)
nombres.X <- colnames(X)
cv <- unlist(lapply(results.2, function(x){x$CV}))
cv <- cv[nombres.X]
ndx <- sort(na.omit(order(cv)[1:prune]))
cv <- cv[ndx, drop = FALSE]
X <- X[, names(cv)]
fin.2 <- min(cv, na.rm = TRUE)
message(paste(" Error ", fin.2, sep = ""))
results.2 <- results.2[ndx]
modelos$results[[length(modelos$results) + 1]] <- results
modelos$results[[length(modelos$results) + 1]] <- results.2
class(modelos) <- "combitwice"
ifelse(fin.2 >= fin.1, return(modelos), NA)
}
} |
simple_UVs <- function(data) {
simple_UVs <- CI <- NULL
simple_UVs <- CIs(data)
dplyr::rename(simple_UVs, simple_UV = CI)
} |
ergm.MCMLE <- function(init, nw, model,
initialfit,
control,
proposal, proposal.obs,
verbose=FALSE,
sequential=control$MCMLE.sequential,
estimate=TRUE, ...) {
message("Starting Monte Carlo maximum likelihood estimation (MCMLE):")
obs <- ! is.null(proposal.obs)
coef.hist <- rbind(init)
stats.hist <- matrix(NA, 0, length(model$nw.stats))
stats.obs.hist <- matrix(NA, 0, length(model$nw.stats))
steplen.hist <- c()
steplen <- control$MCMLE.steplength
if(control$MCMLE.steplength=="adaptive") steplen <- 1
if(is.null(control$MCMLE.samplesize)) control$MCMLE.samplesize <- max(control$MCMLE.samplesize.min,control$MCMLE.samplesize.per_theta*nparam(model,canonical=FALSE, offset=FALSE))
if(obs && is.null(control$obs.MCMLE.samplesize)) control$obs.MCMLE.samplesize <- max(control$obs.MCMLE.samplesize.min,control$obs.MCMLE.samplesize.per_theta*nparam(model,canonical=FALSE, offset=FALSE))
control <- remap_algorithm_MCMC_controls(control, "MCMLE")
control$MCMC.base.effectiveSize <- control$MCMC.effectiveSize
control$obs.MCMC.base.effectiveSize <- control$obs.MCMC.effectiveSize
control$MCMC.base.samplesize <- control$MCMC.samplesize
control$obs.MCMC.base.samplesize <- control$obs.MCMC.samplesize
control0 <- control
ergm.getCluster(control, max(verbose-1,0))
nw.orig <- nw
s <- single.impute.dyads(nw, constraints=proposal$arguments$constraints, constraints.obs=proposal.obs$arguments$constraints, min_informative = control$obs.MCMC.impute.min_informative, default_density = control$obs.MCMC.impute.default_density, output="ergm_state", verbose=verbose)
if(control$MCMLE.density.guard>1){
ec <- network.edgecount(s)
control$MCMC.maxedges <- round(min(control$MCMC.maxedges,
max(control$MCMLE.density.guard*ec,
control$MCMLE.density.guard.min)))
if(verbose) message("Density guard set to ",control$MCMC.maxedges," from an initial count of ",ec," edges.")
}
model$nw.stats <- summary(model, s)
statshift <- model$nw.stats - NVL(model$target.stats,model$nw.stats)
statshift[is.na(statshift)] <- 0
s <- update(s, model=model, proposal=proposal, stats=statshift)
s <- rep(list(s),nthreads(control))
if(obs){
control.obs <- control
for(name in OBS_MCMC_CONTROLS) control.obs[[name]] <- control[[paste0("obs.", name)]]
control0.obs <- control.obs
s.obs <- lapply(s, update, model=NVL(model$obs.model,model), proposal=proposal.obs)
}
.boost_samplesize <- function(boost, base=FALSE){
for(ctrl in c("control", if(obs) "control.obs")){
control <- get(ctrl, parent.frame())
sampsize.boost <-
NVL2(control$MCMC.effectiveSize,
boost^control$MCMLE.sampsize.boost.pow,
boost)
control$MCMC.samplesize <- round((if(base) control$MCMC.base.samplesize else control$MCMC.samplesize) * sampsize.boost)
control$MCMC.effectiveSize <- NVL3((if(base) control$MCMC.base.effectiveSize else control$MCMC.effectiveSize), . * boost)
control$MCMC.samplesize <- ceiling(max(control$MCMC.samplesize, control$MCMC.effectiveSize*control$MCMLE.min.depfac))
assign(ctrl, control, parent.frame())
}
NULL
}
if(control$MCMLE.termination=='confidence'){
estdiff.prev <- NULL
d2.not.improved <- rep(FALSE, control$MCMLE.confidence.boost.lag)
}
mcmc.init <- init
calc.MCSE <- FALSE
last.adequate <- FALSE
ERGM_STATE_ELEMENTS <- c("el", "nw0", "stats", "ext.state", "ext.flag")
STATE_VARIABLES <- c("mcmc.init", "calc.MCSE", "last.adequate", "coef.hist", "stats.hist", "stats.obs.hist", "steplen.hist", "steplen","setdiff.prev","d2.not.improved")
CONTROL_VARIABLES <- c("control", "control.obs", "control0", "control0.obs")
INTERMEDIATE_VARIABLES <- c("s", "s.obs", "statsmatrices", "statsmatrices.obs", "coef.hist", "stats.hist", "stats.obs.hist", "steplen.hist")
if(!is.null(control$resume)){
message("Resuming from state saved in ", sQuote(control$resume),".")
state <- new.env()
load(control$resume,envir=state)
.merge_controls <- function(saved.ctrl, saved.ctrl0, ctrl0){
ctrl <- saved.ctrl
for(name in union(names(ctrl), names(ctrl0))){
if(!identical(ctrl[[name]],ctrl0[[name]])){
if(!identical(ctrl0[[name]], saved.ctrl0[[name]])){
if(verbose) message("Passed-in control setting ", sQuote(name), " changed from original run: overriding saved state.")
ctrl[[name]] <- ctrl0[[name]]
}else if(verbose) message("Passed-in control setting ", sQuote(name), " unchanged from original run: using saved state.")
}
}
ctrl
}
control <- .merge_controls(state$control, state$control0, control0)
if(obs) control.obs <- .merge_controls(state$control.obs, state$control0.obs, control0.obs)
for(i in seq_along(s)) for(name in ERGM_STATE_ELEMENTS) s[[i]][[name]] <- state$s.reduced[[i]][[name]]
if(obs) for(i in seq_along(s.obs)) for(name in ERGM_STATE_ELEMENTS) s.obs[[i]][[name]] <- state$s.obs.reduced[[i]][[name]]
for(name in intersect(ls(state), STATE_VARIABLES)) assign(name, state[[name]])
rm(state)
}
for(iteration in 1:control$MCMLE.maxit){
if(verbose){
message("\nIteration ",iteration," of at most ", control$MCMLE.maxit,
" with parameter:")
message_print(mcmc.init)
}else{
message("Iteration ",iteration," of at most ", control$MCMLE.maxit,":")
}
if(!is.null(control$checkpoint)){
message("Saving state in ", sQuote(sprintf(control$checkpoint, iteration)),".")
s.reduced <- s
for(i in seq_along(s.reduced)) s.reduced[[i]]$model <- s.reduced[[i]]$proposal <- NULL
if(obs){
s.obs.reduced <- s.obs
for(i in seq_along(s.obs.reduced)) s.obs.reduced[[i]]$model <- s.obs.reduced[[i]]$proposal <- NULL
}
save(list=intersect(ls(), c("s.reduced", "s.obs.reduced", STATE_VARIABLES, CONTROL_VARIABLES)), file=sprintf(control$checkpoint, iteration))
rm(s.reduced)
suppressWarnings(rm(s.obs.reduced))
}
if(verbose) message("Starting unconstrained MCMC...")
z <- ergm_MCMC_sample(s, control, theta=mcmc.init, verbose=max(verbose-1,0))
if(z$status==1) stop("Number of edges in a simulated network exceeds that in the observed by a factor of more than ",floor(control$MCMLE.density.guard),". This is a strong indicator of model degeneracy or a very poor starting parameter configuration. If you are reasonably certain that neither of these is the case, increase the MCMLE.density.guard control.ergm() parameter.")
statsmatrices <- z$stats
s.returned <- z$networks
statsmatrix <- as.matrix(statsmatrices)
if(verbose){
message("Back from unconstrained MCMC.")
if(verbose>1){
message("Average statistics:")
message_print(colMeans(statsmatrix))
}
}
if(obs){
if(verbose) message("Starting constrained MCMC...")
z.obs <- ergm_MCMC_sample(s.obs, control.obs, theta=mcmc.init, verbose=max(verbose-1,0))
statsmatrices.obs <- z.obs$stats
s.obs.returned <- z.obs$networks
statsmatrix.obs <- as.matrix(statsmatrices.obs)
if(verbose){
message("Back from constrained MCMC.")
if(verbose>1){
message("Average statistics:")
message_print(colMeans(statsmatrix.obs))
}
}
}else{
statsmatrices.obs <- statsmatrix.obs <- NULL
z.obs <- NULL
}
if(sequential) {
s <- s.returned
if(obs){
s.obs <- s.obs.returned
}
}
if(!is.null(control$MCMLE.save_intermediates)){
save(list=intersect(ls(), INTERMEDIATE_VARIABLES), file=sprintf(control$MCMLE.save_intermediates, iteration))
}
esteqs <- ergm.estfun(statsmatrices, theta=mcmc.init, model=model)
esteq <- as.matrix(esteqs)
if(isTRUE(all.equal(apply(esteq,2,stats::sd), rep(0,ncol(esteq)), check.names=FALSE))&&!all(esteq==0))
stop("Unconstrained MCMC sampling did not mix at all. Optimization cannot continue.")
check_nonidentifiability(esteq, NULL, model,
tol = control$MCMLE.nonident.tol, type="statistics",
nonident_action = control$MCMLE.nonident,
nonvar_action = control$MCMLE.nonvar)
esteqs.obs <- if(obs) ergm.estfun(statsmatrices.obs, theta=mcmc.init, model=model) else NULL
esteq.obs <- if(obs) as.matrix(esteqs.obs) else NULL
if(!is.null(control$MCMC.effectiveSize)){
control$MCMC.interval <- round(max(z$final.interval/control$MCMLE.effectiveSize.interval_drop,1))
control$MCMC.burnin <- round(max(z$final.interval*16,16))
if(verbose) message("New interval = ",control$MCMC.interval,".")
if(obs){
control.obs$MCMC.interval <- round(max(z.obs$final.interval/control$MCMLE.effectiveSize.interval_drop,1))
control.obs$MCMC.burnin <- round(max(z.obs$final.interval*16,16))
if(verbose) message("New constrained interval = ",control.obs$MCMC.interval,".")
}
}
if(verbose){
message("Average estimating function values:")
message_print(if(obs) colMeans(esteq.obs)-colMeans(esteq) else -colMeans(esteq))
}
if(!estimate){
if(verbose){message("Skipping optimization routines...")}
s.returned <- lapply(s.returned, as.network)
l <- list(coefficients=mcmc.init, mc.se=rep(NA,length=length(mcmc.init)),
sample=statsmatrices, sample.obs=statsmatrices.obs,
iterations=1, MCMCtheta=mcmc.init,
loglikelihood=NA,
mle.lik=NULL,
gradient=rep(NA,length=length(mcmc.init)),
samplesize=control$MCMC.samplesize, failure=TRUE,
newnetwork = s.returned[[1]],
newnetworks = s.returned)
return(structure (l, class="ergm"))
}
if(control$MCMLE.termination=='confidence'){
estdiff <- NVL3(esteq.obs, colMeans(.), 0) - colMeans(esteq)
pprec <- diag(sqrt(control$MCMLE.MCMC.precision), nrow=length(estdiff))
Vm <- pprec%*%(cov(esteq) - NVL3(esteq.obs, cov(.), 0))%*%pprec
novar <- diag(Vm) == 0
Vm[!novar,!novar] <- as.matrix(nearPD(Vm[!novar,!novar,drop=FALSE], posd.tol=0)$mat)
iVm <- ginv(Vm)
diag(Vm)[novar] <- sqrt(.Machine$double.xmax)
d2 <- estdiff%*%iVm%*%estdiff
if(d2<2) last.adequate <- TRUE
}
if(verbose){message("Starting MCMLE Optimization...")}
if(!is.null(control$MCMLE.steplength.margin)){
steplen <- .Hummel.steplength(
if(control$MCMLE.steplength.esteq) esteq else statsmatrix[,!model$etamap$offsetmap,drop=FALSE],
if(control$MCMLE.steplength.esteq) esteq.obs else statsmatrix.obs[,!model$etamap$offsetmap,drop=FALSE],
control$MCMLE.steplength.margin, control$MCMLE.steplength, point.gamma.exp=control$MCMLE.steplength.point.exp, steplength.prev=steplen, x1.prefilter=control$MCMLE.steplength.prefilter, x2.prefilter=control$MCMLE.steplength.prefilter, precision=control$MCMLE.steplength.precision, min=control$MCMLE.steplength.min, verbose=verbose,
x2.num.max=control$MCMLE.steplength.miss.sample, parallel=control$MCMLE.steplength.parallel, steplength.maxit=control$MCMLE.steplength.maxit, control=control
)
steplen0 <-
if(control$MCMLE.termination%in%c("precision","Hummel") && control$MCMLE.steplength.margin<0 && control$MCMLE.steplength==steplen)
.Hummel.steplength(
if(control$MCMLE.steplength.esteq) esteq else statsmatrix[,!model$etamap$offsetmap,drop=FALSE],
if(control$MCMLE.steplength.esteq) esteq.obs else statsmatrix.obs[,!model$etamap$offsetmap,drop=FALSE],
0, control$MCMLE.steplength, steplength.prev=steplen, point.gamma.exp=control$MCMLE.steplength.point.exp, x1.prefilter=control$MCMLE.steplength.prefilter, x2.prefilter=control$MCMLE.steplength.prefilter, precision=control$MCMLE.steplength.precision, min=control$MCMLE.steplength.min, verbose=verbose,
x2.num.max=control$MCMLE.steplength.miss.sample, steplength.maxit=control$MCMLE.steplength.maxit,
parallel=control$MCMLE.steplength.parallel, control=control
)
else steplen
steplen.converged <- control$MCMLE.steplength==steplen0
}else{
steplen <- control$MCMLE.steplength
steplen.converged <- TRUE
}
message("Optimizing with step length ", fixed.pval(steplen, eps = control$MCMLE.steplength.min), ".")
if(control$MCMLE.steplength==steplen && !steplen.converged)
message("Note that convergence diagnostic step length is ",steplen0,".")
if(steplen.converged || is.null(control$MCMLE.steplength.margin) || iteration==control$MCMLE.maxit) calc.MCSE <- TRUE
steplen.hist <- c(steplen.hist, steplen)
v<-ergm.estimate(init=mcmc.init, model=model,
statsmatrices=statsmatrices,
statsmatrices.obs=statsmatrices.obs,
epsilon=control$epsilon,
nr.maxit=control$MCMLE.NR.maxit,
nr.reltol=control$MCMLE.NR.reltol,
calc.mcmc.se=control$MCMLE.termination == "precision" || (control$MCMC.addto.se && last.adequate) || iteration == control$MCMLE.maxit,
hessianflag=control$main.hessian,
method=control$MCMLE.method,
dampening=control$MCMLE.dampening,
dampening.min.ess=control$MCMLE.dampening.min.ess,
dampening.level=control$MCMLE.dampening.level,
metric=control$MCMLE.metric,
steplen=steplen, steplen.point.exp=control$MCMLE.steplength.point.exp,
verbose=verbose,
estimateonly=!calc.MCSE)
message("The log-likelihood improved by ", fixed.pval(v$loglikelihood, 4), ".")
coef.hist <- rbind(coef.hist, coef(v))
stats.obs.hist <- NVL3(statsmatrix.obs, rbind(stats.obs.hist, apply(.[], 2, base::mean)))
stats.hist <- rbind(stats.hist, apply(statsmatrix, 2, base::mean))
if(control$MCMLE.termination=='Hotelling'){
conv.pval <- ERRVL(try(suppressWarnings(approx.hotelling.diff.test(esteqs, esteqs.obs)$p.value)), NA)
message("Nonconvergence test p-value:", format(conv.pval), "")
if(!is.na(conv.pval) && conv.pval>=1-sqrt(1-control$MCMLE.conv.min.pval)){
if(last.adequate){
message("No nonconvergence detected twice. Stopping.")
break
}else{
message("No nonconvergence detected once; increasing sample size if not already increased.")
last.adequate <- TRUE
.boost_samplesize(control$MCMLE.last.boost, TRUE)
}
}else{
last.adequate <- FALSE
}
}else if(control$MCMLE.termination=='confidence'){
if(!is.null(estdiff.prev)){
d2.prev <- estdiff.prev%*%iVm%*%estdiff.prev
if(verbose) message("Distance from origin on tolerance region scale: ", d2, " (previously ", d2.prev, ").")
d2.not.improved <- d2.not.improved[-1]
if(d2 >= d2.prev){
d2.not.improved <- c(d2.not.improved,TRUE)
}else{
d2.not.improved <- c(d2.not.improved,FALSE)
}
}
estdiff.prev <- estdiff
if(d2<2){
IS.lw <- function(sm, etadiff){
nochg <- etadiff==0 | apply(sm, 2, function(x) max(x)==min(x))
basepred <- sm[,!nochg,drop=FALSE] %*% etadiff[!nochg]
}
lw2w <- function(lw){w<-exp(lw-max(lw)); w/sum(w)}
hotel <- try(suppressWarnings(approx.hotelling.diff.test(esteqs, esteqs.obs)), silent=TRUE)
if(inherits(hotel, "try-error")){
message("Unable to test for convergence; increasing sample size.")
.boost_samplesize(control$MCMLE.confidence.boost)
}else{
etadiff <- ergm.eta(coef(v), model$etamap) - ergm.eta(mcmc.init, model$etamap)
esteq.lw <- IS.lw(statsmatrix, etadiff)
esteq.w <- lw2w(esteq.lw)
estdiff <- -lweighted.mean(esteq, esteq.lw)
estcov <- hotel$covariance.x*sum(esteq.w^2)*length(esteq.w)
if(obs){
esteq.obs.lw <- IS.lw(statsmatrix.obs, etadiff)
esteq.obs.w <- lw2w(esteq.obs.lw)
estdiff <- estdiff + lweighted.mean(esteq.obs, esteq.obs.lw)
estcov <- estcov + hotel$covariance.y*sum(esteq.obs.w^2)*length(esteq.obs.w)
}
estdiff <- estdiff[!hotel$novar]
estcov <- estcov[!hotel$novar, !hotel$novar]
d2e <- estdiff%*%iVm[!hotel$novar, !hotel$novar]%*%estdiff
if(d2e<1){
T2 <- try(.ellipsoid_mahalanobis(estdiff, estcov, iVm[!hotel$novar, !hotel$novar]), silent=TRUE)
if(inherits(T2, "try-error")){
message("Unable to test for convergence; increasing sample size.")
.boost_samplesize(control$MCMLE.confidence.boost)
}else{
nonconv.pval <- .ptsq(T2, hotel$parameter["param"], hotel$parameter["df"], lower.tail=FALSE)
if(verbose) message("Test statistic: T^2 = ",T2,", with ",
hotel$parameter["param"], " free parameters and ",hotel$parameter["df"], " degrees of freedom.")
message("Convergence test p-value: ", fixed.pval(nonconv.pval, 4), ". ", appendLF=FALSE)
if(nonconv.pval < 1-control$MCMLE.confidence){
message("Converged with ",control$MCMLE.confidence*100,"% confidence.")
break
}else{
message("Not converged with ",control$MCMLE.confidence*100,"% confidence; increasing sample size.")
critval <- .qtsq(control$MCMLE.confidence, hotel$parameter["param"], hotel$parameter["df"])
if(verbose) message(control$MCMLE.confidence*100,"% confidence critical value = ",critval,".")
boost <- min((critval/T2),control$MCMLE.confidence.boost)
.boost_samplesize(boost)
}
}
}
}
}
if(d2>=2 || d2e>1){
message("Estimating equations are not within tolerance region.")
if(sum(d2.not.improved) > control$MCMLE.confidence.boost.threshold){
message("Estimating equations did not move closer to tolerance region more than ", control$MCMLE.confidence.boost.threshold," time(s) in ", control$MCMLE.confidence.boost.lag, " steps; increasing sample size.")
.boost_samplesize(control$MCMLE.confidence.boost)
d2.not.improved[] <- FALSE
}
}
}else if(!steplen.converged){
last.adequate <- FALSE
.boost_samplesize(1, TRUE)
}else if(control$MCMLE.termination == "precision"){
prec.loss <- (sqrt(diag(v$mc.cov+v$covar))-sqrt(diag(v$covar)))/sqrt(diag(v$mc.cov+v$covar))
if(verbose){
message("Standard Error:")
message_print(sqrt(diag(v$covar)))
message("MC SE:")
message_print(sqrt(diag(v$mc.cov)))
message("Linear scale precision loss due to MC estimation of the likelihood:")
message_print(prec.loss)
}
if(sqrt(mean(prec.loss^2, na.rm=TRUE)) <= control$MCMLE.MCMC.precision){
if(last.adequate){
message("Precision adequate twice. Stopping.")
break
}else{
message("Precision adequate. Performing one more iteration.")
last.adequate <- TRUE
}
}else{
last.adequate <- FALSE
prec.scl <- max(sqrt(mean(prec.loss^2, na.rm=TRUE))/control$MCMLE.MCMC.precision, 1)
if (!is.null(control$MCMC.effectiveSize)) {
control$MCMC.effectiveSize <- round(control$MCMC.effectiveSize * prec.scl)
if(control$MCMC.effectiveSize/control$MCMC.samplesize>control$MCMLE.MCMC.max.ESS.frac) control$MCMC.samplesize <- control$MCMC.effectiveSize/control$MCMLE.MCMC.max.ESS.frac
message("Increasing target MCMC sample size to ", control$MCMC.samplesize, ", ESS to",control$MCMC.effectiveSize,".")
} else {
control$MCMC.samplesize <- round(control$MCMC.samplesize * prec.scl)
control$MCMC.burnin <- round(control$MCMC.burnin * prec.scl)
message("Increasing MCMC sample size to ", control$MCMC.samplesize, ", burn-in to",control$MCMC.burnin,".")
}
if(obs){
if (!is.null(control.obs$MCMC.effectiveSize)) {
control.obs$MCMC.effectiveSize <- round(control.obs$MCMC.effectiveSize * prec.scl)
if(control.obs$MCMC.effectiveSize/control.obs$MCMC.samplesize>control.obs$MCMLE.MCMC.max.ESS.frac) control.obs$MCMC.samplesize <- control.obs$MCMC.effectiveSize/control.obs$MCMLE.MCMC.max.ESS.frac
message("Increasing target constrained MCMC sample size to ", control.obs$MCMC.samplesize, ", ESS to",control.obs$MCMC.effectiveSize,".")
} else {
control.obs$MCMC.samplesize <- round(control.obs$MCMC.samplesize * prec.scl)
control.obs$MCMC.burnin <- round(control.obs$MCMC.burnin * prec.scl)
message("Increasing constrained MCMC sample size to ", control.obs$MCMC.samplesize, ", burn-in to",control.obs$MCMC.burnin,".")
}
}
}
}else if(control$MCMLE.termination=='Hummel'){
if(last.adequate){
message("Step length converged twice. Stopping.")
break
}else{
message("Step length converged once. Increasing MCMC sample size.")
last.adequate <- TRUE
.boost_samplesize(control$MCMLE.last.boost, TRUE)
}
}
if ((length(steplen.hist) > 2) && sum(tail(steplen.hist,2)) < 2*control$MCMLE.steplength.min) {
stop("MCMLE estimation stuck. There may be excessive correlation between model terms, suggesting a poor model for the observed data. If target.stats are specified, try increasing SAN parameters.")
}
if (iteration == control$MCMLE.maxit) {
message("MCMLE estimation did not converge after ", control$MCMLE.maxit, " iterations. The estimated coefficients may not be accurate. Estimation may be resumed by passing the coefficients as initial values; see 'init' under ?control.ergm for details.")
}
mcmc.init <- coef(v)
}
message("Finished MCMLE.")
v$sample <- statsmatrices
if(obs) v$sample.obs <- statsmatrices.obs
nws.returned <- lapply(s.returned, as.network)
v$network <- nw.orig
v$newnetworks <- nws.returned
v$newnetwork <- nws.returned[[1]]
v$coef.init <- init
v$est.cov <- v$mc.cov
v$mc.cov <- NULL
v$coef.hist <- coef.hist
v$stats.hist <- stats.hist
v$stats.obs.hist <- stats.obs.hist
v$steplen.hist <- steplen.hist
v$iterations <- iteration
if(obs) for(name in OBS_MCMC_CONTROLS) control[[paste0("obs.", name)]] <- control.obs[[name]]
v$control <- control
v$etamap <- model$etamap
v
}
.ellipsoid_mahalanobis <- function(y, W, U){
y <- c(y)
if(y%*%U%*%y>=1) stop("Point is not in the interior of the ellipsoid.")
I <- diag(length(y))
WU <- W%*%U
x <- function(l) c(solve(I+l*WU, y))
zerofn <- function(l) ERRVL(try({x <- x(l); c(x%*%U%*%x)-1}, silent=TRUE), +Inf)
eig <- Re(eigen(WU, only.values=TRUE)$values)
lmin <- -1/max(eig)
l <- uniroot(zerofn, lower=lmin, upper=0, tol=sqrt(.Machine$double.xmin))$root
x <- x(l)
(y-x)%*%solve(W)%*%(y-x)
} |
insert_test <- function(selected_shaker, shaker_name) {
context(str_glue("salt_insert: {shaker_name}"))
if (is.character(selected_shaker)) {
shaker_contents <- selected_shaker
} else {
shaker_contents <- inspect_shaker(selected_shaker)
}
test_that(str_glue("insert {shaker_name}"), {
insert_res <- map(battery, function(x) {
salt_insert(x, p = 0.5, insertions = selected_shaker)
})
imap(insert_res, function(x, n) expect_is(x, class = "character", info = n))
walk2(insert_res, battery_lengths, expect_length)
imap(insert_res, function(x, n) {
expect_true(any(map_lgl(x, function(y) {
any(str_detect(y, fixed(shaker_contents)))
})), info = str_glue("shaker name: {shaker_name} - battery test: {n}"))
})
})
test_that(str_glue("overload insert {shaker_name}"), {
walk(battery, function(b) {
expect_warning(salt_insert(b, insertions = selected_shaker, p = 0.5, n = 30))
})
})
test_that("error on zero-length input", {
expect_error(salt_insert(zero_length, insertions = selected_shaker))
})
}
imap(c(shaker, list("literal" = literal_salts)), insert_test) |
write.tree <- function (tree=NULL, file=NULL) {
if (is.null(tree))
stop(simpleError("Please provide a value for tree to write.tree()"))
if (is(tree, "BIOM"))
tree <- rbiom::phylogeny(tree)
if (!is(tree, "phylo"))
stop(simpleError("Provided tree is not a 'phylo' or 'BIOM' class object."))
rootNode <- setdiff(tree$edge[,1], tree$edge[,2])
parentAt <- aggregate(1:nrow(tree$edge), by=list(tree$edge[,1]), c, simplify=FALSE)
parentAt <- setNames(lapply(parentAt[,2], unlist), parentAt[,1])
fx <- function (root=NULL) {
nodes <- parentAt[[as.character(root)]]
if (length(nodes) == 0) {
nodeLabel <- tree$tip.label[root]
if (any(grepl(" ", nodeLabel, fixed=TRUE))) {
if (any(grepl("_", nodeLabel, fixed=TRUE))) {
nodeLabel <- paste0("'", nodeLabel, "'")
} else {
nodeLabel <- gsub(" ", "_", nodeLabel)
}
}
return (nodeLabel)
}
children <- tree$edge[nodes, 2]
children <- sapply(children, fx)
if (!is.null(tree$edge.length))
children <- paste(sep=":", children, tree$edge.length[nodes])
sprintf("(%s)", paste(collapse=",", children))
}
newick <- paste0(fx(rootNode), ";")
if (!is.null(file))
return (writeLines(text=newick, con=file, sep=""))
return (newick)
} |
compHclust <- function(x,xhc) {
if ((!is.matrix(x))|(!is.numeric(x))) {
stop("'x' must be a numeric matrix")
}
if (any(is.na(as.vector(x)))) {
stop("'x' has missing values, please impute missing values")
}
if (class(xhc)!="hclust") {
stop("'xhc' must be of class 'hclust'")
}
if (ncol(x)!=length(xhc$order)) {
stop("'xhc' must be a clustering of the columns of 'x'")
}
x.hat <- as.matrix(x)%*%A.chc(xhc)
return(list("x.prime"=x-x.hat,"gene.imp"=RGI.chc(x,x.hat)))
} |
cplex_dir <- normalizePath(Sys.getenv("CPLEX_HOME"))
test_that("virgo_solver works on MWCS", {
if (!file.exists(cplex_dir)) {
skip("No CPLEX available")
}
solver <- virgo_solver(cplex_dir=cplex_dir)
solution <- solve_mwcsp(solver, mwcs_small_instance)
expect_equal(solution$weight, 3)
})
test_that("virgo_solver works on GMWCS", {
if (!file.exists(cplex_dir)) {
skip("No CPLEX available")
}
solver <- virgo_solver(cplex_dir=cplex_dir)
solution <- solve_mwcsp(solver, gmwcs_small_instance)
expect_equal(solution$weight, 11)
})
test_that("virgo_solver works on SGMWCS", {
if (!file.exists(cplex_dir)) {
skip("No CPLEX available")
}
solver <- virgo_solver(cplex_dir=cplex_dir)
solution <- solve_mwcsp(solver, sgmwcs_small_instance)
expect_equal(solution$weight, 51)
})
test_that("heuristic virgo_solver works on MWCS", {
solver <- virgo_solver(cplex_dir=NULL)
solution <- solve_mwcsp(solver, mwcs_small_instance)
expect_equal(solution$weight, 3)
})
test_that("heuristic virgo_solver works on GMWCS", {
solver <- virgo_solver(cplex_dir=NULL)
solution <- solve_mwcsp(solver, gmwcs_small_instance)
expect_gt(solution$weight, 0)
expect_lte(solution$weight, 11)
})
test_that("heuristic virgo_solver works on SGMWCS", {
solver <- virgo_solver(cplex_dir=NULL)
solution <- solve_mwcsp(solver, sgmwcs_small_instance)
expect_equal(solution$weight, 51)
})
test_that("virgo solver does not supported repeated negative signals", {
sgmwcs_edges <- data.frame(from = c(1, 2, 2, 3, 4, 5, 1),
to = c(2, 3, 4, 4, 6, 6, 5),
signal = c("S6", "S2", "S7", "S2", "S8", "S9", "S10"))
sgmwcs_instance <- igraph::graph_from_data_frame(sgmwcs_edges,
directed = FALSE)
igraph::V(sgmwcs_instance)$signal <- c("S1", "S3", "S4", "S5", "S1", "S1")
sgmwcs_instance$signals <- stats::setNames(c(7.0, -20.0, 40.0, 15.0, 8.0, 3.0, -7.0, -10.0,
-2.0, -15.3, 1.0),
paste0("S", 1:11))
solver <- virgo_solver(cplex_dir=NULL)
expect_error(solution <- solve_mwcsp(solver, sgmwcs_instance))
})
test_that("heuristic virgo_solver works on SGMWCS", {
solver <- virgo_solver(cplex_dir=NULL)
si <- sgmwcs_small_instance
si$signals <- c(si$signals, "neg"=-1)
solution <- solve_mwcsp(solver, si)
expect_true(!is.null(solution))
}) |
context("gppm-easychecks")
test_that("wrong variable names", {
tmpData <- myDataLong
names(tmpData)[3] <- 't '
expect_error(gpModel <- gppm('b0+b1*t','(t==t
names(tmpData)[3] <- 't!
expect_error(gpModel <- gppm('b0+b1*t','(t==t
names(tmpData)[3] <- 'Ha ha'
expect_error(gpModel <- gppm('b0+b1*t','(t==t
names(tmpData)[3] <- '3D5'
expect_error(gpModel <- gppm('b0+b1*t','(t==t
})
test_that("ID not in", {
expect_error(gpModel <- gppm('b0+b1*t','(t==t
})
test_that("DV not in", {
expect_error(gpModel <- gppm('b0+b1*t','(t==t
})
context("gppm-meanCovariance")
test_that("linear regression", {
gpModel <- gppm('b0+b1*t','(t==t
mFormula <- getIntern(gpModel,'parsedmFormula')
cFormula <- getIntern(gpModel,'parsedcFormula')
expect_equal(mFormula,"b0+b1*X[i,j,1]")
expect_equal(cFormula,"(X[i,j,1]==X[i,k,1])*sigma")
myModelSpec <- summary(gpModel)$modelSpecification
expect_equal(myModelSpec$meanFormula,"b0+b1*t")
expect_equal(myModelSpec$covFormula,"(t==t
expect_equal(myModelSpec$params,c('b0','b1','sigma'))
expect_equal(myModelSpec$nPars,3)
expect_equal(myModelSpec$preds,c('t'))
expect_equal(myModelSpec$nPreds,1)
})
test_that("Bayesian Linear regression", {
gpModel <- gppm('0','(t*t
mFormula <- getIntern(gpModel,'parsedmFormula')
cFormula <- getIntern(gpModel,'parsedcFormula')
expect_equal(mFormula,"0")
expect_equal(cFormula,"(X[i,j,1]*X[i,k,1]+1)*sigmab+(X[i,j,1]==X[i,k,1])*sigma")
})
test_that("squared exponential", {
gpModel <- gppm('c','sigmaf*exp(-(t-t
mFormula <- getIntern(gpModel,'parsedmFormula')
cFormula <- getIntern(gpModel,'parsedcFormula')
expect_equal(mFormula,"c")
expect_equal(cFormula,"sigmaf*exp(-(X[i,j,1]-X[i,k,1])^2/rho)+(X[i,j,1]==X[i,k,1])*sigma")
})
test_that("hard names", {
tmp <- myData
names(tmp) <- c('ID45','t83','y13')
gpModel <- gppm('b0+b1*t83','(t83==t83
mFormula <- getIntern(gpModel,'parsedmFormula')
cFormula <- getIntern(gpModel,'parsedcFormula')
expect_equal(mFormula,"b0+b1*X[i,j,1]")
expect_equal(cFormula,"(X[i,j,1]==X[i,k,1])*sigma")
}) |
plot.ECFOCF <- function(x, ..., result="CF", category=NA, period=1) {
p3p <- list(...)
result <- tolower(result)
if (result=="data") {
do.call(getFromNamespace("plot.TableECFOCF", ns="phenology"), modifyList(list(x=x$data,
period=period,
cex.points=4,
pch=19,
col="black",
cex.axis=0.8,
cex.labels=0.5,
col.labels="red",
show.labels=FALSE,
show.0=FALSE,
pch.0=4,
cex.0=0.5,
col.0="blue",
show.scale = TRUE), p3p))
}
if (result=="ecfocf0") {
if (all(is.na(category)) | (all(category == ""))) {
do.call(getFromNamespace("plot.TableECFOCF", ns="phenology"), modifyList(list(x=x$ECFOCF_0,
period=period,
cex.points=4,
pch=19,
col="black",
cex.axis=0.8,
cex.labels=0.5,
col.labels="red",
show.labels=FALSE,
show.0=FALSE,
pch.0=4,
cex.0=0.5,
col.0="blue",
show.scale = TRUE), p3p))
} else {
do.call(getFromNamespace("plot.TableECFOCF", ns="phenology"),
modifyList(list(x=x$ECFOCF_0_categories[[as.numeric(category)]],
period=period,
cex.points=4,
pch=19,
col="black",
cex.axis=0.8,
cex.labels=0.5,
col.labels="red",
show.labels=FALSE,
show.0=FALSE,
pch.0=4,
cex.0=0.5,
col.0="blue",
show.scale = TRUE), p3p))
}
}
if (result=="ecfocf") {
if (all(is.na(category)) | (all(category == ""))) {
do.call(getFromNamespace("plot.TableECFOCF", ns="phenology"),
modifyList(list(x=x$ECFOCF,
period=period,
cex.points=4,
pch=19,
col="black",
cex.axis=0.8,
cex.labels=0.5,
col.labels="red",
show.labels=FALSE,
show.0=FALSE,
pch.0=4,
cex.0=0.5,
col.0="blue",
show.scale = TRUE), p3p))
} else {
do.call(getFromNamespace("plot.TableECFOCF", ns="phenology"),
modifyList(list(x=x$ECFOCF_categories[[as.numeric(category)]],
period=period,
cex.points=4,
pch=19,
col="black",
cex.axis=0.8,
cex.labels=0.5,
col.labels="red",
show.labels=FALSE,
show.0=FALSE,
pch.0=4,
cex.0=0.5,
col.0="blue",
show.scale = TRUE), p3p))
}
}
if (result=="cf") {
if (all(is.na(category)) | (all(category == ""))) {
cf <- x$CF
main="Clutch Frequency: All categories"
} else {
cf <- x$CF_categories[[as.numeric(category)]]
main=paste0("Clutch Frequency: Category ", as.character(category))
}
do.call(plot, modifyList(list(x=1:length(cf),
xlab="Clutch Frequency",
ylab="Density",
main=main,
y=cf, type="h", xaxt="n"), p3p)[c("x", "y", "type", "col",
"main", "cex.axis", "bty", "las",
"xlab", "ylab", "xaxt", "xlim", "ylim")])
axis(side = 1, at=1:length(cf), cex.axis=unlist(modifyList(list(cex.axis=0.8), p3p)[c("cex.axis")]))
}
if ((result=="ocf") | (result=="dataocf")) {
if (result=="ocf") {
ylab="Density"
if (all(is.na(category)) | (all(category == ""))) {
ecfocf <- x$ECFOCF[, , period]
main="Observed Clutch Frequency: All categories"
} else {
ecfocf <- x$ECFOCF_categories[[as.numeric(category)]][, , period]
main=paste0("Observed Clutch Frequency: Category ", as.character(category))
}
} else {
ylab="Frequency"
ecfocf <- x$data[, , period]
main="Observed OCF"
}
ocf <- rowSums(ecfocf, na.rm = TRUE)
do.call(plot, modifyList(list(x=0:(length(ocf)-1),
xlab="Observed Clutch Frequency",
ylab=ylab,
main=main,
y=ocf, type="h"), p3p)[c("x", "y", "type", "col",
"main", "cex.axis", "bty", "las",
"xlab", "ylab", "xlim", "ylim",
"xaxt", "yaxt", "axes")])
}
if ((result=="ecf") | (result=="dataecf")) {
if (result=="ecf") {
ylab="Density"
if (all(is.na(category)) | (all(category == ""))) {
ecfocf <- x$ECFOCF[, , period]
main="Estimated Clutch Frequency: All categories"
} else {
ecfocf <- x$ECFOCF_categories[[as.numeric(category)]][, , period]
main=paste0("Estimated Clutch Frequency: Category ", as.character(category))
}
} else {
ylab="Frequency"
ecfocf <- x$data[, , period]
main="Observed ECF"
}
ecf <- colSums(ecfocf, na.rm = TRUE)
do.call(plot, modifyList(list(x=0:(length(ecf)-1),
xlab="Estimated Clutch Frequency",
ylab=ylab,
main=main,
y=ecf, type="h"), p3p)[c("x", "y", "type", "col",
"main", "cex.axis", "bty", "las",
"xlab", "ylab", "xlim", "ylim",
"xaxt", "yaxt", "axes")])
}
if (result=="period") {
if (all(is.na(category)) | (all(category == ""))) {
y <- x$period
main="All categories"
} else {
y <- x$period_categories[[as.numeric(category)]]
main=paste("Category", category)
}
perr <- list(x=0:(length(y)-1),
y=y,
las=1, bty="n",
ylab="Probability of nesting", xlab="Period",
main=main)
perr <- modifyList(perr, p3p)
do.call(plot, perr)
}
if (result=="prob") {
if (is.null(x$SE_df)) {
warning("The estimate of standard error for capture probability is not available")
} else {
if (all(is.na(category)) | (all(category == ""))) {
category <- ""
cl <- sapply(X = rownames(x$SE_df), function(x) {
grepl("prob", x)
})
} else {
category <- as.character(category)
cl <- sapply(X = rownames(x$SE_df), function(x) {
grepl(paste0("prob", category, "\\."), x) |
grepl(paste0("a", category), x) |
((grepl(paste0("prob\\."), x)) & (category == "1") & !grepl(paste0("a[^", category, "]"), x))
})
}
perr <- list(x=1:sum(cl),
y=x$SE_df[cl, "Estimate"],
y.minus=x$SE_df[cl, "2.5 %"],
y.plus = x$SE_df[cl, "97.5 %"],
xlim=c(0.5, sum(cl)+0.5), ylim=c(0,1),
las=1, bty="n", xaxt="n",
ylab="Probability of capture", xlab="Categories",
main="SE using delta method")
perr <- modifyList(perr, p3p)
do.call(plot_errbar, perr)
if (is.null(p3p$xaxt)) p3p$xaxt <- "r"
if (p3p$xaxt != "n") {
segments(x0=1:sum(cl),
y0=-0.1, y1=-0.15, xpd=TRUE)
cex <- p3p[["cex.axis"]]
y <- p3p[["y.axis"]]
if (is.null(cex)) cex <- 1
if (is.null(y)) y <- -0.3
do.call(text, modifyList(list(x = 1:sum(cl),
y=y,
cex=cex,
labels = rownames(x$SE_df)[cl],
xpd=TRUE), p3p[c("srt", "labels")]))
}
}
}
} |
library(tinytest)
library(ggiraph)
library(ggplot2)
library(xml2)
source("setup.R")
{
eval(test_geom_layer, envir = list(name = "geom_jitter_interactive"))
} |
library("zoo")
library("chron")
Sys.setenv(TZ = "GMT")
Lines <- "
time latitude longitude altitude distance heartrate
1277648884 0.304048 -0.793819 260 0.000000 94
1277648885 0.304056 -0.793772 262 4.307615 95
1277648894 0.304075 -0.793544 263 25.237911 103
1277648902 0.304064 -0.793387 256 40.042988 115
"
z <- read.zoo(text = Lines, header = TRUE)
z
DF <- structure(list(
Time = structure(1:5, .Label = c("7:10:03 AM", "7:10:36 AM",
"7:11:07 AM", "7:11:48 AM", "7:12:25 AM"), class = "factor"),
Bid = c(6118.5, 6118.5, 6119.5, 6119, 6119),
Offer = c(6119.5, 6119.5, 6119.5, 6120, 6119.5)),
.Names = c("Time", "Bid", "Offer"), row.names = c(NA, -5L),
class = "data.frame")
DF
z <- read.zoo(DF, FUN = function(x)
times(as.chron(paste("1970-01-01", x), format = "%Y-%m-%d %H:%M:%S %p")))
z
Lines <- "
Date;Time;Close
01/09/2009;10:00;56567
01/09/2009;10:05;56463
01/09/2009;10:10;56370
01/09/2009;16:45;55771
01/09/2009;16:50;55823
01/09/2009;16:55;55814
02/09/2009;10:00;55626
02/09/2009;10:05;55723
02/09/2009;10:10;55659
02/09/2009;16:45;55742
02/09/2009;16:50;55717
02/09/2009;16:55;55385
"
f <- function(x) times(paste(x, 0, sep = ":"))
z <- read.zoo(text = Lines, header = TRUE, sep = ";",
split = 1, index = 2, FUN = f)
colnames(z) <- sub("X(..).(..).(....)", "\\3-\\2-\\1", colnames(z))
z
Lines <- "
Date Time O H L C
1/2/2005 17:05 1.3546 1.3553 1.3546 1.35495
1/2/2005 17:10 1.3553 1.3556 1.3549 1.35525
1/2/2005 17:15 1.3556 1.35565 1.35515 1.3553
1/2/2005 17:25 1.355 1.3556 1.355 1.3555
1/2/2005 17:30 1.3556 1.3564 1.35535 1.3563
"
f <- function(d, t) as.chron(paste(as.Date(chron(d)), t))
z <- read.zoo(text = Lines, header = TRUE, index = 1:2, FUN = f)
z
Lines <-
" views number timestamp day time
1 views 910401 1246192687 Sun 6/28/2009 12:38
2 views 921537 1246278917 Mon 6/29/2009 12:35
3 views 934280 1246365403 Tue 6/30/2009 12:36
4 views 986463 1246888699 Mon 7/6/2009 13:58
5 views 995002 1246970243 Tue 7/7/2009 12:37
6 views 1005211 1247079398 Wed 7/8/2009 18:56
7 views 1011144 1247135553 Thu 7/9/2009 10:32
8 views 1026765 1247308591 Sat 7/11/2009 10:36
9 views 1036856 1247436951 Sun 7/12/2009 22:15
10 views 1040909 1247481564 Mon 7/13/2009 10:39
11 views 1057337 1247568387 Tue 7/14/2009 10:46
12 views 1066999 1247665787 Wed 7/15/2009 13:49
13 views 1077726 1247778752 Thu 7/16/2009 21:12
14 views 1083059 1247845413 Fri 7/17/2009 15:43
15 views 1083059 1247845824 Fri 7/17/2009 18:45
16 views 1089529 1247914194 Sat 7/18/2009 10:49
"
cl <- c("NULL", "numeric", "character")[c(1, 1, 2, 2, 1, 3, 1)]
cn <- c(NA, NA, "views", "number", NA, NA, NA)
z <- read.zoo(text = Lines, skip = 1, col.names = cn, colClasses = cl,
index = 3, format = "%m/%d/%Y",
aggregate = function(x) tail(x, 1))
z
(z45 <- z[format(time(z), "%w") %in% 4:5,])
z45[!duplicated(format(time(z45), "%U"), fromLast = TRUE), ]
g <- seq(start(z), end(z), by = "day")
z.filled <- na.locf(z, xout = g)
z.filled[format(time(z.filled), "%w") == "5", ]
Lines <- "
Date,Time,Open,High,Low,Close,Up,Down
05.02.2001,00:30,421.20,421.20,421.20,421.20,11,0
05.02.2001,01:30,421.20,421.40,421.20,421.40,7,0
05.02.2001,02:00,421.30,421.30,421.30,421.30,0,5"
f <- function(d, t) chron(d, paste(t, "00", sep = ":"),
format = c("m.d.y", "h:m:s"))
z <- read.zoo(text = Lines, sep = ",", header = TRUE,
index = 1:2, FUN = f)
z
f2 <- function(d, t) as.chron(paste(d, t), format = "%d.%m.%Y %H:%M")
z2 <- read.zoo(text = Lines, sep = ",", header = TRUE,
index = 1:2, FUN = f2)
z2
z3 <- read.zoo(text = Lines, sep = ",", header = TRUE,
index = 1:2, tz = "", format = "%d.%m.%Y %H:%M")
z3
Lines <- "Date Time V2 V3 V4 V5
2010-10-15 13:43:54 73.8 73.8 73.8 73.8
2010-10-15 13:44:15 73.8 73.8 73.8 73.8
2010-10-15 13:45:51 73.8 73.8 73.8 73.8
2010-10-15 13:46:21 73.8 73.8 73.8 73.8
2010-10-15 13:47:27 73.8 73.8 73.8 73.8
2010-10-15 13:47:54 73.8 73.8 73.8 73.8
2010-10-15 13:49:51 73.7 73.7 73.7 73.7
"
z <- read.zoo(text = Lines, header = TRUE, index = 1:2, tz = "")
z
Lines <- "
13/10/2010 A 23
13/10/2010 B 12
13/10/2010 C 124
14/10/2010 A 43
14/10/2010 B 54
14/10/2010 C 65
15/10/2010 A 43
15/10/2010 B N.A.
15/10/2010 C 65
"
z <- read.zoo(text = Lines, na.strings = "N.A.",
format = "%d/%m/%Y", split = 2)
z
Lines <- '
"","Fish_ID","Date","R2sqrt"
"1",1646,2006-08-18 08:48:59,0
"2",1646,2006-08-18 09:53:20,100
'
z <- read.zoo(text = Lines, header = TRUE, sep = ",",
colClasses = c("NULL", "NULL", "character", "numeric"),
FUN = as.chron)
z
z2 <- read.zoo(text = Lines, header = TRUE, sep = ",",
colClasses = c("NULL", "NULL", "character", "numeric"),
tz = "")
z2
Lines <-
" iteration Datetime VIC1 NSW1 SA1 QLD1
1 1 2011-01-01 00:30 5482.09 7670.81 2316.22 5465.13
2 1 2011-01-01 01:00 5178.33 7474.04 2130.30 5218.61
3 1 2011-01-01 01:30 4975.51 7163.73 2042.39 5058.19
4 1 2011-01-01 02:00 5295.36 6850.14 1940.19 4897.96
5 1 2011-01-01 02:30 5042.64 6587.94 1836.19 4749.05
6 1 2011-01-01 03:00 4799.89 6388.51 1786.32 4672.92
"
z <- read.zoo(text = Lines, skip = 1, index = 3:4,
FUN = paste, FUN2 = as.chron)
z
z2 <- read.zoo(text = Lines, skip = 1, index = 3:4, tz = "")
z2
DF <- structure(list(
Date = structure(c(14609, 14638, 14640, 14666, 14668, 14699,
14729, 14757, 14759, 14760), class = "Date"),
A = c(4.9, 5.1, 5, 4.8, 4.7, 5.3, 5.2, 5.4, NA, 4.6),
B = c(18.4, 17.7, NA, NA, 18.3, 19.4, 19.7, NA, NA, 18.1),
C = c(32.6, NA, 32.8, NA, 33.7, 32.4, 33.6, NA, 34.5, NA),
D = c(77, NA, 78.7, NA, 79, 77.8, 79, 81.7, NA, NA)),
.Names = c("Date", "A", "B", "C", "D"), row.names = c(NA, -10L),
class = "data.frame")
DF
z <- read.zoo(DF)
na.locf(z)[!duplicated(as.yearmon(time(z)), fromLast = TRUE)]
Lines <- "
2009-10-07 0.009378
2009-10-19 0.014790
2009-10-23 -0.005946
2009-10-23 0.009096
2009-11-08 0.004189
2009-11-10 -0.004592
2009-11-17 0.009397
2009-11-24 0.003411
2009-12-02 0.003300
2010-01-15 0.010873
2010-01-20 0.010712
2010-01-20 0.022237
"
z <- read.zoo(text = Lines, aggregate = function(x) tail(x, 1))
z
Lines <- "
timestamp,time-step-index,value
2009-11-23 15:58:21,23301,800
2009-11-23 15:58:29,23309,950
"
z <- read.zoo(text = Lines, header = TRUE, sep = ",", tz = "")
z
z2 <- read.zoo(text = Lines, header = TRUE, sep = ",", FUN = as.chron)
z2
Lines <- "
Date Time Value
01/23/2000 10:12:15 12.12
01/24/2000 11:10:00 15.00
"
z <- read.zoo(text = Lines, header = TRUE, index = 1:2, FUN = chron)
z
Lines <- "
Year Qtr1 Qtr2 Qtr3 Qtr4
1992 566 443 329 341
1993 344 212 133 112
1994 252 252 199 207
"
za <- read.zoo(text = Lines, header = TRUE)
za
zq <- zooreg(as.vector(t(za)), start = yearqtr(start(za)), freq = 4)
zq |
expandYearlyCosts <- function(costdb, startcolumn, endcolumn)
{
if(!("Cost_ID" %in% colnames(costdb)))
{
stop("The 'invacost' object does not seem to be the invacost database (lacks cost_ID column)")
}
if(!(startcolumn %in% colnames(costdb)))
{
stop("The 'startcolumn' does not exist in the invacost database, please check spelling.")
}
if(!(endcolumn %in% colnames(costdb)))
{
stop("The 'endcolumn' does not exist in the invacost database, please check spelling.")
}
if(!(sum(is.na(costdb[,startcolumn]))==0))
{
stop(paste("The 'startcolumn' is missing values for", sum(is.na(costdb[,startcolumn])),"rows.
A pre-filled start column should be available in 'Probable_starting_year_adjusted' (see the help file)."))
}
if(!(sum(is.na(costdb[,endcolumn]))==0))
{
stop(paste("The 'endcolumn' is missing values for", sum(is.na(costdb[,endcolumn])),"rows.
A pre-filled end column should be available in 'Probable_ending_year_adjusted' (see the help file)."))
}
return(
dplyr::bind_rows(
lapply(costdb$Cost_ID, function(x, costdb.,
start,
end) {
years <- costdb.[which(costdb.$Cost_ID == x), start]:
costdb.[which(costdb.$Cost_ID == x), end]
return(data.frame(Impact_year = years,
costdb.[which(costdb.$Cost_ID == x), ][
rep(seq_len(nrow(costdb.[costdb.$Cost_ID == x, ])),
each = length(years)), ]))
}, costdb. = costdb, start = startcolumn, end = endcolumn)
)
)
} |
variance_ratio <- function(df, time.var,
species.var,
abundance.var,
bootnumber,
replicate.var = NA,
average.replicates = TRUE,
level = 0.95, li, ui) {
if ((!missing(li) | !missing(ui))) {
warning("argument li and ui are deprecated; please use level instead.",
call. = FALSE)
}
check_numeric(df, time.var, abundance.var)
if (is.na(replicate.var)) {
check_single_onerep(df, time.var, species.var)
VR <- variance_ratio_longformdata(df, time.var, species.var, abundance.var)
nullval <- cyclic_shift(df, time.var = time.var,
species.var = species.var,
abundance.var = abundance.var,
FUN = variance_ratio_matrixdata,
bootnumber = bootnumber)
nullout <- confint(nullval)
output <- cbind(nullout, VR)
} else {
df <- droplevels(df)
check_single(df, time.var, species.var, replicate.var)
if (average.replicates == TRUE) {
check_multispp(df, species.var, replicate.var)
df <- df[order(df[[replicate.var]]),]
X <- split(df, df[replicate.var])
VR <- mean(unlist(lapply(X, FUN = variance_ratio_longformdata, time.var, species.var, abundance.var)))
nullval <- cyclic_shift(df = df, time.var = time.var,
species.var = species.var,
abundance.var = abundance.var,
replicate.var = replicate.var,
FUN = variance_ratio_matrixdata,
bootnumber = bootnumber)
nullout <- confint(nullval)
output <- cbind(nullout, VR)
} else {
check_multispp(df, species.var, replicate.var)
df <- df[order(df[[replicate.var]]),]
X <- split(df, df[replicate.var])
cyclic_shift_nofun <- function(f = variance_ratio_matrixdata){
function(...) {
cyclic_shift(FUN = f, ...)
}
}
null_list <- lapply(X = X, FUN = cyclic_shift_nofun(),
time.var = time.var,
species.var = species.var,
abundance.var = abundance.var,
replicate.var = NA,
bootnumber = bootnumber)
null_intervals <- lapply(null_list, confint)
repnames <- lapply(names(null_intervals), as.data.frame)
nullout <- do.call("rbind", Map(cbind, repnames, null_intervals))
names(nullout)[1] <- replicate.var
VR_list <- lapply(X, FUN = variance_ratio_longformdata,
time.var, species.var, abundance.var)
VRnames <- lapply(names(VR_list), as.data.frame)
VR_df <- lapply(VR_list, as.data.frame)
VRout <- do.call("rbind", Map(cbind, VRnames, VR_df))
names(VRout) <- c(replicate.var, "VR")
output <- merge(nullout, VRout, by = replicate.var)
}
}
row.names(output) <- NULL
return(output)
}
variance_ratio_matrixdata <- function(comdat){
check_sppvar(comdat)
all.cov <- stats::cov(comdat, use = "pairwise.complete.obs")
col.var <- apply(comdat, 2, stats::var)
com.var <- sum(all.cov)
pop.var <- sum(col.var)
var.ratio <- com.var/pop.var
return(var.ratio)
}
variance_ratio_longformdata <- function(df, time.var, species.var, abundance.var){
com.use <- transpose_community(df, time.var, species.var, abundance.var)
var.ratio <- variance_ratio_matrixdata(com.use)
return(var.ratio)
} |
above_percent <- function(data, targets_above = c(140, 180, 250)){
x = target_val = id = NULL
rm(list = c("id", "target_val", "x"))
data = check_data_columns(data)
is_vector = attr(data, "is_vector")
targets_above = as.double(targets_above)
out = lapply(
targets_above,
function(target_val) {
data = data %>%
dplyr::group_by(id) %>%
dplyr::summarise(x = mean(gl > target_val, na.rm = TRUE) * 100) %>%
dplyr::mutate(target_val = paste0("above_", target_val))
data
})
out = dplyr::bind_rows(out)
out = tidyr::spread(data = out, key = target_val, value = x)
if (is_vector) {
out$id = NULL
}
return(out)
} |
.warningGEVShapeLarge <- function(xi){
if(xi>=4.5)
warning("A shape estimate larger than 4.5 was produced.\n",
"Shape parameter values larger than 4.5 are critical\n",
"in the GEV family as to numerical issues. Be careful with \n",
"ALE results obtained here; they might be unreliable.")
}
.pretreat.of.interest <- function(of.interest,trafo,withMu=FALSE){
if(is.null(trafo)){
of.interest <- unique(of.interest)
if(!withMu && length(of.interest) > 2)
stop("A maximum number of two parameters resp. parameter transformations may be selected.")
if(withMu && length(of.interest) > 3)
stop("A maximum number of three parameters resp. parameter transformations may be selected.")
if(!withMu && !all(of.interest %in% c("scale", "shape", "quantile", "expected loss", "expected shortfall")))
stop("Parameters resp. transformations of interest have to be selected from: ",
"'scale', 'shape', 'quantile', 'expected loss', 'expected shortfall'.")
if(withMu && !all(of.interest %in% c("loc", "scale", "shape", "quantile", "expected loss", "expected shortfall")))
stop("Parameters resp. transformations of interest have to be selected from: ",
"'loc', 'scale', 'shape', 'quantile', 'expected loss', 'expected shortfall'.")
muAdd <- 0
if(withMu & "loc" %in% of.interest){
muAdd <- 1
muWhich <- which(of.interest=="loc")
notmuWhich <- which(!of.interest %in% "loc")
of.interest <- of.interest[c(muWhich,notmuWhich)]
}
if(("scale" %in% of.interest) && ("scale" != of.interest[1+muAdd])){
of.interest[2+muAdd] <- of.interest[1+muAdd]
of.interest[1+muAdd] <- "scale"
}
if(!("scale" %in% of.interest) && ("shape" %in% of.interest) && ("shape" != of.interest[1+muAdd])){
of.interest[2+muAdd] <- of.interest[1+muAdd]
of.interest[1+muAdd] <- "shape"
}
if(!any(c("scale", "shape") %in% of.interest) && ("quantile" %in% of.interest)
&& ("quantile" != of.interest[1+muAdd])){
of.interest[2+muAdd] <- of.interest[1+muAdd]
of.interest[1+muAdd] <- "quantile"
}
if(!any(c("scale", "shape", "quantile") %in% of.interest)
&& ("expected shortfall" %in% of.interest)
&& ("expected shortfall" != of.interest[1+muAdd])){
of.interest[2+muAdd] <- of.interest[1+muAdd]
of.interest[1+muAdd] <- "expected shortfall"
}
}
return(of.interest)
}
.define.tau.Dtau <- function(of.interest, btq, bDq, btes,
bDes, btel, bDel, p, N){
tau <- NULL
if("scale" %in% of.interest){
tau <- function(theta){ th <- theta[1]; names(th) <- "scale"; th}
Dtau <- function(theta){ D <- t(c(1, 0)); rownames(D) <- "scale"; D}
}
if("shape" %in% of.interest){
if(is.null(tau)){
tau <- function(theta){th <- theta[2]; names(th) <- "shape"; th}
Dtau <- function(theta){D <- t(c(0,1));rownames(D) <- "shape";D}
}else{
tau <- function(theta){th <- theta
names(th) <- c("scale", "shape"); th}
Dtau <- function(theta){ D <- diag(2);
rownames(D) <- c("scale", "shape");D}
}
}
if("quantile" %in% of.interest){
if(is.null(p)) stop("Probability 'p' has to be specified.")
if(is.null(tau)){
tau <- function(theta){ }; body(tau) <- btq
Dtau <- function(theta){ };body(Dtau) <- bDq
}else{
tau1 <- tau
tau <- function(theta){ }
body(tau) <- substitute({ btq0
th0 <- tau0(theta)
th <- c(th0, q)
names(th) <- c(names(th0),"quantile")
th
}, list(btq0=btq, tau0 = tau1))
Dtau1 <- Dtau
Dtau <- function(theta){}
body(Dtau) <- substitute({ bDq0
D0 <- Dtau0(theta)
D1 <- rbind(D0, D)
rownames(D1) <- c(rownames(D0),"quantile")
D1
}, list(Dtau0 = Dtau1, bDq0 = bDq))
}
}
if("expected shortfall" %in% of.interest){
if(is.null(p)) stop("Probability 'p' has to be specified.")
if(is.null(tau)){
tau <- function(theta){ }; body(tau) <- btes
Dtau <- function(theta){ }; body(Dtau) <- bDes
}else{
tau1 <- tau
tau <- function(theta){ }
body(tau) <- substitute({ btes0
th0 <- tau0(theta)
th <- c(th0, es)
names(th) <- c(names(th0),"expected shortfall")
th}, list(tau0 = tau1, btes0=btes))
Dtau1 <- Dtau
Dtau <- function(theta){}
body(Dtau) <- substitute({ bDes0
D0 <- Dtau0(theta)
D1 <- rbind(D0, D)
rownames(D1) <- c(rownames(D0),"expected shortfall")
D1}, list(Dtau0 = Dtau1, bDes0=bDes))
}
}
if("expected loss" %in% of.interest){
if(is.null(N)) stop("Expected frequency 'N' has to be specified.")
if(is.null(tau)){
tau <- function(theta){ }; body(tau) <- btel
Dtau <- function(theta){ }; body(Dtau) <- bDel
}else{
tau1 <- tau
tau <- function(theta){ }
body(tau) <- substitute({ btel0
th0 <- tau0(theta)
th <- c(th0, el)
names(th) <- c(names(th0),"expected los")
th}, list(tau0 = tau1, btel0=btel))
Dtau1 <- Dtau
Dtau <- function(theta){}
body(Dtau) <- substitute({ bDel0
D0 <- Dtau0(theta)
D1 <- rbind(D0, D)
rownames(D1) <- c(rownames(D0),"expected loss")
D1}, list(Dtau0 = Dtau1, bDel0=bDel))
}
}
trafo <- function(x){ list(fval = tau(x), mat = Dtau(x)) }
return(trafo)
}
setMethod("validParameter",signature(object="GEVFamily"),
function(object, param, tol =.Machine$double.eps){
if (is(param, "ParamFamParameter"))
param <- main(param)
if (!all(is.finite(param)))
return(FALSE)
if (any(param[1] <= tol))
return(FALSE)
if(object@param@withPosRestr) if (any(param[2] <= tol))
return(FALSE)
if (any(param[2] <= -1/2))
return(FALSE)
return(TRUE)
})
GEVFamily <- function(loc = 0, scale = 1, shape = 0.5,
of.interest = c("scale", "shape"),
p = NULL, N = NULL, trafo = NULL,
start0Est = NULL, withPos = TRUE,
secLevel = 0.7,
withCentL2 = FALSE,
withL2derivDistr = FALSE,
withMDE = FALSE,
..ignoreTrafo = FALSE,
..withWarningGEV = TRUE){
theta <- c(loc, scale, shape)
if(..withWarningGEV).warningGEVShapeLarge(shape)
of.interest <- .pretreat.of.interest(of.interest,trafo)
distrSymm <- NoSymmetry()
names(theta) <- c("loc", "scale", "shape")
scaleshapename <- c("scale"="scale", "shape"="shape")
btq <- bDq <- btes <- bDes <- btel <- bDel <- NULL
if(!is.null(p)){
btq <- substitute({ q <- loc0 + theta[1]*((-log(p0))^(-theta[2])-1)/theta[2]
names(q) <- "quantile"
q
}, list(loc0 = loc, p0 = p))
bDq <- substitute({ scale <- theta[1]; shape <- theta[2]
D1 <- ((-log(p0))^(-shape)-1)/shape
D2 <- -scale/shape*(D1 + log(-log(p0))*(-log(p0))^(-shape))
D <- t(c(D1, D2))
rownames(D) <- "quantile"; colnames(D) <- NULL
D }, list(p0 = p))
btes <- substitute({ if(theta[2]>=1L){
warning("Expected value is infinite for shape > 1")
es <- NA
}else{
pg <- pgamma(-log(p0),1-theta[2], lower.tail = TRUE)
es <- theta[1] * (gamma(1-theta[2]) * pg/ (1-p0) - 1 )/
theta[2] + loc0 }
names(es) <- "expected shortfall"
es }, list(loc0 = loc, p0 = p))
bDes <- substitute({ if(theta[2]>=1L){ D1 <- D2 <- NA} else {
scale <- theta[1]; shape <- theta[2]
pg <- pgamma(-log(p0), 1-theta[2], lower.tail = TRUE)
dd <- ddigamma(-log(p0),1-theta[2])
g0 <- gamma(1-theta[2])
D1 <- (g0*pg/(1-p0)-1)/theta[2]
D21 <- D1/theta[2]
D22 <- dd/(1-p0)/theta[2]
D2 <- -theta[1]*(D21+D22)}
D <- t(c(D1, D2))
rownames(D) <- "expected shortfall"
colnames(D) <- NULL
D }, list(loc0 = loc, p0 = p))
}
if(!is.null(N)){
btel <- substitute({ if(theta[2]>=1L){
warning("Expected value is infinite for shape > 1")
el <- NA
}else{
el <- N0*(loc0+theta[1]*(gamma(1-theta[2])-1)/theta[2])}
names(el) <- "expected loss"
el }, list(loc0 = loc,N0 = N))
bDel <- substitute({ if(theta[2]>=1L){ D1 <- D2 <- NA}else{
scale <- theta[1]; shape <- theta[2]
ga <- gamma(1-shape)
D1 <- N0*(ga-1)/shape
D2 <- -N0*scale*ga*digamma(1-shape)/shape-
D1*scale/shape}
D <- t(c(D1, D2))
rownames(D) <- "expected loss"
colnames(D) <- NULL
D }, list(loc0 = loc, N0 = N))
}
fromOfInt <- FALSE
if(is.null(trafo)||..ignoreTrafo){fromOfInt <- TRUE
trafo <- .define.tau.Dtau(of.interest, btq, bDq, btes, bDes,
btel, bDel, p, N)
}else if(is.matrix(trafo) & nrow(trafo) > 2)
stop("number of rows of 'trafo' > 2")
param <- ParamFamParameter(name = "theta", main = c(theta[2],theta[3]),
fixed = theta[1],
trafo = trafo, withPosRestr = withPos,
.returnClsName ="ParamWithScaleAndShapeFamParameter")
distribution <- GEV(loc = loc, scale = scale, shape = shape)
startPar <- function(x,...){
mu <- theta[1]
n <- length(x)
epsn <- min(floor(secLevel*sqrt(n))+1,n)
if(is.null(start0Est)){
e0 <- .getBetaXiGEV(x=x, mu=mu, xiGrid=.getXiGrid(), withPos=withPos, withMDE=withMDE)
}else{
if(is(start0Est,"function")){
e1 <- start0Est(x, ...)
e0 <- if(is(e1,"Estimate")) estimate(e1) else e1
}else stop("Argument 'start0Est' must be a function or NULL.")
if(!is.null(names(e0)))
e0 <- e0[c("scale", "shape")]
}
if(quantile(e0[2]/e0[1]*(x-mu), epsn/n)< (-1)){
if(e0[2]>0)
stop("shape is positive and some data smaller than 'loc-scale/shape' ")
else
stop("shape is negative and some data larger than 'loc-scale/shape' ")
}
names(e0) <- NULL
return(e0)
}
makeOKPar <- function(theta) {
if(withPos){
theta <- abs(theta)
}else{
if(!is.null(names(theta))){
if(theta["shape"]< (-1/2)) theta["shape"] <- -1/2+1e-4
theta["scale"] <- abs(theta["scale"])
}else{
theta[1] <- abs(theta[1])
if(theta[2]< (-1/2)) theta[2] <- -1/2+1e-4
}
}
return(theta)
}
modifyPar <- function(theta){
theta <- makeOKPar(theta)
sh <- if(!is.null(names(theta))) theta["shape"] else theta[2]
if(..withWarningGEV).warningGEVShapeLarge(sh)
if(!is.null(names(theta))){
sc <- theta["scale"]
sh <- theta["shape"]
}else{
sc <- theta[1]
sh <- theta[2]
}
GEV(loc = loc, scale = theta[1], shape = theta[2])
}
L2deriv.fct <- function(param) {
sc <- force(main(param)[1])
k <- force(main(param)[2])
tr <- fixed(param)[1]
if(..withWarningGEV).warningGEVShapeLarge(k)
Lambda1 <- function(x) {
y <- x*0
ind <- if(k>0)(x > tr-sc/k) else (x<tr-sc/k)
x <- (x[ind]-tr)/sc
x1 <- 1 + k * x
y[ind] <- (x*(1-x1^(-1/k))-1)/x1/sc
return(y)
}
Lambda2 <- function(x) {
y <- x*0
ind <- if(k>0)(x > tr-sc/k) else (x<tr-sc/k)
x <- (x[ind]-tr)/sc
x1 <- 1 + k * x
x2 <- x / x1
y[ind]<- (1-x1^(-1/k))/k*(log(x1)/k-x2)-x2
return(y)
}
if(withCentL2){
dist0 <- GEV(scale = sc, shape = k, loc = tr)
suppressWarnings({
z1 <- E(dist0, fun=Lambda1)
z2 <- E(dist0, fun=Lambda2)
})
}else{z1 <- z2 <- 0}
return(list(function(x){ Lambda1(x)-z1 },function(x){ Lambda2(x)-z2 }))
}
FisherInfo.fct <- function(param) {
sc <- force(main(param)[1])
k <- force(main(param)[2])
if(abs(k)>=1e-4){
k1 <- k+1
if(..withWarningGEV).warningGEVShapeLarge(k)
G20 <- gamma(2*k)
G10 <- gamma(k)
G11 <- digamma(k)*gamma(k)
G01 <- ..dig1
G02 <- ..trig1dig1sq
x0 <- k1^2*2*k
I11 <- G20*x0-2*G10*k*k1+1
I11 <- I11/sc^2/k^2
I12 <- G20*(-x0)+ G10*(k^3+4*k^2+3*k) - k1
I12 <- I12 + G11*(k^3+k^2) -G01*k
I12 <- I12/sc/k^3
I22 <- G20*x0 +k1^2 -G10*(x0+2*k*k1)
I22 <- I22 - G11*2*k^2*k1 + G01*2*k*k1+k^2 *G02
I22 <- I22 /k^4
}else{
I11 <- ..I22/sc^2
I12 <- ..I23/sc
I22 <- ..I33
}
mat <- PosSemDefSymmMatrix(matrix(c(I11,I12,I12,I22),2,2))
dimnames(mat) <- list(scaleshapename,scaleshapename)
return(mat)
}
FisherInfo <- FisherInfo.fct(param)
name <- "GEV Family"
L2Fam <- new("GEVFamily")
L2Fam@scaleshapename <- scaleshapename
L2Fam@name <- name
L2Fam@param <- param
L2Fam@distribution <- distribution
[email protected] <- L2deriv.fct
[email protected] <- FisherInfo.fct
L2Fam@FisherInfo <- FisherInfo
L2Fam@startPar <- startPar
L2Fam@makeOKPar <- makeOKPar
L2Fam@modifyParam <- modifyPar
L2Fam@L2derivSymm <- FunSymmList(NonSymmetric(), NonSymmetric())
L2Fam@L2derivDistrSymm <- DistrSymmList(NoSymmetry(), NoSymmetry())
L2deriv <- EuclRandVarList(RealRandVariable(L2deriv.fct(param),
Domain = Reals()))
L2derivDistr <- NULL
if(withL2derivDistr){
suppressWarnings(L2derivDistr <-
imageDistr(RandVar = L2deriv, distr = distribution))
}
if(fromOfInt){
[email protected] <- substitute(GEVFamily(loc = loc0, scale = scale0,
shape = shape0, of.interest = of.interest0,
p = p0, N = N0,
withPos = withPos0, withCentL2 = FALSE,
withL2derivDistr = FALSE, ..ignoreTrafo = TRUE),
list(loc0 = loc, scale0 = scale, shape0 = shape,
of.interest0 = of.interest, p0 = p, N0 = N,
withPos0 = withPos))
}else{
[email protected] <- substitute(GEVFamily(loc = loc0, scale = scale0,
shape = shape0, of.interest = NULL,
p = p0, N = N0, trafo = trafo0,
withPos = withPos0, withCentL2 = FALSE,
withL2derivDistr = FALSE),
list(loc0 = loc, scale0 = scale, shape0 = shape,
p0 = p, N0 = N,
withPos0 = withPos, trafo0 = trafo))
}
L2Fam@LogDeriv <- function(x){
x0 <- (x-loc)/scale
x1 <- 1 + x0 * shape
(shape+1)/scale/x1 + x1^(-1-1/shape)/scale
}
L2Fam@L2deriv <- L2deriv
L2Fam@L2derivDistr <- L2derivDistr
[email protected] <- FALSE
[email protected] <- FALSE
[email protected] <- FALSE
return(L2Fam)
}
ddigamma <- function(t,s){
int <- function(x) exp(-x)*(log(x))*x^(s-1)
integrate(int, lower=0, upper=t)$value
}
|
Subsets and Splits