code
stringlengths
1
13.8M
context("na_locf") test_that("All NA vector gives warning", { expect_warning(na_locf(c(NA, NA, NA, NA, NA))) }) test_that("Correct results for all options with a modifed tsAirgap dataset (additionalNAs at end)", { skip_on_cran() x <- tsAirgap x[135:144] <- NA expect_equal(round(mean(na_locf(x, option = "locf", na_remaining = "mean")), digits = 1), 271.9) expect_equal(round(mean(na_locf(x, option = "nocb", na_remaining = "mean")), digits = 1), 266.7) expect_equal(round(mean(na_locf(x, option = "locf", na_remaining = "rev")), digits = 1), 271.9) expect_equal(round(mean(na_locf(x, option = "nocb", na_remaining = "rev")), digits = 1), 275.3) expect_equal(round(mean(na_locf(x, option = "locf", na_remaining = "rm")), digits = 1), 271.9) expect_equal(round(mean(na_locf(x, option = "nocb", na_remaining = "rm")), digits = 1), 266.7) expect_equal(round(mean(na_locf(x, option = "locf", na_remaining = "keep"), na.rm = T), digits = 1), 271.9) expect_equal(round(mean(na_locf(x, option = "nocb", na_remaining = "keep"), na.rm = T), digits = 1), 266.7) }) test_that("Correct results for all options with a modifed tsAirgap dataset (additionalNAs at start)", { skip_on_cran() x <- tsAirgap x[1:5] <- NA expect_equal(round(mean(na_locf(x, option = "locf", na_remaining = "mean")), digits = 1), 284.3) expect_equal(round(mean(na_locf(x, option = "nocb", na_remaining = "mean")), digits = 1), 283.0) expect_equal(round(mean(na_locf(x, option = "locf", na_remaining = "rev")), digits = 1), 279.2) expect_equal(round(mean(na_locf(x, option = "nocb", na_remaining = "rev")), digits = 1), 283.0) expect_equal(round(mean(na_locf(x, option = "locf", na_remaining = "rm")), digits = 1), 284.3) expect_equal(round(mean(na_locf(x, option = "nocb", na_remaining = "rm")), digits = 1), 283.0) expect_equal(round(mean(na_locf(x, option = "locf", na_remaining = "keep"), na.rm = T), digits = 1), 284.3) expect_equal(round(mean(na_locf(x, option = "nocb", na_remaining = "keep"), na.rm = T), digits = 1), 283.0) }) test_that("Correct results for all options with the tsAirgap dataset", { skip_on_cran() x <- tsAirgap expect_equal(round(mean(na_locf(x, option = "locf", na_remaining = "mean")), digits = 1), 278.8) expect_equal(round(mean(na_locf(x, option = "nocb", na_remaining = "mean")), digits = 1), 282.7) expect_equal(round(mean(na_locf(x, option = "locf", na_remaining = "rev")), digits = 1), 278.8) expect_equal(round(mean(na_locf(x, option = "nocb", na_remaining = "rev")), digits = 1), 282.7) expect_equal(round(mean(na_locf(x, option = "locf", na_remaining = "rm")), digits = 1), 278.8) expect_equal(round(mean(na_locf(x, option = "nocb", na_remaining = "rm")), digits = 1), 282.7) expect_equal(round(mean(na_locf(x, option = "locf", na_remaining = "keep"), na.rm = T), digits = 1), 278.8) expect_equal(round(mean(na_locf(x, option = "nocb", na_remaining = "keep"), na.rm = T), digits = 1), 282.7) }) test_that("Imputation works for data.frame", { x <- data.frame(tsAirgap, tsAirgap, tsAirgapComplete) expect_false(anyNA(na_locf(x, option = "locf", na_remaining = "mean"))) expect_false(anyNA(na_locf(x, option = "nocb", na_remaining = "mean"))) expect_false(anyNA(na_locf(x, option = "locf", na_remaining = "rev"))) expect_false(anyNA(na_locf(x, option = "nocb", na_remaining = "rev"))) expect_false(anyNA(na_locf(x, option = "locf", na_remaining = "rm"))) expect_false(anyNA(na_locf(x, option = "nocb", na_remaining = "rm"))) }) test_that("Warning for wrong input for option parameter", { expect_error(na_locf(tsAirgap, option = "wrongOption")) }) test_that("Warning for wrong input for na_remaining parameter", { x <- tsAirgap x[1:2] <- NA expect_error(na_locf(x, na_remaining = "Wrong")) }) test_that("Test NA at beginning", { x <- tsAirgap x[1:2] <- NA expect_false(anyNA(na_locf(x, option = "locf", na_remaining = "mean"))) expect_false(anyNA(na_locf(x, option = "locf", na_remaining = "rev"))) expect_false(anyNA(na_locf(x, option = "nocb", na_remaining = "mean"))) expect_false(anyNA(na_locf(x, option = "nocb", na_remaining = "rev"))) expect_equal(length(na_locf(x, option = "nocb", na_remaining = "rm")), 144) expect_equal(length(na_locf(x, option = "locf", na_remaining = "rm")), 142) expect_equal(length(na_locf(x, option = "nocb", na_remaining = "keep")), 144) expect_false(anyNA(na_locf(x))) }) test_that("Test NA at end", { x <- tsAirgap x[143:144] <- NA expect_false(anyNA(na_locf(x, option = "locf", na_remaining = "mean"))) expect_false(anyNA(na_locf(x, option = "locf", na_remaining = "rev"))) expect_false(anyNA(na_locf(x, option = "nocb", na_remaining = "mean"))) expect_false(anyNA(na_locf(x, option = "nocb", na_remaining = "rev"))) expect_equal(length(na_locf(x, option = "nocb", na_remaining = "rm")), 142) expect_equal(length(na_locf(x, option = "locf", na_remaining = "rm")), 144) expect_false(anyNA(na_locf(x))) }) test_that("Multiple NAs in a row", { x <- tsAirgap x[40:80] <- NA expect_false(anyNA(na_locf(x, option = "locf", na_remaining = "mean"))) expect_false(anyNA(na_locf(x, option = "locf", na_remaining = "rev"))) expect_false(anyNA(na_locf(x, option = "nocb", na_remaining = "mean"))) expect_false(anyNA(na_locf(x, option = "nocb", na_remaining = "rev"))) expect_equal(length(na_locf(x, option = "nocb", na_remaining = "rm")), 144) expect_equal(length(na_locf(x, option = "locf", na_remaining = "rm")), 144) expect_false(anyNA(na_locf(x))) }) test_that("Over 90% NAs", { x <- tsAirgap x[10:140] <- NA expect_false(anyNA(na_locf(x, option = "locf", na_remaining = "mean"))) expect_false(anyNA(na_locf(x, option = "locf", na_remaining = "rev"))) expect_false(anyNA(na_locf(x, option = "nocb", na_remaining = "mean"))) expect_false(anyNA(na_locf(x, option = "nocb", na_remaining = "rev"))) expect_false(anyNA(na_locf(x))) })
library("psychotools") data("VerbalAggression", package = "psychotools") d <- VerbalAggression[, c("gender", "anger")] d$poly <- itemresp(VerbalAggression$resp[, 13:18], mscale = 0:2, labels = c("Want-Curse", "Do-Curse", "Want-Scold", "Do-Scold", "Want-Shout", "Do-Shout")) head(d$poly) summary(d$poly) prop.table(summary(d$poly), 1) plot(d$poly) library("likert") lik <- likert(as.data.frame(as.list(d$poly))) lik plot(lik) d$dich <- d$poly mscale(d$dich) <- c(0, 1, 1) par(mfrow = c(1, 2)) plot(d$poly) plot(d$dich) par(mfrow = c(1, 1)) ram <- raschmodel(d$dich) ram summary(ram) plot(ram, type = "curves") par(mfrow = c(1, 2)) plot(ram, type = "profile") plot(ram, type = "regions") par(mfrow = c(1, 1)) plot(ram, type = "piplot") plot(ram, type = "information") raip <- itempar(ram) raip confint(raip) confint(itempar(ram, ref = 1, alias = FALSE)) library("lmtest") coeftest(itempar(ram, ref = 1, alias = FALSE)) rapp <- personpar(ram) rapp confint(rapp) rsm <- rsmodel(d$poly) pcm <- pcmodel(d$poly) pp <- personpar(pcm) vcpp <- vcov(pp) iprm <- itempar(ram, alias = FALSE, ref = 1) iprsm <- itempar(rsm, alias = FALSE, ref = 1) ippcm <- itempar(pcm, alias = FALSE, ref = 1) print(cbind(RM = iprm, RSM = iprsm, PCM = ippcm), digits = 5) atprsm <- threshpar(rsm, relative = FALSE, ref = 1) atppcm <- threshpar(pcm, relative = FALSE, ref = 1) print(cbind(coef(atprsm, type = "matrix"), coef(atppcm, type = "matrix")), digits = 5) rtprsm <- threshpar(rsm, ref = 1, relative = TRUE) rtppcm <- threshpar(pcm, ref = 1, relative = TRUE) print(cbind(coef(rtprsm, type = "matrix"), coef(rtppcm, type = "matrix")), digits = 5) lbs <- labels(d$poly) tlm <- c(-2, 6) cols <- colorspace::rainbow_hcl(4, c = 60, l = 75) cols2 <- colorspace::heat_hcl(6, h = c(0, -100), c = 60, l = 75) cols3 <- colorspace::rainbow_hcl(3, c = 60, l = 60) plot(pcm, type = "curves", ref = 1, items = 1:6, layout = matrix(1:6, ncol = 3, nrow = 2, byrow = FALSE), names = lbs, ylim = c(0, 1), xlim = tlm, col = cols[1:3], lwd = 1.5, xlab = expression(paste("Latent trait ", theta)), ylab = "Probability") plot(pcm, type = "regions", names = lbs, parg = list(ref = 1), ylab = expression(paste("Latent trait ", theta)), ylim = tlm, col = cols[1:3]) plot(pcm, type = "profile", what = "items", names = lbs, ylab = expression(paste("Latent trait ", theta)), parg = list(ref = 1), ylim = tlm) plot(rsm, type = "curves", items = 1, ref = 1, xlim = tlm, col = c(" plot(pcm, type = "curves", items = 1, ref = 1, lty = 2, xlim = tlm, col = c(" legend(x = 0.85, y = 6.5, legend = c("RSM", "PCM"), bty = "n", lty = 1:2, lwd = 2) plot(ram, type = "profile", what = "items", parg = list(ref = 1), col = cbind(cols3[1], "lightgray"), ref = FALSE, names = lbs, ylim = tlm, ylab = "Item location parameters") plot(rsm, type = "profile", what = "items", parg = list(ref = 1), col = cbind(cols3[2], "lightgray"), ylim = tlm, add = TRUE) plot(pcm, type = "profile", what = "items", parg = list(ref = 1), col = cbind(cols3[3], "lightgray"), ylim = tlm, add = TRUE) legend(x = 0.85, y = 6.5, legend = c("RM", "RSM", "PCM"), bty = "n", col = cols3, pch = 16) plot(rsm, type = "profile", what = "threshold", parg = list(ref = 1), col = cbind(cols3[2], cols3[2]), names = lbs, ylim = tlm) plot(pcm, type = "profile", what = "threshold", parg = list(ref = 1), col = cbind(cols3[3], cols3[3]), add = TRUE) legend(x = 0.85, y = 6.5, legend = c("RSM", "PCM"), bty = "n", col = cols3[2:3], pch = 16) plot(ram, type = "information", what = "items", ref = 1, xlab = expression(paste("Latent trait ", theta)), names = lbs, lty = 1, xlim = c(-4, 8), ylim = c(0, 0.6), main = "", lwd = 2, col = cols2, ylab = "Item information") plot(pcm, type = "information", what = "items", ref = 1, lty = 2, xlim = c(-4, 8), lwd = 2, col = cols2, add = TRUE) legend(x = 6, y = 0.74, legend = c("RM", "PCM"), bty = "n", lwd = 2, lty = 1:2) plot(pcm, type = "information", what = "categories", ref = 1, items = 1:6, xlab = expression(paste("Latent trait ", theta)), ylab = "Category information", lwd = 2, names = lbs, col = cols, xlim = c(-4, 8), ylim = c(0, 0.3), layout = matrix(1:6, ncol = 3, nrow = 2, byrow = FALSE)) AIC(rsm, pcm) BIC(rsm, pcm) library("lmtest") lrtest(rsm, pcm) tp <- threshpar(pcm, type = "mode", relative = TRUE, ref = 1, alias = FALSE) C <- cbind(1, diag(-1, nrow = 5, ncol = 5)) library("car") linearHypothesis(tp, hypothesis.matrix = C, rhs = rep.int(0, 5)) rmall <- raschmodel(d$dich) rmmale <- raschmodel(subset(d, gender == "male")$dich) rmfemale <- raschmodel(subset(d, gender == "female")$dich) (LRT <- as.vector(- 2 * (logLik(rmall) - (logLik(rmmale) + logLik(rmfemale))))) pchisq(LRT, df = 5, lower.tail = FALSE) ipmale <- itempar(rmmale, ref = c(2, 3)) ipfemale <- itempar(rmfemale, ref = c(2, 3)) waldtests <- (coef(ipmale) - coef(ipfemale)) / sqrt(diag(vcov(ipmale)) + diag(vcov(ipfemale))) pvalues <- 2*pnorm(abs(waldtests), lower.tail = FALSE) cbind("Test Statistic" = waldtests, "P-Value" = pvalues) set.seed(1) anchortest(rmfemale, rmmale, class = "forward", method = "MPT", adjust = "holm") library("psychotree") rt <- raschtree(dich ~ gender + anger, data = d) plot(rt, tp_args = list(names = lbs, abbreviate = FALSE))
if (require(tree)) { require(ggplot2) require(MASS) data(cpus, package = "MASS") cpus.ltr <- tree(log10(perf) ~ syct + mmin + mmax + cach + chmin + chmax, data = cpus) tree_data <- dendro_data(cpus.ltr) ggplot(segment(tree_data)) + geom_segment(aes(x = x, y = y, xend = xend, yend = yend, size = n), colour = "lightblue" ) + scale_size("n") + geom_text( data = label(tree_data), aes(x = x, y = y, label = label), vjust = -0.5, size = 4 ) + geom_text( data = leaf_label(tree_data), aes(x = x, y = y, label = label), vjust = 0.5, size = 3 ) + theme_dendro() }
expected <- eval(parse(text="187L")); test(id=0, code={ argv <- eval(parse(text="list(structure(list(srcfile = \"/home/lzhao/tmp/RtmpS45wYI/R.INSTALL2aa62411bcd3/rpart/R/rpart.R\", frow = 187L, lrow = 187L), .Names = c(\"srcfile\", \"frow\", \"lrow\"), row.names = c(NA, -1L), class = \"data.frame\"), 2L)")); do.call(`.subset2`, argv); }, o=expected);
euclidean_distance <- function(point, cloud, threads = 1L) { results <- euclidean_rcpp(point, as.matrix(cloud), threads) return(results) }
SurvCD <- function(X0, Y0, status, penalty=c("network", "mcp", "lasso"), lamb.1=NULL, lamb.2=NULL, clv=NULL, r=5, init=NULL, alpha.i=1, robust=TRUE, standardize=TRUE) { intercept = TRUE status = as.numeric(status) if(is.null(clv)){ clv = intercept*1 }else{ clv = setdiff(union(intercept, (clv+intercept)), 0) } n = nrow(X0); p.c = length(clv); p = ncol(X0)-p.c+intercept; if(standardize) X1 = scale(X0, center = FALSE, scale = apply(X0, 2, function(t) stats::sd(t)*sqrt((n-1)/n))) if(intercept) X1 = cbind(Intercept = rep(1, n), X1) Y1 = Y0 out = KMweight(X1, Y1, status, robust) X = out$X + 10^-9 Y = out$Y init = match.arg(init, choices = c("zero","cox","elnet")) x.c=X[, clv, drop = FALSE]; x.g = X[, -clv, drop = FALSE] if(init == "cox"){ b0 = initiation_cox(out$Xo, out$Yo, out$So) } else if(init == "elnet"){ b0 = initiation(X, Y, alpha.i) } else{ b0 = rep(0, (p+p.c)) } if(penalty == "network"){ a = Adjacency(x.g) b = RunNetSurv(x.c, x.g, Y, lamb.1, lamb.2, b0[clv], b0[-clv], r, a, p, p.c, robust) }else if(penalty == "mcp"){ b = RunMCPSurv(x.c, x.g, Y, lamb.1, b0[clv], b0[-clv], r, p, p.c, robust) }else{ b = RunLassoSurv(x.c, x.g, Y, lamb.1, b0[clv], b0[-clv], p, p.c, robust) } b = as.numeric(b) vname = colnames(X0) if(!is.null(vname)){ names(b) = c("Intercept", vname[clv], vname[-clv]) }else if(p.c==1){ names(b) = c("Intercept", paste("g", seq = (1:p), sep="")) }else{ names(b) = c("Intercept", paste("clv", seq = (1:(p.c-1)), sep=""), paste("g", seq = (1:p), sep="")) } return(drop(b)) } KMweight <- function(X1, Y1, status, robust){ y.log <- log(Y1); inds = order(y.log) n = nrow(X1) xs=X1[inds,] d=status[inds] yy = y.log[inds] w <- numeric(n) w[1]=d[1]/n for ( i in 2:n ){ tmp = 1 for ( j in 1: (i-1) ) tmp = tmp*((n-j)/(n-j+1))^d[j] w[i]=d[i]/(n-i+1)*tmp } if(robust){ XZ = w * xs YZ = w * yy }else{ XZ = sqrt(w) * xs YZ = sqrt(w) * yy } list(X = XZ, Y = YZ, Xo=xs, Yo=Y1[inds], So=d) }
if(getRversion() >= "2.15.1") utils::globalVariables(c( ".", "Nsurv", "Nsurv_q50_check", "ppc_matching_valid", "SE_id", "Nsurv_q50_valid", "Nsurv_qinf95_valid", "Nsurv_qsup95_valid", "conc", "q50", "qinf95", "qsup95", "time"))
romberg <- function(f, a, b, maxit = 25, tol = 1e-12, ...) { stopifnot(is.numeric(a), is.numeric(b), length(a) == 1, length(b) == 1) tol <- abs(tol) if (a == b) return(list(value = 0, iter = 0, rel.error = 0)) if (a > b) return(-1 * romberg(f, b, a, tol = tol, ...)) fun <- match.fun(f) f <- function(x) fun(x, ...) eps <- .Machine$double.eps if (!is.finite(f(a))) a <- a + eps * sign(b-a) if (!is.finite(f(b))) b <- b - eps * sign(b-a) I <- matrix(0, nrow = maxit+1, ncol = maxit+1) n <- 1; iter <- 0; err <- 1.0 while (err > tol && iter < maxit) { iter <- iter+1 n <- 2 * n h <- (b-a) / n S <- f(a) for (i in 1:(n-1)) { xi <- a + h * i S <- S + 2*f(xi) } S <- (S + f(b)) * h/2 I[iter+1, 1] <- S for (k in 2:(iter+1)) { j <- 2+iter-k I[j,k] <- (4^(k-1)*I[j+1,k-1] - I[j,k-1]) / (4^(k-1)-1) } err <- abs(I[1,iter+1] - I[2,iter]) } if (iter == maxit) warning("Maximum number of iterations has been reached.") return(list(value = I[1, iter+1], iter = iter, rel.error = err)) }
make.branches.quasse.fftR <- function(control) { nx <- control$nx dx <- control$dx r <- control$r dt.max <- control$dt.max tc <- control$tc f.hi <- make.pde.quasse.fftR(nx*r, dx/r, dt.max, 2L) f.lo <- make.pde.quasse.fftR(nx, dx, dt.max, 2L) combine.branches.quasse(f.hi, f.lo, control) } make.pde.quasse.fftR <- function(nx, dx, dt.max, nd) { function(y, len, pars, t0) { padding <- pars$padding ndat <- length(pars$lambda) nt <- as.integer(ceiling(len / dt.max)) dt <- len / nt if ( !(length(y) %in% (nd * nx)) ) stop("Wrong size y") if ( length(pars$lambda) != length(pars$mu) || length(pars$lambda) > (nx-3) ) stop("Incorrect length pars") if ( pars$diffusion <= 0 ) stop("Invalid diffusion parameter") if ( !is.matrix(y) ) y <- matrix(y, nx, nd) ans <- quasse.integrate.fftR(y, pars$lambda, pars$mu, pars$drift, pars$diffusion, nt, dt, nx, ndat, dx, padding[1], padding[2]) q <- sum(ans[,2]) * dx ans[,2] <- ans[,2] / q list(log(q), ans) } } quasse.integrate.fftR <- function(vars, lambda, mu, drift, diffusion, nstep, dt, nx, ndat, dx, nkl, nkr) { kern <- fftR.make.kern(-dt * drift, sqrt(dt * diffusion), nx, dx, nkl, nkr) fy <- fft(kern) for ( i in seq_len(nstep) ) { vars <- fftR.propagate.t(vars, lambda, mu, dt, ndat) vars <- fftR.propagate.x(vars, nx, fy, nkl, nkr) } vars } fftR.make.kern <- function(mean, sd, nx, dx, nkl, nkr) { kern <- rep(0, nx) xkern <- (-nkl:nkr)*dx ikern <- c((nx - nkl + 1):nx, 1:(nkr + 1)) kern[ikern] <- normalise(dnorm(xkern, mean, sd)) kern } fftR.propagate.t <- function(vars, lambda, mu, dt, ndat) { i <- seq_len(ndat) r <- lambda - mu z <- exp(dt * r) e0 <- vars[i,1] d0 <- vars[i,-1] vars[i,1] <- (mu + z*(e0 - 1)*mu - lambda*e0) / (mu + z*(e0 - 1)*lambda - lambda*e0) dd <- (z * r * r)/(z * lambda - mu + (1-z)*lambda*e0)^2 vars[i,-1] <- dd * d0 vars } fftR.propagate.x <- function(vars, nx, fy, nkl, nkr) { ifft <- function(x) fft(x, inverse=TRUE) f <- function(z, fy, n) { nx <- length(z) for ( i in seq_len(n) ) z <- Re(ifft(fft(z) * fy))/nx z } vars.out <- Re(apply(apply(vars, 2, fft) * fy, 2, ifft))/nx ndat <- nx - (nkl + 1 + nkr) i.prev.l <- 1:nkl i.prev.r <- (ndat-nkr+1):ndat i.zero <- (ndat+1):nx vars.out[c(i.prev.l, i.prev.r),] <- vars[c(i.prev.l, i.prev.r),] vars.out[i.zero,] <- 0 vars.out[vars.out < 0] <- 0 vars.out }
strictOp <- function(expr, warnOnly = FALSE, errorCall = substitute(expr)) { condFun <- if(warnOnly) warning else stop fCall <- substitute(expr) if(!is.language(fCall)) { warning("expression supplied to strictOp() was not a function call") return(expr) } fname <- fCall[[1]] univariate <- length(fCall) == 2 || eval.parent(substitute(missing(E2), list(E2 = fCall[[3]]))) if(is.name(fname)) { f <- as.character(fname) gen = getGeneric(f) } else { gen <- getGeneric(eval.parent(fname)) if(is.null(gen) ) f <- deparse(fname) else f <- gen@generic fCall[[1]] <- as.name(f) } if(univariate) { localCall <- fCall localCall[[2]] <- quote(e1); if(length(localCall) > 2) localCall[[3]] <- NULL } else { localCall <- fCall localCall[[2]] <- quote(e1); localCall[[3]] <- quote(e2) } e1 <- eval.parent(fCall[[2]]) e2 <- if(univariate) .MissingArg else eval.parent(fCall[[3]]) if(is.null(gen)) { warning("Function \"", f, "\" is not one of the operators that can be checked") return(eval(localCall)) } group = gen@group if(length(group) == 0) { f <- as.character(f) if(identical(f, "&&") || identical(f, "||")) .strictCondOp(f, e1, e2, eval(localCall), errorCall, condFun) else if(identical(f, "!")) .strictLogicOp(f, e1, e2, eval(localCall), errorCall, condFun) else { warning("Function \"", f, "\" is not one of the operators that can be checked") eval(localCall) } } else { g1 = group[[1]] if(!(is.character(g1) && length(g1) == 1)) { warning("Function \"", f, "\" has a non-standard generic group") return(eval(localCall)) } switch(g1, Arith = .strictArithOp(f, e1, e2, eval(localCall), errorCall, condFun), Logic = .strictLogicOp(f, e1, e2, eval(localCall), errorCall, condFun), Compare = .strictCompareOp(f, e1, e2, localCall, errorCall, condFun), { warning("Function \"", f, "\" is not one of the operators that can be checked") eval(localCall) }) } } .MissingArg <- new.env() .Missing <- function(obj) identical(obj, .MissingArg) `.tail<-` <- function(x, value) { c(x, paste(value, collapse = "")) } .strictCondOp <- function(f, e1, e2, expr, errorCall, condFun) { msg <- character() if(!is.logical(e1)) .tail(msg) <- c("First argument is not logical: class \"", class(e1), "\"") else if(length(e1) != 1) .tail(msg) <- c("Length of first argument shojuld be 1; got ", length(e1)) else if(is.na(e1)) .tail(msg) <- c("First argument is NA") if(.Missing(e2)) .tail(msg) <- "No univariate version of this operator" else if(!is.logical(e2)) .tail(msg) <- c("Second argument is not logical: class \"", class(e2), "\"") else if(length(e2) != 1) .tail(msg) <- c("Length of second argument shojuld be 1; got ", length(e2)) else if(is.na(e2)) .tail(msg) <- c("Second argument is NA") if(length(msg) > 0) .strictOpMessage(errorCall, msg, condFun) return(expr) } .strictLogicOp <- function(f, e1, e2, expr, errorCall, condFun) { is.raw <- function(x)identical(typeof(x), "raw") msg <- character() if(!is.logical(e1) && !is.raw(e1)) .tail(msg) <- c("First argument is not logical or raw: class \"", class(e1), "\"") if(.Missing(e2)) { if(!identical(f, "!")) .tail(msg) <- "No univariate version of this operator" } else if(!is.logical(e2) && !is.raw(e2)) .tail(msg) <- c("Second argument is not logical or raw: class \"", class(e2), "\"") if(length(msg) > 0) .strictOpMessage(errorCall, msg, condFun) return(expr) } .checkDataType <- function(x) switch(typeof(x), double = , integer = "numeric", character = "character", logical ="logical", complex = "complex", raw = "raw", environment = if(.Missing(x)) "MISSING" else "other", "other") .strictCompareOp <- function(f, e1, e2, expr, errorCall, condFun) { msg <- character() typeCheck = paste(.checkDataType(e1), .checkDataType(e2), sep=".") switch(typeCheck, numeric.numeric = , character.character = , logical.logical = , complex.complex = , raw.raw = {}, { if(length(grep("MISSING", typeCheck))>0) .tail(msg) <- "Univariate version of this operator undefined" else .tail(msg) <- c("Undefined combination of types for comparison: ", typeof(e1), ", ", typeof(e2)) }) l1 = length(e1); l2 = length(e2) if(l1 != l2 && l1 != 1 && l2 != 1) .tail(msg) <- c("Ambiguous unequal lengths: ", l1, ", ", l2) if(length(msg) > 0) .strictOpMessage(errorCall, msg, condFun) return(eval.parent(expr)) } .strictArithOp <- function(f, e1, e2, expr, errorCall, condFun) { msg <- character() if(.Missing(e2)) { switch(f, "+" = , "-" = {}, .tail(msg) <- c("Univariate version not defined for operator ", f) ) switch(.checkDataType(e1), numeric = , complex = {}, .tail(msg) <- c("Undefined type for univariate arithmetic: ", typeof(e1)) ) } else { typeCheck = paste(.checkDataType(e1), .checkDataType(e2), sep=".") switch(typeCheck, numeric.numeric = , numeric.complex = , complex.numeric = {}, .tail(msg) <- c("Undefined combination of types for arithmetic: ", typeof(e1), ", ", typeof(e2)) ) l1 = length(e1); l2 = length(e2) if(l1 != l2 && l1 != 1 && l2 != 1) .tail(msg) <- c("Ambiguous unequal lengths: ", l1, ", ", l2) } if(length(msg) > 0) .strictOpMessage(errorCall, msg, condFun) return(eval.parent(expr)) } .strictOpMessage <- function(errorCall, msg, condFun) { condFun("<strictOp>: ", deparse(errorCall)[[1]], ": ", paste(msg, collapse = "; "), call. = FALSE) } .makeStrictEnv <- function() { myEnv <- environment(sys.function()) doOp <- function(f) { op <- args(f) if(!is.null(op)) { body(op) <- substitute(strictOp(WHAT(e1, e2), errorCall = sys.call()), list(WHAT = call("::", as.name("base"), as.name(f)))) assign(f, op, envir = .strictEnv) } } for(group in c("Arith", "Logic", "Compare")) { groupGen <- getGeneric(group) for(f in getGroupMembers(groupGen)) doOp(f) } for(f in c("&&", "||")) doOp(f) assign("!", function(x) strictOp(base::`!`(x), errorCall = sys.call()), envir = .strictEnv) } .strictEnv <- new.env(TRUE) .makeStrictEnv() withStrictOps <- function(expr, attach) { if(missing(expr)) { warning("Cannot attach the environment \"strictOps\" because of CRAN restrictions\n (added long after this function was written)") } else eval(substitute(expr), .strictEnv, enclos = parent.frame()) }
library(checkargs) context("isNonZeroNumberOrNaOrNanOrInfVectorOrNull") test_that("isNonZeroNumberOrNaOrNanOrInfVectorOrNull works for all arguments", { expect_identical(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(NULL, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(TRUE, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(FALSE, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(NA, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(0, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(-1, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(-0.1, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(0.1, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(1, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(NaN, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(-Inf, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(Inf, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroNumberOrNaOrNanOrInfVectorOrNull("", stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNonZeroNumberOrNaOrNanOrInfVectorOrNull("X", stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(c(TRUE, FALSE), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(c(FALSE, TRUE), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(c(NA, NA), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(c(0, 0), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(c(-1, -2), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(c(-0.1, -0.2), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(c(0.1, 0.2), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(c(1, 2), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(c(NaN, NaN), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(c(-Inf, -Inf), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(c(Inf, Inf), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(c("", "X"), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(c("X", "Y"), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(NULL, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_error(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(TRUE, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(FALSE, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_identical(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(NA, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_error(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(0, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_identical(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(-1, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(-0.1, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(0.1, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(1, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(NaN, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(-Inf, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(Inf, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_error(isNonZeroNumberOrNaOrNanOrInfVectorOrNull("", stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNonZeroNumberOrNaOrNanOrInfVectorOrNull("X", stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(c(TRUE, FALSE), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(c(FALSE, TRUE), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_identical(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(c(NA, NA), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_error(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(c(0, 0), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_identical(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(c(-1, -2), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(c(-0.1, -0.2), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(c(0.1, 0.2), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(c(1, 2), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(c(NaN, NaN), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(c(-Inf, -Inf), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(c(Inf, Inf), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_error(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(c("", "X"), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNonZeroNumberOrNaOrNanOrInfVectorOrNull(c("X", "Y"), stopIfNot = TRUE, message = NULL, argumentName = NULL)) })
.printNamedList <- function(nList, ...) { na <- names(nList) for (i in seq(along = na)) { cat(sprintf("%-20s", na[i]), deparse(nList[[i]]), "\n", ...) } }
summary.Gammareg <- function(object, ...){ covB = object$desvB covG = object$desvG desviacion = c(sqrt(diag(covB)),sqrt(diag(covG))) L = object$interv[,1] U = object$interv[,2] n = object$n r = object$r coef1 = coef(object)[1:nrow(covB)] coef2 = coef(object)[(nrow(covB)+1):length(coef(object))] t1 = abs(coef1/sqrt(diag(covB))) t2 = abs(coef2/sqrt(diag(covG))) p1 = round(pt(t1,n-r-1, lower.tail = FALSE),4) p2 = round(pt(t2,n-r, lower.tail = FALSE), 4) p = c(p1,p2) TAB <- cbind( Coefficient = coef(object), Deviation = desviacion, pvalue = p, L.CredIntv = L, U.CredIntv = U ) colnames(TAB) <- c("Estimate", "Deviation", "p-value" , "L.Intv", "U.Intv") res <- list(call=object$call, coefficients=TAB, covB=object$desvB, covG=object$desvG, AIC=object$AIC, iteration=object$iteration, convergence=object$convergence) class(res) <- "summary.Gammareg" res }
test_that("mixture model works", { data(tracks.list) tracks.list<- lapply(tracks.list, function(x) x[1:250,]) tracks.list<- dplyr::bind_rows(tracks.list) tracks<- subset(tracks.list, select = c(SL, TA)) set.seed(1) alpha=0.1 ngibbs=1000 nburn=ngibbs/2 nmaxclust=7 dat.res<- cluster_obs(dat = tracks, alpha = alpha, ngibbs = ngibbs, nmaxclust = nmaxclust, nburn = nburn) expect_length(dat.res, 6) expect_type(dat.res$loglikel, "double") expect_is(dat.res$theta, "matrix") expect_length(dat.res$phi, 2) expect_type(dat.res$phi, "list") expect_length(dat.res$z.MAP, nrow(tracks)) expect_equal(rowSums(dat.res$z.posterior), rep(nburn, nrow(tracks))) })
expected <- eval(parse(text="c(\"1\", \"2\", \"3\", \"6\", \"7\", \"7.1\", \"7.2\", \"8\", \"8.1\", \"10\", \"11\", \"12\", \"12.1\", \"12.2\", \"15\", \"15.1\", \"16\", \"17\", \"19\", \"20\", \"21\", \"21.1\", \"23\")")); test(id=0, code={ argv <- eval(parse(text="list(c(\"1\", \"2\", \"3\", \"6\", \"7\", \"7\", \"7\", \"8\", \"8\", \"10\", \"11\", \"12\", \"12\", \"12\", \"15\", \"15\", \"16\", \"17\", \"19\", \"20\", \"21\", \"21\", \"23\"), \".\")")); .Internal(make.unique(argv[[1]], argv[[2]])); }, o=expected);
loglik_adherence <- function(adherence, shape, rate, wa, Z, fit) { res <- sum(adherence*Z) - sum(fit$norm) if (!is.null(shape)){ res <- res + sum(wa*((shape - 1L)*log(adherence) - rate*adherence)) } res } score_adherence <- function(adherence, ranker, shape, rate, wa, Z, fit) { res <- Z - rowsum(fit$score, ranker) if (!is.null(shape)){ res <- res + wa*((shape - 1L)/adherence - rate) } res } normalization <- function(alpha, delta, a, d, P, R, G, W = NULL){ nr <- length(a) score <- numeric(nr) len <- lengths(G) pseudo <- len[2L] > nr if (pseudo) { real <- G[[2L]] <= nr len[2L] <- sum(real) } norm <- numeric(sum(len)) z <- 1L for (p in P){ if (p == 2L && pseudo) { r <- G[[p]][real] } else r <- G[[p]] nr <- length(r) item_id <- as.integer(R[r, 1L:p]) x1 <- matrix(alpha[item_id], nrow = nr, ncol = p) y1 <- rowSums(x1^a[r]*log(x1)) z1 <- rowSums(x1^a[r]) e <- d[d <= p][-1] if (length(e)){ i <- seq_len(max(e)) if (max(e) == p) { id <- p - 1L } else id <- max(e) id2 <- 1L repeat{ v1 <- alpha[R[r, i[1L]]] last <- i[id] == p if (last) { end <- id } else end <- min(max(e), id + 1L) for (k in 2L:end){ v1 <- v1 * alpha[R[r, i[k]]] if (k < id2 | ! k %in% d) next v2 <- v1^(a[r]/k) y1 <- y1 + delta[d == k]*v2*log(v1)/k z1 <- z1 + delta[d == k]*v2 } if (i[1L] == (p - 1L)) break if (last){ id2 <- id - 1L v <- i[id2] len <- min(p - 2L - v, max(e) - id2) id <- id2 + len i[id2:id] <- v + seq_len(len + 1L) } else { id2 <- id i[id] <- i[id] + 1L } } } if (!is.null(W)){ if (p == 2L && pseudo) { w <- W[[p]][real] } else w <- W[[p]] norm[z:(z + nr - 1L)] <- norm[z:(z + nr - 1L)] + w * log(z1) score[r] <- score[r] + w * y1/z1 } else { norm[z:(z + nr - 1L)] <- norm[z:(z + nr - 1L)] + log(z1) score[r] <- score[r] + y1/z1 } z <- z + nr } list(norm = norm, score = score) }
.BP_DetectClick <- function(bone) { click.locn <- locator(n = 1, type = "n") if (is.null(click.locn)) { click.locn <- list(x=NA, y=NA) } else { if (click.locn$x<1) click.locn$x <- 1 if (click.locn$x>dim(bone)[1]) click.locn$x <- dim(bone)[1] if (click.locn$y<1) click.locn$y <- 1 if (click.locn$y>dim(bone)[2]) click.locn$y <- dim(bone)[2] } return(c(x=click.locn$x, y=click.locn$y)) }
UnfoldingSMACOF <- function(P, W = matrix(1, dim(P)[1], dim(P)[2]), Constrained = FALSE, ENV = NULL, model = "Ratio", condition = "Matrix", r = 2, maxiter = 100, tolerance = 1e-05, lambda = 1, omega = 0, X0, Y0){ n = dim(P)[1] m = dim(P)[2] DimNames = "Dim-1" for (i in 2:r) DimNames = c(DimNames, paste("Dim-", i, sep = "")) ColNames = colnames(P) RowNames = rownames(P) D = DistUnfold(X0, Y0) DH = dhatsunfol(P, D, W, modelo = model, condicion = condition) cv2 = sd(as.vector(DH$Dh))/mean(DH$Dh) pstress = sum(sum((W * (D - DH$Dh))^2))^lambda * (1 + omega/cv2) Conf = UpdateUnfol(X0, Y0, W, DH$Dh) errorest = 1 k = 0 history = NULL while ((k <= maxiter) & (errorest > tolerance)) { k = k + 1 if (Constrained) Conf = UpdateUnfolConstr(X0, Y0, W, DH$Dh, ENV) else Conf = UpdateUnfol(X0, Y0, W, DH$Dh) D = DistUnfold(Conf$X, Conf$Y) DH = dhatsunfol(P, D, W, model, condition) cv2 = sd(as.vector(DH$Dh))/mean(DH$Dh) newpstress = sum(sum((W * (D - DH$Dh))^2))^lambda * (1 + omega/cv2) errorest = (pstress - newpstress)^2 pstress = newpstress X0 = Conf$X Y0 = Conf$Y history = rbind(history, c(k, errorest)) print(c(k, errorest)) } rownames(Conf$X) = RowNames colnames(Conf$X) = DimNames rownames(Conf$Y) = ColNames colnames(Conf$Y) = DimNames dmean = sum(sum(D * W))/sum(sum(W)) stress1 = sum(sum(((D - DH$Dh)^2) * W))/sum(sum(((D)^2) * W)) stress2 = sum(sum(((D - DH$Dh)^2) * W))/sum(sum(((D - dmean)^2) * W)) rs = cor(as.vector(DH$Dh * W), as.vector(D * W)) rsq = rs^2 sstress1 = sqrt(sum(sum(((D^2 - DH$Dh^2)^2) * W))/sum(sum(((D^2)^2) * W))) dmean2 = sum(sum((D^2) * W))/sum(sum(W)) sstress2 = sqrt(sum(sum(((D^2 - DH$Dh^2)^2) * W))/sum(sum(((D^2 - dmean2)^2) * W))) rho = cor(as.vector(DH$Dh * W), as.vector(D * W), method = "spearman") tau = cor(as.vector(DH$Dh * W), as.vector(D * W), method = "kendall") fitcols = matrix(0, m, 1) for (i in 1:m) fitcols[i] = cor((DH$Dh * W)[, i], (D * W)[, i])^2 rownames(fitcols) = ColNames colnames(fitcols) = "R-Squared" colnames(history) = c("Iteration", "Error") rownames(DH$Tol) = colnames(P) colnames(DH$Tol) = "Tolerance" if (Constrained) Analysis = "Constrained Unfolding - SMACOF" else Analysis = "Unfolding - SMACOF" Unfold = list() Unfold$call <- match.call() Unfold$Analysis = Analysis Unfold$nsites = n Unfold$nspecies = m Unfold$nvars = NULL Unfold$alpha = NULL Unfold$dimens = r Unfold$Abundances = P Unfold$TransformedAbundances = P Unfold$Disparities = DH$Dh Unfold$Distances = D Unfold$Environment = ENV Unfold$TransfEnvironment = ENV Unfold$Weighted_Averages = NULL Unfold$Minima_Z = NULL Unfold$Maxima_Z = NULL Unfold$Medians_Z = NULL Unfold$P25_Z = NULL Unfold$P75_Z = NULL Unfold$Means = NULL Unfold$Deviations = NULL Unfold$IterationHistory = history Unfold$X = Conf$X Unfold$Y = Conf$Y Unfold$Tolerance = DH$Tol Unfold$RawStress = pstress Unfold$Stress1 = stress1 Unfold$Stress2 = stress2 Unfold$Sstress1 = sstress1 Unfold$Sstress2 = sstress2 Unfold$Pearson = rs Unfold$Spearman = rho Unfold$Kendall = tau Unfold$RSQ = rsq Unfold$ColumnsFit = fitcols Unfold$model = model Unfold$condition = condition class(Unfold) = "Unfolding" return(Unfold) }
precision.simulation <- function(N, med=2, disp=1.3, percentile=.5, nsim=100, exact.data=FALSE, pct.type.A=.5, exp.win.dat=NULL, verb=FALSE) { if(percentile <= 0 | percentile >=1) stop("percentile must be between 0 and 1.") if(pct.type.A < 0 | pct.type.A >1) stop("% of data that is type A must be between 0 and 1.") if(is.null(exp.win.dat)){ if(verb) message("NYC exposure window data used") exp.win.dat <- get(data(exp.win.lengths, envir = environment())) } if(exact.data) { out <- precision.simulation.exact(N=N, med=med, disp=disp, percentile=percentile, nsim=nsim, verb=verb) } else { out <- precision.simulation.coarse(N=N, med=med, disp=disp, percentile=percentile, nsim=nsim, pct.type.A=pct.type.A, exp.win.dat=exp.win.dat, verb=verb) } target <- qlnorm(percentile, log(med), log(disp)) bias <- out[,"ests"]-target out <- cbind(out, bias) return(out) } precision.simulation.exact <- function(N, med, disp, percentile, nsim, verb) { storage <- matrix(NA, ncol=3, nrow=nsim) colnames(storage) <- c("ests", "SE", "conv") data <- matrix(0, ncol=6, nrow=nsim*N) colnames(data) <- c("dataset.id", "EL", "ER", "SL", "SR", "type") data[,"dataset.id"] <- rep(1:nsim, each=N) data[,"SL"] <- rlnorm(N*nsim, meanlog=log(med), sdlog=log(disp)) data[,"SR"] <- data[,"SL"] data[,"type"] <- 2 for(i in 1:nsim){ tmp.dat <- data[which(data[,"dataset.id"]==i),] tmp.fit <- dic.fit(tmp.dat, ptiles=percentile) if(tmp.fit$conv==1){ row.name <- paste("p", round(percentile*100), sep="") which.row <- which(rownames(tmp.fit$ests)==row.name)[1] storage[i,c("ests", "SE")] <- tmp.fit$ests[which.row, c("est", "StdErr")] } else { storage[i,c("ests", "SE")] <- NA } storage[i,"conv"] <- tmp.fit$conv if(verb & i%%(round(nsim/10))==0) print(paste("iteration",i,"complete ::", Sys.time())) } return(storage) } precision.simulation.coarse <- function(N, med, disp, percentile, nsim, pct.type.A, exp.win.dat, verb) { storage <- matrix(NA, ncol=3, nrow=nsim) colnames(storage) <- c("ests", "SE", "conv") for(i in 1:nsim){ tmp.dat <- generate.coarse.data(N=N, med=med, disp=disp, pct.type.A=pct.type.A, exp.win.dat=exp.win.dat) tmp.fit <- dic.fit(tmp.dat, ptiles=percentile) if(tmp.fit$conv==1){ row.name <- paste("p", round(percentile*100), sep="") which.row <- which(rownames(tmp.fit$ests)==row.name)[1] storage[i,c("ests", "SE")] <- tmp.fit$ests[which.row, c("est", "StdErr")] } else { storage[i,c("ests", "SE")] <- NA } storage[i,"conv"] <- tmp.fit$conv if(verb & i%%(round(nsim/10))==0) print(paste("iteration",i,"complete ::", Sys.time())) } return(storage) } generate.coarse.data <- function(N, med, disp, pct.type.A, exp.win.dat) { n.type.A <- round(N*pct.type.A) n.type.B <- N-n.type.A E <- runif(N, 10, 11) T <- rlnorm(N, log(med), log(disp)) S <- T + E SR <- ceiling(S) SL <- floor(S) win.type <- rep(0:1, times=c(n.type.A, n.type.B)) potential.lengths <- sample(exp.win.dat, size=N, replace=TRUE) win.length <- 1*(win.type==0) + potential.lengths*(win.type>0) ER <- ceiling(E)*(win.type==0) + SR*(win.type==1) EL <- pmin(ER-win.length, floor(E)) cbind(EL, E, ER, SL, S, SR, win.length, win.type, type=0) }
library("datasets") context("Test `find_data()` behavior") test_that("Test find_data.default()", { expect_true(inherits(find_data(lm(mpg ~ cyl, data = mtcars)), "data.frame"), label = "find_data.default() works") m1 <- lm(mpg ~ cyl, data = mtcars, subset = am == 1) expect_true(nrow(find_data(m1)) == nrow(mtcars[mtcars$am == 1, ]), label = "find_data.default(data, subset) works") mtcars2 <- mtcars mtcars2[1:3,] <- NA_real_ m2 <- lm(mpg ~ cyl, data = mtcars2) expect_true(nrow(find_data(m2)) == nrow(mtcars2[-c(1:3), ]), label = "find_data.default(data, na.action) works") m3 <- lm(mpg ~ cyl, data = mtcars2, subset = am == 1) expect_true(nrow(find_data(m3)) == nrow(na.omit(mtcars2[mtcars2$am == 1, ])), label = "find_data.default(data, subset, na.action) works") expect_error(find_data(StructTS(log10(UKgas), type = "BSM")), label = "find_data.default([no formula]) errors") }) test_that("Test find_data.lm()", { expect_true(inherits(find_data(lm(mpg ~ cyl, data = mtcars)), "data.frame"), label = "find_data.lm() works") }) test_that("Test find_data.glm()", { expect_true(inherits(find_data(glm(mpg ~ cyl, data = mtcars)), "data.frame"), label = "find_data.glm() works") }) test_that("Test find_data.data.frame()", { expect_true(inherits(find_data(mtcars), "data.frame"), label = "find_data.data.frame() works") }) test_that("Test find_data.lm() and prediction.lm() with missing data", { mtcars2 <- mtcars mtcars2$mpg[1:4] <- NA_real_ m1 <- lm(mpg ~ cyl, data = mtcars2, na.action = na.omit) expect_true(identical(dim(find_data(m1)), dim(na.omit(mtcars2))), label = "find_data.lm() drops missing data when 'na.action = na.omit'") expect_true(nrow(prediction(m1)) == nrow(na.omit(mtcars2)), label = "prediction.lm() returns correct rows when 'na.action = na.omit'") m2 <- lm(mpg ~ cyl, data = mtcars2, na.action = na.exclude) expect_true(identical(dim(find_data(m2)), dim(na.omit(mtcars2))), label = "find_data.lm() drops missing data when 'na.action = na.exclude'") expect_true(nrow(prediction(m2)) == nrow(na.omit(mtcars2)), label = "prediction.lm() returns correct rows when 'na.action = na.exclude'") m3 <- lm(mpg ~ cyl, data = mtcars) p3 <- prediction(m3, mtcars2, na.action = na.pass) expect_true(nrow(p3) == nrow(mtcars), label = "prediction.lm() returns correct rows when prediction(na.action = na.pass) for missing outcome") expect_true(all(!is.na(p3$fitted)[1:4]), label = "prediction.lm() returns numeric predictions when prediction(na.action = na.pass) for missing outcome") expect_true(nrow(prediction(m3, mtcars2, na.action = na.omit)) == nrow(mtcars2), label = "prediction.lm() returns correct rows when prediction(na.action = na.omit) for missing outcome") expect_true(nrow(prediction(m3, mtcars2, na.action = na.exclude)) == nrow(mtcars2), label = "prediction.lm() returns correct rows when prediction(na.action = na.exclude) for missing outcome") m4 <- lm(cyl ~ mpg, data = mtcars) p4 <- prediction(m4, mtcars2, na.action = na.pass) expect_true(nrow(p4) == nrow(mtcars), label = "prediction.lm() returns correct rows when prediction(na.action = na.pass) for missing covariate") expect_true(all(is.na(p4$fitted)[1:4]), label = "prediction.lm() returns NA predictions when prediction(na.action = na.pass) for missing covariate") expect_error(prediction(m4, mtcars2, na.action = na.omit), label = "prediction.lm() fails when prediction(na.action = na.omit) for missing covariate") expect_error(prediction(m4, mtcars2, na.action = na.exclude), label = "prediction.lm() fails when prediction(na.action = na.exclude) for missing covariate") rm(mtcars2) }) test_that("Test find_data.lm() with subsetted data", { mtcars2 <- mtcars mtcars2$mpg[1:4] <- NA_real_ m1 <- lm(mpg ~ cyl, data = mtcars2, subset = !is.na(mpg)) expect_true(identical(dim(find_data(m1)), dim(na.omit(mtcars2))), label = "find_data.lm() has correct dimensions when subsetting") expect_true(nrow(prediction(m1)) == nrow(na.omit(mtcars2)), label = "prediction.lm() returns correct rows when subsetting") x <- c(rep(TRUE, 30), FALSE, FALSE) m2 <- lm(mpg ~ cyl, data = mtcars2, subset = x) expect_true(identical(nrow(find_data(m2)), nrow(na.omit(mtcars2))-2L), label = "find_data.lm() subsets correctly when subsetting variable is global") expect_true(identical(rownames(find_data(m2)), head(rownames(na.omit(mtcars2)), 26)), label = "find_data.lm() returns correct rows when subsetting and missing data are present") rm(mtcars2) })
NULL "ukg_eeri"
library(NetworkInference) df <- simulate_rnd_cascades(50, n_node = 20) cascades <- as_cascade_long(df) df_matrix <- as.matrix(cascades) cascades <- as_cascade_wide(df_matrix) result <- netinf(cascades, quiet = TRUE, p_value_cutoff = 0.05) pander::pandoc.table(head(result))
context("checkNull") test_that("checkNull", { myobj = NULL expect_succ_all(Null, myobj) myobj = TRUE expect_fail_all(Null, myobj) expect_false(testNull(integer(0))) expect_true(testNull(NULL)) expect_error(assertNull(-1), "NULL") })
get_transcription <- function( job, download = TRUE, ... ) { bod <- list(TranscriptionJobName = job) out <- transcribeHTTP(action = "GetTranscriptionJob", body = bod, ...)$TranscriptionJob if (isTRUE(download)) { transcription_list <- content(httr::GET(out$Transcript$TranscriptFileUri), "text", encoding = "UTF-8") results <- jsonlite::fromJSON(transcription_list)$results out$Transcriptions <- unlist(results$transcripts) out$TranscriptionItems <- results$item } else { out$Transcriptions <- NULL out$TranscriptionItems <- NULL } return(structure(out, class = "aws_transcription")) } print.aws_transcription <- function(x, ...) { cat(paste0("Job: ", x$TranscriptionJobName, " (Status: ", x$TranscriptionJobStatus,")\n")) cat(paste0("Media URI: ", x$Media$MediaFileUri, "\n")) cat(paste0("MediaFormat: ", x$MediaFormat, " (", x$MediaSampleRateHertz, " Hertz)\n")) cat(paste0("LanguageCode: ", x$LanguageCode, "\n")) cat(paste0("CreationTime: ", as.POSIXct(x$CreationTime, origin = "1970-01-01"), "\n")) cat(paste0("CompletionTime: ", as.POSIXct(x$CompletionTime, origin = "1970-01-01"), "\n")) cat("Settings:\n") print(x$Settings) if ("TranscriptionItems" %in% names(x)) { cat(sprintf(ngettext(nrow(x$TranscriptionItems), "TranscriptionItems: 1 transcription", "TranscriptionItems: %d transcription items"), nrow(x$TranscriptionItems)), "\n") } if ("Transcriptions" %in% names(x)) { cat("Transcriptions:\n") print(x$Transcriptions) } invisible(x) }
genericEGRETDotPlot <- function(x,y, xlim, ylim, xTicks=pretty(xlim),yTicks=pretty(ylim), printTitle=TRUE, xaxs="i",xlab="",yaxs="i",ylab="",plotTitle="", pch=20,cex=0.7,cex.main=1.3,font.main=2,cex.lab=1.2, tcl=0.5,cex.axis=1,las=1,xDate=FALSE, tinyPlot=FALSE,hLine=FALSE,oneToOneLine=FALSE, rmSciX=FALSE,rmSciY=FALSE,customPar=FALSE,col="black",lwd=1, showXLabels=TRUE,showYLabels=TRUE, showXAxis=TRUE,showYAxis=TRUE, removeFirstX=FALSE,removeLastX=FALSE, removeFirstY=FALSE,removeLastY=FALSE, ...){ if(!customPar){ if (tinyPlot){ par(mar=c(4,5,1,0.1),mgp=c(2.5,0.5,0)) } else { par(mar=c(5,6,4,2) + 0.1,mgp=c(3,0.5,0)) } } plot(x,y,xlim=xlim,xaxs=xaxs,xlab=if(showXLabels) xlab else "",axes=FALSE, ylim=ylim,yaxs=yaxs,ylab=if(showYLabels) ylab else "", main=plotTitle,col=col,lwd=lwd, pch=pch,cex=cex,cex.main=cex.main,font.main=font.main,cex.lab=cex.lab,...) box() if (hLine) abline(h = 0) if (oneToOneLine) abline(a=0,b=1) if(rmSciX){ xTicksLab <- prettyNum(xTicks) } else { xTicksLab <- xTicks } if(rmSciY){ yTicksLab <- prettyNum(yTicks) } else { yTicksLab <- yTicks } if(xDate){ yearStart <- floor(min(xlim)) yearEnd <- ceiling(max(xlim)) if(yearEnd-yearStart >= 4){ xSpan<-c(yearStart,yearEnd) xTicks<-pretty(xSpan,n=5) xTicksLab <- xTicks } else { xlabels <- c(as.Date(paste(yearStart,"-01-01",sep="")), as.Date(paste(yearEnd,"-01-01",sep=""))) xlabels <- pretty(xlabels,n=5) xTicksDates <- as.POSIXlt(xlabels) years <- xTicksDates$year + 1900 day <- xTicksDates$yday xTicks <- years + day/365 xTicksLab <- format(xlabels, "%Y-%b") } } if (removeFirstX){ xTicks <- c("", xTicks[2:(length(xTicks))]) } if (removeLastX){ xTicks <- c(xTicks[1:(length(xTicks)-1)] , "") } if (removeFirstY){ yTicks <- c("", yTicks[2:(length(yTicks))]) } if (removeLastY){ yTicks <- c(yTicks[1:(length(yTicks)-1)] , "") } if(showXAxis){ axis(1,tcl=tcl,at=xTicks,cex.axis=cex.axis,labels=xTicksLab) } else { axis(1,tcl=tcl,at=xTicks,labels=FALSE) } axis(3,tcl=tcl,at=xTicks,labels=FALSE) if(showYAxis){ axis(2,tcl=tcl,las=las,at=yTicks,cex.axis=cex.axis,labels=yTicksLab) } else { axis(2,tcl=tcl,at=yTicks,labels=FALSE) } axis(4,tcl=tcl,at=yTicks,labels=FALSE) }
true_pairs(eta=0.99, rho=0.75, M=100, R=1)
knitr::opts_chunk$set(eval = FALSE)
dep.t.test <- function(formula, data, block, sig.level=.05, digits=3){ xx <- aggregate(formula, data=data, FUN=sumfun)[[2]] indvar <- unlist(strsplit(as.character(formula), " ")[3]) depvar <- unlist(strsplit(as.character(formula), " ")[2]) datawide <- reshape(data, direction="wide", idvar=block, timevar=indvar) corr <- cor(datawide[, paste(depvar, ".", levels(data[, indvar]), sep="")])[1,2] output <- dep.t.test.second(m=xx[,1], sd=xx[,2], n=xx[1,3], corr=corr, sig.level=sig.level,digits=digits) return(output) }
set_secret_key <- function(key = NULL, secret = NULL, force = FALSE) { env_id <- Sys.getenv("AWS_ACCESS_KEY_ID") env_pass <- Sys.getenv("AWS_SECRET_ACCESS_KEY") if ( (identical(env_id, "") | identical(env_pass, "")) | !force) { if (!is.null(key) & !is.null(secret)) { Sys.setenv(AWS_ACCESS_KEY_ID = key) Sys.setenv(AWS_SECRET_ACCESS_KEY = secret) } else { message("Couldn't find env var AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY_ID. See ?set_secret_key for more details.") message("Please enter your AWS_ACCESS_KEY_ID and press enter:") pat <- readline(": ") Sys.setenv(AWS_ACCESS_KEY_ID = pat) message("Now please enter your AWS_ACCESS_KEY_ID and press enter:") pat <- readline(": ") Sys.setenv(AWS_SECRET_ACCESS_KEY = pat) } } }
hc_theme_bloom <- function(...) { theme <- list( colors = c(" chart = list( backgroundColor = " style = list( fontFamily = "Roboto", color = " ) ), title = list( align = "left", style = list( fontFamily = "Roboto", color = " fontWeight = "bold" ) ), subtitle = list( align = "left", style = list( fontFamily = "Roboto", color = " fontWeight = "bold" ) ), xAxis = list( lineColor = " lineWidth = 2, tickColor = " tickWidth = 2, labels = list( style = list( color = "black" ) ), title = list( style = list( color = "black" ) ) ), yAxis = list( opposite = TRUE, gridLineWidth = 2, gridLineColor = " lineColor = " minorGridLineColor = " labels = list( align = "left", style = list( color = "black" ), x = 0, y = -2 ), tickLength = 0, tickColor = " tickWidth = 1, title = list( style = list( color = "black" ) ) ), tooltip = list( backgroundColor = " borderColor = " style = list( color = " ) ), legend = list( layout = "horizontal", align = "left", verticalAlign = "top", itemStyle = list( color = " ), itemHiddenStyle = list( color = " ) ), credits = list( style = list( color = " ) ), labels = list( style = list( color = " ) ), drilldown = list( activeAxisLabelStyle = list( color = " ), activeDataLabelStyle = list( color = " ) ), navigation = list( buttonOptions = list( symbolStroke = " theme = list( fill = " ) ) ), legendBackgroundColor = "rgba(0, 0, 0, 0.5)", background2 = " dataLabelsColor = " textColor = " contrastTextColor = " maskColor = "rgba(255,255,255,0.3)" ) theme <- structure(theme, class = "hc_theme") if (length(list(...)) > 0) { theme <- hc_theme_merge( theme, hc_theme(...) ) } theme }
knitr::opts_chunk$set( collapse = TRUE, comment = " ) library(tremendousr) test_client <- trem_client_new(api_key = "TEST_YOUR-KEY-HERE", sandbox = TRUE) test_client
covZ <- function(t_seq, Y, C, sigma2) { temp <- expand.grid(Y,Y) t.pair <- expand.grid(t_seq,t_seq) d <- length(Y) id <- expand.grid(1:d,1:d) m <- d Z <- apply(temp, 1, function(z) prod(z)) Z.info <- as.matrix(cbind(Z,t.pair,id)) Z.info <- Z.info[Z.info[,5] <= Z.info[,4],] Z.tri <- matrix(NA,nrow=length(Y),ncol=length(Y)) Z.tri[lower.tri(Z.tri, diag=T)] <- Z.info[,1] Z.tri <- t(Z.tri) id1 <- as.matrix(expand.grid(1:d,1:d,1:d,1:d)) id2 <- as.matrix(expand.grid(1:d^2,1:d^2)) id.tab <- as.matrix(cbind(id1,id2)) id.tab <- id.tab[id.tab[,5] <= id.tab[,6],] k.del <- cbind(id.tab[,1]==id.tab[,3],id.tab[,2]==id.tab[,4], id.tab[,1]==id.tab[,4],id.tab[,2]==id.tab[,3]) c.term <- cbind(C[cbind(id.tab[,1],id.tab[,3])], C[cbind(id.tab[,2],id.tab[,4])], C[cbind(id.tab[,1],id.tab[,4])], C[cbind(id.tab[,2],id.tab[,3])]) id.tab <- cbind(id.tab,k.del,c.term) CovZZ3.vec = id.tab[,12] * id.tab[,11] + id.tab[,14] * id.tab[,13] + (id.tab[,8] * id.tab[,7] + id.tab[,10] * id.tab[,9]) *sigma2^2 + (id.tab[,12] * id.tab[,7] + id.tab[,14] * id.tab[,9] + id.tab[,13] * id.tab[,10] + id.tab[,11] * id.tab[,8]) * sigma2 CovZZ3 <- matrix(NA,nrow=length(Z),ncol=length(Z)) CovZZ3[upper.tri(CovZZ3, diag=T)] <- CovZZ3.vec return (list(CovZZ = CovZZ3,CovZZ.vech = CovZZ3.vec, Z.info = Z.info,Z.tri = Z.tri)) }
is.scalar <- function(x){ result <- (is.numeric(x) && length(x) == 1 && is.finite(x)) return(result) } ifelse1 <- function (test, x, y) if (test) x else y
function(pr){ pr$run() }
OcpTsSdEwma <- function(data, n.train, threshold, l = 3, m = 5) { if (!is.numeric(data) | (sum(is.na(data)) > 0)) { stop("data argument must be a numeric vector and without NA values.") } if (!is.numeric(n.train) | n.train > length(data)) { stop("n.train argument must be a numeric value greater then data length.") } if (!is.numeric(threshold) | threshold <= 0 | threshold > 1) { stop("threshold argument must be a numeric value in (0,1] range.") } if (!is.numeric(l)) { stop("l argument must be a numeric value.") } if (!is.numeric(m) | m > length(data)) { stop("m argument must be a numeric value and smaller than all dataset length.") } ApplyKolmogorovTest <- function(pos) { if ((pos - (m - 1)) > 0 & (pos + m) <= length(data)) { part1 <- data[(pos - (m - 1)):pos] part2 <- data[(pos + 1):(pos + m)] res.test <- suppressWarnings(stats::ks.test(part1, part2, exact = FALSE)) return(ifelse(res.test$p.value > 0.05, 0, 1)) } else { return(1) } } result <- OcpSdEwma(data, n.train, threshold, l) anomaly.pos <- which(result$is.anomaly == 1) result[anomaly.pos, "is.anomaly"] <- sapply(anomaly.pos, ApplyKolmogorovTest) return(result) }
Optimal.Similarity <- function(Distance, CheckArguments = TRUE) { if (CheckArguments) CheckentropartArguments() if (is.matrix(Distance)) { if (nrow(Distance) != ncol(Distance)) { stop("Distance must be a square matrix") } if (any(diag(Distance) != 0)) { stop("The diagonal of Distance must contain zeros only") } } else { if (!inherits(Distance, "dist")) { stop("Distance must be a matrix or a dist object") } } Distances <- as.numeric(Distance/max(Distance)) u <- 1 Optim <- stats::optim(u, function(u) stats::var(exp(-u*Distances)), lower=0, upper=1000, method="L-BFGS-B", control=list(fnscale=-1)) Result <- list(u=Optim$par, Matrix=exp(-u*as.matrix(Distance)/max(Distances))) return (Result) }
pos<-function(vec){ (abs(vec)+vec)/2 } const<-function(signs,knots,degree){ cc<-prod(((signs+1)/2 - signs*knots))^degree if(cc==0) return(1) return(cc) } makeBasis<-function(signs,vars,knots,datat,degree){ cc<-const(signs,knots,degree) temp1<-pos(signs*(datat[vars,,drop=F]-knots))^degree if(length(vars)==1){ return(c(temp1)/cc) } else{ temp2<-1 for(pp in 1:length(vars)){ temp2<-temp2*temp1[pp,] } return(temp2/cc) } } makeBasisCat<-function(vars,sub,data){ temp<-1 for(ii in 1:length(vars)){ temp<-temp*as.numeric(data[,vars[ii]] %in% sub[[ii]]) } return(temp) }
taxize_nexml <- function(nexml, type = c("ncbi", "itis", "col", "tpl", "gbif", "wd"), warnings = TRUE, ...){ if (!requireNamespace("taxadb", quietly = TRUE)) { stop("taxadb package required to convert look up taxonomic ids", call. = FALSE) } get_ids <- getExportedValue("taxadb", "get_ids") type <- tolower(type) type <- match.arg(type) for(j in 1:length(nexml@otus)){ labels <- unname(vapply(nexml@otus[[j]]@otu, slot, character(1L), "label")) clean_labels <- gsub("_", " ", labels) taxa_ids <- get_ids(clean_labels, type, format = "uri", ...) for(i in 1:length(taxa_ids)){ id <- taxa_ids[[i]] if(is.na(id) & warnings) warning(paste("ID for otu", nexml@otus[[j]]@otu[[i]]@label, "not found. Consider checking the spelling or alternate classification")) else nexml@otus[[j]]@otu[[i]]@meta <- c(nexml@otus[[j]]@otu[[i]]@meta, meta(href = taxa_ids[[i]], rel = "tc:toTaxon")) } } nexml }
context("Test repetition functions") test_that("maybe", { expect_equal(maybe(Digit())("a123"), list(result=NULL, leftover="a123")) expect_equal(maybe(Digit())("123"), list(result="1", leftover="23")) }) test_that("many", { expect_equal(many(Digit())("a123"), list(result=NULL, leftover="a123")) expect_equal(many(Digit())("123"), list(result=list("1", "2", "3", NULL), leftover="")) }) test_that("some", { expect_equal(some(Digit())("a123"), list()) expect_equal(some(Digit())("1a23"), list(result=list("1", NULL), leftover="a23")) expect_equal(some(Digit())("123a"), list(result=list("1", "2", "3", NULL), leftover="a")) })
delta_Bel<-function(x,K,q=0.9){ n<-nrow(x) nn<-get.knn(x,K) D<-nn$nn.dist is<-nn$nn.index alpha<-1/K if(is.null(q)) g<-rep(1,n) else g <- 1/apply(D,1,quantile,prob=q) BelC<-rep(0,n) for(i in 1:n) BelC[i]<-1-prod(1-alpha*exp(-g[is[i,]]^2*D[i,]^2)) Dist <- as.matrix(dist(x)) maxdist<-max(Dist) tri<-sort(BelC,decreasing =TRUE,index.return = TRUE) bel_sorted<-tri$x ordbel<-tri$ix delta<-rep(0,n) delta[ordbel[1]]<- -1 for(i in 2:n){ delta[ordbel[i]]<-maxdist for(j in 1:(i-1)){ if(Dist[ordbel[i],ordbel[j]]<delta[ordbel[i]]) delta[ordbel[i]]<-Dist[ordbel[i],ordbel[j]] } } delta[ordbel[1]]<-max(delta) plot(delta,BelC,ylim=range(min(BelC)-0.1,max(BelC)+0.1)) print("With the mouse, select the lower left corner of a rectangle containing the prototypes.") t<-locator(1) abline(v=t$x,lty=2) abline(h=t$y,lty=2) ii<-which(delta>t$x & BelC>t$y) print(ii) points(delta[ii],BelC[ii],pch=3,col="red") g0<-x[ii,] return(list(BelC=BelC,delta=delta,g0=g0,ii=ii)) }
if (requireNamespace("extrafont", quietly = TRUE)) { library("extrafont", quietly = TRUE) extrafont::loadfonts(device = "pdf", quiet = TRUE) } server <- function(input, output, session) { current_project_df <- shiny::eventReactive( { input$go input$by_date_radio input$precision_radio }, { if (input$source_type=="demo") { if (input$by_date_radio=="By date") { if (input$precision_radio=="Day") { ganttrify::test_project_date_day } else { ganttrify::test_project_date_month } } else { ganttrify::test_project } } else if (input$source_type=="csv") { req(input$project_file) readr::read_csv(file = input$project_file$datapath) } else if (input$source_type=="googledrive") { googlesheets4::gs4_deauth() googlesheets4::read_sheet(ss = input$googledrive_link, sheet = 1, col_names = TRUE, col_types = "c") } else if (input$source_type=="xlsx") { req(input$project_file_xlsx) readxl::read_excel(path = input$project_file_xlsx$datapath, sheet = 1) } }, ignoreNULL = FALSE) current_spots_df <- shiny::eventReactive({ input$go input$by_date_radio input$precision_radio }, { if (input$source_type=="demo") { if (input$by_date_radio=="By date") { if (input$precision_radio=="Day") { ganttrify::test_spots_date_day } else { ganttrify::test_spots_date_month } } else { ganttrify::test_spots } } else if (input$source_type=="csv") { req(input$spot_file) readr::read_csv(file = input$spot_file$datapath) } else if (input$source_type=="googledrive") { googlesheets4::gs4_deauth() googlesheets4::read_sheet(ss = input$googledrive_link, sheet = 2, col_names = TRUE, col_types = "c") } else if (input$source_type=="xlsx") { req(input$project_file_xlsx) if (length(readxl::excel_sheets(input$project_file_xlsx$datapath))>1) { readxl::read_excel(path = input$project_file_xlsx$datapath, sheet = 2) } } }, ignoreNULL = FALSE) output$current_project_table <- renderTable( if (input$go==0) { ganttrify::test_project } else if (is.null(current_project_df())==FALSE) { current_project_df() }, striped = TRUE, hover = TRUE, digits = 0, align = "c", width = "100%") output$current_spots_table <- renderTable( if (input$go==0) { ganttrify::test_spots } else if (is.null(current_spots_df())==FALSE) { current_spots_df() }, striped = TRUE, hover = TRUE, digits = 0, align = "c", width = "100%" ) gantt_chart <- shiny::reactive({ gantt_gg <- ganttrify::ganttrify(project = current_project_df(), project_start_date = input$start_date, spots = if (length(current_spots_df())>0) { if (tibble::is_tibble(current_spots_df())&nrow(current_spots_df()>0)) { current_spots_df()} else {NULL}} else {NULL}, by_date = ifelse(input$by_date_radio=="By date", TRUE, FALSE), exact_date = ifelse(input$precision_radio=="Day", ifelse(input$by_date_radio=="By date", TRUE, FALSE), FALSE), mark_quarters = input$mark_quarters, font_family = "Roboto Condensed", month_number = input$month_number, size_wp = input$size_wp, size_activity = input$size_activity, size_text_relative = input$size_text_relative/100, colour_palette = unlist(ifelse(test = input$custom_palette_check, strsplit(input$custom_palette_text, split = ","), list(as.character(wesanderson::wes_palette(input$wes_palette)))))) if (ggplot2::is.ggplot(gantt_gg)==FALSE) { warning("Please make sure that you have provided properly formatted data and selected the relevant option between 'By project month number' and 'By date'. Check the demo file for reference.") } else { gantt_gg } }) output$gantt <- renderPlot({ gantt_chart() }) output$download_gantt_png <- downloadHandler(filename = "gantt.png", content = function(con) { ggplot2::ggsave(filename = con, plot = gantt_chart(), width = input$download_width, height = input$download_height, units = "cm", type = "cairo") } ) output$download_gantt_pdf <- downloadHandler(filename = "gantt.pdf", content = function(con) { ggplot2::ggsave(filename = con, plot = gantt_chart(), width = input$download_width, height = input$download_height, device = cairo_pdf, units = "cm") } ) output$download_gantt_svg <- downloadHandler(filename = "gantt.svg", content = function(con) { ggplot2::ggsave(filename = con, plot = gantt_chart(), width = input$download_width, height = input$download_height, units = "cm") } ) shiny::observeEvent(eventExpr = input$a4_button, { shiny::updateNumericInput(inputId = "download_width", value = 29.7, session = session) shiny::updateNumericInput(inputId = "download_height", value = 21, session = session) }) }
nycflights13_create_sql <- function(con, schema = "", ...) { check_for_pkg("nycflights13", message) local_tables <- utils::data(package = "nycflights13")$results[, "Item"] unique_index <- list( airlines = list("carrier"), planes = list("tailnum") ) index <- list( airports = list("faa"), flights = list( c("year", "month", "day"), "carrier", "tailnum", "origin", "dest" ), weather = list(c("year", "month", "day"), "origin") ) if (inherits(con, "SQLiteConnection") | schema == "") { remote_tables <- dbListTables(con) } else { remote_schemas <- DBI::dbGetQuery( con, glue::glue_sql("SELECT schema_name FROM information_schema.schemata", .con = con ) ) remote_schemas <- as.character(remote_schemas$schema_name) if (!(schema %in% remote_schemas)) { DBI::dbExecute( con, glue::glue_sql("CREATE SCHEMA {`schema`}", .con = con ) ) } remote_tables <- DBI::dbGetQuery( con, glue::glue_sql( paste0( "SELECT table_name FROM information_schema.tables WHERE ", "table_schema={schema}" ), .con = con ) ) remote_tables <- as.character(remote_tables$table_name) } tables <- setdiff(local_tables, remote_tables) message("Creating the testing database from nycflights13") for (table in tables) { df <- getExportedValue("nycflights13", table) message("Creating table: ", table) if (schema != "") { if (class(con) %in% "PostgreSQLConnection") { table_name <- c(schema, table) } else { table_name <- DBI::Id(schema = schema, table = table) } } else { table_name <- table } DBI::dbWriteTable( con, table_name, df, temporary = FALSE, row.names = FALSE, overwrite = TRUE ) } return(invisible(con)) } nycflights13_create_sqlite <- function(location = ":memory:", ...) { check_for_pkg("RSQLite") sqlite_con <- dbConnect(RSQLite::SQLite(), location) sqlite_con <- nycflights13_create_sql(sqlite_con, schema = "", ...) return(invisible(sqlite_con)) } nycflights_sqlite <- function() { check_for_pkg("RSQLite") path <- system.file("nycflights.sqlite", package = "dittodb") return(DBI::dbConnect(RSQLite::SQLite(), path)) }
load.genelist<-function(file="genelist.txt", format="column", sep="\t") { if (format=="row") { glist<-readLines(file) glist<-strsplit(glist[1], sep)[[1]] } else if(format=="column") { glist<-read.delim(file, as.is = TRUE)[[1]] } else{ print ("Gene list has to be a single row or a single column") } glist<-unique(toupper(glist)) return (glist) } load.genesets<-function(file="geneset.gmt.txt") { gs<-readLines(file) return (gs) } geneListProfile<-function(gs, glist, threshold=10) { num.gs<-length(gs) labels<-NULL sizes<-NULL symbols<-NULL othercommon<-NULL for (i in 1: num.gs){ line<-strsplit(gs[i],"\t")[[1]] sym<-toupper(line[3:length(line)]) common<-intersect(glist, sym) size<-length(common) if(size<threshold){ othercommon=union(othercommon, common) } else{ labels<-c(labels, line[1]) sizes<-c(sizes,length(common)) symbols<-c(symbols, list(common)) } } if(length(othercommon)>0) { labels<-c(labels, "Others") sizes<-c(sizes, length(othercommon)) symbols<-c(symbols, list(othercommon)) } return (list(labels=labels, sizes=sizes, symbols=symbols)) } printGeneListProfile<-function(r, file="", format=NULL) { if(is.character(format)) { if(toupper(format)=="MSIGDB") { for (i in 1:length(r$labels)) { cat(paste(r$labels[i],"\t"), file=file, append=TRUE) cat(paste("na","\t"), file=file, append=TRUE) for (j in 1: length(r$symbols[[i]])) { cat(paste(r$symbols[[i]][j],"\t"), file=file, append=TRUE) } cat("\n", file=file, append=TRUE) } } } else { for (i in 1:length(r$labels)) { cat(paste(r$labels[i],"\t"), file=file, append=TRUE) cat(paste(r$sizes[i],"\n"), file=file, append=TRUE) } } }
Spider.Plot<-function( data, data.label, data.fill, data.color, data.linetype, data.alpha, data.size, data.label.color, data.label.size, group, criteria, valor, title, title.color, title.size, label.size, label.color, label.angle, label.position, theta, grid, grid.color, grid.radius.color, grid.linetype, grid.size, grid.radius.linetype, grid.radius.size, axis, axis.label, axis.color, axis.size, axis.linetype, axis.angle, axis.label.color, axis.label.size, axis.label.displace, axis.label.angle, legend.position, legend.size, legend.text.color, plot.margin ) { find.radius<-function( r, tl, tk, t ) { M<-matrix( c( r * ( cos( tl ) - cos( tk ) ), -cos( t ), r * ( sin( tl ) - sin( tk ) ), -sin( t ) ), 2, 2, byrow = TRUE ) b<-c( -r * cos( tk ), -r * sin( tk ) ) return( solve( M, b )[2] ) } Grp<-deparse( substitute( group ) ) Cri<-deparse( substitute( criteria ) ) Val<-deparse( substitute( valor ) ) n<-nlevels( data[,Cri] ) m<-length( grid ) N<-n + 1 t<-( seq( 0, 2 * pi, length.out = N ) + theta ) %% (2*pi) t<-t[-N] Data<-data Data$x<-Data$val * cos( t[ as.numeric( Data[[Cri]] ) ] ) Data$y<-Data$val * sin( t[ as.numeric( Data[[Cri]] ) ] ) Labels<-data.frame( label = levels( Data[[Cri]] ) ) Labels$x<-label.position * cos( t ) Labels$y<-label.position * sin( t ) ald<-axis.label.displace * c( -sin( axis.angle ), cos( axis.angle ) ) k<-max( which( t <= axis.angle ) ) l<-(k+1) %% n alpha<-sapply( grid, FUN = find.radius, t[l], t[k], axis.angle ) axis.break.position<-data.frame( x = grid[m] * alpha * cos( axis.angle ), y = grid[m] * alpha * sin( axis.angle ), xlab = grid[m] * alpha * cos( axis.angle ) + ald[1], ylab = grid[m] * alpha * sin( axis.angle ) + ald[2] ) axis.break.position<-data.frame( axis.break.position, label = axis.label ) with( Data, { p<-ggplot( data = Data, aes( x = x, y = y ) ) for ( i in 1:m ) { X<-data.frame( x = grid[i] * cos( t ), y = grid[i] * sin( t ) ) p<-p + geom_polygon( data = X, aes( x = x, y = y ), fill = 'white', colour = grid.color, linetype = grid.linetype, size = grid.size, alpha = 0.0 ) } p<-p + geom_segment( data = X, aes( x = 0, y = 0, xend = x, yend = y ), colour = grid.radius.color, linetype = grid.radius.linetype, size = grid.radius.size ) p<-p + geom_segment( data = X, aes( x = 0, y = 0, xend = axis.break.position[m,1], yend = axis.break.position[m,2] ), colour = axis.color, linetype = axis.linetype, size = axis.size ) p<-p + geom_text( data = axis.break.position, aes( x = xlab, y = ylab, label = label ), size = axis.label.size, color = axis.label.color, angle = axis.label.angle ) p<-p + geom_polygon( aes( fill = Data[[Grp]], group = Data[[Grp]], colour = Data[[Grp]], linetype = Data[[Grp]], alpha = Data[[Grp]], size = Data[[Grp]] ), show.legend = TRUE ) p<-p + scale_fill_manual( values = data.fill, labels = data.label, guide = guide_legend( label.theme = element_text( family = 'Times', angle = 0, colour = data.label.color, size = data.label.size ) ) ) + scale_color_manual( values = data.color, guide = "none" ) + scale_linetype_manual( values = data.linetype, guide = "none" ) + scale_alpha_manual( values = data.alpha, guide = "none" ) + scale_size_manual( values = data.size, guide = "none" ) p<-p + geom_text( data = Labels, aes( x = x, y = y, label = label ), size = label.size, color = label.color, angle = label.angle ) p<-p + theme( plot.margin = plot.margin, panel.background = element_rect( fill = "white", colour = NA ), panel.border = element_blank() , panel.grid.major.x = element_blank(), panel.grid.major.y = element_blank(), panel.grid.minor.x = element_blank(), panel.grid.minor.y = element_blank(), title = element_text( family = 'Times', colour = title.color, size = title.size ), axis.ticks = element_blank(), axis.text.x = element_blank(), axis.title.x = element_blank(), axis.text.y = element_blank(), axis.title.y = element_blank(), legend.position = legend.position, legend.background = element_blank(), legend.title = element_blank() ) return( p ) }) }
rootSplit <- function(tree){ if(!inherits(tree,"phylo")){ stop("tree must be of class 'phylo'") } tips <- lapply(tree$edge[tree$edge[,1] == (Ntip(tree)+1),2],function(zz) if(zz>Ntip(tree)){tree$tip.label[prop.part(tree)[[zz-Ntip(tree)]]] }else{tree$tip.label[zz]}) return(tips) }
context("cor_heatmap") test_that("cor_heatmap takes numeric values only", { data(bpd_phy); data(bpd_clin) set <- tidy_micro(otu_tabs = list("P" = bpd_phy), clinical = bpd_clin, prev_cutoff = 5, ra_cutoff = 0.1, exclude_taxa = "Bacteria", filter_summary = FALSE, count_summary = FALSE) %>% filter(day == 7) expect_error( cor_heatmap(set, table = "P", bpd1), "'x' must be numeric" ) expect_error( cor_heatmap(set, table = "P") ) }) test_that("cor_heatmap takes numeric values only", { data(bpd_phy); data(bpd_clin) set <- tidy_micro(otu_tabs = list("P" = bpd_phy), clinical = bpd_clin, prev_cutoff = 5, ra_cutoff = 0.1, exclude_taxa = "Bacteria", filter_summary = FALSE, count_summary = FALSE) %>% filter(day == 7) expect_error( cor_heatmap(set, table = "P", weight, method = "X"), "'method' must be one of: pearson, kendall, spearman") })
constrmbbefd <- function(x, fix.arg, obs, ddistnam) { res <- x[1]*(1-x[2]) names(res) <- NULL res } constrmbbefd1 <- function(x, fix.arg, obs, ddistnam) { res <- c(x[1]+1, -x[1], x[2]-1, x[1]*(1-x[2])) names(res) <- NULL res } constrmbbefd1jac <- function(x, fix.arg, obs, ddistnam) { j <- matrix(0, 4, 2) j[1,] <- c(1, 0) j[2,] <- c(0, -1) j[3,] <- c(1, 0) j[4,] <- c(-x[2], -x[1]) dimnames(j) <- NULL j } constrmbbefd2 <- function(x, fix.arg, obs, ddistnam) { res <- c(x[1], x[1], 1-x[2], x[1]*(1-x[2])) names(res) <- NULL res } constrmbbefd2jac <- function(x, fix.arg, obs, ddistnam) { j <- matrix(0, 4, 2) j[1,] <- c(1, 0) j[2,] <- c(0, 1) j[3,] <- c(0, -1) j[4,] <- c(-x[2], -x[1]) dimnames(j) <- NULL j } constrMBBEFD <- function(x, fix.arg, obs, ddistnam) { res <- c(x[1]-1, x[2]) names(res) <- NULL res } constrMBBEFD1 <- function(x, fix.arg, obs, ddistnam) { res <- c(x[1]-1, x[2]-1, x[1]*x[2]-1) names(res) <- NULL res } constrMBBEFD1jac <- function(x, fix.arg, obs, ddistnam) { j <- matrix(0, 3, 2) j[1,] <- c(1, 0) j[2,] <- c(0, 1) j[3,] <- c(x[2], x[1]) dimnames(j) <- NULL j } constrMBBEFD2 <- function(x, fix.arg, obs, ddistnam) { res <- c(x[1]-1, 1-x[2], x[2], 1-x[1]*x[2]) names(res) <- NULL res } constrMBBEFD2jac <- function(x, fix.arg, obs, ddistnam) { j <- matrix(0, 4, 2) j[1,] <- c(1, 0) j[2,] <- c(0, -1) j[3,] <- c(0, 1) j[4,] <- c(-x[2], -x[1]) dimnames(j) <- NULL j }
mklag <- function(lag) { if(any(!is.numeric(lag))||length(lag)>2) stop("'lag' must a integer vector or length 2 or 1") if(length(lag)==1L) lag <- if(lag<0L) c(lag,0L) else c(0L,lag) if(diff(lag)<0L) stop("lag[1] must be <= lag[2]") return(round(lag[1L:2L])) }
print.quantile.prodlim <- function(x,digits=2,na.val="--",...){ if (attr(x,"reverse")==FALSE) cat("Quantiles of the event time distribution based on the ", ifelse(x$type=="surv","Kaplan-Meier","Aalen-Johansen"), "method.") else cat("Quantiles of the potential follow up time distribution based on the Kaplan-Meier method", "\napplied to the censored times reversing the roles of event status and censored.") thisfmt <- paste0("%1.",digits[[1]],"f") printx <- function(u){ ifelse(is.na(u),na.val,sprintf(thisfmt,u)) } cat("\n") lapply(1:length(x),function(i){ tab <- x[[i]] cat("\nTable of quantiles and corresponding confidence limits:\n") if (attr(x,"cotype")!=1) { if(length(names(x)[i])){ cat("\n",names(x)[i],"\n\n") } } print(tab,digits=digits) if(all(c(0.25,0.5,0.75) %in% tab$q)){ if (attr(x,"model")=="survival") cat("Median time (IQR):",printx(tab[tab$q==0.5,"quantile"])," (",printx(tab[tab$q==0.75,"quantile"]),";",printx(tab[tab$q==0.25,"quantile"]),")","\n",sep="") else cat("Median time (IQR):",printx(tab[tab$q==0.5,"quantile"])," (",printx(tab[tab$q==0.25,"quantile"]),";",printx(tab[tab$q==0.75,"quantile"]),")","\n",sep="") } }) invisible(x) }
SRSin <- function(Species_list, Occurrence_data, Raster_list,Pro_areas=NULL, Gap_Map=FALSE){ taxon <- NULL longitude <- NULL par_names <- c("species","latitude","longitude","type") if(missing(Occurrence_data)){ stop("Please add a valid data frame with columns: species, latitude, longitude, type") } if(isFALSE(identical(names(Occurrence_data),par_names))){ stop("Please format the column names in your dataframe as species, latitude, longitude, type") } if (isTRUE("RasterStack" %in% class(Raster_list))) { Raster_list <- raster::unstack(Raster_list) } else { Raster_list <- Raster_list } if(is.null(Gap_Map) | missing(Gap_Map)){ Gap_Map <- FALSE } else if(isTRUE(Gap_Map) | isFALSE(Gap_Map)){ Gap_Map <- Gap_Map } else { stop("Choose a valid option for GapMap (TRUE or FALSE)") } if(is.null(Pro_areas) | missing(Pro_areas)){ if(file.exists(system.file("data/preloaded_data/protectedArea/wdpa_reclass.tif",package = "GapAnalysis"))){ Pro_areas <- raster::raster(system.file("data/preloaded_data/protectedArea/wdpa_reclass.tif",package = "GapAnalysis")) } else { stop("Protected areas file is not available yet. Please run the function GetDatasets() and try again") } } else{ Pro_areas <- Pro_areas } if(isTRUE(Gap_Map)){ GapMapIn_list <- list() } df <- data.frame(matrix(ncol = 2, nrow = length(Species_list))) colnames(df) <- c("species", "SRSin") for(i in seq_len(length(Species_list))){ for(j in seq_len(length(Raster_list))){ if(grepl(j, i, ignore.case = TRUE)){ sdm <- Raster_list[[j]] } d1 <- Occurrence_data[Occurrence_data$species == Species_list[i],] test <- GapAnalysis::ParamTest(d1, sdm) if(isTRUE(test[1])){ stop(paste0("No Occurrence data exists, but and SDM was provide. Please check your occurrence data input for ", Species_list[i])) } };rm(j) if(isFALSE(test[2])){ df$species[i] <- as.character(Species_list[i]) df$GRSex[i] <- 0 warning(paste0("Either no occurrence data or SDM was found for species ", as.character(Species_list[i]), " the conservation metric was automatically assigned 0")) }else{ Pro_areas1 <- raster::crop(x = Pro_areas,y = sdm) if(raster::res(Pro_areas1)[1] != raster::res(sdm)[1]){ Pro_areas1 <- raster::resample(x = Pro_areas1, y = sdm) } sdm[sdm[] != 1] <- NA Pro_areasSpecies <- sdm * Pro_areas1 occData1 <- Occurrence_data[which(Occurrence_data$species==Species_list[i] & !is.na(Occurrence_data$latitude) & !is.na(Occurrence_data$longitude) ),] sp::coordinates(occData1) <- ~longitude+latitude if(is.na(raster::crs(sdm))){ warning("No coordinate system was provided, assuming +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0","\n") raster::projection(sdm) <- "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0" } suppressWarnings(sp::proj4string(occData1) <- sp::CRS(raster::projection(sdm))) inSDM <- occData1[!is.na(raster::extract(x = sdm,y = occData1)),] protectPoints <- sum(!is.na(raster::extract(x = Pro_areas1,y = inSDM))) totalNum <- dim(inSDM)[1] if(protectPoints >= 0 ){ SRSin <- 100 *(protectPoints/totalNum) }else{ SRSin <- 0 } df$species[i] <- as.character(Species_list[i]) df$SRSin[i] <- SRSin if(isTRUE(Gap_Map)){ message(paste0("Calculating SRSin gap map for ",as.character(Species_list[i])),"\n") gapP <- inSDM[is.na(raster::extract(x = Pro_areas1,y = inSDM)),] gapP<- sp::SpatialPoints(coords = gapP@coords) gap_map <- raster::rasterize(x = gapP, field = rep(x = 1, length(gapP)), y = sdm, fun='count') gap_map[is.na(gap_map),] <- 0 sdm[sdm[] !=1] <- NA gap_map <- sdm * gap_map GapMapIn_list[[i]] <- gap_map names(GapMapIn_list[[i]] ) <- Species_list[[i]] } } } if(isTRUE(Gap_Map)){ df <- list(SRSin=df, gap_maps = GapMapIn_list ) }else{ df <- df } return(df) }
ptbs <- function(time,lambda=1,xi=1,beta=1,x=NULL,dist=dist.error("norm")) { if(is.character(dist)) dist=dist.error(dist) aux <- .test.tbs(lambda,xi,beta,x,time=time,type="d") return(.ptbs(time,lambda,xi,aux$beta,aux$x,dist)) } .ptbs <- function(time,lambda=1,xi=1,beta=1,x=NULL,dist="norm") { out <- dist$p(c(.g.lambda(log(time),lambda)-.g.lambda(c(x%*%beta),lambda)),xi) return(c(out)) }
library(LEANR) library(ROCR) set.seed(123456) instances<-LEANR:::instances LEAN_results_sim<-LEANR:::LEAN_results_sim gene.order<-rownames(instances[[1]]$pvals) class_matrix<-t(foreach(i=1:length(instances),.combine=rbind) %do% { tmp<-!grepl('BG',instances[[i]]$pvals$NodeType); names(tmp)<-rownames(instances[[i]]$pvals); tmp[gene.order] }) LEAN_matrix<-t(foreach(i=1:length(instances),.combine=rbind) %do% { tmp<-LEAN_results_sim[[i]]$restab[,'pstar'] names(tmp)<-rownames(LEAN_results_sim[[i]]$restab); tmp[gene.order] }) SG_matrix<-t(foreach(i=1:length(instances),.combine=rbind) %do% { tmp<-instances[[i]]$pvals[,'P.Value'] names(tmp)<-rownames(instances[[i]]$pvals); tmp[gene.order] }) predictions<-list(LEAN=prediction(-LEAN_matrix,class_matrix), SG=prediction(-SG_matrix,class_matrix)) performances<-lapply(predictions,function(pred){performance(pred,"tpr","fpr")}) names(performances)<-names(predictions) aucs_ind<-lapply(predictions,function(pred){performance(pred,"auc")@y.values}) aucs<-lapply(aucs_ind,function(x)mean(unlist(x))) names(aucs)<-names(predictions) plot(performances$LEAN,xlim=c(0,.2),col='black',avg='vertical',lwd=3, spread.estimate='stderror',show.spread.at=seq(.02,.2,l=9),main='ROC performance on simulated subnetworks') plot(performances$SG,col='orange',avg='vertical',lwd=3,add=T, spread.estimate='stderror',show.spread.at=seq(.02,.2,l=9)) abline(a=0,b=1,lty=2,col='cyan') legend('topleft',c(sprintf('LEAN (AUC=%0.3g)',aucs$LEAN),sprintf('Single-gene (AUC=%0.3g)',aucs$SG)),fill=c('black','orange'))
setClass( "Aggregation.matrix.default", representation( ), contains = "Aggregation.matrix", prototype = list(name = "Aggregation.matrix.default"), validity = function(object) { TRUE } ) setMethod( f = "initialize", signature = "Aggregation.matrix.default", definition = function(.Object) { methods::validObject(.Object) return(.Object) } ) setMethod( "Aggregate", signature = c( "Aggregation.matrix.default", "character", "character", "logical", "numeric"), function( aggregation.matrix, factor.evaluation, resource.evaluation, factor.is.specific, nrfactors){ if (factor.evaluation == "Cr") { if (resource.evaluation == "Ex") return(1) if (factor.is.specific) return(NA) return(0) } if (factor.evaluation == "C") { if (resource.evaluation == "Ex") return(1 + 1/nrfactors) if (resource.evaluation == "G") return(1) if (factor.is.specific) return(NA) return(0) } if (factor.evaluation == "LC") { if (resource.evaluation == "Ex") return(1 + 2/nrfactors) if (resource.evaluation == "G") return(1 + 1/nrfactors) if (resource.evaluation == "R") return(1) if (factor.is.specific) return(NA) return(0) } if (factor.evaluation == "I") { if (resource.evaluation == "Ex") return(1 + 3/nrfactors) if (resource.evaluation == "G") return(1 + 2/nrfactors) if (resource.evaluation == "R") return(1 + 1/nrfactors) if (resource.evaluation == "W") return(1) if (resource.evaluation == "Em") return(0.01) if (resource.evaluation == "Z") return(0.001) if (factor.is.specific) return(NA) return(0) } stop("fail when agregating - invalid factor or resource evaluation") } ) setMethod("show", "Aggregation.matrix.default", function(object){ cat("\nAgregation Matrix Default:\n") cat("general evaluation matrix") cr <- c( "1", "0", "0", "0", "0", "0", "0") c <- c("(1 + 1/nf)", "1", "0", "0", "0", "0", "0") lc <- c("(1 + 2/nf)", "(1 + 1/nf)", "1", "0", "0", "0", "0") i <- c("(1 + 3/nf)", "(1 + 2/nf)", "(1 + 1/nf)", "1", "0.01", "0.001", "0") df <- rbind(cr, c, lc, i) colnames(df) <- c("Ex", "G", "R", "W", "Em", "Z", "In") row.names(df) <- c("Cr", "C", "LC", "I") cat("\n") print(df) cat("\nSpecfics factors to a project must achieve a value bigger then 0, otherwise they are evaluated as NA and causes the full option not being acceptable.\n ") cat("More information about the model see: Cosenza, Carlos Alberto Nunes, Francisco Antonio Doria, and Leonardo Antonio Monteiro Pessoa. Hierarchy Models for the Organization of Economic Spaces. Procedia Computer Science 55 (2015): 82-91. https://doi.org/10.1016/j.procs.2015.07.010") } )
NULL getShippingZones <- function(...) { private$.request("shipping_zones", ...)$shipping_zones }
OZ <- function(mat, n.step=1, spks=1, eps=0.001) { time.minutes.check <- time.minutes <- id_cycle <- rit <-time.minutes.zero<-temperature.s<-heat.flow<-T.deg<- NULL mat.zero <- mat[mat$ri > 0][, time.minutes.check := (time.minutes.zero - min(time.minutes.zero)), by = id_cycle][] T.peak.max <- (mat.zero[, temperature.s[which.max(heat.flow)], by = id_cycle]) T.step <- ceil(((max(T.peak.max$V1) - min(T.peak.max$V1)) / nrow(T.peak.max))) / n.step T.range <- seq((floor(min(T.peak.max$V1))), (ceil(max(T.peak.max$V1)) + T.step), by = T.step) DT <- lapply(T.range, function(x) mat.zero[, .SD[which.min(abs(temperature.s - x))], by = list(id_cycle)]) for (i in 1:length(T.range)) { DT[[i]]$T.deg <- T.range[[i]] } DT <- rbindlist(DT) Xc <- na.omit(DT$ri) logPhi <- log10(na.omit(DT$rate)) x <- logPhi y <- log10(-log((1 - Xc))) xy <- data.table(x, y, DT$id_cycle, DT$T.deg) setnames(xy, c("x", "y", "id_cycle", "T.deg")) xy <- xy[is.finite(rowSums(xy)), ] formulas <- list(y ~ x) mod <- xy[, lapply(formulas, function(x) list(lm(x, data = .SD))), by = T.deg] m <- lapply(mod$V1, function(x) -x$coeff[[2]]) my.list <- list("mod" = mod, "xy" = xy, "m" = m) print(summaryTableOz(my.list)) return(my.list) }
library(hamcrest) library(utils) test.typeConvert.1 <- function() { assertThat(type.convert(c('1','2','3'), 'NA', FALSE), identicalTo(c(1L,2L,3L))) } test.typeConvert.2 <- function() { assertThat(type.convert(c('T','NA','F'), 'NA', FALSE), identicalTo(c(TRUE, NA, FALSE))) } test.typeConvert.3 <- function() { assertThat(type.convert(c('bing', 'bop'), 'FOO', TRUE), equalTo(c("bing","bop"))) } test.typeConvert.4 <- function() { assertThat(type.convert(c('bing', 'bop'), 'FOO', FALSE), identicalTo(structure(1:2, class = "factor", .Label = c("bing", "bop")))) } test.typeConvert.5 <- function() { assertThat(type.convert(c('T','NA',''), 'NA', FALSE), identicalTo(c(TRUE, NA, NA))) } test.typeConvert.6 <- function() { assertThat(type.convert(c('T','FALSE','BOB'), 'BOB', FALSE), identicalTo(c(TRUE, FALSE, NA))) } test.typeConvert.7 <- function() { assertThat(type.convert(c('3.5','3.6','FOO'), 'FOO', FALSE), identicalTo(c(3.5,3.6,NA))) } test.typeConvert.8 <- function() { assertThat(type.convert(c('C','A','B'), 'FOO', FALSE), identicalTo( structure(c(3L, 1L, 2L), .Label = c("A", "B", "C"), class = "factor") )) }
yahooImport <- function (query, file = "tempfile", source = NULL, frequency = c("daily", "weekly", "monthly"), from = NULL, to = Sys.timeDate(), nDaysBack = 366, save = FALSE, sep = ";", try = TRUE) { stopifnot(length(query) == 1) freq <- match.arg(frequency) aggregation <- substr(freq, 1, 1) if (is.null(to)) to <- Sys.timeDate() to <- trunc(as.timeDate(to),"days") if (is.null(from)) { if (is.null(nDaysBack)) { stop("The \"from\" and \"nDaysBack\" arguments cannot be NULL at the same time.") } else { from <- to - nDaysBack*24*3600 } } from <- trunc(as.timeDate(from),"days") from <- as.character(from) to <- as.character(to) yearFrom <- substring(from, 1, 4) monthFrom <- as.character(as.integer(substring(from, 6, 7))-1) dayFrom <- substring(from, 9, 10) yearTo <- substring(to, 1, 4) monthTo <- as.character(as.integer(substring(to, 6, 7))-1) dayTo <- substring(to, 9, 10) Query <- paste("s=", query, "&a=", monthFrom, "&b=", dayFrom, "&c=", yearFrom, "&d=", monthTo, "&e=", dayTo, "&f=", yearTo, "&g=", aggregation, "&q=q&y=0&z=", query, "&x=.csv", sep = "") if (is.null(source)) source <- "http://chart.yahoo.com/table.csv?" if (try) { z <- try(yahooImport(query, file, source, frequency, from, to, nDaysBack, save, sep, try = FALSE)) if (inherits(z, "try-error") || inherits(z, "Error")) { return("No Internet Access") } else { return(z) } } else { url <- paste(source, Query, sep = "") tmp <- tempfile() download.file(url = url, destfile = tmp) mat <- read.table(tmp, header = TRUE, sep = ",") X <- rev(as.timeSeries(mat)) colnames(X) <- paste(sub("\\^","",query), colnames(X), sep = ".") } if (save) { write.table(as.data.frame(X), file = file, sep = sep) } else { unlink(file) } ans <- new("fWEBDATA", call = match.call(), param = c( "Instrument" = query, "Frequency " = freq), data = X, title = "Data Import from www.yahoo.com", description = description() ) ans } yahooSeries <- function(symbols, from = NULL, to = Sys.timeDate(), nDaysBack = 366, ...) { X <- yahooImport(query = symbols[1], from = from, to = to, nDaysBack=nDaysBack, ...)@data N <- length(symbols) if (N > 1) { for (i in 2:N) { Y <- yahooImport(query = symbols[i], from = from, to = to, nDaysBack=nDaysBack, ...)@data X <- merge(X, Y) } } X }
library(hamcrest) test.paste <- function() { s1 <- paste("foo", "bar") s2 <- paste("x", 0, sep = "") s3 <- paste(c("A", "B"), collapse = ", ") assertThat(s1, equalTo("foo bar")) assertThat(s2, equalTo("x0")) assertThat(s3, equalTo("A, B")) } test.paste.factors <- function() { x <- as.factor(c("Geothermal", "Electricity")) assertThat(paste(x[1], x[2]), identicalTo("Geothermal Electricity")) } test.paste.null <- function() { assertThat(paste(NULL), identicalTo(character(0))) assertThat(paste(NULL, collapse=""), identicalTo("")) } test.paste.eval <- function() { assertThat(paste(quote(a)), identicalTo("a")) }
lmvar_no_fit <- function( y, X_mu = NULL, X_sigma = NULL, intercept_mu = TRUE, intercept_sigma = TRUE, sigma_min = 0, slvr_options = list(method = "NR"), control = list(), ...){ control_call = control isnull_X = FALSE isnull_X_sigma = FALSE if(is.null(X_mu)){ isnull_X = TRUE intercept_mu = TRUE } if(is.null(X_sigma)){ isnull_X_sigma = TRUE intercept_sigma = TRUE } if (inherits( X_mu, 'numeric')){ X_mu = as.matrix(X_mu) } if (inherits( X_sigma, 'numeric')){ X_sigma = as.matrix(X_sigma) } if (!("mu_full_rank" %in% names(control))){ control$mu_full_rank = FALSE } if (!("sigma_full_rank" %in% names(control))){ control$sigma_full_rank = FALSE } if (!isnull_X){ if (nrow(X_mu) != length(y)){ stop("Number of rows of matrix X_mu not equal to length of response vector y") } if (is.element( "(Intercept)", colnames(X_mu))){ stop("Matrix X_mu can not have a column with the name '(Intercept)'") } } if (!isnull_X_sigma){ if (nrow(X_sigma) != length(y)){ stop("Number of rows of matrix X_sigma not equal to length of response vector y") } if (is.element( "(Intercept_s)", colnames(X_sigma))){ stop("Matrix X_sigma can not have a column with the name '(Intercept_s)'") } } if (length(sigma_min) > 1 & length(sigma_min) != length(y)){ stop("The length of 'sigma_min' must be 1, or equal to the length of the response vector y") } if(any(sigma_min > 0) & any(sigma_min <= 0)){ stop("All values in 'sigma_min' must be strictly positive, or all values must be zero") } n = length(y) Intercept = rep.int(1, n) if (isnull_X){ X_mu = matrix(Intercept, nrow=n, ncol=1) } else if (intercept_mu){ X_mu = cbind( Intercept, X_mu) } if (isnull_X_sigma){ X_sigma = matrix(Intercept, nrow=n, ncol=1) } else if (intercept_sigma){ X_sigma = cbind( Intercept, X_sigma) } names = matrix_column_names( X_mu, X_sigma, intercept_mu, intercept_sigma) colnames(X_mu) = names$colnames_X colnames(X_sigma) = names$colnames_X_sigma aliased_mu = logical(length = ncol(X_mu)) aliased_sigma = logical(length = ncol(X_sigma)) names(aliased_mu) = colnames(X_mu) names(aliased_sigma) = colnames(X_sigma) equal_matrices = FALSE if (!control$sigma_full_rank & ncol(X_mu) == ncol(X_sigma)){ if (all(X_mu == X_sigma)){ equal_matrices = TRUE } } qX = Matrix::qr(X_mu) if (!control$mu_full_rank){ X_mu = make_matrix_full_rank( qX, X_mu) } if (!control$sigma_full_rank){ if (equal_matrices){ i = names(aliased_mu) %in% colnames(X_mu) X_sigma = X_mu colnames(X_sigma) = names(aliased_sigma)[i] } else X_sigma = make_matrix_full_rank(X_sigma) } names = names(aliased_mu) aliased_mu = !is.element( names, colnames(X_mu)) names(aliased_mu) = names names = names(aliased_sigma) aliased_sigma = !is.element( names, colnames(X_sigma)) names(aliased_sigma) = names if (nrow(X_mu) < (ncol(X_mu) + ncol(X_sigma))){ stop("Too few observations. There must be at least ", ncol(X_mu) + ncol(X_sigma), " observations.") } rlist = list( call = match.call(), aliased_mu = aliased_mu, aliased_sigma = aliased_sigma, y = y, X_mu = X_mu, X_sigma = X_sigma, intercept_mu = intercept_mu, intercept_sigma = intercept_sigma, sigma_min = sigma_min, slvr_options = slvr_options, control = control_call) class(rlist) = "lmvar_no_fit" return(rlist) }
knitr::opts_chunk$set( warning = FALSE, message = FALSE ) options(digits=4) par(mar=c(5,4,1,1)+.1) library(matlib) A <- matrix( c(1, 2, 3, 2, 3, 0, 0, 1,-2), nrow=3, byrow=TRUE) (AI <- cbind(A, diag(3))) (AI[2,] <- AI[2,] - 2*AI[1,]) (AI[3,] <- AI[3,] + AI[2,]) (AI[2,] <- -1 * AI[2,]) (AI[3,] <- -(1/8) * AI[3,]) AI AI[2,] <- AI[2,] - 6 * AI[3,] AI[1,] <- AI[1,] - 3 * AI[3,] AI[1,] <- AI[1,] - 2 * AI[2,] AI (AInv <- AI[,-(1:3)]) inv(A) AI <- cbind(A, diag(3)) AI <- rowadd(AI, 1, 2, -2) AI <- rowadd(AI, 2, 3, 1) AI <- rowmult(AI, 2, -1) AI <- rowmult(AI, 3, -1/8) AI AI <- rowadd(AI, 3, 2, -6) AI <- rowadd(AI, 2, 1, -2) AI <- rowadd(AI, 3, 1, -3) AI echelon( cbind(A, diag(3))) echelon( cbind(A, diag(3)), verbose=TRUE, fractions=TRUE)
power.single.cost<-function(initial,protein,n1,artifact,budget,s,assaycost2.function,assaycost3.function,recruit,optimize=FALSE) { set.seed(100) sigma_m=diag(protein$sigma^2) BETA.ARTIFACT<-protein$beta*artifact SIGMA<-protein$sigma PROTEINID<-protein$proteinid sample.frame=mvrnorm(n=10000,BETA.ARTIFACT,sigma_m) sample.t=t(sample.frame) SAMPLE.MATRIX<-cbind(sample.t,protein$group) N1=n1 BUDGET<-budget;RECRUIT<-recruit;S=s; COST2.FUNCTION<-match.fun(assaycost2.function) COST3.FUNCTION<-match.fun(assaycost3.function) Ttest<-function(sample,n,m,beta.artifact=BETA.ARTIFACT,sigma=SIGMA,sample.matrix=SAMPLE.MATRIX,n1=N1,recruit=RECRUIT,cost2=COST2.FUNCTION,cost3=COST3.FUNCTION,proteinid=PROTEINID) { proteingr2=sample;proteinsample=t(sample)[,1:m] beta.sample=rowMeans(proteingr2[,1:n]); sigma.sample=apply(proteinsample,2,sd);tstat=beta.sample/sigma.sample*sqrt(n) proteingr3<-cbind(proteingr2,beta.sample,sigma.sample) prob.t=pt(abs(tstat),df=n-1,lower.tail=FALSE)*2 c(prob.t) } calculate.n3<-function(n2,p2,p3,budget=BUDGET,s=S,cost2=COST2.FUNCTION,cost3=COST3.FUNCTION,recruit=RECRUIT) { return(((budget-s)-match.fun(cost2)(n2,p2)-recruit*n2)/(match.fun(cost3)(p3)+recruit)) } do.one.experiment.t<-function(initial,budget=BUDGET,s=S,sigma=SIGMA,beta.artifact=BETA.ARTIFACT,proteinID=PROTEINID,sample.matrix=SAMPLE.MATRIX,n1=N1,cost2=COST2.FUNCTION,cost3=COST3.FUNCTION,proteinid=PROTEINID,recruit=RECRUIT) { n2=round(initial[3]);p=dim(sample.matrix)[1]; sample.stage1<-sample(c(1:10000),n1) sample.data=sample.matrix[,sample.stage1] t.pvalue=Ttest(sample=sample.data,n=n1,m=p) in.stage2<-(t.pvalue<initial[1]) p2<-sum(in.stage2) beta2<-beta.artifact[in.stage2] sigma2<-sigma[in.stage2] proteinid2<-proteinID[in.stage2] sample.stageII=sample(c(1:10000),n2) sample.data2=sample.matrix[in.stage2,sample.stageII] t.pvalue2=Ttest(sample=sample.data2,n=n2,m=p2) in.stage3<-(t.pvalue2<initial[2]) beta3<-beta2[in.stage3] sigma3<-sigma2[in.stage3] p3<-sum(in.stage3) proteinid3<-proteinid2[in.stage3] n3=calculate.n3(n2=n2,p2=p2,p3=p3,budget=BUDGET,s=S,cost2=COST2.FUNCTION,cost3=COST3.FUNCTION,recruit=RECRUIT) if (n3>100) { final.power<-power.t.test(n3,delta=beta3,sd=sigma3,sig.level=0.05,type="paired",alternative="two.sided")$power final.stage<-(final.power>0.85) detect.positive=sum(final.power) p4=sum(final.stage) proteinid4<-proteinid3[final.stage] return(c(detect.positive=p4,n3=n3,p2=p2,p3=p3,p4=p4,proteinid2=proteinid2,proteinid3=proteinid3,proteinid4=proteinid4)) } else return(c(0,0,p2,p3,1,rep(0,p2),rep(0,p3),rep(0,1))) } expect.positive=c(rep(0,1000)) n3.vect=c(rep(0,1000)) n2=round(initial[3]) no.protein=length(BETA.ARTIFACT);num.col=6+no.protein stage2.cost=c(rep(0,1000));stage3.cost=c(rep(0,1000)) SELECT1<-matrix(nrow=1000,ncol=num.col,rep(0,1000*num.col)) SELECT2<-matrix(nrow=1000,ncol=num.col,rep(0,1000*num.col)) SELECT3<-matrix(nrow=1000,ncol=num.col,rep(0,1000*num.col)) for (i in 1:1000) { set.seed(i*100) esolution=do.one.experiment.t(initial) expect.positive[i]=esolution[1] n3.vect[i]=esolution[2] p2=esolution[3] p3=esolution[4] p4=esolution[5] if(p2 !=0 & p3 !=0 & p4!=0) {SELECT1[i,1:p2]=esolution[6:(6+p2-1)] SELECT2[i,1:p3]=esolution[(6+p2):(6+p2+p3-1)] SELECT3[i,1:p4]=esolution[(6+p2+p3):(6+p2+p3+p4-1)]} else print ("NO protein selected at final stage") stage2.cost[i]=match.fun(COST2.FUNCTION)(n2,p2)+recruit*n2;stage3.cost[i]=match.fun(COST3.FUNCTION)(p3)*n3.vect[i]+recruit*n3.vect[i] } mean.expect.pos=mean(expect.positive[expect.positive>=0]) mean.n3<-mean(n3.vect[n3.vect>=0]) mean.stage2.cost=mean(stage2.cost);mean.stage3.cost=mean(stage3.cost) if(optimize) return(-mean.expect.pos) else { print("no. of expected positive:");print(expect.positive) print("n3:");print(n3.vect) print("summary of expected positive:");print(summary(expect.positive)) print("n3 vector"); print(summary(n3.vect)); print(table(SELECT1));print(table(SELECT2));print(table(SELECT3)) par(mfcol=c(3,1)) hist(expect.positive,main="expected positive",xlim=c(0,(mean.expect.pos+1)));hist(n3.vect,main="n3",xlim=c(0,(mean.n3+100)));plot(expect.positive,n3.vect,xlab="expected positive",ylab="n3") print(paste("cost at stage II:",mean.stage2.cost),quote=FALSE) print(paste("cost at stage III:",mean.stage3.cost),quote=FALSE) return(c(mean.n3,mean.stage2.cost,mean.stage3.cost)) } }
FPTsimul <- function(obj,M) { spikes <- numeric(M) time.points <- obj$time rate.vec <- obj$g0/(1-obj$gg0) N1time <- length(obj$time) t0 <- time.points[1] deltat <- time.points[2]-time.points[1] Nmin <- floor(N1time/10) Nmax <- which.min(abs(rate.vec[(Nmin+1):(N1time+1)]-rate.vec[Nmin:N1time]))+Nmin tol <- 0.0001 tmax <- t0 + Nmax*deltat lamax <- 1.01*max(rate.vec) nreject <- 0 for (ifire in 1:M) { Tcurr <- t0 repeat { Tcurr <- Tcurr - log(runif(1))/lamax lambdacurr <- rate.vec[Nmax] if (Tcurr < tmax) { icurr <- min(floor((Tcurr-t0)/deltat+1.001),(N1time-1)) lambdacurr <- rate.vec[icurr]+(rate.vec[icurr+1]-rate.vec[icurr])*(Tcurr-time.points[icurr])/deltat } u2 <- runif(1) lacheck <- abs(lambdacurr/lamax - u2) if (lacheck <= tol ) { nreject <- nreject + 1 Tcurr <- t0 } if ((lacheck > tol) & (lambdacurr/lamax >= u2) ) break() } spikes[ifire] <- Tcurr } return(spikes) }
expect_equal( mtcars %>% summarise(mean(mpg)), data.frame("mean(mpg)" = mean(mtcars$mpg), check.names = FALSE), info = "Test single summaries" ) expect_equal( mtcars %>% summarise(meanMpg = mean(mpg)), data.frame("meanMpg" = mean(mtcars$mpg)), info = "Test single summaries with column name" ) expect_equal( mtcars %>% summarise(mean(mpg), sum(disp)), data.frame("mean(mpg)" = mean(mtcars$mpg), "sum(disp)" = sum(mtcars$disp), check.names = FALSE), info = "Test multiple summarise" ) expect_equal( mtcars %>% summarise(meanMpg = mean(mpg), sumDisp = sum(disp)), data.frame("meanMpg" = mean(mtcars$mpg), "sumDisp" = sum(mtcars$disp), check.names = FALSE), info = "Test multiple summarise with column names" ) expect_equal( summarise(data.frame(x = 1:10), y = mean(x), z = y + 1), data.frame(y = 5.5, z = 6.5), info = "Can use freshly create variables" ) expect_equal( mtcars %>% summarise(n(), range(mpg)), structure(list(`n()` = c(32L, 32L), `range(mpg)` = c(10.4, 33.9)), class = "data.frame", row.names = c(NA, -2L)), info = "Functions returning multiple values get split over rows" ) expect_equal( mtcars %>% summarise(n(), list(range(mpg))), structure(list(`n()` = 32L, `list(range(mpg))` = list(c(10.4, 33.9))), class = "data.frame", row.names = c(NA, -1L)), info = "Functions returning multiple values that are wrapped in list are returned as nested columns" ) res <- mtcars %>% group_by(am, cyl, gear) %>% summarise(meanMpg = mean(mpg), sumDisp = sum(disp)) gd <- group_data(res) expect_equal( gd, structure( list( am = c(0, 0, 0, 1, 1, 1), cyl = c(4, 6, 8, 4, 6, 8), .rows = list(1:2, 3:4, 5L, 6:7, 8:9, 10L) ), row.names = c(NA, 6L), class = "data.frame", .drop = TRUE ), info = "Ensure the summarised data still contains group attributes" ) attr(res, "groups") <- NULL expect_equal( res, structure( list( am = c(0, 0, 0, 0, 0, 1, 1, 1, 1, 1), cyl = c(4, 4, 6, 6, 8, 4, 4, 6, 6, 8), gear = c(3, 4, 3, 4, 3, 4, 5, 4, 5, 5), meanMpg = c(21.5, 23.6, 19.75, 18.5, 15.05, 28.0333333333333, 28.2, 21, 19.7, 15.4), sumDisp = c(120.1, 287.5, 483, 335.2, 4291.4, 533.5, 215.4, 320, 145, 652) ), row.names = c(NA, 10L), class = c("grouped_df", "data.frame") ), info = "Test multiple groups and multiple summary functions" ) expect_equal( summarise(mtcars), data.frame(), info = "empty summarise returns empty data.frame" ) res <- mtcars %>% group_by(am) %>% summarise() expect_equal( class(res), c("grouped_df", "data.frame"), info = "empty grouped summarise() returns groups ) expect_equal( { attr(res, "groups") <- NULL class(res) <- "data.frame" res }, data.frame(am = c(0, 1)), info = "empty grouped summarise() returns groups ) df <- data.frame(x = 1, y = 2) %>% group_by(x, y) expect_equal( df %>% summarise() %>% group_vars(), "x", info = ".groups = NULL drops the last grouping variable when the results return a single value" ) expect_equal( df %>% summarise(.groups = "drop_last") %>% group_vars(), "x", info = ".groups = 'drop_last' drops the last grouping variable" ) expect_equal( df %>% summarise(.groups = "drop") %>% group_vars(), character(), info = ".groups = 'drop' drops all grouping variables" ) expect_equal( df %>% summarise(.groups = "keep") %>% group_vars(), c("x", "y"), info = ".groups = 'keep' keeps all grouping variables" ) expect_equal( mtcars %>% group_by(cyl, vs) %>% summarise(cyl_n = n()) %>% group_vars(), "cyl", info = ".groups = NULL drops the last grouping variable when the results return a single value for multiple groups" )
exists.ftp.file <- function(url, file.path) { tryCatch({test_connection <- curl::curl_fetch_memory(url = url)}, error = return(FALSE)) if (test_connection$status_code == 226) { con <- curl::curl(url = url, open = "rb", curl::new_handle(dirlistonly = TRUE)) ftp.content <- suppressMessages(readr::read_delim(con, delim = "\n", col_names = FALSE)) close(con) return(is.element(as.character(basename(file.path)), as.character(ftp.content$X1))) } else { return(FALSE) } } exists.ftp.file.new <- function(url, file.path) { if (!RCurl::url.exists(dirname(url))) return(FALSE) con <- RCurl::getURL(url, ftp.use.epsv = FALSE, dirlistonly = TRUE) ftp.content <- suppressMessages(readr::read_delim(con, delim = "\n", col_names = FALSE)) return(is.element(as.character(basename(file.path)), as.character(ftp.content$X1))) }
output$amstock1 <- renderAmCharts({ data("data_stock_2") amTimeSeries(data_stock_2, "date", c("ts1", "ts2")) }) output$code_amstock1 <- renderText({ " data('data_stock_2') amTimeSeries(data_stock_2, 'date', c('ts1', 'ts2')) " }) output$amstock2 <- renderAmCharts({ data('data_stock_2') amTimeSeries(data_stock_2, "date", c("ts1", "ts2"), bullet = "round", groupToPeriods = c('hh', 'DD', '10DD'), linewidth = c(3, 1)) }) output$code_amstock2 <- renderText({ " data('data_stock_2') amTimeSeries(data_stock_2, 'date', c('ts1', 'ts2'), bullet = 'round', groupToPeriods = c('hh', 'DD', '10DD'), linewidth = c(3, 1)) " }) output$amstock3 <- renderAmCharts({ data('data_stock_2') ZoomButton <- data.frame(Unit = c("DD", "DD", "MAX"), multiple = c(1, 10 ,1), label = c("Day","10 days", "MAX")) amTimeSeries(data_stock_2, 'date', c('ts1', 'ts2'), bullet = 'round', ZoomButton = ZoomButton, main = 'My title', ylab = 'Interest', export = TRUE, creditsPosition = 'bottom-left', group = 'a') }) output$code_amstock3 <- renderText({ " data('data_stock_2') ZoomButton <- data.frame(Unit = c('DD', 'DD', 'MAX'), multiple = c(1, 10 ,1), label = c('Day','10 days', 'MAX')) amTimeSeries(data_stock_2, 'date', c('ts1', 'ts2'), bullet = 'round', ZoomButton = ZoomButton, main = 'My title', ylab = 'Interest', export = TRUE, creditsPosition = 'bottom-left', group = 'a') " }) output$amstock4 <- renderAmCharts({ data('data_stock_2') amTimeSeries(data_stock_2, 'date', c('ts1', 'ts2'), aggregation = 'Sum', legend = TRUE, maxSeries = 1300, group = 'a') }) output$code_amstock4 <- renderText({ " data('data_stock_2') amTimeSeries(data_stock_2, 'date', c('ts1', 'ts2'), aggregation = 'Sum', legend = TRUE, maxSeries = 1300, group = 'a') " }) output$amstock5 <- renderAmCharts({ data(data_stock_3) amStockMultiSet(data = data_stock_3) }) output$code_amstock5 <- renderText({ " data(data_stock_3) amStockMultiSet(data = data_stock_3) " }) output$amstock6 <- renderAmCharts({ data(data_stock_3) amStockMultiSet(data = data_stock_3, panelColumn = c(1,2,1,1)) }) output$code_amstock6 <- renderText({ " data(data_stock_3) amStockMultiSet(data = data_stock_3, panelColumn = c(1,2,1,1)) " }) output$amstock7 <- renderAmCharts({ data(data_stock_3) ZoomButton <- data.frame(Unit = c("DD", "DD", "MAX"), multiple = c(10, 15 ,1), label = c("10 days","15 days", "MAX")) amStockMultiSet(data = data_stock_3, panelColumn = c(1,2,1,1), percentHeightPanel = c(3,1), ZoomButtonPosition = "top", ZoomButton = ZoomButton, export = TRUE) }) output$code_amstock7 <- renderText({ " data(data_stock_3) ZoomButton <- data.frame(Unit = c('DD', 'DD', 'MAX'), multiple = c(10, 15 ,1), label = c('10 days','15 days', 'MAX')) amStockMultiSet(data = data_stock_3, panelColumn = c(1,2,1,1), percentHeightPanel = c(3,1), ZoomButtonPosition = 'top', ZoomButton = ZoomButton, export = TRUE) " })
options(na.action=na.exclude) options(contrasts=c('contr.treatment', 'contr.poly')) library(survival) lung2 <- na.omit(lung[c('time', 'status', 'wt.loss')]) fit <- coxph(Surv(time, status) ~ pspline(wt.loss,3), lung2, x=T) fit0<- coxph(Surv(time, status) ~ 1, lung2) fit1<- coxph(Surv(time, status) ~ fit$x, lung2, iter=0, init=fit$coef) all.equal(fit$loglik[1], fit0$loglik) all.equal(fit$loglik[2], fit1$loglik[2]) imat <- solve(fit1$var) var2 <- fit$var %*% imat %*% fit$var all.equal(fit$var2, var2)
setGeneric("as.PiecewiseLinearFuzzyNumber", function(object, ...) standardGeneric("as.PiecewiseLinearFuzzyNumber")) setMethod( f="as.PiecewiseLinearFuzzyNumber", signature(object="TrapezoidalFuzzyNumber"), definition=function(object, knot.n=0, knot.alpha=seq(0, 1, length.out=knot.n+2)[-c(1,knot.n+2)]) { stopifnot(length(knot.n) == 1, knot.n >= 0) stopifnot(knot.n == length(knot.alpha)) a <- alphacut(object, c(0, knot.alpha, 1)) PiecewiseLinearFuzzyNumber(knot.left=a[,1], knot.right=rev(a[,2]), knot.alpha=knot.alpha) }) setMethod( f="as.PiecewiseLinearFuzzyNumber", signature(object="numeric"), definition=function(object, knot.n=0, knot.alpha=seq(0, 1, length.out=knot.n+2)[-c(1,knot.n+2)]) { stopifnot(is.finite(object)) stopifnot(length(knot.n) == 1, knot.n >= 0) stopifnot(knot.n == length(knot.alpha)) if (length(object) == 1) PiecewiseLinearFuzzyNumber(a1=object, a2=object, a3=object, a4=object, knot.n=knot.n, knot.alpha=knot.alpha, knot.left=rep(object, knot.n), knot.right=rep(object, knot.n)) else if (length(object) == 2) PiecewiseLinearFuzzyNumber(a1=object[1], a2=object[1], a3=object[2], a4=object[2], knot.n=knot.n, knot.alpha=knot.alpha, knot.left=rep(object, knot.n), knot.right=rep(object, knot.n)) else stop("`object` should be a numeric vector of length 1 or 2") }) setMethod( f="as.PiecewiseLinearFuzzyNumber", signature(object="FuzzyNumber"), definition=function(object, knot.n=0, knot.alpha=seq(0, 1, length.out=knot.n+2)[-c(1,knot.n+2)]) { stop("This method is only for exact conversion. Use piecewiseLinearApproximation() instead.") }) setMethod( f="as.PiecewiseLinearFuzzyNumber", signature(object="PiecewiseLinearFuzzyNumber"), definition=function(object, knot.n=0, knot.alpha=seq(0, 1, length.out=knot.n+2)[-c(1,knot.n+2)]) { stopifnot(length(knot.n) == 1, knot.n >= 0) stopifnot(knot.n == length(knot.alpha)) if (length(setdiff([email protected], knot.alpha)) != 0) stop("This method is only for exact conversion. Use piecewiseLinearApproximation() instead.") a <- alphacut(object, c(0, knot.alpha, 1)) PiecewiseLinearFuzzyNumber(knot.left=a[,1], knot.right=rev(a[,2])) })
hsic.clust <- function( x, y, z, sig=1, p=100, numCluster=10, numCol=50, eps=0.1, paral=1 ){ x = as.matrix(x) y = as.matrix(y) z = as.matrix(z) n = nrow(as.matrix(x)) H = diag(n)-1/n*matrix(rep(x = 1, length.out = n*n), n, n) pval.perm=matrix(0,p) tempx = inchol(as.matrix(x), kernel = 'rbfdot', kpar = list(sigma = 1/sig), maxiter = numCol) iCHx = [email protected] tempy = inchol(as.matrix(y), kernel = 'rbfdot', kpar = list(sigma = 1/sig), maxiter = numCol) iCHy = [email protected] tempz = inchol(as.matrix(z), kernel = 'rbfdot', kpar = list(sigma = 1/sig), maxiter = numCol) iCHz = [email protected] a = svd(x = H%*%iCHx) Ux = a$u Sx = a$d b = svd(x = H%*%iCHy) Uy = b$u Sy = b$d c = svd(x = H%*%iCHz) Uz = c$u Sz = c$d if (length(Sx) != 1){ MSx <- diag(Sx^2) } else {MSx <- as.matrix(Sx^2)} if (length(Sy) != 1){ MSy <- diag(Sy^2) } else {MSy <- as.matrix(Sy^2)} if (length(Sz) != 1){ MSz <- diag(Sz^2/(Sz^2+eps)) } else {MSz <- as.matrix(Sz^2/(Sz^2+eps))} hsic = 1/(n*n)*sum(diag( Ux%*%((MSx%*%t(Ux))%*%(Uy%*%MSy))%*%t(Uy) -2*Ux%*%((((MSx%*%t(Ux))%*%(Uz%*%MSz))%*%t(Uz))%*%(Uy%*%MSy))%*%t(Uy) + Ux%*%((((MSx%*%t(Ux))%*%(Uz%*%MSz))%*%t(Uz))%*%(Uy%*%((MSy%*%t(Uy))%*%(Uz%*%MSz))))%*%t(Uz))) if (paral == 1){ pval.perm = lapply(X = 1:p, function(m, Ux, Sx, Uy, Sy, Uz, Sz, sig, numCol, numCluster) { t = kmeans(z,numCluster) perm = c(1:n) for (j in 1:numCluster){ perm[t$cluster==j] = perm[t$cluster==j][sample(sum(t$cluster==j))] } Uyp <- Uy[perm,] result = 1/(n*n)*sum(diag( Ux%*%((MSx%*%t(Ux))%*%(Uyp%*%MSy))%*%t(Uyp) -2*Ux%*%((((MSx%*%t(Ux))%*%(Uz%*%MSz))%*%t(Uz))%*%(Uyp%*%MSy))%*%t(Uyp) + Ux%*%((((MSx%*%t(Ux))%*%(Uz%*%MSz))%*%t(Uz))%*%(Uyp%*%((MSy%*%t(Uyp))%*%(Uz%*%MSz))))%*%t(Uz))) return ( result ) }, Ux=Ux, Sx=Sx, Uy=Uy, Sy=Sy, Uz=Uz, Sz=Sz, sig, numCol, numCluster=numCluster) } else { cl <- makeCluster(mc <- getOption('cl.cores',paral)) clusterEvalQ(cl, library(kernlab)) clusterEvalQ(cl, library(psych)) pval.perm <- parLapply(cl = cl, X = 1:p, function(m, Ux, Sx, Uy, Sy, Uz, Sz, sig, eps, numCol, numCluster) { m t <- kmeans(z,numCluster) perm <- c(1:n) for (j in 1:numCluster){ perm[t$cluster==j] <- perm[t$cluster==j][sample(sum(t$cluster==j))] } Uyp <- Uy[perm,] result <- 1/(n*n)*sum(diag( Ux%*%((diag(Sx^2)%*%t(Ux))%*%(Uyp%*%diag(Sy^2)))%*%t(Uyp) -2*Ux%*%((((diag(Sx^2)%*%t(Ux))%*%(Uz%*%diag(Sz^2/(Sz^2+eps))))%*%t(Uz))%*%(Uyp%*%diag(Sy^2)))%*%t(Uyp) + Ux%*%((((diag(Sx^2)%*%t(Ux))%*%(Uz%*%diag(Sz^2/(Sz^2+eps))))%*%t(Uz))%*%(Uyp%*%((diag(Sy^2)%*%t(Uyp))%*%(Uz%*%diag(Sz^2/(Sz^2+eps))))))%*%t(Uz))) return ( result ) }, Ux=Ux, Sx=Sx, Uy=Uy, Sy=Sy, Uz=Uz, Sz=Sz, sig=sig, eps=eps, numCol=numCol, numCluster=numCluster) stopCluster(cl) } pval.perm2 <- matrix(0,ncol=p) for (i in 1:p){pval.perm2[i]<-pval.perm[[i]]} pval <- mean(c(pval.perm2,hsic)>=hsic) HSMean <- mean(pval.perm2) HSVariance <- var(pval.perm2) names(hsic) <- "HSIC" names(HSMean) <-"HSIC mean" names(HSVariance) <- "HSIC variance" dataname <- paste("Cluster permutation approximation", sep = "") e <- list(method = paste("HSIC test of conditional independence", sep = ""), statistic = hsic, estimate = hsic, estimates = c(hsic,HSMean,HSVariance), p.value = pval, replicates = pval.perm2, data.name = dataname) class(e) <- "htest" return(e) }
function_to_pmml <- function(expr) { xformed <- .pmmlU(expr) return(xformed) }
heat.lin <- function(n, part) { shape <- 0:(n-1) return(shape) } heat.exp <- function(n, part, base=1.015) { shape <- base^(0:(n-1)) if(part == 2) shape <- max(shape) - rev(shape) return(shape) } heat <- function(colors=c(" n <- as.integer(n) if(length(colors) != 3) stop("'colors' must contain 3 color names or hexadecimal representations") if(n %% 2L == 1L) stop("'n' must be a multiple of 2") input <- col2rgb(colors) output <- matrix(as.integer(NA), nrow=nrow(input), ncol=n, dimnames=list(rownames(input), NULL)) for(channel in rownames(input)) { shape1 <- shapeFun(n=n/2L, part=1L, ...) shape2 <- shapeFun(n=n/2L, part=2L, ...) output[channel,] <- c( shape1 / max(shape1) * (input[channel,2L] - input[channel,1L]) + input[channel,1L], shape2 / max(shape2) * (input[channel,3L] - input[channel,2L]) + input[channel,2L] ) } output <- rgb(t(output), maxColorValue=255L) return(output) }
lumpedMatrix = function(mutmat, lump, afreq = attr(mutmat, 'afreq')) { als = colnames(mutmat) if(setequal(lump, als)) { newM = matrix(1, ncol=1, nrow=1, dimnames=list("lump", "lump")) mod = newMutationMatrix(newM, model = "trivial") return(mod) } if(!isLumpable(mutmat, lump)) stop2("The model is not lumpable for this set of alleles") keep = setdiff(als, lump) N = length(keep) + 1 lump_idx = match(lump, als) keep_idx = match(keep, als) newM = mutmat[c(keep, lump[1]), c(keep, lump[1])] newM[, N] = 1 - rowSums(newM[, 1:(N-1), drop = F]) colnames(newM)[N] = rownames(newM)[N] = "lump" if(!is.null(afreq)) { lumpedFreq = c(afreq[keep_idx], sum(afreq[lump_idx])) names(lumpedFreq) = colnames(newM) } else { lumpedFreq = NULL } newMutationMatrix(newM, afreq = lumpedFreq, lumpedAlleles = lump, model = attr(mutmat, 'model'), rate = attr(mutmat, 'rate'), seed = attr(mutmat, 'seed')) }
append_chains <- function(...) UseMethod("append_chains") append_chains.default <- function(...) { dots <- list(...) dots <- dots[sapply(dots, length) > 0L] if (coda::is.mcmc(dots[[1]])) do.call(append_chains.mcmc, dots) else if (coda::is.mcmc.list(dots[[1]])) do.call(append_chains.mcmc, dots) else stop("No method available to append these chains.", call. = FALSE) } append_chains.mcmc.list <- function(...) { dots <- list(...) if (length(dots) == 1L) return(dots[[1]]) nchains <- sapply(dots, coda::nchain) if (length(unique(nchains)) != 1) stop( "All mcmc.list objects must have the same number of chains. ", "The passed objects have ", paste(nchains, collapse = ", "), " respectively.", call. = FALSE ) ans <- vector("list", nchains[1]) for (i in 1:nchains[1]) ans[[i]] <- do.call(append_chains.mcmc, lapply(dots, "[[", i)) coda::as.mcmc.list(ans) } append_chains.mcmc <- function(...) { dots <- list(...) if (length(dots) == 1L) return(dots[[1]]) thin <- sapply(dots, coda::thin) if (length(unique(thin)) != 1L) stop("All `mcmc` objects have to have the same `thin` parameter.", "Observed: ", paste(thin, collapse=", "), " respectively.", call.=FALSE) nvar <- sapply(dots, coda::nvar) if (length(unique(nvar)) != 1L) stop("All `mcmc` objects have to have the same number of parameters.", "Observed: ", paste(nvar, collapse=", "), " respectively.", call.=FALSE) mcpar <- lapply(dots, coda::mcpar) start <- sapply(mcpar, "[[", 1) end <- sapply(mcpar, "[[", 2) rn <- lapply(dots, function(d) { as.integer(rownames(unclass(d))) }) midnames <- Map(function(rn., add) { as.character(rn. - rn.[1] + add + thin[1]) }, rn = rn[-1], add=cumsum(end[-length(end)]) ) rn <- c(as.character(rn[[1]]), unlist(midnames)) end[-1] <- end[-1] + thin[-1] - start[-1] dat <- do.call(rbind, unclass(dots)) rownames(dat) <- rn coda::mcmc( data = dat, start = start[1], end = sum(end), thin = thin[1] ) }
f <- '{"type":"Feature","properties":{"id":1,"name":"foo"},"geometry":{"type":"LineString","coordinates":[[101,0],[102,1]]}}' sf <- geojson_sf(f) wkt <- geojson_wkt(f) expect_true(all(names(sf) %in% c("id", "name","geometry"))) expect_true(all(names(wkt) %in% c("id","name","geometry"))) expect_true(sf$id == 1) expect_true(wkt$id == 1) expect_true(sf$name == "foo") expect_true(wkt$name == "foo") js <- '[{"type": "Feature", "properties" : {}, "geometry": { "type": "Polygon","coordinates": [[[-10.0, -10.0],[10.0, -10.0],[10.0, 10.0],[-10.0, -10.0]]]} },{"type": "Feature", "properties" : {"id":1}, "geometry": {"type": "MultiPolygon", "coordinates": [[[[180.0, 40.0], [180.0, 50.0], [170.0, 50.0],[170.0, 40.0], [180.0, 40.0]]], [[[-170.0, 40.0], [-170.0, 50.0], [-180.0, 50.0],[-180.0, 40.0], [-170.0, 40.0]]]]} },{"type": "FeatureCollection", "features": [{ "type": "Feature", "properties": {"id" : 2, "value" : "foo"}, "geometry": {"type": "Point","coordinates": [100.0, 0.0]} },{"type": "Feature", "properties": null, "geometry": { "type": "LineString", "coordinates": [[101.0, 0.0],[102.0, 1.0]]}}] },{"type": "GeometryCollection", "geometries": [ {"type": "Point","coordinates": [100.0, 0.0]}, {"type": "LineString","coordinates": [[101.0, 0.0],[102.0, 1.0]]}, {"type" : "MultiPoint","coordinates" : [[0,0],[1,1],[2,2]]} ]},{"type": "Polygon","coordinates": [[[-10.0, -10.0],[10.0, -10.0],[10.0, 10.0],[-10.0, -10.0]]]}]' sf <- geojson_sf(js) wkt <- geojson_wkt(js) expect_true(ncol(sf) == 3) expect_true(ncol(wkt) == 3) expect_true(sum(sf$id, na.rm = T) == 3) expect_true(sum(wkt$id, na.rm = T) == 3) expect_true(sf$value[!is.na(sf$value)] == "foo") expect_true(wkt$value[!is.na(wkt$value)] == "foo") f <- '{"type":"Feature","properties":{"id":1,"name":"foo"},"geometry":{"type":"LineString","coordinates":[[101,0],[102,1]]}}' sf <- geojson_sf(f) sfc <- geojson_sfc(f) expect_true(all(class(sf$geometry) == class(sfc))) js <- '{"type":"Point","coordinates":[null,null]}' expect_error( geojson_sf(js), "Invalid lon/lat object") js <- '{"type":"Point","coordinates":[,]}' expect_error(geojson_sf(js), "Invalid JSON") js <- '{"type":"Point","coordinates":[]}' expect_error(geojson_sf(js), "Invalid lon/lat object") js <- '{"type":"Point","coordinates":{}}' expect_error(geojson_sf(js), "No 'array' member at object index 0 - invalid GeoJSON") js <- '{"type","Feature","geometry":null}' expect_error(geojson_sf(js), "Invalid JSON") js <- '{"type","Feature","geometry":null,"properties":{}}' expect_error(geojson_sf(js), "Invalid JSON") js <- '{"type":"FeatureCollection","features":[ {"type":"Feature","properties":{"id":1},"geometry":{"type":"Point","coordinates":[0,0]}}, {"type":"Feature","properties":{"id":2},"geometry":null}]}' expect_true(nrow(geojson_sf(js)) == 2) js <- '{"type":"Feature","properties":{"id":2},"geometry": null}' expect_true(nrow(geojson_sf(js)) == 1) js <- '{"type":"FeatureCollection","features":[ {"type":"Feature","properties":{"id":1.0},"geometry":{"type":"MultiPoint","coordinates":[[0.0,0.0],[1.0,1.0]]}}, {"type":"Feature","properties":{"id":2.0},"geometry":{"type":"Point","coordinates":[0.0,0.0]}}, {"type":"Feature","properties":{"id":3.0},"geometry":null}]}' expect_true(nrow(geojson_sf(js)) == 3) expect_true(all(geojson_sf(js)[['id']] == 1:3)) sf <- geojson_sf(js) expect_true(all( is.na( as.numeric( sf$geometry[[3]] ) ) ) ) expect_true( as.character( sf_geojson( sf ) ) == gsub("\\t|\\n|\\r","",js) ) js <- '{"type":"FeatureCollection","features":[ {"type":"Feature","properties":{"id":3},"geometry":{"type":"MultiPoint","coordinates":[[0,0],[1,1]]}}, {"type":"Feature","properties":{"id":1},"geometry":null}, {"type":"Feature","properties":{"id":2},"geometry":{"type":"Point","coordinates":[0,0]}}]}' expect_true(nrow(geojson_sf(js)) == 3) expect_true(all(geojson_sf(js)[['id']] == c(3,1,2))) sf <- geojson_sf(js) expect_true(length(sf$geometry[[2]]) == 0) js <- '{"type":"Point","coordinates":null}' expect_error(geojson_sf(js), "No 'array' member at object index 0 - invalid GeoJSON") js <- '{"type":"FeatureCollection","features":[ {"type":"Feature","properties":{"id":3.0},"geometry":{"type":"MultiPoint","coordinates":[[0.0,0.0],[1.1,1.1]]}}, {"type":"Feature","properties":{"id":1.0},"geometry":null}, {"type":"Feature","properties":{"id":2.0},"geometry":{"type":"Point","coordinates":[0.0,0.0]}}]}' sf <- geojson_sf( js ) js2 <- sf_geojson( sf ) expect_true( as.character( js2 ) == gsub("\\t|\\r|\\n", "", js) ) sf2 <- geojson_sf( js2 ) expect_equal(sf, sf2) s <- geojson_sf( geo_melbourne ) g <- sf_geojson( s ) s2 <- geojson_sf( g ) expect_true( all( names(s) %in% names(s2) ) ) expect_true( all(s$AREASQKM == s2$AREASQKM) ) expect_true( all(s$SA2_NAME == s2$SA2_NAME) ) expect_true( all(s$SA3_NAME == s2$SA3_NAME) ) expect_true( all(s$fillColor == s2$fillColor) ) expect_true( all(s$polygonId == s2$polygonId) ) expect_true( all(s$strokeColor == s2$strokeColor) ) expect_true( all(s$strokeWeight == s2$strokeWeight) )
context("getG") for (nCores in seq_len(2)) { test_that(paste("getGi", "on", nCores, "cores"), { hasCores(nCores) n <- 10 p <- 100 X <- matrix(data = rnorm(n * p), nrow = n, ncol = p) for (chunkSize in c(NULL, p, ceiling(p / 3))) { G <- tcrossprod(scale(X)) G <- G / mean(diag(G)) G2 <- getG(X = X, scale = TRUE, scaleG = TRUE, chunkSize = chunkSize, nCores = nCores) expect_equivalent(G, G2) G <- tcrossprod(scale(X)) G2 <- getG(X = X, scale = TRUE, scaleG = FALSE, chunkSize = chunkSize, nCores = nCores) expect_equivalent(G, G2) G <- tcrossprod(scale(X, center = TRUE, scale = FALSE)) G <- G / mean(diag(G)) G2 <- getG(X = X, scale = FALSE, scaleG = TRUE, chunkSize = chunkSize, nCores = nCores) expect_equivalent(G, G2) G <- tcrossprod(scale(X, center = TRUE, scale = FALSE)) G2 <- getG(X = X, scale = FALSE, scaleG = FALSE, chunkSize = chunkSize, nCores = nCores) expect_equivalent(G, G2) G <- tcrossprod(X) G2 <- getG(X = X, center = FALSE, scale = FALSE, scaleG = FALSE, chunkSize = chunkSize, nCores = nCores) expect_equivalent(G, G2) } X[sample(1:length(X), size = 20)] <- NA G <- getG(X, nCores = nCores) expect_true(!any(is.na(G))) }) test_that(paste("getGij", "on", nCores, "cores"), { hasCores(nCores) n <- 10 p <- 100 X <- matrix(data = rnorm(n * p), nrow = n, ncol = p) for (chunkSize in c(NULL, p, ceiling(p / 3))) { i <- sample(1:nrow(X), size = 3) i2 <- sample(1:nrow(X), size = 4) centers <- colMeans(X) scales <- apply(X, 2, sd) * sqrt((n - 1)/n) G <- tcrossprod(scale(X)) G <- G / mean(diag(G)) G_12 <- getG(X = X, center = centers, scale = scales, scaleG = TRUE, i = i, i2 = i2, chunkSize = chunkSize, nCores = nCores) expect_equivalent(G[i, i2], G_12) G_12 <- getG(X = X, center = centers, scale = scales, scaleG = TRUE, i = i, i2 = i, chunkSize = chunkSize, nCores = nCores) expect_equivalent(G[i, i], G_12) G <- tcrossprod(scale(X) * sqrt(n/(n - 1))) G_12 <- getG(X = X, center = centers, scale = scales, scaleG = FALSE, i = i, i2 = i2, chunkSize = chunkSize, nCores = nCores) expect_equivalent(G[i, i2], G_12) G_12 <- getG(X = X, center = centers, scale = scales, scaleG = FALSE, i = i, i2 = i, chunkSize = chunkSize, nCores = nCores) expect_equivalent(G[i, i], G_12) scales <- rep(1, ncol(X)) G <- tcrossprod(scale(X, center = TRUE, scale = FALSE)) G <- G / ncol(X) G_12 <- getG(X = X, center = centers, scale = scales, scaleG = TRUE, i = i, i2 = i2, chunkSize = chunkSize, nCores = nCores) expect_equivalent(G[i, i2], G_12) G_12 <- getG(X = X, center = centers, scale = scales, scaleG = TRUE, i = i, i2 = i, chunkSize = chunkSize, nCores = nCores) expect_equivalent(G[i, i], G_12) G <- tcrossprod(scale(X, center = TRUE, scale = FALSE)) G_12 <- getG(X = X, center = centers, scale = scales, scaleG = FALSE, i = i, i2 = i2, chunkSize = chunkSize, nCores = nCores) expect_equivalent(G[i, i2], G_12) G_12 <- getG(X = X, center = centers, scale = scales, scaleG = FALSE, i = i, i2 = i, chunkSize = chunkSize, nCores = nCores) expect_equivalent(G[i, i], G_12) } }) test_that(paste("getG_symDMatrix", "on", nCores, "cores"), { hasCores(nCores) W <- matrix(data = rnorm(200), nrow = 10, ncol = 20) G1 <- tcrossprod(scale(W)) G1 <- G1 / mean(diag(G1)) G2 <- getG_symDMatrix(X = W, blockSize = ceiling(nrow(W) / 3), folderOut = testDir(), nCores = nCores) expect_equivalent(G2[], G1) }) }
prodestOP <- function(Y, fX, sX, pX, idvar, timevar, R = 20, cX = NULL, opt = 'optim', theta0 = NULL, cluster = NULL, tol = 1e-100, exit = FALSE){ Start = Sys.time() Y <- checkM(Y) fX <- checkM(fX) sX <- checkM(sX) pX <- checkM(pX) idvar <- checkM(idvar) timevar <- checkM(timevar) snum <- ncol(sX) fnum <- ncol(fX) if (!is.null(cX)) {cX <- checkM(cX); cnum <- ncol(cX)} else {cnum <- 0} polyframe <- data.frame(cbind(sX,pX)) mod <- model.matrix( ~ .^2 - 1, data = polyframe) mod <- mod[match(rownames(polyframe), rownames(mod)),] if (exit[1] == TRUE){ att = TRUE if (is.logical(exit)){ exitdata = data.frame(idvar = idvar, timevar = timevar) maxdate <- max(exitdata$timevar) exit <- as.matrix(do.call(rbind, lapply(split(exitdata, list(exitdata$idvar)), function(x){ maxid = max(x$timevar) x$ans <- x$timevar == maxid & maxid != maxdate cbind(x$ans) } ))) } else { exit <- checkMD(exit) } if ( (mean(exit) == 1) | (mean(exit) == 0) ){ stop("No ID appears to exit the sample. Check the exit variable or run the model without exit = TRUE") } else { lagProbitvars <- cbind(mod, sX^2, pX^2) for (i in 1:dim(lagProbitvars)[2]){ lagProbitvars[, i] <- lagPanel(lagProbitvars[, i], idvar = idvar, timevar = timevar) } probreg <- glm(exit ~ lagProbitvars, family = binomial(link = 'probit')) Pr.hat <- predict(probreg, newdata = as.data.frame(lagProbitvars), type = 'response') } } else { att = FALSE Pr.hat <- matrix(0, nrow = nrow(mod), ncol = 1) } regvars <- cbind(fX, cX, mod, sX^2, pX^2) lag.sX = sX for (i in 1:snum) { lag.sX[, i] = lagPanel(sX[, i], idvar = idvar, timevar = timevar) } data <- suppressWarnings(as.matrix(data.frame(state = sX, lag.sX = lag.sX, free = fX, Y = Y, idvar = idvar, timevar = timevar, regvars = regvars, Pr.hat = Pr.hat))) if (!is.null(cX)) { data <- suppressWarnings(as.matrix(data.frame(data, cX = cX))) } betas <- finalOPLP(ind = TRUE, data = data, fnum = fnum, snum = snum, cnum = cnum, opt = opt, theta0 = theta0, boot = FALSE, tol = tol, att = att) boot.indices <- block.boot.resample(idvar, R) if (is.null(cluster)){ nCores = NULL boot.betas <- matrix(unlist(lapply(boot.indices, finalOPLP, data = data, fnum = fnum, snum = snum, cnum = cnum, opt = opt, theta0 = theta0, boot = TRUE, tol = tol, att = att)), ncol = fnum+snum+cnum, byrow = TRUE) } else { nCores = length(cluster) clusterEvalQ(cl = cluster, library(prodest)) boot.betas <- matrix(unlist(parLapply(cl = cluster, boot.indices, finalOPLP, data = data, fnum = fnum, snum = snum, cnum = cnum, opt = opt, theta0 = theta0, boot = TRUE, tol = tol, att = att)), ncol = fnum+snum+cnum, byrow = TRUE) } boot.errors <- apply(boot.betas,2,sd,na.rm=TRUE) res.names <- c(colnames(fX, do.NULL = FALSE, prefix = 'fX'), colnames(sX, do.NULL = FALSE, prefix = 'sX') ) if (!is.null(cX)) {res.names <- c(res.names,colnames(cX, do.NULL = FALSE, prefix = 'cX'))} names(betas$betas) <- res.names names(betas$FSbetas)[2 : length(betas$FSbetas)] <- c(res.names, rep(" ", (length(betas$FSbetas) - length(res.names) - 1))) names(boot.errors) <- res.names elapsedTime = Sys.time() - Start out <- new("prod", Model = list(method = 'OP', FSbetas = betas$FSbetas, boot.repetitions = R, elapsed.time = elapsedTime, theta0 = theta0 , opt = opt, opt.outcome = betas$opt.outcome, nCores = nCores), Data = list(Y = Y, free = fX, state = sX, proxy = pX, control = cX, idvar = idvar, timevar = timevar, FSresiduals = betas$FSresiduals), Estimates = list(pars = betas$betas, std.errors = boot.errors)) return(out) } prodestLP <- function(Y, fX, sX, pX, idvar, timevar, R = 20, cX = NULL, opt = 'optim', theta0 = NULL, cluster = NULL, tol = 1e-100, exit = FALSE){ Start = Sys.time() Y <- checkM(Y) fX <- checkM(fX) sX <- checkM(sX) pX <- checkM(pX) idvar <- checkM(idvar) timevar <- checkM(timevar) snum <- ncol(sX) fnum <- ncol(fX) if (!is.null(cX)) {cX <- checkM(cX); cnum <- ncol(cX)} else {cnum <- 0} polyframe <- data.frame(cbind(sX,pX)) mod <- model.matrix( ~.^2-1, data = polyframe) mod <- mod[match(rownames(polyframe),rownames(mod)),] if (exit[1] == TRUE){ att = TRUE if (is.logical(exit)){ exitdata = data.frame(idvar = idvar, timevar = timevar) maxdate <- max(exitdata$timevar) exit <- as.matrix(do.call(rbind, lapply(split(exitdata, list(exitdata$idvar)), function(x){ maxid = max(x$timevar) x$ans <- x$timevar == maxid & maxid != maxdate cbind(x$ans) } ))) } else { exit <- checkMD(exit) } if ( (mean(exit) == 1) | (mean(exit) == 0) ){ stop("No ID appears to exit the sample. Check the exit variable or run the model without exit = TRUE") } else { lagProbitvars <- cbind(mod, sX^2, pX^2) for (i in 1:dim(lagProbitvars)[2]){ lagProbitvars[, i] <- lagPanel(lagProbitvars[, i], idvar = idvar, timevar = timevar) } probreg <- glm(exit ~ lagProbitvars, family = binomial(link = 'probit')) Pr.hat <- predict(probreg, newdata = as.data.frame(lagProbitvars), type = 'response') } } else { att = FALSE Pr.hat <- matrix(0, nrow = nrow(mod), ncol = 1) } regvars <- cbind(fX, cX, mod, sX^2, pX^2) lag.sX = sX for (i in 1:snum) { lag.sX[, i] = lagPanel(sX[, i], idvar = idvar, timevar = timevar) } data <- suppressWarnings(as.matrix(data.frame(state = sX, lag.sX = lag.sX, free = fX, Y = Y, idvar = idvar, timevar = timevar, regvars = regvars, Pr.hat = Pr.hat))) if (!is.null(cX)) { data <- suppressWarnings(as.matrix(data.frame(data, cX = cX))) } betas <- finalOPLP(ind = TRUE, data = data, fnum = fnum, snum = snum, cnum = cnum, opt = opt, theta0 = theta0, boot = FALSE, tol = tol, att = att) boot.indices <- block.boot.resample(idvar, R) if (is.null(cluster)){ nCores = NULL boot.betas <- matrix(NA, R, (fnum + snum + cnum)) for (i in 1:R){ boot.betas[i,] <- finalOPLP(ind = boot.indices[[i]], data = data, fnum = fnum, snum = snum, cnum = cnum, opt = opt, theta0 = theta0, boot = TRUE, tol = tol, att = att) } } else { nCores = length(cluster) clusterEvalQ(cl = cluster, library(prodest)) boot.betas <- matrix(unlist(parLapply(cl = cluster, boot.indices, finalOPLP, data = data, fnum = fnum, snum = snum, cnum = cnum, opt = opt, theta0 = theta0, boot = TRUE, tol = tol, att = att)), ncol = fnum + snum + cnum, byrow = TRUE) } boot.errors <- apply(boot.betas, 2, sd, na.rm = TRUE) res.names <- c(colnames(fX, do.NULL = FALSE, prefix = 'fX'), colnames(sX, do.NULL = FALSE, prefix = 'sX') ) if (!is.null(cX)) {res.names <- c(res.names,colnames(cX, do.NULL = FALSE, prefix = 'cX'))} names(betas$betas) <- res.names names(betas$FSbetas)[2 : length(betas$FSbetas)] <- c(res.names, rep(" ", (length(betas$FSbetas) - length(res.names) - 1))) names(boot.errors) <- res.names elapsedTime = Sys.time() - Start out <- new("prod", Model = list(method = 'LP', FSbetas = betas$FSbetas, boot.repetitions = R, elapsed.time = elapsedTime, theta0 = theta0 , opt = opt, opt.outcome = betas$opt.outcome, nCores = nCores), Data = list(Y = Y, free = fX, state = sX, proxy = pX, control = cX, idvar = idvar, timevar = timevar, FSresiduals = betas$FSresiduals), Estimates = list(pars = betas$betas, std.errors = boot.errors)) return(out) } finalOPLP <- function(ind, data, fnum, snum, cnum, opt, theta0, boot, tol, att){ if (sum(as.numeric(ind)) == length(ind)){ newid <- data[ind, 'idvar', drop = FALSE] } else { newid <- as.matrix(as.numeric(rownames(ind))) ind <- as.matrix(ind) } data <- data[ind,] first.stage <- lm(data[,'Y'] ~ data[,grepl('regvars', colnames(data))], na.action = na.exclude) fX <- data[,grepl('free', colnames(data)), drop = FALSE] phi <- fitted(first.stage) beta.free <- coef(first.stage)[2:(1 + fnum)] if (cnum != 0) { beta.control <- coef(first.stage)[(2 + fnum):(1 + fnum + cnum)] } else { beta.control <- NULL } if (is.null(theta0)) { theta0 <- coef(first.stage)[(2 + fnum):(1 + fnum + snum)] + rnorm((snum), 0, 0.01) } phi <- phi - (fX %*% beta.free) newtime <- data[,'timevar', drop = FALSE] rownames(phi) <- NULL rownames(newtime) <- NULL lag.phi <- lagPanel(value = phi, idvar = newid, timevar = newtime) res <- data[,'Y', drop = FALSE] - (fX %*% beta.free) state = data[, grepl('state', colnames(data)), drop = FALSE] lag.sX = data[, grepl('lag.sX', colnames(data)), drop = FALSE] Pr.hat <- data[, grepl('Pr.hat', colnames(data)), drop = FALSE] tmp.data <- model.frame(state ~ lag.sX + phi + lag.phi + res + Pr.hat) if (opt == 'optim'){ try.state <- try(optim(theta0, gOPLP, method = "BFGS", mX = tmp.data$state, mlX = tmp.data$lag.sX, vphi = tmp.data$phi, vlag.phi = tmp.data$lag.phi, vres = tmp.data$res, stol = tol, Pr.hat = tmp.data$Pr.hat, att = att), silent = TRUE) if (!inherits(try.state, "try-error")) { beta.state <- try.state$par opt.outcome <- try.state } else { beta.state <- matrix(NA,(snum),1) opt.outcome <- list(convergence = 99) } } else if (opt == 'DEoptim') { try.state <- try(DEoptim(fn = gOPLP, lower = c(theta0), upper = rep.int(1,length(theta0)), mX = tmp.data$state, mlX = tmp.data$lag.sX, vphi = tmp.data$phi, vlag.phi = tmp.data$lag.phi, vres = tmp.data$res, stol = tol, Pr.hat = tmp.data$Pr.hat, att = att, control = DEoptim.control(trace = FALSE)), silent = TRUE) if (!inherits(try.state, "try-error")) { beta.state <- try.state$optim$bestmem opt.outcome <- try.state } else { beta.state <- matrix(NA,(snum), 1) opt.outcome <- list(convergence = 99) } } else if (opt == 'solnp') { try.state <- try(suppressWarnings(solnp(theta0, gOPLP, mX = tmp.data$state, mlX = tmp.data$lag.sX, vphi = tmp.data$phi, vlag.phi = tmp.data$lag.phi, vres = tmp.data$res, stol = tol, Pr.hat = tmp.data$Pr.hat, att = att, control = list(trace = FALSE))), silent = TRUE) if (!inherits(try.state, "try-error")) { beta.state <- try.state$pars opt.outcome <- try.state } else { beta.state <- matrix(NA,(snum),1) opt.outcome <- list(convergence = 99) } } if (boot == FALSE){ return(list(betas = c(beta.free, beta.state, beta.control), opt.outcome = opt.outcome, FSbetas = coef(first.stage), FSresiduals = resid(first.stage))) } else{ return(c(beta.free, beta.state, beta.control)) } } gOPLP <- function(vtheta, mX, mlX, vphi, vlag.phi, vres, stol, Pr.hat, att){ Omega <- vphi - mX %*% vtheta Omega_lag <- vlag.phi - mlX %*% vtheta if (att == FALSE){ Omega_lag_pol <- cbind(1, Omega_lag, Omega_lag^2, Omega_lag^3) } else { Omega_lag_pol <- cbind(1, Omega_lag, Omega_lag^2, Omega_lag^3, Pr.hat, Pr.hat^2, Pr.hat^3, Pr.hat * Omega_lag, Pr.hat^2 * Omega_lag, Pr.hat * Omega_lag^2) } g_b <- solve(crossprod(Omega_lag_pol), tol = stol) %*% t(Omega_lag_pol) %*% Omega XI <- vres - (mX %*% vtheta) - (Omega_lag_pol %*% g_b) crit <- crossprod(XI) return(crit) }
classCode=function(value,indicator="fertility"){ if(indicator== "saltclass"){ classcode=ifelse(value<2,"None",ifelse(value<3,"Saline",ifelse(value<4,"Saline_sodic",ifelse(value<5,"Sodic",ifelse(value<6,"Alkaline","Class not included"))))) } else if(indicator=="saltseverity"){ class0=ifelse(value>4,"Alkaline",ifelse(value>3,"Sodic",ifelse(value>2,"saline_sodic",ifelse(value>1,"saline",ifelse(value>0,"None","Class not included"))))) class01 =ifelse(value>11,"ExtremeSalinity",ifelse(value>10,"VeryStrongSalinity",ifelse(value>9,"StrongSalinity",ifelse(value>8,"ModerateSalinity",ifelse(value>7,"SlightSalinity", ifelse(value>6,"SlightSalinity",ifelse(value>5,"None",class0))))))) class02=ifelse(value>16,"VeryStrongSodicity",ifelse(value>15,"StrongSodicity",ifelse(value>14,"ModerateSodicity",ifelse(value>13,"SlightSodicity",ifelse(value>12,"None",class01))))) classcode=ifelse(value>17,"None",ifelse(value>18,"class not included",class02)) } else if(indicator=="texture"){ classcode=ifelse(value==1,"Cl",ifelse(value==2,"SiCl",ifelse(value==3,"SiClLo",ifelse(value==4,"SiLo", ifelse(value==5,"SaLo",ifelse(value==6,"Si",ifelse(value==7,"ClLo",ifelse(value==8,"SaCl", ifelse(value==9,"SaClLo",ifelse(value==10,"LoSa",ifelse(value==11,"Lo",ifelse(value==12,"Sa", ifelse(value==13,"CSa",ifelse(value==14,"MSa",ifelse(value==15,"FSa",ifelse(value==16,"HCl", "Texture not included")))))))))))))))) } else if(indicator=="suitability"){ classcode=ifelse(value==1,"High",ifelse(value==2,"Moderate",ifelse(value==3,"Marginal",ifelse(value==4,"NotsuitableNow",ifelse(value==5,"Notsuitable", "Class not included"))))) } else if(indicator=="fertility"){ classcode=ifelse(value<1.449,"High",ifelse(value<2.449,"Moderate",ifelse(value<3.449,"Low",ifelse(value<4.5,"VeryLow","Class not included")))) } else if(indicator=="drainage"){ classcode=ifelse(value==1,"VPD",ifelse(value==2,"PDr",ifelse(value==3,"ImDr",ifelse(value==4,"MoDr",ifelse(value==5,"WDr",ifelse(value==6,"SDr",ifelse(value==7,"ExDr", "Class not included"))))))) } else if(indicator=="erodibility"){classcode=ifelse(value>0.01,"VeryLow",ifelse(value>0.1,"Low",ifelse(value>0.2,"Moderate",ifelse(value>0.6,"High",ifelse(value>0.7,"Extreme", "Class not included"))))) } else if(indicator=="permeability"){classcode=ifelse(value==1,"VerySlow",ifelse(value==2,"Slow",ifelse(value==3,"ModeratelySlow",ifelse(value==4,"Moderate",ifelse(value==5,"ModeratelyRapid",ifelse(value==6,"Rapid",ifelse(value==7,"VeryRapid","Class not included")))))))} else if(indicator=="structure"){ classcode=ifelse(structure==1,"Granular",ifelse(structure==2,"Crumby", ifelse(structure==3,"AngularBlocky",ifelse(structure==4,"Columnar", ifelse(structure==5,"SubAngularBlocky", ifelse(structure==6,"Platty",ifelse(structure==7,"SingleGrain",ifelse(structure==8,"Massive", ifelse(structure==9,"Prismatic",ifelse(structure==10,"Cloddy","Class not included")))))))))) } classcode=as.factor(classcode) return(classcode) }
signed_blockmodel <- function(g,k,alpha = 0.5,annealing = FALSE){ if(!"sign"%in%igraph::edge_attr_names(g)){ stop("network does not have a sign edge attribute") } if(missing(k)){ stop('argument "k" is missing, with no default') } A <- igraph::get.adjacency(g,"both","sign",sparse = TRUE) if(!annealing){ init_cluster <- sample(0:(k-1),nrow(A),replace = TRUE) res <- optimBlocks1(A,init_cluster,k,alpha) res$membership <- res$membership+1 } else{ init_cluster <- sample(1:k,nrow(A),replace = TRUE) tmp <- stats::optim(par = init_cluster, fn = blockCriterion1, A = A,alpha=alpha,k=k,gr = genclu,method = "SANN", control = list(maxit = 50000, temp = 100, tmax = 500, trace = FALSE, REPORT = 5)) tmp <- stats::optim(par = tmp$par, fn = blockCriterion1, A = A,alpha=alpha,k=k,gr = genclu,method = "SANN", control = list(maxit = 5000, temp = 5, tmax = 500, trace = FALSE, REPORT = 5)) res <- list(membership = tmp$par,criterion = tmp$value) } res } signed_blockmodel_general <- function(g,blockmat,alpha = 0.5){ if(!"sign"%in%igraph::edge_attr_names(g)){ stop("network does not have a sign edge attribute") } if(missing(blockmat)){ stop('argument "blockmat" is missing, with no default') } if(!all(blockmat%in%c(-1,1))){ stop('"blockmat" may only contain -1 and 1') } A <- igraph::get.adjacency(g,"both","sign",sparse = TRUE) init_cluster <- sample(0:(nrow(blockmat)-1),nrow(A),replace = TRUE) res <- optimBlocksSimS(A,init_cluster,blockmat,alpha) res$membership <- res$membership+1 res } genclu <- function(blocks,A,alpha,k){ v <- sample(1:length(blocks),1) clu <- 1:k clu <- clu[-blocks[v]] knew <- sample(clu,1) blocks[v] <- knew blocks }
setMethod('sampleRegular', signature(x='Raster'), function( x, size, ext=NULL, cells=FALSE, xy=FALSE, asRaster=FALSE, sp=FALSE, useGDAL=FALSE, ...) { stopifnot(hasValues(x) | isTRUE(xy)) size <- round(size) stopifnot(size > 0) nl <- nlayers(x) rotated <- rotated(x) if (is.null(ext)) { rcut <- raster(x) firstrow <- 1 lastrow <- nrow(rcut) firstcol <- 1 lastcol <- ncol(rcut) } else { rcut <- crop(raster(x), ext) ext <- extent(rcut) yr <- yres(rcut) xr <- xres(rcut) firstrow <- rowFromY(x, [email protected] *yr) lastrow <- rowFromY(x, ext@ymin+0.5*yr) firstcol <- colFromX(x, ext@xmin+0.5*xr) lastcol <- colFromX(x, [email protected]*xr) } allx <- FALSE if (size >= ncell(rcut)) { if (!is.null(ext)) { x <- crop(x, ext) } if (asRaster & !rotated) { return(x) } nr <- nrow(rcut) nc <- ncol(rcut) allx <- TRUE } else { Y <- X <- sqrt(ncell(rcut)/size) nr <- max(1, floor((lastrow - firstrow + 1) / Y)) nc <- max(1, floor((lastcol - firstcol + 1) / X)) rows <- (lastrow - firstrow + 1)/nr * 1:nr + firstrow - 1 rows <- rows - (0.5 * (lastrow - firstrow + 1)/nr) cols <- (lastcol - firstcol + 1)/nc * 1:nc + firstcol - 1 cols <- cols - (0.5 * (lastcol - firstcol + 1)/nc) cols <- unique(round(cols)) rows <- unique(round(rows)) cols <- cols[cols > 0] rows <- rows[rows > 0] nr <- length(rows) nc <- length(cols) } hv <- hasValues(x) if (fromDisk(x) & useGDAL & hv) { if ( any(rotated | .driver(x, FALSE) != 'gdal') ) { useGDAL <- FALSE } else { offs <- c(firstrow,firstcol)-1 reg <- c(nrow(rcut), ncol(rcut))-1 if ( nl > 1 ) { v <- matrix(NA, ncol=nl, nrow=prod(nr, nc)) for (i in 1:nl) { xx <- x[[i]] con <- rgdal::GDAL.open(xx@file@name, silent=TRUE) band <- bandnr(xx) vv <- rgdal::getRasterData(con, band=band, offset=offs, region.dim=reg, output.dim=c(nr, nc)) rgdal::closeDataset(con) if (xx@data@gain != 1 | xx@data@offset != 0) { vv <- vv * xx@data@gain + xx@data@offset } if (xx@file@nodatavalue < 0) { vv[vv <= xx@file@nodatavalue] <- NA } else { vv[vv == xx@file@nodatavalue] <- NA } v[, i] <- vv } } else { band <- bandnr(x) con <- rgdal::GDAL.open(x@file@name, silent=TRUE) v <- rgdal::getRasterData(con, band=band, offset=offs, region.dim=reg, output.dim=c(nr, nc)) rgdal::closeDataset(con) v <- matrix(v, ncol=1) colnames(v) <- names(x) if (x@data@gain != 1 | x@data@offset != 0) { v <- v * x@data@gain + x@data@offset } if (.naChanged(x)) { if (x@file@nodatavalue < 0) { v[v <= x@file@nodatavalue] <- NA } else { v[v == x@file@nodatavalue] <- NA } } } if (asRaster) { if (is.null(ext)) { outras <- raster(x) } else { outras <- raster(ext) crs(outras) <- crs(x) } nrow(outras) <- nr ncol(outras) <- nc if (nl > 1) { outras <- brick(outras, nl=nl) outras <- setValues(outras, v) } else { outras <- setValues(outras, as.vector(v)) } names(outras) <- names(x) if (any(is.factor(x))) { levels(outras) <- levels(x) } return(outras) } else { if (cells) { warning("'cells=TRUE' is ignored when 'useGDAL=TRUE'") } if (xy) { warning("'xy=TRUE' is ignored when 'useGDAL=TRUE'") } if (sp) { warning("'sp=TRUE' is ignored when 'useGDAL=TRUE'") } return( v ) } } } if (allx) { cell <- 1:ncell(rcut) } else { cell <- cellFromRowCol(x, rep(rows, each=nc), rep(cols, times=nr)) } if (asRaster) { if (rotated) { if (is.null(ext)) { outras <- raster(extent(x)) } else { outras <- raster(ext) crs(outras) <- crs(x) } ncol(outras) <- nc nrow(outras) <- nr xy <- xyFromCell(outras, 1:ncell(outras)) if (hv) { m <- .xyValues(x, xy) } else { m <- NA } } else { if (allx) { if (!is.null(ext)) { return(crop(x, ext)) } else { return(x) } } cell <- cellFromRowCol(x, rep(rows, each=nc), rep(cols, times=nr)) if (hv) { m <- .cellValues(x, cell) } else { m <- NA } if (is.null(ext)) { outras <- raster(x) } else { outras <- raster(ext) crs(outras) <- crs(x) } nrow(outras) <- nr ncol(outras) <- nc } if (nl > 1) { outras <- brick(outras, nl=nl) } outras <- setValues(outras, m) names(outras) <- names(x) if (any(is.factor(x))) { levels(outras) <- levels(x) } return(outras) } else { if (allx) { cell <= 1:ncell(rcut) } else { cell <- cellFromRowCol(x, rep(rows, each=nc), rep(cols, times=nr)) } m <- NULL nstart <- 1 if (xy) { m <- xyFromCell(x, cell) nstart <- 3 } if (cells) { m <- cbind(m, cell=cell) nstart <- nstart + 1 } if (hv) { m <- cbind(m, .cellValues(x, cell)) colnames(m)[nstart:(nstart+nl-1)] <- names(x) } if (sp) { if (hv) { m <- sp::SpatialPointsDataFrame(xyFromCell(x, cell), data.frame(m), proj4string=.getCRS(x)) } else { m <- sp::SpatialPoints(xyFromCell(x, cell), proj4string=.getCRS(x)) } } return(m) } } )
xnet<-function(Y,fm=suppressWarnings(require("network")),seed=1) { if(!is.null(seed)) { set.seed(seed) } if(fm) { x<-network::as.network(Y) n <- network::network.size(x) d <- network::as.matrix.network(x, matrix.type = "adjacency") d[is.na(d)] <- 0 d <- network::as.network(matrix(as.numeric(d > 0), n, n)) U<-network::network.layout.fruchtermanreingold(d,layout.par=NULL) } if(!fm) { Y0<-Y ; diag(Y0)<-1 U<-Re(eigen(Y0)$vec[,1:2]) } U<-sweep(U,2,apply(U,2,mean)) ; U<-sweep(U,2,apply(U,2,sd),"/") U }
source("ESEUR_config.r") rg=read.csv(paste0(ESEUR_dir, "reliability/RelGrowth.csv"), as.is=TRUE) ccf(rg$Total_failures, rg$Monthly_Sales, lag.max=4, ylab = "Cross-correlation\n")
GenBSpline <- function(x,nIntKnot=NULL,order=NULL) { if (is.null(nIntKnot)==TRUE) { nIntKnot <- 10 } if (is.null(order)==TRUE) { order <- 3 } if (nIntKnot < order) { stop('The number of knots should be greater than the order of B-spline basis.') } kOrder <- 0 n <- length(x) t0 <- seq(0,1,length.out=(nIntKnot+2))[-c(1,nIntKnot+2)] newB <- matrix(0,nrow=n,ncol=(nIntKnot+1)) t <- c(0,t0,1) for (i in 1:n) { for (k in 1:(nIntKnot)) { if (x[i] >= t[k] && x[i] < t[k+1]) { newB[i,k] <- 1 } if (x[i]>=t[nIntKnot+1]) newB[i,nIntKnot+1] <- 1 } } if (order == 0) { return(B=newB) } else { while (kOrder < order) { kOrder <- kOrder + 1 oldB <- cbind(rep(0,n),newB,rep(0,n)) newB <- matrix(0,nrow=n,ncol=(nIntKnot+1+kOrder)) t <- c(0,t,1) for (i in 1:n) { newB[i,1] <- (t[1+1+kOrder]-x[i])/(t[1+1+kOrder]-t[1+1])*oldB[i,1+1] for (k in 2:(nIntKnot+kOrder)) { newB[i,k] <- (x[i]-t[k])/(t[k+kOrder]-t[k])*oldB[i,k] + (t[k+1+kOrder]-x[i])/(t[k+1+kOrder]-t[k+1])*oldB[i,k+1] } newB[i,nIntKnot+1+kOrder] <- (x[i]-t[nIntKnot+1+kOrder])/(t[nIntKnot+1+2*kOrder]-t[nIntKnot+1+kOrder])*oldB[i,nIntKnot+1+kOrder] } } return(B=newB) } }
RCM_int <- function(OM, RCMdata, condition = c("catch", "catch2", "effort"), selectivity = "logistic", s_selectivity = "B", LWT = list(), comp_like = c("multinomial", "lognormal"), prior = list(), max_F = 3, cores = 1L, integrate = FALSE, mean_fit = FALSE, drop_nonconv = FALSE, drop_highF = FALSE, control = list(iter.max = 2e+05, eval.max = 4e+05), ...) { dots <- list(...) if(!is.null(dots$maxF)) max_F <- dots$maxF comp_like <- match.arg(comp_like) condition <- match.arg(condition) dat_update <- check_RCMdata(RCMdata, OM, condition) OM <- dat_update$OM RCMdata <- dat_update$RCMdata StockPars <- dat_update$StockPars FleetPars <- dat_update$FleetPars ObsPars <- dat_update$ObsPars nsim <- OM@nsim proyears <- OM@proyears maxage <- OM@maxage nyears <- RCMdata@Misc$nyears nfleet <- RCMdata@Misc$nfleet nsurvey <- RCMdata@Misc$nsurvey OM@maxF <- max_F message("OM@maxF updated to ", max_F, ".") if(!any(RCMdata@CAA > 0, na.rm = TRUE) && !any(RCMdata@CAL > 0, na.rm = TRUE)) { fix_sel <- TRUE message("No fishery length or age compositions were provided. Selectivity is fixed to values from OM.") } else { fix_sel <- FALSE } if(length(selectivity) == 1) selectivity <- rep(selectivity, RCMdata@Misc$nsel_block) if(length(selectivity) < RCMdata@Misc$nsel_block) stop("selectivity vector should be of length ", RCMdata@Misc$nsel_block, ").", call. = FALSE) sel <- int_sel(selectivity) if(nsurvey > 0) { if(is.null(s_selectivity)) s_selectivity <- rep("B", nsurvey) if(length(s_selectivity) == 1) s_selectivity <- rep(s_selectivity, nsurvey) s_sel <- int_s_sel(s_selectivity, nfleet) } else { s_sel <- int_s_sel("B") } RCMdata@Misc$LWT <- make_LWT(LWT, nfleet, nsurvey) message(ifelse(OM@SRrel == 1, "Beverton-Holt", "Ricker"), " stock-recruitment relationship used.") prior <- make_prior(prior, nsurvey, OM@SRrel, dots) par_identical_sims <- par_identical_sims_fn(StockPars, FleetPars, ObsPars, RCMdata, dots) if(!is.null(dots$resample) && dots$resample) { if(!requireNamespace("mvtnorm", quietly = TRUE)) stop("Please install the mvtnorm package.", call. = FALSE) message("\nResample = TRUE. Running mean fit model first...") mean_fit_output <- RCM_est(RCMdata = RCMdata, selectivity = sel, s_selectivity = s_sel, LWT = RCMdata@Misc$LWT, comp_like = comp_like, prior = prior, max_F = max_F, integrate = integrate, StockPars = StockPars, ObsPars = ObsPars, FleetPars = FleetPars, mean_fit = TRUE, dots = dots) if(length(mean_fit_output) > 0 && !mean_fit_output$report$conv) { warning("Mean fit model did not appear to converge. Will not be able to sample the covariance matrix.") message("Model did not converge. Returning the mean-fit model for evaluation.") drop_nonconv <- TRUE samps <- mean_fit_output$obj$env$last.par.best %>% matrix(nrow = nsim, ncol = length(mean_fit_output$obj$par), byrow = TRUE) } else { message("Model converged. Sampling covariance matrix for nsim = ", nsim, " replicates...") if(!all(par_identical_sims)) { message("Note: not all ", nsim, " replicates are identical.") message("These parameters should be identical among simulations: ", which(!par_identical_sims) %>% names() %>% paste0(collapse = " ")) } samps <- mvtnorm::rmvnorm(nsim, mean_fit_output$opt$par, mean_fit_output$SD$cov.fixed) } report_internal_fn <- function(x, samps, obj, conv) { report <- obj$report(samps[x, ]) %>% RCM_posthoc_adjust(obj, par = samps[x, ]) report$conv <- conv return(report) } res <- lapply(1:nsim, report_internal_fn, samps = samps, obj = mean_fit_output$obj, conv = mean_fit_output$report$conv) mod <- lapply(res, function(x) list(obj = mean_fit_output$obj, report = x)) conv <- rep(mean_fit_output$report$conv, nsim) } else { if(all(par_identical_sims)) { message("\nAll ", nsim, " replicates are identical. Fitting once and replicating single fit...") mean_fit_output <- RCM_est(RCMdata = RCMdata, selectivity = sel, s_selectivity = s_sel, LWT = RCMdata@Misc$LWT, comp_like = comp_like, prior = prior, max_F = max_F, integrate = integrate, StockPars = StockPars, ObsPars = ObsPars, FleetPars = FleetPars, mean_fit = TRUE, control = control, dots = dots) mod <- lapply(1:nsim, function(x) return(mean_fit_output)) } else { message("\nFitting model (", nsim, " simulations) ...") if(cores > 1 && !snowfall::sfIsRunning()) MSEtool::setup(as.integer(cores)) if(snowfall::sfIsRunning()) { mod <- snowfall::sfClusterApplyLB(1:nsim, RCM_est, RCMdata = RCMdata, selectivity = sel, s_selectivity = s_sel, LWT = RCMdata@Misc$LWT, comp_like = comp_like, prior = prior, max_F = max_F, integrate = integrate, StockPars = StockPars, ObsPars = ObsPars, FleetPars = FleetPars, control = control, dots = dots) } else { mod <- lapply(1:nsim, RCM_est, RCMdata = RCMdata, selectivity = sel, s_selectivity = s_sel, LWT = RCMdata@Misc$LWT, comp_like = comp_like, prior = prior, max_F = max_F, integrate = integrate, StockPars = StockPars, ObsPars = ObsPars, FleetPars = FleetPars, control = control, dots = dots) } if(mean_fit) { message("Generating additional model fit from mean values of parameters in the operating model...\n") mean_fit_output <- RCM_est(RCMdata = RCMdata, selectivity = sel, s_selectivity = s_sel, LWT = RCMdata@Misc$LWT, comp_like = comp_like, prior = prior, max_F = max_F, integrate = integrate, StockPars = StockPars, ObsPars = ObsPars, FleetPars = FleetPars, mean_fit = TRUE, control = control, dots = dots) if(!mean_fit_output$report$conv) warning("Mean fit model did not appear to converge.") } else mean_fit_output <- list() } res <- lapply(mod, getElement, "report") conv <- vapply(res, getElement, logical(1), name = "conv") } if(drop_highF) { highF <- vapply(res, function(x) max(getElement(x, "F"), na.rm = TRUE) >= max_F, logical(1)) if(sum(highF)) message(sum(highF), " out of ", nsim , " model fits had F on the upper boundary (F = ", max_F, "; ", round(100*sum(highF)/nsim, 2), "% of simulations).\n") conv <- conv & !highF } if(drop_nonconv) { NaF <- vapply(res, function(x) any(is.na(x$F) | is.infinite(x$F)), logical(1)) if(sum(NaF)) message(sum(NaF), " out of ", nsim , " iterations had F with NA's") conv <- conv & !NaF } if(sum(conv) < nsim) message("Non-converged iteration(s): ", paste(which(!conv), collapse = " "), "\n") if(!sum(conv)) { message("Non-converged for all iterations. Returning all for evaluation.") keep <- !logical(OM@nsim) } else if(sum(conv) < nsim && (drop_nonconv | drop_highF)) { message("Non-converged and/or highF iterations will be removed.\n") keep <- conv } else { keep <- !logical(OM@nsim) } OM@cpars$R0 <- vapply(res, getElement, numeric(1), "R0") message("Range of unfished age-0 recruitment (OM@cpars$R0): ", paste(round(range(OM@cpars$R0), 2), collapse = " - ")) initD <- vapply(res, function(x) x$E[1]/x$E0_SR, numeric(1)) message("Range of initial spawning depletion: ", paste(round(range(initD), 2), collapse = " - ")) OM@cpars$D <- vapply(res, function(x) x$E[length(x$E)-1]/x$E0_SR, numeric(1)) message("Range of spawning depletion (OM@cpars$D): ", paste(round(range(OM@cpars$D), 2), collapse = " - "), "\n") OM@isRel <- FALSE make_F <- function(x) { apicalF <- x$F apicalF[apicalF < 1e-4] <- 1e-4 F_at_age <- lapply(1:ncol(apicalF), function(xx) apicalF[, xx] * x$vul[1:nyears, , xx]) %>% simplify2array() %>% apply(1:2, sum) return(F_at_age) } F_matrix <- lapply(res, make_F) apical_F <- lapply(F_matrix, function(x) apply(x, 1, max)) expand_V_matrix <- function(x) { y <- matrix(x[nyears, ], proyears, maxage + 1, byrow = TRUE) rbind(x, y) } V <- Map("/", e1 = F_matrix, e2 = apical_F) %>% lapply(expand_V_matrix) OM@cpars$V <- simplify2array(V) %>% aperm(c(3, 2, 1)) OM@cpars$Find <- do.call(rbind, apical_F) message("Historical F and selectivity trends set in OM@cpars$Find and OM@cpars$V, respectively.") message("Selectivity during projection period is set to that in most recent historical year.") OM@cpars$qs <- rep(1, nsim) Eff <- apply(OM@cpars$Find, 2, range) OM@EffLower <- Eff[1, ] OM@EffUpper <- Eff[2, ] if(length(OM@EffYears) != nyears) OM@EffYears <- 1:nyears if(length(OM@Esd) == 0 && is.null(OM@cpars$Esd)) OM@Esd <- c(0, 0) message("Historical effort trends set in OM@EffLower and OM@EffUpper.\n") OM@cpars$Perr <- StockPars$procsd message("Recruitment standard deviation set in OM@cpars$Perr.") make_Perr <- function(x) { bias_corr <- ifelse(x$obj$env$data$est_rec_dev, exp(-0.5 * x$report$tau^2), 1) res <- exp(x$report$log_rec_dev) * bias_corr res[1] <- res[1] * x$report$R_eq/x$report$R0 return(res) } Perr <- do.call(rbind, lapply(mod, make_Perr)) make_early_Perr <- function(x) { res <- x$report$R_eq * x$report$NPR_equilibrium / x$report$R0 / x$report$NPR_unfished[1, ] bias_corr <- ifelse(x$obj$env$data$est_early_rec_dev, exp(-0.5 * x$report$tau^2), 1) early_dev <- exp(x$report$log_early_rec_dev) * bias_corr out <- res[-1] * early_dev return(rev(out)) } early_Perr <- do.call(rbind, lapply(mod, make_early_Perr)) OM@cpars$Perr_y <- StockPars$Perr_y OM@cpars$Perr_y[, 1:OM@maxage] <- early_Perr OM@cpars$Perr_y[, (OM@maxage+1):(OM@maxage + nyears)] <- Perr message("Historical recruitment set in OM@cpars$Perr_y.") log_rec_dev <- do.call(rbind, lapply(res, getElement, "log_rec_dev")) if(!all(log_rec_dev == 0)) { OM@cpars$AC <- apply(log_rec_dev, 1, function(x) { out <- acf(x, lag.max = 1, plot = FALSE)$acf[2] ifelse(is.na(out), 0, out) }) OM@AC <- range(OM@cpars$AC) message("Range of recruitment autocorrelation OM@AC: ", paste(round(range(OM@AC), 2), collapse = " - ")) sample_future_dev <- function() { if(!is.null(dots$map_log_rec_dev) && any(is.na(dots$map_log_rec_dev))) { yr_fixed_rec_dev <- which(is.na(dots$map_log_rec_dev)) if(any(yr_fixed_rec_dev > max(dots$map_log_rec_dev, na.rm = TRUE))) { yr_hist_sample <- yr_fixed_rec_dev[yr_fixed_rec_dev > max(dots$map_log_rec_dev, na.rm = TRUE)] %>% min() samp_hist <- Map(dev_AC, AC = OM@cpars$AC, stdev = StockPars$procsd, chain_start = log_rec_dev[, yr_hist_sample - 1], MoreArgs = list(n = length(yr_hist_sample:nyears), mu = 1)) log_rec_dev[, yr_hist_sample:nyears] <<- do.call(rbind, samp_hist) OM@cpars$Perr_y[, (OM@maxage + yr_hist_sample):(OM@maxage + nyears)] <<- exp(log_rec_dev[, yr_hist_sample:nyears]) message("Historical recruitment deviations sampled with autocorrelation starting in year ", yr_hist_sample, " out of OM@nyears = ", nyears) } } samp_proj <- Map(dev_AC, AC = OM@cpars$AC, stdev = StockPars$procsd, chain_start = log_rec_dev[, nyears], MoreArgs = list(n = proyears, mu = 1)) return(exp(do.call(rbind, samp_proj))) } OM@cpars$Perr_y[, (OM@maxage+nyears+1):ncol(OM@cpars$Perr_y)] <- sample_future_dev() message("Future recruitment deviations sampled with autocorrelation (in OM@cpars$Perr_y).\n") } OM@cpars$Len_age <- StockPars$Len_age OM@cpars$Linf <- StockPars$Linf OM@cpars$K <- StockPars$K OM@cpars$t0 <- StockPars$t0 OM@cpars$LenCV <- StockPars$LenCV OM@cpars$LatASD <- StockPars$LatASD OM@cpars$Wt_age <- StockPars$Wt_age if(any(apply(StockPars$Mat_age, 1, function(x) all(x >= 0.5)))) { OM@cpars$L50 <- StockPars$L50 OM@cpars$L95 <- StockPars$L95 } else { OM@cpars$Mat_age <- StockPars$Mat_age } if(prior$use_prior[2]) { OM@cpars$h <- vapply(res, getElement, numeric(1), "h") } else { OM@cpars$h <- StockPars$hs } if(prior$use_prior[3]) { OM@cpars$M_ageArray <- vapply(res, getElement, numeric(1), "Mest") %>% array(c(nsim, maxage+1, nyears + proyears)) } else { OM@cpars$M_ageArray <- StockPars$M_ageArray } if(any(RCMdata@CAL > 0, na.rm = TRUE) || (any(RCMdata@MS > 0, na.rm = TRUE) & RCMdata@MS_type == "length") || any(RCMdata@IAL > 0, na.rm = TRUE)) { OM@cpars$CAL_bins <- RCMdata@Misc$lbin OM@cpars$CAL_binsmid <- RCMdata@Misc$lbinmid message("RCM length bins will be added to OM.") } if(!is.null(dots$plusgroup) && !dots$plusgroup) OM@cpars$plusgroup <- 0L if(!any(RCMdata@I_sd > 0, na.rm = TRUE)) OM@cpars$Iobs <- ObsPars$Iobs message("Growth, maturity, natural mortality, and steepness values from RCM are set in OM@cpars.\n") RCMdata@Misc$prior <- prior output <- new("RCModel", OM = MSEtool::SubCpars(OM, keep), SSB = do.call(rbind, lapply(res[keep], getElement, "E")), NAA = lapply(res[keep], getElement, "N") %>% simplify2array() %>% aperm(c(3, 1, 2)), CAA = lapply(res[keep], getElement, "CAApred") %>% simplify2array() %>% aperm(c(4, 1:3)), CAL = lapply(res[keep], getElement, "CALpred") %>% simplify2array() %>% aperm(c(4, 1:3)), mean_fit = mean_fit_output, conv = conv[keep], data = RCMdata, Misc = res[keep]) output@config <- list(drop_sim = which(!keep)) if(sum(RCMdata@Chist > 0, na.rm = TRUE) || nsurvey > 0) { real_Data <- new("Data") real_Data@Year <- (output@OM@CurrentYr - output@OM@nyears + 1):output@OM@CurrentYr real_Data@LHYear <- max(real_Data@Year) real_Data@MaxAge <- maxage if(sum(RCMdata@Chist > 0, na.rm = TRUE) && all(!is.na(RCMdata@Chist))) { real_Data@Cat <- matrix(rowSums(RCMdata@Chist, na.rm = TRUE), 1, nyears) real_Data@CV_Cat <- sqrt(exp((rowSums(RCMdata@C_sd * RCMdata@Chist)/rowSums(RCMdata@Chist))^2 - 1)) %>% matrix(1, nyears) message("Historical catch data added to OM@cpars$Data@Cat.") if(nfleet > 1) message("Annual catch CV is a weighted average by fleet-specific catch.") } if(nfleet == 1) { if(sum(RCMdata@CAA, na.rm = TRUE)) { real_Data@CAA <- aperm(RCMdata@CAA, c(3, 1, 2)) message("Age comps added to OM@cpars$Data@CAA (nfleet = 1).") } if(sum(RCMdata@CAL, na.rm = TRUE)) { real_Data@CAL <- aperm(RCMdata@CAL, c(3, 1, 2)) real_Data@CAL_mids <- RCMdata@Misc$lbinmid real_Data@CAL_bins <- RCMdata@Misc$lbin message("Length comps added to OM@cpars$Data@CAL (nfleet = 1).") } } if(.hasSlot(real_Data, "AddInd") && nsurvey > 0) { real_Data@AddInd <- array(RCMdata@Index, c(nyears, nsurvey, output@OM@nsim)) %>% aperm(perm = c(3, 2, 1)) real_Data@CV_AddInd <- array(sqrt(exp(RCMdata@I_sd^2) - 1), c(nyears, nsurvey, output@OM@nsim)) %>% aperm(perm = c(3, 2, 1)) real_Data@AddIndType <- vapply(s_sel, process_AddIndType, numeric(1), nfleet = nfleet) real_Data@AddIndV <- lapply(1:nsurvey, process_AddIndV, Misc = output@Misc, s_sel = s_sel, n_age = maxage + 1, nfleet = nfleet, nyears = nyears) %>% simplify2array() %>% aperm(c(1, 3, 2)) real_Data@AddIunits <- RCMdata@I_units output@OM@cpars$AddIbeta <- matrix(1, output@OM@nsim, nsurvey) message("Historical indices added to OM@cpars$Data@AddInd.") } output@OM@cpars$Data <- real_Data } if(RCMdata@Misc$condition == "catch2") { catch_check_fn <- function(x, report, data) { if(report[[x]]$conv) { catch_diff <- report[[x]]$Cpred/RCMdata@Chist - 1 flag <- max(abs(catch_diff), na.rm = TRUE) > 0.01 | any(is.na(report[[x]]$Cpred)) } else { flag <- FALSE } return(flag) } do_catch_check <- vapply(1:length(res), catch_check_fn, logical(1), report = res, data = data) if(any(do_catch_check)) { flag_ind <- paste(which(do_catch_check), collapse = " ") message("Note: there is predicted catch that deviates from observed catch by more than 1% in simulations:") message(flag_ind) } } message("Complete.") return(output) } process_AddIndType <- function(s_sel, nfleet) { if(s_sel == -4 || s_sel == -2 || s_sel == -1 || s_sel == 0) { return(1) } else if(s_sel == -3) { return(2) } else { return(ifelse(nfleet > 1, 1, 3)) } } process_AddIndV <- function(sur, Misc, s_sel, n_age, nfleet, nyears) { if(s_sel[sur] < -2 || (s_sel[sur] == 1 & nfleet == 1)) { out <- matrix(1, length(Misc), n_age) } else { out <- do.call(rbind, lapply(Misc, function(x) x$ivul[nyears, , sur])) } return(out) } RCM_retro <- function(x, nyr = 5) { if(length(x@mean_fit) == 0) stop("Re-run RCM() with argument `mean_fit = TRUE`", .call = FALSE) data <- x@mean_fit$obj$env$data params <- x@mean_fit$obj$env$parameters n_y <- data$n_y map <- x@mean_fit$obj$env$map if(data$nfleet > 1) { retro_ts <- array(NA, dim = c(nyr+1, n_y + 1, data$nfleet + 4)) TS_var <- c(paste("Fleet", 1:data$nfleet, "F"), "Apical F", "SSB", "SSB_SSB0", "R") } else { retro_ts <- array(NA, dim = c(nyr+1, n_y + 1, 4)) TS_var <- c("Apical F", "SSB", "SSB_SSB0", "R") } dimnames(retro_ts) <- list(Peel = 0:nyr, Year = (x@OM@CurrentYr - n_y):x@OM@CurrentYr + 1, Var = TS_var) new_args <- lapply(n_y - 0:nyr, RCM_retro_subset, data = data, params = params, map = map) lapply_fn <- function(i, new_args, x) { obj2 <- MakeADFun(data = new_args[[i+1]]$data, parameters = new_args[[i+1]]$params, map = new_args[[i+1]]$map, random = x@mean_fit$obj$env$random, DLL = "SAMtool", silent = TRUE) if(new_args[[i+1]]$data$condition == "catch2") { if(any(is.na(obj2$report(obj2$par)$F)) || any(is.infinite(obj2$report(obj2$par)$F))) { for(ii in 1:10) { obj2$par["R0x"] <- 0.5 + obj2$par["R0x"] if(all(!is.na(obj2$report(obj2$par)$F)) && all(!is.infinite(obj2$report(obj2$par)$F))) break } } } mod <- optimize_TMB_model(obj2, control = list(iter.max = 2e+05, eval.max = 4e+05), restart = 0) opt2 <- mod[[1]] SD <- mod[[2]] if(!is.character(opt2)) { report <- obj2$report(obj2$env$last.par.best) %>% RCM_posthoc_adjust(obj2, dynamic_SSB0 = FALSE) FMort <- rbind(report$F, matrix(NA, i + 1, ncol(report$F))) if(data$nfleet > 1) FMort <- cbind(FMort, apply(report$F_at_age, 1, max, na.rm = TRUE) %>% c(rep(NA, i+1))) SSB <- c(report$E, rep(NA, i)) SSB_SSB0 <- SSB/report$E0_SR R <- c(report$R, rep(NA, i)) retro_ts[i+1, , ] <<- cbind(FMort, SSB, SSB_SSB0, R) return(SD$pdHess) } return(FALSE) } conv <- vapply(0:nyr, lapply_fn, logical(1), new_args = new_args, x = x) if(any(!conv)) warning("Peels that did not converge: ", paste0(which(!conv) - 1, collapse = " ")) retro <- new("retro", Model = "RCM", Name = x@OM@Name, TS_var = TS_var, TS = retro_ts) if(data$nfleet > 1) { attr(retro, "TS_lab") <- c(paste("Fishing mortality of Fleet", 1:data$nfleet), "Apical F", "Spawning biomass", "Spawning depletion", "Recruitment") } else { attr(retro, "TS_lab") <- c(paste("Fishing mortality of Fleet", 1:data$nfleet), "Spawning biomass", "Spawning depletion", "Recruitment") } return(retro) } RCM_retro_subset <- function(yr, data, params, map) { data_out <- structure(data, check.passed = NULL) params_out <- lapply(params, function(x) if(!is.null(attr(x, "map"))) attr(x, "shape") else x) if(yr < data$n_y) { mat <- c("C_hist", "E_hist", "I_hist", "sigma_I", "sigma_C", "CAA_n", "CAL_n", "IAA_n", "IAL_n", "msize") if(!is.null(map$log_M)) mat <- c(mat, "M_data") mat_ind <- match(mat, names(data_out)) data_out[mat_ind] <- lapply(data_out[mat_ind], function(x) x[1:yr, , drop = FALSE]) mat2 <- c("len_age", "wt", "mat", "sel_block") mat_ind2 <- match(mat2, names(data_out)) data_out[mat_ind2] <- lapply(data_out[mat_ind2], function(x) x[1:(yr+1), , drop = FALSE]) data_out$nsel_block <- data_out$sel_block %>% as.vector() %>% unique() %>% length() data_out$n_y <- yr arr <- c("CAA_hist", "CAL_hist", "IAA_hist", "IAL_hist") arr_ind <- match(arr, names(data_out)) data_out[arr_ind] <- lapply(data_out[arr_ind], function(x) x[1:yr, , , drop = FALSE]) data_out$est_rec_dev <- data_out$est_rec_dev[1:yr] params_out$log_rec_dev <- params_out$log_rec_dev[1:yr] if(!is.null(map$log_rec_dev)) map$log_rec_dev <- map$log_rec_dev[1:yr] %>% factor() if(data_out$condition == "catch") { params_out$log_F_dev <- params_out$log_F_dev[1:yr, , drop = FALSE] if(any(data_out$yind_F + 1 > yr)) { data_out$yind_F <- as.integer(0.5 * yr) params_out$log_F_dev[data_out$yind_F + 1, ] <- params$log_F_dev[data$yind_F + 1, ] } } if(data$nsel_block > data_out$nsel_block) { sel_block_ind <- data_out$sel_block %>% as.vector() %>% unique() params_out$vul_par <- params_out$vul_par[, sel_block_ind, drop = FALSE] if(!is.null(map$vul_par)) map$vul_par <- map$vul_par[, sel_block_ind, drop = FALSE] %>% factor() } } return(list(data = data_out, params = params_out, map = map)) } profile_likelihood_RCM <- function(x, ...) { dots <- list(...) if(!length(x@mean_fit)) stop("No model found. Re-run RCM with mean_fit = TRUE.") data <- x@mean_fit$obj$env$data params <- x@mean_fit$obj$env$parameters n_y <- data$n_y map <- x@mean_fit$obj$env$map LWT <- try(x@data@Misc$LWT, silent = TRUE) if(is.character(LWT)) LWT <- x@data$LWT new_args <- RCM_retro_subset(n_y, data = data, params = params, map = map) if(!is.null(dots$D)) { if(length(dots) > 1) message("Only doing depletion profile...") if(!requireNamespace("abind", quietly = TRUE)) { stop("Please install the abind package to run this profile.") } if(!requireNamespace("reshape2", quietly = TRUE)) { stop("Please install the reshape2 package to run this profile.") } profile_grid <- expand.grid(D = dots$D) new_args$data$IAA_hist <- abind::abind(new_args$data$IAA_hist, array(NA, c(n_y, new_args$data$n_age, 1)), along = 3) new_args$data$IAL_hist <- abind::abind(new_args$data$IAL_hist, array(NA, c(n_y, length(new_args$data$lbinmid), 1)), along = 3) new_args$data$IAA_n <- cbind(new_args$data$IAA_n, rep(0, n_y)) new_args$data$IAL_n <- cbind(new_args$data$IAL_n, rep(0, n_y)) new_args$data$nsurvey <- new_args$data$nsurvey + 1 new_args$data$ivul_type <- c(new_args$data$ivul_type, -3) new_args$data$abs_I <- c(new_args$data$abs_I, 0) new_args$data$I_units <- c(new_args$data$I_units, 1) new_args$data$LWT_index <- rbind(new_args$data$LWT_index, rep(1, 3)) new_args$data$use_prior <- c(new_args$data$use_prior, 0) new_args$data$prior_dist <- rbind(new_args$data$prior_dist, rep(NA_real_, 2)) new_args$params$ivul_par <- cbind(new_args$params$ivul_par, rep(0, nrow(new_args$params$ivul_par))) if(!is.null(new_args$map$ivul_par)) { new_args$map$ivul_par <- factor(c(new_args$map$ivul_par, rep(NA, nrow(new_args$params$ivul_par)))) } LWT$Index <- c(LWT$Index, 1) LWT$IAA <- c(LWT$IAA, 1) LWT$IAL <- c(LWT$IAL, 1) profile_fn <- function(i, new_args, x) { SSB_index <- SSB_Isd <- rep(NA_real_, n_y) SSB_index[1] <- 1 SSB_index[n_y] <- profile_grid$D[i] SSB_Isd[c(1, n_y)] <- 0.01 new_args$data$I_hist <- cbind(new_args$data$I_hist, SSB_index) new_args$data$sigma_I <- cbind(new_args$data$sigma_I, SSB_Isd) obj2 <- MakeADFun(data = new_args$data, parameters = new_args$params, map = new_args$map, random = x@mean_fit$obj$env$random, DLL = "SAMtool", silent = TRUE) mod <- optimize_TMB_model(obj2, control = list(iter.max = 2e+05, eval.max = 4e+05), restart = 0) report <- obj2$report(obj2$env$last.par.best) RCM_get_likelihoods(report, LWT = LWT, f_name = paste0("Fleet_", 1:new_args$data$nfleet), s_name = paste0("Index_", 1:(new_args$data$nsurvey-1)) %>% c("SSB_depletion")) } do_profile <- lapply(1:nrow(profile_grid), profile_fn, new_args = new_args, x = x) profile_grid$nll <- vapply(do_profile, function(xx) xx[[1]][1, 1], numeric(1)) prof <- sapply(do_profile, nll_depletion_profile) %>% t() prof_out <- apply(prof, 2, sum) %>% as.logical() profile_grid <- cbind(profile_grid, prof[, prof_out] %>% as.data.frame()) output <- new("prof", Model = "RCM", Par = "D", MLE = x@mean_fit$report$E[n_y]/x@mean_fit$report$E0_SR, grid = profile_grid) } else { if(is.null(dots$R0) && is.null(dots$h)) stop("Sequence of neither D, R0, nor h was found. See help file.") if(!is.null(dots$R0)) { R0 <- dots$R0 } else { R0 <- x@mean_fit$report$R0 profile_par <- "h" } if(!is.null(dots$h)) { h <- dots$h } else { h <- x@mean_fit$report$h profile_par <- "R0" } profile_grid <- expand.grid(R0 = R0, h = h) joint_profile <- !exists("profile_par", inherits = FALSE) profile_fn <- function(i, new_args, x) { new_args$params$R0x <- log(profile_grid$R0[i] * new_args$data$rescale) if(new_args$data$SR_type == "BH") { new_args$params$transformed_h <- logit((profile_grid$h[i] - 0.2)/0.8) } else { new_args$params$transformed_h <- log(profile_grid$h[i] - 0.2) } if(joint_profile) { new_args$map$R0x <- new_args$map$transformed_h <- factor(NA) } else { if(profile_par == "R0") new_args$map$R0x <- factor(NA) else new_args$map$transformed_h <- factor(NA) } obj2 <- MakeADFun(data = new_args$data, parameters = new_args$params, map = new_args$map, random = x@mean_fit$obj$env$random, DLL = "SAMtool", silent = TRUE) mod <- optimize_TMB_model(obj2, control = list(iter.max = 2e+05, eval.max = 4e+05), restart = 0) report <- obj2$report(obj2$env$last.par.best) RCM_get_likelihoods(report, LWT = LWT, f_name = paste0("Fleet_", 1:new_args$data$nfleet), s_name = paste0("Index_", 1:new_args$data$nsurvey)) } do_profile <- lapply(1:nrow(profile_grid), profile_fn, new_args = new_args, x = x) profile_grid$nll <- vapply(do_profile, function(xx) xx[[1]][1, 1], numeric(1)) prof <- sapply(do_profile, nll_depletion_profile) %>% t() prof_out <- apply(prof, 2, sum) %>% as.logical() profile_grid <- cbind(profile_grid, prof[, prof_out] %>% as.data.frame()) if(joint_profile) { pars <- c("R0", "h") MLE <- c(x@mean_fit$report$R0, x@mean_fit$report$h) } else { pars <- profile_par MLE <- getElement(x@mean_fit$report, pars) } output <- new("prof", Model = "RCM", Par = pars, MLE = MLE, grid = profile_grid) } return(output) } nll_depletion_profile <- function(xx) { nll_fleet <- xx[[2]][-nrow(xx[[2]]), ] %>% select(starts_with("Fleet")) nll_fleet$Data <- rownames(nll_fleet) nll_fleet <- reshape2::melt(nll_fleet, id.var = "Data", value.var = "nll") nll_index <- xx[[4]][-nrow(xx[[4]]), ] %>% select(starts_with("Index")) nll_index$Data <- rownames(nll_index) nll_index <- reshape2::melt(nll_index, id.var = "Data", value.var = "nll") nll <- rbind(nll_fleet, nll_index) nll$Name <- paste(nll$variable, nll$Data) c(nll$value, xx[[1]][c(2, 5, 6), 1]) %>% structure(names = paste(nll$variable, nll$Data) %>% c("Recruitment Deviations", "Penalty", "Prior")) }
knitr::opts_chunk$set( collapse = TRUE, comment = " ) library(igate) set.seed(123) n <- nrow(iris)*2/3 rows <- sample(1:nrow(iris), n) df <- iris[rows, ] results <- igate(df, target = "Sepal.Length", good_end = "high", savePlots = TRUE) results igate.regressions(df, target = "Sepal.Length", ssv = results$Causes, savePlots = TRUE) validation_df <- iris[-rows,] val <- validate(iris, target = "Sepal.Length", causes = results$Causes, results_df = results) head(val[[1]]) val[[2]] val[[3]]
ve <- 2 fn <- NULL rf <- c("def-model.RDS", "validate-clean.txt") em <- EnvManager$new(ve = ve, rp = "./") ed <- em$setup_env(rf, fn) mfn <- paste0(ed, "/def-model.RDS") vfn <- paste0(ed, "/validate-clean.txt") me <- ModelEvaluator$new(mf = mfn, ve = ve) stats <- me$intrinsic_evaluation(lc = 20, fn = vfn) print(stats) em$td_env()
prep_fa <- function(df_fa){ cc <- NA use <- NA fa_names <- NA if(!(is.data.frame(df_fa) | is.list(df_fa))){ err_code <- 1 err_message <- "The fatty acid data are not in a valid data frame." return(list(cc = cc, use = use, fa_names = fa_names, err_code = err_code, err_message = err_message)) } to_use <- df_fa[1,] == 1 if(sum(to_use) != 2){ err_code <- 2 err_message <- paste("One and only one set of calibration coefficients and", "fatty acid suites must be selected.", sep=" ") return(list(cc = cc, use = use, fa_names = fa_names, err_code = err_code, err_message = err_message)) } cc_to_use <- max.col(to_use, "first") fa_to_use <- max.col(to_use, "last") cc <- df_fa[,cc_to_use][-1] use <- as.logical(df_fa[,fa_to_use][-1]) fa_names <- as.character(df_fa[,1][-1]) if(sum(use) < 2){ err_code <- 3 err_message <- "The number of fatty acids to use must exceed 1." return(list(cc = cc, use = use, fa_names = fa_names, err_code = err_code, err_message = err_message)) } err_code <- 0 err_message <- "Success!" return(list(cc = cc, use = use, fa_names = fa_names, err_code = err_code, err_message = err_message)) }
gibbs_met <- function(log_f,no_var,ini_value,iters,iters_per.iter=1,iters_met, stepsizes_met, ...) { if(no_var != length(ini_value)) stop("The number of variables in initial values does NOT match no_var") if(!is.finite(log_f(ini_value,...))) stop("The initial value has 0 probability") chain <- matrix(0, iters + 1, no_var) chain[1,] <- ini_value gibbs_update_per.iter_per.par <- function(iter, i_par) { log_f_condition <- function(x_i) { x <- chain[iter,] x[i_par] <- x_i log_f(x,...) } chain[iter,i_par] <<- met_gaussian(log_f=log_f_condition, iters=iters_met,no_var=1, ini_value=chain[iter,i_par], stepsizes_met=stepsizes_met[i_par])[iters_met+1] } gibbs_update_per.iter <- function(iter) { chain[iter,] <<- chain[iter-1,] replicate(iters_per.iter, sapply(1:no_var,gibbs_update_per.iter_per.par,iter=iter) ) } sapply(seq(2,iters+1), gibbs_update_per.iter) chain } met_gaussian <- function(log_f, no_var, ini_value, iters,iters_per.iter=1,stepsizes_met, ...) { if(no_var != length(ini_value)) stop("The number of variables in initial values does NOT match p") if(!is.finite(log_f(ini_value,...))) stop("The initial value has 0 probability") chain <- matrix(0,iters+1,no_var) chain[1,] <- ini_value old_log_f <- log_f(ini_value,...) one_transition <- function(i) { chain[i,] <<- chain[i-1,] i_inside <- 0 repeat{ i_inside <- i_inside + 1 x_prop <- rnorm(no_var) * stepsizes_met + chain[i,] new_log_f <- log_f(x_prop,...) if(log(runif(1)) < new_log_f - old_log_f) { chain[i,] <<- x_prop old_log_f <<- new_log_f } if(i_inside == iters_per.iter) break } } sapply(seq(2,iters+1),one_transition) chain }
expected <- eval(parse(text="structure(list(dim = c(1L, 1L), a = c(NA, 3, -1, 2), class = structure(\"B\", package = \".GlobalEnv\")), .Names = c(\"dim\", \"a\", \"class\"))")); test(id=0, code={ argv <- eval(parse(text="list(structure(1, .Dim = c(1L, 1L), a = c(NA, 3, -1, 2), class = structure(\"B\", package = \".GlobalEnv\")))")); do.call(`attributes`, argv); }, o=expected);
X <- rbind(diag(8), -diag(8)) * sqrt(8) beta <- c(-1,-1,-1,-1,2,2,2,2) y <- as.numeric(X %*% beta) group <- c(1,1,1,1,2,2,2,2) fit <- grpreg(X, y, group, lambda=c(2, 1.999999, 1, 0)) expect_equal(predict(fit, type='nvars', which=2), 4) expect_equivalent(coef(fit, lambda=0), c(0, beta)) expect_equivalent(coef(fit, lambda=1), c(0, 0, 0, 0, 0, 1, 1, 1, 1))
"Hastings.coeff" <- function(object,...){ UseMethod("Hastings.coeff") }
context("Wavelet clustering (wclust)") t1 <- cbind(1:100, sin(seq(0, 10 * 2 * pi, length.out = 100))) t2 <- cbind(1:100, sin(seq(0, 10 * 2 * pi, length.out = 100) + 0.1 * pi)) t3 <- cbind(1:100, rnorm(100)) wt.t1 <- wt(t1) wt.t2 <- wt(t2) wt.t3 <- wt(t3) w.arr <- array(dim = c(3, NROW(wt.t1$wave), NCOL(wt.t1$wave))) w.arr[1, , ] <- wt.t1$wave w.arr[2, , ] <- wt.t2$wave w.arr[3, , ] <- wt.t3$wave test_that("Basic test of wclust without progress bar", { c <- wclust(w.arr, quiet = TRUE) expect_true(is.matrix(c$diss.mat)) expect_equal(dim(c$diss.mat), c(3,3)) expect_equal(class(c$dist.mat), "dist") }) test_that("Progressbar should not cause errors", { expect_output( out <- wclust(w.arr), regexp = "\\|=+=\\| 100%" ) })
d = read.csv('https://raw.githubusercontent.com/m-clark/Datasets/master/us%20cpi/USCPI.csv', header=F) inflation = d[,1] summary(inflation) statespaceEM = function( params, y, omega2_0, omega2, tol = .00001, maxits = 100, showits = T ) { require(spam) n = length(y) sigma2 = params$sigma2 H = diag(n) for (i in 1:(ncol(H) - 1)) { H[i + 1, i] = -1 } Omega2 = as.spam(diag(omega2, n)) Omega2[1, 1] = omega2_0 H = as.spam(H) HinvOmega2H = t(H) %*% chol2inv(chol(Omega2)) %*% H it = 0 converged = FALSE if (showits) cat(paste("Iterations of EM:", "\n")) while ((!converged) & (it < maxits)) { sigma2Old = sigma2[1] Sigma2invOld = diag(n)/sigma2Old K = HinvOmega2H + Sigma2invOld tau = solve(K, y/sigma2Old) K_inv_tr = sum(1/eigen(K)$values) sigma2 = 1/n * (K_inv_tr + crossprod(y-tau)) converged = max(abs(sigma2 - sigma2Old)) <= tol it = it + 1 if (showits & it == 1 | it%%5 == 0) cat(paste(format(it), "...", "\n", sep = "")) } Kfinal = HinvOmega2H + diag(n) / sigma2[1] taufinal = solve(K, (y / sigma2[1])) out = list(sigma2 = sigma2, tau = taufinal) } ssMod_1 = statespaceEM( params = data.frame(sigma2 = var(inflation)), y = inflation, tol = 1e-4, omega2_0 = 9, omega2 = 1 ^ 2 ) ssMod_.5 = statespaceEM( params = data.frame(sigma2 = var(inflation)), y = inflation, tol = 1e-4, omega2_0 = 9, omega2 = .5 ^ 2 ) ssMod_1$sigma2 ssMod_.5$sigma2 library(lubridate) series = ymd(paste0(rep(1947:2014, e = 4), '-', c('01', '04', '07', '10'), '-', '01')) seriestext = series[1:length(inflation)] library(tidyverse) data.frame( series = series[1:length(inflation)], inflation, Mod_1 = ssMod_1$tau, Mod_.5 = ssMod_.5$tau ) %>% ggplot(aes(x = series, y = inflation)) + geom_point(color = 'gray50') + geom_line(aes(y = Mod_1), color = ' geom_line(aes(y = Mod_.5), color = 'skyblue3') + scale_x_date(date_breaks = '10 years') + theme_light()
plot.loadings <- function(x, reorder = TRUE, gray=FALSE, grey=FALSE, ...) { args <- list(...) if (is.null(args$main)) args$main <- paste(deparse(substitute(x)), collapse = "\n") if (is.null(args$breaks)) args$breaks <- c(-sqrt(c(1, 0.75, 0.5, 0.25, 0.16)), sqrt(c(0.16, 0.25, 0.50, 0.75, 1))) if (is.null(args$digits)) args$digits <- 2 if (is.null(args$xlab)) args$xlab <- "Component" if (is.null(args$ylab)) args$ylab <- "Variable" args$x <- unclass(x) if (is.null(args$col)) { args$col <- if (grey||gray) colorRampPalette(c("black", "white", "black")) else colorRampPalette(c("blue", "white", "red")) } if (is.null(rownames(args$x))) rownames(args$x) <- sprintf("V%.0f", 1:nrow(x)) if (reorder) { o <- apply(x, 1, function(v) { v<-v^2; c(which.max(v), -max(v))}) o <- order(o[1,], o[2,]) args$x <- args$x[o,] } do.call("plot.matrix", args) }
npcs <- function(x, y, algorithm = c("CX", "ER"), classifier = c("logistic", "knn", "randomforest", "tree", "neuralnet", "svm", "lda", "qda", "nb", "nnb"), w, alpha, split.ratio = 0.5, split.mode = c("by-class", "merged"), tol = 1e-6, refit = TRUE, protect = TRUE, opt.alg = c("Hooke-Jeeves", "Nelder-Mead"), ...) { algorithm <- match.arg(algorithm) classifier <- match.arg(classifier) split.mode <- match.arg(split.mode) opt.alg <- match.arg(opt.alg) n <- length(y) K <- length(unique(y)) w.ori <- w w <- w/sum(w) index <- which(!is.na(alpha)) if (algorithm == "CX") { pik <- as.numeric(table(y)/n) if (classifier == "logistic") { fit <- multinom(y ~ ., data = data.frame(x = x, y = y), trace = FALSE, ...) if (K> 2) { posterior <- predict(fit, newdata = data.frame(x = x, y = y), type = "prob") } else { pt1 <- predict(fit, newdata = data.frame(x = x, y = y) , type = "prob") posterior <- cbind(1-pt1, pt1) } } else if (classifier == "knn") { fit <- knn3(x = x, y = factor(y), ...) posterior <- predict(fit, newdata = x, type = "prob") } else if (classifier == "randomforest") { fit <- randomForest(x = x, y = factor(y), ...) posterior <- predict(fit, newdata = x, type = "prob") } else if (classifier == "svm") { fit <- svm(x = x, y = factor(y), probability = TRUE, ...) posterior <- attr(predict(fit, newdata = x, probability = TRUE), "probabilities") posterior <- posterior[, match(1:K, as.numeric(colnames(posterior)))] } else if (classifier == "nb") { fit <- naiveBayes(x = x, y = factor(y), ...) posterior <- predict(fit, newdata = x, type = "raw") } else if (classifier == "tree") { fit <- rpart(y ~ ., data = data.frame(x = x, y = factor(y)), ...) posterior <- predict(fit, newdata = data.frame(x = x, y = factor(y)), type = "prob") } else if (classifier == "neuralnet") { fit <- nnet(y ~ ., data = data.frame(x = x, y = factor(y)), trace = FALSE, ...) if (K> 2) { posterior <- predict(fit, newdata = data.frame(x = x, y = factor(y)) , type = "raw") } else { pt1 <- predict(fit, newdata = data.frame(x = x, y = factor(y)), type = "raw") posterior <- cbind(1-pt1, pt1) } } else if (classifier == "lda") { fit <- lda(x = x, grouping = factor(y), ...) posterior <- predict(fit, x)$posterior } else if (classifier == "qda") { fit <- qda(x = x, grouping = factor(y), ...) posterior <- predict(fit, x)$posterior } else if (classifier == "nnb") { if (is.null(colnames(x))) { colnames(x) <- paste0("x", 1:ncol(x)) } fit <- nonparametric_naive_bayes(x = x, y = factor(y), ...) posterior <- predict(fit, x, type = "prob") } if (length(index) == 1) { if (opt.alg == "Nelder-Mead"){ lambda <- optimize(f = obj.CX, lower = 0, maximum = T, upper = 200, alpha = alpha, pik = pik, posterior = posterior, w = w, index = index, tol = tol) } else if (opt.alg == "Hooke-Jeeves") { lambda <- hjkb1(par = rep(0, length(index)), fn = obj.CX, upper = rep(200, length(index)), lower = rep(0, length(index)), control = c(maximize = TRUE, tol = tol), alpha = alpha, pik = pik, posterior = posterior, w = w, index = index) } } else if (length(index) > 1) { if (opt.alg == "Nelder-Mead"){ lambda <- nmkb(par = rep(0.0001, length(index)), fn = obj.CX, upper = rep(200, length(index)), lower = rep(0, length(index)), control = c(maximize = TRUE, tol = tol), alpha = alpha, pik = pik, posterior = posterior, w = w, index = index) } else if (opt.alg == "Hooke-Jeeves") { lambda <- hjkb(par = rep(0, length(index)), fn = obj.CX, upper = rep(200, length(index)), lower = rep(0, length(index)), control = c(maximize = TRUE, tol = tol), alpha = alpha, pik = pik, posterior = posterior, w = w, index = index) } } } if (algorithm == "ER") { if (split.mode == "merged") { ind <- sample(n, floor(n*split.ratio)) pik <- as.numeric(table(y[-ind])/length(y[-ind])) } else { ind <- Reduce("c", sapply(1:K, function(k){ ind.k <- which(y == k) sample(ind.k, floor(length(ind.k)*split.ratio)) }, simplify = F)) pik <- as.numeric(table(y[-ind])/length(y[-ind])) } if (classifier == "logistic") { fit <- multinom(y~., data = data.frame(x = x[-ind, ], y = y[-ind]) , trace = F) if (K> 2) { posterior <- predict(fit, newdata = data.frame(x = x[ind, ], y = y[ind]), type = "prob") } else { pt1 <- predict(fit, newdata = data.frame(x = x[ind, ], y = y[ind]), type = "prob") posterior <- cbind(1-pt1, pt1) } if (refit) { fit <- multinom(y~., data = data.frame(x = x, y = y), trace = F) pik <- as.numeric(table(y)/length(y)) } } else if (classifier == "knn") { fit <- knn3(x = x[-ind, ], y = factor(y)[-ind], ...) posterior <- predict(fit, newdata = x[ind, ], type = "prob") if (refit) { fit <- knn3(x = x, y = factor(y), ...) pik <- as.numeric(table(y)/length(y)) } } else if (classifier == "randomforest") { fit <- randomForest(x = x[-ind, ], y = factor(y)[-ind], ...) posterior <- predict(fit, newdata = x[ind, ], type = "prob") if (refit) { fit <- randomForest(x = x, y = factor(y), ...) pik <- as.numeric(table(y)/length(y)) } } else if (classifier == "svm") { fit <- svm(x = x[-ind, ], y = factor(y)[-ind], probability = TRUE, ...) posterior <- attr(predict(fit, newdata = x[ind, ], probability = TRUE), "probabilities") posterior <- posterior[, match(1:K, as.numeric(colnames(posterior)))] if (refit) { fit <- svm(x = x, y = factor(y), probability = TRUE, ...) pik <- as.numeric(table(y)/length(y)) } } else if (classifier == "nb") { fit <- naiveBayes(x = x[-ind, ], y = factor(y)[-ind], ...) posterior <- predict(fit, newdata = x[ind, ], type = "raw") if (refit) { fit <- naiveBayes(x = x, y = factor(y), ...) pik <- as.numeric(table(y)/length(y)) } } else if (classifier == "tree") { fit <- rpart(y ~ ., data = data.frame(x = x[-ind, ], y = factor(y)[-ind]), ...) posterior <- predict(fit, newdata = data.frame(x = x[ind, ]), type = "prob") if (refit) { fit <- rpart(y ~ ., data = data.frame(x = x, y = factor(y)), ...) pik <- as.numeric(table(y)/length(y)) } } else if (classifier == "neuralnet") { fit <- nnet(y ~ ., data = data.frame(x = x[-ind, ], y = factor(y)[-ind]), trace = FALSE, ...) if (K> 2) { posterior <- predict(fit, newdata = data.frame(x = x[ind, ]), type = "raw") } else { pt1 <- predict(fit, newdata = data.frame(x = x[ind, ]), type = "raw") posterior <- cbind(1-pt1, pt1) } if (refit) { fit <- nnet(y ~ ., data = data.frame(x = x, y = factor(y)), trace = FALSE, ...) pik <- as.numeric(table(y)/length(y)) } } else if (classifier == "lda") { fit <- lda(x = x[-ind, ], grouping = factor(y)[-ind]) posterior <- predict(fit, x[ind, ])$posterior if (refit) { fit <- lda(x = x, grouping = factor(y), ...) pik <- as.numeric(table(y)/length(y)) } } else if (classifier == "qda") { fit <- qda(x = x[-ind, ], grouping = factor(y)[-ind]) posterior <- predict(fit, x[ind, ])$posterior if (refit) { fit <- qda(x = x, grouping = factor(y), ...) pik <- as.numeric(table(y)/length(y)) } } else if (classifier == "nnb") { if (is.null(colnames(x))) { colnames(x) <- paste0("x", 1:ncol(x)) } fit <- nonparametric_naive_bayes(x = x[-ind, ], y = factor(y)[-ind], ...) posterior <- predict(fit, x[ind, ], type = "prob") if (refit) { fit <- nonparametric_naive_bayes(x = x, y = factor(y), ...) pik <- as.numeric(table(y)/length(y)) } } if (length(index) == 1) { if (opt.alg == "Nelder-Mead"){ lambda <- optimize(f = obj.ER, lower = 0, maximum = T, upper = 200, alpha = alpha, pik = pik, posterior = posterior, w = w, index = index, y = y[ind], tol = tol) } else if (opt.alg == "Hooke-Jeeves") { lambda <- hjkb1(par = rep(0, length(index)), fn = obj.ER, upper = rep(200, length(index)), lower = rep(0, length(index)), control = c(maximize = TRUE, tol = tol), alpha = alpha, pik = pik, posterior = posterior, w = w, index = index, y = y[ind]) } } else if (length(index) > 1) { if (opt.alg == "Nelder-Mead"){ lambda <- nmkb(par = rep(0.0001, length(index)), fn = obj.ER, upper = rep(200, length(index)), lower = rep(0, length(index)), control = c(maximize = TRUE, tol = tol), alpha = alpha, pik = pik, posterior = posterior, w = w, index = index, y = y[ind]) } else if (opt.alg == "Hooke-Jeeves") { lambda <- hjkb(par = rep(0, length(index)), fn = obj.ER, upper = rep(200, length(index)), lower = rep(0, length(index)), control = c(maximize = TRUE, tol = tol), alpha = alpha, pik = pik, posterior = posterior, w = w, index = index, y = y[ind]) } } } if (length(index) == 1 && opt.alg == "Nelder-Mead") { obj.value <- lambda$objective lambda <- lambda$maximum } else { obj.value <- lambda$value lambda <- lambda$par } if (obj.value > 1) { stop("The NP problem is infeasible!") } if (protect) { lambda[lambda <= 1e-3] <- 1e-3 } lambda.full <- rep(NA, length(alpha)) lambda.full[index] <- lambda L <- list(lambda = lambda.full*sum(w.ori), fit = fit, classifier = classifier, algorithm = algorithm, alpha = alpha, w = w.ori, pik = pik) class(L) <- "npcs" return(L) }
setDecisionNodes <- function(network, ...) { nodes <- as.character(substitute(list(...)))[-1] network[["nodeDecision"]][nodes] <- lapply(X = network[["nodeDecision"]][nodes], FUN = function(x) TRUE) network } setUtilityNodes <- function(network, ...) { nodes <- as.character(substitute(list(...)))[-1] network[["nodeUtility"]][nodes] <- lapply(X = network[["nodeUtility"]][nodes], FUN = function(x) TRUE) network }
`[.labelled` <- function(x, i, ...){ structure( NextMethod(), label = attr(x, "label"), class = class(x) ) } `[<-.labelled` <- function(x, i, ..., value){ structure( NextMethod(), label = attr(x, "label"), class = c("labelled", class(x)[!class(x) %in% "labelled"]) ) }
.makeTinyMap <- function(geom = NULL){ assertClass(x = geom, classes = "geom") theWindow <- getWindow(x = geom) thePoints <- getPoints(x = geom) xmin <- round(min(theWindow$x), 2) xminFill <- paste0(rep(" ", nchar(xmin)), collapse = "") xmax <- round(max(theWindow$x), 2) xmaxFill <- paste0(rep(" ", nchar(xmax)), collapse = "") ymin <- round(min(theWindow$y), 2) ymax <- round(max(theWindow$y), 2) full <- '\u25C9' half <- '\u25CE' quarter <- '\u25CB' empty <- '\u25CC' filled <- NULL nrPoints <- dim(thePoints)[1] for(i in 1:4){ for(j in 1:4){ x <- xmin + c(((xmax-xmin)/4 * j) - (xmax-xmin)/4, (xmax-xmin)/4 * j) y <- ymin + c(((ymax-ymin)/4 * i) - (ymax-ymin)/4, (ymax-ymin)/4 * i) target <- data.frame(x = c(x[1], x[2], x[2], x[1], x[1]), y = c(y[1], y[1], y[2], y[2], y[1])) inside <- pointInGeomC(vert = as.matrix(thePoints[c("x", "y")]), geom = as.matrix(target), invert = FALSE) pointsInside <- sum(inside != 0) ratio <- pointsInside/nrPoints if(ratio <= 1/16){ recent <- empty } else if(ratio > 1/16 & ratio <= 1/8){ recent <- quarter } else if(ratio > 1/8 & ratio <= 1/4){ recent <- half } else if(ratio > 1/4){ recent <- full } filled <- c(filled, recent) } } out <- paste0(c("", xminFill, ymax, "\n", " ", xminFill, filled[13], filled[14], filled[15], filled[16], xmaxFill, "\n", " ", xminFill, filled[9], filled[10], filled[11], filled[12], xmaxFill, "\n", " ", xminFill, filled[5], filled[6], filled[7], filled[8], xmaxFill, "\n", " ", xmin, filled[1], filled[2], filled[3], filled[4], xmax, "\n", " ", xminFill, ymin, "")) return(out) }
logdr.gui <- function( base.txt) { ebase <- tclVar(1) bb <- tclVar( 10) refresh <- function() { tkdelete( col.listbox, 0.0, "end") if( !is.nothing) { dd.select <- as.numeric( tkcurselection( data.listbox))+1 dd <- get( full.list[ dd.select]) } else dd <- in2extRemesData for( i in 1:ncol( dd$data)) tkinsert( col.listbox, "end", paste( colnames( dd$data)[i])) invisible() } ldr.trans <- function() { if( !is.nothing) { data.select <- as.numeric( tkcurselection( data.listbox))+1 dd.cmd <- paste( "dd <- get( \"", full.list[ data.select], "\")", sep="") ddname <- full.list[ data.select] } else dd.cmd <- "dd <- in2extRemesData" eval( parse( text=dd.cmd)) write( dd.cmd, file="in2extRemes.log", append=TRUE) if( tclvalue(ebase) == 1 ) log.b <- exp(1) else { log.b <- as.numeric( tclvalue( bb)) bbext <- deparse( log.b) } cols.selected.cmd <- "cols.selected <- character(0)" eval( parse( text=cols.selected.cmd)) write( cols.selected.cmd, file="in2extRemes.log", append=TRUE) temp <- as.numeric( tkcurselection( col.listbox)) + 1 if( is.na( temp)) return() cnames.cmd <- "cnames <- colnames( dd[[\"data\"]])" eval( parse( text=cnames.cmd)) write( cnames.cmd, file="in2extRemes.log", append=TRUE) for( i in 1:length( temp)) { cols.selected.cmd <- paste(" cols.selected <- c( cols.selected, \"", cnames[ temp[i]], "\")", sep="") eval( parse( text=cols.selected.cmd)) write( cols.selected.cmd, file="in2extRemes.log", append=TRUE) } N.cmd <- "N <- dim( dd[[\"data\"]])[1]" eval( parse( text=N.cmd)) write( N.cmd, file="in2extRemes.log", append=TRUE) tmp.ldr.cmd <- "tmp.ldr <- matrix( NA, nrow=N, ncol=length( cols.selected) )" eval( parse( text=tmp.ldr.cmd)) write( tmp.ldr.cmd, file="in2extRemes.log", append=TRUE) tmp.ldr.cmd <- paste( "tmp.ldr[ 1:(N-1),] <- log( dd[[\"data\"]][2:N, cols.selected], base=", log.b, ") -", " log( dd[[\"data\"]][1:(N-1), cols.selected], base=", log.b, ")", sep="") eval( parse( text=tmp.ldr.cmd)) write( tmp.ldr.cmd, file="in2extRemes.log", append=TRUE) CMD <- "for( i in 1: dim( tmp.ldr)[2]) tmp.ldr[is.na( tmp.ldr[,i]),i] <- mean(tmp.ldr[,i],na.rm=TRUE)" eval( parse( text=CMD)) write( CMD, file="in2extRemes.log", append=TRUE) if( tclvalue(ebase) == 1) newnames <- paste( cnames[temp], ".ldr", sep="") else newnames <- paste( cnames[temp], ".", bbext, "ldr", sep="") for( i in 1:length( newnames)) { cnames.cmd <- paste( "cnames <- c( cnames, \"", newnames[i], "\")", sep="") eval( parse( text=cnames.cmd)) write( cnames.cmd, file="in2extRemes.log", append=TRUE) } newdata.cmd <- "dd[[\"data\"]] <- cbind( dd[[\"data\"]], tmp.ldr)" eval( parse( text=newdata.cmd)) write( newdata.cmd, file="in2extRemes.log", append=TRUE) colnamesCMD <- "colnames( dd[[\"data\"]]) <- cnames" eval( parse( text=colnamesCMD)) write( colnamesCMD, file="in2extRemes.log", append=TRUE) assignCMD <- paste( "assign( \"", full.list[ data.select], "\", dd, pos=\".GlobalEnv\")", sep="") eval( parse( text=assignCMD)) write( assignCMD, file="in2extRemes.log", append=TRUE) msg <- paste( "\n", "log daily return (base= ", round( log.b, digits=6), ") taken for", "\n", " ", cols.selected, " and assigned to ", newnames, sep="") cat( msg) tkdestroy( base) invisible() } ldrhelp <- function() { help.msg1 <- paste( " ", "This is a simple function that takes an n X 1 data set Y and computes the ", "log (base bb) daily return. That is:", " ", sep="\n") help.msg2 <- paste(" ", "log( Y[2:n], base=bb) - log( Y[1:(n-1)], base=bb)", " ", sep="\n") help.msg3 <- paste(" ", "Returns an object of class \"in2extRemesDataObject\" ", " ", sep="\n") cat( help.msg1) cat( help.msg2) cat( help.msg3) invisible() } endprog <- function() { tkdestroy( base) } base <- tktoplevel() tkwm.title( base, "Log Daily Returns Transformation") top.frm <- tkframe( base, borderwidth=2, relief="groove") mid.frm <- tkframe( base, borderwidth=2, relief="groove") bot.frm <- tkframe( base, borderwidth=2, relief="groove") data.listbox <- tklistbox( top.frm, yscrollcommand=function(...) tkset(data.scroll, ...), selectmode="single", width=20, height=5, exportselection=0) data.scroll <- tkscrollbar( top.frm, orient="vert", command=function(...) tkyview( data.listbox, ...)) temp <- ls(all.names=TRUE, name=".GlobalEnv") full.list <- character(0) is.nothing <- TRUE for( i in 1:length( temp)) { if( is.null( class( get( temp[i])))) next if( (class(get( temp[i]))[1] == "in2extRemesDataObject")) { tkinsert( data.listbox, "end", paste( temp[i])) full.list <- c( full.list, temp[i]) is.nothing <- FALSE } } tkpack( tklabel( top.frm, text="Data Object", padx=4), side="top") tkpack( data.listbox, data.scroll, side="left", fill="y") tkpack( top.frm) tkbind( data.listbox, "<Button-1>", "") tkbind( data.listbox, "<ButtonRelease-1>", refresh) leftmid.frm <- tkframe( mid.frm, borderwidth=2, relief="groove") col.listbox <- tklistbox( leftmid.frm, yscrollcommand=function(...) tkset( col.scroll, ...), selectmode="multiple", width=20, height=5, exportselection=0) col.scroll <- tkscrollbar( leftmid.frm, orient="vert", command=function(...) tkyview( col.listbox, ...)) if( is.nothing) { for( i in 1:ncol( in2extRemesData$data)) tkinsert( col.listbox, "end", paste( colnames( dd$data)[i])) } else tkinsert( col.listbox, "end", "") tkpack( tklabel( leftmid.frm, text="Variables to Transform", padx=4), side="top") tkpack( col.listbox, side="left") tkpack( col.scroll, side="right") rightmid.frm <- tkframe( mid.frm, borderwidth=2, relief="groove") exp.base <- tkcheckbutton( rightmid.frm, text="Use Exponential Base", variable=ebase) other.base <- tkentry( rightmid.frm, textvariable=bb, width=4) tkpack( exp.base, side="top") tkpack( other.base, tklabel( rightmid.frm, text="Use other base", padx=4), side="bottom") tkpack( leftmid.frm, rightmid.frm, side="left") ok.but <- tkbutton( bot.frm, text="OK", command=ldr.trans) cancel.but <- tkbutton( bot.frm, text="Cancel", command=endprog) help.but <- tkbutton( bot.frm, text="Help", command=ldrhelp) tkpack( ok.but, cancel.but, side="left") tkpack( help.but, side="right") tkbind( ok.but, "<Return>", ldr.trans) tkbind( cancel.but, "<Return>", endprog) tkbind( help.but, "<Return>", ldrhelp) tkpack( top.frm, fill="x") tkpack( mid.frm, fill="x") tkpack( bot.frm, side="bottom") }
prediction.nls <- function(model, data = find_data(model, parent.frame()), at = NULL, calculate_se = FALSE, ...) { data <- data if (missing(data) || is.null(data)) { pred <- make_data_frame(fitted = predict(model, ...), se.fitted = NA_real_) } else { if (is.null(at)) { out <- data } else { out <- build_datalist(data, at = at, as.data.frame = TRUE) at_specification <- attr(out, "at_specification") } tmp <- predict(model, newdata = out, ...) pred <- make_data_frame(out, fitted = tmp, se.fitted = rep(NA_real_, length(tmp))) } vc <- NA_real_ structure(pred, class = c("prediction", "data.frame"), at = if (is.null(at)) at else at_specification, type = NA_character_, call = if ("call" %in% names(model)) model[["call"]] else NULL, model_class = class(model), row.names = seq_len(nrow(pred)), vcov = vc, jacobian = NULL, weighted = FALSE) }
pgfIpoissonbinomial <- function(s,params) { k<-s[abs(s)>1] if (length(k)>0) warning("At least one element of the vector s are out of interval [-1,1]") if (length(params)<3) stop("At least one value in params is missing") if (length(params)>3) stop("The length of params is 3") theta<-params[1] p<-params[2] n<-params[3] if (theta<=0) stop ("Parameter theta must be positive") if ((p>=1)|(p<=0)) stop ("Parameter p belongs to the interval (0,1)") if (n<0) stop("Parameter n must be positive") if(!(abs(n-round(n))<.Machine$double.eps^0.5)) stop("Parameter n must be positive integer") zval<-1+log(s)/theta (zval^(1/n)-1+p)/p }
bc_test_cond<-function(x,y,z,ic.chosen="SC",max.lag=min(4,length(x)-1),plot=F,type.chosen="none",p=0,conf=0.95){ 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(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.") } requireNamespace("vars") if(p<=0){ mod=VAR(cbind(x,y,z),lag.max=max.lag,ic=ic.chosen,type.chosen) if(mod$p>1){ p=mod$p } if(mod$p==1){ p=2 mod=VAR(cbind(x,y,z),lag.max=max.lag,ic=ic.chosen,type.chosen) } } if(p>0){ if(p>1){ mod=VAR(cbind(x,y,z),p=p,ic=ic.chosen,type.chosen) } if(p==1){ p=2 mod=VAR(cbind(x,y,z),p=p,ic=ic.chosen,type.chosen) } } r<-c(0,0) r<-matrix(0,2,1) beta<-matrix(mod$p,1) for(k in 1:mod$p){ beta[k]<-coef(mod)$x[2+(k-1)*mod$K,1] } freq.good=spec.pgram(y,plot=F)$freq/frequency(x); R<-matrix(0,2,mod$p) R_all<-array(0,dim=c(2,mod$p,length(freq.good))) for (l in 1:length(freq.good)){ for(k in 1:mod$p){ R[1,k]<-cos(freq.good[l]*pi*k) R[2,k]<-sin(freq.good[l]*pi*k) } R_all[,,l]<-R; } X_design<-cbind(x,y) n<-dim(X_design)[1] X_all<-matrix(0,n-as.numeric(mod$p),mod$p) X_past<-matrix(0,n-as.numeric(mod$p),1) for(k in 1:mod$p){ X_past<-as.matrix(X_design[seq(1+k,1+k+n-as.numeric(mod$p)-1)-1,2]) X_all[1:(n-as.numeric(mod$p)),k]<-X_past } X_all<-X_all[,dim(X_all)[2]:1] res_yes<-residuals(mod)[,1] sse<-sum(t(res_yes)%*%res_yes) F_test<-vector(mode="numeric",length(freq.good)) F_test_pre<-vector(mode="numeric",length(freq.good)) F_thr<-vector(mode="numeric",length(freq.good)) for (l in 1:length(freq.good)){ if(l<length(freq.good)){ r_matrix<-r; R_matrix<-as.matrix(R_all[,,l]); F_test_pre[l]<-t(r_matrix-R_matrix%*%beta)%*%solve(R_matrix%*%solve(t(X_all)%*%(X_all))%*%t(R_matrix))%*%(r_matrix-R_matrix%*%beta) F_test[l]<-(F_test_pre[l]/2)/(sse/(n-2*mod$p))} if(l==length(freq.good)){ r_matrix<-r[1]; R_matrix<-matrix(R_all[1,,l],1,p); F_test_pre[l]<-t(r_matrix-R_matrix%*%beta)%*%solve(R_matrix%*%solve(t(X_all)%*%(X_all))%*%t(R_matrix))%*%(r_matrix-R_matrix%*%beta) F_test[l]<-(F_test_pre[l]/1)/(sse/(n-1*mod$p)) } } quant_bc<-vector(mode="numeric",length(freq.good)) for (l in 1:length(freq.good)){ quant_bc[l]<-pf(F_test[l],2,n-2*mod$p,lower.tail=F) if(l==length(freq.good)){ quant_bc[l]<-pf(F_test[l],1,n-1*mod$p,lower.tail=F) } } alpha<-1-conf signif_bc<-which(quant_bc<alpha) length(signif_bc) F_thr[1:length(freq.good)-1]<-qf(conf,2,n-2*mod$p) F_thr[length(freq.good)]<-qf(conf,1,n-1*mod$p) GG<-list( freq.good,length(x), freq.good[signif_bc], conf, F_test, F_thr, roots(mod), as.numeric(mod$p) ) names(GG)<-c("frequency","n","confidence_level","significant_frequencies","F-test","F-threshold","roots","delays") if(plot==F){ return(GG)} if(plot==T){ plot(F_test,type="l") abline(F_thr,type="l") } }