code
stringlengths
1
13.8M
context("encrypt_data") test_that("encrypt_data", { pair <- keypair_openssl("pair1", "pair1") r <- openssl::rand_bytes(20) v <- encrypt_data(r, pair, NULL) expect_is(v, "raw") expect_identical(decrypt_data(v, pair, NULL), r) }) test_that("encrypt_object", { pair <- keypair_openssl("pair1", "pair1") r <- list(runif(10), sample(20)) v <- encrypt_object(r, pair, NULL) expect_is(v, "raw") expect_identical(decrypt_object(v, pair), r) }) test_that("encrypt_string", { pair <- keypair_openssl("pair1", "pair1") r <- paste(sample(letters), collapse = "") v <- encrypt_string(r, pair) expect_is(v, "raw") expect_identical(decrypt_string(v, pair), r) }) test_that("encrypt_file", { pair <- keypair_openssl("pair1", "pair1") path1 <- tempfile() path2 <- tempfile() path3 <- tempfile() on.exit(suppressWarnings(file.remove(path1, path2, path3))) write.csv(mtcars, path1) encrypt_file(path1, pair, path2) expect_true(file.exists(path2)) expect_false(unname(tools::md5sum(path1)) == unname(tools::md5sum(path2))) decrypt_file(path2, pair, path3) expect_true(file.exists(path3)) expect_identical(unname(tools::md5sum(path1)), unname(tools::md5sum(path3))) }) test_that("input validation", { key <- key_sodium(sodium::keygen()) expect_error(encrypt_data(iris, key), "Expected a raw vector") expect_error(encrypt_string(raw(10), key), "must be a scalar character") expect_error(encrypt_string(letters, key), "must be a scalar character") }) test_that("decrypt_data from file", { key <- key_sodium(sodium::keygen()) path <- tempfile() r <- sodium::random(20) encrypt_data(r, key, path) expect_identical(decrypt_data(path, key), r) expect_error(decrypt_data(tempfile(), key), "must be a file that exists") })
library(norm2) set.seed(1234) simdata <- data.frame( Y1=rnorm(10), Y2=rnorm(10), Y3=rnorm(10), X1=rnorm(10) ) simdata$Y3[7] <- simdata$Y2[3]<- NA emResult <- emNorm( cbind(Y1,Y2,Y3) ~ X1, data=simdata ) imp <- impNorm( emResult, method="predict") print( round( imp, 5 ) ) set.seed(1234) imp <- impNorm( emResult, method="random") print( round( imp, 5 ) ) data(marijuana) emResult <- emNorm( marijuana, prior="ridge", prior.df=0.5 ) set.seed(23) imp <- impNorm( emResult, method="random") print( round( imp, 5 ) ) data(cholesterol) emResult <- emNorm(cholesterol) set.seed(23) imp1 <- impNorm( emResult ) print( imp1 ) set.seed(23) imp2 <- impNorm( cbind(Y1,Y2,Y3)~1, data=cholesterol, param=emResult$param ) print( imp2 ) set.seed(23) imp3 <- impNorm( cholesterol, param=emResult$param ) print( imp3 ) print( all( imp1 == imp2 ) ) print( all( imp1 == imp3 ) )
as.repeatedTrain <- function(x) { if (!is.list(x)) x <- list(x) if (!is.null(names(x))) { xN <- names(x) } else { xN <- paste("stim.",1:length(x)) } x <- lapply(x, as.spikeTrain) names(x) <- xN class(x) <- "repeatedTrain" x } is.repeatedTrain <- function(x) { if (!("repeatedTrain" %in% class(x))) return(FALSE) if (!all(sapply(x,is.spikeTrain))) return(FALSE) return(TRUE) } raster <- function(x, stimTimeCourse = NULL, colStim = "grey80", xlim, pch, xlab, ylab, main, ...) { do.call(plot.repeatedTrain,as.list(match.call()[-1])) } plot.repeatedTrain <- function (x, stimTimeCourse = NULL, colStim = "grey80", xlim, pch, xlab, ylab, main, ...) { if (!is.repeatedTrain(x)) x <- as.repeatedTrain(x) nbTrains <- length(x) if (missing(xlim)) xlim <- c(0, ceiling(max(sapply(x, max)))) if (missing(xlab)) xlab <- "Time (s)" if (missing(ylab)) ylab <- "trial" if (missing(main)) main <- paste(deparse(substitute(x)), "raster") if (missing(pch)) pch <- ifelse(nbTrains <= 20, "|", ".") oldpar <- par(mar = c(5, 4, 2, 1)) on.exit(par(oldpar)) acquisitionDuration <- max(xlim) plot(c(0, acquisitionDuration), c(0, nbTrains + 1), type = "n", xlab = xlab, ylab = ylab, xlim = xlim, ylim = c(1, nbTrains + 1), bty = "n", main = main, ...) if (!is.null(stimTimeCourse)) { rect(stimTimeCourse[1], 0.1, stimTimeCourse[2], nbTrains + 0.9, col = colStim, lty = 0) } invisible(sapply(1:nbTrains, function(idx) points(x[[idx]], numeric(length(x[[idx]])) + idx, pch = pch))) axis(2, at = 1:nbTrains) axis(1) } plot.psth <- function(x, stimTimeCourse = NULL, colStim = "grey80", colCI = NULL, xlab, ylab, main, xlim, ylim, lwd = 2, col = 1, ...) { if (!is.null(stimTimeCourse)) { if (length(stimTimeCourse) != 2) stop(paste(deparse(substitute(stimTimeCourse)), "should be a vector with 2 elements.") ) } if (missing(xlab)) xlab <- "Time (s)" if (missing(ylab)) ylab <- "Freq (Hz)" if (missing(main)) { nameList <- deparse(x$call[["repeatedTrain"]]) main <- paste(nameList, "PSTH") } withCI <- !is.null(x$ciUp) originalBreaksArg <- x$call[["breaks"]] if (!is.null(originalBreaksArg) && (length(eval(originalBreaksArg))==2)) smoothOne <- TRUE else smoothOne <- FALSE if (missing(xlim)) { if (!smoothOne) xlim <- range(x$breaks) else xlim <- range(x$mids) + c(-0.5,0.5)*x$breaks["step"] } if (missing(ylim)) ylim <- c(0, ifelse(withCI, max(x$ciUp), max(x$freq))) plot(xlim, ylim, type = "n", xlab = xlab, ylab = ylab, main = main, xlim = xlim, ylim = ylim, ...) if (!is.null(stimTimeCourse)) { rect(stimTimeCourse[1], 0, stimTimeCourse[2], ylim[2], col = colStim, lty = 0) } if (withCI) { if (is.null(colCI)) { if (!smoothOne) { sapply(1:length(x$mids), function(idx) segments(x$breaks[idx], x$ciLow[idx], x$breaks[idx + 1], x$ciLow[idx], lty = 2) ) sapply(1:length(x$mids), function(idx) segments(x$breaks[idx], x$ciUp[idx], x$breaks[idx + 1], x$ciUp[idx], lty = 2) ) } else { lines(x$mids, x$ciLow, lty = 2) lines(x$mids, x$ciUp, lty = 2) } } else { if (!smoothOne) { sapply(1:length(x$mids), function(idx) rect(x$breaks[idx], x$ciLow[idx], x$breaks[idx + 1], x$ciUp[idx], lty = 0, col = colCI)) } else { polygon(c(x$mids, rev(x$mids)), c(x$ciLow, rev(x$ciUp)), col = colCI, border = NA) } } } if (!smoothOne) { invisible(sapply(1:length(x$mids), function(idx) { segments(x$breaks[idx], x$freq[idx], x$breaks[idx + 1], x$freq[idx], lwd = lwd, col = col) if (idx == 1) segments(x$breaks[idx], 0, x$breaks[idx], x$freq[idx], lwd = lwd, col = col) if (idx != length(x$mids)) { segments(x$breaks[idx + 1], x$freq[idx], x$breaks[idx + 1], x$freq[idx + 1], lwd = lwd, col = col) } else { segments(x$breaks[idx + 1], x$freq[idx], x$breaks[idx + 1], 0, lwd = lwd, col = col) } } ) ) } else { lines(x$mids, x$freq, col = col, lwd = lwd) } abline(h = 0) } psth <- function (repeatedTrain, breaks=20, include.lowest = TRUE, right = TRUE, plot = TRUE, CI = 0.95, ... ) { if (!is.repeatedTrain(repeatedTrain)) repeatedTrain <- as.repeatedTrain(repeatedTrain) if (!inherits(breaks,"numeric")) stop("breaks should be a numeric.") nbTrials <- length(repeatedTrain) breaksName <- deparse(substitute(breaks)) l <- floor(min(sapply(repeatedTrain,function(l) l[1]))) r <- ceiling(max(sapply(repeatedTrain,function(l) l[length(l)]))) if (length(breaks) != 2) { if (length(breaks)==1) breaks <- seq(l,r,length.out=breaks+1) counts <- t(sapply(repeatedTrain, function(train) hist(x = unclass(train), breaks = breaks, include.lowest = include.lowest, right = right, plot = FALSE)$counts ) ) h <- list(breaks = breaks, counts = counts, mids = breaks[-length(breaks)]+diff(breaks)/2) f <- colSums(counts)/(nbTrials * diff(h$breaks)) } else { if (is.null(names(breaks))) { bw <- breaks[1] step <- breaks[2] } else { if (!all(names(breaks) %in% c("bw", "step"))) stop(paste(breaksName, "should have named elements: bw and step")) bw <- as.numeric(breaks["bw"]) step <- as.numeric(breaks["step"]) } bwh <- bw/2 breaks <- c(bw = bw, step = step) mids <- seq(bwh, r - bwh, by = step) counts <- t(sapply(repeatedTrain, function(train) sapply(mids, function(m) ifelse(right, sum(m - bwh < train & train <= m + bwh), sum(m - bwh <= train & train < m + bwh)) ) ) ) h <- list(breaks = breaks, counts = counts, mids = mids) f <- colSums(counts)/(nbTrials * bw) } if (!is.null(CI)) { expectedCount <- colSums(counts) ciUp <- sapply(1:length(h$mids), function(idx) qpois(1-(1-CI)/2,expectedCount[idx]) ) if (length(breaks) > 2) ciUp <- ciUp / (nbTrials * diff(h$breaks)) else ciUp <- ciUp / (nbTrials * bw) ciLow <- sapply(1:length(h$mids), function(idx) qpois((1-CI)/2,expectedCount[idx]) ) if (length(breaks) > 2) ciLow <- ciLow / (nbTrials * diff(h$breaks)) else ciLow <- ciLow / (nbTrials * bw) } if (!is.null(CI)) { result <- list(freq = f, ciUp = ciUp, ciLow = ciLow, breaks = h$breaks, mids = h$mids, counts = h$counts, nbTrials = nbTrials, call = match.call()) class(result) <- "psth" } else { result <- list(freq = f, ciUp = NULL, ciLow = NULL, breaks = h$breaks, mids = h$mids, counts = h$counts, nbTrials = nbTrials, call = match.call()) class(result) <- "psth" } if (plot) { plot(result,...) } else { return(result) } } print.repeatedTrain <- function(x,...) { main <- "Raster plot" plot(x,main=main,...) } summary.repeatedTrain <- function(object, responseWindow, acquisitionWindow, ...) { repeatedTrain <- object rm(object) nbRepeates <- length(repeatedTrain) if (missing(acquisitionWindow)) acquisitionWindow <- c(min(sapply(repeatedTrain,function(l) floor(l[1]))), max(sapply(repeatedTrain,function(l) ceiling(l[length(l)]))) ) acquisitionDuration <- diff(acquisitionWindow) if (!missing(responseWindow)) { if (length(responseWindow) != 2) stop("Wrong responseWindow.") if ((responseWindow[1] < acquisitionWindow[1]) || (responseWindow[2] > acquisitionWindow[2]) ) warning("responseWindow does not make much sense.") stimDuration <- diff(responseWindow) } else { responseWindow <- NULL stimDuration <- NULL } theStats <- sapply(repeatedTrain, function(l) { nb <- length(l) nu <- nb/acquisitionDuration result <- c(nb=nb,nu=nu) if (!is.null(stimDuration)) { goodOnes <- responseWindow[1] < l & l < responseWindow[2] nbR <- sum(goodOnes) nuR <- nbR/stimDuration result <- c(result,c(nbR=nbR,nuR=nuR)) } result } ) stationarityTest <- chisq.test(theStats["nb",],...)$p.value if (!is.null(stimDuration)) { stationarityTestR <- chisq.test(theStats["nbR",],...)$p.value } else { stationarityTestR <- NULL } result <- list(nbRepeates=nbRepeates, acquisitionWindow=acquisitionWindow, responseWindow=responseWindow, stats=theStats, globalPval=stationarityTest, responsePval=stationarityTestR) class(result) <- "summary.repeatedTrain" return(result) } print.summary.repeatedTrain <- function(x,...) { obj <- x rm(x) cat(paste(obj$nbRepeates, " repeats in the object.\n")) print(t(obj$stats)) cat(paste("The p value of the chi 2 test for the stationarity accross repeats is:\n", obj$globalPval, ".\n",sep="") ) if (!is.null(obj$responseWindow)) cat(paste("The p value of the chi 2 test for the stationarity accross repeats during the stim. is:\n", obj$responsePval, ".\n",sep="") ) } df4counts <- function(repeatedTrain, breaks=length(repeatedTrain) ) { if (!is.repeatedTrain(repeatedTrain)) repeatedTrain <- as.repeatedTrain(repeatedTrain) nbTrials <- length(repeatedTrain) breaksName <- deparse(substitute(breaks)) trainNames <- names(repeatedTrain) if (is.null(trainNames)) trainNames <- paste("trial",1:nbTrials) l <- floor(min(sapply(repeatedTrain,function(l) l[1]))) r <- ceiling(max(sapply(repeatedTrain,function(l) l[length(l)]))) if (length(breaks) == 1) { breaks <- seq(l,r,length.out=breaks+1) } counts <- sapply(repeatedTrain, function(train) hist(x=train[l <= train & train <= r], breaks=breaks, plot=FALSE)$counts ) mids <- breaks[-length(breaks)]+diff(breaks)/2 nb <- length(mids) data.frame(Count=as.numeric(counts), Bin=factor(rep(1:nb,nbTrials)), Trial=factor(rep(trainNames,each=nb)), Rate=as.numeric(counts)/diff(breaks), Time=rep(mids,nbTrials) ) }
view_step <- function(pause_length = 1, step_length = 1, nsteps = NULL, look_ahead = pause_length, delay = 0, include = TRUE, ease = 'cubic-in-out', wrap = TRUE, pause_first = FALSE, fixed_x = FALSE, fixed_y = FALSE, exclude_layer = NULL, aspect_ratio = 1) { ggproto(NULL, ViewStep, fixed_lim = list(x = fixed_x, y = fixed_y), exclude_layer = exclude_layer, aspect_ratio = aspect_ratio, params = list( pause_length = pause_length, step_length = step_length, nsteps = nsteps, look_ahead = look_ahead, delay = delay, include = include, ease = ease, wrap = wrap, pause_first = pause_first ) ) } ViewStep <- ggproto('ViewStep', View, setup_params = function(self, data, params) { nsteps <- params$nstep %||% max(length(params$step_length), length(params$pause_length)) step_length <- rep(params$step_length, length.out = nsteps) pause_length <- rep(params$pause_length, length.out = nsteps) look_ahead <- rep(params$look_ahead, length.out = nsteps) if (!params$pause_first) { pause_length <- c(0, pause_length) step_length <- c(step_length, 0) look_ahead <- c(look_ahead, look_ahead[1]) if (!params$wrap) pause_length[length(pause_length)] <- 0 } else if (!params$wrap) { step_length[length(step_length)] <- 0 } params$step_length <- step_length params$pause_length <- pause_length params$look_ahead <- look_ahead params }, train = function(self, data, params) { nframes <- params$nframes if (params$wrap) nframes <- nframes + 1 frames <- distribute_frames(params$pause_length, params$step_length, nframes) if (!params$pause_first) { frames$transition_length[length(frames$transition_length)] <- frames$transition_length[1] } look_ahead <- round(params$look_ahead * frames$mod) breaks <- cumsum(frames$static_length + frames$transition_length) + look_ahead if (params$wrap) { breaks <- breaks %% nframes breaks[breaks == 0] <- 1L breaks <- if (params$pause_first) { c(breaks[length(breaks)], breaks) } else { c(breaks[length(breaks) - 1], breaks) } } else { breaks <- c(1, pmin(breaks, params$nframes)) } data <- data[!seq_along(data) %in% params$excluded_layers] windows <- lapply(breaks, function(i) { data <- lapply(data, `[[`, i) ranges <- self$get_ranges(data, params) x_range <- range(unlist(lapply(ranges, `[[`, 'x'))) y_range <- range(unlist(lapply(ranges, `[[`, 'y'))) data.frame(xmin = x_range[1], xmax = x_range[2], ymin = y_range[1], ymax = y_range[2]) }) if (params$include) { windows <- lapply(seq_along(windows), function(i) { if (i == 1) { if (!params$wrap) return(windows[[i]]) else i <- c(length(windows), i) } else { i <- c(i - 1, i) } range <- do.call(rbind, windows[i]) data.frame(xmin = min(range$xmin), xmax = max(range$xmax), ymin = min(range$ymin), ymax = max(range$ymax)) }) } frame_ranges <- if (params$wrap) { if (params$pause_first) { windows[[length(windows)]] } else { windows[[length(windows) - 1]] } } else { windows[[1]] } for (i in seq_len(length(windows) - 1)) { if (frames$static_length[i] != 0) { frame_ranges <- keep_state(frame_ranges, frames$static_length[i]) } if (frames$transition_length[i] != 0) { frame_ranges <- self$window_transition(frame_ranges, windows[[i + 1]], frames$transition_length[i], params) } } frame_ranges <- frame_ranges[frame_ranges$.frame <= params$nframes, ] frame_ranges$.frame <- (frame_ranges$.frame + round(params$delay * frames$mod)) %% params$nframes frame_ranges <- frame_ranges[order(frame_ranges$.frame), ] params$frame_ranges <- frame_ranges params }, set_view = function(self, plot, params, i) { range <- params$frame_ranges[i, ] self$reset_limits(plot, c(range$xmin, range$xmax), c(range$ymin, range$ymax)) }, window_transition = function(windows, next_window, n, params) { tween_state(windows, next_window, params$ease, n) } )
context("Kernel loader") test_that("Kernel translator",{ expect_true(is.kern_linear(kernel_translator(1:3, kernel = "linear"))) res <- kernel_translator(1:3, kernel = "fbm,0.7") expect_true(is.kern_fbm(res)) expect_equal(get_hyperparam(res), 0.7) res <- kernel_translator(1:3, kernel = "se,0.7") expect_true(is.kern_se(res)) expect_equal(get_hyperparam(res), 0.7) res1 <- kernel_translator(1:3, kernel = "poly,0.7") res2 <- kernel_translator(1:3, kernel = "poly3") res3 <- kernel_translator(1:3, kernel = "poly4,0.9") expect_true(all(is.kern_poly(res1), is.kern_poly(res2), is.kern_poly(res3))) expect_equal(get_hyperparam(res1), 0.7) expect_equal(get_hyperparam(res2), 0) expect_equal(get_hyperparam(res3), 0.9) expect_equal(get_polydegree(res1), 2) expect_equal(get_polydegree(res2), 3) expect_equal(get_polydegree(res3), 4) }) test_that("Kernel to param to theta", { kernels <- c("linear", "fbm,0.7", "se,2", "poly3,0.15", "pearson") which.pearson <- c(F, F, F, F, T) poly.degree <- c(NA, NA, NA, 3, NA) lambda <- rep(1, 5) psi <- 1 names(psi) <- "psi" res1 <- kernel_to_param(kernels, lambda) res2 <- param_to_theta(res1, list(est.lambda = c(FALSE, TRUE), est.hurst = TRUE, est.lengthscale = FALSE, est.offset = TRUE, est.psi = TRUE)) res3 <- theta_to_param(res2$theta, list(thetal = res2, which.pearson = which.pearson, poly.degree = poly.degree)) expect_equal(kernels, res3$kernels) expect_equal(length(collapse_param(res3)$param), 8) expect_equal(theta_to_psi(res2$theta, list(thetal = res2)), psi) expect_equal(res1, res3) }) test_that("Incorrect specification of kernels", { y <- x <- 1:3 expect_warning(mod <- kernL(y, x, x, x, kernel = c("poly", "se"))) expect_warning(mod <- kernL(y, x, kernel = c("poly", "se"))) }) test_that("Interactions", { y <- x <- 1:3 mod1 <- kernL(y, x, x, x, interactions = c("1:2", "1:2:3")) mod2 <- kernL(stack.loss ~ . ^ 2, stackloss) expect_true(is.ipriorKernel(mod1)) expect_equal(mod1$no.int, 1) expect_equal(mod1$no.int.3plus, 1) expect_true(is.ipriorKernel(mod2)) expect_equal(mod2$no.int, 3) expect_equal(mod2$no.int.3plus, 0) }) test_that("Fixed hyperparameter option", { y <- x <- 1:3 mod <- kernL(y, x, kernel = "fbm,0.8", fixed.hyp = TRUE) expect_true(is.ipriorKernel(mod)) expect_false(all(unlist(mod$estl))) }) test_that("Formula input", { dat <- gen_smooth(3) mod1 <- kernL(y ~ ., dat, kernel = "poly") mod2 <- kernL(dat$y, dat$X, kernel = "poly") tmp1 <- capture.output(print(mod1)) tmp2 <- capture.output(print(mod2)) expect_equal(tmp1[-3], tmp2[-3]) }) test_that("get_Hlam()", { y <- x1 <- 1:3 x2 <- factor(1:3) x3 <- 4:6 mod1 <- kernL(y, x1, x2, x3, kernel = c("se", "pearson", "fbm")) theta1 <- mod1$thetal$theta mod2 <- kernL(y, x1, x2, x3, kernel = c("se", "pearson", "fbm"), est.hurst = TRUE, est.lengthscale = TRUE) theta2 <- mod2$thetal$theta expect_equivalent(get_Hlam(mod1, theta1, theta.is.lambda = TRUE), get_Hlam(mod2, theta2)) }) test_that("Training samples specified", { y <- x <- 1:10 mod <- kernL(y, x, train.samp = 1:5) expect_equal(mod$n, 5) expect_equal(mod$y.test, mod$Xl.test[[1]]) mod <- kernL(y ~ x, data.frame(y, x), train.samp = 1:5) expect_equal(mod$n, 5) expect_equivalent(mod$y.test, mod$Xl.test[[1]]) }) test_that("Test samples specified", { y <- x <- 1:10 mod <- kernL(y, x, test.samp = 1:5) expect_equal(mod$n, 5) expect_equal(mod$y.test, mod$Xl.test[[1]]) mod <- kernL(y ~ x, data.frame(y, x), test.samp = 1:5) expect_equal(mod$n, 5) expect_equivalent(mod$y.test, mod$Xl.test[[1]]) }) test_that("Warn if training samples not correct", { y <- x <- 1:10 expect_warning(kernL(y, x, train.samp = 1:200)) expect_warning(kernL(y, x, train.samp = 250)) }) test_that("Stop if train.samp and test.samp both specified", { y <- x <- 1:10 expect_error(kernL(y, x, train.samp = 1:5, test.samp = 1:5)) })
.correct_r_uvdrr <- function(rxyi, qxa = 1, qyi = 1, ux = 1){ rxpi <- rxyi / qyi (rxpi / (ux * sqrt((1 / ux^2 - 1) * rxpi^2 + 1))) / qxa } .attenuate_r_uvdrr <- function(rtpa, qxa = 1, qyi = 1, ux = 1){ rxpa <- rtpa * qxa ux * rxpa / sqrt((ux^2 - 1) * rxpa^2 + 1) * qyi } .correct_r_uvirr <- function(rxyi, qxi = 1, qyi = 1, ut = 1){ rtpi <- rxyi / (qxi * qyi) rtpi / (ut * sqrt((1 / ut^2 - 1) * rtpi^2 + 1)) } .attenuate_r_uvirr <- function(rtpa, qxi = 1, qyi = 1, ut = 1){ ut * rtpa / sqrt((ut^2 - 1) * rtpa^2 + 1) * (qxi * qyi) } .correct_r_bvdrr <- function(rxyi, qxa = 1, qya = 1, ux = 1, uy = 1){ rtpa <- ((rxyi^2 - 1) / (2 * rxyi) * ux * uy + sign(rxyi) * sqrt((1 - rxyi^2)^2 / (4 * rxyi^2) * ux^2 * uy^2 + 1)) / (qxa * qya) rtpa[is.na(rtpa)] <- 0 rtpa } .attenuate_r_bvdrr <- function(rtpa, qxa = 1, qya = 1, ux = 1, uy = 1){ (sqrt((1/(qya * qxa) - rtpa^2 * qya * qxa)^2 + 4 * rtpa^2 * ux^2 * uy^2) + rtpa^2 * qya * qxa - 1/(qya * qxa))/(2 * rtpa * ux * uy) } .lambda_bvirr <- function(ux, uy, sign_rxz = 1, sign_ryz = 1){ ux_prime <- ux uy_prime <- uy ux_prime[ux > 1 / ux] <- 1 / ux[ux > 1 / ux] uy_prime[uy > 1 / uy] <- 1 / uy[uy > 1 / uy] sign_x <- sign(ux - 1) sign_y <- sign(uy - 1) sign_x <- sign(1 - ux) sign_y <- sign(1 - uy) sign_x * sign_y * sign(sign_rxz * sign_ryz) * (sign_x * ux_prime + sign_y * uy_prime) / (ux_prime + uy_prime) } .correct_r_bvirr <- function(rxyi, qxa = 1, qya = 1, ux = 1, uy = 1, sign_rxz = 1, sign_ryz = 1){ lambda <- .lambda_bvirr(ux = ux, uy = uy, sign_rxz = sign_rxz, sign_ryz = sign_ryz) (rxyi * ux * uy + lambda * sqrt(abs(1 - ux^2) * abs(1 - uy^2))) / (qxa * qya) } .attenuate_r_bvirr <- function(rtpa, qxa = 1, qya = 1, ux = 1, uy = 1, sign_rxz = 1, sign_ryz = 1){ lambda <- .lambda_bvirr(ux = ux, uy = uy, sign_rxz = sign_rxz, sign_ryz = sign_ryz) (rtpa * qxa * qya - lambda * sqrt(abs(1 - ux^2) * abs(1 - uy^2))) / (ux * uy) } .correct_r_rb <- function(rxyi, qx = 1, qy = 1, ux = 1){ rxyi / (qx * qy * sqrt(ux + rxyi^2 * (1 - ux^2))) } .attenuate_r_rb <- function(rtpa, qx = 1, qy = 1, ux = 1){ (rtpa * qy * qx * ux) / sqrt(rtpa^2 * qy^2 * qx^2 * ux^2 - rtpa^2 * qy^2 * qx^2 + 1) }
panel.xblocks <- function(x, ...) UseMethod("panel.xblocks") panel.xblocks.default <- function (x, y, ..., col = NULL, border = NA, height = unit(1, "npc"), block.y = unit(0, "npc"), vjust = 0, name = "xblocks", gaps = FALSE, last.step = median(diff(tail(x)))) { if (is.function(y)) y <- y(x) x <- as.numeric(x) if (length(x) == 0) return() if (is.unsorted(x, na.rm = TRUE)) stop("'x' should be ordered (increasing)") if (is.na(last.step)) last.step <- 0 if (gaps) { .Deprecated(msg = "The 'gaps' argument is deprecated; use panel.xblocks(time(z), is.na(z))") y <- is.na(y) } if (is.logical(y)) { y <- y } else if (is.numeric(y)) { y <- !is.na(y) } else { y <- as.character(y) } NAval <- if (is.character(y)) "" else FALSE y[is.na(y)] <- NAval yrle <- rle(y) blockCol <- yrle$values blockCol[blockCol == NAval] <- NA if (is.logical(y) && is.null(col)) col <- trellis.par.get("plot.line")$col if (length(col) > 0) { if (is.character(col)) col[col == ""] <- NA ok <- !is.na(blockCol) blockCol[ok] <- rep(col, length = sum(ok)) } idxBounds <- cumsum(c(1, yrle$lengths)) idxStart <- head(idxBounds, -1) idxEnd <- tail(idxBounds, -1) idxEnd[length(idxEnd)] <- length(y) blockStart <- x[idxStart] blockEnd <- x[idxEnd] blockEnd[length(blockEnd)] <- tail(blockEnd, 1) + last.step blockWidth <- blockEnd - blockStart grid::grid.rect(x = blockStart, width = blockWidth, y = block.y, height = height, hjust = 0, vjust = vjust, default.units = "native", name = name, gp = gpar(fill = blockCol, col = border, ...)) } panel.xblocks.ts <- function(x, y = x, ...) { if (!is.function(y)) y <- as.vector(y) panel.xblocks(as.vector(time(x)), y, ...) } panel.xblocks.zoo <- function(x, y = x, ...) { if (!is.function(y)) y <- zoo::coredata(y) panel.xblocks(zoo::index(x), y, ...) }
geom_segment_3d <- function(mapping = NULL, data = NULL, stat = "identity", position = "identity", ..., arrow = NULL, arrow.fill = NULL, lineend = "butt", linejoin = "round", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, extrude = FALSE, material = list(), keep2d = FALSE) { layer( data = data, mapping = mapping, stat = stat, geom = GeomSegment3d, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list( arrow = arrow, arrow.fill = arrow.fill, lineend = lineend, linejoin = linejoin, na.rm = na.rm, extrude = extrude, material = material, keep2d = keep2d, ... ) ) } GeomSegment3d <- ggplot2::ggproto( "GeomSegment3d", ggplot2::Geom, required_aes = c("x", "y", "z", "xend", "yend", "zend"), non_missing_aes = c("linetype", "size", "shape"), default_aes = augment_aes( extrusion_aesthetics, aes( colour = "black", size = 0.5, linetype = 1, alpha = NA ) ), draw_panel = function(data, panel_params, coord, arrow = NULL, arrow.fill = NULL, lineend = "butt", linejoin = "round", na.rm = FALSE, extrude = FALSE, material = list(), keep2d = FALSE) { if (isTRUE(keep2d)) { grob2d <- GeomSegment$draw_panel(data, panel_params, coord, arrow = arrow, arrow.fill = arrow.fill, lineend = lineend, linejoin = linejoin, na.rm = na.rm) } else { grob2d <- ggplot2::zeroGrob() } data <- remove_missing( data, na.rm = na.rm, c("x", "y", "xend", "yend", "linetype", "size", "shape"), name = "geom_segment" ) if (empty(data)) return(ggplot2::zeroGrob()) if (!coord$is_linear()) { abort("GeomSegment3d: Non-linear coord not handled. (yet!)") } coord <- coord$transform(data, panel_params) arrow.fill <- arrow.fill %||% coord$colour x <- with(coord, interleave(x, xend)) y <- with(coord, interleave(y, yend)) z <- with(coord, interleave(z, zend)) color <- with(coord, rep(colour, each = 2)) size <- with(coord, rep(size , each = 2)) alpha <- with(coord, rep(alpha , each = 2)) alpha <- ifelse(is.na(alpha), 1, alpha) rgl_call <- cryogenic::capture_call( segments3d( x = x, y = y, z = z, color = color, alpha = alpha, lwd = coord$size[1] * ggplot2::.pt ), defaults = material ) segments_grob <- snowcrash::encode_robj_to_rasterGrob(rgl_call) extrusion <- list(faces_grob = ggplot2::zeroGrob(), edges_grob = ggplot2::zeroGrob()) if (isTRUE(extrude)) { ex_data <- coord ex_data$id <- seq_len(nrow(ex_data)) ex_data2 <- ex_data ex_data2$x <- ex_data2$xend ex_data2$y <- ex_data2$yend ex_data2$z <- ex_data2$zend ex_data <- rbind(ex_data, ex_data2) ex_data <- ex_data[order(ex_data$id),] ex_data$id <- ceiling(seq_len(nrow(ex_data))/2) extrusion <- create_extrusion(ex_data, closed = FALSE) } grid::grobTree( grob2d, segments_grob, extrusion$faces_grob, extrusion$edges_grob ) }, draw_key = ggplot2::draw_key_path )
readResults = function(N = 0, rel = "UN", gzip = TRUE, strPath = "", strVer = "", fileName = NULL){ if(is.null(fileName)){ if(nchar(strVer)==0){ fileName = sprintf("results-sim-%s-%d.csv", rel, N) }else{ fileName = sprintf("results-sim-%s-%d-%s.csv", rel, N, strVer) } } if(nchar(strPath)>0){ fileName = paste(strPath, fileName, sep = "") } if(gzip & !grepl("gz$", fileName)) fileName = paste(fileName, ".gz", sep = "") res = matrix(scan(fileName, sep = ','), ncol = 3, byrow = T) return(data.frame(sib = res[,1], pc = res[,2], ibs = res[,3])) }
printClustersFromLabels<-function(obj,labels) { N<-dim(obj$Qmat)[1] clsIDVec<-sort(unique(obj$indexClsVec) ) if(missing(labels)) { IDs<-1:N for(cls in clsIDVec) { print("===============") M<-sum(obj$indexClsVec == cls) print(sprintf("ID%d, md%.2f, N%d",cls,obj$homoClusters[[cls]]$maxDiffAdmixRatio,M)) print(IDs[obj$indexClsVec == cls]) } }else{ print("Overall labels") print("===============") str<-"" allLabelVec<-unique(labels) countVec<-c() for(label_itr in allLabelVec) { c1<-sum( labels == label_itr ) countVec<-c(countVec,c1) str<-sprintf("%s%s(%d)",str,label_itr,c1) } print(str) for(cls in clsIDVec) { print("===============") currLabels<-labels[obj$indexClsVec == cls] currLabelsMembers<-unique(currLabels) print(sprintf("ID%d, md%.2f, N%d",cls,obj$homoClusters[[cls]]$maxDiffAdmixRatio,length(currLabels))) str<-"" for(label_itr in currLabelsMembers) { c1<-sum( currLabels == label_itr ) c2<-countVec[allLabelVec == label_itr] str<-sprintf("%s%s(%d/%d)",str,label_itr,c1,c2) } print(str) } } }
thetaHill <- function (x, k = NULL, x0 = NULL, w = NULL) { if(!is.numeric(x) || length(x) == 0) stop("'x' must be a numeric vector") haveK <- !is.null(k) if(haveK) { if(!is.numeric(k) || length(k) == 0 || k[1] < 1) { stop("'k' must be a positive integer") } else k <- k[1] } else if(!is.null(x0)) { if(!is.numeric(x0) || length(x0) == 0) stop("'x0' must be numeric") else x0 <- x0[1] } else stop("either 'k' or 'x0' must be supplied") haveW <- !is.null(w) if(haveW) { if(!is.numeric(w) || length(w) != length(x)) { stop("'w' must be numeric vector of the same length as 'x'") } if(any(w < 0)) stop("negative weights in 'w'") if(any(i <- is.na(x))) { x <- x[!i] w <- w[!i] } order <- order(x) x <- x[order] w <- w[order] } else { if(any(i <- is.na(x))) x <- x[!i] x <- sort(x) } .thetaHill(x, k, x0, w) } .thetaHill <- function (x, k = NULL, x0 = NULL, w = NULL) { n <- length(x) haveK <- !is.null(k) haveW <- !is.null(w) if(haveK) { if(k >= n) stop("'k' must be smaller than the number of observed values") x0 <- x[n-k] } else { if(x0 >= x[n]) stop("'x0' must be smaller than the maximum of 'x'") k <- length(which(x > x0)) } if(haveW) { w <- w[(n-k+1):n] sum(w)/sum(w*(log(x[(n-k+1):n]) - log(x0))) } else { k/sum(log(x[(n-k+1):n]) - log(x0)) } }
topidx <- function(DEM, resolution, river=NULL) { nrow <- dim(DEM)[1] ncol <- dim(DEM)[2] stopifnot(is(DEM, "matrix"),(is(river,"matrix") || is.null(river))) if(min(as.vector(DEM[!is.na(DEM)])) < -9000) stop("DEM contains unrealistic values (< -9000)") if(is.null(river)) { river = rep(0,nrow*ncol) } else { if(min(river) < 0) stop("Error: the object 'river' should only contain positive values") } DEM[is.na(DEM)] <- -9999 result <- .C("c_topidx", PACKAGE = "topmodel", as.double(DEM), as.integer(river), as.integer(nrow), as.integer(ncol), as.double(resolution), as.double(resolution), result = double(length(DEM)*2))$result atb <- matrix(result[1:(nrow*ncol)],nrow=nrow) area <- matrix(result[(nrow*ncol+1):(nrow*ncol*2)],nrow=nrow) atb[atb < -9] <- NA area[area < -9] <- NA return(list(atb = atb,area = area)) }
summary.MangroveTree <- function(object,...){ object$printSummary() }
subgroups <- function(las, x, select, continuous, breaks, default_breaks = 4, thresholds = c(-0.05, 0.05), significance, alpha = 0.01) { if (!"lassie" %in% class(las)) { stop("Invalid 'las' argument: must be a 'lassie' object") } x <- tryCatch(data.frame(x), error = function(c) { stop("Invalid 'x' argument: must be convertible to a data.frame") }) if (nrow(x) != nrow(las$data$raw)) { stop("Invalid 'las' or 'x' argument: raw 'las' data.frame must have the same number of rows as 'x'. Check if you are not using two different data.frames") } raw <- x if (missing(select) || is.null(select)) { select <- colnames(raw)[! colnames(raw) %in% las$lassie_params$var] } x <- tryCatch(subset(raw, select = select), error = function(c) { stop("Invalid 'select' argument: needs to be a vector of column numbers or column names") }) select <- colnames(x) if (any(select %in% las$lassie_params$var)) { stop("Invalid 'select' argument: variable names in 'select' cannot correspond to variable names in 'las'") } if (missing(continuous) || is.null(continuous)) { continuous <- NULL } continuous <- tryCatch(colnames(subset(raw, select = continuous)), error = function(c) { stop("Invalid 'continuous' argument: needs to be a vector of column numbers or column names") }) if (missing(breaks)) { breaks <- NULL } if (!is.numeric(thresholds) || length(thresholds) != 2) { stop("Invalid 'tresholds' argument: must be two numeric values") } if (thresholds[1] > thresholds[2]) { thresholds <- sort(thresholds, decreasing = FALSE) } if ((missing(significance) || is.null(significance))) { if ("permtest" %in% class(x)) significance <- TRUE else significance <- FALSE } if (! "permtest" %in% class(las) && significance) { warning("Invalid 'significance' argument: run permtest to take into account significance of values. Resuming subgroup analysis with 'significance' set to FALSE") significance <- FALSE } if (significance && (!is.numeric(alpha) || alpha <= 0 || alpha >= 1)) { stop("Invalid 'alpha' argument: must be a numeric between 0 and 1 non included") } measure <- las$lassie_params$measure df <- reshape2::melt(las$local, value.name = "local") pos <- df$local > thresholds[2] neg <- df$local < thresholds[1] if (significance) { local_p <- reshape2::melt(las$local_p, value.name = "local_p") df <- plyr::join(df, local_p, by = las$lassie_params$var) pos <- pos & df$local_p <= alpha neg <- neg & df$local_p <= alpha } ind <- !pos & !neg df$subgroups <- NA_character_ assoc_levels <- c() if (sum(pos) > 0) { df$subgroups[pos] <- "Positive" assoc_levels <- c(assoc_levels, "Positive") } if (sum(ind) > 0) { df$subgroups[ind] <- "Independent" assoc_levels <- c(assoc_levels, "Independent") } if (sum(neg) > 0) { df$subgroups[neg] <- "Negative" assoc_levels <- c(assoc_levels, "Negative") } if (length(assoc_levels) < 2) { stop("Analysis requires at least two local association subgroups. Try setting less stringent 'thresholds' or 'alpha' level, or setting 'significance' to FALSE.") } df$subgroups <- factor(df$subgroups, levels = assoc_levels) df <- plyr::join(las$data$pp, df, by = las$lassie_params$var) na <- stats::na.action(las$data$pp) x <- subset(x, subset = ! 1:nrow(x) %in% na) df <- cbind(df$subgroups, x) new_varname <- paste(las$lassie_params$var, collapse="_") colnames(df)[1] <- new_varname select <- c(select, new_varname) lassie(df, select = select, continuous = continuous, measure = measure, breaks = breaks, default_breaks = default_breaks) }
nlsfit <- function(data, model=1, start=c(a=1,b=1,c=1,d=1, e=1)){ s=start n=names(data) d1 = as.data.frame(data[, 1]) d2 = as.data.frame(data[, -1]) f = function(h) { data.frame(d1, d2[h]) } h = length(d2) h = 1:h l = lapply(h, f) R2 <- function(m) { gl <- length(fitted(m)) - 1 sqt <- var((fitted(m) + resid(m))) * gl r1 <- (sqt - deviance(m))/sqt r1=round(r1,4) return(r1) } R3 <- function(m) { gl <- length(fitted(m)) - 1 sqt <- var((fitted(m) + resid(m))) * gl r1 <- (sqt - deviance(m))/sqt p1 <- (gl/((gl + 1) - (length(coef(m) + 1))) * (1 - r1)) r2 <- 1 - p1 r2=round(r2,4) return(r2) } f1=function(data){names(data) = c("x", "y") ml = lm(data[, 2] ~ data[, 1]) c1 = coef(ml)[[1]] c2 = coef(ml)[[2]] m=nls(y~a+b*x, data=data, start=list(a=c1,b=c2),control = nls.control(maxiter = 6000)) c=coef(m); s=summary(m); a=c[1];b=c[2];l=c(a,b,summary(m)[11][[1]][7], summary(m)[11][[1]][8], R2(m), R3(m),AIC(m), BIC(m)); l=round(l,8);l=as.data.frame(l) rownames(l)=c("coefficient a", "coefficient b", "p-value t.test for a", "p-value t.test for b", "r-squared", "adjusted r-squared", "AIC", "BIC") return(l)} f2=function(data){names(data) = c("x", "y") mq = lm(data[, 2] ~ data[, 1] + I(data[, 1]^2)) c3 = coef(mq)[[1]] c4 = coef(mq)[[2]] c5 = coef(mq)[[3]] m=nls(y~a+b*x+c*x^2, data=data, start=list(a=c3,b=c4,c=c5),control = nls.control(maxiter = 6000));c=coef(m); s=summary(m); a=c[1];b=c[2];c=c[3];pm = a - (b^2)/(4 * c) pc = -0.5 * b/c; l=c(a,b,c,summary(m)[11][[1]][10], summary(m)[11][[1]][11], summary(m)[11][[1]][12], R2(m), R3(m),AIC(m), BIC(m), pm,pc); l=round(l,8);l=as.data.frame(l) rownames(l)=c("coefficient a", "coefficient b", "coefficient c", "p-value t.test for a", "p-value t.test for b", "p-value t.test for c", "r-squared", "adjusted r-squared", "AIC", "BIC","maximum or minimum value for y", "critical point in x") return(l) } f3=function(data){names(data) = c("x", "y") ml = lm(data[, 2] ~ data[, 1]) mq = lm(data[, 2] ~ data[, 1] + I(data[, 1]^2)) c1 = coef(ml)[[1]] c2 = coef(ml)[[2]] c3 = coef(mq)[[1]] c4 = coef(mq)[[2]] c5 = coef(mq)[[3]] pc = -0.5 * c4/c5 ff=function(x){c3+c4*x+c5*x^2} pp=ff(pc) a=start[1] b=start[2] c=start[3] a11=ifelse(a==1,pp,a) b11=ifelse(b==1,c2,b) c11=ifelse(c==1,pc,c) m <- nls(y ~ a + b * (x - c) * (x <= c), start = list(a = a11, b = b11, c = c11), data = data, control = nls.control(maxiter = 6000)) c=coef(m); a=c[1];b=c[2];c=c[3] l=c(a,b,c,summary(m)[11][[1]][10], summary(m)[11][[1]][11], summary(m)[11][[1]][12], R2(m), R3(m),AIC(m), BIC(m), a,c); l=round(l,8);l=as.data.frame(l) rownames(l)=c("coefficient a", "coefficient b", "coefficient c", "p-value t.test for a", "p-value t.test for b", "p-value t.test for c", "r-squared", "adjusted r-squared", "AIC", "BIC","maximum or minimum value for y", "critical point in x") return(l) } f4=function(data){names(data) = c("x", "y") mq = lm(data[, 2] ~ data[, 1] + I(data[, 1]^2)) c3 = coef(mq)[[1]] c4 = coef(mq)[[2]] c5 = coef(mq)[[3]] a=start[1] b=start[2] c=start[3] a11=ifelse(a==1,c3,a) b11=ifelse(b==1,c4,b) c11=ifelse(c==1,c5,c) m <- nls(y ~ (a + b * x + c * I(x^2)) * (x <= -0.5 * b/c) + (a + I(-b^2/(4 * c))) * (x > -0.5 * b/c), start = list(a = a11, b = b11, c = c11), data = data, control = nls.control(maxiter = 6000)) c=coef(m); a=c[1];b=c[2];c=c[3] pmm = (a + I(-b^2/(4 * c))) pcc = -0.5 * b/c l=c(a,b,c,summary(m)[11][[1]][10], summary(m)[11][[1]][11], summary(m)[11][[1]][12], R2(m), R3(m),AIC(m), BIC(m), pmm,pcc); l=round(l,8);l=as.data.frame(l) rownames(l)=c("coefficient a", "coefficient b", "coefficient c", "p-value t.test for a", "p-value t.test for b", "p-value t.test for c", "r-squared", "adjusted r-squared", "AIC", "BIC","maximum or minimum value for y", "critical point in x") return(l) } f5=function(data){names(data) = c("x", "y") fp=function(a,b,c,x,d){ifelse(x>=d,(a-c*d)+(b+c)*x, a+b*x)} m=nls(y~fp(a,b,c,x,d), start=list(a=s[1],b=s[2],c=s[3], d=s[4]), data=data,control = nls.control(maxiter = 6000));c=coef(m); a=c[1];b=c[2];c1=c;c=c[3];d=c1[4] l=c(a,b,c,d,summary(m)[11][[1]][13], summary(m)[11][[1]][14], summary(m)[11][[1]][15],summary(m)[11][[1]][16], R2(m), R3(m),AIC(m), BIC(m)); l=round(l,8);l=as.data.frame(l) rownames(l)=c("coefficient a", "coefficient b", "coefficient c","coefficient d", "p-value t.test for a", "p-value t.test for b", "p-value t.test for c", "p-value t.test for d","r-squared", "adjusted r-squared", "AIC", "BIC") return(l) } f6=function(data){names(data) = c("x", "y") m=nls(y~a*exp(b*x) ,start=list(a=s[1],b=s[2]),data=data,control = nls.control(maxiter = 6000));c=coef(m); a=c[1];b=c[2] l=c(a,b,summary(m)[11][[1]][7], summary(m)[11][[1]][8], R2(m), R3(m),AIC(m), BIC(m)); l=round(l,8);l=as.data.frame(l) rownames(l)=c("coefficient a", "coefficient b", "p-value t.test for a", "p-value t.test for b", "r-squared", "adjusted r-squared", "AIC", "BIC") return(l) } f7=function(data){names(data) = c("x", "y") m=nls(y~a*(1+b*(exp(-c*x)))^-1, data=data, start=list(a=s[1],b=s[2],c=s[3]),control = nls.control(maxiter = 6000));c=coef(m); s=summary(m); a=c[1];b=c[2];c=c[3]; l=c(a,b,c,summary(m)[11][[1]][10], summary(m)[11][[1]][11], summary(m)[11][[1]][12], R2(m), R3(m),AIC(m), BIC(m)); l=round(l,8);l=as.data.frame(l) rownames(l)=c("coefficient a", "coefficient b", "coefficient c", "p-value t.test for a", "p-value t.test for b", "p-value t.test for c", "r-squared", "adjusted r-squared", "AIC", "BIC") return(l) } f8=function(data){names(data) = c("x", "y") m=nls(y~a*(1-b*(exp(-c*x)))^3, data=data, start=list(a=s[1],b=s[2],c=s[3]),control = nls.control(maxiter = 6000));c=coef(m); s=summary(m); a=c[1];b=c[2];c=c[3]; l=c(a,b,c,summary(m)[11][[1]][10], summary(m)[11][[1]][11], summary(m)[11][[1]][12], R2(m), R3(m),AIC(m), BIC(m)); l=round(l,8);l=as.data.frame(l) rownames(l)=c("coefficient a", "coefficient b", "coefficient c", "p-value t.test for a", "p-value t.test for b", "p-value t.test for c", "r-squared", "adjusted r-squared", "AIC", "BIC") return(l) } f9=function(data){names(data) = c("x", "y") m=nls(y~a*(1-b*(exp(-c*x))), data=data, start=list(a=s[1],b=s[2],c=s[3]),control = nls.control(maxiter = 6000));c=coef(m); s=summary(m); a=c[1];b=c[2];c=c[3]; l=c(a,b,c,summary(m)[11][[1]][10], summary(m)[11][[1]][11], summary(m)[11][[1]][12], R2(m), R3(m),AIC(m), BIC(m)); l=round(l,8);l=as.data.frame(l) rownames(l)=c("coefficient a", "coefficient b", "coefficient c", "p-value t.test for a", "p-value t.test for b", "p-value t.test for c", "r-squared", "adjusted r-squared", "AIC", "BIC") return(l) } f10=function(data){names(data) = c("x", "y") m=nls(y~a*exp(-b*exp(-c*x)), data=data, start=list(a=s[1],b=s[2],c=s[3]),control = nls.control(maxiter = 6000));c=coef(m); s=summary(m); a=c[1];b=c[2];c=c[3]; l=c(a,b,c,summary(m)[11][[1]][10], summary(m)[11][[1]][11], summary(m)[11][[1]][12], R2(m), R3(m),AIC(m), BIC(m)); l=round(l,8);l=as.data.frame(l) rownames(l)=c("coefficient a", "coefficient b", "coefficient c", "p-value t.test for a", "p-value t.test for b", "p-value t.test for c", "r-squared", "adjusted r-squared", "AIC", "BIC") return(l) } f11=function(data){names(data) = c("x", "y") m=nls(y~(a*x^b)*exp(-c*x), data=data, start=list(a=s[1],b=s[2],c=s[3]),control = nls.control(maxiter = 6000));c=coef(m); s=summary(m); a=c[1];b=c[2];c=c[3]; pm=a*(b/c)^b*exp(-b);pc=b/c;l=c(a,b,c,summary(m)[11][[1]][10], summary(m)[11][[1]][11], summary(m)[11][[1]][12], R2(m), R3(m),AIC(m), BIC(m), pm,pc); l=round(l,8);l=as.data.frame(l) rownames(l)=c("coefficient a", "coefficient b", "coefficient c", "p-value t.test for a", "p-value t.test for b", "p-value t.test for c", "r-squared", "adjusted r-squared", "AIC", "BIC","maximum or minimum value for y", "critical point in x") return(l) } y1=c(25,24,26,28,30,31,27,26,25,24,23,24,22,21,22,20,21,19,18,17,18,18,16,17,15,16,14) x1=c(15,15,15,75,75,75,135,135,135,195,195,195,255,255,255,315,315,315,375,375,375,435,435,435, 495,495,495) dados=data.frame(x1,y1) f12=function(data){names(data) = c("x", "y") m=nls(y ~ a + b * (1 - exp(-c * x)), data=data, start=list(a=20,b=60,c=0.05),control = nls.control(maxiter = 6000));c=coef(m); s=summary(m); a=c[1];b=c[2];c=c[3]; l=c(a,b,c,summary(m)[11][[1]][10], summary(m)[11][[1]][11], summary(m)[11][[1]][12], R2(m), R3(m),AIC(m), BIC(m)); l=round(l,8);l=as.data.frame(l) rownames(l)=c("coefficient a", "coefficient b", "coefficient c", "p-value t.test for a", "p-value t.test for b", "p-value t.test for c", "r-squared", "adjusted r-squared", "AIC", "BIC") return(l) } tempo=c(0,12,24,36,48,60,72,84,96,108,120,144,168,192) gas=c(0.002,3.8,8,14.5,16,16.5,17,17.4,17.9,18.1,18.8,19,19.2,19.3) d=data.frame(tempo,gas) m=nls(gas~(vf1/(1+exp(2-4*k1*(tempo-l))))+(vf2/(1+exp(2-4*k2*(tempo-l)))), start=list(vf1=19,vf2=4,k1=0.05,k2=0.005,l=5), data=d) f13=function(data){names(data) = c("x", "y") m=nls(y~(a/(1+exp(2-4*c*(x-e))))+(b/(1+exp(2-4*d*(x-e)))), start=list(a=s[1],b=s[2],c=s[3],d=s[4],e=s[5]), data=data,control = nls.control(maxiter = 6000));cc=coef(m); s=summary(m); a=cc[1];b=cc[2];c=cc[3];d=cc[4];e=cc[5]; l=c(a,b,c,d,e,summary(m)[11][[1]][16], summary(m)[11][[1]][17], summary(m)[11][[1]][18],summary(m)[11][[1]][19],summary(m)[11][[1]][20], R2(m), R3(m),AIC(m), BIC(m)); l=round(l,8);l=as.data.frame(l) rownames(l)=c("coefficient a", "coefficient b", "coefficient c","coefficient d","coefficient e", "p-value t.test for a", "p-value t.test for b", "p-value t.test for c","p-value t.test for d","p-value t.test for e" ,"r-squared", "adjusted r-squared", "AIC", "BIC") return(l) } fun=list(f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13) fu=fun[[model]] r1=as.data.frame(lapply(l, fu)) names(r1)=n[-1] models=c("y~a+b*x","y~a+b*x+c*x^2","y ~ a + b * (x - c) * (x <= c)","y ~ (a + b * x + c * I(x^2)) * (x <= -0.5 * b/c) + (a + I(-b^2/(4 * c))) * (x > -0.5 * b/c)","ifelse(x>=d,(a-c*d)+(b+c)*x, a+b*x)","y~a*exp(b*x)","y~a*(1+b*(exp(-c*x)))^-1","y~a*(1-b*(exp(-c*x)))^3","y~a*(1-b*(exp(-c*x)))", "y~a*exp(-b*exp(-c*x)","y~(a*x^b)*exp(-c*x)","y ~ a + b * (1 - exp(-c * x))","y~(a/(1+exp(2-4*c*(x-e))))+(b/(1+exp(2-4*d*(x-e))))") r2=models[model] r=list(r2,r1);names(r)=c("Model","Parameters") return(r) }
.runThisTest <- Sys.getenv("RunAllinsightTests") == "yes" if (.runThisTest && Sys.getenv("USER") != "travis") { if (requiet("testthat") && requiet("insight") && requiet("VGAM")) { data("hunua") m1 <- download_model("vgam_1") m2 <- download_model("vgam_2") test_that("model_info", { expect_true(model_info(m1)$is_binomial) expect_true(model_info(m2)$is_binomial) expect_false(model_info(m1)$is_bayesian) expect_false(model_info(m2)$is_bayesian) }) test_that("find_predictors", { expect_identical(find_predictors(m1), list(conditional = c("vitluc", "altitude"))) expect_identical( find_predictors(m1, flatten = TRUE), c("vitluc", "altitude") ) expect_null(find_predictors(m1, effects = "random")) expect_identical(find_predictors(m2), list(conditional = c("vitluc", "altitude"))) expect_identical( find_predictors(m2, flatten = TRUE), c("vitluc", "altitude") ) expect_null(find_predictors(m2, effects = "random")) }) test_that("find_random", { expect_null(find_random(m1)) expect_null(find_random(m2)) }) test_that("get_random", { expect_warning(get_random(m1)) expect_warning(get_random(m2)) }) test_that("find_response", { expect_identical(find_response(m1), "agaaus") expect_identical(find_response(m2), "cbind(agaaus, kniexc)") expect_identical(find_response(m2, combine = FALSE), c("agaaus", "kniexc")) }) test_that("get_response", { expect_equal(get_response(m1), hunua$agaaus) expect_equal( get_response(m2), data.frame(agaaus = hunua$agaaus, kniexc = hunua$kniexc) ) }) test_that("get_predictors", { expect_equal(colnames(get_predictors(m1)), c("vitluc", "altitude")) expect_equal(colnames(get_predictors(m2)), c("vitluc", "altitude")) }) test_that("link_inverse", { expect_equal(link_inverse(m1)(.2), plogis(.2), tolerance = 1e-5) expect_equal(link_inverse(m2)(.2), plogis(.2), tolerance = 1e-5) }) test_that("get_data", { expect_equal(nrow(get_data(m1)), 392) expect_equal(nrow(get_data(m2)), 392) expect_equal(colnames(get_data(m1)), c("agaaus", "vitluc", "altitude")) expect_equal( colnames(get_data(m2)), c("agaaus", "kniexc", "vitluc", "altitude") ) }) test_that("find_formula", { expect_length(find_formula(m1), 1) expect_equal( find_formula(m1), list(conditional = as.formula("agaaus ~ vitluc + s(altitude, df = 2)")), ignore_attr = TRUE ) expect_length(find_formula(m2), 1) expect_equal( find_formula(m2), list( conditional = as.formula("cbind(agaaus, kniexc) ~ vitluc + s(altitude, df = c(2, 3))") ), ignore_attr = TRUE ) }) test_that("find_terms", { expect_equal( find_terms(m1), list( response = "agaaus", conditional = c("vitluc", "s(altitude, df = 2)") ) ) expect_equal( find_terms(m1, flatten = TRUE), c("agaaus", "vitluc", "s(altitude, df = 2)") ) expect_equal( find_terms(m2), list( response = "cbind(agaaus, kniexc)", conditional = c("vitluc", "s(altitude, df = c(2, 3))") ) ) expect_equal( find_terms(m2, flatten = TRUE), c( "cbind(agaaus, kniexc)", "vitluc", "s(altitude, df = c(2, 3))" ) ) }) test_that("find_variables", { expect_equal( find_variables(m1), list( response = "agaaus", conditional = c("vitluc", "altitude") ) ) expect_equal( find_variables(m1, flatten = TRUE), c("agaaus", "vitluc", "altitude") ) expect_equal(find_variables(m2), list( response = c("agaaus", "kniexc"), conditional = c("vitluc", "altitude") )) expect_equal( find_variables(m2, flatten = TRUE), c("agaaus", "kniexc", "vitluc", "altitude") ) }) test_that("n_obs", { expect_equal(n_obs(m1), 392) expect_equal(n_obs(m2), 392) }) test_that("linkfun", { expect_false(is.null(link_function(m1))) expect_false(is.null(link_function(m2))) }) test_that("find_parameters", { expect_equal( find_parameters(m1), list( conditional = c("(Intercept)", "vitluc"), smooth_terms = "s(altitude, df = 2)" ) ) expect_equal(nrow(get_parameters(m1)), 3) expect_equal( get_parameters(m1)$Parameter, c("(Intercept)", "vitluc", "s(altitude, df = 2)") ) expect_equal( find_parameters(m2), list( conditional = c( "(Intercept):1", "(Intercept):2", "vitluc:1", "vitluc:2" ), smooth_terms = c("s(altitude, df = c(2, 3)):1", "s(altitude, df = c(2, 3)):2") ) ) expect_equal(nrow(get_parameters(m2)), 6) expect_equal( get_parameters(m2)$Parameter, c( "(Intercept):1", "(Intercept):2", "vitluc:1", "vitluc:2", "s(altitude, df = c(2, 3)):1", "s(altitude, df = c(2, 3)):2" ) ) }) test_that("is_multivariate", { expect_false(is_multivariate(m1)) expect_false(is_multivariate(m2)) }) test_that("find_statistic", { expect_identical(find_statistic(m1), "chi-squared statistic") expect_identical(find_statistic(m2), "chi-squared statistic") }) } }
setClass("EUtilsSummary", representation( db = "character", count = "numeric", retmax = "numeric", retstart = "numeric", PMID = "character", querytranslation = "character" ) ) EUtilsSummary <- function(query,type="esearch",db="pubmed",url=NULL,encoding="unknown",...){ if(is.null(url)){ url <- EUtilsQuery(query,type,db,...) } lines <- readLines(url,warn=FALSE,encoding=encoding) res <- ParseTags(lines) EMPTYCHECK <- length(grep("^(?:<eSearchResult>)?<Count>0<\\/Count>", lines))!=0 if(EMPTYCHECK){ res$Id <- character(0) res$Count <- 0 } new("EUtilsSummary", db = db, count = res$Count, retstart = res$RetStart, retmax = res$RetMax, PMID = res$Id, querytranslation = res$QueryTranslation ) } setMethod("print","EUtilsSummary",function(x,...) print(x@querytranslation)) setMethod("show","EUtilsSummary",function(object) print(object@querytranslation)) setMethod("summary","EUtilsSummary",function(object,...){ cat("Query:\n") cat(object@querytranslation,"\n\n") cat("Result count: ",object@count) invisible(object@PMID) }) setMethod("QueryCount","EUtilsSummary",function(object) object@count) setMethod("QueryId","EUtilsSummary",function(object) object@PMID) setMethod("QueryTranslation","EUtilsSummary",function(object) object@querytranslation)
getPowerFitNested <- function(altNested, altParent, cutoff = NULL, nullNested = NULL, nullParent = NULL, revDirec = FALSE, usedFit = NULL, alpha = 0.05, nVal = NULL, pmMCARval = NULL, pmMARval = NULL, condCutoff = TRUE, df = 0) { result <- NULL if(is.null(cutoff)) { if(!is.null(nullNested) & !is.null(nullParent)) { result <- getPowerFitNestedNullObj(altNested = altNested, altParent = altParent, nullNested = nullNested, nullParent = nullParent, revDirec = revDirec, usedFit = usedFit, alpha = alpha, nVal = nVal, pmMCARval = pmMCARval, pmMARval = pmMARval, df = df) } else { stop("Please specify fit index cutoff, 'cutoff', or the result object representing the null model, 'nullObject'.") } } else { if(is.null(nullNested) & is.null(nullParent)) { result <- getPowerFitNestedCutoff(altNested = altNested, altParent = altParent, cutoff = cutoff, revDirec = revDirec, usedFit = usedFit, nVal = nVal, pmMCARval = pmMCARval, pmMARval = pmMARval, condCutoff = condCutoff, df = df) } else { stop("Please specify either fit index cutoff, 'cutoff', or the result object representing the null model, 'nullObject', but not both.") } } result } getPowerFitNestedCutoff <- function(altNested, altParent, cutoff, revDirec = FALSE, usedFit = NULL, nVal = NULL, pmMCARval = NULL, pmMARval = NULL, condCutoff = TRUE, df = 0) { if (is.null(nVal) || is.na(nVal)) nVal <- NULL if (is.null(pmMCARval) || is.na(pmMCARval)) pmMCARval <- NULL if (is.null(pmMARval) || is.na(pmMARval)) pmMARval <- NULL mod <- clean(altNested, altParent) altNested <- mod[[1]] altParent <- mod[[2]] if (!isTRUE(all.equal(unique(altNested@paramValue), unique(altParent@paramValue)))) stop("Models are based on different data and cannot be compared, check your random seed") if (!isTRUE(all.equal(unique(altNested@n), unique(altParent@n)))) stop("Models are based on different values of sample sizes") if (!isTRUE(all.equal(unique(altNested@pmMCAR), unique(altParent@pmMCAR)))) stop("Models are based on different values of the percent completely missing at random") if (!isTRUE(all.equal(unique(altNested@pmMAR), unique(altParent@pmMAR)))) stop("Models are based on different values of the percent missing at random") Data <- as.data.frame((altNested@fit - altParent@fit)) condition <- c(length(unique(altNested@pmMCAR)) > 1, length(unique(altNested@pmMAR)) > 1, length(unique(altNested@n)) > 1) condValue <- cbind(altNested@pmMCAR, altNested@pmMAR, altNested@n) colnames(condValue) <- c("Percent MCAR", "Percent MAR", "N") condValue <- condValue[, condition] if (is.null(condValue) || length(condValue) == 0) condValue <- NULL predictorVal <- rep(NA, 3) if (condition[3]) { ifelse(is.null(nVal), stop("Please specify the sample size value, 'nVal', because the sample size in the result object is varying"), predictorVal[3] <- nVal) } if (condition[1]) { ifelse(is.null(pmMCARval), stop("Please specify the percent of completely missing at random, 'pmMCARval', because the percent of completely missing at random in the result object is varying"), predictorVal[1] <- pmMCARval) } if (condition[2]) { ifelse(is.null(pmMARval), stop("Please specify the percent of missing at random, 'pmMARval', because the percent of missing at random in the result object is varying"), predictorVal[2] <- pmMARval) } predictorVal <- predictorVal[condition] output <- getPowerFitDataFrame(Data, cutoff, revDirec, usedFit, predictor = condValue, predictorVal = predictorVal, condCutoff = condCutoff, df = df) return(output) } getPowerFitNestedNullObj <- function(altNested, altParent, nullNested, nullParent, revDirec = FALSE, usedFit = NULL, alpha = 0.05, nVal = NULL, pmMCARval = NULL, pmMARval = NULL, df = 0) { if (!multipleAllEqual(unique(altNested@n), unique(altParent@n), unique(nullNested@n), unique(nullParent@n))) stop("Models are based on different values of sample sizes") if (!multipleAllEqual(unique(altNested@pmMCAR), unique(altParent@pmMCAR), unique(nullNested@pmMCAR), unique(nullParent@pmMCAR))) stop("Models are based on different values of the percent completely missing at random") if (!multipleAllEqual(unique(altNested@pmMAR), unique(altParent@pmMAR), unique(nullNested@pmMAR), unique(nullParent@pmMAR))) stop("Models are based on different values of the percent missing at random") if (!isTRUE(all.equal(unique(altNested@paramValue), unique(altParent@paramValue)))) stop("'altNested' and 'altParent' are based on different data and cannot be compared, check your random seed") if (!isTRUE(all.equal(unique(nullNested@paramValue), unique(nullParent@paramValue)))) stop("'nullNested' and 'nullParent' are based on different data and cannot be compared, check your random seed") usedFit <- cleanUsedFit(usedFit, colnames(altNested@fit), colnames(altParent@fit), colnames(nullNested@fit), colnames(nullParent@fit)) if(is.null(nullNested)) nullNested <- altNested if(is.null(nullParent)) nullParent <- altParent mod <- clean(altNested, altParent, nullNested, nullParent) altNested <- mod[[1]] altParent <- mod[[2]] nullNested <- mod[[3]] nullParent <- mod[[4]] if (is.null(nVal) || is.na(nVal)) nVal <- NULL if (is.null(pmMCARval) || is.na(pmMCARval)) pmMCARval <- NULL if (is.null(pmMARval) || is.na(pmMARval)) pmMARval <- NULL condition <- c(length(unique(altNested@pmMCAR)) > 1, length(unique(altNested@pmMAR)) > 1, length(unique(altNested@n)) > 1) condValue <- cbind(altNested@pmMCAR, altNested@pmMAR, altNested@n) colnames(condValue) <- c("Percent MCAR", "Percent MAR", "N") condValue <- condValue[, condition] if (is.null(condValue) || length(condValue) == 0) condValue <- NULL predictorVal <- rep(NA, 3) if (condition[3]) { ifelse(is.null(nVal), stop("Please specify the sample size value, 'nVal', because the sample size in the result object is varying"), predictorVal[3] <- nVal) } if (condition[1]) { ifelse(is.null(pmMCARval), stop("Please specify the percent of completely missing at random, 'pmMCARval', because the percent of completely missing at random in the result object is varying"), predictorVal[1] <- pmMCARval) } if (condition[2]) { ifelse(is.null(pmMARval), stop("Please specify the percent of missing at random, 'pmMARval', because the percent of missing at random in the result object is varying"), predictorVal[2] <- pmMARval) } predictorVal <- predictorVal[condition] usedDirec <- (usedFit %in% getKeywords()$reversedFit) if (revDirec) usedDirec <- !usedDirec usedDist <- as.data.frame((altNested@fit - altParent@fit)[, usedFit]) nullFit <- as.data.frame((nullNested@fit - nullParent@fit)[, usedFit]) temp <- rep(NA, length(usedFit)) if (is.null(condValue)) { usedCutoff <- as.vector(t(getCutoffDataFrame(nullFit, alpha = alpha, usedFit = usedFit))) names(usedCutoff) <- usedFit temp <- pValueDataFrame(usedCutoff, usedDist, revDirec = usedDirec) names(temp) <- usedFit if(all(c("chisq", "df") %in% colnames(nullNested@fit))) { cutoffChisq <- qchisq(1 - alpha, df=(nullNested@fit - nullParent@fit)[,"df"]) powerChi <- mean((altNested@fit - altParent@fit)[,"chisq"] > cutoffChisq) temp <- c("TraditionalChi" = powerChi, temp) } } else { varyingCutoff <- getCutoffDataFrame(object = nullFit, alpha = alpha, revDirec = FALSE, usedFit = usedFit, predictor = condValue, df = df, predictorVal = "all") for (i in 1:length(temp)) { temp[i] <- pValueVariedCutoff(varyingCutoff[, i], usedDist[, i], revDirec = usedDirec[i], x = condValue, xval = predictorVal) } names(temp) <- usedFit } return(temp) } multipleAllEqual <- function(...) { obj <- list(...) multipleAllEqualList(obj) } multipleAllEqualList <- function(obj) { for (i in 2:length(obj)) { for (j in 1:(i - 1)) { temp <- isTRUE(all.equal(obj[[i]], obj[[j]])) if (!temp) return(FALSE) } } return(TRUE) } multipleAnyEqual <- function(...) { obj <- list(...) multipleAnyEqualList(obj) } multipleAnyEqualList <- function(obj) { for (i in 2:length(obj)) { for (j in 1:(i - 1)) { temp <- isTRUE(all.equal(obj[[i]], obj[[j]])) if (temp) return(TRUE) } } return(FALSE) }
library(testthat) library(LaF) context("laf_to_ffdf") test_that( "laf_to_ffdf", { lines <- c( " 1M 1.45Rotterdam ", " 2F12.00Amsterdam ", " 3 .22 Berlin ", " M22 Paris ", " 4F12345London ", " 5M Copenhagen", " 6M-12.1 ", " 7F -1Oslo ") data <- data.frame( id=c(1,2,3,NA,4,5,6,7), gender=as.factor(c("M", "F", NA, "M", "F", "M", "M", "F")), x=c(1.45, 12, 0.22, 22, 12345, NA, -12.1, -1), city=c("Rotterdam", "Amsterdam", "Berlin", "Paris", "London", "Copenhagen", "", "Oslo"), stringsAsFactors=FALSE ) tmp.fwf <- tempfile("tmp.fwf") writeLines(lines, con=tmp.fwf, sep="\n") laf <- laf_open_fwf(filename=tmp.fwf, column_types=c("integer", "categorical", "double", "string"), column_widths=c(2,1,5,10) ) foo <- laf_to_ffdf(laf, nrow=2) bar <- laf_to_ffdf(laf, nrows=1, columns=c(1, 2, 3)) laf2 <- laf_open_fwf(filename=tmp.fwf, column_types=c("integer", "categorical", "double", "string"), column_widths=c(2,1,5,10) ) bar2 <- laf_to_ffdf(laf2, nrows=1, columns=c(1, 2, 3)) bar3 <- laf_to_ffdf(laf2, nrows=1, columns=c(1, 2, 3)) })
create_report <- function(data, output_format = html_document(toc = TRUE, toc_depth = 6, theme = "yeti"), output_file = "report.html", output_dir = getwd(), y = NULL, config = configure_report(), report_title = "Data Profiling Report", ...) { if (!is.data.table(data)) data <- data.table(data) if (!is.null(y)) { if (!(y %in% names(data))) stop("`", y, "` not found in data!") } report_dir <- system.file("rmd_template/report.rmd", package = "DataExplorer") suppressWarnings(render( input = report_dir, output_format = output_format, output_file = output_file, output_dir = output_dir, intermediates_dir = output_dir, params = list(data = data, report_config = config, response = y, set_title = report_title), ... )) report_path <- path.expand(file.path(output_dir, output_file)) browseURL(report_path) }
pplace_to_table <- function(pplace,type="full",run_id=NULL){ if(class(pplace)!="pplace"){ stop("ERROR: the input is not an object of class pplace") } if(!is.null(run_id)){ pplace <- sub_pplace(pplace,run_id=run_id) } out <- NULL if(nrow(pplace$multiclass)>0){ out <- merge(pplace$multiclass,pplace$placement_positions,by="placement_id") if(type=="best"){ out <- out[order(out$ml_ratio,decreasing=TRUE),] out <- out[match(unique(out$placement_id),out[,1]),] } out <- out[order(out$placement_id),] rownames(out) <- NULL colnames(out)[c(5,12)] <- c("tax_id_multilcass","tax_id_placement") } return(out) }
NULL axe_call.flexsurvreg <- function(x, verbose = FALSE, ...) { old <- x x <- exchange(x, "call", call("dummy_call")) add_butcher_attributes( x, old, disabled = c("print()"), verbose = verbose ) } axe_env.flexsurvreg <- function(x, verbose = FALSE, ...) { old <- x attributes(x$data$m)$terms <- axe_env(attributes(x$data$m)$terms) attributes(x$concat.formula)$`.Environment` <- rlang::base_env() x$all.formulae <- purrr::map(x$all.formulae, function(z) axe_env(z, ...)) add_butcher_attributes( x, old, verbose = verbose ) }
Preimage <- function(Data,K_W1, C_out, Cl_assign, max_Nsize = 32, ncores = 4, DIR_out = getwd(), BIG = FALSE){ if(BIG){ bf_preimage = file.path(DIR_out, 'Centroid_preimage') if(file.exists(paste0(bf_preimage, '.bk'))){ file.remove(paste0(bf_preimage, '.bk')) } } clusters = Cl_assign[,ncol(Cl_assign)] centroid_IDs = sort(unique(clusters)) Centroids = C_out[,centroid_IDs] Centroids_norm = apply(Centroids, 2, function(x) x/sqrt(sum(x*x))) if(BIG){ C_preimage = bigstatsr::FBM(nrow =nrow(Data), ncol = ncol(Centroids_norm), backingfile = bf_preimage)$save() }else{ C_preimage <- matrix(0, nrow = nrow(Data), ncol = ncol(Centroids_norm)) } if(BIG){ for(i in 1:ncol(Centroids_norm)){ index = which(clusters == centroid_IDs[i]) kernel_c<- bigstatsr::big_apply(K_W1, a.FUN = function(X, ind, Y){ return(abs(Y%*%X[,ind])) } , a.combine = 'c', ind = index, Y = t(Centroids_norm[,i])) if(length(index)> 1){ if(length(index)<= max_Nsize){ neigbours_IDs = index }else{ neigbours_IDs = index[sort.int(kernel_c, index.return = TRUE, decreasing = TRUE)$ix[1:max_Nsize]] } cluster_sum <- bigstatsr::big_apply(Data, a.FUN = function(X, ind){ return( rowSums(X[,ind])) }, a.combine = 'plus', ind = neigbours_IDs) C_preimage[, i]<- cluster_sum/ min(length(index), max_Nsize) }else{ C_preimage[,i]<- Data[,index] } } }else{ for(i in 1:ncol(Centroids_norm)){ index = which(clusters == centroid_IDs[i]) kernel_c<- bigstatsr::big_apply(K_W1, a.FUN = function(X, ind, Y){ abs(Y%*%X[,ind]) } , a.combine = 'c', ind = index, Y = t(Centroids_norm[,i])) if(length(index)> 1){ neigbours_IDs = sort(index[sort.int(kernel_c, index.return = TRUE, decreasing = TRUE)$ix[1:min(length(index), max_Nsize)]]) C_preimage[, i]<- rowSums(Data[,neigbours_IDs])/min(length(index), max_Nsize) }else{ C_preimage[,i]<- Data[,index] } } } return(C_preimage) }
NULL .backup$create_backup_plan_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupPlan = structure(list(BackupPlanName = structure(logical(0), tags = list(type = "string")), Rules = structure(list(structure(list(RuleName = structure(logical(0), tags = list(type = "string")), TargetBackupVaultName = structure(logical(0), tags = list(type = "string")), ScheduleExpression = structure(logical(0), tags = list(type = "string")), StartWindowMinutes = structure(logical(0), tags = list(type = "long")), CompletionWindowMinutes = structure(logical(0), tags = list(type = "long")), Lifecycle = structure(list(MoveToColdStorageAfterDays = structure(logical(0), tags = list(type = "long")), DeleteAfterDays = structure(logical(0), tags = list(type = "long"))), tags = list(type = "structure")), RecoveryPointTags = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map", sensitive = TRUE)), CopyActions = structure(list(structure(list(Lifecycle = structure(list(MoveToColdStorageAfterDays = structure(logical(0), tags = list(type = "long")), DeleteAfterDays = structure(logical(0), tags = list(type = "long"))), tags = list(type = "structure")), DestinationBackupVaultArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure"))), tags = list(type = "list")), AdvancedBackupSettings = structure(list(structure(list(ResourceType = structure(logical(0), tags = list(type = "string")), BackupOptions = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure")), BackupPlanTags = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map", sensitive = TRUE)), CreatorRequestId = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$create_backup_plan_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupPlanId = structure(logical(0), tags = list(type = "string")), BackupPlanArn = structure(logical(0), tags = list(type = "string")), CreationDate = structure(logical(0), tags = list(type = "timestamp")), VersionId = structure(logical(0), tags = list(type = "string")), AdvancedBackupSettings = structure(list(structure(list(ResourceType = structure(logical(0), tags = list(type = "string")), BackupOptions = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$create_backup_selection_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupPlanId = structure(logical(0), tags = list(location = "uri", locationName = "backupPlanId", type = "string")), BackupSelection = structure(list(SelectionName = structure(logical(0), tags = list(type = "string")), IamRoleArn = structure(logical(0), tags = list(type = "string")), Resources = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list")), ListOfTags = structure(list(structure(list(ConditionType = structure(logical(0), tags = list(type = "string")), ConditionKey = structure(logical(0), tags = list(type = "string")), ConditionValue = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure")), CreatorRequestId = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$create_backup_selection_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(SelectionId = structure(logical(0), tags = list(type = "string")), BackupPlanId = structure(logical(0), tags = list(type = "string")), CreationDate = structure(logical(0), tags = list(type = "timestamp"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$create_backup_vault_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupVaultName = structure(logical(0), tags = list(location = "uri", locationName = "backupVaultName", type = "string")), BackupVaultTags = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map", sensitive = TRUE)), EncryptionKeyArn = structure(logical(0), tags = list(type = "string")), CreatorRequestId = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$create_backup_vault_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupVaultName = structure(logical(0), tags = list(type = "string")), BackupVaultArn = structure(logical(0), tags = list(type = "string")), CreationDate = structure(logical(0), tags = list(type = "timestamp"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$delete_backup_plan_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupPlanId = structure(logical(0), tags = list(location = "uri", locationName = "backupPlanId", type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$delete_backup_plan_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupPlanId = structure(logical(0), tags = list(type = "string")), BackupPlanArn = structure(logical(0), tags = list(type = "string")), DeletionDate = structure(logical(0), tags = list(type = "timestamp")), VersionId = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$delete_backup_selection_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupPlanId = structure(logical(0), tags = list(location = "uri", locationName = "backupPlanId", type = "string")), SelectionId = structure(logical(0), tags = list(location = "uri", locationName = "selectionId", type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$delete_backup_selection_output <- function(...) { list() } .backup$delete_backup_vault_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupVaultName = structure(logical(0), tags = list(location = "uri", locationName = "backupVaultName", type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$delete_backup_vault_output <- function(...) { list() } .backup$delete_backup_vault_access_policy_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupVaultName = structure(logical(0), tags = list(location = "uri", locationName = "backupVaultName", type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$delete_backup_vault_access_policy_output <- function(...) { list() } .backup$delete_backup_vault_notifications_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupVaultName = structure(logical(0), tags = list(location = "uri", locationName = "backupVaultName", type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$delete_backup_vault_notifications_output <- function(...) { list() } .backup$delete_recovery_point_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupVaultName = structure(logical(0), tags = list(location = "uri", locationName = "backupVaultName", type = "string")), RecoveryPointArn = structure(logical(0), tags = list(location = "uri", locationName = "recoveryPointArn", type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$delete_recovery_point_output <- function(...) { list() } .backup$describe_backup_job_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupJobId = structure(logical(0), tags = list(location = "uri", locationName = "backupJobId", type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$describe_backup_job_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(AccountId = structure(logical(0), tags = list(type = "string")), BackupJobId = structure(logical(0), tags = list(type = "string")), BackupVaultName = structure(logical(0), tags = list(type = "string")), BackupVaultArn = structure(logical(0), tags = list(type = "string")), RecoveryPointArn = structure(logical(0), tags = list(type = "string")), ResourceArn = structure(logical(0), tags = list(type = "string")), CreationDate = structure(logical(0), tags = list(type = "timestamp")), CompletionDate = structure(logical(0), tags = list(type = "timestamp")), State = structure(logical(0), tags = list(type = "string")), StatusMessage = structure(logical(0), tags = list(type = "string")), PercentDone = structure(logical(0), tags = list(type = "string")), BackupSizeInBytes = structure(logical(0), tags = list(type = "long")), IamRoleArn = structure(logical(0), tags = list(type = "string")), CreatedBy = structure(list(BackupPlanId = structure(logical(0), tags = list(type = "string")), BackupPlanArn = structure(logical(0), tags = list(type = "string")), BackupPlanVersion = structure(logical(0), tags = list(type = "string")), BackupRuleId = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")), ResourceType = structure(logical(0), tags = list(type = "string")), BytesTransferred = structure(logical(0), tags = list(type = "long")), ExpectedCompletionDate = structure(logical(0), tags = list(type = "timestamp")), StartBy = structure(logical(0), tags = list(type = "timestamp")), BackupOptions = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map")), BackupType = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$describe_backup_vault_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupVaultName = structure(logical(0), tags = list(location = "uri", locationName = "backupVaultName", type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$describe_backup_vault_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupVaultName = structure(logical(0), tags = list(type = "string")), BackupVaultArn = structure(logical(0), tags = list(type = "string")), EncryptionKeyArn = structure(logical(0), tags = list(type = "string")), CreationDate = structure(logical(0), tags = list(type = "timestamp")), CreatorRequestId = structure(logical(0), tags = list(type = "string")), NumberOfRecoveryPoints = structure(logical(0), tags = list(type = "long"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$describe_copy_job_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(CopyJobId = structure(logical(0), tags = list(location = "uri", locationName = "copyJobId", type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$describe_copy_job_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(CopyJob = structure(list(AccountId = structure(logical(0), tags = list(type = "string")), CopyJobId = structure(logical(0), tags = list(type = "string")), SourceBackupVaultArn = structure(logical(0), tags = list(type = "string")), SourceRecoveryPointArn = structure(logical(0), tags = list(type = "string")), DestinationBackupVaultArn = structure(logical(0), tags = list(type = "string")), DestinationRecoveryPointArn = structure(logical(0), tags = list(type = "string")), ResourceArn = structure(logical(0), tags = list(type = "string")), CreationDate = structure(logical(0), tags = list(type = "timestamp")), CompletionDate = structure(logical(0), tags = list(type = "timestamp")), State = structure(logical(0), tags = list(type = "string")), StatusMessage = structure(logical(0), tags = list(type = "string")), BackupSizeInBytes = structure(logical(0), tags = list(type = "long")), IamRoleArn = structure(logical(0), tags = list(type = "string")), CreatedBy = structure(list(BackupPlanId = structure(logical(0), tags = list(type = "string")), BackupPlanArn = structure(logical(0), tags = list(type = "string")), BackupPlanVersion = structure(logical(0), tags = list(type = "string")), BackupRuleId = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")), ResourceType = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$describe_global_settings_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(), tags = list(type = "structure")) return(populate(args, shape)) } .backup$describe_global_settings_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(GlobalSettings = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map")), LastUpdateTime = structure(logical(0), tags = list(type = "timestamp"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$describe_protected_resource_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(ResourceArn = structure(logical(0), tags = list(location = "uri", locationName = "resourceArn", type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$describe_protected_resource_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(ResourceArn = structure(logical(0), tags = list(type = "string")), ResourceType = structure(logical(0), tags = list(type = "string")), LastBackupTime = structure(logical(0), tags = list(type = "timestamp"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$describe_recovery_point_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupVaultName = structure(logical(0), tags = list(location = "uri", locationName = "backupVaultName", type = "string")), RecoveryPointArn = structure(logical(0), tags = list(location = "uri", locationName = "recoveryPointArn", type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$describe_recovery_point_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(RecoveryPointArn = structure(logical(0), tags = list(type = "string")), BackupVaultName = structure(logical(0), tags = list(type = "string")), BackupVaultArn = structure(logical(0), tags = list(type = "string")), SourceBackupVaultArn = structure(logical(0), tags = list(type = "string")), ResourceArn = structure(logical(0), tags = list(type = "string")), ResourceType = structure(logical(0), tags = list(type = "string")), CreatedBy = structure(list(BackupPlanId = structure(logical(0), tags = list(type = "string")), BackupPlanArn = structure(logical(0), tags = list(type = "string")), BackupPlanVersion = structure(logical(0), tags = list(type = "string")), BackupRuleId = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")), IamRoleArn = structure(logical(0), tags = list(type = "string")), Status = structure(logical(0), tags = list(type = "string")), CreationDate = structure(logical(0), tags = list(type = "timestamp")), CompletionDate = structure(logical(0), tags = list(type = "timestamp")), BackupSizeInBytes = structure(logical(0), tags = list(type = "long")), CalculatedLifecycle = structure(list(MoveToColdStorageAt = structure(logical(0), tags = list(type = "timestamp")), DeleteAt = structure(logical(0), tags = list(type = "timestamp"))), tags = list(type = "structure")), Lifecycle = structure(list(MoveToColdStorageAfterDays = structure(logical(0), tags = list(type = "long")), DeleteAfterDays = structure(logical(0), tags = list(type = "long"))), tags = list(type = "structure")), EncryptionKeyArn = structure(logical(0), tags = list(type = "string")), IsEncrypted = structure(logical(0), tags = list(type = "boolean")), StorageClass = structure(logical(0), tags = list(type = "string")), LastRestoreTime = structure(logical(0), tags = list(type = "timestamp"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$describe_region_settings_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(), tags = list(type = "structure")) return(populate(args, shape)) } .backup$describe_region_settings_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(ResourceTypeOptInPreference = structure(list(structure(logical(0), tags = list(type = "boolean"))), tags = list(type = "map"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$describe_restore_job_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(RestoreJobId = structure(logical(0), tags = list(location = "uri", locationName = "restoreJobId", type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$describe_restore_job_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(AccountId = structure(logical(0), tags = list(type = "string")), RestoreJobId = structure(logical(0), tags = list(type = "string")), RecoveryPointArn = structure(logical(0), tags = list(type = "string")), CreationDate = structure(logical(0), tags = list(type = "timestamp")), CompletionDate = structure(logical(0), tags = list(type = "timestamp")), Status = structure(logical(0), tags = list(type = "string")), StatusMessage = structure(logical(0), tags = list(type = "string")), PercentDone = structure(logical(0), tags = list(type = "string")), BackupSizeInBytes = structure(logical(0), tags = list(type = "long")), IamRoleArn = structure(logical(0), tags = list(type = "string")), ExpectedCompletionTimeMinutes = structure(logical(0), tags = list(type = "long")), CreatedResourceArn = structure(logical(0), tags = list(type = "string")), ResourceType = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$export_backup_plan_template_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupPlanId = structure(logical(0), tags = list(location = "uri", locationName = "backupPlanId", type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$export_backup_plan_template_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupPlanTemplateJson = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$get_backup_plan_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupPlanId = structure(logical(0), tags = list(location = "uri", locationName = "backupPlanId", type = "string")), VersionId = structure(logical(0), tags = list(location = "querystring", locationName = "versionId", type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$get_backup_plan_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupPlan = structure(list(BackupPlanName = structure(logical(0), tags = list(type = "string")), Rules = structure(list(structure(list(RuleName = structure(logical(0), tags = list(type = "string")), TargetBackupVaultName = structure(logical(0), tags = list(type = "string")), ScheduleExpression = structure(logical(0), tags = list(type = "string")), StartWindowMinutes = structure(logical(0), tags = list(type = "long")), CompletionWindowMinutes = structure(logical(0), tags = list(type = "long")), Lifecycle = structure(list(MoveToColdStorageAfterDays = structure(logical(0), tags = list(type = "long")), DeleteAfterDays = structure(logical(0), tags = list(type = "long"))), tags = list(type = "structure")), RecoveryPointTags = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map", sensitive = TRUE)), RuleId = structure(logical(0), tags = list(type = "string")), CopyActions = structure(list(structure(list(Lifecycle = structure(list(MoveToColdStorageAfterDays = structure(logical(0), tags = list(type = "long")), DeleteAfterDays = structure(logical(0), tags = list(type = "long"))), tags = list(type = "structure")), DestinationBackupVaultArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure"))), tags = list(type = "list")), AdvancedBackupSettings = structure(list(structure(list(ResourceType = structure(logical(0), tags = list(type = "string")), BackupOptions = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure")), BackupPlanId = structure(logical(0), tags = list(type = "string")), BackupPlanArn = structure(logical(0), tags = list(type = "string")), VersionId = structure(logical(0), tags = list(type = "string")), CreatorRequestId = structure(logical(0), tags = list(type = "string")), CreationDate = structure(logical(0), tags = list(type = "timestamp")), DeletionDate = structure(logical(0), tags = list(type = "timestamp")), LastExecutionDate = structure(logical(0), tags = list(type = "timestamp")), AdvancedBackupSettings = structure(list(structure(list(ResourceType = structure(logical(0), tags = list(type = "string")), BackupOptions = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$get_backup_plan_from_json_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupPlanTemplateJson = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$get_backup_plan_from_json_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupPlan = structure(list(BackupPlanName = structure(logical(0), tags = list(type = "string")), Rules = structure(list(structure(list(RuleName = structure(logical(0), tags = list(type = "string")), TargetBackupVaultName = structure(logical(0), tags = list(type = "string")), ScheduleExpression = structure(logical(0), tags = list(type = "string")), StartWindowMinutes = structure(logical(0), tags = list(type = "long")), CompletionWindowMinutes = structure(logical(0), tags = list(type = "long")), Lifecycle = structure(list(MoveToColdStorageAfterDays = structure(logical(0), tags = list(type = "long")), DeleteAfterDays = structure(logical(0), tags = list(type = "long"))), tags = list(type = "structure")), RecoveryPointTags = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map", sensitive = TRUE)), RuleId = structure(logical(0), tags = list(type = "string")), CopyActions = structure(list(structure(list(Lifecycle = structure(list(MoveToColdStorageAfterDays = structure(logical(0), tags = list(type = "long")), DeleteAfterDays = structure(logical(0), tags = list(type = "long"))), tags = list(type = "structure")), DestinationBackupVaultArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure"))), tags = list(type = "list")), AdvancedBackupSettings = structure(list(structure(list(ResourceType = structure(logical(0), tags = list(type = "string")), BackupOptions = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$get_backup_plan_from_template_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupPlanTemplateId = structure(logical(0), tags = list(location = "uri", locationName = "templateId", type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$get_backup_plan_from_template_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupPlanDocument = structure(list(BackupPlanName = structure(logical(0), tags = list(type = "string")), Rules = structure(list(structure(list(RuleName = structure(logical(0), tags = list(type = "string")), TargetBackupVaultName = structure(logical(0), tags = list(type = "string")), ScheduleExpression = structure(logical(0), tags = list(type = "string")), StartWindowMinutes = structure(logical(0), tags = list(type = "long")), CompletionWindowMinutes = structure(logical(0), tags = list(type = "long")), Lifecycle = structure(list(MoveToColdStorageAfterDays = structure(logical(0), tags = list(type = "long")), DeleteAfterDays = structure(logical(0), tags = list(type = "long"))), tags = list(type = "structure")), RecoveryPointTags = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map", sensitive = TRUE)), RuleId = structure(logical(0), tags = list(type = "string")), CopyActions = structure(list(structure(list(Lifecycle = structure(list(MoveToColdStorageAfterDays = structure(logical(0), tags = list(type = "long")), DeleteAfterDays = structure(logical(0), tags = list(type = "long"))), tags = list(type = "structure")), DestinationBackupVaultArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure"))), tags = list(type = "list")), AdvancedBackupSettings = structure(list(structure(list(ResourceType = structure(logical(0), tags = list(type = "string")), BackupOptions = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$get_backup_selection_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupPlanId = structure(logical(0), tags = list(location = "uri", locationName = "backupPlanId", type = "string")), SelectionId = structure(logical(0), tags = list(location = "uri", locationName = "selectionId", type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$get_backup_selection_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupSelection = structure(list(SelectionName = structure(logical(0), tags = list(type = "string")), IamRoleArn = structure(logical(0), tags = list(type = "string")), Resources = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list")), ListOfTags = structure(list(structure(list(ConditionType = structure(logical(0), tags = list(type = "string")), ConditionKey = structure(logical(0), tags = list(type = "string")), ConditionValue = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure")), SelectionId = structure(logical(0), tags = list(type = "string")), BackupPlanId = structure(logical(0), tags = list(type = "string")), CreationDate = structure(logical(0), tags = list(type = "timestamp")), CreatorRequestId = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$get_backup_vault_access_policy_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupVaultName = structure(logical(0), tags = list(location = "uri", locationName = "backupVaultName", type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$get_backup_vault_access_policy_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupVaultName = structure(logical(0), tags = list(type = "string")), BackupVaultArn = structure(logical(0), tags = list(type = "string")), Policy = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$get_backup_vault_notifications_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupVaultName = structure(logical(0), tags = list(location = "uri", locationName = "backupVaultName", type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$get_backup_vault_notifications_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupVaultName = structure(logical(0), tags = list(type = "string")), BackupVaultArn = structure(logical(0), tags = list(type = "string")), SNSTopicArn = structure(logical(0), tags = list(type = "string")), BackupVaultEvents = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$get_recovery_point_restore_metadata_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupVaultName = structure(logical(0), tags = list(location = "uri", locationName = "backupVaultName", type = "string")), RecoveryPointArn = structure(logical(0), tags = list(location = "uri", locationName = "recoveryPointArn", type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$get_recovery_point_restore_metadata_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupVaultArn = structure(logical(0), tags = list(type = "string")), RecoveryPointArn = structure(logical(0), tags = list(type = "string")), RestoreMetadata = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map", sensitive = TRUE))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$get_supported_resource_types_input <- function(...) { list() } .backup$get_supported_resource_types_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(ResourceTypes = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$list_backup_jobs_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(NextToken = structure(logical(0), tags = list(location = "querystring", locationName = "nextToken", type = "string")), MaxResults = structure(logical(0), tags = list(location = "querystring", locationName = "maxResults", type = "integer")), ByResourceArn = structure(logical(0), tags = list(location = "querystring", locationName = "resourceArn", type = "string")), ByState = structure(logical(0), tags = list(location = "querystring", locationName = "state", type = "string")), ByBackupVaultName = structure(logical(0), tags = list(location = "querystring", locationName = "backupVaultName", type = "string")), ByCreatedBefore = structure(logical(0), tags = list(location = "querystring", locationName = "createdBefore", type = "timestamp")), ByCreatedAfter = structure(logical(0), tags = list(location = "querystring", locationName = "createdAfter", type = "timestamp")), ByResourceType = structure(logical(0), tags = list(location = "querystring", locationName = "resourceType", type = "string")), ByAccountId = structure(logical(0), tags = list(location = "querystring", locationName = "accountId", type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$list_backup_jobs_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupJobs = structure(list(structure(list(AccountId = structure(logical(0), tags = list(type = "string")), BackupJobId = structure(logical(0), tags = list(type = "string")), BackupVaultName = structure(logical(0), tags = list(type = "string")), BackupVaultArn = structure(logical(0), tags = list(type = "string")), RecoveryPointArn = structure(logical(0), tags = list(type = "string")), ResourceArn = structure(logical(0), tags = list(type = "string")), CreationDate = structure(logical(0), tags = list(type = "timestamp")), CompletionDate = structure(logical(0), tags = list(type = "timestamp")), State = structure(logical(0), tags = list(type = "string")), StatusMessage = structure(logical(0), tags = list(type = "string")), PercentDone = structure(logical(0), tags = list(type = "string")), BackupSizeInBytes = structure(logical(0), tags = list(type = "long")), IamRoleArn = structure(logical(0), tags = list(type = "string")), CreatedBy = structure(list(BackupPlanId = structure(logical(0), tags = list(type = "string")), BackupPlanArn = structure(logical(0), tags = list(type = "string")), BackupPlanVersion = structure(logical(0), tags = list(type = "string")), BackupRuleId = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")), ExpectedCompletionDate = structure(logical(0), tags = list(type = "timestamp")), StartBy = structure(logical(0), tags = list(type = "timestamp")), ResourceType = structure(logical(0), tags = list(type = "string")), BytesTransferred = structure(logical(0), tags = list(type = "long")), BackupOptions = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map")), BackupType = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list")), NextToken = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$list_backup_plan_templates_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(NextToken = structure(logical(0), tags = list(location = "querystring", locationName = "nextToken", type = "string")), MaxResults = structure(logical(0), tags = list(location = "querystring", locationName = "maxResults", type = "integer"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$list_backup_plan_templates_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(NextToken = structure(logical(0), tags = list(type = "string")), BackupPlanTemplatesList = structure(list(structure(list(BackupPlanTemplateId = structure(logical(0), tags = list(type = "string")), BackupPlanTemplateName = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$list_backup_plan_versions_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupPlanId = structure(logical(0), tags = list(location = "uri", locationName = "backupPlanId", type = "string")), NextToken = structure(logical(0), tags = list(location = "querystring", locationName = "nextToken", type = "string")), MaxResults = structure(logical(0), tags = list(location = "querystring", locationName = "maxResults", type = "integer"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$list_backup_plan_versions_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(NextToken = structure(logical(0), tags = list(type = "string")), BackupPlanVersionsList = structure(list(structure(list(BackupPlanArn = structure(logical(0), tags = list(type = "string")), BackupPlanId = structure(logical(0), tags = list(type = "string")), CreationDate = structure(logical(0), tags = list(type = "timestamp")), DeletionDate = structure(logical(0), tags = list(type = "timestamp")), VersionId = structure(logical(0), tags = list(type = "string")), BackupPlanName = structure(logical(0), tags = list(type = "string")), CreatorRequestId = structure(logical(0), tags = list(type = "string")), LastExecutionDate = structure(logical(0), tags = list(type = "timestamp")), AdvancedBackupSettings = structure(list(structure(list(ResourceType = structure(logical(0), tags = list(type = "string")), BackupOptions = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$list_backup_plans_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(NextToken = structure(logical(0), tags = list(location = "querystring", locationName = "nextToken", type = "string")), MaxResults = structure(logical(0), tags = list(location = "querystring", locationName = "maxResults", type = "integer")), IncludeDeleted = structure(logical(0), tags = list(location = "querystring", locationName = "includeDeleted", type = "boolean"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$list_backup_plans_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(NextToken = structure(logical(0), tags = list(type = "string")), BackupPlansList = structure(list(structure(list(BackupPlanArn = structure(logical(0), tags = list(type = "string")), BackupPlanId = structure(logical(0), tags = list(type = "string")), CreationDate = structure(logical(0), tags = list(type = "timestamp")), DeletionDate = structure(logical(0), tags = list(type = "timestamp")), VersionId = structure(logical(0), tags = list(type = "string")), BackupPlanName = structure(logical(0), tags = list(type = "string")), CreatorRequestId = structure(logical(0), tags = list(type = "string")), LastExecutionDate = structure(logical(0), tags = list(type = "timestamp")), AdvancedBackupSettings = structure(list(structure(list(ResourceType = structure(logical(0), tags = list(type = "string")), BackupOptions = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$list_backup_selections_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupPlanId = structure(logical(0), tags = list(location = "uri", locationName = "backupPlanId", type = "string")), NextToken = structure(logical(0), tags = list(location = "querystring", locationName = "nextToken", type = "string")), MaxResults = structure(logical(0), tags = list(location = "querystring", locationName = "maxResults", type = "integer"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$list_backup_selections_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(NextToken = structure(logical(0), tags = list(type = "string")), BackupSelectionsList = structure(list(structure(list(SelectionId = structure(logical(0), tags = list(type = "string")), SelectionName = structure(logical(0), tags = list(type = "string")), BackupPlanId = structure(logical(0), tags = list(type = "string")), CreationDate = structure(logical(0), tags = list(type = "timestamp")), CreatorRequestId = structure(logical(0), tags = list(type = "string")), IamRoleArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$list_backup_vaults_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(NextToken = structure(logical(0), tags = list(location = "querystring", locationName = "nextToken", type = "string")), MaxResults = structure(logical(0), tags = list(location = "querystring", locationName = "maxResults", type = "integer"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$list_backup_vaults_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupVaultList = structure(list(structure(list(BackupVaultName = structure(logical(0), tags = list(type = "string")), BackupVaultArn = structure(logical(0), tags = list(type = "string")), CreationDate = structure(logical(0), tags = list(type = "timestamp")), EncryptionKeyArn = structure(logical(0), tags = list(type = "string")), CreatorRequestId = structure(logical(0), tags = list(type = "string")), NumberOfRecoveryPoints = structure(logical(0), tags = list(type = "long"))), tags = list(type = "structure"))), tags = list(type = "list")), NextToken = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$list_copy_jobs_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(NextToken = structure(logical(0), tags = list(location = "querystring", locationName = "nextToken", type = "string")), MaxResults = structure(logical(0), tags = list(location = "querystring", locationName = "maxResults", type = "integer")), ByResourceArn = structure(logical(0), tags = list(location = "querystring", locationName = "resourceArn", type = "string")), ByState = structure(logical(0), tags = list(location = "querystring", locationName = "state", type = "string")), ByCreatedBefore = structure(logical(0), tags = list(location = "querystring", locationName = "createdBefore", type = "timestamp")), ByCreatedAfter = structure(logical(0), tags = list(location = "querystring", locationName = "createdAfter", type = "timestamp")), ByResourceType = structure(logical(0), tags = list(location = "querystring", locationName = "resourceType", type = "string")), ByDestinationVaultArn = structure(logical(0), tags = list(location = "querystring", locationName = "destinationVaultArn", type = "string")), ByAccountId = structure(logical(0), tags = list(location = "querystring", locationName = "accountId", type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$list_copy_jobs_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(CopyJobs = structure(list(structure(list(AccountId = structure(logical(0), tags = list(type = "string")), CopyJobId = structure(logical(0), tags = list(type = "string")), SourceBackupVaultArn = structure(logical(0), tags = list(type = "string")), SourceRecoveryPointArn = structure(logical(0), tags = list(type = "string")), DestinationBackupVaultArn = structure(logical(0), tags = list(type = "string")), DestinationRecoveryPointArn = structure(logical(0), tags = list(type = "string")), ResourceArn = structure(logical(0), tags = list(type = "string")), CreationDate = structure(logical(0), tags = list(type = "timestamp")), CompletionDate = structure(logical(0), tags = list(type = "timestamp")), State = structure(logical(0), tags = list(type = "string")), StatusMessage = structure(logical(0), tags = list(type = "string")), BackupSizeInBytes = structure(logical(0), tags = list(type = "long")), IamRoleArn = structure(logical(0), tags = list(type = "string")), CreatedBy = structure(list(BackupPlanId = structure(logical(0), tags = list(type = "string")), BackupPlanArn = structure(logical(0), tags = list(type = "string")), BackupPlanVersion = structure(logical(0), tags = list(type = "string")), BackupRuleId = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")), ResourceType = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list")), NextToken = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$list_protected_resources_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(NextToken = structure(logical(0), tags = list(location = "querystring", locationName = "nextToken", type = "string")), MaxResults = structure(logical(0), tags = list(location = "querystring", locationName = "maxResults", type = "integer"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$list_protected_resources_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(Results = structure(list(structure(list(ResourceArn = structure(logical(0), tags = list(type = "string")), ResourceType = structure(logical(0), tags = list(type = "string")), LastBackupTime = structure(logical(0), tags = list(type = "timestamp"))), tags = list(type = "structure"))), tags = list(type = "list")), NextToken = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$list_recovery_points_by_backup_vault_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupVaultName = structure(logical(0), tags = list(location = "uri", locationName = "backupVaultName", type = "string")), NextToken = structure(logical(0), tags = list(location = "querystring", locationName = "nextToken", type = "string")), MaxResults = structure(logical(0), tags = list(location = "querystring", locationName = "maxResults", type = "integer")), ByResourceArn = structure(logical(0), tags = list(location = "querystring", locationName = "resourceArn", type = "string")), ByResourceType = structure(logical(0), tags = list(location = "querystring", locationName = "resourceType", type = "string")), ByBackupPlanId = structure(logical(0), tags = list(location = "querystring", locationName = "backupPlanId", type = "string")), ByCreatedBefore = structure(logical(0), tags = list(location = "querystring", locationName = "createdBefore", type = "timestamp")), ByCreatedAfter = structure(logical(0), tags = list(location = "querystring", locationName = "createdAfter", type = "timestamp"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$list_recovery_points_by_backup_vault_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(NextToken = structure(logical(0), tags = list(type = "string")), RecoveryPoints = structure(list(structure(list(RecoveryPointArn = structure(logical(0), tags = list(type = "string")), BackupVaultName = structure(logical(0), tags = list(type = "string")), BackupVaultArn = structure(logical(0), tags = list(type = "string")), SourceBackupVaultArn = structure(logical(0), tags = list(type = "string")), ResourceArn = structure(logical(0), tags = list(type = "string")), ResourceType = structure(logical(0), tags = list(type = "string")), CreatedBy = structure(list(BackupPlanId = structure(logical(0), tags = list(type = "string")), BackupPlanArn = structure(logical(0), tags = list(type = "string")), BackupPlanVersion = structure(logical(0), tags = list(type = "string")), BackupRuleId = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")), IamRoleArn = structure(logical(0), tags = list(type = "string")), Status = structure(logical(0), tags = list(type = "string")), CreationDate = structure(logical(0), tags = list(type = "timestamp")), CompletionDate = structure(logical(0), tags = list(type = "timestamp")), BackupSizeInBytes = structure(logical(0), tags = list(type = "long")), CalculatedLifecycle = structure(list(MoveToColdStorageAt = structure(logical(0), tags = list(type = "timestamp")), DeleteAt = structure(logical(0), tags = list(type = "timestamp"))), tags = list(type = "structure")), Lifecycle = structure(list(MoveToColdStorageAfterDays = structure(logical(0), tags = list(type = "long")), DeleteAfterDays = structure(logical(0), tags = list(type = "long"))), tags = list(type = "structure")), EncryptionKeyArn = structure(logical(0), tags = list(type = "string")), IsEncrypted = structure(logical(0), tags = list(type = "boolean")), LastRestoreTime = structure(logical(0), tags = list(type = "timestamp"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$list_recovery_points_by_resource_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(ResourceArn = structure(logical(0), tags = list(location = "uri", locationName = "resourceArn", type = "string")), NextToken = structure(logical(0), tags = list(location = "querystring", locationName = "nextToken", type = "string")), MaxResults = structure(logical(0), tags = list(location = "querystring", locationName = "maxResults", type = "integer"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$list_recovery_points_by_resource_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(NextToken = structure(logical(0), tags = list(type = "string")), RecoveryPoints = structure(list(structure(list(RecoveryPointArn = structure(logical(0), tags = list(type = "string")), CreationDate = structure(logical(0), tags = list(type = "timestamp")), Status = structure(logical(0), tags = list(type = "string")), EncryptionKeyArn = structure(logical(0), tags = list(type = "string")), BackupSizeBytes = structure(logical(0), tags = list(type = "long")), BackupVaultName = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$list_restore_jobs_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(NextToken = structure(logical(0), tags = list(location = "querystring", locationName = "nextToken", type = "string")), MaxResults = structure(logical(0), tags = list(location = "querystring", locationName = "maxResults", type = "integer")), ByAccountId = structure(logical(0), tags = list(location = "querystring", locationName = "accountId", type = "string")), ByCreatedBefore = structure(logical(0), tags = list(location = "querystring", locationName = "createdBefore", type = "timestamp")), ByCreatedAfter = structure(logical(0), tags = list(location = "querystring", locationName = "createdAfter", type = "timestamp")), ByStatus = structure(logical(0), tags = list(location = "querystring", locationName = "status", type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$list_restore_jobs_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(RestoreJobs = structure(list(structure(list(AccountId = structure(logical(0), tags = list(type = "string")), RestoreJobId = structure(logical(0), tags = list(type = "string")), RecoveryPointArn = structure(logical(0), tags = list(type = "string")), CreationDate = structure(logical(0), tags = list(type = "timestamp")), CompletionDate = structure(logical(0), tags = list(type = "timestamp")), Status = structure(logical(0), tags = list(type = "string")), StatusMessage = structure(logical(0), tags = list(type = "string")), PercentDone = structure(logical(0), tags = list(type = "string")), BackupSizeInBytes = structure(logical(0), tags = list(type = "long")), IamRoleArn = structure(logical(0), tags = list(type = "string")), ExpectedCompletionTimeMinutes = structure(logical(0), tags = list(type = "long")), CreatedResourceArn = structure(logical(0), tags = list(type = "string")), ResourceType = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list")), NextToken = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$list_tags_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(ResourceArn = structure(logical(0), tags = list(location = "uri", locationName = "resourceArn", type = "string")), NextToken = structure(logical(0), tags = list(location = "querystring", locationName = "nextToken", type = "string")), MaxResults = structure(logical(0), tags = list(location = "querystring", locationName = "maxResults", type = "integer"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$list_tags_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(NextToken = structure(logical(0), tags = list(type = "string")), Tags = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map", sensitive = TRUE))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$put_backup_vault_access_policy_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupVaultName = structure(logical(0), tags = list(location = "uri", locationName = "backupVaultName", type = "string")), Policy = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$put_backup_vault_access_policy_output <- function(...) { list() } .backup$put_backup_vault_notifications_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupVaultName = structure(logical(0), tags = list(location = "uri", locationName = "backupVaultName", type = "string")), SNSTopicArn = structure(logical(0), tags = list(type = "string")), BackupVaultEvents = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$put_backup_vault_notifications_output <- function(...) { list() } .backup$start_backup_job_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupVaultName = structure(logical(0), tags = list(type = "string")), ResourceArn = structure(logical(0), tags = list(type = "string")), IamRoleArn = structure(logical(0), tags = list(type = "string")), IdempotencyToken = structure(logical(0), tags = list(type = "string")), StartWindowMinutes = structure(logical(0), tags = list(type = "long")), CompleteWindowMinutes = structure(logical(0), tags = list(type = "long")), Lifecycle = structure(list(MoveToColdStorageAfterDays = structure(logical(0), tags = list(type = "long")), DeleteAfterDays = structure(logical(0), tags = list(type = "long"))), tags = list(type = "structure")), RecoveryPointTags = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map", sensitive = TRUE)), BackupOptions = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$start_backup_job_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupJobId = structure(logical(0), tags = list(type = "string")), RecoveryPointArn = structure(logical(0), tags = list(type = "string")), CreationDate = structure(logical(0), tags = list(type = "timestamp"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$start_copy_job_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(RecoveryPointArn = structure(logical(0), tags = list(type = "string")), SourceBackupVaultName = structure(logical(0), tags = list(type = "string")), DestinationBackupVaultArn = structure(logical(0), tags = list(type = "string")), IamRoleArn = structure(logical(0), tags = list(type = "string")), IdempotencyToken = structure(logical(0), tags = list(type = "string")), Lifecycle = structure(list(MoveToColdStorageAfterDays = structure(logical(0), tags = list(type = "long")), DeleteAfterDays = structure(logical(0), tags = list(type = "long"))), tags = list(type = "structure"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$start_copy_job_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(CopyJobId = structure(logical(0), tags = list(type = "string")), CreationDate = structure(logical(0), tags = list(type = "timestamp"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$start_restore_job_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(RecoveryPointArn = structure(logical(0), tags = list(type = "string")), Metadata = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map", sensitive = TRUE)), IamRoleArn = structure(logical(0), tags = list(type = "string")), IdempotencyToken = structure(logical(0), tags = list(type = "string")), ResourceType = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$start_restore_job_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(RestoreJobId = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$stop_backup_job_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupJobId = structure(logical(0), tags = list(location = "uri", locationName = "backupJobId", type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$stop_backup_job_output <- function(...) { list() } .backup$tag_resource_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(ResourceArn = structure(logical(0), tags = list(location = "uri", locationName = "resourceArn", type = "string")), Tags = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map", sensitive = TRUE))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$tag_resource_output <- function(...) { list() } .backup$untag_resource_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(ResourceArn = structure(logical(0), tags = list(location = "uri", locationName = "resourceArn", type = "string")), TagKeyList = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list", sensitive = TRUE))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$untag_resource_output <- function(...) { list() } .backup$update_backup_plan_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupPlanId = structure(logical(0), tags = list(location = "uri", locationName = "backupPlanId", type = "string")), BackupPlan = structure(list(BackupPlanName = structure(logical(0), tags = list(type = "string")), Rules = structure(list(structure(list(RuleName = structure(logical(0), tags = list(type = "string")), TargetBackupVaultName = structure(logical(0), tags = list(type = "string")), ScheduleExpression = structure(logical(0), tags = list(type = "string")), StartWindowMinutes = structure(logical(0), tags = list(type = "long")), CompletionWindowMinutes = structure(logical(0), tags = list(type = "long")), Lifecycle = structure(list(MoveToColdStorageAfterDays = structure(logical(0), tags = list(type = "long")), DeleteAfterDays = structure(logical(0), tags = list(type = "long"))), tags = list(type = "structure")), RecoveryPointTags = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map", sensitive = TRUE)), CopyActions = structure(list(structure(list(Lifecycle = structure(list(MoveToColdStorageAfterDays = structure(logical(0), tags = list(type = "long")), DeleteAfterDays = structure(logical(0), tags = list(type = "long"))), tags = list(type = "structure")), DestinationBackupVaultArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure"))), tags = list(type = "list")), AdvancedBackupSettings = structure(list(structure(list(ResourceType = structure(logical(0), tags = list(type = "string")), BackupOptions = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$update_backup_plan_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupPlanId = structure(logical(0), tags = list(type = "string")), BackupPlanArn = structure(logical(0), tags = list(type = "string")), CreationDate = structure(logical(0), tags = list(type = "timestamp")), VersionId = structure(logical(0), tags = list(type = "string")), AdvancedBackupSettings = structure(list(structure(list(ResourceType = structure(logical(0), tags = list(type = "string")), BackupOptions = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$update_global_settings_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(GlobalSettings = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "map"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$update_global_settings_output <- function(...) { list() } .backup$update_recovery_point_lifecycle_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupVaultName = structure(logical(0), tags = list(location = "uri", locationName = "backupVaultName", type = "string")), RecoveryPointArn = structure(logical(0), tags = list(location = "uri", locationName = "recoveryPointArn", type = "string")), Lifecycle = structure(list(MoveToColdStorageAfterDays = structure(logical(0), tags = list(type = "long")), DeleteAfterDays = structure(logical(0), tags = list(type = "long"))), tags = list(type = "structure"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$update_recovery_point_lifecycle_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupVaultArn = structure(logical(0), tags = list(type = "string")), RecoveryPointArn = structure(logical(0), tags = list(type = "string")), Lifecycle = structure(list(MoveToColdStorageAfterDays = structure(logical(0), tags = list(type = "long")), DeleteAfterDays = structure(logical(0), tags = list(type = "long"))), tags = list(type = "structure")), CalculatedLifecycle = structure(list(MoveToColdStorageAt = structure(logical(0), tags = list(type = "timestamp")), DeleteAt = structure(logical(0), tags = list(type = "timestamp"))), tags = list(type = "structure"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$update_region_settings_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(ResourceTypeOptInPreference = structure(list(structure(logical(0), tags = list(type = "boolean"))), tags = list(type = "map"))), tags = list(type = "structure")) return(populate(args, shape)) } .backup$update_region_settings_output <- function(...) { list() }
ms.face<-function(features,...){ xy <- unlist(features) spline<-function(a,y,m=200,plot=FALSE){ n<-length(a) h<-diff(a) dy<-diff(y) sigma<-dy/h lambda<-h[-1]/(hh<-h[-1]+h[-length(h)]) mu<-1-lambda d<-6*diff(sigma)/hh tri.mat<-2*diag(n-2) tri.mat[2+ (0:(n-4))*(n-1)] <-mu[-1] tri.mat[ (1:(n-3))*(n-1)] <-lambda[-(n-2)] M<-c(0,solve(tri.mat)%*%d,0) x<-seq(from=a[1],to=a[n],length=m) anz.kl <- hist(x,breaks=a,plot=FALSE)$counts adj<-function(i) i-1 i<-rep(1:(n-1),anz.kl)+1 S.x<- M[i-1]*(a[i]-x )^3 / (6*h[adj(i)]) + M[i] *(x -a[i-1])^3 / (6*h[adj(i)]) + (y[i-1] - M[i-1]*h[adj(i)]^2 /6) * (a[i]-x)/ h[adj(i)] + (y[i] - M[i] *h[adj(i)]^2 /6) * (x-a[i-1]) / h[adj(i)] if(plot){ plot(x,S.x,type="l"); points(a,y) } return(cbind(x,S.x)) } n.char<-15 xy<-rbind(xy) n<-1 face.orig<-list( eye =rbind(c(12,0),c(19,8),c(30,8),c(37,0),c(30,-8),c(19,-8),c(12,0)) ,iris =rbind(c(20,0),c(24,4),c(29,0),c(24,-5),c(20,0)) ,lipso=rbind(c(0,-47),c( 7,-49),lipsiend=c( 16,-53),c( 7,-60),c(0,-62)) ,lipsi=rbind(c(7,-54),c(0,-54)) ,nose =rbind(c(0,-6),c(3,-16),c(6,-30),c(0,-31)) ,shape =rbind(c(0,44),c(29,40),c(51,22),hairend=c(54,11),earsta=c(52,-4), earend=c(46,-36),c(38,-61),c(25,-83),c(0,-89)) ,ear =rbind(c(60,-11),c(57,-30)) ,hair =rbind(hair1=c(72,12),hair2=c(64,50),c(36,74),c(0,79)) ) lipso.refl.ind<-4:1 lipsi.refl.ind<-1 nose.refl.ind<-3:1 hair.refl.ind<-3:1 shape.refl.ind<-8:1 shape.xnotnull<-2:8 nose.xnotnull<-2:3 for(ind in 1:n){ factors<-xy[ind,] face <- face.orig m<-mean(face$lipso[,2]) face$lipso[,2]<-m+(face$lipso[,2]-m)*(1+0.7*factors[4]) face$lipsi[,2]<-m+(face$lipsi[,2]-m)*(1+0.7*factors[4]) face$lipso[,1]<-face$lipso[,1]*(1+0.7*factors[5]) face$lipsi[,1]<-face$lipsi[,1]*(1+0.7*factors[5]) face$lipso["lipsiend",2]<-face$lipso["lipsiend",2]+20*factors[6] m<-mean(face$eye[,2]) face$eye[,2] <-m+(face$eye[,2] -m)*(1+0.7*factors[7]) face$iris[,2]<-m+(face$iris[,2]-m)*(1+0.7*factors[7]) m<-mean(face$eye[,1]) face$eye[,1] <-m+(face$eye[,1] -m)*(1+0.7*factors[8]) face$iris[,1]<-m+(face$iris[,1]-m)*(1+0.7*factors[8]) m<-min(face$hair[,2]) face$hair[,2]<-m+(face$hair[,2]-m)*(1+0.2*factors[9]) m<-0 face$hair[,1]<-m+(face$hair[,1]-m)*(1+0.2*factors[10]) m<-0 face$hair[c("hair1","hair2"),2]<-face$hair[c("hair1","hair2"),2]+50*factors[11] m<-mean(face$nose[,2]) face$nose[,2]<-m+(face$nose[,2]-m)*(1+0.7*factors[12]) face$nose[nose.xnotnull,1]<-face$nose[nose.xnotnull,1]*(1+factors[13]) m<-mean(face$shape[c("earsta","earend"),1]) face$ear[,1]<-m+(face$ear[,1]-m)* (1+0.7*factors[14]) m<-min(face$ear[,2]) face$ear[,2]<-m+(face$ear[,2]-m)* (1+0.7*factors[15]) face<-lapply(face,function(x){ x[,2]<-x[,2]*(1+0.2*factors[1]);x}) face<-lapply(face,function(x){ x[,1]<-x[,1]*(1+0.2*factors[2]);x}) face<-lapply(face,function(x){ x[,1]<-ifelse(x[,1]>0, ifelse(x[,2] > -30, x[,1], pmax(0,x[,1]+(x[,2]+50)*0.2*sin(1.5*(-factors[3])))),0);x}) invert<-function(x) cbind(-x[,1],x[,2]) face.obj<-list( eyer=face$eye ,eyel=invert(face$eye) ,irisr=face$iris ,irisl=invert(face$iris) ,lipso=rbind(face$lipso,invert(face$lipso[lipso.refl.ind,])) ,lipsi=rbind(face$lipso["lipsiend",],face$lipsi, invert(face$lipsi[lipsi.refl.ind,,drop=FALSE]), invert(face$lipso["lipsiend",,drop=FALSE])) ,earr=rbind(face$shape["earsta",],face$ear,face$shape["earend",]) ,earl=invert(rbind(face$shape["earsta",],face$ear,face$shape["earend",])) ,nose=rbind(face$nose,invert(face$nose[nose.refl.ind,])) ,hair=rbind(face$shape["hairend",],face$hair,invert(face$hair[hair.refl.ind,]), invert(face$shape["hairend",,drop=FALSE])) ,shape=rbind(face$shape,invert(face$shape[shape.refl.ind,])) ) tmp <- list(x=numeric(0),y=numeric(0)) for(ind in seq(face.obj)) { x <-face.obj[[ind]][,1]; y<-face.obj[[ind]][,2] xx<-spline(1:length(x),x,40,FALSE)[,2] yy<-spline(1:length(y),y,40,FALSE)[,2] xx <- xx/105 yy <- yy/105 tmp$x <- c(tmp$x,NA,xx) tmp$y <- c(tmp$y,NA,yy) } } return(tmp) }
context("Stress Get Data") library("SWIM") set.seed(0) x <- data.frame(cbind( "normal" = rnorm(1000), rgamma(1000, shape = 2), rbeta(1000, shape1 = 2, shape2 = 2))) colnames(x) <- c("normal", "", "beta") colnames(x) k <- 1:3 new_means <- c(1, 1, 0.75) res1 <- stress(type = "mean", x = x, k = k, new_means = new_means) test_that("get data", { expect_equal(colnames(get_data(res1)), colnames(x)) expect_equal(colnames(get_data(res1, xCol = "all")), colnames(x)) expect_equal(colnames(get_data(res1, xCol = colnames(x)[1])), colnames(x)[1]) expect_equal(colnames(get_data(res1, xCol = 1)), colnames(x)[1]) expect_equal(colnames(get_data(res1, xCol = colnames(x)[-2])), colnames(x)[-2]) expect_equal(colnames(get_data(res1, xCol = c(1,3))), colnames(x)[-2]) expect_error(colnames(get_data(res1, xCol = c("all", "all")))) expect_error(colnames(get_data(res1, xCol = c(1, "all")))) }) set.seed(0) x <- data.frame(cbind( rnorm(1000), rgamma(1000, shape = 2), rbeta(1000, shape1 = 2, shape2 = 2))) colnames(x) <- c("X1", "X2", "X3") k <- 1:3 new_means <- c(1, 1, 0.75) res2 <- stress(type = "mean", x = x, k = k, new_means = new_means) test_that("get data", { expect_equal(colnames(get_data(res2)), colnames(x)) expect_equal(colnames(get_data(res2, xCol = "all")), colnames(x)) expect_equal(colnames(get_data(res2, xCol = colnames(x)[1])), colnames(x)[1]) expect_equal(colnames(get_data(res2, xCol = 1)), colnames(x)[1]) expect_equal(colnames(get_data(res2, xCol = colnames(x)[-2])), colnames(x)[-2]) expect_equal(colnames(get_data(res2, xCol = c(1,3))), colnames(x)[-2]) expect_error(colnames(get_data(res2, xCol = c("all", "all")))) expect_error(colnames(get_data(res2, xCol = c(1, "all")))) }) set.seed(0) x <- as.matrix(cbind( rnorm(1000), rgamma(1000, shape = 2), rbeta(1000, shape1 = 2, shape2 = 2))) colnames(x) <- c("X1", "X2", "X3") k <- 1:3 new_means <- c(1, 1, 0.75) res3 <- stress(type = "mean", x = x, k = k, new_means = new_means) test_that("get data", { expect_equal(colnames(get_data(res3)), colnames(x)) expect_equal(colnames(get_data(res3, xCol = "all")), colnames(x)) expect_equal(colnames(get_data(res3, xCol = 1)), "X1") expect_equal(colnames(get_data(res3, xCol = c(1,3))), c("X1", "X3")) expect_error(colnames(get_data(res3, xCol = c("normal", "beta")))) expect_error(colnames(get_data(res3, xCol = c("all", "all")))) expect_error(colnames(get_data(res3, xCol = c(1, "all")))) })
`print.RRT`=function(x, ...){ cat("\nCall:\n") print(x$Call) cat("\n",x$Model," model", sep = "") cat("\n",x$Name," model for the ",x$Type," estimator\nParameters: ", paste(names(x$Param),gsub(" ","",formatC(x$Param,digits=2)),sep="=",collapse="; "),"\n",sep="") if((x$Model=="Qualitative")&(x$Type=="total")){ cat("\nEstimation:",round(x$Estimation)) }else{ cat("\nEstimation:",x$Estimation) } cat("\nVariance:",x$Variance) cat("\nConfidence interval (",format(100*(x$ConfidenceLevel),digits=2),"%)\n",sep="") cat(" Lower bound:",x$ConfidenceInterval[1],"\n") cat(" Upper bound:",x$ConfidenceInterval[2],"\n\n") }
library('smaa') pvf1 <- function(x) { smaa.pvf(x, cutoffs=c(-0.15, 0.35), values=c(0, 1)) } pvf2 <- function(x) { smaa.pvf(x, cutoffs=c(50, 100), values=c(1, 0)) } stopifnot(all.equal(pvf1(0.35), 1)) stopifnot(all.equal(pvf1(-0.15), 0)) stopifnot(all.equal(pvf1(0.1), 0.5)) stopifnot(all.equal(pvf1(c(0.35, 0.1)), c(1, 0.5))) stopifnot(all.equal(pvf2(50), 1)) stopifnot(all.equal(pvf2(100), 0)) stopifnot(all.equal(pvf2(75), 0.5)) stopifnot(all.equal(pvf2(c(75, 100)), c(0.5, 0))) pvf3 <- function(x) { smaa.pvf(x, cutoffs=c(-0.15, 0.0, 0.25, 0.35), values=c(0, 0.1, 0.9, 1)) } pvf4 <- function(x) { smaa.pvf(x, cutoffs=c(50, 75, 90, 100), values=c(1, 0.8, 0.5, 0)) } stopifnot(all.equal(pvf3(0.35), 1.0)) stopifnot(all.equal(pvf3(-0.15), 0.0)) stopifnot(all.equal(pvf3(0.0), 0.1)) stopifnot(all.equal(pvf3(0.25), 0.9)) stopifnot(all.equal(pvf3(0.1), 2/5*0.8+0.1)) stopifnot(all.equal(pvf4(50), 1.0)) stopifnot(all.equal(pvf4(60), 1-(2/5*0.2))) stopifnot(all.equal(pvf4(75), 0.8)) stopifnot(all.equal(pvf4(90), 0.5)) stopifnot(all.equal(pvf4(100), 0.0)) stopifnot(all.equal(pvf4(c(50,90,100)), c(1.0, 0.5, 0.0))) pvf5 <- function(x) { smaa.pvf(x, cutoffs=c(50, 75, 90, 100), values=c(1, 0.8, 0.5, 0), outOfBounds="interpolate") } stopifnot(all.equal(pvf5(c(50,90,100)), c(1.0, 0.5, 0.0))) stopifnot(all.equal(pvf5(c(10, 40, 101, 120)), c(1.32, 1.08, -0.05, -1))) pvf6 <- function(x) { smaa.pvf(x, cutoffs=c(50, 75, 90, 100), values=c(1, 0.8, 0.5, 0), outOfBounds="clip") } stopifnot(all.equal(pvf6(c(50,90,100)), c(1.0, 0.5, 0.0))) stopifnot(all.equal(pvf6(c(10, 40, 101, 120)), c(1.0, 1.0, 0.0, 0.0))) pvf7 <- function(x) { smaa.pvf(x, cutoffs=c(-0.15, 0.0, 0.25, 0.35), values=c(0, 0.1, 0.9, 1), outOfBounds="clip") } stopifnot(all.equal(pvf7(c(0.35, -0.15, 0.0, 0.25)), c(1.0, 0.0, 0.1, 0.9))) stopifnot(all.equal(pvf7(c(0.38, -0.20)), c(1.0, 0.0)))
"new_function_names"
NULL NULL NULL NULL NULL NULL
iterate.factor.comb <- function (p, n, i) { ret <- NULL for(col in 1:n){ ret <- c(ret, ((i-1)%/%(p^(n-col)))%%p) } ret } matrix.search<-function(A, l) { for (i in 1:nrow(A)) if (all(A[i,]==l)) {return(i); break;} return(0) } multi.modp<-function(a,b,p){ la <- length(a) lb <- length(b) dummy <- numeric(la+lb-1) for (i in 1:(la+lb-1)){ dummy[i] <- sum(a[max(i-lb+1,1):min(i,la)]*b[min(lb,i):max(1,i-la+1)]) %%p } return(dummy) } myGF<-function(p, n) { x<-GF(p,n) obj<-x[[1]] pol<-x[[2]][1,] if (n>1) { addition<-matrix(0,p^n,p^n) for(i in 1:(p^n)) for(j in i:(p^n)) { newobj<-(obj[i,]+obj[j,]) %%p addition[i,j]<-addition[j,i]<-matrix.search(obj,newobj) } multiply<-matrix(0,p^n,p^n) for(i in 1:(p^n)) for(j in i:(p^n)) { newobj<-redu.modp(multi.modp(obj[i,],obj[j,],p),pol,p) multiply[i,j]<-multiply[j,i]<-matrix.search(obj,newobj) } } else { addition<-matrix(0,p^n,p^n) for(i in 0:(p-1)) for(j in 0:(p-1)) { addition[i+1,j+1]<-addition[j+1,i+1]<-(i+j)%%p+1 } multiply<-matrix(0,p^n,p^n) for(i in 0:(p-1)) for(j in 0:(p-1)) { multiply[i+1,j+1]<-multiply[j+1,i+1]<-(i*j)%%p+1 } } return(list(objects=obj,add=addition,multiply=multiply)) } elements.of.matrix<-function(A, i, j) { apply(cbind(i,j),1,function(x) A[x[1],x[2]]) } bibd<-function(v, k, method=0, ...) { if(v<k) stop("v < k ") if(method==0){ if(k>v/2) method <- 2 if(v<6 || k<3) method <- 1 if(v==6 && k==3) method <- 3 if(v==7 && k==3) method <- 3 if(v==8 && k==3) method <- 6 if(v==8 && k==4) method <- 4 if(v==9 && k==3) method <- 4 if(v==9 && k==4) method <- 6 if(v==10 && k==3) method <- 9 if(v==10 && k==4) method <- 7 if(v==10 && k==5) method <- 18 if(v==11 && k==3) method <- 6 if(v==11 && k==4) method <- 6 if(v==11 && k==5) method <- 6 if(v==12 && k==3) method <- 9 if(v==12 && k==4) method <- 8 if(v==12 && k==5) method <- 15 if(v==12 && k==6) method <- 5 if(v%%4==3) method <- 16 } if(method==1) ret <- bibd.method1(v,k) if(method==2) ret <- bibd.method2(v,k) if(method==3) ret <- bibd.method3(v,k) if(method==4) ret <- bibd.method4(v,k) if(method==6) ret <- bibd.method6(v,k) if(method==7) ret <- bibd.method7(v,k) if(method==8) ret <- bibd.method8(v,k) if(method==9) ret <- bibd.method9(v,k) if(method==10) ret <- bibd.method10(v,k) if(method==11) ret <- bibd.method11(v,k) if(method==12) ret <- bibd.method12(v,k) if(method==13) ret <- bibd.method13(v,k) if(method==14) ret <- bibd.method14(v,k) if(method==15) ret <- bibd.method15(v,k) if(method==16) ret <- bibd.method16(v,k) if(method==17) ret <- bibd.method17(v,k) if(method==18) ret <- bibd.method18(v,k) if(method==19) ret <- bibd.method18(v,k) class(ret)<-"bibd" return(ret) } print.bibd<-function(x, width=getOption("width"), ...) { x<-x[do.call(order,lapply(1:ncol(x), function(i) x[,i])),] t<-test.bibd(x) vdgts<-ceiling(log(t$v+1)/log(10)) bdgts<-ceiling(log(t$b+1)/log(10)) cat(" block treatments\n") for (i in 1:nrow(x)) { to.print<-paste(i) while (nchar(to.print)<bdgts) to.print<-paste(" ",to.print,sep="") cat(to.print," (",sep="") for (j in 1:ncol(x)) { to.print<-paste(x[i,j]) while (nchar(to.print)<vdgts) to.print<-paste(" ",to.print,sep="") cat(to.print) if (j!=ncol(x)) cat(", ") else cat(")\n") } } cat(paste("\n v = ",t$v, " k = ",t$k, " b = ",t$b, " r = ",t$r, " lambda = ", t$lambda, "\n\n", sep="")) } compact.2.imatrix<-function(A) { v<-length(unique(as.vector(A))) b<-nrow(A) B<-matrix(0,v,b) for (i in 1:nrow(A)) B[A[i,],i]<-1 class(B)<-"bibdmatrix" return(B) } print.bibdmatrix<-function(B) { cat("\nIncidence matrix of bibd:\n\n") B<-unclass(B) NextMethod(B) } imatrix.2.compact<-function(B) { A<-matrix(0,ncol(B),sum(B[,1])) for (i in 1:ncol(B)) A[i,]<-which(B[,i]==1) class(A)<-"bibd" return(A) } test.bibd<-function(A, fast=TRUE) { flag<-TRUE abc<-unique(as.vector(A)) B<-compact.2.imatrix(A) v<-length(abc); k<-ncol(A); b<-nrow(A); r<-sum(B[1,]==1) lambda<-sum(B[1,]==1&B[2,]==1) if(!fast) { if (any(apply(B,1,sum)!=r)) warning("Desing is not equi-replicated.") flag<-TRUE for (i in 1:(nrow(B)-1)) for (j in (i+1):nrow(B)) if (flag&sum(B[i,]==1&B[j,]==1)!=lambda) {flag<-FALSE; warning("Desing is not balanced.")} } return(list(v=v,k=k,b=b,r=r,lambda=lambda)) } necessary.conditions<-function(v, k, b, r, lambda) { if (v*r!=b*k) return(1); if (lambda*(v-1)!=r*(k-1)) return(2); if (b<v) return(3) if (2*lambda*(v*r-b-(v-1))*(b-3)/r/(r-1)/(v*r-b-v+3)<1 & v<6) return(4) return(0); } bibd.method3<-function(v, k, verbose=T) { primen100 <- c(2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59, 61,67,71,73,79,83,89,97) s <- 0; n <- 0 for(p in primen100){ for(N in 1:100){ v1 <- (as.bigz(p)^as.bigz(N+1)-1)/as.bigz(p-1) if(verbose)cat(paste("v:",as.numeric(as.character(v1)),"\n")) for(M in (N-1):1){ k1 <- (as.bigz(p)^as.bigz(M+1)-1)/as.bigz(p-1) if(verbose)cat(paste("k:",as.numeric(as.character(k1)),"\n")) if(v==v1 && k==k1){ s=p; n=N; m=M; break } } if(s!=0) break } if(s!=0) break } if(s==0 && n==0) stop("no s and n found") h=1 is.null.comb<-function(q,w) { e<-rep(0,length(q)) for (i in 1:length(q)) e[i]<-gf$multiply[q[i],w[i]] dummy<-1 for (i in 1:length(q)) dummy<-gf$add[dummy,e[i]] return(dummy==1) } p<-s gf<-myGF(p,h) if((p^h)^(n+1)>2^32)stop("p and h too large") poi<-coef<-factor.comb(p^h,n+1)[-1,]+1 just.this<-rep(TRUE,nrow(poi)) for (i in 1:(nrow(poi)-1)) for (j in 2:(p^h)) for (k in (i+1):nrow(poi)) { dummy<-elements.of.matrix(gf$multiply,poi[i,],rep(j,ncol(poi))) if (all(dummy==poi[k,])) just.this[k]<-FALSE } poi<-poi[just.this,] results<-NULL for (i in 1:nrow(coef)) { res<-c() for (j in 1:nrow(poi)) if (is.null.comb(coef[i,],poi[j,])) res<-c(res,j) results[[i]]<-res+1 } k<-max(sapply(results,length)) for (i in 1:nrow(coef)) if (length(results[[i]])==k-1) results[[i]]<-c(1,results[[i]]) results<-unique(results) if (m!=n-1) for (i in (n-2):m) { new.results<-NULL index<-0 for (j in 1:(length(results)-1)) for (k in (j+1):length(results)) { index<-index+1 new.results[[index]]<-intersect(results[[j]],results[[k]]) } l<-max(sapply(new.results,length)) results<-NULL new.index<-0 for (j in 1:index) if (length(new.results[[j]])==l) { new.index<-new.index+1 results[[new.index]]<-new.results[[j]] } results<-unique(results) } results<-matrix(as.numeric(as.factor(unlist(results))),byrow=TRUE,nrow=length(results)) return(results) } bibd.method3.new<-function(n, s, h=1, m=n-1) { is.null.comb<-function(q,w) { e<-rep(0,length(q)) for (i in 1:length(q)) e[i]<-gf$multiply[q[i],w[i]] dummy<-1 for (i in 1:length(q)) dummy<-gf$add[dummy,e[i]] return(dummy==1) } p<-s gf<-myGF(p,h) poi <- NULL npoi <- (p^h)^(n+1) mpoi <- n+1 I <- 1 while(I<=npoi){ if(I%%1000==0)cat(paste("I:",I,"\n")) poiI <- iterate.factor.comb(p^h,n+1,I)[-1]+1 i <- I j <- 2 while(j<=p^h){ k <- i+1 while(k<=npoi){ if(k%%1000==0)cat(paste("k:",k,"\n")) poiK <- iterate.factor.comb(p^h,n+1,k)[-1]+1 dummy<-elements.of.matrix(gf$multiply,poiI,rep(j,mpoi)) if (!all(dummy==poiK)) poi <- rbind(poi,poiI) k <- k+1 } j <- j+1 } I <- I+1 } results<-list() lresults <- 1 i <- 1 while(i<=npoi){ if(i%%1000==0)cat(paste("i:",i,"\n")) poiI <- iterate.factor.comb(p^h,n+1,i)[-1]+1 res<-c() for (j in 1:nrow(poi)) if (is.null.comb(poiI,poi[j,])) res<-c(res,j) results[[lresults]]<-res+1 lresults <- lresults+1 i <- i+1 } k<-max(sapply(results,length)) for (i in 1:length(results)) if (length(results[[i]])==k-1) results[[i]]<-c(1,results[[i]]) results<-unique(results) if (m!=n-1) for (i in (n-2):m) { new.results<-NULL index<-0 for (j in 1:(length(results)-1)) for (k in (j+1):length(results)) { index<-index+1 new.results[[index]]<-intersect(results[[j]],results[[k]]) } l<-max(sapply(new.results,length)) results<-NULL new.index<-0 for (j in 1:index) if (length(new.results[[j]])==l) { new.index<-new.index+1 results[[new.index]]<-new.results[[j]] } results<-unique(results) } results<-matrix(as.numeric(as.factor(unlist(results))),byrow=TRUE,nrow=length(results)) return(results) } bibd.method4<-function(n, s, h=1, m=n-1) { is.null.comb<-function(q,w) { e<-rep(0,length(q)) for (i in 1:length(q)) e[i]<-gf$multiply[q[i],w[i]] dummy<-w[length(q)+1] for (i in 1:length(q)) dummy<-gf$add[dummy,e[i]] return(dummy==1) } p<-s gf<-myGF(p,h) poi<-factor.comb(p^h,n)+1 coef<-factor.comb(p^h,n+1)[-1,]+1 results<-NULL for (i in 1:nrow(coef)) { res<-c() for (j in 1:nrow(poi)) if (is.null.comb(poi[j,],coef[i,])) res<-c(res,j) results[[i]]<-res } results<-unique(results) if (m!=n-1) for (i in (n-2):m) { new.results<-NULL index<-0 for (j in 1:(length(results)-1)) for (k in (j+1):length(results)) { index<-index+1 new.results[[index]]<-intersect(results[[j]],results[[k]]) } l<-max(sapply(new.results,length)) results<-NULL new.index<-0 for (j in 1:index) if (length(new.results[[j]])==l) { new.index<-new.index+1 results[[new.index]]<-new.results[[j]] } results<-unique(results) } new.results<-results l<-max(sapply(new.results,length)) results<-NULL new.index<-0 for (j in 1:length(new.results)) if (length(new.results[[j]])==l) { new.index<-new.index+1 results[[new.index]]<-new.results[[j]] } results<-unique(results) results<-matrix(as.numeric(as.factor(unlist(results))),byrow=TRUE,nrow=length(results)) return(results) } bibd.method1<-function(v, k) { return(t(combn(v,k))) } bibd.method2<-function(v, k, method=0) { A <- bibd(v,v-k,method) abc<-unique(as.vector(A)) B<-NULL for (i in 1:nrow(A)) B<-rbind(B,setdiff(abc,A[i,])) return(B) } bibd.method6<-function(v, k, Nsim=1, seed=NA) { if (!is.na(seed)) set.seed(seed); f <- as.numeric(as.character(factorize(v))) fu <- unique(f) if(length(fu)==1){ p <- as.integer(fu) m <- length(f) A<-MOLS(p,m) flag<-TRUE solution<-matrix(0,1,1) for (index in 1:Nsim) { B<-matrix(0,k,dim(A)[3]*dim(A)[2]) elmnts<-sample(p^m,k) for (i in 1:dim(A)[3]) for (j in 1:dim(A)[2]) B[,(i-1)*dim(A)[2]+j]<-sort(match(elmnts,A[,j,i])) B<-unique(t(B)) if (flag | nrow(B)<nrow(solution)) solution<-B flag<-FALSE } return(solution) } else { stop("method 6 not applicable") } } bibd.method5<-function(A) { l<-(nrow(A)-3)/4 if (l!=round(l) | length(unique(as.vector(A)))!=4*l+3 | ncol(A)!=2*l+1) stop("Assumptions violated!") B<-bibd.method2(A) A<-cbind(A,4*l+4) return(rbind(A,B)) } bibd.method16<-function(v, k) { if ((v+1) %% 4 != 0) stop("v+1 must be divisible by 4") if(k!=(v-1)/2) stop(" ... wrong k ....") A<-hadamard.matrix(v+1)[-1,-1] B<-NULL for (i in 1:nrow(A)) B<-rbind(B,which(A[i,]==1)) return(B) } dset.table<- rbind(c(7,3,1,1,1,7), c(9,3,3,3,4,3), c(9,4,3,1,2,9), c(10,3,4,2,6,5), c(10,4,4,2,3,5), c(11,3,3,1,5,11), c(11,4,6,1,5,11), c(11,5,2,1,1,11), c(13,3,1,1,2,13), c(13,4,1,1,4,13), c(13,4,4,1,3,13), c(13,6,5,1,2,13), c(15,3,3,3,7,5), c(15,7,3,1,1,15), c(16,3,2,1,5,16), c(16,5,4,1,3,16), c(17,4,3,1,4,17), c(17,5,5,1,4,17), c(17,8,7,1,2,17), c(19,3,1,1,3,19), c(19,4,2,1,3,19), c(19,6,5,1,3,19), c(19,9,4,1,1,19), c(21,3,3,3,10,7), c(21,4,3,1,5,21), c(21,5,1,1,5,21), c(21,6,9,3,6,7), c(22,4,4,2,7,11), c(22,7,8,2,4,11), c(23,11,1,1,11,23), c(25,3,1,1,4,25)) colnames(dset.table)<-c("v","k","rho","s","t","m") dset.table<-as.data.frame(dset.table) dsets<-NULL dsets[[1]]<-matrix(c(1,2,4),1,3,byrow=T) dsets[[2]]<-matrix(c(1,2,0+1i,1+1i,2+1i,0+2i,1+2i,2+2i,0,0,0+1i,0+2i),4,3,byrow=T) dsets[[3]]<-matrix(c(0,1,2,4,0,3,4,7),2,4,byrow=T) dsets[[4]]<-matrix(c(0,3,1+1i,1,2,1+1i,1+1i,4+1i,4,0+1i,4+1i,1+1i,0,3,4+1i,1,2,4+1i),6,3,byrow=T) dsets[[5]]<-matrix(c(0,3,0+1i,4+1i,0,0+1i,1+1i,3+1i,1,2,3,0+1i),3,4,byrow=T) dsets[[6]]<-matrix(c(0,1,3,0,1,5,0,2,7,0,1,8,0,3,5),5,3,byrow=T) dsets[[7]]<-matrix(c(0,1,8,9,0,2,5,7,0,1,4,5,0,2,3,5,0,4,5,9),5,4,byrow=T) dsets[[8]]<-matrix(c(1,3,4,5,9),1,5,byrow=T) dsets[[9]]<-matrix(c(0,1,4,0,2,7),2,3,byrow=T) dsets[[10]]<-matrix(c(1,3,9,13),1,4,byrow=T) dsets[[11]]<-matrix(c(0,1,2,4,8,0,1,3,6,12,0,2,5,6,10),3,5,byrow=T) dsets[[12]]<-matrix(c(0,1,3,6,7,11,0,1,2,3,7,11),2,6,byrow=T) dsets[[13]]<-matrix(c(1,4,0+1i,2,3,0+1i,1,4+1i,0+2i,2+1i,3+1i,0+2i,1+2i,4+2i,0,2+2i,3+2i,0,0,0+1i,0+2i),7,3,byrow=T) dsets[[14]]<-matrix(c(1,2,4,5,8,10,15),1,7,byrow=T) dsets[[15]]<-matrix(c(0,1,3,0,4,9,0,2,8,0,3,7,0,1,6),5,3,byrow=T) dsets[[16]]<-matrix(c(0,1,2,4,7,0,1,5,8,10,0,1,3,7,11),3,5,byrow=T) dsets[[17]]<-matrix(c(0,1,3,7,0,1,5,7,0,1,6,9,0,2,5,9),4,4,byrow=T) dsets[[18]]<-matrix(c(0,1,4,13,16,0,3,5,12,14,0,2,8,9,15,0,6,7,10,11),4,5,byrow=T) dsets[[19]]<-matrix(c(0,1,3,7,8,12,14,15,0,2,3,4,7,8,9,11),2,8,byrow=T) dsets.table2<-rbind(c(6,3,2,1,1,1,5), c(8,4,3,1,1,1,7), c(10,5,4,1,1,1,7), c(12,3,2,1,3,1,11), c(12,6,5,1,1,1,11), c(14,7,6,1,1,1,13), c(15,5,4,1,2,1,14), c(15,6,10,2,3,2,7), c(16,8,7,1,1,1,15)) dsets2<-NULL dsets2[[1]]<-matrix(c(0,1,3,NaN,0,1),2,3,byrow=T) dsets2[[2]]<-matrix(c(0,1,2,4,NaN,1,2,4),2,4,byrow=T) dsets2[[3]]<-matrix(c(0,1,2,4,8,NaN,0,1,4,6),2,5,byrow=T) dsets2[[4]]<-matrix(c(0,1,3,0,1,5,0,2,5,NaN,0,4),4,3,byrow=T) dsets2[[5]]<-matrix(c(0,1,3,7,0,1,3,5,NaN,0,1,5),3,4,byrow=T) dsets2[[6]]<-matrix(c(0,1,3,4,5,9,NaN,0,4,5,6,8),2,6,byrow=T) dsets2[[7]]<-matrix(c(0,1,3,4,9,10,12,NaN,1,3,4,9,10,12),2,7,byrow=T) dsets2[[8]]<-matrix(c(0,1,4,9,11,0,1,4,10,12,NaN,0,1,2,7),3,5,byrow=T) dsets2[[9]]<-matrix(c(1,2,4,0+1i,1+1i,3+1i,2,3,5,0+1i,1+1i,3+1i,0,4,5,0+1i,1+1i,3+1i,NaN,0,0+1i,1+1i,2+1i,4+1i,NaN,0,3,5,6,0+1i),5,6,byrow=T) dsets2[[10]]<-matrix(c(3,4,5,6,8,10,11,14,NaN,0,1,2,7,9,12,13),2,8,byrow=T) bibd.method7<-function(ds, m) { result<-NULL for (i in 1:nrow(ds)) for (j in 0:(m-1)) result<-rbind(result,complex(real=(Re(ds[i,])+j)%%m,imaginary=Im(ds[i,]))) dr<-dim(result) result<-as.numeric(as.factor(result)) dim(result)<-dr for (i in 1:nrow(result)) result[i,]<-sort(result[i,]) return(result) } bibd.method8<-bibd.method7 admissible.triples <- function(v){ U <- 0:(v-1) W <- c(0:(v-2), Inf) d <- matrix(0,nrow=v,ncol=v) for(u in U){ for(w in W){ if(is.infinite(w)){ d[u+1,length(W)] <- Inf } else d[u+1,w+1] <- min((u-w)%%v,(w-u)%%v) } } ds <- unique(c(d)) maxd <- max(ds,na.rm=T) choices.index <- factor.comb(length(ds),3)+1 ret <- NULL collect <- NULL for(j in 1:dim(choices.index)[1]){ triple <- c(ds[choices.index[j,1]], ds[choices.index[j,2]], ds[choices.index[j,3]]) triple <- sort(triple) if(triple[1]+triple[2]==triple[3]){ chr <- "" for(k in triple){ chr <- paste(chr,k,sep="") } if(!(chr %in% collect)){ ret <- rbind(ret,triple) collect <- cbind(collect,chr) } } } dimnames(ret) <- NULL ret } admissible.triples.repeated <- function(v, lambda){ t <- admissible.triples(v) } not.yet.implemented <- function(){ stop("not yet implemented") } bibd.method9 <- function(v, k){ not.yet.implemented() } bibd.method10 <- function(v, k){ not.yet.implemented() } bibd.method11 <- function(v, k){ not.yet.implemented() } bibd.method12 <- function(v, k){ not.yet.implemented() } bibd.method13 <- function(v, k){ not.yet.implemented() } bibd.method14 <- function(v, k){ not.yet.implemented() } bibd.method15 <- function(v, k){ not.yet.implemented() } bibd.method17 <- function(v, k){ not.yet.implemented() } bibd.method18 <- function(v, k){ not.yet.implemented() }
ids_new_to_old <- function(id) { gsub("IEU-a:", "", id) } ids_new_to_old2 <- function(id) { id <- gsub("IEU-a-", "", id) id <- gsub("-a-", "-a:", id) id <- gsub("-b-", "-b:", id) id <- gsub("-c-", "-c:", id) id <- gsub("-d-", "-d:", id) return(id) } ids_old_to_new <- function(id) { ieu_index <- ! grepl("[A-Z]+-[a-z]+:", id) id[ieu_index] <- paste0("IEU-a:", id[ieu_index]) return(id) } ids_old_to_new2 <- function(id) { id <- gsub(":", "-", id) ieu_index <- ! grepl("[A-Z]+-[a-z]+-", id) id[ieu_index] <- paste0("IEU-a-", id[ieu_index]) id <- gsub(":", "-", id) return(id) }
initialize_data.frame = function(data, position = position){ cnames = colnames(data)[-1] log.pos = grep("log\\(.+\\)",cnames) cnames = gsub("log\\(","",cnames) cnames = gsub("I\\(","",cnames) cnames = gsub("\\)","",cnames) cnames = gsub("\\^[0-9]+","",cnames) cnames = unique(cnames) if(!is.null(position)){ dc_var = cnames[position] cnames[position] = paste0(dc_var,"_val1") cnames = append(cnames, paste0(dc_var,"_val2"), position) names = c("val1_mean","val1_lower","val1_upper","val2_mean","val2_lower","val2_upper","dc_mean","dc_lower","dc_upper",cnames) log.pos = ifelse(log.pos > position, log.pos + 1, log.pos) if(position %in% log.pos){ log.pos = append(log.pos, position + 1, which(log.pos == position)) } log.pos = log.pos + 9 }else{ names = c("mean","lower","upper",cnames) log.pos = log.pos + 3 } result = data.frame(t(rep(NA,length(names)))) colnames(result) = names return(list(result=result,log.pos=log.pos)) }
.RookeryApp <- setRefClass( 'RookeryApp', fields = c('app','name','appEnv','configured','workingDir'), methods = list( initialize = function(app=NULL,name=NULL,...){ if (is.null(name) || !is.character(name)){ base::warning("Need a proper app 'name'") .self$configured <- FALSE return(callSuper(...)) } .self$name <- name if (is.character(app) && file.exists(app)){ .self$workingDir <- dirname(app) oldwd <- setwd(.self$workingDir) on.exit(setwd(oldwd)) appEnv <<- new.env(parent=globalenv()) appEnv$.appFile <<- normalizePath(basename(app)) appEnv$.mtime <<- as.integer(file.info(appEnv$.appFile)$mtime) sys.source(appEnv$.appFile,envir=.self$appEnv) if (exists(.self$name,.self$appEnv,inherits=FALSE)) .self$app <- get(.self$name,.self$appEnv) else if (exists('app',.self$appEnv,inherits=FALSE)) .self$app <- get('app',.self$appEnv) else { base::warning("Cannot find a suitable app in file ",app) .self$app <- NULL } } else { base::warning("File does not exist: ",app) .self$configured <- FALSE; } if (!is_rookable(.self$app)){ base::warning("App ",name," is not rookable'") .self$configured <- FALSE; } else { .self$configured <- TRUE; } callSuper(...) } ) ) .Rookery <- setRefClass( 'Rookery', fields = c('req','res','appHash','messages'), methods = list( initialize = function(...){ appHash <<- new.env() messages <<- list( emptypath = c( '<h2>Oops! option Rook.Rookery.paths is NULL</h2>', '<p>You must set this to a character vector containing', 'valid directories where Rook apps live.</p>' ), nodots = c( '<h2>Apps cannot be named . or ..</h2>' ) ) callSuper(...) }, message = function(name,opt=NULL){ msg <- paste(messages,collapse='\n') if (!is.null(opt)) msg <- sprintf(msg,opt) res$header('Content-Type','text/html') res$write(msg) }, findSuitableApp = function(appName){ if (appName %in% c('.','..')){ message('nodots') return(NULL) } paths <- getOption('Rook.Rookery.paths') if (is.null(paths)){ message('emptypath') return(NULL) } }, listAllApps = function(){ }, call = function(env){ req <<- Request$new(env) res <<- Response$new() appName <- strsplit(req$path_info(),'/',fixed=TRUE)[[1]][2] if (is.na(appName)){ listAllApps() } else { app <- findSuitableApp(appName) if (!is.null(app)){ new_path_info <- req$path_info() req$path_info(sub(paste("/",appName,sep=''),'',new_path_info)) oldwd <- setwd(app$workingDir) on.exit(setwd(oldwd)) if (is(app$app,'function')) { return(app$app(env)) } else { return(app$app$call(env)) } } } res$finish() } ) )
cruzMapRiver <- reactive({ world2 <- cruz.map.range$world2 rivs <- map("rivers", plot = FALSE) if (world2) rivs$x <- ifelse(rivs$x < 0, rivs$x+360, rivs$x) rivs }) cruzMapColorLand <- reactive({ ifelse(input$color_land_all == TRUE, input$color_land, "white") }) cruzMapGrid <- reactive({ list( col = input$grid_line_color, lwd = input$grid_line_width, lty = input$grid_line_type ) }) cruzMapBathyLoad <- eventReactive(input$depth_file, { req(input$depth_file) file.in <- input$depth_file cruz.list$bathy.xyz <- NULL bathy.xyz <- read.csv(file.in$datapath) validate( need(ncol(bathy.xyz) >= 3, "The bathymetric CSV file must contain at least 3 columns") ) cruz.list$bathy.xyz <- bathy.xyz NULL }) cruzMapColorWater <- reactive({ if (input$color_water_style == 1) { bathy <- NULL } else { bathy.xyz <- cruz.list$bathy.xyz validate(need(bathy.xyz, "Please load a CSV file with bathymetric data")) bathy.xyz[[1]] <- if (cruz.map.range$world2) { ifelse(bathy.xyz[[1]] < 0, bathy.xyz[[1]] + 360, bathy.xyz[[1]]) } else { ifelse(bathy.xyz[[1]] > 180, bathy.xyz[[1]] - 360, bathy.xyz[[1]]) } lon.range <- cruz.map.range$lon.range lat.range <- cruz.map.range$lat.range bathy.xyz.keep <- between(bathy.xyz[[1]], lon.range[1], lon.range[2]) & between(bathy.xyz[[2]], lat.range[1], lat.range[2]) bathy <- try( marmap::as.bathy(bathy.xyz[bathy.xyz.keep, ]), silent = TRUE ) validate(need(inherits(bathy, "bathy"), paste("Unable to convert the loaded CSV file into a bathy object;", "see `maramp::as.bathy` for data format requirements"))) validate(need(length(bathy) > 0, "The loaded bathymetric data does not cover any of the current map area") ) } list(input$color_water, bathy) }) output$depth_download_button <- renderUI({ v.val <- input$depth_res v.mess <- "Bathymetric data resolution must be a whole number between 0 and 60" validate(need(!is.na(v.val), v.mess)) validate(need(isTRUE(all.equal(v.val %% 1, 0)), v.mess)) validate(need(between(v.val, 0, 60), v.mess)) downloadButton("depth_download", "Download bathymetric file") }) output$depth_download_message <- renderUI({ if (cruz.list$bathy.download) { validate( paste("CruzPlot was not able to resolve host: gis.ngdc.noaa.gov.", "Please check your internet connection and try again") ) } else { NULL } }) observe({ input$tabs input$tabset1 isolate(cruz.list$bathy.download <- FALSE) }) output$depth_download <- downloadHandler( filename = function() { paste0( paste( "marmap_coord", paste(cruz.map.range$lon.range[1], cruz.map.range$lon.range[2], cruz.map.range$lat.range[1], cruz.map.range$lat.range[2], sep = ";"), "res", input$depth_res, sep = "_"), ".csv" ) }, content = function(file) { cruz.list$bathy.download <- FALSE lon.range <- cruz.map.range$lon.range lat.range <- cruz.map.range$lat.range world2 <- cruz.map.range$world2 bathy <- try(marmap::getNOAA.bathy( lon1 = input$lon_left, lon2 = input$lon_right, lat1 = lat.range[1], lat2 = lat.range[2], resolution = input$depth_res, antimeridian = world2, keep = FALSE ), silent = TRUE) if (!isTruthy(bathy)) cruz.list$bathy.download <- TRUE validate(need(bathy, "Download did not work")) write.csv(marmap::as.xyz(bathy), file = file, row.names = FALSE) } )
require_pkgs = function(pkgs) { for (pkg in pkgs) { if (!require(pkg, character.only = TRUE)) { stop(paste("please install the package '", pkg, "'. install.packages('", pkg, "') ")) } } }
"randfn" <- function(n, family, ...){ args <- list(...) switch(family, negbin= rnbinom(n, size=exp(args$size), mu=args$mu), poisson=rpois(n, lambda=args$mu), geometric=rgeom(n, prob= args$mu), binom=rbinom(n, size=args$size, prob=args$mu) ) }
estimate_prob <- function(x) { if (!is.data.frame(x)) { x <- tryCatch(as.data.frame(x), error = function(c) { stop("Invalid 'x' argument: must be convertible to a data.frame") }) } if (ncol(x) < 2) { stop("Invalid 'x' argument: needs to have at least two columns.") } cnames <- colnames(x) prob <- list() prob[["margins"]] <- lapply(cnames, function(i) { v <- x[, i] dim_names <- list() lev <- levels(v) if (is.null(lev)) lev <- unique(v) dim_names[[i]] <- lev array(prop.table(table(v, useNA = "ifany")), dimnames = dim_names) }) names(prob[["margins"]]) <- cnames observed <- as.array(prop.table(table(x, useNA = "ifany"))) prob[["observed"]] <- observed expected <- prob[["margins"]][[1]] for (i in cnames[2:length(cnames)]) { expected <- outer(expected, prob[["margins"]][[i]]) } expected <- array(expected, dim = dim(observed), dimnames = dimnames(observed)) prob[["expected"]] <- expected prob }
tg_channel_err <- function( channel_id = tg_get_channel_id(), start_date = Sys.Date() - 15, end_date = Sys.Date(), group = c('day', 'week', 'month') ) { group <- match.arg(group) resp <- tg_make_request( method = 'channels/err', token = tg_get_token(), channelId = channel_id, startDate = as.numeric(as.POSIXct(start_date)), endDate = as.numeric(as.POSIXct(end_date)), group = group ) data <- tg_parse_response(resp) return(data) }
`ordisegments` <- function (ord, groups, levels, replicates, order.by, display = "sites", col = 1, show.groups, label = FALSE, ...) { pts <- scores(ord, display = display, ...) npoints <- nrow(pts) if (missing(groups)) groups <- gl(levels, replicates, npoints) if (!missing(order.by)) { if (length(order.by) != nrow(pts)) stop(gettextf("the length of order.by (%d) does not match the number of points (%d)", length(order.by), nrow(pts))) ord <- order(order.by) pts <- pts[ord,] groups <- groups[ord] } if (!missing(show.groups)) { take <- groups %in% show.groups pts <- pts[take, , drop = FALSE] groups <- groups[take] } out <- seq(along = groups) inds <- names(table(groups)) if (is.factor(col)) col <- as.numeric(col) col <- rep(col, length=length(inds)) names(col) <- inds ends <- names <- NULL for (is in inds) { gr <- out[groups == is] if (length(gr) > 1) { X <- pts[gr, , drop = FALSE] X0 <- X[-nrow(X), , drop = FALSE] X1 <- X[-1, , drop = FALSE] ordiArgAbsorber(X0[, 1], X0[, 2], X1[, 1], X1[, 2], col = col[is], FUN = segments, ...) if (label) { ends <- rbind(ends, X[c(1, nrow(X)), ]) names <- c(names, is, is) } } } if (label) ordiArgAbsorber(ends, labels = names, border = col, col = par("fg"), FUN = ordilabel, ...) invisible() }
qini <- function(x, ...) UseMethod("qini") qini.default <- function(x, ...) stop("uplift: No method implemented for this class of object") qini.performance <- function(x, direction = 1, plotit = TRUE, ...) { if (!inherits(x, "performance")) stop("uplift: x is not of class performance") if (!direction %in% c(1, 2)) stop("uplift: direction must be either 1 or 2") perf <- x groups <- nrow(perf) if (direction == 1) { inc.gains <- cumsum(perf[, 4] - perf[, 5] * sum(perf[, 2]) / sum(perf[, 3])) / sum(perf[, 2]) overall.inc.gains <- sum(perf[, 4]) / sum(perf[, 2]) - sum(perf[, 5]) / sum(perf[, 3]) } else { inc.gains <- cumsum(-1 * (perf[, 4] - perf[, 5] * sum(perf[, 2]) / sum(perf[, 3]))) / sum(perf[, 2]) overall.inc.gains <- sum(perf[, 5]) / sum(perf[, 3]) - sum(perf[, 4]) / sum(perf[, 2]) } random.inc.gains <- cumsum(rep(overall.inc.gains / groups, groups)) x <- seq(1 / groups, 1, 1 / groups) y <- inc.gains auuc <- 0 for (i in 2:length(x)) { auuc <- auuc + 0.5 * (x[i] - x[i-1]) * (y[i] + y[i-1]) } y.rand <- random.inc.gains auuc.rand <- 0 for (i in 2:length(x)) { auuc.rand <- auuc.rand + 0.5 * (x[i] - x[i-1]) * (y.rand[i] + y.rand[i-1]) } Qini <- auuc - auuc.rand miny <- 100 * min(c(random.inc.gains, inc.gains)) maxy <- 100 * max(c(random.inc.gains, inc.gains)) if (plotit) { plot(inc.gains * 100 ~ seq(100 / groups, 100, 100 / groups), type ="b", col = "blue", lty = 2, xlab = "Proportion of population targeted (%)", ylab = "Cumulative incremental gains (pc pt)", ylim = c(miny, maxy), ...) lines(random.inc.gains * 100 ~ seq(100 / groups, 100, 100 / groups), type = "l", col = "red", lty = 1) legend("topright", c("Model", "Random"), col=c("blue", "red"), lty=c(2,1)) } res <- list(Qini = Qini, inc.gains = inc.gains, random.inc.gains = random.inc.gains) return(res) }
ruleList2Exec <- function(X,allRulesList){ typeX = getTypeX(X) ruleExec <- unique(t(sapply(allRulesList,singleRuleList2Exec,typeX=typeX))) ruleExec <- t(ruleExec) colnames(ruleExec) <- "condition" return(ruleExec) }
knitr::opts_chunk$set( collapse = TRUE, comment = " ) library(kidney.epi) head(ktx) egfr.ckdepi (creatinine = 1.4, age = 60, sex = "Male", ethnicity = "White", creatinine_units = "mg/dl", label_afroamerican = c ("Afroamerican"), label_sex_male = c ("Male"), label_sex_female = c ("Female")) mydata <- ktx mydata$ckdepi <- egfr.ckdepi ( creatinine = mydata$don.creatinine, age = mydata$don.age, sex = mydata$don.sex, ethnicity = mydata$don.ethnicity, creatinine_units = "mg/dl", label_afroamerican = c ("Afroamerican"), label_sex_male = c ("Male"), label_sex_female = c ("Female")) summary(mydata$ckdepi)
library(deming) sen <- data.frame(t=c(1, 2, 3, 4, 10, 12, 18), y=c(9, 15, 19, 20, 45, 55, 78)) fit <- pbreg(y ~ t, data=sen, conf=.93) all.equal(coef(fit), c("(Intercept)"=6, "t"=4)) all.equal(fit$ci[2,], c(26/7, 35/8), check.attributes=FALSE) fit2 <- pbreg(y ~ t, data=sen, conf=.93, method=2) fit3 <- pbreg(y ~ t, data=sen, conf=.93, method=3) all.equal(coef(fit2), coef(fit)) all.equal(coef(fit3), coef(fit)) all.equal(fit2$ci, fit$ci) all.equal(fit3$ci, fit$ci) pdata <- data.frame(x=1:6, y=c(2,1.2, 4.1,3.5,6.3, 3)) fit <- pbreg(y~x, pdata) all.equal(coef(fit), c(1/8, 1.05), check.attributes=FALSE) fit3 <- pbreg(y ~ x, pdata, method=3) all.equal(coef(fit3), coef(fit)) fit2 <- pbreg(y ~ x, pdata, method=2) temp <- tan(mean(c(atan(2.2/2), atan(4.3/4)))) all.equal(as.vector(coef(fit2)), c(median(pdata$y- pdata$x*temp), temp))
prune_leaf <- function(dend, leaf_name, ...) { labels_dend <- labels(dend) if (length(labels_dend) != length(unique(labels_dend))) warning("Found duplicate labels in the tree (this might indicate a problem in the tree you supplied)") if (!(leaf_name %in% labels_dend)) { warning(paste("There is no leaf with the label", leaf_name, "in the tree you supplied", "\n", "Returning original tree", "\n")) return(dend) } if (sum(labels_dend %in% leaf_name) > 1) { warning(paste( "There are multiple leaves by the name of '", leaf_name, "' in the tree you supplied. Their locations is:", paste(which(labels_dend %in% leaf_name), collapse = ","), "\n", "Returning original tree", "\n" )) return(dend) } is.father.of.leaf.to.remove <- function(dend, leaf_name) { is.father <- FALSE for (i in seq_len(length(dend))) { if (is.leaf(dend[[i]]) == TRUE && labels(dend[[i]]) == leaf_name) is.father <- TRUE } return(is.father) } remove_leaf_if_child <- function(dend, leaf_name) { if (all(labels(dend) != leaf_name)) { return(dend) } else { attr(dend, "members") <- attr(dend, "members") - 1 if (!is.father.of.leaf.to.remove(dend, leaf_name)) { for (i in seq_len(length(dend))) { dend[[i]] <- remove_leaf_if_child(dend[[i]], leaf_name) } } else { if (length(dend) == 2) { leaf_location <- 1 if (is.leaf(dend[[leaf_location]]) == T && labels(dend[[leaf_location]]) == leaf_name) { branch_to_bumpup <- 2 dend <- dend[[branch_to_bumpup]] } else { branch_to_bumpup <- 1 dend <- dend[[branch_to_bumpup]] } } else if (length(dend) > 2) { dend_leaves <- unlist(lapply(dend, is.leaf)) dend_labels <- character(length = length(dend_leaves)) dend_labels[!dend_leaves] <- NA if (sum(dend_leaves) > 0) { dend_labels[dend_leaves] <- unlist(lapply(dend, function(x) attr(x, "label"))) dend_matches <- dend_labels == leaf_name dend_keep <- which(!(dend_leaves & dend_matches)) pruned <- dend[dend_keep] attributes(pruned) <- attributes(dend) attr(pruned, "members") <- length(dend_keep) dend <- pruned } } } } return(dend) } new_dend <- remove_leaf_if_child(dend, leaf_name) new_dend <- suppressWarnings(stats_midcache.dendrogram(new_dend)) return(new_dend) } prune <- function(dend, ...) { UseMethod("prune") } prune.default <- function(dend, ...) { stop("object dend must be a dendrogram/hclust/phylo object") } prune.dendrogram <- function(dend, leaves, reindex_dend = TRUE, ...) { leaves <- as.character(leaves) for (i in seq_along(leaves)) { dend <- prune_leaf(dend, leaves[i]) } if (reindex_dend) dend <- reindex_dend(dend) return(dend) } prune.hclust <- function(dend, leaves, ...) { x_dend <- as.dendrogram(dend) x_dend_pruned <- x_dend %>% prune(leaves, ...) %>% reindex_dend() x_pruned <- as_hclust_fixed(x_dend_pruned, dend) return(x_pruned) } prune.phylo <- function(dend, ...) { ape::drop.tip(phy = dend, ...) } prune.rpart <- function(dend, ...) { rpart::prune.rpart(tree = dend, ...) } prune_common_subtrees.dendlist <- function(dend, ...) { if (!length(dend) == 2) stop("The dend must of be of length 2") if (!is.dendlist(dend)) stop("The dend must of be of class dendlist") clusters <- common_subtrees_clusters(dend[[1]], dend[[2]]) labels_to_prune <- labels(dend[[1]])[clusters == 0] dend1 <- prune(dend[[1]], labels_to_prune) dend2 <- prune(dend[[2]], labels_to_prune) dend_12 <- dendlist(dend1, dend2) names(dend_12) <- names(dend) dend_12 } intersect_trees <- function(dend1, dend2, warn = dendextend_options("warn"), ...) { labels_dend1 <- labels(dend1) labels_dend2 <- labels(dend2) intersected_labels <- intersect(labels_dend1, labels_dend2) if (length(intersected_labels) == 0) { warning("The two trees had no common labels!") return(dendlist()) } ss_labels_to_keep <- labels_dend1 %in% intersected_labels ss_labels_to_prune_1 <- !ss_labels_to_keep pruned_dend1 <- prune(dend1, labels_dend1[ss_labels_to_prune_1]) ss_labels_to_keep <- labels_dend2 %in% intersected_labels ss_labels_to_prune_2 <- !ss_labels_to_keep pruned_dend2 <- prune(dend2, labels_dend2[ss_labels_to_prune_2]) if (warn && any(c(ss_labels_to_prune_1, ss_labels_to_prune_2))) { warning("The labels in both tree had different values - trees were pruned.") } return(dendlist(pruned_dend1, pruned_dend2)) } reindex_dend <- function(dend) { order.dendrogram(dend) <- dend %>% order.dendrogram() %>% rank() %>% as.integer() return(dend) }
refreshDataSetsList <- function(outp = TRUE) { removeIfExists("dSList", envir = KTSEnv) tsLoaded <- tsDetect() gapLoaded <- gapDetect() rmLoaded <- rmDetect() if (is.null(tsLoaded)) { nTS <- NULL } else { nTS <- length(tsLoaded) } if (is.null(gapLoaded)) { nGaps <- NULL } else { nGaps <- length(gapLoaded) } if (is.null(rmLoaded)) { nRM <- NULL } else { nRM <- length(rmLoaded) } dSList <- list(TS = tsLoaded, gaps = gapLoaded, rm = rmLoaded, nTS = nTS, nGaps = nGaps, nRM = nRM) assign("dSList", dSList, envir = KTSEnv) if (outp != FALSE) { writeOutpTs <- function(nameTS) { timSer <- get(nameTS, envir = KTSEnv) lTimSer <- nrow(timSer) sampPers <- getUniqueSampPer(timSer) sampPers <- sampPers[which(sampPers[, 1] > 10), 2] txt <- c(paste("TIME SERIES:", nameTS), paste("First date:", as.character(timSer$time[1])), paste("Last date:", as.character(timSer$time[lTimSer])), paste("Length:", as.character(lTimSer)), paste("Likely sampling periods(sec):", paste(sampPers, collapse = ","))) tcltk::tkinsert(KTSEnv$txtWidget, "end", paste(txt, collapse = "\n")) tcltk::tkinsert(KTSEnv$txtWidget, "end", paste("\n\n")) } writeOutpGap <- function(nameGap) { gapSet <- get(nameGap, envir = KTSEnv) txt <- c(paste("SET OF GAPS:", nameGap), paste("Number of NAs:", as.character(length(gapSet$gaps))), paste("Original time series:", gapSet$tsName), "Characteristics of the original time series:", paste("initial and final dates:", gapSet$tsIni, ";", gapSet$tsEnd), paste("length and sampling period:", gapSet$tsLength, ";", gapSet$samPerMin)) tcltk::tkinsert(KTSEnv$txtWidget, "end", paste(txt, collapse = "\n")) tcltk::tkinsert(KTSEnv$txtWidget, "end", paste("\n\n")) } writeOutpRM <- function(nameRM) { recMat <- get(nameRM, envir = KTSEnv) if (recMat$type != "cross") { warningRM = paste("Number of ones (only", "upper triangle,without diag.):", nrow(recMat$ones)) } else { warningRM = paste("Number of ones (both triangles and diag.):", nrow(recMat$ones)) } txt <- c(paste("RECURRENCE MATRIX:", nameRM), warningRM, paste("Type:", recMat$type), paste("Tolerance:", paste(recMat$tol, collapse = ",")), paste("Distance:", paste(recMat$dist, collapse = ",")), paste("Embedding dimension:", paste(recMat$embDim, collapse = ",")), paste("Delay:", paste(recMat$delay, collapse = ",")), paste("Original time series:", paste(recMat$tsName, collapse = ",")), paste("Lengths:", paste(recMat$tsLength, collapse = ",")), paste("Sampling periods:", paste(recMat$samPerSec, collapse = ",")), paste("Initial dates:", paste(recMat$tsIni, collapse = ","))) tcltk::tkinsert(KTSEnv$txtWidget, "end", paste(txt, collapse = "\n")) tcltk::tkinsert(KTSEnv$txtWidget, "end", paste("\n\n")) } tcltk::tkinsert(KTSEnv$txtWidget, "end", paste("LOADED OBJECTS", collapse = "\n")) tcltk::tkinsert(KTSEnv$txtWidget, "end", paste("\n\n")) tcltk::tkinsert(KTSEnv$txtWidget, "end", date()) tcltk::tkinsert(KTSEnv$txtWidget, "end", paste("\n\n")) if (class(KTSEnv$dSList$TS) == "character") { apply(as.matrix(KTSEnv$dSList$TS), 1, FUN = writeOutpTs) } else { tcltk::tkinsert(KTSEnv$txtWidget, "end", paste("TIME SERIES:none", collapse = "\n")) tcltk::tkinsert(KTSEnv$txtWidget, "end", paste("\n\n")) } if (class(KTSEnv$dSList$gaps) == "character") { apply(as.matrix(KTSEnv$dSList$gaps), 1, FUN = writeOutpGap) } else { tcltk::tkinsert(KTSEnv$txtWidget, "end", paste("SETS OF GAPS:none", collapse = "\n")) tcltk::tkinsert(KTSEnv$txtWidget, "end", paste("\n\n")) } if (class(KTSEnv$dSList$rm) == "character") { apply(as.matrix(KTSEnv$dSList$rm), 1, FUN = writeOutpRM) } else { tcltk::tkinsert(KTSEnv$txtWidget, "end", paste("RECURRENCE MATRICES:none",collapse = "\n")) tcltk::tkinsert(KTSEnv$txtWidget, "end", paste("\n\n")) } endingLines() } }
tam.np <- function( dat, probs_init=NULL, pweights=NULL, lambda=NULL, control=list(), model="2PL", n_basis=0, basis_type="hermite", penalty_type="lasso", pars_init=NULL, orthonormalize=TRUE) { s1 <- Sys.time() CALL <- match.call() disp <- "....................................................\n" increment.factor <- progress <- nodes <- snodes <- ridge <- xsi.start0 <- QMC <- NULL maxiter <- conv <- convD <- min.variance <- max.increment <- Msteps <- convM <- NULL R <- trim_increment <- NULL fac.oldxsi <- acceleration <- NULL e1 <- environment() tam_fct <- "tam.np" res <- tam_mml_control_list_define(control=control, envir=e1, tam_fct=tam_fct, prior_list_xsi=NULL) control <- con <- res$con con1a <- res$con1a res <- tam_np_inits( dat=dat, nodes=nodes, pweights=pweights, probs_init=probs_init, n_basis=n_basis, model=model ) maxK <- res$maxK K <- res$K K1 <- res$K1 TP <- res$TP I <- res$I probs <- res$probs pi.k <- res$pi.k dat_resp <- res$dat_resp dat2 <- res$dat2 N <- res$N pweights <- res$pweights theta <- res$theta items <- res$items use_basis <- res$use_basis prob_dim <- c(I, K1, TP) dev <- 1E200 iterate <- TRUE converged <- TRUE iter <- 1 pi_k_array <- array(NA, dim=c(I,K1,TP)) for (ii in 1:I){ for (kk in 1:K1){ pi_k_array[ii,kk,] <- pi.k } } if (use_basis){ res <- tam_np_create_spline_basis(nodes=nodes, n_basis=n_basis, items=items, pi.k=pi.k, dat=dat, lambda=lambda, basis_type=basis_type, pars_init=pars_init, orthonormalize=orthonormalize, model=model) probs <- res$probs } est_bspline <- res$est_bspline desmat <- res$desmat pars <- res$pars lambda <- res$lambda orthonormalize <- res$orthonormalize spline_optim <- res$spline_optim target_fct <- res$target_fct index_target <- res$index_target index_basis <- res$index_basis n_reg_max <- res$n_reg_max while( iterate ){ res <- tam_mml_progress_em0(progress=progress, iter=iter, disp=disp, print_estep=FALSE) probs0 <- as.vector(probs) dev0 <- dev res <- tam_rcpp_tam_np_posterior( dat2=dat2, dat_resp=dat_resp, probs0=probs0, pi_k=pi.k, pweights=pweights, K1=K1 ) f.yi.qk <- res$fyiqk f.qk.yi <- res$fqkyi n.ik <- array(res$nik, dim=prob_dim ) N.ik <- array(res$Nik, dim=c(I,TP) ) probs <- array(res$probs, dim=prob_dim ) ll <- res$ll ll_individual <- res$ll_individual dev <- -2*ll res <- tam_np_mstep_trait_distribution(nodes=nodes, f.qk.yi=f.qk.yi, model=model, pi.k=pi.k) sigma <- res$sigma pi.k <- res$pi.k if (use_basis){ res <- tam_np_mstep_items( I=I, n.ik=n.ik, desmat=desmat, Msteps=Msteps, spline_optim=spline_optim, probs=probs, pars=pars, lambda=lambda, iter=iter, dev=dev, n_basis=n_basis, penalty_type=penalty_type, target_fct=target_fct, index_target=index_target, index_basis=index_basis, model=model) probs <- res$probs } spline_optim <- res$spline_optim pars <- res$pars n_reg <- res$n_reg par_reg_penalty <- res$par_reg_penalty n_est <- res$n_est AIC <- res$AIC regularized <- res$regularized probs_change <- max( sqrt( (probs - probs0)^2 *pi_k_array ) ) np_change <- probs_change devch <- - ( dev - dev0 ) deviance_change <- devch rel_deviance_change <- deviance_change / dev0 res <- tam_mml_progress_em(progress=progress, deviance=dev, deviance_change=deviance_change, iter=iter, rel_deviance_change=rel_deviance_change, is_mml_3pl=FALSE, xsi_change=0, beta_change=0, variance_change=0, B_change=0, skillspace='np', delta_change=0, digits_pars=6, devch=devch, penalty_xsi=0, is_np=TRUE, is_latreg=TRUE, np_change=np_change, par_reg_penalty=par_reg_penalty, n_reg=n_reg, AIC=AIC, n_est=n_est, n_reg_max=n_reg_max) iter <- iter + 1 if (iter > maxiter){ converged <- FALSE iterate <- FALSE } if ( ( probs_change < conv) & ( abs(rel_deviance_change) < convD ) ){ iterate <- FALSE } } n.ik <- array( n.ik, dim=c(prob_dim, 1) ) pi.k <- matrix(pi.k, ncol=1) theta <- matrix(theta, ncol=1) loglike <- -dev/2 if (! use_basis){ n_est <- NA } ic <- tam_np_information_criteria(dev=dev, n_est=n_est, n=N) pen_val <- sum(par_reg_penalty) if (use_basis){ ncol_pars <- ncol(pars) if (model=="2PL"){ np <- ncol_pars - n_reg } if (model=="1PL"){ np <- ncol_pars - 1 - n_reg } item <- data.frame(item=items, regul=regularized, lambda=lambda, np=np, pars) } else { item <- NULL } s2 <- Sys.time() time <- c(s1, s2) res <- list( CALL=CALL, dat=dat, dat2=dat2, dat_resp=dat_resp, n.ik=n.ik, N.ik=N.ik, item=item, rprobs=probs, pi.k=pi.k, nodes=nodes, pweights=pweights, like=f.yi.qk, hwt=f.qk.yi, iter=iter, loglike=loglike, AIC=AIC, converged=converged, iter=iter, time=time, dev=dev, theta=theta, G=1, pars=pars, n_est=n_est, n_reg=n_reg, regularized=regularized, basis_type=basis_type, n_basis=n_basis, desmat=desmat, ic=ic, pid=NULL, orthonormalize=orthonormalize, penalty_type=penalty_type, pen_val=pen_val, use_basis=use_basis, model=model, sigma=sigma, ll_individual=ll_individual, control=control) class(res) <- "tam.np" return(res) }
get_pushover_sounds <- function(app = get_pushover_app()) { assert_valid_app(app) response <- pushover_api( verb = "GET", url = "https://api.pushover.net/1/sounds.json", query = list(token = app) ) response$sounds }
generic_sews <- function(mat, subsize = 4, abs_skewness = FALSE, moranI_coarse_grain = FALSE) { compute_indicator(mat, raw_generic_indic, subsize = subsize, abs_skewness = abs_skewness, moranI_coarse_grain = moranI_coarse_grain, taskname = "Generic indicators") } raw_generic_indic <- function(mat, subsize, abs_skewness, moranI_coarse_grain) { if ( is.numeric(mat) && subsize > 1 ) { warning(paste("Input matrix has continous values but will be", "coarse-grained anyway. Set subsize=1 to disable coarse", "graining.")) } if ( is.logical(mat) && subsize == 1 ) { warning(paste("Input matrix is binary but no coarse-graining will be", "performed.")) } mat_cg <- coarse_grain(mat, subsize) if ( length(unique(as.vector(mat_cg))) == 1 ) { return( c(variance = var(as.vector(mat_cg)), skewness = NA_real_, moran = NA_real_, mean = mean(mat)) ) } skewness_value <- cpp_skewness(mat_cg) if (abs_skewness) { skewness_value <- abs(skewness_value) } if (moranI_coarse_grain) { moran_value <- raw_moran(mat_cg) } else { moran_value <- raw_moran(mat) } c(variance = var(as.vector(mat_cg)), skewness = skewness_value, moran = moran_value, mean = mean(mat)) } raw_cg_variance <- function(mat, subsize = 5) { if ( ! is.matrix(mat) ) { stop("raw_cg_variance only accepts a single matrix as input.") } c(variance = var( as.vector( coarse_grain(mat, subsize) ) )) } raw_cg_moran <- function(mat, subsize = 1) { if ( ! is.matrix(mat) ) { stop("raw_cg_moran only accepts a single matrix as input.") } c(moran = raw_moran( coarse_grain(mat, subsize) )) } raw_cg_skewness <- function(mat, subsize = 5, absolute = TRUE) { if ( ! is.matrix(mat) ) { stop("raw_cg_skewness only accepts a single matrix as input.") } a <- cpp_skewness( coarse_grain(mat, subsize) ) if (absolute) { a <- abs(a) } c(skewness = a) }
fMP_NLMainGxM_closedform <- function(listdata, param) { m = c(listdata$M1,listdata$M2); p = c(listdata$P1,listdata$P2); rG = listdata$rG; aM = param$aM; cM = param$cM; eM = param$eM; aU = param$aU; cU = param$cU; eU = param$eU; muM = param$muM; muP = param$muP; beta1 = param$beta1; beta2 = param$beta2; alphaU = param$alphaU; kappaU = param$kappaU; epsilonU = param$epsilonU; entry11 = aM^2 + cM^2 + eM^2 entry12 = aM^2*rG + cM^2 SigmaM = matrix(c(entry11, entry12, entry12, entry11),2,2) invSigmaM = solve(SigmaM); fm = log(2*pi) + 0.5*log(det(SigmaM)) + 0.5*(m-muM) %*% invSigmaM %*%(m-muM); muP_M = muP + beta1*m + beta2*(m^2); entry11 = (aU+alphaU*m[1])^2 + (cU+kappaU*m[1])^2 + (eU+epsilonU*m[1])^2; entry12 = (aU+alphaU*m[1])*(aU+alphaU*m[2])*rG + (cU+kappaU*m[1])*(cU+kappaU*m[2]); entry22 = (aU+alphaU*m[2])^2 + (cU+kappaU*m[2])^2 + (eU+epsilonU*m[2])^2; covP_M = matrix(c(entry11, entry12, entry12, entry22),2,2) fp_M = log(2*pi) + 0.5*log(det(covP_M)) + 0.5*(p-muP_M) %*% solve(covP_M) %*% (p-muP_M); return(fm+fp_M); }
tblBlocks <- function(x, rowgroupSize=0, ...) { x <- { if (inherits(x, "textTable")) tblEntries(x, ...) else as.tblEntries(x) } rowheadInside <- attr(x, "rowheadInside") required <- c("id", "part", "headlayer", "level_in_layer", "arow1", "arow2", "acol1", "acol2") if (length(chk <- setdiff(required, names(x))) > 0) stop( "Following columns are required to define standard ", "blocks, but are missing from 'x': ", toString(chk)) if (is.na(rowheadInside)) stop( "Can't create standard blocks because 'rowheadInside' is NA") if (!rowheadInside && any(with(x, part == "rowhead" & headlayer == 0))) stop( "Found 'rowhead' entries for layer 0, but 'rowheadInside' is FALSE") partinfo <- tblParts(x) n_rowhead <- partinfo["rowhead", "nc"] nc_rowhead <- { if (rowheadInside && n_rowhead > 0) n_rowhead <- n_rowhead - 1 else n_rowhead } nc_body <- partinfo["body", "nc"] n_colhead <- partinfo["colhead", "nr"] nr_stub <- max(partinfo[c("colhead", "rowheadLabels"), "nr"]) nr_prebody <- sum(partinfo[c("title", "subtitle"), "nr"]) + nr_stub ad <- adim(x) nr_tbl <- ad[1] nc_tbl <- ad[2] nr_rhbody <- nr_tbl - nr_prebody - partinfo["foot", "nr"] stopifnot((nc_tbl == nc_rowhead + nc_body) || (rowheadInside && nc_body == 0 && nc_rowhead == 0 && nc_tbl == 1)) partinfo[c("title", "subtitle", "foot"), "nc"] <- nc_tbl min2 <- function(x) { if (length(x[!is.na(x)]) == 0) NA_real_ else min(x, na.rm=TRUE) } max2 <- function(x) { if (length(x[!is.na(x)]) == 0) NA_real_ else max(x, na.rm=TRUE) } blocks <- data.frame(id="table", type="table", subtype=NA_character_, headlayer=NA_real_, level_in_layer=NA_real_, group_in_level=NA_real_, nr=nr_tbl, nc=nc_tbl, arow1={ if (nr_tbl == 0) NA else 1 }, arow2={ if (nr_tbl == 0) NA else nr_tbl }, acol1={ if (nc_tbl == 0) NA else 1 }, acol2={ if (nc_tbl == 0) NA else nc_tbl }, row.names="table", stringsAsFactors=FALSE) if (rowheadInside) { id <- c("title", "subtitle", "colhead", "rowheadLabels", "rowhead_and_body", "foot") cumrows <- cumsum(c(partinfo[c("title", "subtitle", "colhead"), "nr"], nr_rhbody, partinfo["foot", "nr"])) cumcols <- c(nc_rowhead, nc_tbl) arow2 <- cumrows[c(1, 2, 3, 3, 4, 5)] acol2 <- cumcols[c(2, 2, 2, 1, 2, 2)] nr <- c(partinfo[c("title", "subtitle", "colhead", "rowheadLabels"), "nr"], nr_rhbody, partinfo["foot", "nr"]) nc <- c(nc_tbl, nc_tbl, partinfo["colhead", "nc"], nc_rowhead, nc_tbl, nc_tbl) } else { id <- c("title", "subtitle", "colhead", "rowheadLabels", "rowhead", "body", "foot") arow2 <- partinfo[id, "arow2"] acol2 <- partinfo[id, "acol2"] nr <- partinfo[id, "nr"] nc <- partinfo[id, "nc"] } arow2[nr == 0] <- NA acol2[nc == 0] <- NA dfr <- data.frame(id, type=id, subtype=NA_character_, headlayer=NA_real_, level_in_layer=NA_real_, group_in_level=NA_real_, nr, nc, arow1=arow2 - nr + 1, arow2, acol1=acol2 - nc + 1, acol2, row.names=id, stringsAsFactors=FALSE) blocks <- rbind(blocks, dfr) dfr <- data.frame(id="stub", type="stub", subtype=NA_character_, headlayer=NA_real_, level_in_layer=NA_real_, group_in_level=NA_real_, nr=nr_stub, nc=nc_rowhead, arow1=blocks["colhead", "arow1"], arow2=blocks["colhead", "arow2"], acol1={ if (nc_rowhead == 0) NA else 1 }, acol2={ if (nc_rowhead == 0) NA else nc_rowhead }, row.names="stub", stringsAsFactors=FALSE) blocks <- rbind(blocks, dfr) blockUnion <- function(blks, which_rows, new_id, type=new_id, subtype=NA_character_) { mat <- data.matrix(blks[which_rows, c("nr", "nc", "arow1", "arow2", "acol1", "acol2")]) rownames(mat) <- NULL arow1 <- min2(mat[, "arow1"]) arow2 <- max2(mat[, "arow2"]) acol1 <- min2(mat[, "acol1"]) acol2 <- max2(mat[, "acol2"]) nr <- { if (is.na(arow2 - arow1)) 0 else arow2 - arow1 + 1 } nc <- { if (is.na(acol2 - acol1)) 0 else acol2 - acol1 + 1 } dfr <- data.frame(id=new_id, type=type, subtype=subtype, headlayer=NA_real_, level_in_layer=NA_real_, group_in_level=NA_real_, nr=nr, nc=nc, arow1=arow1, arow2=arow2, acol1=acol1, acol2=acol2, row.names=new_id, stringsAsFactors=FALSE) dfr } dfr <- blockUnion(blocks, new_id="titles", which_rows=c("title", "subtitle")) blocks <- rbind(blocks, dfr) if (!rowheadInside) { dfr1 <- blockUnion(blocks, new_id="rowhead_and_stub", which_rows=c("stub", "rowhead")) blocks <- rbind(blocks, dfr1) } dfr2 <- blockUnion(blocks, new_id="colhead_and_stub", which_rows=c("stub", "colhead")) blocks <- rbind(blocks, dfr2) if (!rowheadInside) { dfr1 <- blockUnion(blocks, new_id="rowhead_and_body", which_rows=c("body", "rowhead")) blocks <- rbind(blocks, dfr1) } dfr2 <- blockUnion(blocks, new_id="colhead_and_body", which_rows=c("body", "colhead")) blocks <- rbind(blocks, dfr2) xhiers <- list(rowhead=attr(x, "rowhier"), colhead=attr(x, "colhier")) for (part in c("rowhead", "colhead")) { which_head <- substr(part, 1, 3) xhier <- xhiers[[part]] n_head <- length(xhier) if (n_head == 0) next xhier <- do.call(rbind, xhier) nnodes <- nrow(xhier) if (nnodes > 0) { layer <- xhier$headlayer varnum <- n_head - layer + 1 if (which_head == "row" && rowheadInside) { layer <- ifelse(layer == n_head, 0, layer) } eid <- { if (which_head == "row") paste("rowhead", xhier$start, varnum, sep=",") else paste("colhead", varnum, xhier$start, sep=",") } if (!all(okay <- (eid %in% x$id))) stop( "Following entries not found in 'x': ", toString(eid[!okay], width=60)) arow1 <- x[eid, "arow1"] acol1 <- x[eid, "acol1"] if (which_head == "row") { arow2 <- ifelse(layer == 0, arow1, arow1 + xhier$runlen - 1) acol2 <- x[eid, "acol2"] } else { arow2 <- x[eid, "arow2"] acol2 <- acol1 + xhier$runlen - 1 } dfrA <- data.frame(type=paste0(which_head, "block"), subtype="A", headlayer=layer, level_in_layer=xhier[, "level_in_layer"], group_in_level=NA_real_, arow1, arow2, acol1, acol2, stringsAsFactors=FALSE) dfrB <- dfrA dfrB$subtype <- "B" dfrC <- dfrB dfrC$subtype <- "C" if (which_head == "row") { dfrB$acol2 <- blocks["stub", "acol2"] dfrC$acol2 <- nc_tbl if (rowheadInside) { lyr0 <- (layer == 0) if (nc_rowhead + nc_body > 0) { dfrB[lyr0, "arow1"] <- dfrA[lyr0, "arow1"] + 1 dfrB[lyr0, "arow2"] <- dfrA[lyr0, "arow1"] + xhier[lyr0, "runlen"] dfrC[lyr0, c("arow1", "arow2")] <- dfrB[lyr0, c("arow1", "arow2")] if (nc_rowhead == 0) { dfrB[lyr0, c("acol1", "acol2")] <- NA_real_ } } else { dfrB[lyr0, c("arow1", "arow2", "acol1", "acol2")] <- NA_real_ dfrC[lyr0, c("arow1", "arow2", "acol1", "acol2")] <- NA_real_ } } } else { dfrB$arow2 <- blocks["stub", "arow2"] dfrC$arow2 <- blocks["stub", "arow2"] + nr_rhbody } dfr2 <- rbind(dfrA, dfrB, dfrC) id <- with(dfr2, paste(type, subtype, headlayer, level_in_layer, sep="/")) nr <- with(dfr2, ifelse(is.na(arow2 - arow1), 0, arow2 - arow1 + 1)) nc <- with(dfr2, ifelse(is.na(acol2 - acol1), 0, acol2 - acol1 + 1)) dfr2 <- data.frame(id, dfr2[, c("type", "subtype", "headlayer", "level_in_layer", "group_in_level")], nr, nc, dfr2[, c("arow1", "arow2", "acol1", "acol2")], row.names=id, stringsAsFactors=FALSE) blocks <- rbind(blocks, dfr2) } } if (rowgroupSize > 0) { grpblks <- make_rowgroups(blocks, rowheadruns=attr(x, "rowhier"), rowgroupSize=rowgroupSize) blocks <- rbind(blocks, grpblks) } stopifnot(!any(duplicated(blocks$id)), !anyNA(blocks$nr), !anyNA(blocks$nc)) stopifnot(with(blocks, all((is.na(arow2-arow1) & nr==0) | (!is.na(arow2-arow1) & nr==arow2-arow1+1 & nr > 0)))) stopifnot(with(blocks, all((is.na(acol2-acol1) & nc==0) | (!is.na(acol2-acol1) & nc==acol2-acol1+1 & nc > 0)))) had_enabled_entries <- rep(NA, nrow(blocks)) wch_entries <- entries_by_block(x, blocks=blocks, strict=FALSE) for (i in seq_along(wch_entries)) { had_enabled_entries[i] <- any(x[wch_entries[[i]], "enabled"]) } blocks$had_enabled_entries <- had_enabled_entries row.names(blocks) <- blocks$id blocks <- structure(blocks, rowheadInside=rowheadInside, rowgroupSize=rowgroupSize) class(blocks) <- c("tblBlocks", "data.frame") blocks }
grab_rt_live <- function(State = state_name, ST = state_abbrv){ url <- "https://d14wlfuexuxgcm.cloudfront.net/covid/rt.csv" if ( as.character(url_file_exists(url)[1]) == "TRUE" ) { rt_live <- read.csv("https://d14wlfuexuxgcm.cloudfront.net/covid/rt.csv") %>% filter(region == ST) %>% mutate(date = as.Date(as.character(date)), region = as.character(region)) msg <- paste0("Successfully download data from Rt.live for ", State, " on ", Sys.Date()) } else { msg <- paste0("Problem with Rt.live link to file updates. Check URL.") } print(msg) return(rt_live) }
setMethod('predict', signature(object='Mahalanobis'), function(object, x, toCenter=FALSE, ext=NULL, filename='', ...) { if (toCenter) { m <- colMeans(object@presence, na.rm=TRUE) } if (! (extends(class(x), 'Raster')) ) { if (! all(colnames(object@presence) %in% colnames(x)) ) { stop('missing variables in matrix ') } x <- x[ , colnames(object@presence),drop=FALSE] if (toCenter) { mah <- 1 - apply(data.frame(x), 1, FUN=function(z) mahalanobis(z, m, object@cov, inverted=TRUE)) return(mah) } else { mah <- 1 - apply(data.frame(x), 1, FUN=function(z) min( mahalanobis(object@presence, z, object@cov, inverted=TRUE))) } } else { if (! all(colnames(object@presence) %in% names(x)) ) { stop('missing variables in Raster object ') } out <- raster(x) if (!is.null(ext)) { out <- crop(out, ext) firstrow <- rowFromY(x, yFromRow(out, 1)) firstcol <- colFromX(x, xFromCol(out, 1)) } else { firstrow <- 1 firstcol <- 1 } ncols <- ncol(out) if (canProcessInMemory(out, 2)) { inmem <- TRUE v <- matrix(NA, ncol=nrow(out), nrow=ncol(out)) } else { inmem <- FALSE if (filename == '') { filename <- rasterTmpFile() if (getOption('verbose')) { message('writing raster to:', filename) } } out <- writeStart(out, filename=filename, ...) } cn <- colnames(object@presence) tr <- blockSize(out, n=nlayers(x)+2) pb <- pbCreate(tr$n, ...) for (i in 1:tr$n) { rr <- firstrow + tr$row[i] - 1 vals <- getValuesBlock(x, row=rr, nrows=tr$nrows[i], firstcol, ncols) vals <- vals[,cn,drop=FALSE] if (toCenter) { res <- 1 - apply(data.frame(vals), 1, FUN=function(z) mahalanobis(z, m, object@cov, inverted=TRUE)) } else { res <- 1 - apply(data.frame(vals), 1, FUN=function(z) min( mahalanobis(object@presence, z, object@cov, inverted=TRUE))) } if (inmem) { res <- matrix(res, nrow=ncol(out)) cols = tr$row[i]:(tr$row[i]+dim(res)[2]-1) v[, cols] <- res } else { out <- writeValues(out, res, tr$row[i]) } pbStep(pb, i) } if (inmem) { out <- setValues(out, as.vector(v)) if (filename != '') { out <- writeRaster(out, filename, ...) } } else { out <- writeStop(out) } pbClose(pb) return(out) } })
bubbleRadviz <- function(x, main = NULL, group = NULL, color = NULL, size = c(3,16), label.color=NULL, label.size=NULL, bubble.color, bubble.fg, bubble.size, scale, decreasing, add) { if(!missing(bubble.color)) warning('bubble.color is a deprecated argument, use plot(x)+geom_point() and custom data and mappings to change plot.',call. = FALSE) if(!missing(bubble.fg)) warning('bubble.fg is a deprecated argument, use plot(x)+geom_point() and custom data and mappings to change plot.',call. = FALSE) if(!missing(bubble.size)) warning('bubble.size is a deprecated argument, use plot(x)+geom_point() and custom data and mappings to change plot.',call. = FALSE) if(!missing(scale)) warning('scale is a deprecated argument, use plot(x)+geom_point() and custom data and mappings to change plot.',call. = FALSE) if(!missing(decreasing)) warning('decreasing is a deprecated argument, use plot(x)+geom_point() and custom data and mappings to change plot.',call. = FALSE) if(!missing(add)) warning('add is a deprecated argument, use plot(x)+geom_point() and custom data and mappings to change plot.',call. = FALSE) if(is.null(group)) { stop('Group must be set to a grouping column') } if(!is.null(color)) { if(!color %in% colnames(x$proj$data)) { stop(color,'is not a valid column name') } else if(!is.numeric(x$proj$data[,color])) { stop('color must correspond to a numeric vector') } } p <- x$proj+ ggtitle(main) if(!is.null(label.color) | !is.null(label.size)) { if(is.null(label.size)) label.size <- NA if(is.null(label.color)) label.color <- 'orangered4' if(!is.numeric(label.size)) label.size <- as.numeric(label.size) p$layers[[1]] <- geom_text(data = p$layers[[1]]$data, aes_string(x='X1',y='X2',label='Channel'), color=label.color, size=label.size) } dims <- c(color,'rx','ry') slayer <- geom_point(data=left_join(x$proj$data %>% filter(!.data$rvalid) %>% select(c(dims,group)) %>% group_by(!!sym(group)) %>% summarise_at(.vars=dims,.funs=median), x$proj$data %>% count(!!sym(group)), by=group) %>% mutate(!!group:=factor(!!sym(group)), !!group:=reorder(!!sym(group),.data$n,max)), aes_string(x='rx',y='ry', color=ifelse(is.null(color),group,color), size='n')) p$layers <- c(slayer,p$layers) p <- p+ scale_size(range=size) if(!is.null(color)) { p <- p+scale_color_gradient(low='grey90',high='dodgerblue4') } return(p) }
simplepanel <- function(title, B, boxes, clicks, redraws=NULL, exit=NULL, env) { stopifnot(is.rectangle(B)) stopifnot(is.list(boxes)) if(!all(unlist(lapply(boxes, is.rectangle)))) stop("some of the boxes are not rectangles") if(!all(unlist(lapply(boxes, is.subset.owin, B=B)))) stop("Some boxes do not lie inside the bounding box B") stopifnot(is.list(clicks) && length(clicks) == length(boxes)) if(!all(unlist(lapply(clicks, is.function)))) stop("clicks must be a list of functions") if(is.null(redraws)) { redraws <- rep.int(list(dflt.redraw), length(boxes)) } else { stopifnot(is.list(redraws) && length(redraws) == length(boxes)) if(any(isnul <- unlist(lapply(redraws, is.null)))) redraws[isnul] <- rep.int(list(dflt.redraw), sum(isnul)) if(!all(unlist(lapply(redraws, is.function)))) stop("redraws must be a list of functions") } if(is.null(exit)) { exit <- function(...) { NULL} } else stopifnot(is.function(exit)) stopifnot(is.environment(env)) n <- length(boxes) bnames <- names(boxes) %orifnull% rep("", n) cnames <- names(clicks) %orifnull% rep("", n) dnames <- paste("Button", seq_len(n)) nama <- ifelse(nzchar(bnames), bnames, ifelse(nzchar(cnames), cnames, dnames)) out <- list(title=title, B=B, nama=nama, boxes=boxes, clicks=clicks, redraws=redraws, exit=exit, env=env) class(out) <- c("simplepanel", class(out)) return(out) } grow.simplepanel <- function(P, side=c("right","left","top","bottom"), len=NULL, new.clicks, new.redraws=NULL, ..., aspect) { verifyclass(P, "simplepanel") side <- match.arg(side) stopifnot(is.list(new.clicks)) if(!all(unlist(lapply(new.clicks, is.function)))) stop("new.clicks must be a list of functions") if(is.null(new.redraws)) { new.redraws <- rep.int(list(dflt.redraw), length(new.clicks)) } else { stopifnot(is.list(new.redraws) && length(new.redraws) == length(new.clicks)) if(any(isnul <- sapply(new.redraws, is.null))) new.redraws[isnul] <- rep.int(list(dflt.redraw), sum(isnul)) if(!all(unlist(lapply(new.redraws, is.function)))) stop("new.redraws must be a list of functions") } if(missing(aspect) || is.null(aspect)) { n <- length(new.clicks) nama <- names(new.clicks) if(sum(nzchar(nama)) != n) nama <- names(new.redraws) if(sum(nzchar(nama)) != n) nama <- paste("Box", seq_len(n)) aspect <- 3/max(4, nchar(nama)) } B <- P$B n <- length(new.clicks) switch(side, right={ new.width <- if(!is.null(len)) len else sidelengths(B)[1]/2 extraspace <- owin(B$xrange[2] + c(0, new.width), B$yrange) new.boxes <- layout.boxes(extraspace, n, ..., aspect=aspect) }, left={ new.width <- if(!is.null(len)) len else sidelengths(B)[1]/2 extraspace <- owin(B$xrange[1] - c(new.width, 0), B$yrange) new.boxes <- layout.boxes(extraspace, n, ..., aspect=aspect) }, top={ new.height <- if(!is.null(len)) len else sidelengths(B)[2]/2 extraspace <- owin(B$xrange, B$yrange[2] + c(0, new.height)) new.boxes <- layout.boxes(extraspace, n, ..., aspect=aspect, horizontal=TRUE) }, bottom={ new.height <- if(!is.null(len)) len else sidelengths(B)[2]/2 extraspace <- owin(B$xrange, B$yrange[1] - c(new.height, 0)) new.boxes <- layout.boxes(extraspace, n, ..., aspect=aspect, horizontal=TRUE) }) with(P, simplepanel(title, boundingbox(B, extraspace), append(boxes, new.boxes), append(clicks, new.clicks), append(redraws, new.redraws), exit, env)) } redraw.simplepanel <- function(P, verbose=FALSE) { verifyclass(P, "simplepanel") if(verbose) cat("Redrawing entire panel\n") with(P, { plot(B, type="n", main=title) for(j in seq_along(nama)) (redraws[[j]])(boxes[[j]], nama[j], env) }) invisible(NULL) } clear.simplepanel <- function(P) { verifyclass(P, "simplepanel") plot(P$B, main="") invisible(NULL) } run.simplepanel <- function(P, popup=TRUE, verbose=FALSE) { verifyclass(P, "simplepanel") if(popup) dev.new() ntitle <- sum(nzchar(P$title)) opa <- par(mar=c(0,0,ntitle+0.2,0),ask=FALSE) with(P, { more <- TRUE while(more) { redraw.simplepanel(P, verbose=verbose) xy <- spatstatLocator(1) if(is.null(xy)) { if(verbose) cat("No (x,y) coordinates\n") break } found <- FALSE for(j in seq_along(boxes)) { if(inside.owin(xy$x, xy$y, boxes[[j]])) { found <- TRUE if(verbose) cat(paste("Caught click on", sQuote(nama[j]), "\n")) more <- (clicks[[j]])(env, xy) if(!is.logical(more) || length(more) != 1) { warning(paste("Click function for", sQuote(nama[j]), "did not return TRUE/FALSE")) more <- FALSE } if(verbose) cat(if(more) "Continuing\n" else "Terminating\n") break } } if(verbose && !found) cat(paste("Coordinates", paren(paste(xy, collapse=",")), "not matched to any box\n")) } }) if(verbose) cat("Calling exit function\n") rslt <- with(P, exit(env)) par(opa) if(popup) dev.off() return(rslt) } layout.boxes <- function(B, n, horizontal=FALSE, aspect=0.5, usefrac=0.9){ stopifnot(is.rectangle(B)) stopifnot(n > 0) width <- sidelengths(B)[1] height <- sidelengths(B)[2] if(!horizontal) { heightshare <- height/n useheight <- min(width * aspect, heightshare * usefrac) usewidth <- min(useheight /aspect, width * usefrac) lostwidth <- width - usewidth lostheightshare <- heightshare - useheight template <- owin(c(0, usewidth), c(0, useheight)) boxes <- list() boxes[[1]] <- shift(template, c(B$xrange[1]+lostwidth/2, B$yrange[1] + lostheightshare/2)) if(n > 1) for(j in 2:n) boxes[[j]] <- shift(boxes[[j-1]], c(0, heightshare)) } else { boxes <- layout.boxes(flipxy(B), n, horizontal=FALSE, aspect=1/aspect, usefrac=usefrac) boxes <- lapply(boxes, flipxy) } return(boxes) } dflt.redraw <- function(button, name, env) { plot(button, add=TRUE, border="pink") text(centroid.owin(button), labels=name) } print.simplepanel <- function(x, ...) { nama <- x$nama cat("simplepanel object\n") cat(paste("\tTitle:", sQuote(x$title), "\n")) cat("\tPanel names:") for(i in seq_along(nama)) { if(i %% 6 == 1) cat("\n\t") cat(paste0(sQuote(nama[i]), " ")) } cat("\n") return(invisible(NULL)) }
starwars_dm <- function(configure_dm = TRUE, remote = FALSE) { requires_dm("starwars_dm()") x <- if (isTRUE(remote)) { dm::dm_from_src(starwars_connect(), learn_keys = FALSE) } else { dm::as_dm(starwarsdb_tables()) } if (!isTRUE(configure_dm)) return(x) starwars_dm_configure(x) } starwars_dm_configure <- function(dm) { requires_dm("starwars_dm_configure()") dm %>% dm::dm_add_pk("films", "title") %>% dm::dm_add_pk("people", "name") %>% dm::dm_add_pk("planets", "name") %>% dm::dm_add_pk("species", "name") %>% dm::dm_add_pk("vehicles", "name") %>% dm::dm_add_fk("films_people", "title", "films") %>% dm::dm_add_fk("films_people", "character", "people") %>% dm::dm_add_fk("films_planets", "title", "films") %>% dm::dm_add_fk("films_planets", "planet", "planets") %>% dm::dm_add_fk("films_vehicles", "title", "films") %>% dm::dm_add_fk("films_vehicles", "vehicle", "vehicles") %>% dm::dm_add_fk("pilots", "pilot", "people") %>% dm::dm_add_fk("pilots", "vehicle", "vehicles") %>% dm::dm_add_fk("people", "species", "species") %>% dm::dm_add_fk("people", "homeworld", "planets") %>% dm::dm_set_colors( " " " " " ) } requires_dm <- function(fn = NULL) { if (!has_dm()) { msg <- "requires the {dm} package: install.packages('dm')" if (!is.null(fn)) msg <- paste(fn, msg) stop(msg, call. = is.null(fn)) } } has_dm <- function() { requireNamespace("dm", quietly = TRUE) }
estPI <- function(X,g,type="pair",goi=NULL,mc=1,order=TRUE,alg="Cnaive"){ type <- match.arg(type,c("single","pair","triple")) alg <- match.arg(alg,c("Cnaive","Csubmat","Rsubmat","Rnaive","Rgrid")) g <- relabelGroups(g) result <- list() dimX <- dim(X) XisVector <- is.null(dimX) if(is.null(goi)) goi <- g goi <- unique(goi) Ngoi <- length(goi) pickThose <- is.element(g,goi) ifelse(XisVector , X <- X[pickThose] , X <- X[pickThose,]) g <- g[pickThose] if(mc>detectCores()) { mc <- detectCores() warning(paste("You do not have so many cores on this machine! I automatically reduced it to your machines maximum number:",mc,"\n")) } mc <- min(dimX[2],mc) NlistItems <- c() if(type=="single") { NlistItems <- Ngoi comb <- goi } else if (type=="pair"){ NlistItems <- getNListItems(Ngoi,"pair",order) comb <- getComb(goi,type="pairs",order) } else if (type=="triple"){ NlistItems <- getNListItems(Ngoi,"triple",order) comb <- getComb(goi,type="triple",order) } inner1 <- function(i,X,g,t,goi,alg){ PE1(X[,i],g,t,goi,alg) } inner2 <- function(i,X,g,comb,alg){ PE2(X[,i],g,comb,alg) } inner3 <- function(i,X,g,comb,alg){ PE3(X[,i],g,comb,alg) } for(oRun in 1:NlistItems) { if(XisVector) { if(type=="single") { result[[oRun]] <- PE1(X,g,goi[oRun],goi,alg) names(result)[oRun] <- paste("P(",goi[oRun],")",sep="") } else if(type=="pair") { result[[oRun]] <- PE2(X,g,comb[oRun,],alg) names(result)[oRun] <- paste("P(",paste(comb[oRun,],collapse="<"),")",sep="") } else if(type=="triple") { result[[oRun]] <- PE3(X,g,comb[oRun,],alg) names(result)[oRun] <- paste("P(",paste(comb[oRun,],collapse="<"),")",sep="") } } else { if(type=="single") { result[[oRun]] <- unlist(mclapply(c(1:dimX[2]),inner1,X,g,goi[oRun],goi,alg,mc.cores=mc)) names(result)[oRun] <- paste("P(",goi[oRun],")",sep="") } else if(type=="pair"){ result[[oRun]] <- unlist(mclapply(c(1:dimX[2]),inner2,X,g,comb[oRun,],alg,mc.cores=mc)) names(result)[oRun] <- paste("P(",paste(comb[oRun,],collapse="<"),")",sep="") } else if(type=="triple"){ result[[oRun]] <- unlist(mclapply(c(1:dimX[2]),inner3,X,g,comb[oRun,],alg,mc.cores=mc)) names(result)[oRun] <- paste("P(",paste(comb[oRun,],collapse="<"),")",sep="") } } } if(XisVector) { result <- unlist(result) } else { temp <- matrix(NA,nrow=NlistItems,ncol=dimX[2]) for(i in 1:NlistItems) { temp[i,] <- result[[i]] } rownames(temp) <- names(result) colnames(temp) <- colnames(X) result <- temp } res <- list(probs=result,type=type,goi=goi,order=order,obs=X,g=g,alg=alg) class(res) <- "estPI" return(res) }
sienaRI <- function(data, ans=NULL, theta=NULL, algorithm=NULL, effects=NULL, getChangeStats=FALSE) { if (!inherits(data, "siena")) { stop("no a legitimate Siena data specification") } datatypes <- sapply(data$depvars, function(x){attr(x,"type")}) if (any(datatypes == "bipartite")) { stop("sienaRI works only for dependent variables of type 'oneMode' or 'behavior'") } if(!is.null(ans)) { if (!inherits(ans, "sienaFit")) { stop(paste("ans is not a legitimate Siena fit object", sep="")) } if(!is.null(algorithm)||!is.null(theta)||!is.null(effects)) { warning(paste("some informations are multiply defined \n", "results will be based on 'theta', 'algorithm', and 'effects'\n", "stored in 'ans' (as 'ans$theta', 'ans$x', 'ans$effects')\n", sep="")) } if (sum(ans$effects$include==TRUE & (ans$effects$type =="endow"|ans$effects$type =="creation")) > 0) { stop("sienaRI does not yet work for models containing endowment or creation effects") } if (any(ans$effects$shortName %in% c("unspInt", "behUnspInt"))){ stop("sienaRI does not yet work for models containing interaction effects") } contributions <- getChangeContributions(algorithm = ans$x, data = data, effects = ans$effects) RI <- expectedRelativeImportance(conts = contributions, effects = ans$effects, theta =ans$theta, thedata=data, getChangeStatistics=getChangeStats) } else { if (!inherits(algorithm, "sienaAlgorithm")) { stop(paste("algorithm is not a legitimate Siena algorithm specification", sep="")) } algo <- algorithm if (!inherits(effects, "sienaEffects")) { stop(paste("effects is not a legitimate Siena effects object", sep="")) } if(sum(effects$include==TRUE & (effects$type =="endow"|effects$type =="creation")) > 0) { stop("sienaRI does not yet work for models containing endowment or creation effects") } effs <- effects if (!is.numeric(theta)) { stop("theta is not a legitimate parameter vector") } if(length(theta) != sum(effs$include==TRUE & effs$type!="rate")) { if(length(theta) != sum(effs$include==TRUE)) { stop("theta is not a legitimate parameter vector \n number of parameters has to match number of effects") } warning(paste("length of theta does not match the number of objective function effects\n", "theta is treated as if containing rate parameters")) paras <- theta contributions <- getChangeContributions(algorithm = algo, data = data, effects = effs) RI <- expectedRelativeImportance(conts = contributions, effects = effs, theta = paras, thedata=data, getChangeStatistics=getChangeStats) }else{ paras <- theta contributions <- getChangeContributions(algorithm = algo, data = data, effects = effs) RI <- expectedRelativeImportance(conts = contributions, effects = effs, theta = paras, thedata=data, getChangeStatistics=getChangeStats) } } RI } getChangeContributions <- function(algorithm, data, effects) { f <- unpackData(data,algorithm) effects <- effects[effects$include,] if (!is.null(algorithm$settings)) { stop('not implemented: RI together with settings') } else { effects$setting <- rep("", nrow(effects)) } pData <- .Call(C_setupData, PACKAGE=pkgname, list(as.integer(f$observations)), list(f$nodeSets)) ans <- reg.finalizer(pData, clearData, onexit = FALSE) ans<- .Call(C_OneMode, PACKAGE=pkgname, pData, list(f$nets)) ans <- .Call(C_Bipartite, PACKAGE=pkgname, pData, list(f$bipartites)) ans<- .Call(C_Behavior, PACKAGE=pkgname, pData, list(f$behavs)) ans<-.Call(C_ConstantCovariates, PACKAGE=pkgname, pData, list(f$cCovars)) ans<-.Call(C_ChangingCovariates,PACKAGE=pkgname, pData,list(f$vCovars)) ans<-.Call(C_DyadicCovariates,PACKAGE=pkgname, pData,list(f$dycCovars)) ans<-.Call(C_ChangingDyadicCovariates,PACKAGE=pkgname, pData, list(f$dyvCovars)) storage.mode(effects$parm) <- 'integer' storage.mode(effects$group) <- 'integer' storage.mode(effects$period) <- 'integer' effects$effectPtr <- rep(NA, nrow(effects)) depvarnames <- names(data$depvars) tmpeffects <- split(effects, effects$name) myeffectsOrder <- match(depvarnames, names(tmpeffects)) ans <- .Call(C_effects, PACKAGE=pkgname, pData, tmpeffects) pModel <- ans[[1]][[1]] for (i in 1:length(ans[[2]])) { effectPtr <- ans[[2]][[i]] tmpeffects[[i]]$effectPtr <- effectPtr } myeffects <- tmpeffects for(i in 1:length(myeffectsOrder)){ myeffects[[i]]<-tmpeffects[[myeffectsOrder[i]]] } ans <- .Call(C_getTargets, PACKAGE=pkgname, pData, pModel, myeffects, parallelrun=TRUE, returnActorStatistics=FALSE, returnStaticChangeContributions=TRUE) ans } expectedRelativeImportance <- function(conts, effects, theta, thedata=NULL, getChangeStatistics=FALSE, effectNames = NULL) { waves <- length(conts[[1]]) effects <- effects[effects$include == TRUE,] noRate <- effects$type != "rate" effects <- effects[noRate,] if(sum(noRate)!=length(theta)) { theta <- theta[noRate] } effectNa <- attr(conts,"effectNames") effectTypes <- attr(conts,"effectTypes") networkNames <- attr(conts,"networkNames") networkTypes <- attr(conts,"networkTypes") networkInteraction <- effects$interaction1 effectIds <- paste(effectNa,effectTypes,networkInteraction, sep = ".") currentDepName <- "" depNumber <- 0 for(eff in 1:length(effectIds)) { if(networkNames[eff] != currentDepName) { currentDepName <- networkNames[eff] actors <- length(conts[[1]][[1]][[1]]) if (networkTypes[eff] == "oneMode") { choices <- actors }else if(networkTypes[eff] == "behavior"){ choices <- 3 } else { stop("so far, sienaRI works only for dependent variables of type 'oneMode' or 'behavior'") } depNumber <- depNumber + 1 currentDepEffs <- effects$name == currentDepName effNumber <- sum(currentDepEffs) depNetwork <- thedata$depvars[[depNumber]] if (networkTypes[eff] == "oneMode") { depNetwork[,,1][is.na(depNetwork[,,1])] <- 0 } else { depNetwork[,,1][is.na(depNetwork[,,1])] <- attr(depNetwork, 'modes')[1] } for (m in 2:dim(depNetwork)[3]){depNetwork[,,m][is.na(depNetwork[,,m])] <- depNetwork[,,m-1][is.na(depNetwork[,,m])]} if (networkTypes[eff] == "oneMode") { for (m in 1:dim(depNetwork)[3]){diag(depNetwork[,,m]) <- 0} } structurals <- (depNetwork >= 10) if (networkTypes[eff] == "oneMode"){ if (attr(depNetwork, 'symmetric')){ message('\nNote that for symmetric networks, effect sizes are for modelType 2 (forcing).')}} entropies <- vector(mode="numeric", length = actors) expectedRI <- list() expectedI <- list() RIActors <- list() IActors <- list() absoluteSumActors <- list() RHActors <-list() changeStats <-list() sigma <- list() for(w in 1:waves) { currentDepEffectContributions <- conts[[1]][[w]][currentDepEffs] currentDepEffectContributions <- sapply(lapply(currentDepEffectContributions, unlist), matrix, nrow=actors, ncol=choices, byrow=TRUE, simplify="array") cdec <- apply(currentDepEffectContributions, c(2,1), as.matrix) if (dim(currentDepEffectContributions)[3] <= 1) { cdec <- array(cdec, dim=c(1,dim(cdec))) } rownames(cdec) <- effectNa[currentDepEffs] if (getChangeStatistics) { changeStats[[w]] <- cdec } if (networkTypes[eff] == "oneMode") { for (ff in 1:dim(cdec)[1]){cdec[ff,,][t(structurals[,,w])] <- NA} } distributions <- apply(cdec, 3, calculateDistributions, theta[which(currentDepEffs)]) distributions <- lapply(apply(distributions, 2, list), function(x){matrix(x[[1]], nrow=effNumber+1, ncol=choices, byrow=F)}) entropy_vector <- unlist(lapply(distributions, function(x){entropy(x[1,])})) RIs_list <- lapply(distributions,function(x){L1D(x[1,], x[2:dim(x)[1],])}) RIs_matrix <-(matrix(unlist(RIs_list),nrow=effNumber, ncol=actors, byrow=F)) entropies <- entropy_vector RIActors[[w]] <- t(t(RIs_matrix)/rowSums(t(RIs_matrix), na.rm=TRUE)) rownames(RIActors[[w]]) <- effectNa[currentDepEffs] absoluteSumActors[[w]] <- colSums(RIs_matrix, na.rm=TRUE) RHActors[[w]] <- entropies expectedRI[[w]] <- rowMeans(RIActors[[w]], na.rm=TRUE) IActors[[w]] <- RIs_matrix rownames(IActors[[w]]) <- effectNa[currentDepEffs] expectedI[[w]] <- rowMeans(RIs_matrix, na.rm=TRUE) sigma[[w]] <- apply(cdec, c(1,3), sd, na.rm=TRUE) rownames(sigma[[w]]) <- effectNa[currentDepEffs] } RItmp <- NULL RItmp$dependentVariable <- currentDepName RItmp$expectedRI <- expectedRI RItmp$RIActors <- RIActors RItmp$expectedI <- expectedI RItmp$IActors <- IActors RItmp$absoluteSumActors <- absoluteSumActors RItmp$RHActors <- RHActors RItmp$sigma <- sigma if(!is.null(effectNames)) { RItmp$effectNames <- effectNames[currentDepEffs] }else{ RItmp$effectNames <- paste(effectTypes[currentDepEffs], " ", effects$effectName[currentDepEffs], sep="") } if (getChangeStatistics){ RItmp$changeStatistics <- changeStats } class(RItmp) <- "sienaRI" if(depNumber == 1){ RI <- RItmp }else if(depNumber == 2){ RItmp1 <- RI RI <- list() RI[[1]]<-RItmp1 RI[[2]]<-RItmp }else{ RI[[depNumber]]<-RItmp } } } if(depNumber>1) { message(paste("more than one dependent variable\n", "return value is therefore not of class 'sienaRI'\n", "but a list of objects of class 'sienaRI'.")) } RI } calculateDistributions <- function(effectContributions = NULL, theta = NULL) { neffects <- dim(effectContributions)[1] nchoices <- dim(effectContributions)[2] distributions <- array(NA, dim = c(neffects+1,nchoices)) the.choices <- !is.na(colSums(effectContributions)) if (sum(the.choices) >= 2) { distributions[1,the.choices] <- exp(colSums(theta*effectContributions[,the.choices,drop=FALSE], na.rm=TRUE))/ sum(exp(colSums(theta*effectContributions[,the.choices,drop=FALSE], na.rm=TRUE))) for(eff in 1:neffects) { th <- theta th[eff] <- 0 distributions[eff+1,the.choices] <- exp(colSums(th*effectContributions[,the.choices,drop=FALSE], na.rm=TRUE))/ sum(exp(colSums(th*effectContributions[,the.choices,drop=FALSE], na.rm=TRUE))) } } distributions } entropy <- function(distribution = NULL) { if (sum(!is.na((distribution))) <= 1) { certainty <- NA } else { entropy <- -1*(sum(distribution * log(distribution), na.rm=TRUE)/ log(sum(!is.na((distribution))))) certainty <- 1 - entropy } certainty } KLD <- function(referenz = NULL, distributions = NULL) { if (sum(!is.na((referenz))) <= 1) { kld <- rep(NA, dim(distributions)[1]) } else { if(is.vector(distributions)) { kld <- sum(referenz * (log(referenz)-log(distributions)), na.rm=TRUE)/log(sum(!is.na((referenz)))) } else { kld <- colSums(referenz * (log(referenz)-t(log(distributions))), na.rm=TRUE)/log(sum(!is.na((referenz)))) } } kld } L1D <- function(referenz = NULL, distributions = NULL) { if (sum(!is.na((referenz))) <= 1) { l1d <- rep(NA, dim(distributions)[1]) } else { if(is.vector(distributions)) { l1d <- sum(abs(referenz-distributions), na.rm=TRUE) } else { l1d <- colSums(abs(referenz-t(distributions)), na.rm=TRUE) } } l1d } print.sienaRI <- function(x, printSigma = FALSE, ...){ if (!inherits(x, "sienaRI")) { if (inherits(x[[1]], "sienaRI")) { cat("This object is a list, the components of which\n") cat("are Siena relative importance of effects objects.\n") cat("Apply the print function to the separate components.\n") } stop("not a legitimate Siena relative importance of effects object") } cat(paste("\n Expected relative importance of effects for dependent variable '", x$dependentVariable,"' at observation moments:\n\n\n", sep="")) waves <- length(x$expectedRI) effs <- length(x$effectNames) colNames = paste("wave ", 1:waves, sep="") line1 <- format("", width =63) line2 <- paste(format(1:effs,width=3), '. ', format(x$effectNames, width = 56),sep="") line3 <- line2 line4 <- format(" R_H ('degree of certainty')", width = 61) line5 <- line2 if (printSigma) { sigmas <- matrix(sapply(x$sigma,rowMeans,na.rm=TRUE), effs, waves) } for (w in 1:length(colNames)) { line1 <- paste(line1, format(colNames[w], width=8)," ", sep = "") line2 <- paste(line2, format(round(x$expectedRI[[w]], 4), width=8, nsmall=4)," ",sep="") line3 <- paste(line3, format(round(x$expectedI[[w]], 4), width=8, nsmall=4)," ",sep="") line4 <- paste(line4, format(round(mean(x$RHActors[[w]], na.rm=TRUE), 4), width=8, nsmall=4)," ",sep="") if (printSigma) { line5 <- paste(line5, format(round(sigmas[,w], 4), width=8, nsmall=4)," ",sep="") } } line2 <- paste(line2, rep('\n',effs), sep="") line3 <- paste(line3, rep('\n',effs), sep="") cat(as.matrix(line1),'\n \n', sep='') cat(as.matrix(line2),'\n', sep='') cat("\n Expected importance of effects for this dependent variable:\n\n") cat(as.matrix(line3),'\n\n', sep='') cat(as.matrix(line4),'\n', sep='') if (printSigma) { cat("\n sigma (within-ego standard deviation of change statistics):\n\n") line5 <- paste(line5, rep('\n',effs), sep="") cat('\n',as.matrix(line5),'\n', sep='') } invisible(x) } summary.sienaRI <- function(object, ...) { if (!inherits(object, "sienaRI")) { stop("not a legitimate Siena relative importance of effects object") } class(object) <- c("summary.sienaRI", class(object)) object } print.summary.sienaRI <- function(x, ...) { if (!inherits(x, "summary.sienaRI")) { stop("not a legitimate summary of a Siena relative importance of effects object") } print.sienaRI(x) invisible(x) } plot.sienaRI <- function(x, actors = NULL, col = NULL, addPieChart = FALSE, radius = 1, width = NULL, height = NULL, legend = TRUE, legendColumns = NULL, legendHeight = NULL, cex.legend = NULL, cex.names = NULL, ...) { if (!inherits(x, "sienaRI")) { stop("not a legitimate Siena relative importance of effects object") } waves <- length(x$expectedRI) if (is.null(actors)) { nactors <- dim(x$RIActors[[1]])[2] actors <- (1:nactors) } else { if ((!inherits(actors,"integer")) || (min(actors) < 1) || (max(actors) > dim(x$RIActors[[1]])[2])) { stop(paste("parameter <actors> must be a set of integers from 1 to", dim(x$RIActors[[1]])[2])) } nactors <- length(actors) } if(legend) { if(!is.null(legendColumns)) { if(is.numeric(legendColumns)) { legendColumns <- as.integer(legendColumns) }else{ legendColumns <- NULL warning("legendColumns has to be of type 'numeric' \n used default settings") } } if(is.null(legendColumns)) { legendColumns <-floor((nactors+2)/11) } if(!is.null(legendHeight)) { if(is.numeric(legendHeight)) { legendHeight <- legendHeight }else{ legendHeight <- NULL warning("legendHeight has to be of type 'numeric' \n used default settings") } } if(is.null(legendHeight)) { legendHeight <- max(0.8,ceiling(length(x$effectNames)/legendColumns)*0.2) } } if(!is.null(height)) { if(is.numeric(height)) { height <- height }else{ height <- NULL warning("height has to be of type 'numeric' \n used default settings") } } if(is.null(height)) { height <- 1 } if(!is.null(width)) { if(is.numeric(width)) { width <- width }else{ width <- NULL warning("width has to be of type 'numeric' \n used default settings") } } if(is.null(width)) { if(addPieChart) { width = (nactors/3+4) }else{ width = (nactors/3+3) } } if(!is.null(cex.legend)) { if(is.numeric(cex.legend)) { cex.legend <- cex.legend }else{ cex.legend <- NULL warning("cex.legend has to be of type 'numeric' \n used default settings") } } if(is.null(cex.legend)) { cex.legend <- 1.3 } if(!is.null(cex.names)) { if(is.numeric(cex.names)) { cex.names <- cex.names }else{ cex.names <- NULL warning("cex.names has to be of type 'numeric' \n used default settings") } } if(is.null(cex.names)) { cex.names <- 1 } if(!is.null(radius)) { if(is.numeric(radius)) { rad <- radius }else{ rad <- NULL warning("radius has to be of type 'numeric' \n used default settings") } } if(is.null(radius)) { rad <- 1 } if(!is.null(col)) { cl <- col }else{ alph <- 175 green <- rgb(127, 201, 127,alph, maxColorValue = 255) lila <-rgb(190, 174, 212,alph, maxColorValue = 255) orange <- rgb(253, 192, 134,alph, maxColorValue = 255) yellow <- rgb(255, 255, 153,alph, maxColorValue = 255) blue <- rgb(56, 108, 176,alph, maxColorValue = 255) lightgray <- rgb(184,184,184,alph, maxColorValue = 255) darkgray <- rgb(56,56,56,alph, maxColorValue = 255) gray <- rgb(120,120,120,alph, maxColorValue = 255) pink <- rgb(240,2,127,alph, maxColorValue = 255) brown <- rgb(191,91,23,alph, maxColorValue = 255) cl <- c(green,lila,orange,yellow,blue,lightgray,darkgray,gray,pink,brown) while(length(cl)<length(x$effectNames)){ alph <- (alph+75)%%255 green <- rgb(127, 201, 127,alph, maxColorValue = 255) lila <-rgb(190, 174, 212,alph, maxColorValue = 255) orange <- rgb(253, 192, 134,alph, maxColorValue = 255) yellow <- rgb(255, 255, 153,alph, maxColorValue = 255) blue <- rgb(56, 108, 176,alph, maxColorValue = 255) lightgray <- rgb(184,184,184,alph, maxColorValue = 255) darkgray <- rgb(56,56,56,alph, maxColorValue = 255) gray <- rgb(120,120,120,alph, maxColorValue = 255) pink <- rgb(240,2,127,alph, maxColorValue = 255) brown <- rgb(191,91,23,alph, maxColorValue = 255) cl <- c(cl,green,lila,orange,yellow,blue,lightgray,darkgray,gray,pink,brown) } } bordergrey <-"gray25" if(addPieChart) { if(legend) { layoutMatrix <- matrix(c(1:(2*waves+1),(2*waves+1)), byrow= TRUE, ncol=2, nrow=(waves+1)) layout(layoutMatrix,widths= c((nactors/6)+10,3.5+2.5*(rad^2)), heights=c(rep(height,waves),legendHeight)) }else{ layoutMatrix <- matrix(c(1:(2*waves)), byrow= TRUE, ncol=2, nrow=waves) layout(layoutMatrix,widths = c((nactors/6)+10,7+2.5*(rad^2)), heights=rep(height,waves)) } }else{ if(legend) { layoutMatrix <- matrix(c(1:(waves+1)), byrow= TRUE, ncol=1, nrow=(waves+1)) layout(layoutMatrix) }else{ layoutMatrix <- matrix(c(1:waves), byrow= TRUE, ncol=1, nrow=waves) layout(layoutMatrix, heights=2*rep(height,waves)) } par( oma = c( 1, 1, 2, 1 ), xpd=T , cex = 0.75, no.readonly = TRUE ) } par(mar = c(3,3,1,1)) for(w in 1:waves) { barplot(cbind(x$RIActors[[w]][,actors], x$expectedRI[[w]]), space=c(rep(0.1,nactors),1.5),width=c(rep(1,nactors),1), beside =FALSE, yaxt = "n", xlab="Actor", cex.names = cex.names, ylab=paste("wave ", w, sep=""),border=bordergrey, col = cl, names.arg=c(actors,"exp. rel. imp.")) axis(2, at=c(0,0.25,0.5,0.75,1),labels=c("0","","0.5","","1")) axis(4, at=c(0,0.25,0.5,0.75,1),labels=c("0","","0.5","","1")) if(addPieChart) { pie(x$expectedRI[[w]], col = cl, labels=NA, border = bordergrey, radius = rad) mtext("exp. rel. imp.",side = 1, line = 1, cex=cex.names*0.75) } } if(legend) { plot(c(0,1), c(0,1), col=rgb(0,0,0,0), axes=FALSE, ylab = "", xlab = "") legend(0, 1, x$effectNames, fill=cl, ncol = legendColumns, bty = "n", cex=cex.legend) } invisible(cl) }
labtoind <- function(x,row,col,Mat,symmetrical=FALSE){ symmetrical <- x@matrices$symmetrical[x@matrices$name == Mat] if (symmetrical){ vars <- rbind( x@parameters %>% filter(.data[['matrix']] == Mat) %>% select(ind = .data[['row']], var = .data[['var1']]), x@parameters %>% filter(.data[['matrix']] == Mat) %>% select(ind = .data[['col']], var = .data[['var2']]) ) vars <- vars[!duplicated(vars),] row <- vars$ind[match(row,vars$var)] col <- vars$ind[match(col,vars$var)] } else{ rows <- x@parameters %>% filter(.data[['matrix']] == Mat) %>% group_by(.data[["row"]]) %>% summarize(ind = unique(.data[['row']]), var = unique(.data[['var1']])) cols <- x@parameters %>% filter(.data[['matrix']] == Mat) %>% group_by(.data[["col"]]) %>% summarize(ind = unique(.data[['col']]), var = unique(.data[['var2']])) row <- rows$ind[match(row,rows$var)] col <- cols$ind[match(col,cols$var)] } return(list( row=row,col=col )) }
library(dials) library(purrr) library(dplyr) num_prm <- parameters(mixture(), threshold()) cat_prm <- parameters(activation(), weight_func()) test_that('numerical neighborhood', { vals <- tibble::tibble(mixture = 0.5, threshold = 0.5) set.seed(1) new_vals <- finetune:::random_real_neighbor(vals, vals[0,], num_prm, retain = 100) rad <- control_sim_anneal()$radius correct_r <- purrr::map2_dbl(new_vals$mixture, new_vals$threshold, ~ sqrt((.x - .5) ^ 2 + (.y - .5) ^ 2)) %>% map_lgl( ~ .x >= rad[1] & .x <= rad[2]) expect_true(all(correct_r)) set.seed(1) prev <- tibble::tibble(mixture = runif(5), threshold = runif(5)) set.seed(2) more_vals <- finetune:::new_in_neighborhood(vals, prev, num_prm, radius = rep(0.12, 2)) rad_vals <- sqrt((more_vals$mixture - .5) ^ 2 + (more_vals$threshold - .5) ^ 2) expect_equal(rad_vals, 0.12, tolerance = 0.001) }) test_that('numerical neighborhood boundary filters', { vals <- tibble::tibble(mixture = 0.05, threshold = 0.05) set.seed(1) new_vals <- finetune:::random_real_neighbor(vals, vals[0,], num_prm, retain = 100, tries = 100, r = 0.12) expect_true(nrow(new_vals) < 100) }) test_that('categorical value switching', { vals <- tibble::tibble(activation ="relu", weight_func ="biweight") set.seed(1) new_vals <- purrr::map_dfr( 1:1000, ~ finetune:::random_discrete_neighbor(vals, cat_prm, prob = 1 / 4, change = FALSE) ) relu_same <- mean(new_vals$activation == "relu") biweight_same <- mean(new_vals$weight_func == "biweight") expect_true(relu_same > .7 & relu_same < .8) expect_true(biweight_same > .7 & biweight_same < .8) set.seed(1) prev <- tibble::tibble(activation = dials::values_activation[1:4], weight_func = dials::values_weight_func[1:4]) set.seed(2) must_change <- finetune:::new_in_neighborhood(vals, prev, cat_prm, flip = 1) expect_true(must_change$activation != "relu") expect_true(must_change$weight_func != "biweight") }) test_that('reverse-unit encoding', { prm <- parameters(batch_size(), Laplace(), activation()) %>% update(Laplace = Laplace(c(2, 4)), batch_size = batch_size(c(10, 20))) unit_vals <- tibble::tibble(batch_size = .1, Laplace = .4, activation = .7) vals <- finetune:::encode_set_backwards(unit_vals, prm) expect_true(vals$batch_size > 1) expect_true(vals$Laplace > 1) expect_true(is.character(vals$activation)) })
PerMANOVAF <- function(D, grupo, C, Efectos){ g = length(levels(grupo)) n = dim(D)[1] G = FactorToBinary(grupo) Eij = G %*% t(G) TSS=0.5*sum(D^2)/n ng=diag(t(G) %*% G) WSS=sum(0.5*apply((Eij * D^2)%*%G, 2, sum)/ng) BSS=TSS-WSS Fexp=(BSS/(g-1))/(WSS/(n-g)) Result=list() Result$TSS= TSS Result$BSS = BSS Result$WSS = WSS Result$glt=n-1 Result$glb=g-1 Result$glw=n-g Result$Fexp=Fexp return(Result) }
expected <- eval(parse(text="5")); test(id=0, code={ argv <- eval(parse(text="list(5, 1, 0)")); do.call(`max`, argv); }, o=expected);
rxodeTest( { context("v1 rate constants") test_that("v1 rate constants", { p1 <- rxDerived(v1 = 8, k = 0.5, digits = 3) expect_equal( p1, structure(list( vc = 8, kel = 0.5, vss = 8, cl = 4, t12alpha = 1.39, alpha = 0.5, A = 0.125, fracA = 1 ), class = "data.frame", row.names = c(NA, -1L) ) ) p1 <- rxDerived(v1 = 5, k = 0.7, k12 = 0.5, k21 = 0.05, digits = 3) expect_equal( p1, structure(list( vc = 5, kel = 0.7, k12 = 0.5, k21 = 0.05, vp = 50, vss = 55, cl = 3.5, q = 2.5, t12alpha = 0.568, t12beta = 24.2, alpha = 1.22, beta = 0.0287, A = 0.196, B = 0.00358, fracA = 0.982, fracB = 0.0179 ), class = "data.frame", row.names = c(NA, -1L) ) ) p1 <- rxDerived(v1 = 10, k = 0.3, k12 = 0.2, k13 = 0.1, k21 = 0.02, k31 = 0.001, digits = 3) expect_equal(p1, structure(list( vc = 10, kel = 0.3, k12 = 0.2, k21 = 0.02, k13 = 0.1, k31 = 0.001, vp = 100, vp2 = 1000, vss = 1110, cl = 3, q = 2, q2 = 1, t12alpha = 1.14, t12beta = 52.2, t12gamma = 931, alpha = 0.607, beta = 0.0133, gamma = 0.000745, A = 0.0988, B = 0.00111, C = 6.47e-05, fracA = 0.988, fracB = 0.0111, fracC = 0.000647 ), class = "data.frame", row.names = c(NA, -1L) )) }) context("Volumes and clearances") test_that("Volumes and clearances", { p1 <- rxDerived(v1 = 8.0, cl = 4.0, digits = 3) expect_equal(p1, structure(list( vc = 8, kel = 0.5, vss = 8, cl = 4, t12alpha = 1.39, alpha = 0.5, A = 0.125, fracA = 1 ), class = "data.frame", row.names = c(NA, -1L) )) p1 <- rxDerived(v1 = 5.0, v2 = 50, cl = 3.5, q = 2.5, digits = 3) expect_equal(p1, structure(list( vc = 5, kel = 0.7, k12 = 0.5, k21 = 0.05, vp = 50, vss = 55, cl = 3.5, q = 2.5, t12alpha = 0.568, t12beta = 24.2, alpha = 1.22, beta = 0.0287, A = 0.196, B = 0.00358, fracA = 0.982, fracB = 0.0179 ), class = "data.frame", row.names = c(NA, -1L) )) p1 <- rxDerived( v1 = 10, v2 = 100, v3 = 1000, cl = 3, q = 2, q2 = 1, digits = 3 ) expect_equal(p1, structure(list( vc = 10, kel = 0.3, k12 = 0.2, k21 = 0.02, k13 = 0.1, k31 = 0.001, vp = 100, vp2 = 1000, vss = 1110, cl = 3, q = 2, q2 = 1, t12alpha = 1.14, t12beta = 52.2, t12gamma = 931, alpha = 0.607, beta = 0.0133, gamma = 0.000745, A = 0.0988, B = 0.00111, C = 6.47e-05, fracA = 0.988, fracB = 0.0111, fracC = 0.000647 ), class = "data.frame", row.names = c(NA, -1L) )) }) }, test = "lvl2" )
knitr::opts_chunk$set( collapse = TRUE, comment = " ) library(pkgdown)
Id <- "$Id: c212.interim.BB.hier3.lev0.convergence.R,v 1.9 2019/05/05 13:18:12 clb13102 Exp clb13102 $" c212.interim.BB.indep.convergence.diag <- function(raw, debug_diagnostic = FALSE) { c_base = c212.interim.1a.indep.convergence.diag(raw, debug_diagnostic) if (is.null(c_base)) { return(NULL) } monitor = raw$monitor theta_mon = monitor[monitor$variable == "theta",]$monitor pi_mon = monitor[monitor$variable == "pi",]$monitor alpha_pi_mon = monitor[monitor$variable == "alpha.pi",]$monitor beta_pi_mon = monitor[monitor$variable == "beta.pi",]$monitor nchains = raw$chains if (alpha_pi_mon == 1 && !("alpha.pi" %in% names(raw))) { print("Missing alpha.pi data") return(NULL) } if (beta_pi_mon == 1 && !("beta.pi" %in% names(raw))) { print("Missing beta.pi data") return(NULL) } if (pi_mon == 1 && !("pi" %in% names(raw))) { print("Missing pi data") return(NULL) } if (raw$sim_type == "MH") { if (alpha_pi_mon == 1 && !("alpha.pi_acc" %in% names(raw))) { print("Missing beta.pi_acc data") return(NULL) } if (beta_pi_mon == 1 && !("beta.pi_acc" %in% names(raw))) { print("Missing beta.pi_acc data") return(NULL) } } else { if (theta_mon == 1 && !("theta_acc" %in% names(raw))) { print("Missing theta_acc data") return(NULL) } } pi_conv = data.frame(Interval = character(0), B = character(0), stat = numeric(0), upper_ci = numeric(0), stringsAsFactors=FALSE) alpha.pi_conv = data.frame(Interval = character(0), stat = numeric(0), upper_ci = numeric(0), stringsAsFactors=FALSE) beta.pi_conv = data.frame(Interval = character(0), stat = numeric(0), upper_ci = numeric(0), stringsAsFactors=FALSE) type <- NA if (nchains > 1) { type = "Gelman-Rubin" for (i in 1:raw$nIntervals) { if (pi_mon == 1) { for (b in 1:raw$nBodySys[i]) { g = M_global$GelmanRubin(raw$pi[, i, b, ], nchains) row <- data.frame(Interval = raw$Intervals[i], B = raw$B[i, b], stat = g$psrf[1], upper_ci = g$psrf[2], stringsAsFactors=FALSE) pi_conv = rbind(pi_conv, row) } } } if (alpha_pi_mon == 1) { for (i in 1:raw$nIntervals) { g = M_global$GelmanRubin(raw$alpha.pi[, i, ], nchains) row <- data.frame(Interval = raw$Intervals[i], stat = g$psrf[1], upper_ci = g$psrf[2], stringsAsFactors=FALSE) alpha.pi_conv = rbind(alpha.pi_conv, row) } } if (beta_pi_mon == 1) { for (i in 1:raw$nIntervals) { g = M_global$GelmanRubin(raw$beta.pi[, i, ], nchains) row <- data.frame(Interval = raw$Intervals[i], stat = g$psrf[1], upper_ci = g$psrf[2], stringsAsFactors=FALSE) beta.pi_conv = rbind(beta.pi_conv, row) } } } else { type = "Geweke" for (i in 1:raw$nIntervals) { if (pi_mon == 1) { for (b in 1:raw$nBodySys[i]) { g = M_global$Geweke(raw$pi[1, i, b, ]) row <- data.frame(Interval = raw$Intervals[i], B = raw$B[i, b], stat = g$z, upper_ci = NA, stringsAsFactors=FALSE) pi_conv = rbind(pi_conv, row) } } if (alpha_pi_mon == 1) { g = M_global$Geweke(raw$alpha.pi[1, i, ]) row <- data.frame(Interval = raw$Intervals[i], stat = g$z, upper_ci = NA, stringsAsFactors=FALSE) alpha.pi_conv = rbind(alpha.pi_conv, row) } if (beta_pi_mon == 1) { g = M_global$Geweke(raw$beta.pi[1, i, ]) row <- data.frame(Interval = raw$Intervals[i], stat = g$z, upper_ci = NA, stringsAsFactors=FALSE) beta.pi_conv = rbind(beta.pi_conv, row) } } } theta_acc = data.frame(chain = numeric(0), Interval = character(0), B = character(0), AE = character(0), rate = numeric(0), stringsAsFactors=FALSE) alpha.pi_acc = data.frame(chain = numeric(0), Interval = character(0), rate = numeric(0), stringsAsFactors=FALSE) beta.pi_acc = data.frame(chain = numeric(0), Interval = character(0), rate = numeric(0), stringsAsFactors=FALSE) if (theta_mon == 1) { for (i in 1:raw$nIntervals) { for (b in 1:raw$nBodySys[i]) { for (j in 1:raw$nAE[i, b]) { for (c in 1:nchains) { rate <- raw$theta_acc[c, i, b, j]/raw$iter row <- data.frame(chain = c, Interval = raw$Intervals[i], B = raw$B[i, b], AE = raw$AE[i, b,j], rate = rate, stringsAsFactors=FALSE) theta_acc = rbind(theta_acc, row) } } } } } if (raw$sim_type == "MH") { for (i in 1:raw$nIntervals) { for (c in 1:nchains) { if (alpha_pi_mon == 1) { rate <- raw$alpha.pi_acc[c, i]/raw$iter row <- data.frame(chain = c, Interval = raw$Intervals[i], rate = rate, stringsAsFactors=FALSE) alpha.pi_acc = rbind(alpha.pi_acc, row) } if (beta_pi_mon == 1) { rate <- raw$beta.pi_acc[c, i]/raw$iter row <- data.frame(chain = c, Interval = raw$Intervals[i], rate = rate, stringsAsFactors=FALSE) beta.pi_acc = rbind(beta.pi_acc, row) } } } } rownames(theta_acc) <- NULL rownames(pi_conv) <- NULL rownames(alpha.pi_conv) <- NULL rownames(beta.pi_conv) <- NULL rownames(alpha.pi_acc) <- NULL rownames(beta.pi_acc) <- NULL c_base$theta_acc = theta_acc c_BB = list(pi.conv.diag = pi_conv, alpha.pi.conv.diag = alpha.pi_conv, beta.pi.conv.diag = beta.pi_conv, alpha.pi_acc = alpha.pi_acc, beta.pi_acc = beta.pi_acc) conv.diag = c(c_base, c_BB) attr(conv.diag, "model") = attr(raw, "model") return(conv.diag) } c212.interim.BB.indep.print.convergence.summary <- function(conv) { if (is.null(conv)) { print("NULL conv data") return(NULL) } monitor = conv$monitor theta_mon = monitor[monitor$variable == "theta",]$monitor gamma_mon = monitor[monitor$variable == "gamma",]$monitor mu.theta_mon = monitor[monitor$variable == "mu.theta",]$monitor mu.gamma_mon = monitor[monitor$variable == "mu.gamma",]$monitor sigma2.theta_mon = monitor[monitor$variable == "sigma2.theta",]$monitor sigma2.gamma_mon = monitor[monitor$variable == "sigma2.gamma",]$monitor mu.theta.0_mon = monitor[monitor$variable == "mu.theta.0",]$monitor mu.gamma.0_mon = monitor[monitor$variable == "mu.gamma.0",]$monitor tau2.theta.0_mon = monitor[monitor$variable == "tau2.theta.0",]$monitor tau2.gamma.0_mon = monitor[monitor$variable == "tau2.gamma.0",]$monitor pi_mon = monitor[monitor$variable == "pi",]$monitor alpha_pi_mon = monitor[monitor$variable == "alpha.pi",]$monitor beta_pi_mon = monitor[monitor$variable == "beta.pi",]$monitor model = attr(conv, "model") if (is.null(model)) { print("Convergence model attribute missing") return(NULL) } if (gamma_mon == 1 && !("gamma.conv.diag" %in% names(conv))) { print("Missing gamma.conv.diag data") return(NULL) } if (theta_mon == 1 && !("theta.conv.diag" %in% names(conv))) { print("Missing theta.conv.diag data") return(NULL) } if (mu.gamma_mon == 1 && !("mu.gamma.conv.diag" %in% names(conv))) { print("Missing mu.gamma.conv.diag data") return(NULL) } if (mu.theta_mon == 1 && !("mu.theta.conv.diag" %in% names(conv))) { print("Missing mu.theta.conv.diag data") return(NULL) } if (sigma2.gamma_mon == 1 && !("sigma2.gamma.conv.diag" %in% names(conv))) { print("Missing sigma2.gamma.conv.diag data") return(NULL) } if (sigma2.theta_mon == 1 && !("sigma2.theta.conv.diag" %in% names(conv))) { print("Missing sigma2.theta.conv.diag data") return(NULL) } if (mu.gamma.0_mon == 1 && !("mu.gamma.0.conv.diag" %in% names(conv))) { print("Missing mu.gamma.0.conv.diag data") return(NULL) } if (mu.theta.0_mon == 1 && !("mu.theta.0.conv.diag" %in% names(conv))) { print("Missing mu.theta.0.conv.diag data") return(NULL) } if (tau2.gamma.0_mon== 1 && !("tau2.gamma.0.conv.diag" %in% names(conv))) { print("Missing tau2.gamma.0.conv.diag data") return(NULL) } if (tau2.theta.0_mon == 1 && !("tau2.theta.0.conv.diag" %in% names(conv))) { print("Missing tau2.theta.0.conv.diag data") return(NULL) } if (gamma_mon == 1 && !("gamma_acc" %in% names(conv))) { print("Missing gamma_acc data") return(NULL) } if (theta_mon == 1 && !("theta_acc" %in% names(conv))) { print("Missing theta_acc data") return(NULL) } if (pi_mon == 1 && !("pi.conv.diag" %in% names(conv))) { print("Missing pi.conv.diag data") return(NULL) } if (alpha_pi_mon == 1 && !("alpha.pi.conv.diag" %in% names(conv))) { print("Missing alpha.pi.conv.diag data") return(NULL) } if (beta_pi_mon == 1 && !("beta.pi.conv.diag" %in% names(conv))) { print("Missing beta.pi.conv.diag data") return(NULL) } if (alpha_pi_mon == 1 && !("alpha.pi_acc" %in% names(conv))) { print("Missing alpha.pi_acc data") return(NULL) } if (beta_pi_mon == 1 && !("beta.pi_acc" %in% names(conv))) { print("Missing beta.pi_acc data") return(NULL) } cat(sprintf("Summary Convergence Diagnostics:\n")) cat(sprintf("================================\n")) if (conv$type == "Gelman-Rubin") { if (theta_mon == 1) { cat(sprintf("theta:\n")) cat(sprintf("------\n")) max_t = head(conv$theta.conv.diag[conv$theta.conv.diag$stat == max(conv$theta.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Max Gelman-Rubin diagnostic (%s %s %s): %0.6f\n", max_t$Interval, max_t$B, max_t$AE, max_t$stat)) min_t = head(conv$theta.conv.diag[conv$theta.conv.diag$stat == min(conv$theta.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Min Gelman-Rubin diagnostic (%s, %s %s): %0.6f\n", min_t$Interval, min_t$B, min_t$AE, min_t$stat)) } if (gamma_mon == 1) { cat(sprintf("gamma:\n")) cat(sprintf("------\n")) max_t = head(conv$gamma.conv.diag[conv$gamma.conv.diag$stat == max(conv$gamma.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Max Gelman-Rubin diagnostic (%s %s %s): %0.6f\n", max_t$Interval, max_t$B, max_t$AE, max_t$stat)) min_t = head(conv$gamma.conv.diag[conv$gamma.conv.diag$stat == min(conv$gamma.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Min Gelman-Rubin diagnostic (%s %s %s): %0.6f\n", min_t$Interval, min_t$B, min_t$AE, min_t$stat)) } if (mu.gamma_mon == 1) { cat(sprintf("mu.gamma:\n")) cat(sprintf("---------\n")) max_t = head(conv$mu.gamma.conv.diag[conv$mu.gamma.conv.diag$stat == max(conv$mu.gamma.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Max Gelman-Rubin diagnostic (%s %s): %0.6f\n", max_t$Interval, max_t$B, max_t$stat)) min_t = head(conv$mu.gamma.conv.diag[conv$mu.gamma.conv.diag$stat == min(conv$mu.gamma.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Min Gelman-Rubin diagnostic (%s %s): %0.6f\n", min_t$Interval, min_t$B, min_t$stat)) } if (mu.theta_mon == 1) { cat(sprintf("mu.theta:\n")) cat(sprintf("---------\n")) max_t = head(conv$mu.theta.conv.diag[conv$mu.theta.conv.diag$stat == max(conv$mu.theta.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Max Gelman-Rubin diagnostic (%s %s): %0.6f\n", max_t$Interval, max_t$B, max_t$stat)) min_t = head(conv$mu.theta.conv.diag[conv$mu.theta.conv.diag$stat == min(conv$mu.theta.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Min Gelman-Rubin diagnostic (%s %s): %0.6f\n", min_t$Interval, min_t$B, min_t$stat)) } if (sigma2.gamma_mon == 1) { cat(sprintf("sigma2.gamma:\n")) cat(sprintf("-------------\n")) max_t = head(conv$sigma2.gamma.conv.diag[conv$sigma2.gamma.conv.diag$stat == max(conv$sigma2.gamma.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Max Gelman-Rubin diagnostic (%s %s): %0.6f\n", max_t$Interval, max_t$B, max_t$stat)) min_t = head(conv$sigma2.gamma.conv.diag[conv$sigma2.gamma.conv.diag$stat == min(conv$sigma2.gamma.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Min Gelman-Rubin diagnostic (%s %s): %0.6f\n", min_t$Interval, min_t$B, min_t$stat)) } if (sigma2.theta_mon == 1) { cat(sprintf("sigma2.theta:\n")) cat(sprintf("-------------\n")) max_t = head(conv$sigma2.theta.conv.diag[conv$sigma2.theta.conv.diag$stat == max(conv$sigma2.theta.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Max Gelman-Rubin diagnostic (%s %s): %0.6f\n", max_t$Interval, max_t$B, max_t$stat)) min_t = head(conv$sigma2.theta.conv.diag[conv$sigma2.theta.conv.diag$stat == min(conv$sigma2.theta.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Min Gelman-Rubin diagnostic (%s %s): %0.6f\n", min_t$Interval, min_t$B, min_t$stat)) } if (pi_mon == 1) { cat(sprintf("pi:\n")) cat(sprintf("---\n")) max_t = head(conv$pi.conv.diag[conv$pi.conv.diag$stat == max(conv$pi.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Max Gelman-Rubin diagnostic (%s %s): %0.6f\n", max_t$Interval, max_t$B, max_t$stat)) min_t = head(conv$pi.conv.diag[conv$pi.conv.diag$stat == min(conv$pi.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Min Gelman-Rubin diagnostic (%s %s): %0.6f\n", min_t$Interval, min_t$B, min_t$stat)) } if (mu.gamma.0_mon == 1) { cat(sprintf("mu.gamma.0:\n")) cat(sprintf("-----------\n")) max_t = head(conv$mu.gamma.0.conv.diag[conv$mu.gamma.0.conv.diag$stat == max(conv$mu.gamma.0.conv.diag$stat), ], 1) cat(sprintf("Max Gelman-Rubin diagnostic: (%s) %0.6f\n", max_t$Interval, max_t$stat)) min_t = head(conv$mu.gamma.0.conv.diag[conv$mu.gamma.0.conv.diag$stat == min(conv$mu.gamma.0.conv.diag$stat), ], 1) cat(sprintf("Min Gelman-Rubin diagnostic: (%s) %0.6f\n", min_t$Interval, min_t$stat)) } if (mu.theta.0_mon == 1) { cat(sprintf("mu.theta.0:\n")) cat(sprintf("-----------\n")) max_t = head(conv$mu.theta.0.conv.diag[conv$mu.theta.0.conv.diag$stat == max(conv$mu.theta.0.conv.diag$stat), ], 1) cat(sprintf("Max Gelman-Rubin diagnostic: (%s) %0.6f\n", max_t$Interval, max_t$stat)) min_t = head(conv$mu.theta.0.conv.diag[conv$mu.theta.0.conv.diag$stat == min(conv$mu.theta.0.conv.diag$stat), ], 1) cat(sprintf("Min Gelman-Rubin diagnostic: (%s) %0.6f\n", min_t$Interval, min_t$stat)) } if (tau2.gamma.0_mon == 1) { cat(sprintf("tau2.gamma.0:\n")) cat(sprintf("-------------\n")) max_t = head(conv$tau2.gamma.0.conv.diag[conv$tau2.gamma.0.conv.diag$stat == max(conv$tau2.gamma.0.conv.diag$stat), ], 1) cat(sprintf("Max Gelman-Rubin diagnostic: (%s) %0.6f\n", max_t$Interval, max_t$stat)) min_t = head(conv$tau2.gamma.0.conv.diag[conv$tau2.gamma.0.conv.diag$stat == min(conv$tau2.gamma.0.conv.diag$stat), ], 1) cat(sprintf("Min Gelman-Rubin diagnostic: (%s) %0.6f\n", min_t$Interval, min_t$stat)) } if (tau2.theta.0_mon == 1) { cat(sprintf("tau2.theta.0:\n")) cat(sprintf("-------------\n")) max_t = head(conv$tau2.theta.0.conv.diag[conv$tau2.theta.0.conv.diag$stat == max(conv$tau2.theta.0.conv.diag$stat), ], 1) cat(sprintf("Max Gelman-Rubin diagnostic: (%s) %0.6f\n", max_t$Interval, max_t$stat)) min_t = head(conv$tau2.theta.0.conv.diag[conv$tau2.theta.0.conv.diag$stat == min(conv$tau2.theta.0.conv.diag$stat), ], 1) cat(sprintf("Min Gelman-Rubin diagnostic: (%s) %0.6f\n", min_t$Interval, min_t$stat)) } if (alpha_pi_mon == 1) { cat(sprintf("alpha.pi:\n")) cat(sprintf("----------\n")) max_t = head(conv$alpha.pi.conv.diag[conv$alpha.pi.conv.diag$stat == max(conv$alpha.pi.conv.diag$stat), ], 1) cat(sprintf("Max Gelman-Rubin diagnostic: (%s) %0.6f\n", max_t$Interval, max_t$stat)) min_t = head(conv$alpha.pi.conv.diag[conv$alpha.pi.conv.diag$stat == min(conv$alpha.pi.conv.diag$stat), ], 1) cat(sprintf("Min Gelman-Rubin diagnostic: (%s) %0.6f\n", min_t$Interval, min_t$stat)) } if (beta_pi_mon == 1) { cat(sprintf("beta.pi:\n")) cat(sprintf("--------\n")) max_t = head(conv$beta.pi.conv.diag[conv$beta.pi.conv.diag$stat == max(conv$beta.pi.conv.diag$stat), ], 1) cat(sprintf("Max Gelman-Rubin diagnostic: (%s) %0.6f\n", max_t$Interval, max_t$stat)) min_t = head(conv$beta.pi.conv.diag[conv$beta.pi.conv.diag$stat == min(conv$beta.pi.conv.diag$stat), ], 1) cat(sprintf("Min Gelman-Rubin diagnostic: (%s) %0.6f\n", min_t$Interval, min_t$stat)) } } else { if (theta_mon == 1) { cat(sprintf("theta:\n")) cat(sprintf("------\n")) max_t = head(conv$theta.conv.diag[conv$theta.conv.diag$stat == max(conv$theta.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Max Geweke statistic (%s %s %s): %0.6f (%s)\n", max_t$Interval, max_t$B, max_t$AE, max_t$stat, chk_val(max_t$stat))) min_t = head(conv$theta.conv.diag[conv$theta.conv.diag$stat == min(conv$theta.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Min Geweke statistic (%s %s %s): %0.6f (%s)\n", min_t$Interval, min_t$B, min_t$AE, min_t$stat, chk_val(min_t$stat))) } if (gamma_mon == 1) { cat(sprintf("gamma:\n")) cat(sprintf("------\n")) max_t = head(conv$gamma.conv.diag[conv$gamma.conv.diag$stat == max(conv$gamma.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Max Geweke statistic (%s %s %s): %0.6f (%s)\n", max_t$Interval, max_t$B, max_t$AE, max_t$stat, chk_val(max_t$stat))) min_t = head(conv$gamma.conv.diag[conv$gamma.conv.diag$stat == min(conv$gamma.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Min Geweke statistic (%s %s %s): %0.6f (%s)\n", min_t$Interval, min_t$B, min_t$AE, min_t$stat, chk_val(min_t$stat))) } if (mu.gamma_mon == 1) { cat(sprintf("mu.gamma:\n")) cat(sprintf("---------\n")) max_t = head(conv$mu.gamma.conv.diag[conv$mu.gamma.conv.diag$stat == max(conv$mu.gamma.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Max Geweke statistic (%s %s): %0.6f (%s)\n", max_t$Interval, max_t$B, max_t$stat, chk_val(max_t$stat))) min_t = head(conv$mu.gamma.conv.diag[conv$mu.gamma.conv.diag$stat == min(conv$mu.gamma.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Min Geweke statistic (%s %s): %0.6f (%s)\n", min_t$Interval, min_t$B, min_t$stat, chk_val(min_t$stat))) } if (mu.theta_mon == 1) { cat(sprintf("mu.theta:\n")) cat(sprintf("---------\n")) max_t = head(conv$mu.theta.conv.diag[conv$mu.theta.conv.diag$stat == max(conv$mu.theta.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Max Geweke statistic (%s %s): %0.6f (%s)\n", max_t$Interval, max_t$B, max_t$stat, chk_val(max_t$stat))) min_t = head(conv$mu.theta.conv.diag[conv$mu.theta.conv.diag$stat == min(conv$mu.theta.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Min Geweke statistic (%s %s): %0.6f (%s)\n", min_t$Interval, min_t$B, min_t$stat, chk_val(min_t$stat))) } if (sigma2.gamma_mon == 1) { cat(sprintf("sigma2.gamma:\n")) cat(sprintf("-------------\n")) max_t = head(conv$sigma2.gamma.conv.diag[conv$sigma2.gamma.conv.diag$stat == max(conv$sigma2.gamma.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Max Geweke statistic (%s %s): %0.6f (%s)\n", max_t$Interval, max_t$B, max_t$stat, chk_val(max_t$stat))) min_t = head(conv$sigma2.gamma.conv.diag[conv$sigma2.gamma.conv.diag$stat == min(conv$sigma2.gamma.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Min Geweke statistic (%s %s): %0.6f (%s)\n", min_t$Interval, min_t$B, min_t$stat, chk_val(min_t$stat))) } if (sigma2.theta_mon == 1) { cat(sprintf("sigma2.theta:\n")) cat(sprintf("-------------\n")) max_t = head(conv$sigma2.theta.conv.diag[conv$sigma2.theta.conv.diag$stat == max(conv$sigma2.theta.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Max Geweke statistic (%s %s): %0.6f (%s)\n", max_t$Interval, max_t$B, max_t$stat, chk_val(max_t$stat))) min_t = head(conv$sigma2.theta.conv.diag[conv$sigma2.theta.conv.diag$stat == min(conv$sigma2.theta.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Min Geweke statistic (%s %s): %0.6f (%s)\n", min_t$Interval, min_t$B, min_t$stat, chk_val(min_t$stat))) } if (pi_mon == 1) { cat(sprintf("pi:\n")) cat(sprintf("---\n")) max_t = head(conv$pi.conv.diag[conv$pi.conv.diag$stat == max(conv$pi.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Max Geweke statistic (%s %s): %0.6f (%s)\n", max_t$Interval, max_t$B, max_t$stat, chk_val(max_t$stat))) min_t = head(conv$pi.conv.diag[conv$pi.conv.diag$stat == min(conv$pi.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Min Geweke statistic (%s %s): %0.6f (%s)\n", min_t$Interval, min_t$B, min_t$stat, chk_val(min_t$stat))) } if (mu.gamma.0_mon == 1) { cat(sprintf("mu.gamma.0:\n")) cat(sprintf("-----------\n")) max_t = head(conv$mu.gamma.0.conv.diag[conv$mu.gamma.0.conv.diag$stat == max(conv$mu.gamma.0.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Max Geweke statistic: (%s) %0.6f (%s)\n", max_t$Interval, max_t$stat, chk_val(max_t$stat))) min_t = head(conv$mu.gamma.0.conv.diag[conv$mu.gamma.0.conv.diag$stat == min(conv$mu.gamma.0.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Min Geweke statistic: (%s) %0.6f (%s)\n", min_t$Interval, min_t$stat, chk_val(min_t$stat))) } if (mu.theta.0_mon == 1) { cat(sprintf("mu.theta.0:\n")) cat(sprintf("-----------\n")) max_t = head(conv$mu.theta.0.conv.diag[conv$mu.theta.0.conv.diag$stat == max(conv$mu.theta.0.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Max Geweke statistic: (%s) %0.6f (%s)\n", max_t$Interval, max_t$stat, chk_val(max_t$stat))) min_t = head(conv$mu.theta.0.conv.diag[conv$mu.theta.0.conv.diag$stat == min(conv$mu.theta.0.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Min Geweke statistic: (%s) %0.6f (%s)\n", min_t$Interval, min_t$stat, chk_val(min_t$stat))) } if (tau2.gamma.0_mon == 1) { cat(sprintf("tau2.gamma.0:\n")) cat(sprintf("-------------\n")) max_t = head(conv$tau2.gamma.0.conv.diag[conv$tau2.gamma.0.conv.diag$stat == max(conv$tau2.gamma.0.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Max Geweke statistic: (%s) %0.6f (%s)\n", max_t$Interval, max_t$stat, chk_val(max_t$stat))) min_t = head(conv$tau2.gamma.0.conv.diag[conv$tau2.gamma.0.conv.diag$stat == min(conv$tau2.gamma.0.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Min Geweke statistic: (%s) %0.6f (%s)\n", min_t$Interval, min_t$stat, chk_val(min_t$stat))) } if (tau2.theta.0_mon == 1) { cat(sprintf("tau2.theta.0:\n")) cat(sprintf("-------------\n")) max_t = head(conv$tau2.theta.0.conv.diag[conv$tau2.theta.0.conv.diag$stat == max(conv$tau2.theta.0.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Max Geweke statistic: (%s) %0.6f (%s)\n", max_t$Interval, max_t$stat, chk_val(max_t$stat))) min_t = head(conv$tau2.theta.0.conv.diag[conv$tau2.theta.0.conv.diag$stat == min(conv$tau2.theta.0.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Min Geweke statistic: (%s) %0.6f (%s)\n", min_t$Interval, min_t$stat, chk_val(min_t$stat))) } if (alpha_pi_mon == 1) { cat(sprintf("alpha.pi:\n")) cat(sprintf("----------\n")) max_t = head(conv$alpha.pi.conv.diag[conv$alpha.pi.conv.diag$stat == max(conv$alpha.pi.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Max Geweke statistic: (%s) %0.6f (%s)\n", max_t$Interval, max_t$stat, chk_val(max_t$stat))) min_t = head(conv$alpha.pi.conv.diag[conv$alpha.pi.conv.diag$stat == min(conv$alpha.pi.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Min Geweke statistic: (%s) %0.6f (%s)\n", min_t$Interval, min_t$stat, chk_val(min_t$stat))) } if (beta_pi_mon == 1) { cat(sprintf("beta.pi:\n")) cat(sprintf("----------\n")) max_t = head(conv$beta.pi.conv.diag[conv$beta.pi.conv.diag$stat == max(conv$beta.pi.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Max Geweke statistic: (%s) %0.6f (%s)\n", max_t$Interval, max_t$stat, chk_val(max_t$stat))) min_t = head(conv$beta.pi.conv.diag[conv$beta.pi.conv.diag$stat == min(conv$beta.pi.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Min Geweke statistic: (%s) %0.6f (%s)\n", min_t$Interval, min_t$stat, chk_val(min_t$stat))) } } if (conv$sim_type == "MH") { cat("\nSampling Acceptance Rates:\n") cat("==========================\n") if (theta_mon == 1) { cat("theta:\n") cat("------\n") print(sprintf("Min: %0.6f, Max: %0.6f", min(conv$theta_acc$rate), max(conv$theta_acc$rate))) } if (gamma_mon == 1) { cat("gamma:\n") cat("------\n") print(sprintf("Min: %0.6f, Max: %0.6f", min(conv$gamma_acc$rate), max(conv$gamma_acc$rate))) } if (alpha_pi_mon == 1) { cat("alpha.pi:\n") cat("---------\n") print(sprintf("Min: %0.6f, Max: %0.6f", min(conv$alpha.pi_acc$ratec), max(conv$alpha.pi_acc$ratec))) } if (beta_pi_mon == 1) { cat("beta.pi:\n") cat("--------\n") print(sprintf("Min: %0.6f, Max: %0.6f", min(conv$beta.pi_acc$rate), max(conv$beta.pi_acc$rate))) } } else { cat("\nSampling Acceptance Rates:\n") cat("==========================\n") if (theta_mon == 1) { cat("theta:\n") cat("------\n") print(sprintf("Min: %0.6f, Max: %0.6f", min(conv$theta_acc$rate), max(conv$theta_acc$rate))) } } }
overallcovp1<-function(tfix=2.0,tfix0=1.0,taur=5,u=c(1/taur,1/taur),ut=c(taur/2,taur),pi1=0.5, rate11=c(1,0.5),rate21=rate11,rate31=c(0.7,0.4), rate41=rate21,rate51=rate51,ratec1=c(0.5,0.6), rate10=rate11,rate20=rate10,rate30=rate31, rate40=rate20,rate50=rate20,ratec0=ratec1, tchange=c(0,1),type1=1,type0=1,rp21=0.5,rp20=0.5, eps=1.0e-2,veps=1.0e-2,beta=0,beta0=0){ ratemax<-max(abs(rate11-rate10))+max(abs(rate21-rate20))+max(abs(rate31-rate30))+max(abs(rate41-rate40))+max(abs(rate51-rate50))+max(abs(ratec1-ratec0)) rateb<-max(0.01,min(ratemax,1)) err<-veps/rateb tmax<-max(c(tfix,tchange,taur))+err nr<-length(rate11) tplus<-rep(0,nr) tplus[nr]<-tmax if (nr>1) tplus[-nr]<-tchange[-1] nn<-rep(1,nr) nn[1]<-ceiling((tplus[1]-tchange[1])/err) atchange<-rep(0,nn[1]) atchange<-seq(tchange[1],tplus[1],by=(tplus[1]-tchange[1])/nn[1])[1:nn[1]] if (nr>=2){ for (i in 2:nr){ nn[i]<-ceiling((tplus[i]-tchange[i])/err) atchange<-c(atchange,seq(tchange[i],tplus[i],by=(tplus[i]-tchange[i])/nn[i])[1:nn[i]]) } } atchange1<-sort(unique(c(atchange,tfix,tfix-tfix0),fromLast=T)) aind<-(atchange1[-1]-atchange1[-length(atchange1)]>err/10) ats<-c(0,atchange1[-1][aind==1]) anr<-length(ats)+1 atplus<-rep(0,anr) atplus[anr]<-tmax+0.1*err atplus[-anr]<-ats nplus<-length(atplus) covbeta1<-EA1<-0.0 if (sum((tfix-tfix0)<=atplus & atplus<(tfix-err/10))>0){ ats<-atplus[(tfix-tfix0)<=atplus & atplus<(tfix-err/10)] atsupp<-c(ats,tfix) nsupp<-length(atsupp) BigK1<-pwecxpwuforvar(tfix=tfix,t=atsupp,taur=taur,u=u,ut=ut, rate1=rate11,rate2=rate21,rate3=rate31, rate4=rate41,rate5=rate51,ratec=ratec1, tchange=tchange,type=type1,rp2=rp21,eps=eps) BigK0<-pwecxpwuforvar(tfix=tfix,t=atsupp,taur=taur,u=u,ut=ut, rate1=rate10,rate2=rate20,rate3=rate30, rate4=rate40,rate5=rate50,ratec=ratec0, tchange=tchange,type=type0,rp2=rp20,eps=eps) dk1<-BigK1$f0[-1]-BigK1$f0[-nsupp] dk0<-BigK0$f0[-1]-BigK0$f0[-nsupp] adk1<-(dk1>1.0e-08) adk0<-(dk0>1.0e-08) tk1<-tk0<-atsupp[-nsupp] tk1[adk1==1]<-(BigK1$f1[-1]-BigK1$f1[-nsupp])[adk1==1]/dk1[adk1==1] tk0[adk0==1]<-(BigK0$f1[-1]-BigK0$f1[-nsupp])[adk0==1]/dk0[adk0==1] ST11<-pwecx(t=tk1,rate1=rate11,rate2=rate21,rate3=rate31, rate4=rate41,rate5=rate51,tchange=tchange,type=type1,rp2=rp21,eps=eps)$surv ST10<-pwecx(t=tk1,rate1=rate10,rate2=rate20,rate3=rate30, rate4=rate40,rate5=rate50,tchange=tchange,type=type0,rp2=rp20,eps=eps)$surv SC11<-pwe(t=tk1,rate=ratec1,tchange=tchange)$surv SC10<-pwe(t=tk1,rate=ratec0,tchange=tchange)$surv ST01<-pwecx(t=tk0,rate1=rate11,rate2=rate21,rate3=rate31, rate4=rate41,rate5=rate51,tchange=tchange,type=type1,rp2=rp21,eps=eps)$surv ST00<-pwecx(t=tk0,rate1=rate10,rate2=rate20,rate3=rate30, rate4=rate40,rate5=rate50,tchange=tchange,type=type0,rp2=rp20,eps=eps)$surv SC01<-pwe(t=tk0,rate=ratec1,tchange=tchange)$surv SC00<-pwe(t=tk0,rate=ratec0,tchange=tchange)$surv bb1<-(1-pi1)*ST10*SC10 bb0<-(1-pi1)*ST00*SC00 aa1<-pi1*exp(beta)*ST11*SC11 aa0<-pi1*exp(beta)*ST01*SC01 q1bs<-aa1/(aa1+bb1) q0bs<-aa0/(aa0+bb0) ak1<-innervar(t=tk1-(tfix-tfix0),taur=taur,u=u,ut=ut,pi1=pi1, rate11=rate11,rate21=rate21,rate31=rate31, rate41=rate41,rate51=rate51,ratec1=ratec1, rate10=rate10,rate20=rate20,rate30=rate30, rate40=rate40,rate50=rate50,ratec0=ratec0, tchange=tchange,type1=type1,type0=type0,rp21=rp21,rp20=rp20, eps=eps,veps=veps,beta=beta0) ak0<-innervar(t=tk0-(tfix-tfix0),taur=taur,u=u,ut=ut,pi1=pi1, rate11=rate11,rate21=rate21,rate31=rate31, rate41=rate41,rate51=rate51,ratec1=ratec1, rate10=rate10,rate20=rate20,rate30=rate30, rate40=rate40,rate50=rate50,ratec0=ratec0, tchange=tchange,type1=type1,type0=type0,rp21=rp21,rp20=rp20, eps=eps,veps=veps,beta=beta0) covbeta1<-pi1*sum(q1bs*(1-q1bs)*ak1$qf1*dk1)-(1-pi1)*sum(q0bs^2*ak0$qf1*dk0) covbeta1<-covbeta1-exp(beta0)*pi1*sum((1-q1bs)^2*ak1$qf2*dk1)+exp(beta0)*(1-pi1)*sum(q0bs*(1-q0bs)*ak0$qf2*dk0) EA1<-pi1*sum((1-q1bs)*dk1)-(1-pi1)*sum(q0bs*dk0) } list(covbeta1=covbeta1, EA1=EA1) }
AbForests_RemoveNets<-function(list,opt,distance_mat,tie_flag,weight,N,C,random.seed,alg_opt){ list<-lapply(list, lapply,function(k) { if (length(k)>0){ if(!(is.null(C))){ if(length(k$Seq)<C){ return() } } if(opt=="isotype"){ pre_data<-.PREPROCESSING(k$Seq,k$isotype,distance_mat,NULL) }else{ pre_data<-.PREPROCESSING(k$Seq,k$cluster,distance_mat,NULL) } if(alg_opt=="two-step"){ edgeList<-.FIND_EDGES_v1(pre_data$dist_mat,pre_data$countData) edgeList<-.DELETE_MULTIPLE_PARENTS(edgeList$node_list,edgeList$edges_final,pre_data$dist_mat,pre_data$countData,tie_flag,weight,random.seed) }else{ germline.index<-which(apply(pre_data$countData, 1, function(r) any(grepl("Germline",r)))) adj_mat<-.ADJ_MAT(pre_data$dist_mat) edgeList<-.EDGES(pre_data$dist_mat,adj_mat,germline.index,weight,random.seed) } columns <- grep('Ratio', colnames(pre_data$countData), value=TRUE) values <- lapply(edgeList$node_list, function(x) unlist(pre_data$countData[x,columns])) df_values <- do.call("rbind", values) if(!is.null(N)){ if(nrow(df_values)<N){ return() } } return(k) } }) list<-lapply(list, function(x) Filter(length, x)) if(!(purrr::vec_depth(list)>3)){ list<-lapply(list,function(z) list(z)) } return(list) }
condition_core <- function(i = i, model_i, m_fixed_values) { names_i <- rownames(model_i) n_terms <- nrow(model_i) nCond <- nrow(m_fixed_values) effects <- matrix(NA, nrow = n_terms-1, ncol=7) colnames(effects) <- c("Variable1", "Variable2", "Fixed1", "Fixed2", "Parameter", "Type1", "Type2") names_aux1 <- strsplit(names_i[-1], ":") names_aux2 <- lapply(names_aux1, function(x) gsub("V", "", x)) names_aux3 <- lapply(names_aux2, function(x) { x_out <- rep(NA, length(x)) for(v in 1:length(x)) if(substr(x[v], start = nchar(x[v]), nchar(x[v])) == ".") x_out[v] <- gsub("\\.", "", x[v]) else x_out[v] <- x[v] return(x_out) }) n_var_i <- unlist(lapply(names_aux3, length)) for(q in 1:length(n_var_i)) effects[q, 1:n_var_i[q]] <- as.numeric(unlist(names_aux3[[q]])) for(q in 1:(n_terms-1)) effects[q, 6] <- ifelse(effects[q, 1] == round(effects[q, 1]), 1, 0) for(q in which(n_var_i==2)) effects[q, 7] <- ifelse(effects[q, 2] == round(effects[q, 2]), 1, 0) for(q in 1:(n_terms-1)) for(f in 1:nCond) if(effects[q, 1] == m_fixed_values[f, 1]) effects[q, 3] <- m_fixed_values[f, 2] for(q in which(n_var_i==2)) for(f in 1:nCond) if(effects[q, 2] == m_fixed_values[f, 1]) effects[q, 4] <- m_fixed_values[f, 2] for(q in 1:(n_terms-1)) { if(effects[q, 6] == 0) { var_cat <- strsplit(as.character(effects[q, 1]), "\\.")[[1]] for(f in 1:nCond) if(as.numeric(var_cat[1]) == m_fixed_values[f, 1]) if(as.numeric(var_cat[2]) == m_fixed_values[f, 2]) effects[q, 3] <- 1 else effects[q, 3] <- 0 } } for(q in which(n_var_i==2)) { if(effects[q, 7] == 0) { var_cat <- strsplit(as.character(effects[q, 2]), "\\.")[[1]] for(f in 1:nCond) if(as.numeric(var_cat[1]) == m_fixed_values[f, 1]) if(as.numeric(var_cat[2]) == m_fixed_values[f, 2]) effects[q, 4] <- 1 else effects[q, 4] <- 0 } } effects[, 5] <- model_i[-1, 1] l_cPars <- vector("list", length = n_terms) l_cPars <- lapply(l_cPars, function(x) list() ) if(!i %in% m_fixed_values[, 1]) { l_cPars[[1]][[1]] <- model_i[1, 1] for(q in 1:(n_terms-1)) { if(n_var_i[q] == 1) { if(is.na(effects[q, 3])) { l_cPars[[q+1]][[length(l_cPars[[q+1]])+1]] <- effects[q, 5] } else { l_cPars[[1]][[length(l_cPars[[1]])+1]] <- effects[q, 5] * effects[q, 3] } } if(n_var_i[q] == 2) { ind_spec <- sum(c(is.na(effects[q, 3]), is.na(effects[q, 4]))) if(ind_spec == 2) l_cPars[[q+1]][[length(l_cPars[[q+1]])+1]] <- effects[q, 5] if(ind_spec==1) { ind_specified <- !is.na(c(effects[q, 3], effects[q, 4])) ind_leftover_mainE <- which(effects[n_var_i==1, 1]==effects[q, 1:2][!ind_specified]) l_cPars[[ind_leftover_mainE+1]][[length(l_cPars[[ind_leftover_mainE+1]])+1]] <- effects[q, 5] * effects[q, 3:4][ind_specified] } if(ind_spec == 0) l_cPars[[1]][[length(l_cPars[[1]])+1]] <- effects[q, 5] * effects[q, 3] * effects[q, 4] } } } model_i_new <- matrix(NA, nrow=n_terms, ncol=1) rownames(model_i_new) <- names_i for(q in 1:n_terms) model_i_new[q, 1] <- sum(unlist(l_cPars[[q]])) return(model_i_new) }
msBP.marginalBeta <- function(y, maxS=10, output="tree") { veclen <- 2^(maxS+1) - 1 res <- .C("marginalBeta_C", out= as.double(rep(0, veclen)), as.double(y), as.integer(maxS), PACKAGE = "msBP") if(output=="tree") vec2tree(res$out) else res$out }
funs <- function(.data, fxn, action) { pipe_autoexec(toggle = TRUE) fxn_both <- sprintf("def %s; %s", fxn, action) dots <- comb(tryargs(.data), structure(fxn_both, type = "funs")) structure(list(data = getdata(.data), args = dots), class = "jqr") }
dataset <- data.frame( txt = c("bob","Clare","clare","bob","eve","eve"), num1 = c(3,1,2,0,0,2), num2 = c(1,1,3,0,3,2), etc = c("not","used","as","a","sort","term"), stringsAsFactors = FALSE ) f1 <- sortFrame(dataset, num1) f2 <- sortFrame(dataset, num1, num2) f3 <- sortFrame(dataset, txt)
ssqvis <- function( maxArrivals = Inf, seed = NA, interarrivalType = "M", serviceType = "M", maxTime = Inf, maxDepartures = Inf, maxEventsPerSkyline = 15, saveAllStats = FALSE, saveInterarrivalTimes = FALSE, saveServiceTimes = FALSE, saveWaitTimes = FALSE, saveSojournTimes = FALSE, saveNumInQueue = FALSE, saveNumInSystem = FALSE, saveServerStatus = FALSE, showOutput = TRUE, showSkyline = NULL, showSkylineQueue = TRUE, showSkylineSystem = TRUE, showSkylineServer = TRUE, showTitle = TRUE, jobImage = NA, plotDelay = -1 ) { warnVal <- options("warn") { interarrivalFcn <- NA serviceFcn <- NA checkVal(seed, "i", minex = 1, na = TRUE, null = TRUE) checkVal(maxTime, minex = 0) checkVal(maxArrivals, "i", minex = 0) checkVal(maxDepartures, "i", minex = 0) checkVal(maxEventsPerSkyline, "i", minex = 0) if (maxTime == Inf && maxArrivals == Inf && maxDepartures == Inf) stop("at least one of 'maxTime', 'maxArrivals', or 'maxDepartures' must be < Inf") if (!(interarrivalType %in% c("M","G"))) stop("for animation purposes, interarrivalType must be either 'M' or 'G'") if (!(serviceType %in% c("M","G"))) stop("for animation purposes, serviceType must be either 'M' or 'G'") checkVal(saveAllStats, "l") checkVal(saveInterarrivalTimes, "l") checkVal(saveServiceTimes, "l") checkVal(saveWaitTimes, "l") checkVal(saveSojournTimes, "l") checkVal(saveNumInQueue, "l") checkVal(saveNumInSystem, "l") checkVal(saveServerStatus, "l") if (saveAllStats) { saveInterarrivalTimes <- TRUE saveServiceTimes <- TRUE saveWaitTimes <- TRUE saveSojournTimes <- TRUE saveNumInQueue <- TRUE saveNumInSystem <- TRUE saveServerStatus <- TRUE } checkVal(showOutput, "l") checkVal(showTitle, "l") checkVal(showSkylineSystem, "l") checkVal(showSkylineQueue, "l") checkVal(showSkylineServer, "l") showSkylineResults <- ParseShow( showBools = c(showSkylineSystem, showSkylineQueue, showSkylineServer), show = showSkyline, ignoreBools = missing(showSkylineSystem) && missing(showSkylineQueue) && missing(showSkylineServer) ) showSkylineSystem <- showSkylineResults[1] showSkylineQueue <- showSkylineResults[2] showSkylineServer <- showSkylineResults[3] if (!is.na(jobImage) && !is.character(jobImage)) stop("'jobImage' must be a local link or URL to an image (or a vector of such)") if (!isValNum(plotDelay) || (plotDelay < 0 && plotDelay != -1)) stop("'plotDelay' must be a numeric value (in secs) >= 0 or -1 (interactive mode)") endCriteria <- list(ARRIVALS = 1, DEPARTURES = 2) endValue <- max(if (is.infinite(maxArrivals)) -1 else maxArrivals, if (is.infinite(maxDepartures)) -1 else maxDepartures, if (is.infinite(maxTime)) -1 else maxTime) endType <- if (endValue == maxArrivals || endValue == maxTime) endCriteria$ARRIVALS else if (endValue == maxDepartures) endCriteria$DEPARTURES } numServers <- 1 if (typeof(interarrivalFcn) != "closure") { fcnInfo <- GetDefaultDistroFcn(interarrivalType, isArrival = TRUE, asList = TRUE) interarrivalFcn <- fcnInfo$fcn arrivalNotation <- fcnInfo$notation } else { interarrivalFcn <- ParseDistroFcn(interarrivalFcn, asList = TRUE) if (is.na(interarrivalFcn)) stop("Error: custom distributions not supported for ssqvis") arrivalNotation <- GetDistroNotation(interarrivalFcn) } if (typeof(serviceFcn) != "closure") { fcnInfo <- GetDefaultDistroFcn(serviceType, isArrival = FALSE, asList = TRUE) serviceFcn <- fcnInfo$fcn serviceNotation <- fcnInfo$notation } else { serviceFcn <- ParseDistroFcn(serviceFcn, asList = TRUE) if (is.na(serviceFcn)) stop("Error: custom distributions not supported for ssqvis") serviceNotation <- GetDistroNotation(serviceFcn) } GetPic <- function(i) return(NA) if (!requireNamespace("magick", quietly = TRUE)) { message("Package \"magick\" needed for image inclusion to work. ", "Defaulting from using images.", call. = FALSE) } else if (!is.na(jobImage[1])) { num.jobs <- if (maxArrivals < Inf) maxArrivals+1 else 100 pics <- lapply(jobImage, function(p) as.raster(magick::image_scale(magick::image_read(p), "80"))) if (length(jobImage > 2)) { pictype <- sample(1:length(pics), num.jobs, replace = TRUE) GetPic <- function(i) return(pics[[pictype[i]]]) } else { GetPic <- function(i) return(pics) } } PauseCurrPlot <- NULL pauseData <- NULL if (maxArrivals < Inf) { paramsText <- paste(" (", if (maxArrivals < Inf) paste("N = ", maxArrivals, ")", sep = ""), sep = "") } else { paramsText <- "" } titleText <- bquote( .(arrivalNotation) ~ "/" ~ .(serviceNotation) ~ "/" ~ .(numServers) ~ .(paramsText)) sf_ratio = c(1,2) fs <- function(n) ScaleFont(n, f = 3, r = sf_ratio) arrivalsCal <- list(type = 'a', time = Inf, state = 0) serverCal <- list(type = 's', time = 0, state = 0) DrawCol <- NULL calendarPlotRange <- c( 10, 190, 135, 190) queuePlotRange <- c( 10, 190, 88, 130) skylinePlotRange <- c( 18, 120, 18, 78) statsPlotRange <- c( 130, 181, 18, 78) upArrowPlotRange <- c( 65, 70, 126, 136) calendarPlotBGColor <- rgb(0.95, 0.95, 0.95) getNextEvent <- function() { minTime <- Inf nextEvent <- NULL if (arrivalsCal$state == 1 && arrivalsCal$time < minTime) { minTime <- arrivalsCal$time nextEvent <- arrivalsCal } if (serverCal$state == 1 && serverCal$time < minTime) { minTime <- serverCal$time nextEvent <- serverCal } return (nextEvent) } DrawJob <- NA GetJobHalfWidth <- NA GetJobHalfHeight <- NA initDrawJob <- FALSE SSQVals <- list( time = 0, idsInSystem = c(), idJustRejected = 0, idNextToEnter = 1, idJustServed = 0, currentProgress = 0, numRejects = 0, serviceTime = NA, interarrivalTime = NA, arrivalTime = NA, completionTime = NA ) DrawCurrQueue <- function(time, idsInSystem, idJustRejected, idNextToEnter, idJustServed, currentProgress, numRejects, interarrivalTime, arrivalTime, serviceTime, completionTime, forceDraw = FALSE ) { if (missing(time)) time <- SSQVals[["time"]] if (missing(idsInSystem)) idsInSystem <- SSQVals[["idsInSystem"]] if (missing(idJustRejected)) idJustRejected <- SSQVals[["idJustRejected"]] if (missing(idNextToEnter)) idNextToEnter <- SSQVals[["idNextToEnter"]] if (missing(idJustServed)) idJustServed <- SSQVals[["idJustServed"]] if (missing(currentProgress)) currentProgress <- SSQVals[["currentProgress"]] if (missing(numRejects)) numRejects <- SSQVals[["numRejects"]] if (missing(interarrivalTime)) interarrivalTime <- SSQVals[["interarrivalTime"]] if (missing(arrivalTime)) arrivalTime <- SSQVals[["arrivalTime"]] if (missing(serviceTime)) serviceTime <- SSQVals[["serviceTime"]] if (missing(completionTime)) completionTime <- SSQVals[["completionTime"]] DrawQueueComponents(time = time, idsInSystem = idsInSystem, idJustRejected = idJustRejected, idNextToEnter = idNextToEnter, idJustServed = idJustServed, currentProgress = currentProgress, numRejects = numRejects, interarrivalTime = interarrivalTime, arrivalTime = arrivalTime, serviceTime = serviceTime, completionTime = completionTime, forceDraw = forceDraw ) TogglePlot(upArrowPlotRange) Arrows(100, 0, 100, 150) ScalePlots(dims = c(0, 200, 0, 200)) } setDrawCurrQueue <- function(time, idsInSystem, idJustRejected, idNextToEnter, idJustServed, currentProgress, numRejects, interarrivalTime, arrivalTime, serviceTime, completionTime, shiftInQueue = FALSE, shiftOutServer = FALSE ) { drawPlot <- FALSE if (!missing(time)) { SSQVals[["time"]] <<- time; drawPlot <- TRUE } if (!missing(idsInSystem)) { SSQVals[["idsInSystem"]] <<- idsInSystem; drawPlot <- TRUE } if (!missing(idJustRejected)) { SSQVals[["idJustRejected"]] <<- idJustRejected; drawPlot <- TRUE } if (!missing(idNextToEnter)) { SSQVals[["idNextToEnter"]] <<- idNextToEnter; drawPlot <- TRUE } if (!missing(idJustServed)) { SSQVals[["idJustServed"]] <<- idJustServed; drawPlot <- TRUE } if (!missing(currentProgress)) { SSQVals[["currentProgress"]] <<- currentProgress; drawPlot <- TRUE } if (!missing(numRejects)) { SSQVals[["numRejects"]] <<- numRejects; drawPlot <- TRUE } if (!missing(interarrivalTime)) { SSQVals[["interarrivalTime"]] <<- interarrivalTime; drawPlot <- TRUE } if (!missing(arrivalTime)) { SSQVals[["arrivalTime"]] <<- arrivalTime; drawPlot <- TRUE } if (!missing(serviceTime)) { SSQVals[["serviceTime"]] <<- serviceTime; drawPlot <- TRUE } if (!missing(completionTime)) { SSQVals[["completionTime"]] <<- completionTime; drawPlot <- TRUE } if (shiftInQueue) { SSQVals[["idsInSystem"]] <<- c(SSQVals[["idsInSystem"]], SSQVals[["idNextToEnter"]]) SSQVals[["idNextToEnter"]] <<- SSQVals[["idNextToEnter"]] + 1 drawPlot <- TRUE } if (shiftOutServer) { SSQVals[["idJustServed"]] <<- SSQVals[["idsInSystem"]][1] SSQVals[["idsInSystem"]] <<- SSQVals[["idsInSystem"]][-1] drawPlot <- TRUE } return(drawPlot) } DrawQueueComponents <- function(time, idsInSystem, idJustRejected = 0, idNextToEnter = 0, idJustServed = 0, currentProgress, numRejects = 0, interarrivalTime, arrivalTime, serviceTime, completionTime, forceDraw = FALSE ) { if (pauseData$plotDelay == 0 && !forceDraw) return() if (pauseData$plotDelay == -2) return() if (!initDrawJob) { initDrawJob <<- TRUE hasImg <- !is.na(jobImage[1]) if (hasImg) { jtcol <- "red" GetJobHalfWidth <<- function(i) 6 GetJobHalfHeight <<- function(i) 25 } else { jtcol <- "white" GetJobHalfWidth <<- function(i) max(6, 2 * nchar(i, "width")) GetJobHalfHeight <<- function(i) ScaleFont(250) if (Sys.getenv("RSTUDIO") == 1) { GetJobHalfHeight <<- function(i) ScaleFont(180) } } DrawJob <<- function(i, midWidth = 10, midHeight = 100, textXDisplace = 0, textYDisplace = 0, bg, size = 15) { if (!hasImg) textXDisplace <- textYDisplace <- 0 else bg <- NA TextBox(i, midWidth, midHeight, GetJobHalfWidth(i), GetJobHalfHeight(i), bg = bg, col = jtcol, img = GetPic(i), txd = textXDisplace, tyd = textYDisplace, size = size) } } par(mfrow = c(1, 1), mar = c(0, 0, 0, 0), new = TRUE) { NewPlot() TogglePlot(queuePlotRange) DrawBorder("grey", "white") } size12_ <- if (Sys.getenv("RSTUDIO") == 1) fs(6) else fs(12) size15_ <- if (Sys.getenv("RSTUDIO") == 1) fs(7) else fs(15) size18_ <- if (Sys.getenv("RSTUDIO") == 1) fs(8) else fs(18) { TextBox(paste("System Clock: t =", pround(time)), 45, 170, 25, size = size18_) { segments (30, c(73, 127), x1 = 128, lwd = 2) segments (128, c(73, 127), y1 = c(80, 120), lwd = 2) } { f.svrColor <- simcolors$busySvr f.svcText <- if (length(serviceTime) == 0 || is.na(serviceTime)) bquote(s[.(idsInSystem[1])] == ...) else if (serviceTime <= 0) bquote(s[.(idsInSystem[1])] == .(sym$infinity)) else bquote(s[.(idsInSystem[1])] == .(pround(serviceTime))) f.cmpText <- if (length(completionTime) == 0 || is.na(completionTime)) bquote(c[.(idsInSystem[1])] == ...) else if (completionTime <= 0) bquote(c[.(idsInSystem[1])] == .(sym$infinity)) else bquote(c[.(idsInSystem[1])] == .(pround(completionTime))) if (length(serviceTime) == 0 || is.na(serviceTime) || length(completionTime) == 0 || is.na(completionTime)) f.svrColor <- simcolors$pendSvr if (length(idsInSystem) == 0) { f.svrColor <- simcolors$idleSvr f.svcText <- "idle" f.cmpText <- "" } roundrect(c(150, 100), radx = 15, rady = 50, rx = 5, col = f.svrColor) TextBox(f.svcText, 150, 130, 20, size = size12_) TextBox(f.cmpText, 150, 65, 20, size = size12_) if (length(idsInSystem) > 0) DrawJob(idsInSystem[1], midWidth = 150, midHeight = 100, textXDisplace = 1.3, bg = simcolors$svgJob, size = size15_) } { boxhw_ <- if (Sys.getenv("RSTUDIO") == 1) 15 else 12 TextBox(text = "", mw = 12, mh = 100, hw = boxhw_, hh = 50, bg = simcolors$arr) Arrows( 5, 100, 25, 100) Arrows(170, 100, 190, 100) if (idNextToEnter > 0) { DrawJob(idNextToEnter, midWidth = 10, midHeight = 100, textXDisplace = 1.3, bg = simcolors$inqJob, size = size15_) f.iarText <- if (is.na(interarrivalTime)) bquote(r[.(idNextToEnter)] == ...) else bquote(r[.(idNextToEnter)] == .(pround(interarrivalTime))) f.arrText <- if (is.na(arrivalTime)) bquote(a[.(idNextToEnter)] == ...) else bquote(a[.(idNextToEnter)] == .(pround(arrivalTime))) fsize <- if (is.na(interarrivalTime)) fs(10) else fs(10 - log10(arrivalTime)) if (Sys.getenv("RSTUDIO") == 1) fsize <- if (is.na(interarrivalTime)) fs(6) else fs(5) TextBox(f.iarText, mw = 12, mh = 131, hw = boxhw_, size = fsize) TextBox(f.arrText, mw = 12, mh = 65, hw = boxhw_, size = fsize) } if (idJustServed > 0) { DrawJob(idJustServed, midWidth = 178, midHeight = 100, textYDisplace = 1.6, bg = simcolors$svdJob, size = size15_) } } { f.phh <- if (Sys.getenv("RSTUDIO") == 1) ScaleFont(225) else ScaleFont(300) barmh_ <- if (Sys.getenv("RSTUDIO") == 1) 20 else 25 rect(0, barmh_ - f.phh, 200, barmh_ + f.phh, col = simcolors$progbar[1]) rect(0, barmh_ - f.phh, 200 * currentProgress, barmh_ + f.phh, col = simcolors$progbar[2]) f.ptext <- paste(sep = "", round(currentProgress * 100), "% Completed", if (numRejects > 0) paste(" (", numRejects, " Rejected)", sep = "")) TextBox (f.ptext, mw = 100, mh = barmh_, hw = 100, hh = f.phh, col = simcolors$progtxt, size = size15_) } } if (length(idsInSystem) > 1) { f.lastjob <- idsInSystem[length(idsInSystem)] f.numslots <- max(3, 7 - floor(log10(f.lastjob))) es <- function(n) return(134 - 100 * (n - 1)/f.numslots) f.peakindex <- min(f.numslots, length(idsInSystem)) for (i in 2:f.peakindex) { if (i == f.numslots - 1 && length(idsInSystem) > f.numslots) points( x = es(f.numslots - 1) + 3 * c(-1,0,1), y = c(100,100,100), cex = 0.5, col = "black" ) else if (i == f.numslots) DrawJob(f.lastjob, midWidth = es(i), midHeight = 100, textYDisplace = -1.6, bg = simcolors$inqJob, size = size15_) else DrawJob(idsInSystem[i], midWidth = es(i), midHeight = 100, textYDisplace = -1.6, bg = simcolors$inqJob, size = size15_) } } } PlotInitSkyline <- function (xRange = c(0,1), yRange = c(0,1)) { skybgRange <- skylinePlotRange + c(-5, 5, 0, 5) canShow <- c(showSkylineSystem, showSkylineQueue, showSkylineServer) ScalePlots(skylinePlotRange) TogglePlot(skybgRange) if (Sys.getenv("RSTUDIO") == 1) { DrawBorder(br = "grey", col = "white", xLowerLeft = -5) } else { DrawBorder(br = "grey", col = "white") } TextBox("t", 194, 34, 5, 5) TogglePlot(skylinePlotRange, initPlot = FALSE, mar = c(1,1,1,1)) plot(NA, NA, xlim = xRange, ylim = yRange, xaxt = "n", yaxt = "n", xlab = "", ylab = "", bty = "n", las = 1, type = "s") fontScale <- if (Sys.getenv("RSTUDIO") == 1) ScaleFont(10) else ScaleFont(15) if (sum(canShow) > 0) { legend("top", c("System", "Queue", "Server", "Avg")[canShow > 0], lty = c(canShow[canShow > 0], 2), col = simcolors$sky[c(which(canShow > 0), 1)], cex = fontScale, x.intersp = 0.5, horiz = TRUE) } title(paste("Number in System and In Queue"), cex.main = 0.975) } PlotSkyline <- function(times, numsInSystem, numsInQueue, numsInServer, rangeForPlotting, entireRange, forceDraw = FALSE) { rangePlot <- rangeForPlotting rangeAll <- entireRange yminratio <- (-0.4)/ScaleFont(15) if (length(rangeAll) < 2) { PlotInitSkyline(c(0, 1), c(yminratio, 1.5)) axis(1, 0:1, line = -2, cex.axis = ScaleFont(15)) axis(2, 0:1, line = 0, tck = -0.02, mgp = c(3,0.5,0), cex.axis = ScaleFont(15), las = 1) return() } if (length(rangePlot) > 1 && length(rangeAll) > 1) { rangePlot[2] <- max(which(!is.na(numsInSystem))) rangeAll[2] <- max(which(!is.na(numsInSystem))) rangePlot <- rangePlot[1]:rangePlot[2] rangeAll <- rangeAll [1]:rangeAll [2] } timesSub <- times[rangePlot] numsSub <- numsInSystem[rangePlot] numsQSub <- numsInQueue[rangePlot] numsSSub <- numsInServer[rangePlot] maxTime <- timesSub[length(timesSub)] minTime <- timesSub[1] xRange <- c(minTime, maxTime) yRange <- c(yminratio, 1.5) * max(numsSub) PlotInitSkyline(xRange, yRange) if (showSkylineSystem) lines(timesSub, numsSub, type = "s", col = simcolors$sky[1], lwd = 1.25) if (showSkylineQueue) lines(timesSub, numsQSub, type = "s", col = simcolors$sky[2]) if (showSkylineServer) lines(timesSub, numsSSub, type = "s", col = simcolors$sky[3], lwd = 0.75) xlabs <- pretty(c(minTime, maxTime)) ylabs <- 0:max(numsSub) if (ylabs[length(ylabs)] > 5) ylabs <- pretty(ylabs) axis(1, xlabs, line = -2, cex.axis = ScaleFont(15)) axis(2, ylabs, line = 0, tck = -0.02, mgp = c(3,0.5,0), cex.axis = ScaleFont(15), las = 1) if (length(times[!is.na(times)]) > 1) { if (showSkylineSystem) segments( xRange[1], meanTPS(times[rangeAll], numsInSystem[rangeAll]), xRange[2], lty = "dashed", col = simcolors$sky[1]) if (showSkylineQueue) segments( xRange[1], meanTPS(times[rangeAll], numsInQueue[rangeAll]), xRange[2], lty = "dashed", col = simcolors$sky[2]) if (showSkylineServer) segments( xRange[1], meanTPS(times[rangeAll], numsInServer[rangeAll]), xRange[2], lty = "dashed", col = simcolors$sky[3]) } } calendar_xRange <- calendarPlotRange[2] - calendarPlotRange[1] calendar_yRange <- calendarPlotRange[4] - calendarPlotRange[3] stats_yRange <- statsPlotRange[4] - statsPlotRange[3] chyronRange <- calendarPlotRange + c(0, 0, calendar_yRange - 6, 0) box1Range <- calendarPlotRange + c(0.01 * calendar_xRange, -0.75 * calendar_xRange, 0, -5) box2Range <- calendarPlotRange + c(0.25 * calendar_xRange, -0.24 * calendar_xRange, 0, -5) box3Range <- calendarPlotRange + c(0.73 * calendar_xRange, -0.04 * calendar_xRange, 0, -5) box2PlotRange <- box2Range + c(10, -5, 20, -10) box2TimeRange <- box2Range + c(10, -5, 10, 0) box2TimeRange[4] <- box2TimeRange[3] + 10 statsRange <- statsPlotRange + c(-5, 5, 0, 5) tpsStatsRange <- statsPlotRange + c(0, 0, 5 + stats_yRange * ( 0.48), 0) booStatsRange <- statsPlotRange + c(0, 0, 5, stats_yRange * (-0.44)) chyronSize_ <- if (Sys.getenv("RSTUDIO") == 1) fs(10) else fs(18) SetChyron <- function(text) { TogglePlot(chyronRange) TextBox(text, 100, 100, 100, 100, bg = "grey22", col = "white", font = 2, size = chyronSize_) } DrawEmptyIDF <- function() { TogglePlot(calendarPlotRange + c(0, 0, 0, -4.5)) DrawBorder(calendarPlotBGColor, calendarPlotBGColor) TogglePlot(box2PlotRange + c(-10, 10, -6, 6)) DrawBorder("grey") size_ <- if (Sys.getenv("RSTUDIO") == 1) fs(12) else fs(20) TextBox("No Active \nGeneration", 100, 100, 100, 100, size = size_) } DrawIDF <- function(u, x = NA, gxRange, gxExact, gyExact, isArrival = FALSE) { timeMax <- gxRange[2] xWidth <- diff(gxRange) gyRange <- if (u > 0.1) c(-0.05,1) else c(-0.2,1) f.pcol <- if (isArrival) simcolors$arr else simcolors$svc f.xlab <- if (isArrival) "r" else "s" TogglePlot(box2PlotRange, initPlot = FALSE) plot(NA, NA, xlim = gxRange, ylim = gyRange, xaxt = "n", yaxt = "n", bty = "n", xlab = "") if (is.na(x)) { axis(side = 1, at = pretty(c(0, timeMax)), lwd = 0, lwd.ticks = 1, labels = TRUE, padj = -0.5/ScaleFont(15), cex.axis = ScaleFont(15)) axis(side = 1, at = pretty(c(0, timeMax)), labels = FALSE, tcl = 0, padj = -0.5, cex.axis = ScaleFont(15)) text(timeMax*1.08, gyRange[1] - 0.05, f.xlab, cex = ScaleFont(15), xpd = NA) axis(side = 2, at = c(0, 0.25, 0.5, 0.75, 1), las = 1, cex.axis = ScaleFont(15)) } else { segments(0, u, min(x, timeMax), u, lty = "dashed", lwd = 1, col = "red") if (x < timeMax) segments(x, 0, x, u, lty = "dashed", lwd = 1, col = "red") } DrawPoint(-xWidth/55, u, simcolors$u, cex = ScaleFont(25)) if (!is.na(x) && x < timeMax) DrawPoint(x, if (gyRange[1] == -0.05) -0.02 else -0.15, f.pcol, cex = ScaleFont(25)) lines(gxExact, gyExact, col = f.pcol, lwd = 2) } DrawTimelineComponents <- function(time, maxTime, arrivalTime = NA, completionTime = NA, oldTimes = NA, newTime = NA, inversionLine = TRUE ) { TogglePlot(box2TimeRange + c(-5, 11, -6.5, -6.5)) DrawBorder(NA, calendarPlotBGColor) maxX <- time + maxTime TogglePlot(box2TimeRange, initPlot = FALSE) plot(NA, NA, xlim = c(time, maxX), ylim = c(0, 1), bty = "n", xaxt = "n", yaxt = "n") axis(side = 1, at = pround(time + pretty(c(0, maxTime))), lwd = 0, lwd.ticks = 1, labels = TRUE, padj = -0.5/ScaleFont(15), cex.axis = ScaleFont(15)) axis(side = 1, at = pround(time + pretty(c(0, maxTime + 0.25))), labels = FALSE, tcl = 0, padj = -0.5, cex.axis = ScaleFont(15)) if (inversionLine) { segments(newTime, 0, newTime, 1, lty = "dashed", lwd = 1, col = "red") } showDots <- FALSE for (i in 1:length(oldTimes)) { if (isValNum(oldTimes[i]) && oldTimes[i] == Inf) oldTimes <- NA else if (isValNum(oldTimes[i]) && oldTimes[i] > maxX) { oldTimes[i] <- maxX; showDots <- TRUE } } for (i in 1:length(newTime)) { if (isValNum(newTime[i]) && newTime[i] == Inf) newTime[i] <- NA else if (isValNum(newTime[i]) && newTime[i] > maxX) { newTime[i] <- maxX; showDots <- TRUE } } if (isValNum(arrivalTime) && arrivalTime == Inf) { arrivalTime <- NA } else if (isValNum(arrivalTime) && arrivalTime > maxX) { arrivalTime <- maxX; showDots <- TRUE } if (isValNum(completionTime) && completionTime == Inf) { completionTime <- NA } else if (isValNum(completionTime) && completionTime > maxX) { completionTime <- maxX; showDots <- TRUE } if (showDots) text(time + maxTime * 0.95, 0.1, "...") DrawPoint(oldTimes, 0.1, col = "grey", cex = ScaleFont(25)) DrawPoint(arrivalTime, 0.1, col = simcolors$arrivalTime, cex = ScaleFont(25)) DrawPoint(completionTime, 0.1, col = simcolors$svc, cex = ScaleFont(25)) DrawPoint(newTime, 0.1, col = simcolors$newTime, cex = ScaleFont(25)) text(time + maxTime * 1.1, -0.05, "time", cex = ScaleFont(15), xpd = NA) } DrawCalendarComponents <- function(calendarTimes = c(0,0), encircleTimes = c(FALSE, FALSE), highlightTimes = c(FALSE, FALSE) ) { TogglePlot(box1Range) arrcol <- if (highlightTimes[1]) "yellow" else simcolors$arr svccol <- if (highlightTimes[2]) "yellow" else simcolors$svc sizeS_ <- if (Sys.getenv("RSTUDIO") == 1) fs(8) else fs(15) sizeL_ <- if (Sys.getenv("RSTUDIO") == 1) fs(12) else fs(20) TextBox("", 100, 110, 75, 75, bg = "white") TextBox("Calendar", 100, 180, 75, 15, col = "white", bg = "lightsteelblue4", size = sizeL_) if (encircleTimes[1]) TextBox("", 100, 120, 67.5, 20, bg = "blue") if (encircleTimes[2]) TextBox("", 100, 60, 67.5, 20, bg = "blue") TextBox("Next Arrival", 100, 150, 100, 10, size = sizeS_) TextBox("Next Completion", 100, 88, 100, 10, size = sizeS_) TextBox(paste("a =", pround(calendarTimes[1])), 100, 120, 60, 15, bg = arrcol, size = sizeS_) TextBox(paste("c =", pround(calendarTimes[2])), 100, 60, 60, 15, bg = svccol, size = sizeS_) } CalendarVals <- list(arrivalTime = 0, completionTime = 0, encircleTimes = c(FALSE, FALSE), highlightTimes = c(FALSE, FALSE)) DrawCurrCalendar <- function(arrivalTime, completionTime, encircleTimes, highlightTimes, forceDraw = FALSE) { if (missing(arrivalTime)) arrivalTime <- CalendarVals[["arrivalTime"]] if (missing(completionTime)) completionTime <- CalendarVals[["completionTime"]] if (missing(encircleTimes)) encircleTimes <- CalendarVals[["encircleTimes"]] if (missing(highlightTimes)) highlightTimes <- CalendarVals[["highlightTimes"]] DrawCalendarComponents(c(arrivalTime, completionTime), encircleTimes, highlightTimes) } setDrawCurrCalendar <- function(arrivalTime, completionTime, encircleTimes = c(FALSE, FALSE), highlightTimes = c(FALSE, FALSE) ) { plotCalendar <- FALSE if (!missing(arrivalTime)) { CalendarVals[["arrivalTime"]] <<- arrivalTime; plotCalendar <- TRUE } if (!missing(completionTime)) { CalendarVals[["completionTime"]] <<- completionTime; plotCalendar <- TRUE } if (!missing(encircleTimes)) { CalendarVals[["encircleTimes"]] <<- encircleTimes; plotCalendar <- TRUE } if (!missing(highlightTimes)) { CalendarVals[["highlightTimes"]] <<- highlightTimes; plotCalendar <- TRUE } return(plotCalendar) } TimeLineVals <- list(time = 0, maxTime = 4, arrivalTime = 0, completionTime = 0, oldTimes = NA, newTime = NA) DrawCurrTimeline <- function(time, arrivalTime, completionTime, oldTimes, newTime, inversionLine = TRUE, forceDraw = FALSE) { if (pauseData$plotDelay == 0 && !forceDraw) return() if (pauseData$plotDelay == -2) return() if (missing(time)) time <- TimeLineVals[["time"]] if (missing(arrivalTime)) arrivalTime <- TimeLineVals[["arrivalTime"]] if (missing(completionTime)) completionTime <- TimeLineVals[["completionTime"]] if (missing(oldTimes)) oldTimes <- TimeLineVals[["oldTimes"]] if (missing(newTime)) newTime <- TimeLineVals[["newTime"]] DrawTimelineComponents(time, TimeLineVals[["maxTime"]], arrivalTime, completionTime, oldTimes, newTime, inversionLine) } setDrawCurrTimeline <- function(time, maxTime, arrivalTime, completionTime, oldTimes = NA, newTime = NA ) { plotTimeline <- FALSE if (!missing(time)) { TimeLineVals[["time"]] <<- time; plotTimeline <- TRUE; } if (!missing(maxTime)) { TimeLineVals[["maxTime"]] <<- maxTime; plotTimeline <- TRUE; } if (!missing(arrivalTime)) { TimeLineVals[["arrivalTime"]] <<- arrivalTime; plotTimeline <- TRUE; } if (!missing(completionTime)) { TimeLineVals[["completionTime"]] <<- completionTime; plotTimeline <- TRUE; } if (!missing(oldTimes)) { TimeLineVals[["oldTimes"]] <<- oldTimes; plotTimeline <- TRUE; } if (!missing(newTime)) { TimeLineVals[["newTime"]] <<- newTime; plotTimeline <- TRUE; } return(plotTimeline) } SpecifyEventSteps <- function(currentTime, arrivalTime, completionTime, process, isArrival, advanceTime, numInSystem, forceDraw = FALSE ) { if ((pauseData$plotDelay == 0 && !forceDraw) || (pauseData$plotDelay == -2)) { vfunc <- if (isArrival == TRUE) interarrivalFcn else serviceFcn return(vfunc(num_in_sys = numInSystem, as_list = FALSE)) } if (process == 0) msg <- c( "Initialize Calendar", "Initially, Impossible Events", "Generate U(0, 1) For 1st Interarrival", "Generate 1st Interarrival Time By Inverting", "Compute 1st Arrival Time", "Place 1st Arrival Time On Calendar" ) else if (process == 1) msg <- c( "Process Arrival (Server Idle)", "Check Calendar Times For Minimum Time", "Generate U(0, 1) For Next Service Time", "Compute Next Service Time By Inverting", "Compute Next Completion Time", "Place Next Completion Time On Calendar" ) else if (process == 2) msg <- c( "Process Arrival", "Check Calendar Times For Minimum Time", "Generate U(0, 1) For Next Interarrival Time", "Compute Next Interarrival Time By Inverting", "Compute Next Arrival Time", "Place Next Arrival Time On Calendar" ) else if (process == 3) msg <- c( "Process Arrival (System Not Empty)", "Check Calendar Times For Minimum Time", "Generate U(0, 1) For Next Interarrival Time", "Compute Next Interarrival Time By Inverting", "Compute Next Arrival Time", "Place Next Completion Time on Calendar" ) else if (process == 4) msg <- c( "Process Completion (Queue Not Empty)", "Check Calendar Times For Minimum Time", "Generate U(0, 1) For Next Service Time", "Compute Next Service Time By Inverting", "Compute Next Completion Time", "Place Next Completion Time on Calendar" ) else if (process == 5) { DrawServiceAsImpossible(currentTime, arrivalTime, completionTime) return() } else if (process == 6) { DrawArrivalAsImpossible(currentTime, arrivalTime, completionTime) return() } else if (process == 7) { DrawRejection(currentTime, arrivalTime, completionTime) return() } variate <- DrawInversionProcess(currentTime, arrivalTime, completionTime, isArrival, process, msg, advanceTime, numInSystem, forceDraw = forceDraw) return(variate) } DrawServiceAsImpossible <- function(curr.time, arr.time, cmp.time) { ScalePlots(calendarPlotRange) TogglePlot(calendarPlotRange) DrawBorder(calendarPlotBGColor, calendarPlotBGColor) SetChyron("Advance System Clock") DrawEmptyIDF() DrawCurrCalendar(encircleTimes = c(FALSE, TRUE)) DrawCurrTimeline(time = cmp.time) pauseData <<- PauseCurrPlot("DrawServiceAsImpossible: if (pauseData$menuChoice %in% c('q','e','j')) return() SetChyron("Process Completion (Queue Empty) : Remove Expired Completion From Calendar") DrawEmptyIDF() setDrawCurrCalendar(completionTime = Inf) DrawCurrCalendar(highlightTimes = c(FALSE, TRUE)) setDrawCurrTimeline(time = cmp.time, completionTime = NA) DrawCurrTimeline(newTime = c(cmp.time), inversionLine = FALSE) pauseData <<- PauseCurrPlot("DrawServiceAsImpossible: if (pauseData$menuChoice %in% c('q','e','j')) return() if (arr.time != Inf) { SetChyron(paste("Determine Next Event Type : Find Minimum Time On Calendar")) DrawCurrTimeline(inversionLine = FALSE) DrawCurrCalendar(encircleTimes = c(TRUE, FALSE)) } pauseData <<- PauseCurrPlot("DrawServiceAsImpossible: if (pauseData$menuChoice %in% c('q','e','j')) return() } DrawArrivalAsImpossible <- function(curr.time, arr.time, cmp.time) { ScalePlots(calendarPlotRange) TogglePlot(calendarPlotRange) DrawBorder(calendarPlotBGColor, calendarPlotBGColor) SetChyron("Advance System Clock") DrawEmptyIDF() DrawCurrCalendar(encircleTimes = c(TRUE, FALSE)) DrawCurrTimeline(time = arr.time) pauseData <<- PauseCurrPlot("DrawArrivalAsImpossible: if (pauseData$menuChoice %in% c('q','e','j')) return() SetChyron("Finalizing Arrival : Cease Further Arrival Generations") DrawEmptyIDF() setDrawCurrCalendar(arrivalTime = Inf) DrawCurrCalendar(highlightTimes = c(TRUE, FALSE)) setDrawCurrTimeline(time = arr.time, arrivalTime = NA) DrawCurrTimeline(newTime = c(arr.time), inversionLine = FALSE) pauseData <<- PauseCurrPlot("DrawArrivalAsImpossible: if (pauseData$menuChoice %in% c('q','e','j')) return() SetChyron("Progressing Simulation : Awaiting Next Service") pauseData <<- PauseCurrPlot("DrawArrivalAsImpossible: if (pauseData$menuChoice %in% c('q','e','j')) return() } DrawRejection <- function(curr.time, arr.time, cmp.time) { ScalePlots(calendarPlotRange) TogglePlot(calendarPlotRange) DrawBorder(calendarPlotBGColor, calendarPlotBGColor) SetChyron("Advance System Clock") DrawEmptyIDF() DrawCurrQueue(idNextToEnter = SSQVals["idJustRejected"], idJustRejected = 0) DrawCurrCalendar(encircleTimes = c(TRUE, FALSE)) DrawCurrTimeline(time = arr.time) pauseData <<- PauseCurrPlot("DrawRejection: if (pauseData$menuChoice %in% c('q','e','j')) return() SetChyron("Rejecting Arrival : Ejecting Job and Removing Stale Arrival") DrawEmptyIDF() DrawCurrQueue() setDrawCurrCalendar(arrivalTime = Inf) DrawCurrCalendar(highlightTimes = c(TRUE, FALSE)) setDrawCurrTimeline(time = arr.time, arrivalTime = Inf) DrawCurrTimeline(newTime = c(arr.time), inversionLine = FALSE) pauseData <<- PauseCurrPlot("DrawRejection: if (pauseData$menuChoice %in% c('q','e','j')) return() } DrawInversionProcess <- function( time, arrivalTime, completionTime, isArrival, process, message, advanceTime, numInSystem, forceDraw = FALSE ) { vfunc <- if (isArrival == TRUE) interarrivalFcn else serviceFcn arr0 <- if (arrivalTime == 0) Inf else arrivalTime cmp0 <- if (completionTime == 0) Inf else completionTime result <- vfunc(numInSystem, TRUE) u <- result[["u"]] x <- result[["x"]] quantFnc <- result[["quantile"]] plotText <- result[["text"]] if ((pauseData$plotDelay == 0 && !forceDraw) || (pauseData$plotDelay == -2)) { return(x) } gxRange <- quantFnc(c(0.01, 0.99)) gyExact <- seq(0, 1, by = (diff(0:1))/1000) gxExact <- quantFnc(gyExact) displayVars <- if (isArrival) c("r", "a") else c("s", "c") { ScalePlots(calendarPlotRange) TogglePlot(calendarPlotRange) DrawBorder(calendarPlotBGColor, calendarPlotBGColor) ctitle <- if (time == 0) message[1] else "Advance System Clock" SetChyron(ctitle) DrawEmptyIDF() DrawCalendarComponents(calendarTimes = c(arr0, cmp0), encircleTimes = c(FALSE, FALSE)) DrawTimelineComponents(time = time, maxTime = gxRange[2], arrivalTime = arr0, completionTime = cmp0, oldTimes = NA, newTime = NA) } if (pauseData$plotDelay == 0) return(x) if (advanceTime) { pauseData <<- PauseCurrPlot("DrawInversionProcess: if (pauseData$menuChoice %in% c('q','e','j')) return(x) } { SetChyron(paste(message[1], ":", message[2])) DrawCalendarComponents( calendarTimes = c(arr0, cmp0), encircleTimes = c(time == 0 || isArrival, time == 0 || !isArrival) ) } if (time == 0) { pauseData <<- PauseCurrPlot("DrawInversionProcess: if (pauseData$menuChoice %in% c('q','e','j')) return(x) } sizeTitle_ <- if (Sys.getenv("RSTUDIO") == 1) fs(10) else fs(18) sizeS_ <- if (Sys.getenv("RSTUDIO") == 1) fs(8) else fs(15) sizeL_ <- if (Sys.getenv("RSTUDIO") == 1) fs(12) else fs(20) { SetChyron(paste(message[1], ":", message[3])) if (time == 0) { DrawCalendarComponents(calendarTimes = c(arr0, cmp0), encircleTimes = c(isArrival, !isArrival)) } TogglePlot(box2PlotRange + c(-16, 16, -8, 8)) DrawBorder(calendarPlotBGColor, calendarPlotBGColor) TogglePlot(box2Range + c(-2, 2, 0, 0), initPlot = FALSE) typeText <- if (isArrival) "Interarrival" else "Service" TextBox(paste(typeText, "CDF:", plotText), 100, 180, 100, 10, font = 2, size = sizeTitle_) DrawIDF(u, x = NA, gxRange, gxExact, gyExact, isArrival) DrawTimelineComponents(time = time, maxTime = gxRange[2], arrivalTime = arr0, completionTime = cmp0, oldTimes = NA, newTime = NA) TogglePlot(box3Range) TextBox("U(0,1)", 125, 175, 75, 20, bg = simcolors$u, tyd = 0.3, size = sizeS_) TextBox(pround(u), 125, 155, 75/2, 15, bg = "white", size = sizeS_) Arrows(50, 175, 15, 163) } pauseData <<- PauseCurrPlot("DrawInversionProcess: if (pauseData$menuChoice %in% c('q','e','j')) return(x) { SetChyron(paste(message[1], ":", message[4])) DrawIDF(u, x = x, gxRange, gxExact, gyExact, isArrival) if (isArrival) setDrawCurrQueue(interarrivalTime = x) else setDrawCurrQueue(serviceTime = x) DrawCurrQueue() TogglePlot(box3Range) boxtitle <- paste("New", displayVars[1]) TextBox(boxtitle, 125, 110, 75, 20, tyd = 0.3, bg = if (isArrival) simcolors$arr else simcolors$svc, size = sizeS_) TextBox(pround(x), 125, 90, 75/2, 15, bg = "white", size = sizeS_) Arrows(0, 110, 35, 110) } pauseData <<- PauseCurrPlot("DrawInversionProcess: if (pauseData$menuChoice %in% c('q','e','j')) return(x) { SetChyron(paste(message[1], ":", message[5])) TogglePlot(box3Range) boxtitle <- paste("New", displayVars[2]) boxvalue <- paste(pround(time), "+", displayVars[1]) TextBox(boxtitle, 125, 45, 75, 20, bg = "yellow", tyd = 0.3, size = sizeS_) TextBox(boxvalue, 125, 25, 56.25, 15, bg = "white", size = sizeS_) Arrows(70, 90, 70, 60) DrawTimelineComponents(time = time, maxTime = gxRange[2], arrivalTime = arr0, completionTime = cmp0, oldTimes = NA, newTime = time + x) if (isArrival) setDrawCurrQueue(arrivalTime = time + x) else setDrawCurrQueue(completionTime = time + x) DrawCurrQueue() TogglePlot(box1Range) TextBox(paste(displayVars[2], "=", pround(time + x)), 100, 20, 60, 15, bg = "yellow", size = sizeS_) } pauseData <<- PauseCurrPlot("DrawInversionProcess: if (pauseData$menuChoice %in% c('q','e','j')) return(x) { SetChyron(paste(message[1], ":", message[6])) arr1 <- if ( isArrival) pround(time + x) else arr0 cmp1 <- if (!isArrival) pround(time + x) else cmp0 TogglePlot(box1Range) rect(38, 3, 162, 34.4, col = calendarPlotBGColor, border = NA) setDrawCurrCalendar(arrivalTime = arr1, completionTime = cmp1) DrawCurrCalendar(encircleTimes = c(isArrival, !isArrival), highlightTimes = c(isArrival, !isArrival)) DrawTimelineComponents( time = time, maxTime = gxRange[2], arrivalTime = arr1, completionTime = cmp1, oldTimes = c(arr0, cmp0), inversionLine = FALSE ) } pauseData <<- PauseCurrPlot("DrawInversionProcess: if (pauseData$menuChoice %in% c('q','e','j')) return(x) { DrawEmptyIDF() setDrawCurrTimeline(time = time, maxTime = gxRange[2], arrivalTime = arr1, completionTime = cmp1) DrawCurrTimeline() DrawCurrCalendar() SetChyron("Initialization Complete : Begin Event Loop") } if (process == 0) { pauseData <<- PauseCurrPlot("DrawInversionProcess: if (pauseData$menuChoice %in% c('q','e','j')) return(x) } if (time == 0 || cmp1 < Inf) { SetChyron(paste("Determine Next Event Type : Find Mininum Time On Calendar")) DrawCurrTimeline(inversionLine = FALSE) minIsArrival <- (arr1 < cmp1) && arr1 != Inf DrawCurrCalendar(encircleTimes = c(minIsArrival, !minIsArrival)) } else { SetChyron(paste("Process Arrival : Generate New Service Time")) DrawCurrTimeline(inversionLine = FALSE) DrawCalendarComponents( calendarTimes = c(arr1, cmp1), encircleTimes = c(FALSE, TRUE), highlightTimes = c(FALSE, FALSE) ) } return(x) } StatsValsFresh <- FALSE StatsVals <- list(nt = rep(0, 3), qt = rep(0, 3), xt = rep(0, 3), w = rep("-", 3), s = rep("-", 3), o = rep("-", 3)) DrawStatsTableComponents <- function(n = 0, nt = StatsVals[["nt"]], qt = StatsVals[["qt"]], xt = StatsVals[["xt"]], w = StatsVals[["w"]], s = StatsVals[["s"]], o = StatsVals[["o"]], forceDraw = FALSE ) { if (identical(list(nt, qt, xt, w, s, o), StatsVals)) { if (forceDraw == FALSE && StatsValsFresh == FALSE) { return() } else { StatsValsFresh <<- FALSE } } else { StatsValsFresh <<- TRUE } ScalePlots(statsPlotRange) TogglePlot(statsRange) DrawBorder("grey") if (is.null(DrawCol)) { tw <- c(35, 55, 55, 55) th <- c(35, 40, 40, 40, 40) hbg <- "lightgrey" cbg <- "white" tmw <- tw[1]/2 tmh <- th[1]/2 if (length(tw) > 2) for (i in 2:length(tw)) tmw <- c(tmw, sum(tw[1:(i-1)]) + tw[i]/2) if (length(th) > 2) for (i in 2:length(th)) tmh <- c(tmh, sum(th[1:(i-1)]) + th[i]/2) tmh <- 200 - tmh cellsize_ <- if (Sys.getenv("RSTUDIO") == 1) 12 else 15 DrawCell <- function(text, c, r, bg = cbg, textf = NA) { TextBox(text, tmw[c], tmh[r+1], tw[c]/2, th[r+1]/2, bg = bg, textf = pround, size = cellsize_) } DrawCol <<- function(col, texts, bg = cbg) { for (i in 1:length(texts)) DrawCell(texts[i], col, i, bg = if (col == 1 || i == 1) hbg else bg) } } col1 <- "white" col2 <- "yellow" TogglePlot(tpsStatsRange) size_ <- if (Sys.getenv("RSTUDIO") == 1) 12 else 15 TextBox("Time-Averaged Statistics", 100, 200, 100, 17, bg = "grey22", col = "white", size = size_) DrawCol(1, c("", "@t", "avg", "sd")) DrawCol(2, c("n(t)", nt), if (all(nt == StatsVals[["nt"]])) col1 else col2) DrawCol(3, c("q(t)", qt), if (all(qt == StatsVals[["qt"]])) col1 else col2) DrawCol(4, c("x(t)", xt), if (all(xt == StatsVals[["xt"]])) col1 else col2) TogglePlot(booStatsRange) w <- if (!is.na(w[1])) w else rep("-", 3) s <- if (!is.na(s[1])) s else rep("-", 3) o <- if (!is.na(o[1])) o else rep("-", 3) TextBox(paste("Observed Statistics (n = ", n, ")", sep = ""), 100, 200, 100, 17, bg = "grey22", col = "white", size = size_) DrawCol(1, c("", "i", "avg", "sd")) DrawCol(2, c("wait", w), if (all(w == StatsVals[["w"]])) col1 else col2) DrawCol(3, c("service", s), if (all(s == StatsVals[["s"]])) col1 else col2) DrawCol(4, c("sojourn", o), if (all(o == StatsVals[["o"]])) col1 else col2) StatsVals[1:6] <<- list(nt, qt, xt, w, s, o) } main <- function(seed) { if (is.null(seed) || is.numeric(seed)) simEd::set.seed(seed) numEntries <- 1000 jobs <- list( arrTimes = rep(NA, numEntries), intArrTimes = rep(NA, numEntries), waitTimes = rep(NA, numEntries), serviceTimes = rep(NA, numEntries), sojournTimes = rep(NA, numEntries), currState = rep("pending", numEntries)) idsInSystem <- c() times <- rep(NA, numEntries) numsInSys <- rep(NA, numEntries) numsInQue <- rep(NA, numEntries) numsInSvr <- rep(NA, numEntries) timesPos <- 0 svrPos <- 0 timesServer <- rep(NA, numEntries) numsServer <- rep(NA, numEntries) currTime <- 0.0 prevTime <- 0.0 currSvcTime <- 0.0 currIntArrTime <- 0.0 numInSystem <- 0 numArrivals <- 0 numStarted <- 0 numDepartures <- 0 numRejects <- 0 idJustRejected <- 0 idJustServed <- 0 idLastEntered <- -1 { GetBOOAvg <- function(d, i = length(d), getSd = FALSE) { vals <- d[1:i]; vals <- vals[!is.na(vals)] if (length(vals) == 0) return(rep(NA, 1 + getSd)) xbar <- mean(vals) if (getSd) { s <- sd(vals) s <- if (is.na(s)) 0 else s return(c(xbar, s)) } return(xbar) } GetTPSAvg <- function(n, t = times, i = length(n), getSd = FALSE) { nVals <- n[1:i]; nVals <- nVals[!is.na(nVals)] tVals <- t[1:i]; tVals <- tVals[!is.na(tVals)] if (length(nVals) == 0) return(rep(NA, 1 + getSd)) nbar <- if (length(tVals) > 1) meanTPS(tVals, nVals) else mean(nVals) if (length(nVals) == 1) { return(if (getSd) c(nbar, 0) else nbar) } if (getSd) { s <- sdTPS(tVals, nVals) s <- if (is.na(s)) 0 else s return(c(nbar, s)) } return(nbar) } SetSystemState <- function(time, numInSystem) { timesPos <<- timesPos + 1 if (timesPos > length(times)) { times <<- resize(times) numsInSys <<- resize(numsInSys) numsInQue <<- resize(numsInQue) numsInSvr <<- resize(numsInSvr) } times [timesPos] <<- time numsInSys[timesPos] <<- numInSystem numsInQue[timesPos] <<- max(0, numInSystem - numServers) numsInSvr[timesPos] <<- min(numServers, numInSystem) } SetServerState <- function(time, numInService) { svrPos <<- svrPos + 1 if (svrPos > length(timesServer)) { timesServer <<- resize(timesServer) numsServer <<- resize(numsServer) } timesServer[svrPos] <<- time numsServer [svrPos] <<- numInService } SetJobStateArr <- function(arrivalTime, interarrivalTime, state, i = numArrivals + 1) { if (i > length(jobs$arrTimes)) jobs$arrTimes <<- resize(jobs$arrTimes) if (i > length(jobs$intArrTimes)) jobs$intArrTimes <<- resize(jobs$intArrTimes) if (i > length(jobs$currState)) jobs$currState <- resize(jobs$currState) if (!is.na(jobImage) && length(idsInSystem) > length(pictype)) pictype <<- c(pictype, pictype) jobs$arrTimes [i] <<- arrivalTime jobs$intArrTimes[i] <<- interarrivalTime jobs$currState [i] <<- state } UpdateJobStateArr <- function(arrivalTime, interarrivalTime, state, i = numArrivals + 1) { jobs$arrTimes [i] <<- arrivalTime jobs$intArrTimes[i] <<- interarrivalTime jobs$currState [i] <<- state } SetJobStateSvc <- function(waitTime, serviceTime, state, i = numStarted + 1) { if (i > length(jobs$waitTimes)) jobs$waitTimes <<- resize(jobs$waitTimes) if (i > length(jobs$serviceTimes)) jobs$serviceTimes <<- resize(jobs$serviceTimes) if (i > length(jobs$sojournTimes)) jobs$sojournTimes <<- resize(jobs$sojournTimes) jobs$waitTimes [i] <<- waitTime jobs$serviceTimes [i] <<- serviceTime jobs$sojournTimes [i] <<- waitTime + serviceTime jobs$currState [i] <<- state } } SetSystemState(time = 0, numInSystem = 0) SetServerState(time = 0, numInService = 0) drawQueueSkylineStats <- NULL viewJob <- function(job.num, data = jobs) { if (is.na(job.num)) message("\t", sym$alert, " 'job' must be followed by the job " (e.g., 'job 5')") else if (job.num > numArrivals) message("\t", sym$alert, " Job ", job.num, " has not yet arrived") else { message("\tViewing Job ", job.num) message("\t ", sym$bullet, " Arrival Time = ", format(round(data$arrTimes[job.num], 3), nsmall = 3)) message("\t ", sym$bullet, " Interarrival Time = ", format(round(data$intArrTimes[job.num], 3), nsmall = 3)) message("\t ", sym$bullet, " Wait Time = ", format(round(data$waitTimes[job.num], 3), nsmall = 3)) message("\t ", sym$bullet, " Service Time = ", format(round(data$serviceTimes[job.num], 3), nsmall = 3)) sojourn_ = data$waitTimes[job.num] + data$serviceTimes[job.num] message("\t ", sym$bullet, " Sojourn Time = ", format(round(sojourn_, 3), nsmall = 3)) departure_ = data$arrTimes[job.num] + sojourn_ message("\t ", sym$bullet, " Departure Time = ", format(round(departure_, 3), nsmall = 3)) } } pauseData <<- SetPausePlot( plotDelay = plotDelay, prompt = "Hit 'ENTER' to proceed, 'q' to quit, or 'h' for help/more options: ", viewCommand = c("job"), viewNumArgs = c(1), viewInstruct = c("'job n' = shows attributes of nth job"), viewFunction = list("1" = function(n_) viewJob(n_)) ) PauseCurrPlot <<- function(calledFromWhere = NULL) { if (exists("DEBUG_") && !is.null(calledFromWhere)) { cat("PauseCurrPlot called from ", calledFromWhere, "with plotDelay =", pauseData$plotDelay, "\n") } currValue <- if (endType == endCriteria$ARRIVALS) { numArrivals } else { numDepartures } pauseData <<- PausePlot( pauseData = pauseData, currStep = currValue, maxSteps = endValue ) return(pauseData) } CheckMenuChoice <- function(menuChoice, userOptions) { if (!is.null(userOptions)) { if (sum(sapply(1:2, function(i) userOptions[[i]])) != 0) return(userOptions) } updatedUserOptions <- list(userQuits = FALSE, userEnds = FALSE, userJumps = FALSE) if (menuChoice == 'q') { updatedUserOptions$userQuits <- TRUE } else if (pauseData$menuChoice == 'e') { updatedUserOptions$userEnds <- TRUE pauseData$plotDelay <<- 0 } else if (pauseData$menuChoice == 'j') { updatedUserOptions$userJumps <- TRUE } return(updatedUserOptions) } if(is.null(dev.list())) { dev.new(width = 5, height = 6) } par(mfrow = c(1, 1), mar = c(1,1,1,1), new = FALSE) dev.flush(dev.hold()) dev.hold() ResetPlot() if (showTitle) title(titleText, cex.main = 0.975, line = 0, xpd = NA) DrawCurrQueue(forceDraw = TRUE) PlotSkyline(times = 0, numsInSystem = 0, numsInQueue = 0, numsInServer = 0, rangeForPlotting = 0, entireRange = 0, forceDraw = TRUE) DrawStatsTableComponents(n = 0, forceDraw = TRUE) start.t <- rep(NA, numEntries) end.t <- rep(NA, numEntries) run.count <- 0 currIntArrTime <- SpecifyEventSteps(currentTime = 0, arrivalTime = 0, completionTime = 0, process = 0, isArrival = TRUE, advanceTime = TRUE, numInSystem = 0, forceDraw = TRUE) userOptions <- NULL userOptions <- CheckMenuChoice(pauseData$menuChoice, userOptions) arrivalsCal$time <<- currIntArrTime arrivalsCal$state <<- 1 par(mfrow = c(1, 1), mar = c(0, 0, 0, 0), new = TRUE) DrawQueueComponents(time = 0, idsInSystem = NULL, idJustRejected = 0, idNextToEnter = 1, idJustServed = 0, currentProgress = 0, numRejects = 0, interarrivalTime = currIntArrTime, arrivalTime = currIntArrTime, serviceTime = NA, completionTime = NA, forceDraw = TRUE ) TogglePlot(upArrowPlotRange) Arrows(100, 0, 100, 150) pauseData <<- PauseCurrPlot("After Initial Drawing") userOptions <- CheckMenuChoice(pauseData$menuChoice, userOptions) getCurrProgress <- function() return(max(c(numDepartures/maxDepartures, numArrivals/maxArrivals, currTime/maxTime))) drawCurrQueue <- function(forceDraw = FALSE) { if (pauseData$plotDelay == 0 && !forceDraw) return() if (pauseData$plotDelay == -2) return() iar <- jobs$intArrTimes[numArrivals + 1] if (is.null(idsInSystem)) svc <- NA else svc <- jobs$serviceTimes[idsInSystem[1]] arr <- if (is.na(iar)) iar else arrivalsCal$time cmp <- if (is.na(svc)) svc else serverCal$time if (setDrawCurrQueue(time = currTime, idsInSystem = idsInSystem, idJustRejected = idJustRejected, idNextToEnter = numArrivals + 1, idJustServed = idJustServed, currentProgress = getCurrProgress(), numRejects = numRejects, serviceTime = svc, interarrivalTime = iar, arrivalTime = arr, completionTime = cmp) || forceDraw) { DrawCurrQueue(forceDraw = forceDraw) } TogglePlot(upArrowPlotRange) Arrows(100, 0, 100, 150) } drawCurrStatsTable <- function(forceDraw = FALSE, endOfSim = FALSE) { if (pauseData$plotDelay == 0 && !forceDraw) return() if (pauseData$plotDelay == -2) return() if (numDepartures > 0) { w <- c(jobs$waitTimes[numDepartures], GetBOOAvg(jobs$waitTimes[1:numDepartures], i = numDepartures, getSd = TRUE)) s <- c(jobs$serviceTimes[numDepartures], GetBOOAvg(jobs$serviceTimes[1:numDepartures], i = numDepartures, getSd = TRUE)) o <- c(jobs$sojournTimes[numDepartures], GetBOOAvg(jobs$sojournTimes[1:numDepartures], i = numDepartures, getSd = TRUE)) } else { w <- c(NA, NA) s <- c(NA, NA) o <- c(NA, NA) } if (endOfSim) { if (!is.infinite(maxTime) && endValue == maxTime && timesPos > 1 && currTime >= maxTime) { timesPos <- timesPos - 1 } } nt = c(numsInSys[timesPos], GetTPSAvg(numsInSys, i = timesPos, getSd = TRUE)) qt = c(numsInQue[timesPos], GetTPSAvg(numsInQue, i = timesPos, getSd = TRUE)) xt = c(numsInSvr[timesPos], GetTPSAvg(numsInSvr, i = timesPos, getSd = TRUE)) DrawStatsTableComponents(n = numDepartures, nt = nt, qt = qt, xt = xt, w = w, s = s, o = o, forceDraw = forceDraw ) } plotCurrSkyline <- function(forceDraw = FALSE, endOfSim = FALSE) { if (pauseData$plotDelay == 0 && !forceDraw) return() if (pauseData$plotDelay == -2) return() rangePlot <- NULL entireRange <- NULL if (timesPos == 1) { rangePlot <- 0 entireRange <- 0 } else if (!endOfSim) { rangePlot <- c(max(timesPos - maxEventsPerSkyline, 1), timesPos) entireRange <- c(1, timesPos) } else { rangePlot <- c(1, timesPos) entireRange <- c(1, timesPos) } PlotSkyline(times, numsInSys, numsInQue, numsInSvr, rangePlot, entireRange, forceDraw) } specifyCurrentEventSteps <- function(process, isArrival, advanceTime = TRUE, forceDraw = FALSE ) { drawQueueSkylineStats(forceDraw = forceDraw) generatedTime <- SpecifyEventSteps(currentTime = currTime, arrivalTime = if (currIntArrTime == Inf) Inf else arrivalsCal$time, completionTime = if (currSvcTime == Inf) Inf else serverCal$time, process = process, isArrival = isArrival, advanceTime = advanceTime, numInSystem = numInSystem, forceDraw = forceDraw ) return(generatedTime) } drawQueueSkylineStats <- function(forceDraw = FALSE, endOfSim = FALSE) { if (pauseData$plotDelay == 0 && !forceDraw) return() if (pauseData$plotDelay == -2) return() drawCurrQueue(forceDraw = forceDraw) plotCurrSkyline(forceDraw = forceDraw, endOfSim = endOfSim) drawCurrStatsTable(forceDraw = forceDraw, endOfSim = endOfSim) } while (!userOptions$userQuits && currTime < maxTime && (numDepartures < maxDepartures) && (arrivalsCal$state == 1 || numInSystem > 0)) { idJustServed <- idJustRejected <- 0 nextEvent <- getNextEvent() prevTime <- currTime currTime <- nextEvent$time if (currTime > maxTime || numDepartures >= maxDepartures) { if (currTime > maxTime) currTime <- maxTime SetSystemState(time = currTime, numInSystem = numsInSys[timesPos]) SetServerState(time = currTime, numInService = numsServer[svrPos]) break } if (nextEvent$type == 'a') { pauseData$isJumpStep <- TRUE UpdateJobStateArr(arrivalTime = currTime, interarrivalTime = currIntArrTime, state = "queued") numArrivals <- numArrivals + 1 idLastEntered <- numArrivals numInSystem <- numInSystem + 1 if (!is.na(pauseData$jumpTo) && numArrivals == pauseData$jumpTo) { pauseData$plotDelay <- -1 pauseData$jumpComplete <- TRUE pauseData <<- pauseData } idsInSystem <- append(idsInSystem, numArrivals) setDrawCurrQueue(shiftInQueue = TRUE) if (!is.na(jobImage) && length(idsInSystem) > length(pictype)) pictype <<- c(pictype, pictype) SetSystemState(time = currTime, numInSystem = numInSystem) if (numInSystem == 1) { if (exists("DEBUG_")) print("process = 1") currSvcTime <- specifyCurrentEventSteps(process = 1, isArrival = FALSE) userOptions <- CheckMenuChoice(pauseData$menuChoice, userOptions) if (userOptions$userQuits) { if (exists("DEBUG_")) print("quitting: process = 1!") break } serverCal$time <<- currTime + currSvcTime serverCal$state <<- 1 SetJobStateSvc(waitTime = 0, serviceTime = currSvcTime, state = "in service") numStarted <- numStarted + 1 SetServerState(time = currTime, numInService = 1) } if (arrivalsCal$time >= maxTime || numArrivals == maxArrivals) arrivalsCal$state <<- 0 if (numArrivals < maxArrivals) { if (numInSystem == 1) { if (exists("DEBUG_")) print("process = 2") currIntArrTime <- specifyCurrentEventSteps(process = 2, isArrival = TRUE, advanceTime = FALSE) userOptions <- CheckMenuChoice(pauseData$menuChoice, userOptions) if (userOptions$userQuits) { if (exists("DEBUG_")) print("quitting: process = 2!") break } } else { if (exists("DEBUG_")) print("process = 3") currIntArrTime <- specifyCurrentEventSteps(process = 3, isArrival = TRUE) userOptions <- CheckMenuChoice(pauseData$menuChoice, userOptions) if (userOptions$userQuits) { if (exists("DEBUG_")) print("quitting: process = 3!") break } } arrivalsCal$time <<- arrivalsCal$time + currIntArrTime SetJobStateArr(arrivalTime = arrivalsCal$time, interarrivalTime = currIntArrTime, state = "not arrived") } else { if (exists("DEBUG_")) print("process = 6") specifyCurrentEventSteps(process = 6, isArrival = TRUE) userOptions <- CheckMenuChoice(pauseData$menuChoice, userOptions) if (userOptions$userQuits) { if (exists("DEBUG_")) print("quitting: process = 6!") break } currIntArrTime <- Inf currArr <- Inf } } else { pauseData$isJumpStep <- FALSE numDepartures <- numDepartures + 1 numInSystem <- numInSystem - 1 jobs$currState[idsInSystem[1]] <- "served" idJustServed <- idsInSystem[1] idsInSystem <- idsInSystem[-1] SetSystemState(time = currTime, numInSystem = numInSystem) if (numInSystem > 0) { if (exists("DEBUG_")) print("process = 4") currSvcTime <- specifyCurrentEventSteps(process = 4, isArrival = FALSE) userOptions <- CheckMenuChoice(pauseData$menuChoice, userOptions) if (userOptions$userQuits) { if (exists("DEBUG_")) print("quitting: process = 4!") break } serverCal$time <<- currTime + currSvcTime SetJobStateSvc(waitTime = currTime - jobs$arrTimes[idsInSystem[1]], serviceTime = currSvcTime, state ="in service") numStarted <- numStarted + 1 SetServerState(time = currTime, numInService = 1) } else { serverCal$state <<- 0 SetServerState(time = currTime, numInService = 0) if (pauseData$plotDelay != 0) { if (exists("DEBUG_")) print("process = 5") specifyCurrentEventSteps(process = 5, isArrival = FALSE) userOptions <- CheckMenuChoice(pauseData$menuChoice, userOptions) if (userOptions$userQuits) { if (exists("DEBUG_")) print("quitting: process = 5!") break } } currSvcTime <- Inf currCmp <- Inf } } currArr <- if (currTime >= arrivalsCal$time) Inf else arrivalsCal$time currCmp <- if (currTime >= serverCal$time) Inf else serverCal$time setDrawCurrTimeline( time = currTime, arrivalTime = currArr, completionTime = currCmp) setDrawCurrCalendar( arrivalTime = currArr, completionTime = currCmp) DrawCurrTimeline() drawQueueSkylineStats() pauseData <<- PauseCurrPlot("end of while loop") userOptions <- CheckMenuChoice(pauseData$menuChoice, userOptions) if (userOptions$userQuits) { print("quitting: end of while loop!") break } if (pauseData$plotDelay != 0 && pauseData$plotDelay != -2) { ResetPlot() if (showTitle) title(titleText, cex.main = 0.975, line = -1) } } if (pauseData$plotDelay == 0 && pauseData$menuChoice == 'e') { pauseData <<- PauseCurrPlot("after while loop") pauseData$plotDelay <- -1 } if (pauseData$plotDelay == -2) { pauseData$plotDelay <- -1 pauseData$jumpComplete <- TRUE pauseData$endOfSim <- TRUE pauseData <<- PauseCurrPlot("after while loop") } ResetPlot() if (showTitle) title(titleText, cex.main = 0.975, line = -1) drawQueueSkylineStats(forceDraw = TRUE, endOfSim = TRUE) DrawEmptyIDF() SetChyron("Execution Finished") DrawCurrCalendar(forceDraw = TRUE) setDrawCurrTimeline(time = currTime, arrivalTime = NA, completionTime = NA) DrawCurrTimeline(forceDraw = TRUE) dev.flush(dev.hold()) jobs$arrTimes <- jobs$arrTimes [!is.na(jobs$arrTimes)] jobs$intArrTimes <- jobs$intArrTimes [!is.na(jobs$intArrTimes)] jobs$waitTimes <- jobs$waitTimes [!is.na(jobs$waitTimes)] jobs$serviceTimes <- jobs$serviceTimes [!is.na(jobs$serviceTimes)] if (numDepartures > 0) { jobs$arrTimes <- jobs$arrTimes [1:numDepartures] jobs$intArrTimes <- jobs$intArrTimes [1:numDepartures] jobs$waitTimes <- jobs$waitTimes [1:numDepartures] jobs$serviceTimes <- jobs$serviceTimes[1:numDepartures] } times <- times [!is.na(times)] numsInSys <- numsInSys [!is.na(numsInSys)] numsInQue <- numsInQue [!is.na(numsInQue)] numsInSvr <- numsInSvr [!is.na(numsInSvr)] timesServer <- timesServer [!is.na(timesServer)] numsServer <- numsServer [!is.na(numsServer)] if (pauseData$menuChoice == 'q' && currTime > 0) { timesServer <- c(timesServer, currTime) numsServer <- c(numsServer, numsServer[length(numsServer)]) } if (numDepartures > 0) { jobs$sojournTimes <- (jobs$waitTimes + jobs$serviceTimes)[1:numDepartures] } else { jobs$sojournTimes <- NA } avgWait <- 0 avgSojourn <- 0 avgNumInSys <- 0 util <- 0 avgNumInQue <- 0 if (length(jobs$waitTimes[!is.na(jobs$waitTimes)]) > 0) avgWait <- mean(jobs$waitTimes[!is.na(jobs$waitTimes)]) if (length(jobs$sojournTimes[!is.na(jobs$sojournTimes)]) > 0) avgSojourn<- mean(jobs$sojournTimes[!is.na(jobs$sojournTimes)]) if (length(numsInSys) > 1) avgNumInSys <- meanTPS(times, numsInSys) if (length(numsServer) > 1) util <- meanTPS(timesServer, numsServer) if (length(numsInQue) > 1) avgNumInQue <- meanTPS(times, numsInQue) { printed <- "" printed <- paste(printed, "$customerArrivals\n[1]", sep = "") printed <- paste(printed, numArrivals) printed <- paste(printed, "\n\n$customerDepartures\n[1]", sep = "") printed <- paste(printed, numDepartures) printed <- paste(printed, "\n\n$simulationEndTime\n[1]", sep = "") printed <- paste(printed, round(min(currTime, maxTime), digits = 5)) printed <- paste(printed, "\n\n$avgWait\n[1]", sep = "") printed <- paste(printed, signif(avgWait, digits = 5)) printed <- paste(printed, "\n\n$avgSojourn\n[1]", sep = "") printed <- paste(printed, signif(avgSojourn, digits = 5)) printed <- paste(printed, "\n\n$avgNumInSystem\n[1]", sep = "") printed <- paste(printed, signif(avgNumInSys, digits = 5)) printed <- paste(printed, "\n\n$avgNumInQueue\n[1]", sep = "") printed <- paste(printed, signif(avgNumInQue, digits = 5)) printed <- paste(printed, "\n\n$utilization\n[1]", sep = "") printed <- paste(printed, signif(util, digits = 5)) printed <- paste(printed, "\n\n", sep = "") if (showOutput) on.exit(cat(printed)) } ssq <- list(customerArrivals = numArrivals, customerDepartures = numDepartures, simulationEndTime = min(currTime, maxTime), avgWait = avgWait, avgSojourn = avgSojourn, avgNumInSystem = avgNumInSys, avgNumInQueue = avgNumInQue, utilization = util) { if (length(times) <= 1) { jobs$intArrTimes <- NULL jobs$serviceTimes <- NULL jobs$waitTimes <- NULL jobs$sojournTimes <- NULL } if (saveInterarrivalTimes) ssq$interarrivalTimes <- jobs$intArrTimes if (saveServiceTimes) ssq$serviceTimes <- jobs$serviceTimes if (saveWaitTimes) ssq$waitTimes <- jobs$waitTimes if (saveSojournTimes) ssq$sojournTimes <- jobs$sojournTimes if (saveNumInSystem) { ssq$numInSystemT <- times ssq$numInSystemN <- numsInSys } if (saveNumInQueue) { ssq$numInQueueT <- times ssq$numInQueueN <- numsInQue } if (saveServerStatus) { ssq$serverStatusT <- timesServer ssq$serverStatusN <- numsServer } } options(warn = warnVal$warn) par(mfrow = c(1,1)) return(invisible(ssq)) } return(main(seed)) }
setGeneric("sim", function( fit , data , n=1000 , ... ) { predict(fit) } ) sim_core <- function( fit , data , post , vars , n , refresh=0 , replace=list() , debug=FALSE , ll=FALSE , ... ) { sim_vars <- list() for ( var in vars ) { f <- fit@formula[[1]] for ( i in 1:length(fit@formula) ) { f <- fit@formula[[i]] left <- as.character( f[[2]] ) if ( left==var ) { if ( debug==TRUE ) print(f) break } } lik <- f outcome <- var flik <- as.character(lik[[3]][[1]]) first_char <- substr( flik , 1 , 1 ) if ( first_char != "d" | flik=="dirichlet" ) { for ( ii in 1:length( ulam_dists ) ) { aStanName <- ulam_dists[[ii]]$Stan_name if ( aStanName==flik ) { flik <- ulam_dists[[ii]]$R_name break } } } rlik <- flik if ( ll==FALSE ) { substr( rlik , 1 , 1 ) <- "r" if ( rlik=="rgampois" ) rlik <- "rgampois2" } aggregated_binomial <- FALSE size_var_is_data <- FALSE if ( flik=="dbinom" & ll==TRUE ) { ftemp <- flist_untag(fit@formula)[[1]] size_sym <- ftemp[[3]][[2]] if ( class(size_sym)=="name" ) { aggregated_binomial <- TRUE size_var_is_data <- TRUE } if ( class(size_sym)=="numeric" ) { if ( size_sym > 1 ) aggregated_binomial <- TRUE } } aggregated_binomial <- FALSE pars <- vector(mode="list",length=length(lik[[3]])-1) for ( i in 1:length(pars) ) { pars[[i]] <- lik[[3]][[i+1]] } if ( aggregated_binomial==TRUE ) { pars[[1]] <- 1 data[['ones__']] <- rep( 1 , length(data[[outcome]]) ) if ( refresh > 0 ) message("Aggregated binomial counts detected. Splitting to 0/1 outcome for WAIC calculation.") } pars <- paste( pars , collapse=" , " ) n_cases <- length(data[[outcome]]) if ( n_cases==0 ) { n_cases <- length(data[[1]]) } if ( ll==FALSE ) { xeval <- paste( rlik , "(" , n_cases , "," , pars , ")" , collapse="" ) } else { use_outcome <- outcome if ( aggregated_binomial==TRUE ) use_outcome <- 'ones__' xeval <- paste( rlik , "(" , use_outcome , "," , pars , ",log=TRUE )" , collapse="" ) } sim_out <- matrix(NA,nrow=n,ncol=n_cases) pred <- link( fit , data=data , n=n , post=post , flatten=FALSE , refresh=refresh , replace=replace , debug=debug , ... ) for ( s in 1:n ) { elm <- list() for ( j in 1:length(pred) ) { elm[[j]] <- pred[[j]][s,] } names(elm) <- names(pred) init <- list() for ( j in 1:length(post) ) { par_name <- names(post)[ j ] dims <- dim( post[[par_name]] ) if ( is.null(dims) ) init[[par_name]] <- post[[par_name]][s] if ( length(dims)==1 ) init[[par_name]] <- post[[par_name]][s] if ( length(dims)==2 ) init[[par_name]] <- post[[par_name]][s,] if ( length(dims)==3 ) init[[par_name]] <- post[[par_name]][s,,] } e <- list( as.list(data) , as.list(init) , as.list(elm) ) e <- unlist( e , recursive=FALSE ) if ( length(sim_vars) > 0 ) { for ( j in 1:length(sim_vars) ) { e[[ names(sim_vars)[j] ]] <- sim_vars[[j]][s,] } } sim_out[s,] <- eval( parse( text=xeval ) , envir=e ) } if ( debug==TRUE ) print(str(e)) if ( aggregated_binomial==TRUE ) { if ( size_var_is_data==TRUE ) { size_var <- data[[ as.character(ftemp[[3]][[2]]) ]] } else { size_var <- rep( as.numeric(ftemp[[3]][[2]]) , n_cases ) } n_newcases <- sum(size_var) sim_out_new <- matrix(NA,nrow=n,ncol=n_newcases) current_newcase <- 1 outcome_var <- data[[ outcome ]] for ( i in 1:n_cases ) { num_ones <- outcome_var[i] num_zeros <- size_var[i] - num_ones ll1 <- sim_out[,i] ll0 <- log( 1 - exp(ll1) ) if ( num_ones > 0 ) { for ( j in 1:num_ones ) { sim_out_new[,current_newcase] <- ll1 current_newcase <- current_newcase + 1 } } if ( num_zeros > 0 ) { for ( j in 1:num_zeros ) { sim_out_new[,current_newcase] <- ll0 current_newcase <- current_newcase + 1 } } } sim_out <- sim_out_new } sim_vars[[ var ]] <- sim_out data[[ var ]] <- sim_out } return(sim_vars) } setMethod("sim", "map", function( fit , data , n=1000 , post , vars , ll=FALSE , refresh=0 , replace=list() , debug=FALSE , ... ) { if ( class(fit)!="map" ) stop("Requires map/quap fit") if ( missing(data) ) { data <- fit@data } else { data <- as.list(data) if ( !missing(vars) ) { for ( i in 1:length(vars) ) { if ( !(vars[i] %in% names(data)) ) { data[[ vars[i] ]] <- rep( 0 , length(data[[1]]) ) } } } } if ( missing(post) ) { post <- extract.samples(fit,n=n) } else { n <- dim(post[[1]])[1] if ( is.null(n) ) n <- length(post[[1]]) } if ( missing(vars) ) { lik <- flist_untag(fit@formula)[[1]] vars <- as.character(lik[[2]]) } else { if ( debug==TRUE ) print(vars) } sim_vars <- sim_core( fit=fit , data=data , post=post , vars=vars , n=n , refresh=refresh , replace=replace , debug=debug , ll=ll , ... ) if ( length(sim_vars)==1 ) sim_vars <- sim_vars[[1]] return( sim_vars ) } ) setMethod("sim", "map2stan", function( fit , data , n=1000 , post , refresh=0.1 , replace=list() , ... ) { ag <- attr( fit , "generation" ) if ( !is.null(ag) ) if ( ag=="ulam2018" ) return( sim_ulam( fit , data=data , post=post , n=n , ... ) ) if ( missing(data) ) { data <- fit@data } else { } if ( n==0 ) { n <- stan_total_samples(fit@stanfit) } else { tot_samples <- stan_total_samples(fit@stanfit) n <- min(n,tot_samples) } if ( missing(post) ) post <- extract.samples(fit,n=n) pred <- link( fit , data=data , n=n , post=post , flatten=FALSE , refresh=refresh , replace=replace , ... ) lik <- flist_untag(fit@formula)[[1]] outcome <- as.character(lik[[2]]) flik <- as.character(lik[[3]][[1]]) first_char <- substr( flik , 1 , 1 ) if ( first_char != "d" ) { for ( ii in 1:length(map2stan.templates) ) { aStanName <- map2stan.templates[[ii]]$stan_name if ( aStanName==flik ) { flik <- map2stan.templates[[ii]]$R_name break } } } rlik <- flik substr( rlik , 1 , 1 ) <- "r" if ( rlik=="rgampois" ) rlik <- "rgampois2" pars <- vector(mode="list",length=length(lik[[3]])-1) for ( i in 1:length(pars) ) { pars[[i]] <- lik[[3]][[i+1]] } pars <- paste( pars , collapse=" , " ) n_cases <- length(data[[1]]) xeval <- paste( rlik , "(" , n_cases , "," , pars , ")" , collapse="" ) sim_out <- matrix( NA , nrow=n , ncol=n_cases ) post2 <- as.data.frame(post) for ( s in 1:n ) { elm <- list() for ( j in 1:length(pred) ) { ndims <- length(dim(pred[[j]])) if ( ndims==2 ) elm[[j]] <- pred[[j]][s,] if ( ndims==3 ) elm[[j]] <- pred[[j]][s,,] } names(elm) <- names(pred) e <- list( as.list(data) , as.list(post2[s,]) , as.list(elm) ) e <- unlist( e , recursive=FALSE ) if ( flik=="dordlogit" ) { n_outcome_vals <- dim( pred[[1]] )[3] probs <- pred[[1]][s,,] sim_out[s,] <- sapply( 1:n_cases , function(i) sample( 1:n_outcome_vals , size=1 , replace=TRUE , prob=probs[i,] ) ) } else { sim_out[s,] <- eval(parse(text=xeval),envir=e) } } return(sim_out) } ) if ( FALSE ) { library(rethinking) data(cars) fit <- map( alist( dist ~ dnorm(mu,sigma), mu <- a + b*speed ), data=cars, start=list(a=30,b=0,sigma=5) ) pred <- link(fit,data=list(speed=0:30),flatten=TRUE) sim.dist <- sim(fit,data=list(speed=0:30)) plot( dist ~ speed , cars ) mu <- apply( pred , 2 , mean ) mu.PI <- apply( pred , 2, PI ) y.PI <- apply( sim.dist , 2 , PI ) lines( 0:30 , mu ) shade( mu.PI , 0:30 ) shade( y.PI , 0:30 ) cars$y <- cars$dist m <- map2stan( alist( y ~ dnorm(mu,sigma), mu <- a + b*speed, a ~ dnorm(0,100), b ~ dnorm(0,10), sigma ~ dunif(0,100) ), data=cars, start=list( a=mean(cars$y), b=0, sigma=1 ), warmup=500,iter=2500 ) pred <- link(m,data=list(speed=0:30),flatten=TRUE) sim.dist <- sim(m,data=list(speed=0:30),n=0) plot( dist ~ speed , cars ) mu <- apply( pred , 2 , mean ) mu.PI <- apply( pred , 2, PI ) y.PI <- apply( sim.dist , 2 , PI ) lines( 0:30 , mu ) shade( mu.PI , 0:30 ) shade( y.PI , 0:30 ) }
fmetric <- function(S1,S2,measure="sim",h="laplacian", tau=1,M=NULL,abs.tol=.Machine$double.eps^0.25){ ret <- characterize(S1,S2); T1 <- ret$T1;T2 <- ret$T2;N1 <- ret$N1;N2 <- ret$N2;n.mark <- ret$n.mark if(measure=="sim"){ if(n.mark==0){ if(class(h)=="character"){ if(h=="laplacian"){ return(as.numeric((1/(4*tau*N1*N2))*sum(exp(-abs(outer(T1,T2,FUN="-"))/tau)))/2) }else{ stop("smoother function must be appropriately specified") } }else if(class(h)=="function"){ wv <- function(x){ sum(h(x-T1,tau=tau)*hev(x-T1))*sum(h(x-T2,tau=tau)*hev(x-T2)) } vv <- Vectorize(wv) val <- try(integrate(vv,lower=0,upper=Inf,abs.tol=abs.tol)$val,silent=TRUE) if(class(val)=="try-error"){ val <- try(integrate(vv,lower=0,upper=Inf,abs.tol=1e-1,subdivisions=1000)$val,silent=TRUE) } return(val/(4*N1*N2*tau^2)) }else{ stop("smoother function must be appropriately specified") } }else{ R1 <- as.matrix(S1[,-1]);R2 <- as.matrix(S2[,-1]) if(is.null(M)){ if(n.mark==1){ tmp <- 1/apply(rbind(R1,R2),2,var);M <- as.matrix(ifelse(is.infinite(tmp),as.matrix(1),(tmp))) }else{ tmp <- 1/apply(rbind(R1,R1),2,var);id <- which(is.infinite(tmp)); if(length(id)){ tmp[id] <- 1}; M <- diag(tmp) } } if(sum(eigen(M)$values <0)){ stop("precision matrix of smoothing function for marks must be positive definite") } if(class(h)=="character"){ if(h=="laplacian"){ if(n.mark==1){ crossR1R2 <- outer(as.numeric(R1),as.numeric(R2),FUN="-");W <- exp(-(crossR1R2^2)*as.numeric(M/4)) }else{ crossR1R2 <- outer(t(R1),t(R2),FUN="-") wGauss <- function(x) exp(-mahalanobis(x,center=FALSE,cov=M,inverted=TRUE)/4) W <- apply(apply(crossR1R2,c(2,4),diag),c(2,3),wGauss) } return(as.numeric(sum(W*exp(-abs(outer(T1,T2,FUN="-")/tau)))*sqrt(det(M))/( (2^(n.mark+2))*(pi^(n.mark/2))*tau*N1*N2))) }else{ stop("smoother function must be appropriately specified") } }else if(class(h)=="function"){ if(n.mark==1){ crossR1R2 <- outer(as.numeric(R1),as.numeric(R2),FUN="-");W <- exp(-(crossR1R2^2)*as.numeric(M/4)) }else{ crossR1R2 <- outer(t(R1),t(R2),FUN="-") wGauss <- function(x) exp(-mahalanobis(x,center=FALSE,cov=M,inverted=TRUE)/4) W <- apply(apply(crossR1R2,c(2,4),diag),c(2,3),wGauss) } wv <- function(x){ as.numeric((h(x-T1,tau=tau)*hev(x-T1))%*%W%*%(h(x-T2,tau=tau)*hev(x-T2))) } vv <- Vectorize(wv) val <- try(integrate(vv,lower=0,upper=Inf,abs.tol=abs.tol)$val,silent=TRUE) if(class(val)=="try-error"){ val <- try(integrate(vv,lower=0,upper=Inf,abs.tol=1e-1,subdivisions=1000)$val,silent=TRUE) } val <- val * sqrt(det(M))/( (2^(n.mark+2))*(pi^(n.mark/2))*tau*N1*N2) return(val) }else{ stop("smoother function must be appropriately specified") } } }else if(measure=="dist"){ if(n.mark==0){ if(class(h)=="character"){ if(h=="laplacian"){ val <- sqrt(abs(as.numeric(sum(exp(-abs(outer(T1,T1,FUN="-"))/tau)))/(4*tau*N1^2)+as.numeric(sum(exp(-abs(outer(T2,T2,FUN="-"))/tau)))/(4*tau*N2^2)-as.numeric(sum(exp(-abs(outer(T1,T2,FUN="-"))/tau)))/(2*tau*N1*N2))) return(val) }else{ stop("smoother function must be appropriately specified") } }else if(class(h)=="function"){ wv <- function(x){ (sum((h(x-T1,tau=tau)*hev(x-T1)))/(2*N1)-sum((h(x-T2,tau=tau)*hev(x-T2)))/(2*N2))^2 } vv <- Vectorize(wv) val <- try(integrate(vv,lower=0,upper=Inf,abs.tol=abs.tol)$val,silent=TRUE) if(class(val)=="try-error"){ val <- try(integrate(vv,lower=0,upper=Inf,abs.tol=1e-1,subdivisions=1000)$val,silent=TRUE) } return(sqrt(val)) }else{ stop("smoother function must be appropriately specified") } }else{ R1 <- as.matrix(S1[,-1]);R2 <- as.matrix(S2[,-1]) if(is.null(M)){ if(n.mark==1){ tmp <- 1/apply(rbind(R1,R2),2,var);M <- as.matrix(ifelse(is.infinite(tmp),as.matrix(1),(tmp))) }else{ tmp <- 1/apply(rbind(R1,R1),2,var);id <- which(is.infinite(tmp)); if(length(id)){ tmp[id] <- 1}; M <- diag(tmp) } } if(sum(eigen(M)$values <0)){ stop("precision matrix of smoothing function for marks must be positive definite") } if(n.mark==1){ crossR1R2 <- outer(as.numeric(R1),as.numeric(R2),FUN="-");W12 <- exp(-(crossR1R2^2)*as.numeric(M/4)) crossR1 <- outer(as.numeric(R1),as.numeric(R1),FUN="-");W1 <- exp(-(crossR1^2)*as.numeric(M/4)) crossR2 <- outer(as.numeric(R2),as.numeric(R2),FUN="-");W2 <- exp(-(crossR2^2)*as.numeric(M/4)) }else{ crossR1 <- outer(t(R1),t(R1),FUN="-") crossR2 <- outer(t(R2),t(R2),FUN="-") crossR1R2 <- outer(t(R1),t(R2),FUN="-") wGauss <- function(x) exp(-mahalanobis(x,center=FALSE,cov=M,inverted=TRUE)/4) W1 <- apply(apply(crossR1,c(2,4),diag),c(2,3),wGauss) W2 <- apply(apply(crossR2,c(2,4),diag),c(2,3),wGauss) W12 <- apply(apply(crossR1R2,c(2,4),diag),c(2,3),wGauss) } if(class(h)=="character"){ if(h=="laplacian"){ val <- as.numeric(sum(W1 * exp(-abs(outer(T1,T1,FUN="-"))/(tau))))/(N1^2)+ as.numeric(sum((W2 * exp(-abs(outer(T2,T2,FUN="-"))/(tau)))))/(N2^2) -2*as.numeric(sum((W12 * exp(-abs(outer(T1,T2,FUN="-"))/tau))))/(N1*N2) val <- val*sqrt(det(M))/((2^(n.mark+2))*(pi^(n.mark/2))*tau) return(sqrt(val)) }else{ stop("smoother function must be appropriately specified") } }else if(class(h)=="function"){ wv <- function(x){ (h(x-T1,tau=tau)*hev(x-T1))%*%W1%*%(h(x-T1,tau=tau)*hev(x-T1))/(N1^2)+(h(x-T2,tau=tau)*hev(x-T2))%*%W2%*%(h(x-T2,tau=tau)*hev(x-T2))/(N2^2)-2*(h(x-T1,tau=tau)*hev(x-T1))%*%W12%*%(h(x-T2,tau=tau)*hev(x-T2))/(N1*N2) } vv <- Vectorize(wv) val <- try(integrate(vv,lower=0,upper=Inf,abs.tol=abs.tol)$val,silent=TRUE) if(class(val)=="try-error"){ val <- try(integrate(vv,lower=0,upper=Inf,abs.tol=1e-1,subdivisions=1000)$val,silent=TRUE) } val <- val * sqrt(det(M))/((2^(n.mark+2))*(pi^(n.mark/2))*tau) return(sqrt(val)) }else{ stop("smoother function must be appropriately specified") } } }else{ stop("Measure must be dist or sim") } }
window.mcmcOutput <- function(x, start=1, end=NULL, thin=1, ...) { nChains <- attr(x, "nChains") if(is.null(nChains) || nrow(x) %% nChains != 0) stop("nChains attribute of x is missing or invalid.") draws.per.chain <- nrow(x) / nChains if(start > draws.per.chain) start <- 1 if(is.null(end) || end > draws.per.chain || end <= start) end <- draws.per.chain if(start < 1 || end < 1 || thin < 1) stop("Arguments start, end, and thin must be integers > 1") retain <- seq.int(from=start-1+thin, to=end, by=thin) npar <- ncol(x) x_new <- unclass(x) dim(x_new) <- c(draws.per.chain, nChains, npar) x_new <- x_new[retain, , ] mostattributes(x_new) <- attributes(x) attr(x_new, "mcpar") <- NULL dim(x_new) <- c(length(retain)*nChains, npar) colnames(x_new) <- colnames(x) return(x_new) }
wind_parse_hytek <- function(text) { wind_string <- "(?<=[:alpha:]\\s?\\()(\\+|\\-)?\\d\\.\\d|(?<=[:alpha:]\\s?\\()w\\:\\+?\\-?\\d\\.\\d" row_numbs <- text %>% .[stringr::str_detect(., wind_string)] %>% stringr::str_extract_all("\\d{1,}$") if (length(row_numbs) > 0) { minimum_row <- min(as.numeric(row_numbs)) maximum_row <- as.numeric(length(text)) text <- stringr::str_replace_all(text, "(\\)) (\\d)", "\\1 \\2") text <- stringr::str_replace_all(text, "(?<=\\sX)\\s{5,}(?=\\d)", " NA ") suppressWarnings( data_1_wind <- text %>% .[stringr::str_detect(., paste0(wind_string, "|\\s{2}NA\\s{2}"))] %>% stringr::str_replace_all("\n", "") %>% stringr::str_extract_all( wind_string ) %>% stringr::str_remove_all('\\"') %>% stringr::str_replace_all("\\(", " ") %>% stringr::str_replace_all("\\)", " ") %>% stringr::str_remove_all("c") %>% stringr::str_replace_all(",", " ") %>% purrr::map(trimws) ) data_1_wind <- paste(row_numbs, data_1_wind, sep = " ") data_1_wind <- unlist(purrr::map(data_1_wind, stringr::str_split, "\\s{2,}"), recursive = FALSE) data_wind_length_2 <- data_1_wind[purrr::map(data_1_wind, length) == 2] data_wind_length_3 <- data_1_wind[purrr::map(data_1_wind, length) == 3] data_wind_length_4 <- data_1_wind[purrr::map(data_1_wind, length) == 4] data_wind_length_5 <- data_1_wind[purrr::map(data_1_wind, length) == 5] data_wind_length_6 <- data_1_wind[purrr::map(data_1_wind, length) == 6] data_wind_length_7 <- data_1_wind[purrr::map(data_1_wind, length) == 7] data_wind_length_8 <- data_1_wind[purrr::map(data_1_wind, length) == 8] data_wind_length_9 <- data_1_wind[purrr::map(data_1_wind, length) == 9] data_wind_length_10 <- data_1_wind[purrr::map(data_1_wind, length) == 10] if (length(data_wind_length_10) > 0) { df_10_wind <- data_wind_length_10 %>% list_transform() } else { df_10_wind <- data.frame(Row_Numb = character(), stringsAsFactors = FALSE) } if (length(data_wind_length_9) > 0) { df_9_wind <- data_wind_length_9 %>% list_transform() } else { df_9_wind <- data.frame(Row_Numb = character(), stringsAsFactors = FALSE) } if (length(data_wind_length_8) > 0) { df_8_wind <- data_wind_length_8 %>% list_transform() } else { df_8_wind <- data.frame(Row_Numb = character(), stringsAsFactors = FALSE) } if (length(data_wind_length_7) > 0) { df_7_wind <- data_wind_length_7 %>% list_transform() } else { df_7_wind <- data.frame(Row_Numb = character(), stringsAsFactors = FALSE) } if (length(data_wind_length_6) > 0) { df_6_wind <- data_wind_length_6 %>% list_transform() } else { df_6_wind <- data.frame(Row_Numb = character(), stringsAsFactors = FALSE) } if (length(data_wind_length_5) > 0) { df_5_wind <- data_wind_length_5 %>% list_transform() } else { df_5_wind <- data.frame(Row_Numb = character(), stringsAsFactors = FALSE) } if (length(data_wind_length_4) > 0) { df_4_wind <- data_wind_length_4 %>% list_transform() } else { df_4_wind <- data.frame(Row_Numb = character(), stringsAsFactors = FALSE) } if (length(data_wind_length_3) > 0) { df_3_wind <- data_wind_length_3 %>% list_transform() } else { df_3_wind <- data.frame(Row_Numb = character(), stringsAsFactors = FALSE) } if (length(data_wind_length_2) > 0) { df_2_wind <- data_wind_length_2 %>% list_transform() } else { df_2_wind <- data.frame(Row_Numb = character(), stringsAsFactors = FALSE) } data_wind <- dplyr::bind_rows( df_10_wind, df_9_wind, df_8_wind, df_7_wind, df_6_wind, df_5_wind, df_4_wind, df_3_wind, df_2_wind ) %>% lines_sort(min_row = minimum_row) %>% dplyr::mutate(Row_Numb = as.numeric(Row_Numb) - 1) old_names <- names(data_wind)[grep("^V", names(data_wind))] new_names <- paste("Round", seq(1, length(old_names)), "Wind", sep = "_") data_wind <- data_wind %>% dplyr::rename_at(dplyr::vars(old_names), ~ new_names) %>% dplyr::na_if("NA") } else { data_wind <- data.frame(Row_Numb = as.numeric()) } return(data_wind) }
mean1.ttest <- function(x, mu0=0, alternative=c("two.sided","less","greater")){ check_1d(x) check_number(mu0) if (missing(alternative)){ alternative = "two.sided" } else { if (alternative=="g"){ alternative = "greater" } else if (alternative=="t"){ alternative = "two.sided" } else if (alternative=="l"){ alternative = "less" } alternative = match.arg(alternative) } n = length(x) xbar = mean(x) sd = sd(x) t = (xbar-mu0)/(sd/sqrt(n)) if (alternative=="two.sided"){ pvalue = 2*pt(abs(t),(n-1),lower.tail = FALSE) Ha = paste("true mean is different from ",mu0,".",sep="") } else if (alternative=="less"){ pvalue = pt(t,(n-1),lower.tail = TRUE) Ha = paste("true mean is less than ",mu0,".",sep="") } else if (alternative=="greater"){ pvalue = pt(t,(n-1),lower.tail = FALSE) Ha = paste("true mean is greater than ",mu0,".",sep="") } hname = "One-sample Student\'s t-test" thestat = t DNAME = deparse(substitute(x)) names(thestat) = "t" res = list(statistic=thestat, p.value=pvalue, alternative = Ha, method=hname, data.name = DNAME) class(res) = "htest" return(res) }
FCMres <- function(obj){ rasterMode <- class(obj$Data)[[1]] == "list" if(rasterMode){ necessary <- c("Centers", "Data", "m", "algo", "rasters") attrs <- names(obj) if (sum(necessary %in% attrs) < 5){ stop("The attributes Centers, Data, m, algo and rasters are necessary to create an object with class FCMres from raster data (obj$Data is a list, see details in help(FCMres))") } }else{ necessary <- c("Centers", "Belongings", "Data", "m", "algo") attrs <- names(obj) if (sum(necessary %in% attrs) < 5){ stop("The attributes Centers, Data, m, algo and Belongings are necessary to create an object with class FCMres") } obj$Belongings <- tryCatch(as.matrix(obj$Belongings), error = function(e) print("Obj$Belongings must be coercible to a matrix with as.matrix")) } obj$Centers <- tryCatch(as.matrix(obj$Centers), error = function(e) print("Obj$Centers must be coercible to a matrix with as.matrix")) if(rasterMode){ check_raters_dims(obj$Data) datamatrix <- do.call(cbind,lapply(obj$Data, function(band){ raster::values(band) })) missing_pxl <- complete.cases(datamatrix) data_class <- datamatrix[missing_pxl,] obj$Data <- data_class obj$missing <- missing_pxl obj$isRaster <- TRUE if(is.null(obj$rasters) | class(obj$rasters)!="list"){ stop('When using raster data, the slot "raster" in obj must contains a list of the rasterLayers representing the membership values') } belongmat <- do.call(cbind,lapply(obj$rasters, function(band){ raster::values(band) })) belongmat <- belongmat[missing_pxl,] obj$Belongings <- belongmat old_raster <- obj$rasters names(old_raster) <- paste("group",1:length(old_raster)) rst2 <- old_raster[[1]] vec <- rep(NA,times = raster::ncell(rst2)) DF <- as.data.frame(obj$Belongings) vec[obj$missing] <- max.col(DF, ties.method = "first") raster::values(rst2) <- vec old_raster[["Groups"]] <- rst2 obj$rasters <- old_raster }else{ obj$Data <- tryCatch(as.matrix(obj$Data), error = function(e) print("Obj$Data must be coercible to a matrix with as.matrix")) obj$isRaster <- FALSE } obj$k <- ncol(obj$Belongings) if("Groups" %in% attrs == FALSE){ DF <- as.data.frame(obj$Belongings) obj$Groups <- colnames(DF)[max.col(DF, ties.method = "first")] } test <- round(rowSums(obj$Belongings),8) != 1 if(any(test)){ warning("some rows in the membership matrix does not sum up to 1... This should be checked") } class(obj) <- c("FCMres","list") return(obj) } is.FCMres <- function(x){ attrs <- names(x) necessary <- c("Centers", "Belongings", "Data", "m", "algo") if (sum(necessary %in% attrs) < 3){ return(FALSE) } tryCatch({ as.matrix(x$Data) as.matrix(x$Centers) as.matrix(x$Belongings) },error = function(e)return(FALSE)) if(nrow(x$Data) != nrow(x$Belongings)){ return(FALSE) } if(ncol(x$Data) != ncol(x$Centers)){ return(FALSE) } return(TRUE) } print.FCMres <- function(x, ...){ if(x$isRaster){ part1 <- "FCMres object constructed from a raster dataset" part2 <- paste("dimension of the raster : ",x$rasters[[1]]@nrows,"x",x$rasters[[1]]@cols, " and ", nrow(x$Data), " variables",sep="") }else{ part1 <- "FCMres object constructed from a dataframe" part2 <- paste(nrow(x$Data), " observations and ", ncol(x$Data), " variables", sep="") } elements <- c("algo","k", "m", "alpha", "beta") params <- paste(paste(elements, x[elements], sep = "="), collapse = " ; ") part3 <- paste("parameters of the classification: ",params, sep = "") cat(part1,part2,part3,sep="\n") invisible(x) } summarizeClusters <- function(data, belongmatrix, weighted = TRUE, dec = 3, silent=TRUE) { belongmatrix <- as.data.frame(belongmatrix) if (weighted) { Summaries <- lapply(1:ncol(belongmatrix), function(c) { W <- belongmatrix[, c] Values <- apply(data, 2, function(x) { Q5 <- as.numeric(round(reldist::wtd.quantile(x, q = 0.05, na.rm = TRUE, weight = W),dec)) Q10 <- as.numeric(round(reldist::wtd.quantile(x, q = 0.1, na.rm = TRUE, weight = W),dec)) Q25 <- as.numeric(round(reldist::wtd.quantile(x, q = 0.25, na.rm = TRUE, weight = W),dec)) Q50 <- as.numeric(round(reldist::wtd.quantile(x, q = 0.5, na.rm = TRUE, weight = W),dec)) Q75 <- as.numeric(round(reldist::wtd.quantile(x, q = 0.75, na.rm = TRUE, weight = W),dec)) Q90 <- as.numeric(round(reldist::wtd.quantile(x, q = 0.9, na.rm = TRUE, weight = W),dec)) Q95 <- as.numeric(round(reldist::wtd.quantile(x, q = 0.95, na.rm = TRUE, weight = W),dec)) Mean <- as.numeric(round(weighted.mean(x, W),dec)) Std <- round(sqrt(reldist::wtd.var(x, weight=W)),dec) N <- return(list(Q5 = Q5, Q10 = Q10, Q25 = Q25, Q50 = Q50, Q75 = Q75, Q90 = Q90, Q95 = Q95, Mean = Mean, Std = Std)) }) DF <- do.call(cbind, Values) if(silent==FALSE){ print(paste("Statistic summary for cluster ", c, sep = "")) print(DF) } return(DF) }) names(Summaries) <- paste("Cluster_", c(1:ncol(belongmatrix)), sep = "") return(Summaries) } else { Groups <- colnames(belongmatrix)[max.col(belongmatrix, ties.method = "first")] data$Groups <- Groups Summaries <- lapply(unique(data$Groups), function(c) { DF <- subset(data, data$Groups == c) DF$Groups <- NULL Values <- apply(DF, 2, function(x) { Q5 <- as.numeric(round(quantile(x, probs = 0.05, na.rm = TRUE),dec)) Q10 <- as.numeric(round(quantile(x, probs = 0.1, na.rm = TRUE),dec)) Q25 <- as.numeric(round(quantile(x, probs = 0.25, na.rm = TRUE),dec)) Q50 <- as.numeric(round(quantile(x, probs = 0.5, na.rm = TRUE),dec)) Q75 <- as.numeric(round(quantile(x, probs = 0.75, na.rm = TRUE),dec)) Q90 <- as.numeric(round(quantile(x, probs = 0.9, na.rm = TRUE),dec)) Q95 <- as.numeric(round(quantile(x, probs = 0.95, na.rm = TRUE),dec)) Mean <- round(mean(x),dec) Std <- round(sd(x),dec) return(list(Q5 = Q5, Q10 = Q10, Q25 = Q25, Q50 = Q50, Q75 = Q75, Q90 = Q90, Q95 = Q95, Mean = Mean, Std = Std)) }) DF <- do.call(cbind, Values) if(silent==FALSE){ print(paste("Statistic summary for cluster ", c, sep = "")) print(DF) } return(DF) }) names(Summaries) <- paste("Cluster_", c(1:ncol(belongmatrix)), sep = "") return(Summaries) } } summary.FCMres <- function(object, data = NULL, weighted = TRUE, dec = 3, silent=TRUE, ...) { if(is.null(data)){ df <- object$Data }else{ df <- as.matrix(data) } return(summarizeClusters(df, object$Belongings, weighted, dec, silent)) } predict_membership <- function(object, new_data, nblistw = NULL, window = NULL, standardize = TRUE, ...){ if(object$algo %in% c("FCM", "GFCM", "SFCM", "SGFCM") == FALSE){ stop('pred can only be performed for FCMres object if algo is one of "FCM", "GFCM", "SFCM", "SGFCM"') } results <- object if(results$isRaster == TRUE){ check_raters_dims(new_data) old_data <- new_data new_data_tot <- do.call(cbind,lapply(new_data, function(rast){ return(raster::values(rast)) })) missing <- complete.cases(new_data_tot) new_data <- new_data_tot[missing,] } if (standardize){ for (i in 1:ncol(new_data)) { new_data[, i] <- scale(new_data[, i]) } } if(results$algo %in% c("SFCM", "SGFCM")){ if(results$isRaster == FALSE){ if(is.null(nblistw)){ stop("With a spatial clustering method like SFCM or SGFCM, the spatial matrix listw associated with the new dataset must be provided") } wdata <- calcLaggedData(new_data, nblistw, results$lag_method) }else{ if(is.null(window)){ stop("With a spatial clustering method like SFCM or SGFCM, the spatial matrix window to use on the new dataset must be provided") } fun <- results$lag_method if(class(fun) != "function"){ tryCatch(fun <- eval(parse(text=fun)), error = function(e) print("When using rasters, the parameter lag_method must be a function or a string that can be parsed to a function like sum, mean, min, max ..., Note that this function is applied to the pixels values multiplied by the weights in the window.") ) } wdata_total <- do.call(cbind,lapply(dataset, function(band){ wraster <- focal(band, window, fun, na.rm = TRUE, pad = TRUE) return(raster::values(wraster)) })) wdata <- wdata_total[missing,] } } if(results$algo == "FCM"){ pred_values <- calcBelongMatrix(as.matrix(results$Centers), as.matrix(new_data), m = results$m) }else if(results$algo == "GFCM"){ pred_values <- calcFGCMBelongMatrix(as.matrix(results$Centers), as.matrix(new_data), m = results$m, beta = results$beta) }else if(results$algo == "SFCM"){ pred_values <- calcSFCMBelongMatrix(as.matrix(results$Centers), as.matrix(new_data), wdata = as.matrix(wdata), m = results$m, alpha = results$alpha) }else if(results$algo == "SGFCM"){ pred_values <- calcSFGCMBelongMatrix(as.matrix(results$Centers), as.matrix(new_data), wdata = as.matrix(wdata), m = results$m, alpha = results$alpha, beta = results$beta) } if(results$isRaster == FALSE){ return(pred_values) }else{ nc <- raster::ncell(new_data[[1]]) rasters_membership <- lapply(1:ncol(pred_values), function(i){ rast <- old_data[[1]] vec <- rep(NA,times = nc) vec[missing] <- pred_values[,i] raster::values(rast) <- vec return(rast) }) names(rasters_membership) <- paste("group",1:ncol(pred_values), sep = "") return(rasters_membership) } } predict.FCMres <- function(object, new_data, nblistw = NULL, window = NULL, standardize = TRUE, ...){ return(predict_membership(object, new_data, nblistw, window, standardize, ...)) } plot.FCMres <- function(x, type = "spider", ...){ if(type %in% c("bar", "violin","spider") == FALSE){ stop('the parameter type must be one of "bar", "violin","spider" to plot a FCM.res object') } if(type == "bar"){ return(barPlots(x$Data, x$Belongings)) }else if(type == "violin"){ return(violinPlots(x$Data,x$Groups)) }else if(type == "spider"){ return(spiderPlots(x$Data,x$Belongings)) } }
opal.execute <- function(opal, script, async=FALSE) { if(is.list(opal)){ lapply(opal, function(o){opal.execute(o, script, async=async)}) } else { query <- list() if (async) query <- list(async="true") ignore <- .getRSessionId(opal) opal.post(opal, "r", "session", opal$rid, "execute", query=query, body=script, contentType="application/x-rscript", acceptType = "application/octet-stream") } } opal.execute.source <- function(opal, path, async=FALSE) { if (!file.exists(path)) { stop("No file at path: ", path) } if (file.info(path)$isdir) { stop("Cannot source a directory: ", path) } if(is.list(opal)){ lapply(opal, function(o){opal.execute.source(o, path, async=async)}) } else { tmp <- opal.file_mkdir_tmp(opal) opal.file_upload(opal, path, tmp) filename <- basename(path) opal.file_write(opal, paste0(tmp, filename)) opal.file_rm(opal, tmp) script <- paste0("source('", filename, "')") query <- list() if (async) query <- list(async="true") ignore <- .getRSessionId(opal) opal.post(opal, "r", "session", opal$rid, "execute", query=query, body=script, contentType="application/x-rscript", acceptType = "application/octet-stream") } } opal.load_package <- function(opal, pkg) { resp <- opal.execute(opal, paste('library("', pkg, '")', sep='')) } opal.unload_package <- function(opal, pkg) { resp <- opal.execute(opal, paste('detach("package:', pkg, '", character.only=TRUE, unload=TRUE)', sep='')) }
print.boin<-function(x,...){ print.default(x) }
kmeans.start <- function (x, g, subclasses) { cnames <- levels(g <- factor(g)) J <- length(cnames) g <- as.numeric(g) weights <- as.list(cnames) names(weights) <- cnames subclasses <- rep(subclasses, length = length(cnames)) R <- sum(subclasses) cl <- rep(seq(J), subclasses) cx <- x[seq(R), , drop = FALSE] for (j in seq(J)) { nc <- subclasses[j] which <- cl == j xx <- x[g == j, , drop = FALSE] if ((nc <= 1) || (nrow(xx) <= nc)) { cx[which, ] <- apply(xx, 2, mean) wmj <- matrix(1, sum(g == j), 1) } else { start=nc TT <- kmeans(xx, start) cx[which, ] <- TT$centers wmj <- diag(nc)[TT$cluster, ] } dimnames(wmj) <- list(NULL, paste("s", seq(dim(wmj)[2]), sep = "")) weights[[j]] <- wmj } list(x = cx, cl = factor(cl, labels = cnames), weights = weights) }
set_survey_vars <- function( .svy, x, name = "__SRVYR_TEMP_VAR__", add = FALSE ) { out <- .svy if (length(x) != nrow(.svy)) { cur_group_rows <- group_rows(cur_svy_full())[[cur_group_id()]] if (length(x) == length(cur_group_rows)) { x_stretched <- rep(FALSE, nrow(.svy)) x_stretched[cur_group_rows] <- x x <- x_stretched } } if (inherits(.svy, "twophase2")) { if (!add) { out$phase1$sample$variables <- select(out$phase1$sample$variables, dplyr::one_of(group_vars(out))) } out$phase1$sample$variables[[name]] <- x } else { if (!add) { out$variables <- select(out$variables, dplyr::one_of(group_vars(out))) } out$variables[[name]] <- x } out } get_var_est <- function( stat, vartype, grps = "", level = 0.95, df = Inf, pre_calc_ci = FALSE, deff = FALSE ) { out_width <- 1 out <- lapply(vartype, function(vvv) { if (vvv == "se") { se <- survey::SE(stat) if (!inherits(se, "data.frame")) { se <- data.frame(matrix(se, ncol = out_width)) } names(se) <- "_se" se } else if (vvv == "ci" && !pre_calc_ci) { if (length(level) == 1) { ci <- data.frame(matrix( stats::confint(stat, level = level, df = df), ncol = 2 * out_width )) names(ci) <- c("_low", "_upp") } else { lci <- lapply(level, function(x) {as.data.frame(stats::confint(stat,level = x, df = df))}) ci <- dplyr::bind_cols(lci) names(ci) <- paste0(c("_low", "_upp"), rep(level, each = 2) * 100) } ci } else if (vvv == "ci" && pre_calc_ci) { if (inherits(stat, "data.frame")) { ci <- data.frame(stat[c("ci_l", "ci_u")]) names(ci) <- c("_low", "_upp") } else { ci <- data.frame(matrix(stats::confint(stat), ncol = 2 * out_width)) names(ci) <- c("_low", "_upp") } ci } else if (vvv == "var") { var <- data.frame(matrix(survey::SE(stat) ^ 2, ncol = out_width)) names(var) <- "_var" var } else if (vvv == "cv") { cv <- data.frame((matrix(survey::cv(stat), ncol = out_width))) names(cv) <- "_cv" cv } else { stop(paste0("Unexpected vartype ", vvv)) } }) coef <- data.frame(matrix(coef(stat), ncol = out_width)) names(coef) <- "coef" out <- c(list(coef), out) if (!identical(grps, "")) { out <- c(list(as.data.frame(stat[grps], stringsAsFactors = FALSE)), out) } if (!isFALSE(deff)) { deff <- data.frame(matrix(survey::deff(stat), ncol = out_width)) names(deff) <- "_deff" out <- c(out, list(deff)) } as_srvyr_result_df(dplyr::bind_cols(out)) } get_var_est_quantile <- function(stat, vartype, q, grps = "", level = 0.95, df = Inf) { qnames <- paste0("_q", gsub("\\.", "", formatC(q * 100, width = 2, flag = "0"))) out_width <- length(qnames) out <- lapply(vartype, function(vvv) { if (vvv == "se") { se <- survey::SE(stat) if (!inherits(se, "data.frame")) { se <- data.frame(matrix(se, ncol = out_width)) } names(se) <- paste0(qnames, "_se") se } else if (vvv == "ci") { if (inherits(stat, "data.frame")) { ci_cols <- grep("^ci_[lu]", names(stat)) ci <- data.frame(stat[, ci_cols]) } else { ci <- data.frame(matrix(stats::confint(stat), ncol = 2 * out_width)) } names(ci) <- paste0(qnames, rep(c("_low", "_upp"), each = out_width)) ci } else if (vvv == "var") { var <- data.frame(matrix(survey::SE(stat) ^ 2, ncol = out_width)) names(var) <- paste0(qnames, "_var") var } else if (vvv == "cv") { cv <- data.frame((matrix(survey::cv(stat), ncol = out_width))) names(cv) <- paste0(qnames, "_cv") cv } else { stop(paste0("Unexpected vartype ", vvv)) } }) coef <- data.frame(matrix(coef(stat), ncol = out_width)) names(coef) <- qnames out <- lapply(out, as.data.frame) out <- c(list(coef), out) if (!identical(grps, "")) { out <- c(list(as.data.frame(stat[grps])), out) } as_srvyr_result_df(dplyr::bind_cols(out)) } stop_for_factor <- function(x) { if (is.factor(x)) { stop(paste0( "Factor not allowed in survey functions, should be used as a grouping variable." ), call. = FALSE) } else if (is.character(x)) { stop(paste0( "Character vectors not allowed in survey functions, should be used as a grouping variable." ), call. = FALSE) } } as_srvyr_result_df <- function(x) { class(x) <- c("srvyr_result_df", class(x)) x } is_srvyr_result_df <- function(x) { inherits(x, "srvyr_result_df") } Math.srvyr_result_df <- function(x, ...) { out <- NextMethod("Math", x) class(out) <- c("srvyr_result_df", class(out)) out } Ops.srvyr_result_df <- function(e1, e2) { out <- NextMethod() class(out) <- c("srvyr_result_df", class(out)) out } cur_svy_wts <- function() { cur_svy_env$split[[dplyr::cur_group_id()]][['pweights']] %||% (1/cur_svy_env$split[[dplyr::cur_group_id()]][['prob']]) }
claw <- function(xx) { x <- xx[1] y <- (0.46*(dnorm(x,-1.0,2.0/3.0) + dnorm(x,1.0,2.0/3.0)) + (1.0/300.0)*(dnorm(x,-0.5,.01) + dnorm(x,-1.0,.01) + dnorm(x,-1.5,.01)) + (7.0/300.0)*(dnorm(x,0.5,.07) + dnorm(x,1.0,.07) + dnorm(x,1.5,.07))) return(y) } library("rgenoud") claw1 <- genoud(claw, nvars=1, max=TRUE, pop.size=3000)
p <- 4 f <- function(th) drop(-sin(th / 2) * sin(th)^(p - 2)) I <- integrate(f, lower = 0, upper = pi, rel.tol = 1e-12)$value test_that("Gauss_Legen for N = 5, 10, 20, ..., 2560, 5120", { expect_equal(sum(Gauss_Legen_weights(a = 0, b = pi, N = 5) * f(Gauss_Legen_nodes(a = 0, b = pi, N = 5))), I, tolerance = 1e-3) expect_equal(sum(Gauss_Legen_weights(a = 0, b = pi, N = 10) * f(Gauss_Legen_nodes(a = 0, b = pi, N = 10))), I, tolerance = 1e-12) for (N in c(10 * 2^(1:9))) { expect_equal(sum(Gauss_Legen_weights(a = 0, b = pi, N = N) * f(Gauss_Legen_nodes(a = 0, b = pi, N = N))), I, tolerance = 3e-14) } }) test_that("Gauss_Legen edge cases", { expect_error(Gauss_Legen_weights(a = 0, b = pi, N = 19)) expect_error(Gauss_Legen_nodes(a = 0, b = pi, N = 19)) })
test_that("multi_chrBound checks if input is empty", { x <- data.frame() expect_error(multi_chrBound(x), "input has 0 rows") }) test_that("multi_chrBound correctly formats data", { x <- GenVisR::cytoGeno[GenVisR::cytoGeno$genome == 'hg19',] out <- multi_chrBound(x) expect_equal(nrow(out[out$chromosome == 'chr1',]), 2) expect_equal(out$start, out$end) })
judge_123 <- function(x){ x=x[!is.na(x)] if (length(x)==1) return(TRUE) for (i in 1:(length(x)-1)) { if (x[i] > x[i+1]) return(FALSE) } return(TRUE) } judge_321 <- function(x){ x=x[!is.na(x)] if (length(x)==1) return(TRUE) for (i in 1:(length(x)-1)) { if (x[i] < x[i+1]) return(FALSE) } return(TRUE) }
test_that("Variable names are labeled", { skip_on_cran() skip_if_offline() expect_equal(label_eurostat_vars("geo"), "Geopolitical entity (reporting)") expect_equal(label_eurostat_vars("housing", lang = "fr"), "Habitation") expect_true(any(grepl( "_code", names(label_eurostat( get_eurostat("road_eqr_trams"), code = "geo" )) ))) }) test_that("Label ordering is ordered", { skip_on_cran() skip_if_offline() expect_equal( c( "European Union - 28 countries (2013-2020)", "Finland", "United States" ), levels(label_eurostat(factor(c("FI", "US", "EU28")), dic = "geo", eu_order = TRUE )) ) }) test_that("Countrycodes are labelled for factors", { skip_on_cran() skip_if_offline() expect_equal( levels(label_eurostat(factor(c("FI", "DE", "EU28"), c("FI", "DE", "EU28")), dic = "geo", countrycode = "country.name" )), c("Finland", "Germany", "EU28") ) }) test_that("Countrycodes return NA for countrycode_nomatch = NA", { skip_on_cran() skip_if_offline() expect_equal( suppressWarnings(label_eurostat(c("FI", "DE", "EU28"), dic = "geo", countrycode = "country.name", countrycode_nomatch = NA )), c("Finland", "Germany", NA) ) }) test_that("Countrycodes use eurostat for missing", { skip_on_cran() skip_if_offline() expect_equal( suppressWarnings(label_eurostat(c("FI", "DE", "EU28"), dic = "geo", countrycode = "country.name", countrycode_nomatch = "eurostat" )), c("Finland", "Germany", "European Union - 28 countries (2013-2020)") ) }) test_that("custom_dic works", { skip_on_cran() skip_if_offline() expect_equal( label_eurostat(c("FI", "DE"), dic = "geo", custom_dic = c(DE = "Germany")), c("Finland", "Germany") ) })
util_looks_like_missing <- function(x, n_rules = 1) { if (any(DATA_TYPES_OF_R_TYPE[[class(x)]] %in% c(DATA_TYPES$INTEGER, DATA_TYPES$FLOAT))) { x <- as.numeric(x) } if (!is.numeric(x)) { util_error("%s works only on numeric vectors", dQuote("util_looks_like_missing")) } sysmiss <- !is.finite(x) if (all(sysmiss)) { return(!logical(length = length(x))) } TYPICAL_MISSINGCODES <- c( 99, 999, 9999, 99999, 999999, 9999999, 999999999 ) .x <- abs(x) .x <- gsub("8", "9", .x, fixed = TRUE) .x <- gsub(".", "", .x, fixed = TRUE) .x <- gsub("^0+", "", .x) .x <- gsub("0+$", "", .x) r <- .x %in% TYPICAL_MISSINGCODES tuk <- util_tukey(x) tuk[sysmiss] <- 0 ssig <- util_sixsigma(x) ssig[sysmiss] <- 0 hub <- util_hubert(x) hub[sysmiss] <- 0 sigg <- util_sigmagap(x) sigg[sysmiss] <- 0 return( sysmiss | (r & (tuk + ssig + hub + sigg >= n_rules)) ) }
"simm.bb" <- function(date=1:100, begin = c(0,0), end=begin, id="A1", burst=id, proj4string=CRS()) { if (!inherits(date, "POSIXct")) { class(date) <- c("POSIXct", "POSIXt") attr(date, "tzone") <- "" } n <- length(date) dt <- c(diff(unclass(date)),NA) dx <- c(rnorm(n-1,0,sqrt(dt[-n])),NA) dy <- c(rnorm(n-1,0,sqrt(dt[-n])),NA) W <- cbind(dx,dy) xtmp <- begin x <- begin for (i in 2:(n-1)) { a <- diag(1/(unclass(date[n])-unclass(date[i-1])),2) dX <- as.numeric((a%*%(end - xtmp)*dt[i-1] + W[i-1,])) x <- rbind(x,xtmp+dX) xtmp <- xtmp+dX } x <- rbind(x,end) res <- as.ltraj(data.frame(x[,1],x[,2]),date, id, burst, typeII=TRUE, proj4string=proj4string) return(res) }
f_mlta <- function(S, counts, G, D, tol, maxiter, pdGH) { Ns <- nrow(S) N <- sum(counts) M <- ncol(S) rownames(S) <- NULL eta <- rep(1 / G, G) p <- matrix(1 / M, G, M) lab <- sample(1:G, prob = eta, size = Ns, replace = TRUE) z <- counts * cls(lab) eta <- colSums(z) / N xi <- array(20, c(Ns, M, G)) sigma_xi <- 1 / (1 + exp(-xi)) lambda_xi <- (0.5 - sigma_xi) / (2 * xi) w <- array(rnorm(M * D * G), c(D, M, G)) b <- matrix(rnorm(M, G), G, M) C <- array(0, c(D, D, Ns, G)) mu <- array(0, c(Ns, D, G)) lxi <- matrix(0, G, Ns) v <- matrix(0, Ns, G) ll <- -Inf diff <- 1 iter <- 0 xin <- xi while (diff > tol & iter < maxiter) { iter <- iter + 1 ll_old <- ll if (D == 1) { for (g in 1:G) { w[, , g] <- as.matrix(t(w[, , g])) C[, , , g] <- 1 / (1 - 2 * rowSums(sweep(lambda_xi[, , g], MARGIN = 2, w[, , g] ^ 2, `*`))) mu[, , g] <- C[, , , g] * rowSums(sweep( S - 0.5 + 2 * sweep(lambda_xi[, , g], MARGIN = 2, b[g, ], `*`), MARGIN = 2, w[, , g], `*` )) mu[, , g] <- matrix(mu[, , g], Ns, D) YY <- matrix(C[, , , g] + mu[, , g] ^ 2, ncol = 1) xi[, , g] <- YY %*% (w[, , g] ^ 2) + mu[, , g] %*% t(2 * b[g, ] * w[, , g]) + matrix(b[g, ] ^ 2, nrow = Ns, ncol = M, byrow = TRUE) xi[, , g] <- sqrt(xi[, , g]) sigma_xi[, , g] <- 1 / (1 + exp(-xi[, , g])) lambda_xi[, , g] <- (0.5 - sigma_xi[, , g]) / (2 * xi[, , g]) YYh <- z[, g] * 2 * cbind(c(YY), mu[, , g], mu[, , g], 1) den <- t(YYh) %*% lambda_xi[, , g] num <- rbind(c(mu[, , g]), 1) %*% (z[, g] * (S - 0.5)) wh <- apply(rbind(den, num), 2, function(x) - crossprod(solve(matrix(x[1:4], 2, 2)), x[5:6])) w[, , g] <- wh[1:D, ] w[, , g] <- as.matrix(t(w[, , g])) b[g, ] <- wh[D + 1, ] lxi[g, ] <- 0.5 * log(C[, , , g]) + c(mu[, , g]) ^ 2 / (2 * C[, , , g]) + rowSums( log(sigma_xi[, , g]) - 0.5 * xi[, , g] - lambda_xi[, , g] * xi[, , g] ^ 2 + sweep(lambda_xi[, , g], MARGIN = 2, b[g, ] ^ 2, `*`) + sweep(S - 0.5, MARGIN = 2, b[g, ], `*`) ) } v <- t(eta * exp(lxi)) v[is.nan(v)] <- 0 vsum <- rowSums(v) z <- counts * v / vsum ll <- sum(counts * log(vsum)) eta <- colSums(z) / N diff <- sum(abs(ll - ll_old)) } if (D == 2) { for (g in 1:G) { C2 <- apply(lambda_xi[, , g], 1, function(x) solve(diag(D) - 2 * crossprod(x * t(w[, , g]), t(w[, , g])))) C[, , , g] <- array(C2, c(D, D, Ns)) mu[, , g] <- t(apply(rbind(C2, w[, , g] %*% t( S - 0.5 + 2 * sweep(lambda_xi[, , g], MARGIN = 2, b[g, ], `*`) )), 2, function(x) matrix(x[1:4], nrow = D) %*% (x[-(1:4)]))) YY <- C2 + apply(mu[, , g], 1, tcrossprod) xi[, , g] <- t( apply(YY, 2, function(x) rowSums(( t(w[, , g]) %*% matrix(x, ncol = D) ) * t(w[, , g]))) + (2 * b[g, ] * t(w[, , g])) %*% t(mu[, , g]) + matrix( b[g, ] ^ 2, nrow = M, ncol = Ns, byrow = FALSE ) ) xi[, , g] <- sqrt(xi[, , g]) sigma_xi[, , g] <- 1 / (1 + exp(-xi[, , g])) lambda_xi[, , g] <- (0.5 - sigma_xi[, , g]) / (2 * xi[, , g]) YYh <- z[, g] * 2 * cbind(YY[1, ], YY[2, ], mu[, 1, g], YY[3, ], YY[4, ], mu[, 2, g], mu[, 1, g], mu[, 2, g], 1) den <- t(YYh) %*% lambda_xi[, , g] num <- rbind(t(mu[, , g]), 1) %*% { z[, g] * { S - 0.5 } } wh <- apply(rbind(den, num), 2, function(x) - crossprod(solve(matrix(x[1:9], 3, 3)), x[10:12])) w[, , g] <- wh[1:D, ] w[, , g] <- as.matrix(w[, , g]) b[g, ] <- wh[D + 1, ] detC <- C2[1, ] * C2[4, ] - C2[3, ] * C2[2, ] lxi[g, ] <- 0.5 * log(detC) + 0.5 * apply(rbind(C2[4, ] / detC, -C2[2, ] / detC, -C2[3, ] / detC, C2[1, ] / detC, t(mu[, , g])), 2, function(x) t((x[-{ 1:4 }])) %*% matrix(x[1:4], nrow = D) %*% (x[-{ 1:4 }])) + rowSums( log(sigma_xi[, , g]) - 0.5 * xi[, , g] - lambda_xi[, , g] * { xi[, , g] ^ 2 } + sweep(lambda_xi[, , g], MARGIN = 2, b[g, ] ^ 2, `*`) + sweep(S - 0.5, MARGIN = 2, b[g, ], `*`) ) } v <- t(eta * exp(lxi)) v[is.nan(v)] <- 0 vsum <- rowSums(v) z <- counts * v / vsum ll <- sum(counts * log(vsum)) eta <- colSums(z) / N diff <- sum(abs(ll - ll_old)) } if (D > 2) { for (g in 1:G) { C2 <- apply(lambda_xi[, , g], 1, function(x) solve(diag(D) - 2 * crossprod(x * t(w[, , g]), t(w[, , g])))) C[, , , g] <- array(C2, c(D, D, Ns)) mu[, , g] <- t(apply(rbind(C2, w[, , g] %*% t( S - 0.5 + 2 * sweep(lambda_xi[, , g], MARGIN = 2, b[g, ], `*`) )), 2, function(x) matrix(x[1:(D * D)], nrow = D) %*% ( x[-(1:(D * D))]))) YY <- C2 + apply(mu[, , g], 1, tcrossprod) xi[, , g] <- t( apply(YY, 2, function(x) rowSums((t(w[, , g]) %*% matrix(x, ncol = D)) * t(w[, , g]))) + (2 * b[g, ] * t(w[, , g])) %*% t(mu[, , g]) + matrix(b[g, ] ^ 2, nrow = M, ncol = Ns, byrow = FALSE) ) xi[, , g] <- sqrt(xi[, , g]) sigma_xi[, , g] <- 1 / (1 + exp(-xi[, , g])) lambda_xi[, , g] <- (0.5 - sigma_xi[, , g]) / (2 * xi[, , g]) YYh <- sweep(buildYYh(YY, t(mu[, , g]), D, Ns), MARGIN = 2, 2 * z[, g], `*`) den <- (YYh) %*% lambda_xi[, , g] num <- rbind(t(mu[, , g]), 1) %*% (z[, g] * (S - 0.5)) wh <- apply(rbind(den, num), 2, function(x) - crossprod(solve(matrix(x[1:((D + 1) * (D + 1))], D + 1, D + 1)), x[-(1:((D + 1) * (D + 1)))])) w[, , g] <- wh[1:D, ] w[, , g] <- as.matrix(w[, , g]) b[g, ] <- wh[D + 1, ] detC <- apply(C2, 2, function(x) det(matrix(x, D, D))) lxi[g, ] <- 0.5 * log(detC) + 0.5 * apply(rbind(C2, t(mu[, , g])), 2, function(x) t((x[-(1:(D * D))])) %*% solve(matrix(x[1:(D * D)], nrow = D)) %*% (x[-(1:(D * D))])) + rowSums( log(sigma_xi[, , g]) - 0.5 * xi[, , g] - lambda_xi[, , g] * (xi[, , g] ^ 2) + sweep(lambda_xi[, , g], MARGIN = 2, b[g, ] ^ 2, `*`) + sweep(S - 0.5, MARGIN = 2, b[g, ], `*`) ) } v <- t(eta * exp(lxi)) v[is.nan(v)] <- 0 vsum <- rowSums(v) z <- counts * v / vsum ll <- sum(counts * log(vsum)) eta <- colSums(z) / N diff <- sum(abs(ll - ll_old)) } } npoints <- round(pdGH ^ (1 / D)) ny <- npoints ^ D GaHer <- glmmML::ghq(npoints, FALSE) Ygh <- expand.grid(rep(list(GaHer$zeros), D)) Ygh <- as.matrix(Ygh) Wgh <- apply(as.matrix(expand.grid(rep( list(GaHer$weights), D ))), 1, prod) * apply(exp(Ygh ^ 2), 1, prod) Hy <- apply(Ygh, 1, mvtnorm::dmvnorm) Beta <- Hy * Wgh / sum(Hy * Wgh) fxy <- array(0, c(Ns, ny, G)) for (g in 1:G) { if (D == 1) { Agh <- t(tcrossprod(w[, , g], Ygh) + b[g, ]) } else{ Agh <- t(tcrossprod(t(w[, , g]), Ygh) + b[g, ]) } pgh <- 1 / (1 + exp(-Agh)) fxy[, , g] <- exp(tcrossprod(S, log(pgh)) + tcrossprod(1 - S, log(1 - pgh))) fxy[is.nan(fxy[, , g])] <- 0 } eta <- as.vector(eta) LLva <- ll BICva <- -2 * LLva + (G * (M * (D + 1) - D * (D - 1) / 2) + G - 1) * log(N) llGH1 <- apply(rep(Beta, each = Ns) * fxy, c(1, 3), sum) LL <- sum(counts * log(colSums(eta * t(llGH1)))) BIC <- -2 * LL + (G * (M * (D + 1) - D * (D - 1) / 2) + G - 1) * log(N) expected <- colSums(eta * t(llGH1)) * N rownames(b) <- NULL colnames(b) <- colnames(b, do.NULL = FALSE, prefix = "Item ") rownames(b) <- rownames(b, do.NULL = FALSE, prefix = "Group ") rownames(w) <- rownames(w, do.NULL = FALSE, prefix = "Dim ") colnames(w) <- colnames(w, do.NULL = FALSE, prefix = "Item ") dimnames(w)[[3]] <- paste("Group ", seq(1, G) , sep = '') eta <- matrix(eta, byrow = T, G) rownames(eta) <- rownames(eta, do.NULL = FALSE, prefix = "Group ") colnames(eta) <- "eta" names(LLva) <- c("Log-Likelihood (variational approximation):") names(BICva) <- c("BIC (variational approximation):") names(LL) <- c("Log-Likelihood (G-H Quadrature correction):") names(BIC) <- c("BIC (G-H Quadrature correction):") out <- list( b = b, w = w, eta = eta, mu = mu, C = C, z = z, LL = LL, BIC = BIC, LLva = LLva, BICva = BICva, expected = expected ) out }
dist2 <- function(X) { D2 <- rowSums(X * X) D2 + sweep(X %*% t(X) * -2, 2, t(D2), `+`) } safe_dist2 <- function(X) { D2 <- dist2(X) D2[D2 < 0] <- 0 D2 } x2d <- function(X) { sqrt(safe_dist2(x2m(X))) } c2y <- function(...) { matrix(unlist(list(...)), ncol = 2) } iris10 <- NULL iris10_Y <- NULL diris10 <- NULL dmiris10 <- NULL dmiris10z <- NULL ycat <- NULL ycat2 <- NULL ynum <- NULL ynum2 <- NULL nn <- NULL create_data <- function() { iris10 <<- x2m(iris[1:10, ]) iris10_Y <<- pca_init(iris10, ndim = 2) diris10 <<- dist(iris10) dmiris10 <<- as.matrix(diris10) dmiris10zl <- dmiris10 dmiris10zl[dmiris10zl > 0.71] <- 0 dmiris10z <<- Matrix::drop0(dmiris10zl) ycat <<- as.factor(c(levels(iris$Species)[rep(1:3, each = 3)], NA)) ycat2 <<- as.factor(c(NA, levels(iris$Species)[rep(1:3, times = 3)])) ynum <<- (1:10) / 10 ynum2 <<- seq(from = 10, to = -10, length.out = 10) / 100 nnl <- find_nn(iris10, k = 4, method = "fnn", metric = "euclidean", n_threads = 0, verbose = FALSE) row.names(nnl$idx) <- row.names(iris10) row.names(nnl$dist) <- row.names(iris10) nn <<- nnl } expect_ok_matrix <- function(res, nr = 10, nc = 2) { expect_is(res, "matrix") expect_equal(nrow(res), nr) expect_equal(ncol(res), nc) expect_false(any(is.infinite(res))) } expect_is_nn <- function(res, nr = 10, k = 4) { expect_is(res, "list") expect_is_nn_matrix(res$dist, nr, k) expect_is_nn_matrix(res$idx, nr, k) } expect_is_nn_matrix <- function(res, nr = 10, k = 4) { expect_is(res, "matrix") expect_equal(nrow(res), nr) expect_equal(ncol(res), k) } create_data()
getP.Cnaive <- function(x, y , z = NULL){ if(is.null(z)) { result <- .C("getPR", as.double(x), as.double(y), as.integer(length(x)), as.integer(length(y)),result=as.double(1))$result } else { result <- .C("getPTripR", as.double(x), as.double(y), as.double(z), as.integer(length(x)), as.integer(length(y)), as.integer(length(z)),result=as.double(1))$result } result } permObs2.C <- function(x, y){ nx <- length(x) ny <- length(y) res <- .C("permObs2R", as.double(x), as.double(y), as.integer(nx), as.integer(ny),result=double(nx+ny))$result xOut <- res[1:nx] yOut <- res[(nx+1):(nx+ny)] return(list(x=xOut,y=yOut)) } uit.C <- function(x, y, z){ .C("uitR", as.double(x), as.double(y), as.double(z), as.integer(length(x)), as.integer(length(y)), as.integer(length(z)),result=double(5))$result[1] } getRho.C <- function(x, y, z){ .C("getRhoR", as.integer(length(x)), as.integer(length(y)), as.integer(length(z)),result=double(6))$result[1] } getP.Csub <- function(x,y,z,nper){ .Call( "subMat", c(x, y, z), length(x), length(y),length(z), nper)$result }
require(bvpSolve) measel <- function(t, y, pars, vv) { bet <- 1575*(1+cos(2*pi*t)) dy1 <- mu-bet*y[1]*y[3] dy2 <- bet*y[1]*y[3]-y[2]/lam dy3 <-y[2]/lam-y[3]/vv dy4 <- 0 dy5 <-0 dy6 <-0 list(c(dy1, dy2, dy3, dy4, dy5, dy6)) } dmeasel <- function(t, y, pars, vv) { df <- matrix (data = 0, nrow = 6, ncol = 6) bet <- 1575*(1+cos(2*pi*t)) df[1,1] <- -bet*y[3] df[1,3] <- -bet*y[1] df[2,1] <- bet*y[3] df[2,2] <- -1/lam df[2,3] <- bet*y[1] df[3,2] <- 1/lam df[3,3] <- -1/vv return(df) } bound <- function(i, y, pars,vv) { if ( i == 1 | i == 4) return(y[1]-y[4]) if ( i == 2 | i == 5) return(y[2]-y[5]) if ( i == 3 | i == 6) return(y[3]-y[6]) } dbound <- function(i, y, pars,vv) { if ( i == 1 | i == 4) return(c(1,0,0,-1,0,0)) if ( i == 2 | i == 5) return(c(0,1,0,0,-1,0)) if ( i == 3 | i == 6) return(c(0,0,1,0,0,-1)) } mu <- 0.02 lam <- 0.0279 v <- 0.1 x <- seq (0, 1, by = 0.01) yguess <- matrix(ncol = length(x), nrow = 6, data = 1) rownames(yguess) <- paste("y", 1:6, sep = "") print(system.time( solR <- bvptwp(fun = measel, bound = bound, xguess = x, yguess = yguess, x=x, leftbc = 3, vv = v, ncomp = 6, nmax = 100000, atol = 1e-4) )) plot(sol)
make.mkn <- function(tree, states, k, strict=TRUE, control=list()) { control <- check.control.mkn(control, k) cache <- make.cache.mkn(tree, states, k, strict, control) all.branches <- make.all.branches.mkn(cache, control) rootfunc <- rootfunc.mkn f.pars <- make.pars.mkn(k) ll <- function(pars, root=ROOT.OBS, root.p=NULL, intermediates=FALSE) { qmat <- f.pars(pars) ans <- all.branches(qmat, intermediates) rootfunc(ans, qmat, root, root.p, intermediates) } class(ll) <- c("mkn", "dtlik", "function") ll } make.mk2 <- function(tree, states, strict=TRUE, control=list()) make.mkn(tree, states + 1, 2, strict, check.control.mk2(control)) make.info.mkn <- function(k, phy) { list(name="mkn", name.pretty="Mk(n)", np=as.integer(k * k), argnames=default.argnames.mkn(k), ny=as.integer(k), k=as.integer(k), idx.e=integer(0), idx.d=seq_len(k), phy=phy, ml.default="subplex", mcmc.lowerzero=TRUE, doc=NULL, reference=c( "Pagel (1994)", "Lewis (2001)")) } default.argnames.mkn <- function(k) { base <- ceiling(log10(k + .5)) fmt <- sprintf("q%%0%dd%%0%dd", base, base) sprintf(fmt, rep(1:k, each=k-1), unlist(lapply(1:k, function(i) (1:k)[-i]))) } make.info.mk2 <- function(phy) { info <- make.info.mkn(2, phy) info$name <- "mk2" info$name.pretty <- "Mk2" info$argnames <- default.argnames.mk2() info } default.argnames.mk2 <- function() c("q01", "q10") make.cache.mkn <- function(tree, states, k, strict, control) { method <- control$method tree <- check.tree(tree) if ( !is.null(states) ) states <- check.states(tree, states, strict=strict, strict.vals=1:k) cache <- make.cache(tree) if ( method == "mk2" ) cache$info <- make.info.mk2(tree) else cache$info <- make.info.mkn(k, tree) cache$states <- states if ( method == "ode" ) { cache$info$derivs <- derivs.mkn.ode cache$y <- initial.tip.mkn.ode(cache) cache$info$name.ode <- "mknode" } else if ( method == "" ) { cache$info$name.ode <- "mknpij" } cache } initial.conditions.mkn <- function(init, pars, t, idx) { init[,1] * init[,2] } rootfunc.mkn <- function(res, pars, root, root.p, intermediates) { d.root <- res$vals lq <- res$lq k <- length(d.root) root.p <- root.p.calc(d.root, pars, root, root.p, stationary.freq.mkn) if ( root == ROOT.ALL ) loglik <- log(d.root) + sum(lq) else loglik <- log(sum(root.p * d.root)) + sum(lq) if ( intermediates ) { res$root.p <- root.p attr(loglik, "intermediates") <- res attr(loglik, "vals") <- d.root } loglik } make.all.branches.mkn <- function(cache, control) { if ( control$method == "ode" ) { if ( !is.null(control$backend) && control$backend == "expokit" ) make.all.branches.mkn.expokit(cache, control) else make.all.branches.dtlik(cache, control, initial.conditions.mkn) } else { make.all.branches.mkn.pij(cache, control) } } stationary.freq.mkn <- function(pars) { stop("Needs testing") if ( length(pars) == 2 ) pars[2:1] / sum(pars) else .NotYetImplemented() } make.pars.mkn <- function(k) { qmat <- matrix(0, k, k) idx <- cbind(rep(1:k, each=k-1), unlist(lapply(1:k, function(i) (1:k)[-i]))) npar <- k*(k-1) function(pars) { check.pars.nonnegative(pars, npar) qmat[idx] <- pars diag(qmat) <- -rowSums(qmat) qmat } } mkn.Q <- function(pars, k) { if ( missing(k) ) k <- (1 + sqrt(1 + 4*(length(pars))))/2 if ( abs(k - round(k)) > 1e-6 || length(pars) != k*(k-1) ) stop("Invalid parameter length") make.pars.mkn(k)(pars) } check.control.mkn <- function(control, k) { control <- modifyList(list(method="pij"), control) if ( control$method == "mk2" && k != 2 ) stop("Method 'mk2' only valid when k=2") methods <- c("pij", "mk2", "ode") if ( !(control$method %in% methods) ) stop(sprintf("control$method must be in %s", paste(methods, collapse=", "))) control } check.control.mk2 <- function(control) { control <- modifyList(list(method="mk2"), control) if ( control$method != "mk2" ) stop("Invalid control$method value (just omit it)") control }
stat.anova <- function(table, test=c("Rao","LRT","Chisq", "F", "Cp"), scale, df.scale, n) { test <- match.arg(test) dev.col <- match("Deviance", colnames(table)) if (test == "Rao") dev.col <- match("Rao", colnames(table)) if (is.na(dev.col)) dev.col <- match("Sum of Sq", colnames(table)) switch(test, "Rao" = ,"LRT" = ,"Chisq" = { dfs <- table[, "Df"] vals <- table[, dev.col]/scale * sign(dfs) vals[dfs %in% 0] <- NA vals[!is.na(vals) & vals < 0] <- NA cbind(table, "Pr(>Chi)" = pchisq(vals, abs(dfs), lower.tail = FALSE) ) }, "F" = { dfs <- table[, "Df"] Fvalue <- (table[, dev.col]/dfs)/scale Fvalue[dfs %in% 0] <- NA Fvalue[!is.na(Fvalue) & Fvalue < 0] <- NA cbind(table, F = Fvalue, "Pr(>F)" = pf(Fvalue, abs(dfs), df.scale, lower.tail = FALSE) ) }, "Cp" = { if ("RSS" %in% names(table)) { cbind(table, Cp = table[, "RSS"] + 2*scale*(n - table[, "Res.Df"])) } else { cbind(table, Cp = table[, "Resid. Dev"] + 2*scale*(n - table[, "Resid. Df"])) } }) } printCoefmat <- function(x, digits = max(3L, getOption("digits") - 2L), signif.stars = getOption("show.signif.stars"), signif.legend = signif.stars, dig.tst = max(1L, min(5L, digits - 1L)), cs.ind = 1:k, tst.ind = k+1, zap.ind = integer(), P.values = NULL, has.Pvalue = nc >= 4 && substr(colnames(x)[nc], 1, 3) == "Pr(", eps.Pvalue = .Machine$double.eps, na.print = "NA", ...) { if(is.null(d <- dim(x)) || length(d) != 2L) stop("'x' must be coefficient matrix/data frame") nc <- d[2L] if(is.null(P.values)) { scp <- getOption("show.coef.Pvalues") if(!is.logical(scp) || is.na(scp)) { warning("option \"show.coef.Pvalues\" is invalid: assuming TRUE") scp <- TRUE } P.values <- has.Pvalue && scp } else if(P.values && !has.Pvalue) stop("'P.values' is TRUE, but 'has.Pvalue' is not") if(has.Pvalue && !P.values) { d <- dim(xm <- data.matrix(x[,-nc , drop = FALSE])) nc <- nc - 1 has.Pvalue <- FALSE } else xm <- data.matrix(x) k <- nc - has.Pvalue - (if(missing(tst.ind)) 1 else length(tst.ind)) if(!missing(cs.ind) && length(cs.ind) > k) stop("wrong k / cs.ind") Cf <- array("", dim=d, dimnames = dimnames(xm)) ok <- !(ina <- is.na(xm)) for (i in zap.ind) xm[, i] <- zapsmall(xm[, i], digits) if(length(cs.ind)) { acs <- abs(coef.se <- xm[, cs.ind, drop=FALSE]) if(any(ia <- is.finite(acs))) { digmin <- 1 + if(length(acs <- acs[ia & acs != 0])) floor(log10(range(acs[acs != 0], finite = TRUE))) else 0 Cf[,cs.ind] <- format(round(coef.se, max(1L, digits - digmin)), digits = digits) } } if(length(tst.ind)) Cf[, tst.ind] <- format(round(xm[, tst.ind], digits = dig.tst), digits = digits) if(any(r.ind <- !((1L:nc) %in% c(cs.ind, tst.ind, if(has.Pvalue) nc)))) for(i in which(r.ind)) Cf[, i] <- format(xm[, i], digits = digits) ok[, tst.ind] <- FALSE okP <- if(has.Pvalue) ok[, -nc] else ok x1 <- Cf[okP] dec <- getOption("OutDec") if(dec != ".") x1 <- chartr(dec, ".", x1) x0 <- (xm[okP] == 0) != (as.numeric(x1) == 0) if(length(not.both.0 <- which(x0 & !is.na(x0)))) { Cf[okP][not.both.0] <- format(xm[okP][not.both.0], digits = max(1L, digits - 1L)) } if(any(ina)) Cf[ina] <- na.print if(P.values) { if(!is.logical(signif.stars) || is.na(signif.stars)) { warning("option \"show.signif.stars\" is invalid: assuming TRUE") signif.stars <- TRUE } if(any(okP <- ok[,nc])) { pv <- as.vector(xm[, nc]) Cf[okP, nc] <- format.pval(pv[okP], digits = dig.tst, eps = eps.Pvalue) signif.stars <- signif.stars && any(pv[okP] < .1) if(signif.stars) { Signif <- symnum(pv, corr = FALSE, na = FALSE, cutpoints = c(0, .001,.01,.05, .1, 1), symbols = c("***","**","*","."," ")) Cf <- cbind(Cf, format(Signif)) } } else signif.stars <- FALSE } else signif.stars <- FALSE print.default(Cf, quote = FALSE, right = TRUE, na.print = na.print, ...) if(signif.stars && signif.legend) { if((w <- getOption("width")) < nchar(sleg <- attr(Signif,"legend"))) sleg <- strwrap(sleg, width = w - 2, prefix = " ") cat("---\nSignif. codes: ", sleg, sep = "", fill = w+4 + max(nchar(sleg,"bytes") - nchar(sleg))) } invisible(x) } print.anova <- function(x, digits = max(getOption("digits") - 2L, 3L), signif.stars = getOption("show.signif.stars"), ...) { if (!is.null(heading <- attr(x, "heading"))) cat(heading, sep = "\n") nc <- dim(x)[2L] if(is.null(cn <- colnames(x))) stop("'anova' object must have colnames") has.P <- grepl("^(P|Pr)\\(", cn[nc]) zap.i <- 1L:(if(has.P) nc-1 else nc) i <- which(substr(cn,2,7) == " value") i <- c(i, which(!is.na(match(cn, c("F", "Cp", "Chisq"))))) if(length(i)) zap.i <- zap.i[!(zap.i %in% i)] tst.i <- i if(length(i <- grep("Df$", cn))) zap.i <- zap.i[!(zap.i %in% i)] printCoefmat(x, digits = digits, signif.stars = signif.stars, has.Pvalue = has.P, P.values = has.P, cs.ind = NULL, zap.ind = zap.i, tst.ind = tst.i, na.print = "", ...) invisible(x) }
"brca"
logbin.em <- function(mt, mf, Y, offset, mono, start, control, accelerate = c("em","squarem","pem","qn"), control.method, warn) { accelerate = match.arg(accelerate) control2 <- control control2$trace <- (control$trace > 1) reparam <- logbin.reparam(mt, mf, "em", mono) if (!is.null(start)) { start.expand <- logbin.expand(start, reparam, "em") } if(control$trace > 0) cat("logbin parameterisation 1/1\n") if (length(reparam$Vmat) == 0) { X <- model.matrix(mt, mf) Amat <- diag(ncol(X)) } else { des <- logbin.design(mt, mf, "em", reparam) X <- des$X.reparam Amat <- des$A } thismodel <- nplbin(Y, X, offset, if (!is.null(start)) start.expand$coefs.exp else NULL, Amat = Amat, control = control2, accelerate = accelerate, control.accelerate = list(control.method)) if(control$trace > 0 & control$trace <= 1) cat("Deviance =", thismodel$deviance, "Iterations -", thismodel$iter, "\n") if (length(reparam$Vmat) == 0) { np.coefs <- coefs <- coefs.boundary <- thismodel$coefficients nn.design <- design <- X if (control$coeftrace) coefhist <- thismodel$coefhist } else { np.coefs <- thismodel$coefficients nn.design <- X coefs <- as.vector(logbin.reduce(np.coefs, des$A)) names(coefs) <- gsub("`", "", colnames(des$X.orig)) design <- des$X.orig coefs.boundary <- np.coefs[logbin.expand(coefs, reparam, "em")$which.boundary] if (control$coeftrace) { coefhist <- coefhist.reduce(thismodel$coefhist, des$A, names(coefs)) } } nvars <- length(coefs) vardiff <- length(np.coefs) - nvars aic.c <- thismodel$aic - 2 * vardiff + 2 * nvars * (nvars + 1) / (NROW(Y) - nvars - 1) boundary <- any(coefs.boundary > -control$bound.tol) if (warn) { if (!thismodel$converged) { if (identical(accelerate, "em")) warning(gettextf("nplbin: algorithm did not converge within %d iterations -- increase 'maxit'.", control$maxit), call. = FALSE) else warning(gettextf("nplbin(%s): algorithm did not converge within %d iterations -- increase 'maxit' or try with 'accelerate = \"em\"'.", accelerate, control$maxit), call. = FALSE) } if(boundary) { if(coefs.boundary[1] > -control$bound.tol) warning("nplbin: fitted probabilities numerically 1 occurred", call. = FALSE) else warning("nplbin: MLE on boundary of constrained parameter space", call. = FALSE) } } fit <- list(coefficients = coefs, residuals = thismodel$residuals, fitted.values = thismodel$fitted.values, linear.predictors = thismodel$linear.predictors, deviance = thismodel$deviance, loglik = thismodel$loglik, aic = thismodel$aic - 2*vardiff, aic.c = aic.c, null.deviance = thismodel$null.deviance, iter = thismodel$iter, prior.weights = thismodel$prior.weights, df.residual = thismodel$df.residual + vardiff, df.null = thismodel$df.null, y = thismodel$y, x = design, converged = thismodel$converged, boundary = boundary, np.coefficients = np.coefs, nn.x = nn.design) if (control$coeftrace) fit$coefhist <- coefhist fit }
expected <- eval(parse(text="structure(c(43.6690361821048, 35.0518890362789, 30.2558850234373, 27.1664611723591, 24.9930921115624, 23.3776455926353, 22.122313646246, 21.1173217554787, 20.293145402391, 19.6041024133034, 19.0188803067124, 18.5152545044936, 18.0769941360739, 17.6919540860845, 17.3508558987268, 17.0464826391527, 0.924696372559026, 1.4577878275186, 1.99087928247818, 2.52397073743776, 3.05706219239734, 3.59015364735691, 4.12324510231649, 4.65633655727607, 5.18942801223565, 5.72251946719522, 6.2556109221548, 6.78870237711438, 7.32179383207396, 7.85488528703353, 8.38797674199311, 8.92106819695269), .Dim = c(16L, 2L), .Dimnames = list(NULL, c(\"ymax\", \"xhalf\")))")); test(id=0, code={ argv <- eval(parse(text="list(structure(list(par.vals = structure(c(43.6690361821048, 35.0518890362789, 30.2558850234373, 27.1664611723591, 24.9930921115624, 23.3776455926353, 22.122313646246, 21.1173217554787, 20.293145402391, 19.6041024133034, 19.0188803067124, 18.5152545044936, 18.0769941360739, 17.6919540860845, 17.3508558987268, 17.0464826391527, 0.924696372559026, 1.4577878275186, 1.99087928247818, 2.52397073743776, 3.05706219239734, 3.59015364735691, 4.12324510231649, 4.65633655727607, 5.18942801223565, 5.72251946719522, 6.2556109221548, 6.78870237711438, 7.32179383207396, 7.85488528703353, 8.38797674199311, 8.92106819695269), .Dim = c(16L, 2L), .Dimnames = list(NULL, c(\"ymax\", \"xhalf\")))), .Names = \"par.vals\"), 1L)")); do.call(`.subset2`, argv); }, o=expected);
valid_lbl_pos <- c("default", "visible", "hidden", "topleft") .labelkids_helper = function(charval) { ret = switch(charval, "default" = NA, "visible" = TRUE, "hidden" = FALSE, "topleft" = FALSE, stop("unrecognized charval in .labelkids_helper. this shouldn't ever happen")) } setOldClass("expression") setClassUnion("SubsetDef", c("expression", "logical", "integer", "numeric")) setClassUnion("integerOrNULL", c("NULL", "integer")) setClassUnion("characterOrNULL", c("NULL", "character")) setClass("TreePos", representation(splits = "list", s_values = "list", sval_labels = "character", subset = "SubsetDef"), validity = function(object) { nspl <- length(object@splits) length(object@s_values) == nspl && length(object@sval_labels) == nspl }) setClassUnion("functionOrNULL", c("NULL", "function")) setClassUnion("listOrNULL", c("NULL", "list")) setClassUnion("FormatSpec", c("NULL", "character", "function", "list")) setClass("ValueWrapper", representation(value = "ANY", label = "characterOrNULL"), contains = "VIRTUAL") setClass("SplitValue", contains = "ValueWrapper", representation(extra = "list")) SplitValue <- function(val, extr =list(), label = val) { if (is(val, "SplitValue")) { if (length(splv_extra(val)) > 0) extr <- c(splv_extra(val), extr) splv_extra(val) <- extr return(val) } if (!is(extr, "list")) extr <- list(extr) if (!is(label, "character")) label <- as.character(label) new("SplitValue", value = val, extra = extr, label = label) } setClass("LevelComboSplitValue", contains = "SplitValue", representation(combolevels = "character")) LevelComboSplitValue <- function(val, extr, combolevels, label = val) { new("LevelComboSplitValue", value = val, extra = extr, combolevels = combolevels, label = label) } setClass("Split", contains = "VIRTUAL", representation( payload = "ANY", name = "character", split_label = "character", split_format = "FormatSpec", split_label_position = "character", content_fun = "listOrNULL", content_format = "FormatSpec", content_var = "character", label_children = "logical", extra_args = "list", indent_modifier = "integer", content_indent_modifier = "integer", content_extra_args = "list")) setClass("CustomizableSplit", contains = "Split", representation(split_fun = "functionOrNULL")) setClass("VarLevelSplit", contains = "CustomizableSplit", representation(value_label_var = "character", value_order = "ANY")) VarLevelSplit <- function(var, split_label, labels_var = NULL, cfun = NULL, cformat = NULL, split_fun = NULL, split_format = NULL, valorder = NULL, split_name = var, child_labels = c("default", "visible", "hidden"), extra_args = list(), indent_mod = 0L, label_pos = c("topleft", "hidden", "visible"), cindent_mod = 0L, cvar = "", cextra_args = list() ) { child_labels <- match.arg(child_labels) if (is.null(labels_var)) labels_var <- var new("VarLevelSplit", payload = var, split_label = split_label, name = split_name, value_label_var = labels_var, content_fun = cfun, content_format = cformat, split_fun = split_fun, split_format = split_format, value_order = NULL, label_children = .labelkids_helper(child_labels), extra_args = extra_args, indent_modifier = as.integer(indent_mod), content_indent_modifier = as.integer(cindent_mod), content_var = cvar, split_label_position = label_pos, content_extra_args = cextra_args ) } setClass("NULLSplit", contains = "Split") NULLSplit <- function(...) { new("NULLSplit", payload = character(), split_label = character(), content_fun = NULL, content_format = NULL, split_format = NULL, name = "", indent_modifier = 0L, content_indent_modifier = 0L, content_var = "", label_pos = FALSE) } setClass("AllSplit", contains = "Split") AllSplit <- function(split_label = "", cfun = NULL, cformat = NULL, split_format = NULL, split_name = if (!missing(split_label) && nzchar(split_label)) split_label else "all obs", extra_args = list(), indent_mod = 0L, cindent_mod = 0L, cvar = "", cextra_args = list(), ...) { new("AllSplit", split_label = split_label, content_fun = cfun, content_format = cformat, split_format = split_format, name = split_name, label_children = FALSE, extra_args = extra_args, indent_modifier = as.integer(indent_mod), content_indent_modifier = as.integer(cindent_mod), content_var = cvar, split_label_position = "hidden", content_extra_args = cextra_args) } setClass("RootSplit", contains = "AllSplit") RootSplit <- function(split_label = "", cfun = NULL, cformat = NULL, cvar = "", split_format= NULL, cextra_args = list(), ...) { new("RootSplit", split_label = split_label, content_fun = cfun, content_format = cformat, split_format = split_format, name = "root", label_children = FALSE, indent_modifier = 0L, content_indent_modifier = 0L, content_var = cvar, split_label_position = "hidden", content_extra_args = cextra_args) } setClass("ManualSplit", contains = "AllSplit", representation(levels = "character")) ManualSplit <- function(levels, label, name = "manual", extra_args = list(), indent_mod = 0L, cindent_mod = 0L, cvar = "", cextra_args = list(), label_pos = "visible") { label_pos <- match.arg(label_pos, label_pos_values) new("ManualSplit", split_label = label, levels = levels, name = name, label_children = FALSE, extra_args = extra_args, indent_modifier = 0L, content_indent_modifier = as.integer(cindent_mod), content_var = cvar, split_label_position = label_pos) } setClass("MultiVarSplit", contains = "Split", representation(var_labels = "character", var_names = "character"), validity = function(object) { length(object@payload) >= 1 && all(!is.na(object@payload)) && (length(object@var_labels) == 0 || length(object@payload) == length(object@var_labels)) }) .make_suffix_vec <- function(n) { c("", sprintf("._[[%d]]_.", seq_len(n - 1) + 1L)) } .make_multivar_names <- function(vars) { dups <- duplicated(vars) if (!any(dups)) return(vars) dupvars <- unique(vars[dups]) ret <- vars for (v in dupvars) { pos <- which(ret == v) ret[pos] <- paste0(ret[pos], .make_suffix_vec(length(pos))) } ret } MultiVarSplit <- function(vars, split_label = "", varlabels = NULL, varnames = NULL, cfun = NULL, cformat = NULL, split_format = NULL, split_name = "multivars", child_labels = c("default", "visible", "hidden"), extra_args = list(), indent_mod = 0L, cindent_mod = 0L, cvar = "", cextra_args = list(), label_pos = "visible") { label_pos <- match.arg(label_pos, label_pos_values[-3]) child_labels = match.arg(child_labels) if(length(vars) == 1 && grepl(":", vars)) vars = strsplit(vars, ":")[[1]] if(length(varlabels) == 0) varlabels = vars vnames <- varnames %||% .make_multivar_names(vars) stopifnot(length(vnames) == length(vars)) new("MultiVarSplit", payload = vars, split_label = split_label, var_labels = varlabels, var_names = vnames, content_fun = cfun, content_format = cformat, split_format = split_format, label_children = .labelkids_helper(child_labels), name = split_name, extra_args = extra_args, indent_modifier = as.integer(indent_mod), content_indent_modifier = as.integer(cindent_mod), content_var = cvar, split_label_position = label_pos, content_extra_args = cextra_args) } setClass("VarStaticCutSplit", contains = "Split", representation(cuts = "numeric", cut_labels = "character")) VarStaticCutSplit <- function(var, split_label = var, cuts, cutlabels = NULL, cfun = NULL, cformat = NULL, split_format = NULL, split_name = var, child_labels = c("default", "visible", "hidden"), extra_args = list(), indent_mod = 0L, cindent_mod = 0L, cvar = "", cextra_args = list(), label_pos = "visible") { label_pos <- match.arg(label_pos, label_pos_values) child_labels = match.arg(child_labels) if(is.list(cuts) && is.numeric(cuts[[1]]) && is.character(cuts[[2]]) && length(cuts[[1]]) == length(cuts[[2]])) { cutlabels <- cuts[[2]] cuts <- cuts[[1]] } if (is.unsorted(cuts, strictly = TRUE)) stop("invalid cuts vector. not sorted unique values.") if (is.null(cutlabels) && !is.null(names(cuts))) cutlabels <- names(cuts)[-1] new("VarStaticCutSplit", payload = var, split_label = split_label, cuts = cuts, cut_labels = cutlabels, content_fun = cfun, content_format = cformat, split_format = split_format, name = split_name, label_children = .labelkids_helper(child_labels), extra_args = extra_args, indent_modifier = as.integer(indent_mod), content_indent_modifier = as.integer(cindent_mod), content_var = cvar, split_label_position = label_pos, content_extra_args = cextra_args) } setClass("CumulativeCutSplit", contains = "VarStaticCutSplit") CumulativeCutSplit <- function(var, split_label, cuts, cutlabels = NULL, cfun = NULL, cformat = NULL, split_format = NULL, split_name = var, child_labels = c("default", "visible", "hidden"), extra_args = list(), indent_mod = 0L, cindent_mod = 0L, cvar = "", cextra_args = list(), label_pos = "visible") { label_pos <- match.arg(label_pos, label_pos_values) child_labels = match.arg(child_labels) if(is.list(cuts) && is.numeric(cuts[[1]]) && is.character(cuts[[2]]) && length(cuts[[1]]) == length(cuts[[2]])) { cutlabels <- cuts[[2]] cuts <- cuts[[1]] } if (is.unsorted(cuts, strictly = TRUE)) stop("invalid cuts vector. not sorted unique values.") if (is.null(cutlabels) && !is.null(names(cuts))) cutlabels <- names(cuts)[-1] new("CumulativeCutSplit", payload = var, split_label = split_label, cuts = cuts, cut_labels = cutlabels, content_fun = cfun, content_format = cformat, split_format = split_format, name = split_name, label_children = .labelkids_helper(child_labels), extra_args = extra_args, indent_modifier = as.integer(indent_mod), content_indent_modifier = as.integer(cindent_mod), content_var = cvar, split_label_position = label_pos, content_extra_args = cextra_args) } setClass("VarDynCutSplit", contains = "Split", representation(cut_fun = "function", cut_label_fun = "function", cumulative_cuts = "logical")) VarDynCutSplit <- function(var, split_label, cutfun, cutlabelfun = function(x) NULL, cfun = NULL, cformat = NULL, split_format = NULL, split_name = var, child_labels = c("default", "visible", "hidden"), extra_args = list(), cumulative = FALSE, indent_mod = 0L, cindent_mod = 0L, cvar = "", cextra_args = list(), label_pos = "visible") { label_pos <- match.arg(label_pos, label_pos_values) child_labels = match.arg(child_labels) new("VarDynCutSplit", payload = var, split_label = split_label, cut_fun = cutfun, cumulative_cuts = cumulative, cut_label_fun = cutlabelfun, content_fun = cfun, content_format = cformat, split_format = split_format, name = split_name, label_children = .labelkids_helper(child_labels), extra_args = extra_args, indent_modifier = as.integer(indent_mod), content_indent_modifier = as.integer(cindent_mod), content_var = cvar, split_label_position = label_pos, content_extra_args = cextra_args) } setClass("VAnalyzeSplit", contains = "Split", representation(default_rowlabel = "character", include_NAs = "logical", var_label_position = "character")) setClass("AnalyzeVarSplit", contains = "VAnalyzeSplit", representation(analysis_fun = "function")) setClass("AnalyzeColVarSplit", contains = "VAnalyzeSplit", representation(analysis_fun = "list")) AnalyzeVarSplit <- function(var, split_label = var, afun, defrowlab = "", cfun = NULL, cformat = NULL, split_format = NULL, inclNAs = FALSE, split_name = var, extra_args = list(), indent_mod = 0L, label_pos = "default", cvar = "" ) { label_pos <- match.arg(label_pos, c("default", label_pos_values)) if(!any(nzchar(defrowlab))) { defrowlab = as.character(substitute(afun)) if(length(defrowlab) > 1 || startsWith(defrowlab, "function(")) defrowlab = "" } new("AnalyzeVarSplit", payload = var, split_label = split_label, content_fun = cfun, analysis_fun = afun, content_format = cformat, split_format = split_format, default_rowlabel = defrowlab, include_NAs = inclNAs, name = split_name, label_children = FALSE, extra_args = extra_args, indent_modifier = as.integer(indent_mod), content_indent_modifier = 0L, var_label_position = label_pos, content_var = cvar) } AnalyzeColVarSplit <- function(afun, defrowlab = "", cfun = NULL, cformat = NULL, split_format = NULL, inclNAs = FALSE, split_name = "", extra_args = list(), indent_mod = 0L, label_pos = "default", cvar = "") { label_pos <- match.arg(label_pos, c("default", label_pos_values)) new("AnalyzeColVarSplit", payload = NA_character_, split_label = "", content_fun = cfun, analysis_fun = afun, content_format = cformat, split_format = split_format, default_rowlabel = defrowlab, include_NAs = inclNAs, name = split_name, label_children = FALSE, extra_args = extra_args, indent_modifier = as.integer(indent_mod), content_indent_modifier = 0L, var_label_position = label_pos, content_var = cvar) } setClass("CompoundSplit", contains = "Split", validity = function(object) are(object@payload, "Split")) setClass("AnalyzeMultiVars", contains = "CompoundSplit") .repoutlst <- function(x, nv) { if (!is.function(x) && length(x) == nv) return(x) if (!is(x, "list")) x <- list(x) rep(x, length.out = nv) } .uncompound <- function(csplit) { if (is(csplit, "list")) return(unlist(lapply(csplit, .uncompound))) if (!is(csplit, "CompoundSplit")) return(csplit) pld <- spl_payload(csplit) done <- all(!vapply(pld, is, TRUE, class2 = "CompoundSplit")) if (done) pld else unlist(lapply(pld, .uncompound)) } strip_compound_name <- function(obj) { nm <- obj_name(obj) gsub("^ma_", "", nm) } make_ma_name <- function(spl, pld = spl_payload(spl)) { paste(c("ma", vapply(pld, strip_compound_name, "")), collapse = "_") } AnalyzeMultiVars <- function(var, split_label = "", afun, defrowlab = "", cfun = NULL, cformat = NULL, split_format = NULL, inclNAs = FALSE, .payload = NULL, split_name = NULL, extra_args = list(), indent_mod = 0L, child_labels = c("default", "topleft", "visible", "hidden"), child_names = var, cvar = "" ) { child_labels <- match.arg(child_labels) show_kidlabs <- child_labels if(is.null(.payload)) { nv = length(var) defrowlab = .repoutlst(defrowlab, nv) afun = .repoutlst(afun, nv) split_label = .repoutlst(split_label, nv) cfun = .repoutlst(cfun, nv) cformat = .repoutlst(cformat, nv) inclNAs = .repoutlst(inclNAs, nv) pld = mapply(AnalyzeVarSplit, var = var, split_name = child_names, split_label = split_label, afun = afun, defrowlab = defrowlab, cfun = cfun, cformat = cformat, inclNAs = inclNAs, MoreArgs = list(extra_args = extra_args, indent_mod = indent_mod, label_pos = show_kidlabs, split_format = split_format ), SIMPLIFY = FALSE) } else { pld <- unlist(lapply(.payload, .uncompound)) pld <- lapply(pld, function(x) { rvis = label_position(x) if(!identical(show_kidlabs, "default")) { if(identical(rvis, "default")) rvis = show_kidlabs } label_position(x) = rvis x }) } if (length(pld) == 1) { ret <- pld[[1]] } else { if(is.null(split_name)) split_name <- paste(c("ma", vapply(pld, obj_name, "")), collapse = "_") ret <- new("AnalyzeMultiVars", payload = pld, split_label = "", split_format = NULL, content_fun = NULL, content_format = NULL, label_children = .labelkids_helper(show_kidlabs), split_label_position = "hidden", name = split_name, extra_args = extra_args, indent_modifier = 0L, content_indent_modifier = 0L, content_var = cvar) } ret } setClass("VCompSplit", contains = c("VIRTUAL", "Split"), representation(comparison_func = "function", label_format = "character")) setClassUnion("VarOrFactory", c("function", "character")) setClass("MultiSubsetCompSplit", contains = "VCompSplit", representation(subset1_gen = "VarOrFactory", subset2_gen = "VarOrFactory")) MultiSubsetCompSplit <- function(factory1, factory2, label_fstr = "%s - %s", split_label = "", comparison = `-`, cfun = NULL, cformat = NULL, split_format = NULL) { new("MultiSubsetCompSplit", subset1_gen = factory1, subset2_gen = factory2, label_format = label_fstr, split_label = split_label, content_fun = cfun, content_format = cformat, split_format = split_format, comparison_func = comparison) } setClass("SubsetSplit", contains = "Split", representation(subset_gen = "VarOrFactory", vs_all = "logical", vs_non = "logical", child_order = "character"), validity = function(object) object@vs_all || object@vs_non, prototype = prototype(vs_all = TRUE, vs_non = FALSE)) SubsetSplit <- function(subset, vall = TRUE, vnon = FALSE, order = c("subset", if (vnon) "non", if (vall) "all"), split_label, cfun = NULL, cformat = NULL, split_format = NULL) { new("SubsetSplit", split_label = split_label, content_fun = cfun, content_format = cformat, split_format = split_format, subset_gen = subset, vs_all = vall, vs_non = vnon, child_order = order) } setClass("VarLevWBaselineSplit", contains = "VarLevelSplit", representation(var = "character", ref_group_value = "character")) VarLevWBaselineSplit <- function(var, ref_group, labels_var = var, split_label, split_fun = NULL, label_fstr = "%s - %s", cfun = NULL, cformat = NULL, cvar = "", split_format = NULL, valorder = NULL, split_name = var, extra_args = list()) { new("VarLevWBaselineSplit", payload = var, ref_group_value = ref_group, value_label_var = labels_var, split_label = split_label, content_fun = cfun, content_format = cformat, split_format = split_format, split_fun = split_fun, name = split_name, label_children = FALSE, extra_args = extra_args, indent_modifier = 0L, content_indent_modifier = 0L, content_var = cvar) } setClass("CompSubsetVectors", representation(subset1 = "list", subset2 = "list"), validity = function(object) length(object@subset1) == length(object@subset2)) .chkname <- function(nm) { if (is.null(nm)) nm <- "" if (length(nm) != 1) { stop("name is not of length one") } else if (is.na(nm)) { warning("Got missing value for name, converting to characters '<NA>'") nm <- "<NA>" } nm } TreePos <- function(spls = list(), svals = list(), svlabels = character(), sub = NULL) { svals <- make_splvalue_vec(vals = svals) if (is.null(sub)) { if (length(spls) > 0) { sub <- make_pos_subset(spls = spls, svals = svals) } else { sub <- expression(TRUE) } } new("TreePos", splits = spls, s_values = svals, sval_labels = svlabels, subset = sub) } make_child_pos <- function(parpos, newspl, newval, newlab = newval, newextra = list()) { if (!is(newval, "SplitValue")) nsplitval <- SplitValue(newval, extr = newextra, label = newlab) else nsplitval <- newval newpos <- TreePos( spls = c(pos_splits(parpos), newspl), svals = c(pos_splvals(parpos), nsplitval), svlabels = c(pos_splval_labels(parpos), newlab), sub = .combine_subset_exprs(pos_subset(parpos), make_subset_expr(newspl, nsplitval))) } setClass("VNodeInfo", contains = "VIRTUAL", representation(level = "integer", name = "character" )) setClass("VTree", contains = c("VIRTUAL", "VNodeInfo"), representation(children = "list")) setClass("VLeaf", contains = c("VIRTUAL", "VNodeInfo")) setClass("VLayoutLeaf", contains = c("VIRTUAL", "VLeaf"), representation(pos_in_tree = "TreePos", label = "character")) setClass("VLayoutTree", contains = c("VIRTUAL", "VTree"), representation(split = "Split", pos_in_tree = "TreePos", label = "character")) setClassUnion("VLayoutNode", c("VLayoutLeaf", "VLayoutTree")) setOldClass("function") setOldClass("NULL") setClassUnion("FunctionOrNULL", c("function", "NULL")) setClass("LayoutAxisTree", contains = "VLayoutTree", representation(summary_func = "FunctionOrNULL"), validity = function(object) all(sapply(object@children, function(x) is(x, "LayoutAxisTree") || is(x, "LayoutAxisLeaf")))) setClass("LayoutAxisLeaf", contains = "VLayoutLeaf", representation(func = "function", col_footnotes = "list")) setClass("LayoutColTree", contains = "LayoutAxisTree", representation(display_columncounts = "logical", columncount_format = "character", col_footnotes = "list")) setClass("LayoutColLeaf", contains = "LayoutAxisLeaf") setClass("LayoutRowTree", contains = "LayoutAxisTree") setClass("LayoutRowLeaf", contains = "LayoutAxisLeaf") LayoutColTree <- function(lev = 0L, name = obj_name(spl), label = obj_label(spl), kids = list(), spl = EmptyAllSplit, tpos = TreePos(), summary_function = NULL, disp_colcounts = FALSE, colcount_format = "(N=xx)", footnotes = list()) { footnotes <- make_ref_value(footnotes) if (!is.null(spl)) { new("LayoutColTree", level = lev, children = kids, name = .chkname(name), summary_func = summary_function, pos_in_tree = tpos, split = spl, label = label, display_columncounts = disp_colcounts, columncount_format = colcount_format, col_footnotes = footnotes) } else { stop("problema my manitar") LayoutColLeaf(lev = lev, label = label, tpos = tpos, name = .chkname(name)) } } LayoutColLeaf <- function(lev = 0L, name = label, label = "", tpos = TreePos() ) { new("LayoutColLeaf", level = lev, name = .chkname(name), label = label, pos_in_tree = tpos ) } LayoutRowTree <- function(lev = 0L, kids = list()) { new("LayoutRowTree", level = lev, children = kids) } LayoutRowLeaf <- function(lev = 0L, label = "", pos) { new("LayoutRowLeaf", level = lev, label = label, pos_in_tree = pos) } setClass("InstantiatedColumnInfo", representation(tree_layout = "VLayoutNode", subset_exprs = "list", cextra_args = "list", counts = "integer", total_count = "integer", display_columncounts = "logical", columncount_format = "FormatSpec", top_left = "character") ) InstantiatedColumnInfo <- function(treelyt = LayoutColTree(), csubs = list(expression(TRUE)), extras = list(list()), cnts = NA_integer_, total_cnt = NA_integer_, dispcounts = FALSE, countformat = "(N=xx)", topleft = character()) { leaves <- collect_leaves(treelyt) nl <- length(leaves) extras <- rep(extras, length.out = nl) cnts <- rep(cnts, length.out = nl) csubs <- rep(csubs, length.out = nl) nleaves <- length(leaves) snas <- sum(is.na(cnts)) if (length(csubs) != nleaves || length(extras) != nleaves || length(cnts) != nleaves || (snas != 0 && snas != nleaves)) stop("attempted to create invalid InstatiedColumnInfo object. Please contact the maintainer(s).") new("InstantiatedColumnInfo", tree_layout = treelyt, subset_exprs = csubs, cextra_args = extras, counts = cnts, total_count = total_cnt, display_columncounts = dispcounts, columncount_format = countformat, top_left = topleft) } setClass("VTableNodeInfo", contains = c("VNodeInfo", "VIRTUAL"), representation( col_info = "InstantiatedColumnInfo", format = "FormatSpec", indent_modifier = "integer")) setClass("TableRow", contains = c("VIRTUAL", "VLeaf", "VTableNodeInfo"), representation(leaf_value = "ANY", var_analyzed = "character", label = "character", row_footnotes = "list")) LabelRow <- function(lev = 1L, label = "", name = label, vis = !is.na(label) && nzchar(label), cinfo = EmptyColInfo, indent_mod = 0L) { new("LabelRow", leaf_value = list(), level = lev, label = label, name = .chkname(name), col_info = cinfo, visible = vis, indent_modifier = as.integer(indent_mod)) } setClass("DataRow", contains = "TableRow", representation(colspans = "integer") ) setClass("ContentRow", contains = "TableRow", representation(colspans = "integer") ) setClass("LabelRow", contains = "TableRow", representation(visible = "logical") ) .tablerow <- function(vals = list(), name = "", lev = 1L, label = name, cspan = rep(1L, length(vals)), cinfo = EmptyColInfo, var = NA_character_, format = NULL, klass, indent_mod = 0L, footnotes = list()) { if ((missing(name) || is.null(name) || is.na(name) || nchar(name) == 0) && !missing(label)) name <- label vals <- lapply(vals, rcell) rlabels <- unique(unlist(lapply(vals, obj_label))) if ((missing(label) || is.null(label) || identical(label, "")) && sum(nzchar(rlabels)) == 1) label <- rlabels[nzchar(rlabels)] if (missing(cspan) && !is.null(unlist(lapply(vals, cell_cspan)))) cspan <- vapply(vals, cell_cspan, 0L) rw <- new(klass, leaf_value = vals, name = .chkname(name), level = lev, label = .chkname(label), colspans = cspan, col_info = cinfo, var_analyzed = var, format = NULL, indent_modifier = indent_mod, row_footnotes = footnotes ) rw <- set_format_recursive(rw, format, FALSE) rw } DataRow <- function(...) .tablerow(..., klass = "DataRow") ContentRow <- function(...) .tablerow(..., klass = "ContentRow") setClass("VTitleFooter", contains = "VIRTUAL", representation(main_title = "character", subtitles = "character", main_footer = "character", provenance_footer = "character")) setClass("VTableTree", contains = c("VIRTUAL", "VTableNodeInfo", "VTree", "VTitleFooter"), representation(children = "list", rowspans = "data.frame", labelrow = "LabelRow" )) setClassUnion("IntegerOrNull", c("integer", "NULL")) etable_validity <- function(object) { kids <- tree_children(object) all(sapply(kids, function(k) { (is(k, "DataRow") || is(k, "ContentRow"))})) } setClass("ElementaryTable", contains = "VTableTree", representation(var_analyzed = "character"), validity = etable_validity ) .enforce_valid_kids <- function(lst, colinfo) { if (!no_colinfo(colinfo)) { lst <- lapply(lst, function(x) { if (no_colinfo(x)) col_info(x) <- colinfo else if (!identical(colinfo, col_info(x))) stop("attempted to add child with non-matching, non-empty column info to an existing table") x }) } if (are(lst, "ElementaryTable") && all(sapply(lst, function(tb) { nrow(tb) <= 1 && identical(obj_name(tb), "") }))) { lst <- unlist(lapply(lst, function(tb) tree_children(tb)[[1]])) } if (length(lst) == 0) return(list()) realnames <- sapply(lst, obj_name) lstnames <- names(lst) if (is.null(lstnames)) { names(lst) <- realnames } else if (!identical(realnames, lstnames)) { names(lst) <- realnames } lst } ElementaryTable <- function(kids = list(), name = "", lev = 1L, label = "", labelrow = LabelRow(lev = lev, label = label, vis = !isTRUE(iscontent) && !is.na(label) && nzchar(label)), rspans = data.frame(), cinfo = NULL, iscontent = NA, var = NA_character_, format = NULL, indent_mod = 0L, title = "", subtitles = character(), main_footer = character(), prov_footer = character()) { if (is.null(cinfo)) { if (length(kids) > 0) cinfo <- col_info(kids[[1]]) else cinfo <- EmptyColInfo } if (no_colinfo(labelrow)) col_info(labelrow) <- cinfo kids <- .enforce_valid_kids(kids, cinfo) tab <- new("ElementaryTable", children = kids, name = .chkname(name), level = lev, labelrow = labelrow, rowspans = rspans, col_info = cinfo, var_analyzed = var, format = NULL, indent_modifier = as.integer(indent_mod), main_title = title, subtitles = subtitles, main_footer = main_footer, provenance_footer = prov_footer ) tab <- set_format_recursive(tab, format, FALSE) tab } ttable_validity <- function(object) { all(sapply(tree_children(object), function(x) is(x, "TableTree") || is(x, "ElementaryTable") || is(x, "TableRow"))) } setClass("TableTree", contains = c("VTableTree"), representation(content = "ElementaryTable" ), validity = ttable_validity) TableTree <- function(kids = list(), name = if (!is.na(var)) var else "", cont = EmptyElTable, lev = 1L, label= name, labelrow = LabelRow(lev = lev, label = label, vis = nrow(cont) == 0 && !is.na(label) && nzchar(label)), rspans = data.frame(), iscontent = NA, var = NA_character_, cinfo = NULL, format = NULL, indent_mod = 0L, title = "", subtitles = character(), main_footer = character(), prov_footer = character()) { if (is.null(cinfo)) { if (!is.null(cont)) { cinfo <- col_info(cont) } else if (length(kids) > 0) { cinfo <- col_info(kids[[1]]) } else { cinfo <- EmptyColInfo } } kids <- .enforce_valid_kids(kids, cinfo) if (isTRUE(iscontent) && !is.null(cont) && nrow(cont) > 0) stop("Got table tree with content table and content position") if (no_colinfo(labelrow)) col_info(labelrow) <- cinfo if ((is.null(cont) || nrow(cont) == 0) && all(sapply(kids, is, "DataRow"))) { ElementaryTable(kids = kids, name = .chkname(name), lev = lev, labelrow = labelrow, rspans = rspans, cinfo = cinfo, var = var, format = format, indent_mod = indent_mod, title = title, subtitles = subtitles, main_footer = main_footer, prov_footer = prov_footer) } else { tab <- new("TableTree", content = cont, children = kids, name = .chkname(name), level = lev, labelrow = labelrow, rowspans = rspans, col_info = cinfo, format = NULL, indent_modifier = as.integer(indent_mod), main_title = title, subtitles = subtitles, main_footer = main_footer, provenance_footer = prov_footer) tab <- set_format_recursive(tab, format, FALSE) tab } } setClass("SplitVector", contains = "list", validity = function(object) { if (length(object) >= 1) lst <- tail(object, 1)[[1]] else lst <- NULL all(sapply(head(object, -1), is, "Split")) && (is.null(lst) || is(lst, "Split") || is(lst, "VTableNodeInfo")) }) SplitVector <- function(x = NULL, ..., lst = list(...)) { if (!is.null(x)) lst <- unlist(c(list(x), lst), recursive = FALSE) new("SplitVector", lst) } avar_noneorlast <- function(vec) { if (!is(vec, "SplitVector")) return(FALSE) if (length(vec) == 0) return(TRUE) isavar <- which(sapply(vec, is, "AnalyzeVarSplit")) (length(isavar) == 0) || (length(isavar) == 1 && isavar == length(vec)) } setClass("PreDataAxisLayout", contains = "list", representation(root_split = "ANY"), validity = function(object) { allleafs <- unlist(object, recursive = TRUE) all(sapply(object, avar_noneorlast)) && all(sapply(allleafs, function(x) is(x, "Split") || is(x, "VTableTree"))) }) setClass("PreDataColLayout", contains = "PreDataAxisLayout", representation(display_columncounts = "logical", columncount_format = "character")) setClass("PreDataRowLayout", contains = "PreDataAxisLayout") PreDataColLayout <- function(x = SplitVector(), rtsp = RootSplit(), ..., lst = list(x, ...), disp_colcounts = FALSE, colcount_format = "(N=xx)") { ret <- new("PreDataColLayout", lst, display_columncounts = disp_colcounts, columncount_format = colcount_format) ret@root_split <- rtsp ret } PreDataRowLayout <- function(x = SplitVector(), root = RootSplit(), ..., lst = list(x, ...)) { new("PreDataRowLayout", lst, root_split = root) } setClass("PreDataTableLayouts", contains= "VTitleFooter", representation(row_layout = "PreDataRowLayout", col_layout = "PreDataColLayout", top_left = "character")) PreDataTableLayouts <- function(rlayout = PreDataRowLayout(), clayout = PreDataColLayout(), topleft = character(), title = "", subtitles = character(), main_footer = character(), prov_footer = character()) { new("PreDataTableLayouts", row_layout = rlayout, col_layout = clayout, top_left = topleft, main_title = title, subtitles = subtitles, main_footer = main_footer, provenance_footer = prov_footer) } setOldClass("CellValue") setMethod("length", "CellValue", function(x) 1L) setClass("RefFootnote", representation(value = "character", index = "integer")) RefFootnote = function(note, index = NA_integer_) { if(is(note, "RefFootnote")) return(note) else if(length(note) == 0) return(NULL) new("RefFootnote", value = note, index = index) } CellValue <- function(val, format = NULL, colspan = 1L, label = NULL, indent_mod = NULL, footnotes = NULL) { if (is.null(colspan)) colspan <- 1L if (!is.null(colspan) && !is(colspan, "integer")) colspan <- as.integer(colspan) if ((is.null(label) || is.na(label)) && !is.null(obj_label(val))) label <- obj_label(val) if(!is.list(footnotes)) footnotes <- lapply(footnotes, RefFootnote) ret <- structure(list(val), format = format, colspan = colspan, label = label, indent_mod = indent_mod, footnotes = footnotes, class = "CellValue") } print.CellValue <- function(x, ...) { cat(paste("rcell:", format_rcell(x), "\n")) invisible(x) } setOldClass("RowsVerticalSection") RowsVerticalSection <- function(values, names = names(values), labels = NULL, indent_mods = NULL, formats = NULL, footnotes = NULL) { stopifnot(is(values, "list")) if (is.null(labels)) { labels <- names(values) } if (is.null(names) && all(nzchar(labels))) names <- labels else if (is.null(labels) && !is.null(names)) labels <- names if (!is.null(indent_mods)) indent_mods <- as.integer(indent_mods) structure(values, class = "RowsVerticalSection", row_names = names, row_labels = labels, indent_mods = indent_mods, row_formats = formats, row_footnotes = lapply(footnotes, function(fns) lapply(fns, RefFootnote))) } print.RowsVerticalSection <- function(x, ...) { cat("RowsVerticalSection (in_rows) object print method:\n----------------------------\n") print(data.frame( row_name = attr(x, "row_names"), formatted_cell = vapply(x, format_rcell, character(1)), indent_mod = vapply(x, indent_mod, numeric(1)), row_label = attr(x, "row_labels"), stringsAsFactors = FALSE, row.names = NULL ), row.names = TRUE) invisible(x) }
twosigma_custom<-function(count_matrix,mean_form,zi_form,id,return_summary_fits=TRUE, silent=FALSE,disp_covar=NULL ,weights=rep(1,ncol(count_matrix)) ,control = glmmTMBControl(),ncores=1,cluster_type="Fork" ,chunk_size=10,lb=FALSE,internal_call=FALSE){ passed_args <- names(as.list(match.call())[-1]) required_args<-c("count_matrix","mean_form","zi_form","id") if (any(!required_args %in% passed_args)) { stop(paste("Argument(s)",paste(setdiff(required_args, passed_args), collapse=", "),"missing and must be specified.")) } ngenes<-nrow(count_matrix) genes<-rownames(count_matrix) if(is.null(genes)){genes<-1:ngenes} if(length(id)!=ncol(count_matrix)){stop("Argument id should be a numeric vector with length equal to the number of columns of count_matrix (i.e. the number of cells).")} fit_ts<-function(chunk,id){ k<-0 num_err=0 fit<-vector('list',length=length(chunk)) gene_err<-rep(TRUE,length(chunk)) logLik<-rep(NA,length(chunk)) for(l in unlist(chunk)){ if(num_err>0){break} k<-k+1 count<-count_matrix[l,,drop=FALSE] check_twosigma_custom_input(count,mean_form,zi_form,id,disp_covar) count<-as.numeric(count) if(is.null(disp_covar)){ disp_form<- ~1 }else{ if(is.atomic(disp_covar)&length(disp_covar)==1){ if(disp_covar==0){stop("Invalid dispersion covariate option")}else{ if(disp_covar==1){ disp_form<-~1 }else{ stop("Invalid dispersion covariate option") } } } } if(is.null(disp_form)){ disp_form<- ~ disp_covar} formulas<-list(mean_form=mean_form,zi_form=zi_form,disp_form=disp_form) tryCatch({ f<-glmmTMB(formula=formulas$mean_form ,ziformula=formulas$zi_form ,weights=weights ,dispformula = formulas$disp_form ,family=nbinom2,verbose = F ,control = control) if(return_summary_fits==TRUE){ fit[[k]]<-summary(f) logLik[k]<-as.numeric(fit[[k]]$logLik) gene_err[k]<-(is.na(logLik[k]) | f$sdr$pdHess==FALSE) }else{ fit[[k]]<-f logLik[k]<-as.numeric(summary(fit[[k]])$logLik) gene_err[k]<-(is.na(logLik[k]) | f$sdr$pdHess==FALSE) }},error=function(e){}) return(list(fit=fit,gene_err=gene_err)) } } size=chunk_size chunks<-split(1:ngenes,ceiling(seq_along(genes)/size)) nchunks<-length(chunks) cl=NULL if(cluster_type=="Sock" & ncores>1){ cl<-parallel::makeCluster(ncores) registerDoParallel(cl) vars<-unique(c(all.vars(mean_form)[-1],all.vars(zi_form)[-1])) clusterExport(cl,varlist=vars,envir=environment()) } if(cluster_type=="Fork"&ncores>1){ cl<-parallel::makeForkCluster(ncores,outfile="") registerDoParallel(cl) } if(internal_call==FALSE){ print("Running Gene-Level Models") pboptions(type="timer") if(lb==TRUE){pboptions(use_lb=TRUE)} if(silent==TRUE){pboptions(type="none")} a<-pblapply(chunks,FUN=fit_ts,id=id,cl=cl) if(ncores>1){parallel::stopCluster(cl)} }else{ a<-lapply(chunks,FUN=fit_ts,id=id) } rm(count_matrix) gc() fit<-do.call(c,sapply(a,'[',1)) gene_err<-unlist(sapply(a,'[',2)) names(fit)<-genes names(gene_err)<-genes return(list(fit=fit,gene_err=gene_err)) }