code
stringlengths
1
13.8M
RunDS <- function (DI, thre) { X0 <- rep(0,length(DI)) X0[DI < thre] <- 1 X1 <- c(0,X0,0) st <- c() ed <- c() for (i in 2:(length(X1)-1)){ if (X1[i-1] == 0 & X1[i] == 1){ st <- c(st,i-1) } if (X1[i] == 1 & X1[i+1] == 0){ ed <- c(ed,i-1) } } Duration <- ed-st+1 Frequency <- length(Duration) Severity <- matrix(nrow=Frequency, ncol=1) for (i in 1:Frequency) { Severity[i,1] <- abs(sum(DI[st[i]:ed[i],1]-thre)) } Result <- data.frame(Duration,Severity) return(Result) }
' Authors Torsten Pook, [email protected] Copyright (C) 2017 -- 2020 Torsten Pook This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. ' mutation.intro <- function(population, gen, sex, individual.nr, qtl.posi, haplo.set=1) { if(sum(population$breeding[[gen]][[sex]][[individual.nr]][[2+ haplo.set]]==qtl.posi)==0){ population$breeding[[gen]][[sex]][[individual.nr]][[2+ haplo.set]] <- sort(c(qtl.posi,population$breeding[[gen]][[sex]][[individual.nr]][[2+ haplo.set]])) } else{ population$breeding[[gen]][[sex]][[individual.nr]][[2+ haplo.set]] <- unique(c(qtl.posi,population$breeding[[gen]][[sex]][[individual.nr]][[2+ haplo.set]]))[-1] } return(population) }
tam_irf_3pl <- function(theta, AXsi, B, guess=NULL, subtract_max=TRUE) { if ( is.vector(theta) ){ theta <- matrix( theta, ncol=1 ) } nnodes <- nrow(theta) nitems <- nrow(AXsi) maxK <- ncol(AXsi) if ( is.null(guess) ){ guess <- rep(0,nitems) } probs <- tam_mml_3pl_calc_prob(iIndex=1:nitems, A=NULL, AXsi=AXsi, B=B, xsi=NULL, theta=theta, nnodes=nnodes, maxK=maxK, recalc=FALSE, guess=guess, subtract_max=subtract_max)$rprobs probs <- aperm( probs, c(3,1,2) ) return(probs) }
expect_traces <- function(p, n.traces, name){ stopifnot(is.numeric(n.traces)) L <- expect_doppelganger_built(p, paste0("plotly-subplot-", name)) expect_equivalent(length(L$data), n.traces) L } test_that("simple subplot works", { p1 <- plot_ly(x = c(1, 2)) p2 <- plot_ly(x = c(1, 2)) s <- expect_traces(subplot(p1, p2), 2, "simple") expect_identical(s$data[[2]]$xaxis, s$layout[["yaxis2"]][["anchor"]]) expect_identical(s$data[[2]]$yaxis, s$layout[["xaxis2"]][["anchor"]]) doms <- lapply(s$layout[grepl("^xaxis", names(s$layout))], "[[", "domain") expect_true(doms$xaxis[2] <= doms$xaxis2[1]) }) test_that("nrows argument works", { p1 <- plot_ly(x = c(1, 2)) p2 <- plot_ly(x = c(1, 2)) s <- expect_traces(subplot(p1, p2, nrows = 2), 2, "simple2") expect_identical(s$data[[2]]$xaxis, s$layout[["yaxis2"]][["anchor"]]) expect_identical(s$data[[2]]$yaxis, s$layout[["xaxis2"]][["anchor"]]) doms <- lapply(s$layout[grepl("^[x-y]axis", names(s$layout))], "[[", "domain") expect_true(doms$yaxis[2] > doms$yaxis[1]) expect_true(doms$yaxis[1] > doms$yaxis2[2]) expect_true(doms$yaxis2[2] > doms$yaxis2[1]) }) test_that("group + [x/y]axis works", { penguins <- palmerpenguins::penguins %>% tidyr::drop_na() %>% arrange(species) p <- plot_ly(penguins, x = ~bill_length_mm, y = ~bill_depth_mm, color = ~species, xaxis = ~paste0("x", as.integer(species)), mode = "markers") s <- expect_traces(subplot(p, margin = 0.05), 3, "group") ax <- s$layout[grepl("^[x-y]axis", names(s$layout))] doms <- lapply(ax, "[[", "domain") ydom <- doms[grepl("^y", names(doms))] expect_equivalent(sort(unique(unlist(ydom))), c(0, 1)) xdom <- doms[grepl("^x", names(doms))] expect_true(all(1/3 > xdom[[1]] & xdom[[1]] >= 0)) expect_true(all(2/3 > xdom[[2]] & xdom[[2]] > 1/3)) expect_true(all(1 >= xdom[[3]] & xdom[[3]] > 2/3)) }) test_that("shareX produces one x-axis and a legend", { s <- subplot(plot_ly(x = 1), plot_ly(x = 1), nrows = 2, shareX = TRUE) l <- expect_traces(s, 2, "shareX") expect_true(sum(grepl("^xaxis", names(l$layout))) == 1) expect_true(l$data[[1]]$showlegend %||% TRUE) expect_true(l$data[[2]]$showlegend %||% TRUE) expect_true(l$layout$showlegend %||% TRUE) }) test_that("shareY produces one y-axis", { s <- subplot(plot_ly(x = 1), plot_ly(x = 1), shareY = TRUE) l <- expect_traces(s, 2, "shareY") expect_true(sum(grepl("^yaxis", names(l$layout))) == 1) }) test_that("share both axes", { s <- subplot( plot_ly(x = 1), plot_ly(x = 1), plot_ly(x = 1), plot_ly(x = 1), nrows = 2, shareX = TRUE, shareY = TRUE ) l <- expect_traces(s, 4, "shareBoth") expect_true(sum(grepl("^yaxis", names(l$layout))) == 2) expect_true(sum(grepl("^xaxis", names(l$layout))) == 2) }) d <- data.frame( x = rnorm(100), y = rnorm(100) ) hist_top <- ggplot(d) + geom_histogram(aes(x = x)) empty <- ggplot() + geom_blank() scatter <- ggplot(d) + geom_point(aes(x = x, y = y)) hist_right <- ggplot(d) + geom_histogram(aes(x = y)) + coord_flip() s <- subplot( hist_top, empty, scatter, hist_right, nrows = 2, widths = c(0.8, 0.2), heights = c(0.2, 0.8), margin = 0.005, shareX = TRUE, shareY = TRUE ) test_that("Row/column height/width", { l <- expect_traces(s, 3, "width-height") expect_equivalent(diff(l$layout$xaxis$domain), 0.8 - 0.005) expect_equivalent(diff(l$layout$xaxis2$domain), 0.2 - 0.005) expect_equivalent(diff(l$layout$yaxis$domain), 0.2 - 0.005) expect_equivalent(diff(l$layout$yaxis2$domain), 0.8 - 0.005) }) test_that("recursive subplots work", { p1 <- plot_ly(economics, x = ~date, y = ~unemploy) p2 <- plot_ly(economics, x = ~date, y = ~uempmed) s1 <- subplot(p1, p1, shareY = TRUE) s2 <- subplot(p2, p2, shareY = TRUE) s <- subplot(s1, s2, nrows = 2, shareX = TRUE) l <- expect_traces(s, 4, "recursive") xaxes <- l$layout[grepl("^xaxis", names(l$layout))] yaxes <- l$layout[grepl("^yaxis", names(l$layout))] expect_true(length(xaxes) == 2) expect_true(length(yaxes) == 2) yanchor <- unique(unlist(lapply(xaxes, "[[", "anchor"))) expect_true(length(yanchor) == 1) xanchor <- unique(unlist(lapply(yaxes, "[[", "anchor"))) expect_true(length(xanchor) == 1) expect_true(l$layout[[sub("x", "xaxis", xanchor)]]$domain[1] == 0) expect_true(l$layout[[sub("y", "yaxis", yanchor)]]$domain[1] == 0) xTraceAnchors <- sapply(l$data, "[[", "xaxis") yTraceAnchors <- sapply(l$data, "[[", "yaxis") expect_true(length(unique(paste(xTraceAnchors, yTraceAnchors))) == 4) }) test_that("subplot accepts a list of plots", { vars <- setdiff(names(economics), "date") plots <- lapply(vars, function(var) { plot_ly(x = economics$date, y = economics[[var]], name = var) }) s <- subplot(plots, nrows = length(plots), shareX = TRUE, titleX = FALSE) l <- expect_traces(s, 5, "plot-list") xaxes <- l$layout[grepl("^xaxis", names(l$layout))] yaxes <- l$layout[grepl("^yaxis", names(l$layout))] expect_true(length(xaxes) == 1) expect_true(length(yaxes) == 5) expect_true(l$layout[[sub("y", "yaxis", xaxes[[1]]$anchor)]]$domain[1] == 0) }) test_that("ggplotly understands GGally", { skip_if_not_installed("GGally") expect_doppelganger( GGally::ggpairs(iris), "plotly-subplot-ggmatrix" ) d <- tibble::tibble( v1 = 1:100 + rnorm(100, sd = 20), v2 = 1:100 + rnorm(100, sd = 27), v3 = rep(1, 100) + rnorm(100, sd = 1), v4 = v1 ** 2, v5 = v1 ** 2 ) expect_doppelganger( ggcorr(data, method = c("everything", "pearson")), "ggally-ggcorr" ) }) test_that("annotation paper repositioning", { p1 <- plot_ly(type = "scatter") %>% add_annotations(text = "foo", x = 0.5, y = 0.5, xref = "paper", yref = "paper") p2 <- plot_ly(mtcars, type = "scatter") %>% add_annotations(text = "bar", x = 0.5, y = 0.5, xref = "paper", yref = "paper") s <- subplot(p1, p2, margin = 0) ann <- expect_doppelganger_built(s, "subplot-reposition-annotation")$layout$annotations expect_length(ann, 2) text <- sapply(ann, "[[", "text") x <- sapply(ann, "[[", "x") y <- sapply(ann, "[[", "y") xref <- sapply(ann, "[[", "xref") yref <- sapply(ann, "[[", "yref") expect_equal(x, c(0.25, 0.75)) expect_equal(y, c(0.5, 0.5)) expect_equal(xref, rep("paper", 2)) expect_equal(yref, rep("paper", 2)) }) test_that("shape paper repositioning", { p1 <- plot_ly(mtcars, type = "scatter") %>% layout( shapes = ~list( type = "rect", x0 = 0.25, x1 = 0.75, y0 = 0.25, y1 = 0.75, xref = "paper", yref = "paper", fillcolor = "red" ) ) p2 <- plot_ly(mtcars, type = "scatter") %>% layout( shapes = ~list( type = "line", type = "rect", x0 = 0.25, x1 = 0.75, y0 = 0.25, y1 = 0.75, xref = "paper", yref = "paper", line = list(color = "blue") ) ) s <- subplot(p1, p2) shapes <- expect_doppelganger_built(s, "subplot-reposition-shape")$layout$shapes expect_length(shapes, 2) x0 <- sapply(shapes, "[[", "x0") x1 <- sapply(shapes, "[[", "x1") y0 <- sapply(shapes, "[[", "y0") y1 <- sapply(shapes, "[[", "y1") xref <- sapply(shapes, "[[", "xref") yref <- sapply(shapes, "[[", "yref") expect_equal(x0, c(0.12, 0.64)) expect_equal(x1, c(0.36, 0.88)) expect_equal(y0, rep(0.25, 2)) expect_equal(y1, rep(0.75, 2)) expect_equal(xref, rep("paper", 2)) expect_equal(yref, rep("paper", 2)) p1 <- plot_ly(type = "scatter") %>% layout( shapes = list( type = "rect", x0 = 0.25, x1 = 0.75, xref = "paper", y0 = 0, y1 = 30, yanchor = 0.5, ysizemode = "pixel", yref = "paper", fillcolor = "red" ) ) p2 <- plot_ly(type = "scatter") %>% layout( shapes = list( type = "rect", y0 = 0.25, y1 = 0.75, yref = "paper", x0 = 0, x1 = 30, xanchor = 0.5, xsizemode = "pixel", xref = "paper", line = list(color = "blue") ) ) s <- subplot(p1, p2) shapes <- expect_doppelganger_built(s, "subplot-reposition-shape-fixed")$layout$shapes expect_length(shapes, 2) xanchor <- lapply(shapes, "[[", "xanchor")[[2]] yanchor <- lapply(shapes, "[[", "yanchor")[[1]] x0 <- sapply(shapes, "[[", "x0") x1 <- sapply(shapes, "[[", "x1") y0 <- sapply(shapes, "[[", "y0") y1 <- sapply(shapes, "[[", "y1") expect_equal(xanchor, 0.76) expect_equal(yanchor, 0.5) expect_equal(x0, c(0.12, 0)) expect_equal(x1, c(0.36, 30)) expect_equal(y0, c(0, 0.25)) expect_equal(y1, c(30, 0.75)) }) test_that("image paper repositioning", { skip_if_not_installed("png") r <- as.raster(matrix(hcl(0, 80, seq(50, 80, 10)), nrow = 4, ncol = 5)) p <- plot_ly(x = 1, y = 1) %>% layout( images = list(list( source = raster2uri(r), sizing = "fill", xref = "paper", yref = "paper", x = 0, y = 0, sizex = 0.5, sizey = 0.5, xanchor = "left", yanchor = "bottom" )) ) s <- subplot(p, p, nrows = 1, margin = 0.02) imgs <- expect_doppelganger_built(s, "subplot-reposition-image")$layout$images expect_length(imgs, 2) x <- sapply(imgs, "[[", "x") y <- sapply(imgs, "[[", "y") sizex <- sapply(imgs, "[[", "sizex") sizey <- sapply(imgs, "[[", "sizey") expect_equal(x, c(0, 0.52)) expect_equal(y, c(0, 0)) expect_equal(sizex, rep(0.24, 2)) expect_equal(sizey, rep(0.5, 2)) }) test_that("annotation xref/yref bumping", { p1 <- plot_ly(mtcars) %>% add_annotations(text = ~cyl, x = ~wt, y = ~mpg) p2 <- plot_ly(mtcars) %>% add_annotations(text = ~am, x = ~wt, y = ~mpg) s <- subplot(p1, p2) ann <- expect_doppelganger_built(s, "subplot-bump-axis-annotation")$layout$annotations txt <- sapply(ann, "[[", "text") xref <- sapply(ann, "[[", "xref") yref <- sapply(ann, "[[", "yref") expect_length(ann, 64) expect_equal(txt, c(mtcars$cyl, mtcars$am)) expect_equal(xref, rep(c("x", "x2"), each = 32)) expect_equal(yref, rep(c("y", "y2"), each = 32)) s2 <- subplot(p1, p2, shareY = TRUE) ann2 <- expect_doppelganger_built(s2, "subplot-bump-axis-annotation-shared")$layout$annotations xref2 <- sapply(ann2, "[[", "xref") yref2 <- sapply(ann2, "[[", "yref") expect_equal(xref2, rep(c("x", "x2"), each = 32)) expect_equal(yref2, rep(c("y", "y"), each = 32)) p1 <- plot_ly() %>% add_markers(x = 1, y = 1) %>% add_markers(x = 2, y = 2) %>% add_annotations(text = "foo", x = 1.5, y = 1.5) p2 <- plot_ly() %>% add_markers(x = 1, y = 1) %>% add_markers(x = 2, y = 2) %>% add_annotations(text = "bar", x = 1.5, y = 1.5) s <- subplot(p1, p2) ann <- expect_doppelganger_built(s, "subplot-bump-axis-annotation-traces")$layout$annotations txt <- sapply(ann, "[[", "text") xref <- sapply(ann, "[[", "xref") yref <- sapply(ann, "[[", "yref") expect_length(ann, 2) expect_equal(txt, c("foo", "bar")) expect_equal(xref, c("x", "x2")) expect_equal(yref, c("y", "y2")) s2 <- subplot(p1, p2, shareY = TRUE) ann2 <- expect_doppelganger_built(s2, "subplot-bump-axis-annotation-traces-shared")$layout$annotations xref2 <- sapply(ann2, "[[", "xref") yref2 <- sapply(ann2, "[[", "yref") expect_equal(xref2, c("x", "x2")) expect_equal(yref2, c("y", "y")) }) test_that("shape xref/yref bumping", { p1 <- plot_ly(mtcars, type = "scatter") %>% layout( shapes = ~list( type = "rect", x0 = min(cyl), x1 = max(cyl), y0 = min(am), y1 = max(am), fillcolor = "red" ) ) p2 <- plot_ly(mtcars, type = "scatter") %>% layout( shapes = ~list( type = "line", x0 = min(cyl), x1 = max(cyl), y0 = min(am), y1 = max(am), line = list(color = "blue") ) ) s <- subplot(p1, p2) shapes <- expect_doppelganger_built(s, "subplot-bump-axis-shape")$layout$shapes expect_length(shapes, 2) types <- sapply(shapes, "[[", "type") expect_equal(types, c("rect", "line")) xref <- sapply(shapes, "[[", "xref") yref <- sapply(shapes, "[[", "yref") expect_equal(xref, c("x", "x2")) expect_equal(yref, c("y", "y2")) s2 <- subplot(p1, p2, shareY = TRUE) shapes2 <- expect_doppelganger_built(s2, "subplot-bump-axis-shape-shared")$layout$shapes xref2 <- sapply(shapes2, "[[", "xref") yref2 <- sapply(shapes2, "[[", "yref") expect_equal(xref2, c("x", "x2")) expect_equal(yref2, c("y", "y")) }) test_that("image xref/yref bumping", { skip_if_not_installed("png") r <- as.raster(matrix(hcl(0, 80, seq(50, 80, 10)), nrow = 4, ncol = 5)) p <- plot_ly(x = 1, y = 1) %>% layout( images = list(list( source = raster2uri(r), sizing = "fill", xref = "x", yref = "y", x = 0, y = 0, sizex = 1, sizey = 1, xanchor = "left", yanchor = "bottom" )) ) s <- subplot(p, p, nrows = 1, margin = 0.02) imgs <- expect_doppelganger_built(s, "subplot-bump-axis-image")$layout$images expect_length(imgs, 2) x <- sapply(imgs, "[[", "x") y <- sapply(imgs, "[[", "y") xref <- sapply(imgs, "[[", "xref") yref <- sapply(imgs, "[[", "yref") expect_equal(x, c(0, 0)) expect_equal(y, c(0, 0)) expect_equal(xref, c("x", "x2")) expect_equal(yref, c("y", "y2")) }) test_that("geo+cartesian behaves", { g <- list( scope = 'usa', projection = list(type = 'albers usa'), lakecolor = toRGB('white') ) density <- state.x77[, "Population"] / state.x77[, "Area"] map <- plot_geo( z = ~density, text = state.name, locations = state.abb, locationmode = 'USA-states' ) %>% layout(geo = g) vars <- colnames(state.x77) barcharts <- lapply(vars, function(var) { plot_ly(x = state.x77[, var], y = state.name, type = "bar", orientation = "h", name = var) %>% layout(showlegend = FALSE, hovermode = "y", yaxis = list(showticklabels = FALSE)) }) s <- subplot( subplot(barcharts, margin = 0.01), map, nrows = 2, heights = c(0.3, 0.7) ) l <- expect_traces(s, 9, "geo-cartesian") geoDom <- l$layout[[grep("^geo", names(l$layout))]]$domain expect_equivalent(geoDom$x, c(0, 1)) expect_equivalent(geoDom$y, c(0, 0.68)) }) test_that("May specify legendgroup with through a vector of values", { df <- dplyr::bind_rows( data.frame(x = rnorm(100,2), Name = "x1"), data.frame(x = rnorm(100,6), Name = "x2"), data.frame(x = rnorm(100,4), Name = "x3") ) df$y <- rnorm(300) m <- list( size = 10, line = list( width = 1, color = "black" ) ) base <- plot_ly( df, marker = m, color = ~factor(Name), legendgroup = ~factor(Name) ) expect_warning( s <- subplot( add_histogram(base, x = ~x, showlegend = FALSE), plotly_empty(), add_markers(base, x = ~x, y = ~y), add_histogram(base, y = ~y, showlegend = FALSE), nrows = 2, heights = c(0.2, 0.8), widths = c(0.8, 0.2), shareX = TRUE, shareY = TRUE, titleX = FALSE, titleY = FALSE) %>% layout(barmode = "stack"), regexp = "No trace type|No scatter mode" ) l <- expect_traces(s, 10, "subplot-legendgroup") expect_equivalent( sum(sapply(l$data, function(tr) tr$showlegend %||% TRUE)), 4 ) expect_length( unlist(lapply(l$data, "[[", "legendgroup")), 9 ) })
NULL ValidCorrGpois = function (corMat, theta.vec, lambda.vec, verbose = TRUE) { no.gpois = length(theta.vec) errorCount = 0 if (ncol(corMat) != (no.gpois)) { stop("Dimension of correlation matrix does not match the number of variables!\n") } if (is.positive.definite(corMat) == FALSE) { stop("Specified correlation matrix is not positive definite! \n") } if (isSymmetric(corMat) == FALSE) { stop("Specified correlation matrix is not symmetric! \n") } if (sum(corMat > 1) > 0) { stop("Correlation values cannot be greater than 1! \n") } if (sum(corMat < (-1)) > 0) { stop("Correlation values cannot be less than -1! \n") } if (sum(diag(corMat) != 1) > 0) { stop("All diagonal elements of the correlation matrix must be 1! \n") } maxcor = ComputeCorrGpois(theta.vec, lambda.vec, verbose)$max mincor = ComputeCorrGpois(theta.vec, lambda.vec, verbose)$min for (i in 1:nrow(corMat)) { for (j in 1:i) { if (errorCount == 0) { if (verbose == TRUE) { cat(".") } } if (i != j) { if (corMat[i, j] > maxcor[i, j] | corMat[i, j] < mincor[i, j]) { cat("\n corMat[", i, ",", j, "] must be between ", round(mincor[i,j], 3), " and ", round(maxcor[i,j], 3), "\n") errorCount = errorCount + 1 } } } } if (verbose == TRUE) { cat("\n") } if (errorCount > 0) { stop("Range violation occurred in the target correlation matrix!\n") } return(TRUE) }
props <- function(..., .props = NULL, inherit = TRUE, env = parent.frame()) { check_empty_args() args <- dots(...) all <- args_to_props(c(args, .props), env) structure( all, inherit = inherit, class = "ggvis_props" ) } dots <- function(...) { as.list(substitute(...())) } uses_colon_equals <- function(x) { is.call(x) && identical(x[[1]], quote(`:=`)) } args_to_props <- function(args, env) { expr_to_prop <- function(name, expr, scale = NULL) { name <- strsplit(name, ".", fixed = TRUE)[[1]] property <- name[1] event <- if (length(name) > 1) name[2] else NULL val <- eval(expr, env) prop(property, val, scale = scale, event = event, label = as.character(val)) } prop_full_name <- function(p) { paste(c(p$property, p$event), collapse = ".") } arg_names <- names2(args) named_args <- args[arg_names != ""] unnamed_args <- args[arg_names == ""] named_args <- Map(named_args, names(named_args), f = function(x, name) expr_to_prop(name, x, scale = TRUE) ) unnamed_args <- lapply(unnamed_args, function(x) { if (uses_colon_equals(x)) { expr_to_prop(deparse(x[[2]]), x[[3]], scale = FALSE) } else { eval(x, env) } }) is_prop <- vapply(unnamed_args, is.prop, logical(1)) unnamed_props <- unnamed_args[is_prop] unnamed_values <- unnamed_args[!is_prop] names(named_args) <- vapply(named_args, prop_full_name, character(1)) names(unnamed_props) <- vapply(unnamed_props, prop_full_name, character(1)) missing_names <- setdiff(c("x.update", "y.update"), c(names(named_args), names(unnamed_props))) if (length(unnamed_values) > length(missing_names)) { stop("Too many unnamed properties (can only have x and y)", call. = FALSE) } names(unnamed_values) <- missing_names[seq_along(unnamed_values)] unnamed_values <- Map(unnamed_values, names(unnamed_values), f = function(x, name) expr_to_prop(name, x, scale = TRUE) ) c(named_args, unnamed_props, unnamed_values) } format.ggvis_props <- function(x, ...) { labels <- lapply(x, format, ...) if (length(labels) > 0) { inherit <- if (!attr(x, "inherit", TRUE)) "\ninherit: FALSE" else "" paste0( paste0("* ", names(x), ": ", labels, collapse = "\n"), inherit, sep = "\n") } else { "props()" } } print.ggvis_props <- function(x, ...) cat(format(x, ...)) is.ggvis_props <- function(x) inherits(x, "ggvis_props") `[.ggvis_props` <- function(x, idx) { structure(NextMethod(), inherit = attr(x, "inherit", TRUE), class = "ggvis_props") } merge_props <- function(parent = NULL, child = NULL, inherit = attr(child, "inherit", TRUE)) { if (is.null(parent)) return(child) if (is.null(child)) return(parent) stopifnot(is.ggvis_props(parent), is.ggvis_props(child)) if (identical(inherit, FALSE)) return(child) structure(merge_vectors(parent, child), inherit = attr(parent, "inherit", TRUE), class = "ggvis_props") } is.formula <- function(x) inherits(x, "formula") find_prop_var <- function(props, name) { prop <- props[[name]] if (is.null(prop)) { stop("Can't find prop ", name, call. = FALSE) } if (!is.prop_variable(prop)) { stop("Visual property ", name, " is not a variable", call. = FALSE) } stats::formula(prop) }
fluidPage( fluidRow( bs4Box( title="Settings for group accuracy", width=4, uiOutput("locGroups"), sliderInput("locLevel", label=h5("Confidence interval width"), min=0.5, max=1, value=0.95, step=0.01), checkboxGroupInput("locCItype", label=h5("Bootstrap CI type"), choices=CItypes, selected=NULL) ), bs4Box( title="Group accuracy", width=8, p("For details, see the documentation for", a("groupLocation()", href="https://www.rdocumentation.org/packages/shotGroups/functions/groupLocation"), "and the", a("shotGroups vignette", href="https://cran.rstudio.com/web/packages/shotGroups/vignettes/shotGroups.pdf"), "section 2.5"), selectizeInput("locationOut", label=h5("Select the output elements you want to see"), choices=locationOut, multiple=TRUE, selected=c("1", "3", "5", "6", "7"), width="100%"), downloadButton("saveLocation", "Save results as text file"), verbatimTextOutput("location"), downloadButton("saveLocationPDF", "Save diagram as pdf"), plotOutput("locationPlot", height="500px") ) ) )
npar.ellip <- function(dim, dispstr) { switch(dispstr, "ar1" =, "ex" = 1 , "un" = dim * (dim - 1) / 2, "toep" = dim - 1, stop("'dispstr' not supported (yet)")) } lowbnd.rho.ellip <- function(dim, dispstr, pdim = npar.ellip(dim, dispstr)) { switch(dispstr, "ex" = rep( - 1 / (dim-1), pdim), "ar1"= rep( -1, pdim), "un" = , "toep" = rep(-1, pdim), return("'dispstr' not supported (yet)")) } ellipCopula <- function(family = c("normal", "t"), param = NA_real_, dim = 2L, dispstr = "ex", df = 4, ...) { switch(match.arg(family), "normal" = normalCopula(param, dim = dim, dispstr = dispstr), "t" = tCopula(param, dim = dim, dispstr = dispstr, df = df, ...)) } setMethod(describeCop, c("ellipCopula", "character"), function(x, kind, prefix="", ...) { kind <- match.arg(kind) cl <- sub("Copula$", "", class(x)) if (cl == "normal") cl <- "Normal" clNam <- paste0(prefix, cl, if(nchar(cl) <= 2) "-" else " ", "copula") if(kind == "very short") return(clNam) d <- dim(x) ch <- paste(paste0(clNam, ", dim. d ="), d) switch(kind <- match.arg(kind), short = ch, long = paste0(ch, "\n", prefix, "param.: ", dputNamed(getTheta(x, named=TRUE))), stop("invalid 'kind': ", kind)) }) iTauEllipCopula <- function(copula, tau) sinpi(tau / 2) dTauEllipCopula <- function(copula) { 2 / (pi * sqrt(1 - copula@getRho(copula)^2)) } dTauFunEllipCopula <- function(copula) { function(x) 2 / (pi * sqrt(1 - x^2)) } dRhoEllipCopula <- function(copula) { 6 / (pi * sqrt(4 - copula@getRho(copula)^2)) } dRhoFunEllipCopula <- function(copula) { function(x) 6 / (pi * sqrt(4 - x^2)) } setMethod("iTau", signature("ellipCopula"), iTauEllipCopula) setMethod("dTau", signature("ellipCopula"), dTauEllipCopula) setMethod("dRho", signature("ellipCopula"), dRhoEllipCopula) setMethod("dTauFun", signature("ellipCopula"), dTauFunEllipCopula) setMethod("dRhoFun", signature("ellipCopula"), dRhoFunEllipCopula)
context("testing calculating icer nmb") test_that("testing calculating icer nmb", { well <- health_state("well", cost = 0, utility = 1) disabled <- health_state("disabled", cost = 100, utility = 1) dead <- health_state("dead", cost = 0, utility = 0) tmat <- rbind(c(1, 2, 3), c(NA, 4, 5), c(NA, NA, 6)) colnames(tmat) <- rownames(tmat) <- c("well", "disabled", "dead") tm <- populate_transition_matrix(3, tmat, c(0.6, 0.2, 0.2, 0.6, 0.4, 1), colnames(tmat)) health_states <- combine_state(well, disabled, dead) this_strategy <- strategy(tm, health_states, "control") this_markov <- markov_model(this_strategy, 24, c(1000, 0, 0), discount = c(0, 0)) well <- health_state("well", cost = 0, utility = 1) disabled <- health_state("disabled", cost = 10, utility = 0.5) dead <- health_state("dead", cost = 0, utility = 0) tmat <- rbind(c(1, 2, 3), c(NA, 4, 5), c(NA, NA, 6)) colnames(tmat) <- rownames(tmat) <- c("well", "disabled", "dead") tm <- populate_transition_matrix(3, tmat, c(0.4, 0.4, 0.2, 0.6, 0.4, 1), colnames(tmat)) health_states <- combine_state(well, disabled, dead) this_strategy <- strategy(tm, health_states, "intervention") sec_markov <- markov_model(this_strategy, 24, c(1000, 0, 0), discount = c(0, 0)) list_markov <- combine_markov(this_markov, sec_markov) icer_nmb <- calculate_icer_nmb(list_markov, 20000, comparator = "control") expect_equal(as.numeric(icer_nmb$ICER[2]), 86.67, tol = 1e-3) expect_equal(as.numeric(icer_nmb$ICER[2]), 86.67, tol = 1e-3) expect_error(calculate_icer_nmb(list_markov, 20000, comparator = "con")) expect_error(calculate_icer_nmb(list_markov, 0, comparator = "control")) expect_error(calculate_icer_nmb(NULL, 200, comparator = "control")) icer_nmb <- calculate_icer_nmb(list_markov, 200, comparator = NULL) expect_equal(as.numeric(icer_nmb$NMB[1]), 524.9899, tol = 1e-3) well <- health_state("well", cost = 0, utility = 1) disabled <- health_state("disabled", cost = 100, utility = 1) dead <- health_state("dead", cost = 0, utility = 0) tmat <- rbind(c(1, 2, 3), c(NA, 4, 5), c(NA, NA, 6)) colnames(tmat) <- rownames(tmat) <- c("well", "disabled", "dead") tm <- populate_transition_matrix(3, tmat, c(0.6, 0.2, 0.2, 0.6, 0.4, 1), colnames(tmat)) health_states <- combine_state(well, disabled, dead) this_strategy <- strategy(tm, health_states, "control") this_markov <- markov_model(this_strategy, 24, c(1000, 0, 0), discount = c(0, 0)) well <- health_state("well", cost = 0, utility = 1) disabled <- health_state("disabled", cost = 10, utility = 0.5) dead <- health_state("dead", cost = 0, utility = 0) tmat <- rbind(c(1, 2, 3), c(NA, 4, 5), c(NA, NA, 6)) colnames(tmat) <- rownames(tmat) <- c("well", "disabled", "dead") tm <- populate_transition_matrix(3, tmat, c(0.4, 0.4, 0.2, 0.6, 0.4, 1), colnames(tmat)) health_states <- combine_state(well, disabled, dead) this_strategy <- strategy(tm, health_states, "intervention") sec_markov <- markov_model(this_strategy, 12, c(1000, 0, 0), discount = c(0, 0)) list_markov <- combine_markov(this_markov, sec_markov) expect_error(calculate_icer_nmb(list_markov, 20000, comparator = "control")) sec_markov <- markov_model(this_strategy, 24, c(1000, 0, 0), discount = c(0, 0)) list_markov <- combine_markov(this_markov, sec_markov) newcolnames <- colnames(list_markov) newcolnames[2] <- "changedcost" colnames(list_markov) <- newcolnames expect_error(calculate_icer_nmb(list_markov, 20000, comparator = "control")) }) context("testing checking list of markov models") test_that("testing checking list of markov models", { well <- health_state("well", cost = 0, utility = 1) disabled <- health_state("disabled", cost = 100, utility = 1) dead <- health_state("dead", cost = 0, utility = 0) tmat <- rbind(c(1, 2, 3), c(NA, 4, 5), c(NA, NA, 6)) colnames(tmat) <- rownames(tmat) <- c("well", "disabled", "dead") tm <- populate_transition_matrix(3, tmat, c(0.6, 0.2, 0.2, 0.6, 0.4, 1), colnames(tmat)) health_states <- combine_state(well, disabled, dead) this_strategy <- strategy(tm, health_states, "control") this_markov <- markov_model(this_strategy, 24, c(1000, 0, 0), discount = c(0, 0)) well <- health_state("well", cost = 0, utility = 1) disabled <- health_state("disabled", cost = 10, utility = 0.5) dead <- health_state("dead", cost = 0, utility = 0) tmat <- rbind(c(1, 2, 3), c(NA, 4, 5), c(NA, NA, 6)) colnames(tmat) <- rownames(tmat) <- c("well", "disabled", "dead") tm <- populate_transition_matrix(3, tmat, c(0.4, 0.4, 0.2, 0.6, 0.4, 1), colnames(tmat)) health_states <- combine_state(well, disabled, dead) this_strategy <- strategy(tm, health_states, "intervention") sec_markov <- markov_model(this_strategy, 24, c(1000, 0, 0), discount = c(0, 0)) list_markov <- combine_markov(this_markov, sec_markov) expect_equal(check_list_markov_models(list_markov), 0) this_strategy <- strategy(tm, health_states, "control") sec_markov <- markov_model(this_strategy, 24, c(1000, 0, 0), discount = c(0, 0)) list_markov <- combine_markov(this_markov, sec_markov) expect_error(check_list_markov_models(list_markov)) this_strategy <- strategy(tm, health_states, "intervention") sec_markov <- markov_model(this_strategy, 12, c(1000, 0, 0), discount = c(0, 0)) list_markov <- combine_markov(this_markov, sec_markov) expect_error(check_list_markov_models(list_markov)) this_strategy <- strategy(tm, health_states, "intervention") sec_markov <- markov_model(this_strategy, 24, c(500, 0, 0), discount = c(0, 0)) list_markov <- combine_markov(this_markov, sec_markov) expect_error(check_list_markov_models(list_markov)) well <- health_state("well", cost = 0, utility = 1) disabled <- health_state("disabled", cost = 10, utility = 0.5) dead <- health_state("dead", cost = 0, utility = 0) dead2 <- health_state("dead2", cost = 0, utility = 0) tmat <- rbind(c(1, 2, 3, 4), c(NA, 5, 6, 7), c(NA, NA, 8, 9), c(NA, NA, NA, 10)) colnames(tmat) <- rownames(tmat) <- c("well", "disabled", "dead", "dead2") tm <- populate_transition_matrix(4, tmat, c(0.4, 0.3, 0.2, 0.1, 0.5, 0.4, 0.1, 0.5, 0.5, 1), colnames(tmat)) health_states <- combine_state(well, disabled, dead, dead2) this_strategy <- strategy(tm, health_states, "intervention") sec_markov <- markov_model(this_strategy, 24, c(1000, 0, 0, 0), discount = c(0, 0)) list_markov <- combine_markov(this_markov, sec_markov) expect_error(check_list_markov_models(list_markov)) }) context("testing plotting ceac") test_that("testing plotting ceac", { well <- health_state("well", cost = 0, utility = 1) disabled <- health_state("disabled", cost = 100, utility = 1) dead <- health_state("dead", cost = 0, utility = 0) tmat <- rbind(c(1, 2, 3), c(NA, 4, 5), c(NA, NA, 6)) colnames(tmat) <- rownames(tmat) <- c("well", "disabled", "dead") tm <- populate_transition_matrix(3, tmat, c(0.6, 0.2, 0.2, 0.6, 0.4, 1), colnames(tmat)) health_states <- combine_state(well, disabled, dead) this.strategy <- strategy(tm, health_states, "control") this_markov <- markov_model(this.strategy, 24, c(1000, 0, 0), c(0, 0)) well <- health_state("well", cost = 0, utility = 1) disabled <- health_state("disabled", cost = 10, utility = 0.5) dead <- health_state("dead", cost = 0, utility = 0) tmat <- rbind(c(1, 2, 3), c(NA, 4, 5), c(NA, NA, 6)) colnames(tmat) <- rownames(tmat) <- c("well", "disabled", "dead") tm <- populate_transition_matrix(3, tmat, c(0.4, 0.4, 0.2, 0.6, 0.4, 1), colnames(tmat)) health_states <- combine_state(well, disabled, dead) this.strategy <- strategy(tm, health_states, "intervention") sec_markov <- markov_model(this.strategy, 24, c(1000, 0, 0), c(0, 0)) list_markov <- combine_markov(this_markov, sec_markov) plot_ceac(list_markov, c(1000, 2000, 3000), comparator = "control") expect_error(plot_ceac(NULL, c(1000, 2000, 3000), comparator = "control")) expect_error(plot_ceac(list_markov, NULL, comparator = "control")) expect_error(plot_ceac(list_markov, c(1000), comparator = "control")) }) context("testing plotting efficieny frontier") test_that("testing plotting efficieny frontier", { well <- health_state("well", cost = 0, utility = 1) disabled <- health_state("disabled", cost = 100, utility = 1) dead <- health_state("dead", cost = 0, utility = 0) tmat <- rbind(c(1, 2, 3), c(NA, 4, 5), c(NA, NA, 6)) colnames(tmat) <- rownames(tmat) <- c("well", "disabled", "dead") tm <- populate_transition_matrix(3, tmat, c(0.6, 0.2, 0.2, 0.6, 0.4, 1), colnames(tmat)) health_states <- combine_state(well, disabled, dead) this.strategy <- strategy(tm, health_states, "control") this_markov <- markov_model(this.strategy, 24, c(1000, 0, 0), c(0, 0)) well <- health_state("well", cost = 0, utility = 1) disabled <- health_state("disabled", cost = 10, utility = 0.5) dead <- health_state("dead", cost = 0, utility = 0) tmat <- rbind(c(1, 2, 3), c(NA, 4, 5), c(NA, NA, 6)) colnames(tmat) <- rownames(tmat) <- c("well", "disabled", "dead") tm <- populate_transition_matrix(3, tmat, c(0.4, 0.4, 0.2, 0.6, 0.4, 1), colnames(tmat)) health_states <- combine_state(well, disabled, dead) this.strategy <- strategy(tm, health_states, "intervention") sec_markov <- markov_model(this.strategy, 24, c(1000, 0, 0), c(0, 0)) list_markov <- combine_markov(this_markov, sec_markov) results_cea <- calculate_icer_nmb(list_markov, 20000, comparator = "control") plot_efficiency_frontier(results_cea, c(1000, 2000)) expect_error(plot_efficiency_frontier(NULL, c(1000, 2000))) expect_error(plot_efficiency_frontier(results_cea, NULL)) newcolnames <- colnames(results_cea) newcolnames[2] <- "changedcost" colnames(results_cea) <- newcolnames expect_error(plot_efficiency_frontier(results_cea, c(1000, 2000))) })
nearValue <- function(X, Z, tau, tol = 0.001, maxiter = 100, verbose = TRUE){ pre <- preprocessInputs(data.x = X, data.z = Z) X <- pre$data.x Z <- pre$data.z nCov <- ncol(Z) - 2L rm(pre) bHat <- betaEst(Z = Z, X = X, tau = tau, tol = tol, h = 0, kType = "epan", betaGuess = NULL, maxiter = maxiter, scoreFunction = "scoreNVCF") score <- scoreNVCF(beta = bHat, Z = Z, X = X, tau = tau, h = 0, kType = "epan") invdU <- try(solve(score$dUdBeta), silent = TRUE) if( is(invdU, 'try-error') ) { cat("unable to invert derivative of estimating equation\n") stop(attr(invdU,"condition")) } sig <- invdU %*% (score$mMatrix) %*% invdU sdVec <- sqrt(diag(sig)) results <- matrix(data = 0.0, nrow = nCov, ncol = 4L, dimnames = list(paste("beta",1L:{nCov},sep=""), c("estimate","stdErr","z-value","p-value"))) results[,1L] <- bHat results[,2L] <- sdVec results[,3L] <- bHat/sdVec results[,4L] <- 2.0*pnorm(-abs(results[,3L])) if (verbose) print(results) zv <- bHat/sdVec pv <- 2.0*pnorm(-abs(zv)) return( list( "betaHat" = matrix(bHat,nrow=1L), "stdErr" = sdVec, "zValue" = bHat/sdVec, "pValue" = pv ) ) }
get.Pcent <- function(theMap) { .Deprecated("", package="maptools", msg="exrtact centroid from SpatialPolygons object;\nobjects other than Spatial objects defined in the sp package are deprecated") p.cent <- function(poly, flag) { cent <- .External("RshpCentrd_2d", poly, as.integer(flag), PACKAGE="maptools") cent } if (!inherits(theMap,"Map")) stop("not a Map object") theShapes <- theMap$Shapes if (attr(theShapes,'shp.type') != 'poly') stop("Must be a valid polygon shapelist") cent<-lapply(theShapes, p.cent, 0) return(matrix(unlist(cent), ncol=2, byrow=TRUE)) }
BootstrapVaRFigure <- function(Ra, number.resamples, cl){ if (nargs() < 3){ stop("Too few arguments") } if (nargs() > 3){ stop("Too many arguments") } profit.loss.data <- as.vector(Ra) unsorted.loss.data <- -profit.loss.data losses.data <- sort(unsorted.loss.data) n <- length(losses.data) if (is.vector(cl) & (length(cl) != 1) ) { stop("Confidence level must be a scalar") } if (length(number.resamples) != 1) { stop("Number of resamples must be a scalar") } if (cl >= 1){ stop("Confidence level must be less that 1") } if (cl <= 0){ stop("Confidence level must be at least 0") } if (number.resamples <= 0){ stop("Number of resamples must be at least 0") } VaR <- bootstrap(losses.data, number.resamples, HSVaR, cl)$thetastar mean.VaR <- mean(VaR) std.VaR <- sd(VaR) min.VaR <- min(VaR) max.VaR <- max(VaR) ninety.five.perc.conf.interval <- quantile(VaR, c(.05, .95)) cl.for.label <- 100*cl hist(VaR, 30, xlab="VaR", ylab="Frequency", main=paste("Bootstrapped Historical Simulation VaR at", cl, "% Confidence Level")) }
"assembly"
art.con = function( m, formula, response = "art", factor.contrasts="contr.sum", method = "pairwise", interaction = FALSE, adjust, ... ) { f.parsed = parse.art.con.formula(formula) if (interaction) { art.interaction.contrast = do.art.interaction.contrast(m, f.parsed, response, factor.contrasts, method, adjust, ...) art.interaction.contrast } else { artlm.con = artlm.con.internal(m, f.parsed, response, factor.contrasts, ...) art.contrast = do.art.contrast(f.parsed, artlm.con, method, adjust) art.contrast } }
[ { "title": "Ordinal Data", "href": "http://wiekvoet.blogspot.com/2013/03/ordinal-data.html" }, { "title": "stringdist 0.9.4 and 0.9.3: distances between integer sequences", "href": "http://www.markvanderloo.eu/yaRb/2015/10/27/stringdist-0-9-4-and-0-9-3-distances-between-integer-sequences/" }, { "title": "Sequence generation with no duplicate pairs", "href": "http://shape-of-code.coding-guidelines.com/2012/10/04/sequence-generation-with-no-duplicate-pairs/" }, { "title": "In case you missed it: February 2015 roundup", "href": "http://blog.revolutionanalytics.com/2015/03/in-case-you-missed-it-february-2015-roundup.html" }, { "title": "Matlab-style multiple assignment in R", "href": "https://strugglingthroughproblems.wordpress.com/2010/08/27/matlab-style-multiple-assignment-in%C2%A0r/" }, { "title": "Introduction to exception handling", "href": "http://gallery.rcpp.org/articles/intro-to-exceptions/" }, { "title": "glmnetUtils: quality of life enhancements for elastic net regression with glmnet", "href": "http://blog.revolutionanalytics.com/2016/11/glmnetutils.html" }, { "title": "Building a DGA Classifer: Part 2, Feature Engineering", "href": "http://datadrivensecurity.info/blog/posts/2014/Oct/dga-part2/" }, { "title": "R and Science of Predictive Analytics", "href": "http://datascience.vegas/r-science-predictive-analytics/" }, { "title": "How Much Can We Learn from Top Rankings using Nonnegative Matrix Factorization?", "href": "http://joelcadwell.blogspot.com/2014/07/how-much-can-we-learn-from-top-rankings.html" }, { "title": "Typo in Example 5.18", "href": "https://xianblog.wordpress.com/2010/10/03/typo-in-example-5-18/" }, { "title": "Simple analysis of a few aspects of the Wikipedia World cup 2014 squads data", "href": "http://rscriptsandtips.blogspot.com/2014/05/simple-analysis-of-few-aspects-of.html" }, { "title": "Momentum in R: Part 4 with Quantstrat", "href": "https://rbresearch.wordpress.com/2013/02/19/momentum-in-r-part-4-with-quantstrat/" }, { "title": "Maximum Likelihood versus Goodness of Fit", "href": "http://freakonometrics.hypotheses.org/10069" }, { "title": "A quick analysis of the trends in the number of weddings in France (1975–2010)", "href": "https://web.archive.org/web/http://timotheepoisot.fr/2010/08/a-quick-analysis-of-the-trends-in-the-number-of-weddings-in-france-1975%E2%80%932010/" }, { "title": "Searching for duplicate resource names in PMC article titles", "href": "https://nsaunders.wordpress.com/2015/09/16/searching-for-duplicate-resource-names-in-pmc-article-titles/" }, { "title": "rnpn: An R interface for the National Phenology Network", "href": "https://r-ecology.blogspot.com/2011/08/rnpn-r-interface-for-national-phenology.html" }, { "title": "Text bashing in R for SQL", "href": "http://www.beardedanalytics.com/text-bashing-in-r-for-sql/" }, { "title": "Visualising a Circular Density", "href": "http://freakonometrics.hypotheses.org/20403" }, { "title": "Exporting plain, lattice, or ggplot graphics", "href": "http://gforge.se/2013/03/exporting-plain-lattice-or-ggplot/" }, { "title": "satRday in Cape Town", "href": "http://www.exegetic.biz/blog/2016/05/satrday-cape-town/" }, { "title": "Illustrated Guide to ROC and AUC", "href": "http://www.joyofdata.de/blog/illustrated-guide-to-roc-and-auc/" }, { "title": "Bar Charts and Segmented Bar Charts in R", "href": "https://qualityandinnovation.com/2012/09/02/bar-charts-and-segmented-bar-charts-in-r/" }, { "title": "Plot the new SVG R logo with ggplot2", "href": "http://rud.is/b/2016/02/11/plot-the-new-svg-r-logo-with-ggplot2/" }, { "title": "The R Journal Volume 4/1, June 2012", "href": "https://www.r-bloggers.com/the-r-journal-volume-41-june-2012/" }, { "title": "Analysing the US election using Youtube data", "href": "http://flovv.github.io/US_Election/" }, { "title": "How to reveal anyone’s interests on Twitter using social network analysis", "href": "https://cartesianfaith.com/2014/09/22/how-to-reveal-anyones-interests-on-twitter-using-social-network-analysis/" }, { "title": "Scaling legislative roll call votes with wnominate", "href": "http://is-r.tumblr.com/post/37110530260/scaling-legislative-roll-call-votes-with-wnominate" }, { "title": "Wilcoxon signed rank test", "href": "http://statistic-on-air.blogspot.com/2009/07/wilcoxon-signed-rank-test.html" }, { "title": "Jeff Leek’s non-comprehensive list of awesome things other people did in 2013", "href": "http://www.gettinggeneticsdone.com/2013/12/non-comprehensive-list-of-awesome-things-other-people-did-in-2013.html" }, { "title": "Portfolio Optimization in R, Part 3", "href": "http://statsadventure.blogspot.com/2011/12/portfolio-optimization-in-r-part-3.html" }, { "title": "NIT: Fatty acids study in R – Part 006", "href": "http://nir-quimiometria.blogspot.com/2012/03/nit-fatty-acids-study-in-r-part-006.html" }, { "title": "New package on CRAN: lamW", "href": "http://www.avrahamadler.com/2015/05/26/lamw-package-cran/" }, { "title": "Using R to Analyze Baseball Games in “Real Time”", "href": "https://blogisticreflections.wordpress.com/2009/10/04/using-r-to-analyze-baseball-games-in-real-time/" }, { "title": "project euler-Problem 41", "href": "https://web.archive.org/web/http://ygc.name/2011/11/07/project-euler-problem-41/" }, { "title": "Mumbai, March 24-26, 2011 – R for Finance and Advanced Portfolio Optimization", "href": "https://www.rmetrics.org/node/86" }, { "title": "Course in San Antonio, Texas", "href": "https://xianblog.wordpress.com/2010/03/18/course-in-san-antonio-texas/" }, { "title": "Sourcing an R Script from Dropbox", "href": "http://jaredknowles.com/journal/2012/7/14/sourcing-an-r-script-from-dropbox.html" }, { "title": "Revolution Newsletter: March 2013", "href": "http://blog.revolutionanalytics.com/2013/03/revolution-newsletter-march-2013.html" }, { "title": "Show me the data! Or how to digitize plots", "href": "http://www.magesblog.com/2012/02/show-me-data-or-how-to-digitize-plots.html" }, { "title": "Aggregating spatial points by clusters", "href": "http://robinlovelace.net//r/2014/03/21/clustering-points-R.html" }, { "title": "When Discussing Confidence Level With Others…", "href": "http://statistical-research.com/some-issues-relating-to-margin-of-error/?utm_source=rss&utm_medium=rss&utm_campaign=some-issues-relating-to-margin-of-error" }, { "title": "An Annotated Online Bioinformatics / Computational Biology Curriculum", "href": "http://www.gettinggeneticsdone.com/2014/06/annotated-online-bioinformatics-computational-biology-curriculum.html" }, { "title": "Comparing the contribution of NBA draft picks", "href": "https://statofmind.wordpress.com/2015/01/26/comparing-the-contribution-of-nba-draft-picks/" }, { "title": "A Path Towards Easier Map Projection Machinations with ggplot2", "href": "http://rud.is/b/2015/07/24/a-path-towards-easier-map-projection-machinations-with-ggplot2/" }, { "title": "RProtoBuf & HistogramTools: Statistical Analysis Tools for Large Data Sets", "href": "https://opensource.googleblog.com/2013/10/rprotobuf-histogramtools-statistical_10.html" }, { "title": "httr 0.3", "href": "https://blog.rstudio.org/2014/03/21/httr-0-3/" }, { "title": "Read A Block of Spreadsheet with R", "href": "https://statcompute.wordpress.com/2015/05/10/read-a-block-of-spreadsheet-with-r/" }, { "title": "the random variable that was always less than its mean…", "href": "https://xianblog.wordpress.com/2016/05/30/the-random-variable-that-was-always-less-than-its-mean/" }, { "title": "Practicing static typing in R: Prime directive on trusting our functions with object oriented programming", "href": "http://memosisland.blogspot.com/2013/06/practicing-static-typing-in-r-prime.html" } ]
simtum = function(num.tum = 3, width = 70, height = 70, radius.l = 4, radius.u = 12, seed.center = NULL){ radius = runif(num.tum,radius.l, radius.u) tum = data.frame(row = rep(1:height, each = width), col = rep(1:height, width)) tum$pixel = rnorm(width * height, 0, 0.5) tum$is = FALSE if(!missing(seed.center)) set.seed(seed.center) centers = list(row = c(sample(1:height, num.tum, replace = TRUE)), col = c(sample(1:width, num.tum, replace = TRUE))) for(i in 1:num.tum){ in.circle = which(sqrt((tum$row-centers$row[i])^2 + (tum$col-centers$col[i])^2) <= radius[i]) tum$pixel[in.circle] = tum$pixel[in.circle] + rnorm(length(in.circle),4,1) tum$is[in.circle] = TRUE } tum.range = range(tum$pixel) tum$pixel = tum$pixel - tum.range[1] tum$pixel = tum$pixel / (tum.range[2] - tum.range[1]) return(invisible(tum$pixel)) }
matCorSig <- function(corrs, nsamp, secondMat = FALSE){ if(!secondMat){ pvals = matrix(NA, nrow = nrow(corrs), ncol = ncol(corrs)) corrs = corrs[upper.tri(corrs)] nsamp = nsamp[upper.tri(nsamp)] df = nsamp - 2 pvals_upper = 2 * (1 - pt(abs(corrs) * sqrt(df) / sqrt(1 - corrs^2), df)) pvals[upper.tri(pvals)] = pvals_upper pvals[abs(corrs) == 1] = 0 } else { df = nsamp - 2 pvals = matrix(2 * (1 - pt(abs(corrs) * sqrt(df) / sqrt(1 - corrs^2), df)), nrow = nrow(corrs)) pvals[abs(corrs) == 1] = 0 } return(pvals) }
vif.ridge <- function(mod, ...) { Vif <- function(v) { R <- cov2cor(v) detR <- det(R) p <- nrow(v) res <- rep(0,p) for (i in 1:p) { res[i] <- R[i,i] * det(as.matrix(R[-i,-i])) / detR } res } V <- vcov(mod) res <- t(sapply(V, Vif)) colnames(res) <- colnames(coef(mod)) rownames(res) <- rownames(coef(mod)) res }
tidy_micro <- function(otu_tabs, clinical, tab_names, prev_cutoff = 0.0, ra_cutoff = 0.0, exclude_taxa = NULL, library_name = "Lib", complete_clinical = TRUE, filter_summary = TRUE, count_summary = TRUE){ if(library_name %nin% names(clinical)) stop("Must provide 'library_name' matching column name of sequencing IDs from clinical data") names(clinical)[names(clinical) == library_name] <- "Lib" if(library_name != "Lib") warning(paste0("Renaming '", library_name, "' to 'Lib'") ) if(is.data.frame(otu_tabs) | is.matrix(otu_tabs)){ if(length(tab_names) != 1) { stop("tab_names must have length of 1 if only one OTU table supplied.")} l_otu <- suppressWarnings( otu_tabs %>% mul_otu_long(.meta = clinical) %>% dplyr::mutate(Table = tab_names) ) } else if(is.list(otu_tabs)){ if(missing(tab_names) & is.null(names(otu_tabs))){ stop("otu_tabs must have names, or names must be supplied through tab_names.") } if(is.null(names(otu_tabs))) names(otu_tabs) <- tab_names l_otu <- suppressWarnings(otu_tabs %>% plyr::ldply(mul_otu_long, .meta = clinical, .id = "Table")) } else stop("otu_tabs must be a single data.frame/matrix or list of data.frames/matrices.") l_otu %<>% dplyr::distinct() %>% otu_filter(prev_cutoff = prev_cutoff, ra_cutoff = ra_cutoff, exclude_taxa = exclude_taxa, filter_summary = filter_summary) %>% dplyr::select(.data$Table, dplyr::everything()) if(complete_clinical){ if(!all(l_otu$Lib %in% clinical$Lib) | !all(clinical$Lib %in% l_otu$Lib)){ warning("Warning: Some libraries in OTU table and clinical data don't match. Only libraries contained in each will be kept.\n") l_otu %<>% dplyr::filter(.data$Lib %in% clinical$Lib) } } if(count_summary){ message("Contains ",length(unique(l_otu$Lib))," libraries from OTU files.\n") ss <- l_otu %>% dplyr::distinct(.data$Lib, .keep_all = T) %>% dplyr::pull(.data$Total) %>% summary message("Summary of sequencing depth:"); print(ss) } l_otu %<>% dplyr::mutate(Table = factor(.data$Table), Taxa = factor(.data$Taxa)) l_otu[names(l_otu) != ".data$Table"] }
topologicalInfoContent <- function(g, dist=NULL, deg=NULL){ if(class(g)[1]!="graphNEL"){ stop("'g' must be a 'graphNEL' object") } stopifnot(.validateGraph(g)) if(is.null(dist)){ dist <- distanceMatrix(g) } if(is.null(deg)){ deg <- graph::degree(g) } On <- .cardNi(g,dist,deg) pis <- On/sum(On) In=pis*log2(pis) Iorb <- (-1)*sum(In) ret <- list() ret[["entropy"]] <- Iorb ret[["orbits"]] <- On return(ret) } .getTopology <- function(g,dist,deg){ nodes <- nodes(g) topology<-lapply(nodes,function(vi){ dist.vi<-dist[vi,] max.dist <- max(dist.vi) dist.vi <- dist.vi[dist.vi!=0] deg.vi <- deg[(names(dist.vi))] names(deg.vi) <- dist.vi deg.vi <- deg.vi[order(names(deg.vi))] tmp.names <-names(deg.vi) unames <- unique(names(deg.vi)) deg.vi <- unlist(lapply(unames,function(un){ csel <- grep(paste("^",un,"$",sep=""),names(deg.vi)) return(sort(deg.vi[csel])) })) return(deg.vi) }) names(topology) <- nodes return(topology) } .getOrbits <- function(top){ rest <- names(top) i <- 1 erg <- list() while(length(rest)>0){ rem <- c() vi <- rest[1] erg.tmp <- vi rest <- rest[-1] if(length(rest)>0){ for(j in length(rest):1){ if(identical(top[[vi]],top[[rest[j]]])){ erg.tmp <- cbind(erg.tmp,rest[j]) rest <- rest[-j] } } } erg[[i]]<-sort(erg.tmp) i<-i+1 } return(erg) } .cardNi <- function(g, dist, deg){ top <- .getTopology(g,dist,deg) orbits <- .getOrbits(top) return(sapply(orbits,length)) }
context("wm_record") test_that("wm_record - default usage works", { vcr::use_cassette("wm_record", { aa <- wm_record(id = 105706) }) expect_type(aa, "list") expect_equal(aa$valid_name, "Rhincodontidae") expect_equal(aa$valid_AphiaID, 105706) }) test_that("wm_record fails well", { skip_on_cran() expect_error(wm_record(), "argument \"id\" is missing") expect_error(wm_record("asdfafasdfs"), "id must be of class") vcr::use_cassette("wm_record_error", { expect_error(wm_record(44444), "\\(204\\) No Content") }) }) context("wm_record - plural") test_that("wm_record - default usage works", { vcr::use_cassette("wm_record_plural_plural", { bb <- wm_record(id = c(105706, 126436)) }) expect_is(bb, "data.frame") expect_equal(bb$AphiaID, c(105706, 126436)) }) test_that("wm_record_ - deprecated", { skip_on_cran() expect_warning(wm_record_(id = 105706), "deprecated") })
calculate_digit <- function(number, d5, d5_p, inv_v){ number <- prepare_number(number) c <- 0 for (i in 1:length(number)){ c <- d5_calc(d5, c, d5_p_calc(d5_p, i, number[i])) } final <- inv_v[c + 1] return(final) } d5_p_calc <- function(d5_p, i, number) { d5_p[(i %% 8) + 1, number + 1] + 1 } d5_calc <- function(d5, c, d5_p_calc) { d5[c + 1, d5_p_calc] }
rdb_datasets <- function( provider_code = NULL, use_readLines = getOption("rdbnomics.use_readLines"), curl_config = getOption("rdbnomics.curl_config"), simplify = FALSE, ... ) { progress_bar <- ellipsis_default("progress_bar", list(...), TRUE) check_argument(progress_bar, "logical") if (is.null(provider_code)) { provider_code <- rdb_providers( code = TRUE, use_readLines = use_readLines, curl_config = curl_config ) } check_argument(provider_code, "character", len = FALSE) check_argument(use_readLines, "logical") check_argument(simplify, "logical") api_base_url <- getOption("rdbnomics.api_base_url") check_argument(api_base_url, "character") api_version <- getOption("rdbnomics.api_version") check_argument(api_version, c("numeric", "integer")) authorized_version(api_version) if (getOption("rdbnomics.progress_bar_datasets") & progress_bar) { pb <- utils::txtProgressBar(min = 0, max = length(provider_code), style = 3) } datasets <- sapply(seq_along(provider_code), function(i) { tryCatch({ pc <- provider_code[i] tmp <- paste0(api_base_url, "/v", api_version, "/providers/", pc) tmp <- get_data(tmp, use_readLines, curl_config) tmp <- tmp$category_tree tmp <- unpack(tmp) tmp <- rbindlist_recursive(tmp) tmp <- tmp[, .(code, name)] tmp <- unique(tmp) if (getOption("rdbnomics.progress_bar_datasets") & progress_bar) { utils::setTxtProgressBar(pb, i) } tmp[order(code)] }, error = function(e) { NULL }) }, simplify = FALSE) if (getOption("rdbnomics.progress_bar_datasets") & progress_bar) { close(pb) } datasets <- stats::setNames(datasets, provider_code) datasets <- Filter(Negate(is.null), datasets) datasets <- check_datasets(datasets) if (length(datasets) <= 0) { warning( "Error when fetching the datasets codes.", call. = FALSE ) return(NULL) } if (simplify) { if (length(datasets) == 1) { return(datasets[[1]]) } } datasets }
evalClustLoss <- function(c, gs, lossFn="F-measure", a=1, b=1){ n <- length(c) loss <- NA if(length(gs)!=n){ stop("'c' and 'gs' arguments have not the same length") } if(lossFn == "F-measure"){ loss <- 1 - FmeasureC(pred=c, ref=gs) }else if(lossFn == "Binder"){ c_coclust <- sapply(c, FUN=function(x){x==c}) gs_coclust <- sapply(gs, FUN=function(x){x==gs}) dif <- c_coclust-gs_coclust dif[which(dif==1)] <- b dif[which(dif==-1)] <- a loss <- sum(dif) }else{ stop("Specified loss function not available.\n Specify either 'F-measure' or 'Binder' for the lossFn argument.") } return(loss) }
check.power <- function(nGenes = 10000, pi0 = 0.8, m, mu, disp, fc, up = 0.5, replace = TRUE, fdr = 0.05, sims = 100) { powerfdr.fun <- function(fdr, p){ V <- sum( (p < fdr) & (sim$de == FALSE)) R <- sum( p < fdr ) S <- R - V power <- S / (nGenes * (1 - pi0)) fdr_true <- V / R return(c(power, fdr_true)) } res <- list() pow_bh <- fdr_bh <- pow_qvalue <- fdr_qvalue <- rep(0, sims) for (j in 1:sims){ sim <- sim.counts(nGenes, pi0, m, mu, disp, fc, up, replace) cts <- sim$counts lib.size <- colSums(cts) group = rep(c(1, 2), each = m) d <- DGEList(cts, lib.size, group = group) d <- calcNormFactors(d) design <- model.matrix(~ factor(group)) y <- voom(d, design, plot=FALSE) fit <- lmFit(y, design) fit <- eBayes(fit) pvalue <- fit$p.value[, 2] p_bh <- p.adjust(pvalue, method = "BH") pow_bh[j] <- powerfdr.fun(fdr, p_bh)[1] fdr_bh[j] <- powerfdr.fun(fdr, p_bh)[2] p_qvalue <- qvalue(pvalue)$qvalues pow_qvalue[j] <- powerfdr.fun(fdr, p_qvalue)[1] fdr_qvalue[j] <- powerfdr.fun(fdr, p_qvalue)[2] } res$pow_bh_ave <- mean(pow_bh) res$fdr_bh_ave <- mean(fdr_bh) res$pow_qvalue_ave <- mean(pow_qvalue) res$fdr_qvalue_ave <- mean(fdr_qvalue) return(res) }
beta.div.comp <- function(mat, coef = "J", quant = FALSE, save.abc = FALSE) { if(sum( scale(mat, scale=FALSE)^2 )==0) stop("The data matrix has no variation") if(any(mat<0)) stop("The data matrix contains negative values") coef <- pmatch(coef, c("S", "J", "BS", "BJ", "N")) if (coef == 5 & quant) stop("coef='N' and quant=TRUE: combination not programmed") mat <- as.matrix(mat) n <- nrow(mat) if (is.null(rownames(mat))) noms <- paste("Site", 1:n, sep = "") else noms <- rownames(mat) if (!quant) { if (coef == 1) form = "Podani family, Sorensen" if (coef == 2) form = "Podani family, Jaccard" if (coef == 3) form = "Baselga family, Sorensen" if (coef == 4) form = "Baselga family, Jaccard" if (coef == 5) form = "Podani & Schmera (2011) relativized nestedness" mat.b <- ifelse(mat > 0, 1, 0) a <- mat.b %*% t(mat.b) b <- mat.b %*% (1 - t(mat.b)) c <- (1 - mat.b) %*% t(mat.b) min.bc <- pmin(b, c) if (coef == 1 || coef == 2) { repl <- 2 * min.bc rich <- abs(b - c) if (coef == 1) { repl <- repl / (2 * a + b + c) rich <- rich / (2 * a + b + c) D <- (b + c) / (2 * a + b + c) } else if (coef == 2) { repl <- repl / (a + b + c) rich <- rich / (a + b + c) D <- (b + c) / (a + b + c) } } else if (coef == 3) { D <- (b + c) / (2 * a + b + c) repl <- min.bc / (a + min.bc) rich <- D - repl } else if (coef == 4) { D <- (b + c) / (a + b + c) repl <- 2 * min.bc / (a + 2 * min.bc) rich <- D - repl } else if (coef == 5) { repl <- 2 * min.bc / (a + b + c) D <- (b + c) / (a + b + c) rich <- matrix(0, n, n) for (i in 2:n) { for (j in 1:(i - 1)) { aa = a[i, j] bb = b[i, j] cc = c[i, j] if (a[i, j] == 0) rich[i, j] <- 0 else rich[i, j] <- (aa + abs(bb - cc)) / (aa + bb + cc) } } } rownames(repl) <- rownames(rich) <- rownames(D) <- noms D <- as.dist(D) repl <- as.dist(repl) rich <- as.dist(rich) total.div <- sum(D) / (n * (n - 1)) repl.div <- sum(repl) / (n * (n - 1)) rich.div <- sum(rich) / (n * (n - 1)) part <- c(total.div, repl.div, rich.div, repl.div / total.div, rich.div / total.div) if(coef<=2) names(part) <- c("BDtotal","Repl","RichDif","Repl/BDtotal","RichDif/BDtotal") if(coef>=3) names(part) <- c("BDtotal", "Repl", "Nes", "Repl/BDtotal", "Nes/BDtotal") if (save.abc) { res <- list( repl = repl, rich = rich, D = D, part = part, Note = form, a = as.dist(a), b = as.dist(t(b)), c = as.dist(t(c)) ) } else { res <- list( repl = repl, rich = rich, D = D, part = part, Note = form) } } else { if (coef == 1) form <- "Podani family, percentage difference" if (coef == 2) form <- "Podani family, Ruzicka" if (coef == 3) form <- "Baselga family, percentage difference" if (coef == 4) form <- "Baselga family, Ruzicka" repl <- matrix(0, n, n) rich <- matrix(0, n, n) D <- matrix(0, n, n) rownames(repl) <- rownames(rich) <- rownames(D) <- noms for(i in 2:n) { for(j in 1:(i-1)) { tmp = mat[i,] - mat[j,] A = sum(pmin(mat[i,], mat[j,])) B = sum(tmp[tmp>0]) C = -sum(tmp[tmp<0]) if(coef==1|| coef==3) { den <- (2*A+B+C) } else if(coef==2|| coef==4) { den <- (A+B+C) } if(coef==1 || coef==2) { repl[i,j] <- 2*(min(B,C))/den rich[i,j] <- abs(B-C)/den D[i,j] <- (B+C)/den } if(coef==3) { repl[i,j] <- (min(B,C))/(A+min(B,C)) rich[i,j] <- abs(B-C)*A/(den*(A+min(B,C))) D[i,j] <- (B+C)/den } if(coef==4) { repl[i,j] <- 2*(min(B,C))/(A+2*min(B,C)) rich[i,j] <- abs(B-C)*A/(den*(A+2*min(B,C))) D[i,j] <- (B+C)/den } } } repl <- as.dist(repl) rich <- as.dist(rich) D <- as.dist(D) repl.div <- sum(repl) / (n * (n - 1)) rich.div <- sum(rich) / (n * (n - 1)) total.div <- sum(D) / (n * (n - 1)) part <- c(total.div, repl.div, rich.div, repl.div / total.div, rich.div / total.div) if(coef<=2) names(part) <- c("BDtotal","Repl","RichDif","Repl/BDtotal","RichDif/BDtotal") if(coef>=3) names(part) <- c("BDtotal", "Repl", "Nes", "Repl/BDtotal", "Nes/BDtotal") res <- list( repl = repl, rich = rich, D = D, part = part, Note = form) } res }
library(testthat) library(rgovcan) pid <- "b7ca71fa-6265-46e7-a73c-344ded9212b0" pkg <- govcan_get_record(pid) pkg_list_format <- govcan_get_record(pid, format_resources = TRUE) pkg_list_res <- govcan_get_record(pid, only_resources = TRUE) pkg_list_res_format <- govcan_get_record(pid, format_resources = TRUE, only_resources = TRUE) search_default <- govcan_search("dfo", 10) search_small <- govcan_search("dfo", 2) search_format <- govcan_search("dfo", 10, format_results = TRUE) search_list <- govcan_search("dfo", 10, only_results = FALSE) search_list_format <- govcan_search("dfo", 10, format_results = TRUE, only_results = FALSE) id_resources <- govcan_get_resources(search_default) id_resources_character <- govcan_get_resources("b7ca71fa-6265-46e7-a73c-344ded9212b0")
context("test_aggregate.R") requireNamespace("data.table") verbose <- TRUE test_that("aggregate_by_key: with unique key, should preserve the number of line", { data("adult") adult <- adult[1 : 5000, ] adult$key <- seq_len(nrow(adult)) stored_nrow <- nrow(adult) aggregated_adult <- aggregate_by_key(adult, key = "key", verbose = verbose) expect_equal(stored_nrow, nrow(aggregated_adult)) }) test_that("aggregate_by_key: with at least 1 aggregated col should generate nbr_lines col", { data("adult") adult <- adult[1 : 5000, ] cols <- c("country", "age") aggregated_adult <- aggregate_by_key(adult[, cols], key = "country", verbose = verbose) expect_true(all(c("country", "nbr_lines") %in% names(aggregated_adult))) }) test_that("aggregate_by_key: date are not handled, error should be thrown", { data("messy_adult") messy_adult <- messy_adult[1 : 5000, ] messy_adult[["date3"]] <- as.Date(messy_adult[["date3"]], format = "%d-%m-%Y") cols <- c("country", "date3") sapply(messy_adult, class) expect_error(aggregate_by_key(messy_adult[, cols, with = FALSE], key = "country", verbose = verbose), "I can only handle: numeric, integer, factor, logical, character columns.") }) test_that("private function: aggregate_a_column: aggregate a character with more than thresh unique values should generate one column count of unique.", { data("adult") setDT(adult) unique_keys <- unique(adult[, "country", with = FALSE]) n_country <- nrow(unique_keys) adult[["character_col"]] <- sample(LETTERS, nrow(adult), replace = TRUE) cols <- c("country", "character_col") aggregated_col <- aggregate_a_column(adult[, cols, with = FALSE], col = "character_col", key = "country", unique_keys = unique_keys, thresh = 2) expect_equal(n_country, nrow(aggregated_col)) expect_equal(2, ncol(aggregated_col)) expect_equal(c("country", "n_unique.character_col"), names(aggregated_col)) }) test_that("private function: aggregate_a_column: aggregate a character with les than thresh unique values should generate one column per unique values.", { data("adult") setDT(adult) unique_keys <- unique(adult[, "country", with = FALSE]) n_country <- nrow(unique_keys) adult[["character_col"]] <- sample(c("A", "B"), nrow(adult), replace = TRUE) cols <- c("country", "character_col") aggregated_col <- aggregate_a_column(adult[, cols, with = FALSE], col = "character_col", key = "country", unique_keys = unique_keys, thresh = 2) expect_equal(n_country, nrow(aggregated_col)) expect_equal(3, ncol(aggregated_col)) expect_equal(c("country", "character_col.A", "character_col.B"), names(aggregated_col)) }) test_that("private function: aggregate_a_column: aggregate a logical column. Should create 1 column with count of true value", { data("adult") setDT(adult) unique_keys <- unique(adult[, "country", with = FALSE]) n_country <- nrow(unique_keys) adult[["logical_col"]] <- sample(c(TRUE, FALSE), nrow(adult), replace = TRUE) cols <- c("country", "logical_col") aggregated_col <- aggregate_a_column(adult[, cols, with = FALSE], col = "logical_col", key = "country", unique_keys = unique_keys) expect_equal(n_country, nrow(aggregated_col)) expect_equal(2, ncol(aggregated_col)) expect_equal(c("country", "nbr_true.logical_col"), names(aggregated_col)) }) test_that("private function: aggregate_a_column: aggregate a numeric column with 2 functions. Should create 1 column for each function result", { data("adult") setDT(adult) unique_keys <- unique(adult[, "country", with = FALSE]) n_country <- nrow(unique_keys) cols <- c("country", "age") functions <- c("mean", "sd") aggregated_col <- aggregate_a_column(adult[, cols, with = FALSE], col = "age", key = "country", unique_keys = unique_keys, functions = functions) expect_equal(n_country, nrow(aggregated_col)) expect_equal(3, ncol(aggregated_col)) expect_equal(c("country", "mean.age", "sd.age"), names(aggregated_col)) }) test_that("private function: aggregate_a_column: with duplicated col should return same result on both.", { data("adult") setDT(adult) unique_keys <- unique(adult[, "country", with = FALSE]) n_country <- nrow(unique_keys) adult[["country2"]] <- adult[["country"]] cols <- c("country", "country2") aggregated_col <- aggregate_a_column(adult[, cols, with = FALSE], col = "country2", key = "country", unique_keys = unique_keys, functions = functions) expect_equal(n_country, nrow(aggregated_col)) expect_equal(aggregated_col[["country"]], aggregated_col[["country2"]]) }) test_that("private function: aggregate_a_column: should thow error on more than 2 cols set", { data("adult") cols <- c("country", "age", "education") expect_error(aggregate_a_column(adult[, cols], col = "country", key = "country", unique_keys = unique_keys), ": data_set should have 2 columns.") })
context("Properties") test_that("properties can be read successfully", { data <- ' path <- renv_scope_tempfile("renv-properties-") writeLines(data, con = path) props <- renv_properties_read(path = path) expect_identical(props, list(Key = "Value")) props <- renv_properties_read(path = path, trim = FALSE) expect_identical(props, list(Key = " Value")) }) test_that("quoted properties are unquoted", { props <- renv_properties_read( path = "resources/properties.txt", delimiter = "=", dequote = TRUE ) expected <- list( Key1 = "Value 1", Key2 = 'Value "2"', Key3 = "Value '3'" ) expect_identical(props, expected) })
infer.analysis=function(mat.list, critical, Omega.true.list, offdiag=TRUE) { if ( !is.list(mat.list)){ stop('argument mat.list should be a list') } else if (!is.list(Omega.true.list)) { stop('argument Omega.true.list should be a list') } else if (any(!sapply(mat.list,is.matrix))) { stop('argument mat.list should be a list of matrices') } else if (any(!sapply(Omega.true.list,is.matrix))) { stop('argument Omega.true.list should be a list of matrices') } else if ( length(mat.list)!=length(Omega.true.list) ) { stop('arguments mat.list and Omega.true.list should share the same length') } else if ( any(!(sapply(mat.list,dim)[1,]==sapply(Omega.true.list,dim)[1,]))) { stop('dimension of elements in argument mat.list should match argument Omega.true.list') } else if ( !is.logical(offdiag)) { stop('argument offdiag should be a logical TRUE or FALSE ') } K=length(mat.list) fp=c();fn=c();d=c();nd=c();t=c() for (i in 1:K) { mat.list[[i]]=sign(abs(mat.list[[i]])>critical) if (offdiag==TRUE) { diag(mat.list[[i]])=NA diag(Omega.true.list[[i]])=NA } fp[i]=length(intersect(which(mat.list[[i]] !=0 ), which(Omega.true.list[[i]] ==0))) fn[i] =length(intersect(which(mat.list[[i]] ==0 ), which(Omega.true.list[[i]] !=0))) d[i] =length(which(mat.list[[i]] !=0 )) nd[i] =length(which(mat.list[[i]] ==0 )) t[i] = length(which(Omega.true.list[[i]] !=0 )) } Out = list() Out$fp=fp Out$fn=fn Out$d=d Out$nd=nd Out$t=t return(Out) }
useSweetAlert() observeEvent(input$success, { sendSweetAlert( session = session, title = "Success !!", text = "All in order", type = "success" ) }) observeEvent(input$error, { sendSweetAlert( session = session, title = "Error...", text = "Oups !", type = "error" ) }) observeEvent(input$info, { sendSweetAlert( session = session, title = "Information", text = "Something helpful", type = "info" ) }) observeEvent(input$tags, { sendSweetAlert( session = session, title = "HTLM tags", text = "normal <b>bold</b> <span style='color: steelblue;'>color</span> <h1>h1</h1>", html = TRUE, type = NULL ) }) observeEvent(input$warning, { sendSweetAlert( session = session, title = "Warning !!!", text = NULL, type = "warning" ) })
round_polytope <- function(P, settings = list()){ seed = NULL if (!is.null(settings$seed)) { seed = settings$seed } ret_list = rounding(P, settings, seed) Mat = ret_list$Mat b = Mat[, 1] A = Mat[, -c(1), drop = FALSE] type = P@type if (type == 'Vpolytope') { PP = list("P" = Vpolytope(V = A), "T" = ret_list$T, "shift" = ret_list$shift, "round_value" = ret_list$round_value) }else if (type == 'Zonotope') { PP = list("P" = Zonotope(G = A), "T" = ret_list$T, "shift" = ret_list$shift, "round_value" = ret_list$round_value) } else { PP = list("P" = Hpolytope(A = A, b = b), "T" = ret_list$T, "shift" = ret_list$shift, "round_value" = ret_list$round_value) } return(PP) }
lakeVolume <- function(inLakeMorpho, zmax = NULL, slope_quant = 0.5, correctFactor = 1, addBathy = FALSE) { if (class(inLakeMorpho) != "lakeMorpho") { stop("Input data is not of class 'lakeMorpho'. Run lakeSurround Topo or lakeMorphoClass first.") } if(is.null(inLakeMorpho$elev) & is.null(zmax)){ warning("No maximum depth provided and no elevation data included to estimate maximum depth. Provide a maximum depth or run lakeSurroundTopo first with elevation included. Without these, returns NA.") return(NA) } dmax <- max(raster::getValues(inLakeMorpho$lakeDistance), na.rm = TRUE) if(is.null(zmax)) { zmax <- lakeMaxDepth(inLakeMorpho, slope_quant, correctFactor) } lakevol <- sum((raster::getValues(inLakeMorpho$lakeDistance) * zmax/dmax) * res(inLakeMorpho$lakeDistance)[1] * res(inLakeMorpho$lakeDistance)[2], na.rm = TRUE) if (addBathy) { myBathy <- inLakeMorpho$lakeDistance * zmax/dmax myName <- deparse(substitute(inLakeMorpho)) inLakeMorpho$pseudoBathy <- NULL inLakeMorpho <- c(inLakeMorpho, pseudoBathy = myBathy) class(inLakeMorpho) <- "lakeMorpho" assign(myName, inLakeMorpho, envir = parent.frame()) } return(round(lakevol, 4)) }
"phi2poly" <- function(ph,cp,cc,n=NULL,correct=TRUE) { r.marg<-rep(0,2) c.marg<- rep(0,2) p<-array(rep(0,4),dim=c(2,2)) r.marg[1]<- cp r.marg[2]<- 1 -cp c.marg[1]<- cc c.marg[2]<- 1-cc p[1,1]<- r.marg[1]*c.marg[1]+ ph*sqrt(prod(r.marg,c.marg)) p[2,2]<- r.marg[2]*c.marg[2]+ ph*sqrt(prod(r.marg,c.marg)) p[1,2]<- r.marg[1]*c.marg[2]- ph*sqrt(prod(r.marg,c.marg)) p[2,1]<- r.marg[2]*c.marg[1]- ph*sqrt(prod(r.marg,c.marg)) if(!is.null(n)) p <- p*n result<-tetrachoric(p,correct=correct )$rho return(result)} "phi2tet" <- function(ph,cp,cc,n=NULL,correct=TRUE) { if(is.null(n)) n <- 1 r.marg<-rep(0,2) c.marg<- rep(0,2) p<-array(rep(0,4),dim=c(2,2)) r.marg[1]<- cp/n r.marg[2]<- 1 -cp/n c.marg[1]<- cc/n c.marg[2]<- 1-cc/n p[1,1]<- r.marg[1]*c.marg[1]+ ph*sqrt(prod(r.marg,c.marg)) p[2,2]<- r.marg[2]*c.marg[2]+ ph*sqrt(prod(r.marg,c.marg)) p[1,2]<- r.marg[1]*c.marg[2]- ph*sqrt(prod(r.marg,c.marg)) p[2,1]<- r.marg[2]*c.marg[1]- ph*sqrt(prod(r.marg,c.marg)) if(!is.null(n)) p <- p*n result<-tetrachoric(p,correct=correct )$rho return(result)} "phi2tetra" <- function(ph,m,n=NULL,correct=TRUE) { if(!is.matrix(ph) && !is.data.frame(ph)) {result <- phi2tet(ph,m[1],m[2],n=n,correct=correct) } else { nvar <- nrow(ph) if(nvar !=ncol(ph)) {stop('Matrix must be square')} if (length(m) !=nvar) {stop("length of m must match the number of variables")} result <- as.matrix(ph) for(i in 2:nvar) { for (j in 1:(i-1)) { result[i,j] <- result[j,i] <- phi2tet(ph[i,j],m[i],m[j],n=n,correct=correct) } } } return(result) }
context("change analysis") load(system.file("extdata", "NLA_IN.rda", package = "spsurvey")) popsize <- data.frame( LAKE_ORGN = c("MAN_MADE", "NATURAL"), Total = c(6000, 14000) ) fpc1 <- 20000 fpc2a <- list( Urban = 5000, "Non-Urban" = 15000 ) fpc2b <- list( MAN_MADE = 6000, NATURAL = 14000 ) fpc3 <- c( Ncluster = 200, clusterID_1 = 100, clusterID_2 = 100, clusterID_3 = 100, clusterID_4 = 100 ) fpc4a <- list( Urban = c( Ncluster = 75, clusterID_1 = 50, clusterID_2 = 50, clusterID_3 = 50, clusterID_4 = 50 ), "Non-Urban" = c( Ncluster = 125, clusterID_1 = 50, clusterID_2 = 50, clusterID_3 = 50, clusterID_4 = 50 ) ) fpc4b <- list( NATURAL = c( Ncluster = 130, clusterID_1 = 50, clusterID_2 = 50, clusterID_3 = 50, clusterID_4 = 50 ), MAN_MADE = c( Ncluster = 70, clusterID_1 = 50, clusterID_2 = 50, clusterID_3 = 50, clusterID_4 = 50 ) ) dframe <- droplevels(subset(NLA_IN, YEAR != 2017)) vars_cat <- c("BENT_MMI_COND_2017") vars_cont <- c("ContVar") subpops <- c("All_Sites") popsize <- data.frame( All_Sites = c("Indiana Lakes"), Total = c(20000) ) Change_Estimates <- change_analysis( dframe = dframe, vars_cat = vars_cat, vars_cont = vars_cont, test = c("mean", "median"), subpops = subpops, surveyID = "YEAR", siteID = "UNIQUE_ID", weight = "WGT_TP", xcoord = "XCOORD", ycoord = "YCOORD" ) test_that("Change: Unstratified single-stage analysis", { expect_true(exists("Change_Estimates")) expect_equal(attributes(Change_Estimates$catsum)$class, "data.frame") expect_equal(attributes(Change_Estimates$contsum_mean)$class, "data.frame") expect_equal(attributes(Change_Estimates$contsum_median)$class, "data.frame") expect_equal(nrow(Change_Estimates$catsum), 2) expect_equal(nrow(Change_Estimates$contsum_mean), 1) expect_equal(nrow(Change_Estimates$contsum_median), 2) }) Change_Estimates <- change_analysis( dframe = dframe, vars_cat = vars_cat, vars_cont = vars_cont, test = c("mean", "median"), subpops = subpops, surveyID = "YEAR", siteID = "UNIQUE_ID", weight = "WGT_TP", xcoord = "XCOORD", ycoord = "YCOORD", popsize = popsize ) test_that("Change: with known population sizes", { expect_true(exists("Change_Estimates")) expect_equal(attributes(Change_Estimates$catsum)$class, "data.frame") expect_equal(attributes(Change_Estimates$contsum_mean)$class, "data.frame") expect_equal(attributes(Change_Estimates$contsum_median)$class, "data.frame") expect_equal(nrow(Change_Estimates$catsum), 2) expect_equal(nrow(Change_Estimates$contsum_mean), 1) expect_equal(nrow(Change_Estimates$contsum_median), 2) }) Change_Estimates <- change_analysis( dframe = dframe, vars_cat = vars_cat, vars_cont = vars_cont, test = c("mean", "median"), subpops = subpops, surveyID = "YEAR", siteID = "UNIQUE_ID", weight = "WGT_TP", xcoord = "XCOORD", ycoord = "YCOORD", fpc = fpc1 ) test_that("Change: with finite population correction factor", { expect_true(exists("Change_Estimates")) expect_equal(attributes(Change_Estimates$catsum)$class, "data.frame") expect_equal(attributes(Change_Estimates$contsum_mean)$class, "data.frame") expect_equal(attributes(Change_Estimates$contsum_median)$class, "data.frame") expect_equal(nrow(Change_Estimates$catsum), 2) expect_equal(nrow(Change_Estimates$contsum_mean), 1) expect_equal(nrow(Change_Estimates$contsum_median), 2) }) Change_Estimates <- change_analysis( dframe = dframe, vars_cat = vars_cat, vars_cont = vars_cont, test = c("mean", "median"), subpops = subpops, surveyID = "YEAR", siteID = "UNIQUE_ID", weight = "WGT_TP", xcoord = "XCOORD", ycoord = "YCOORD", stratumID = "LAKE_ORGN" ) test_that("Change: Stratified single-stage analysis", { expect_true(exists("Change_Estimates")) expect_equal(attributes(Change_Estimates$catsum)$class, "data.frame") expect_equal(attributes(Change_Estimates$contsum_mean)$class, "data.frame") expect_equal(attributes(Change_Estimates$contsum_median)$class, "data.frame") expect_equal(nrow(Change_Estimates$catsum), 2) expect_equal(nrow(Change_Estimates$contsum_mean), 1) expect_equal(nrow(Change_Estimates$contsum_median), 2) }) Change_Estimates <- change_analysis( dframe = dframe, vars_cat = vars_cat, vars_cont = vars_cont, test = c("mean", "median"), subpops = subpops, surveyID = "YEAR", siteID = "UNIQUE_ID", weight = "WGT_TP", xcoord = "XCOORD", ycoord = "YCOORD", stratumID = "LAKE_ORGN", fpc = fpc2b ) test_that("Change: with finite population correction factor", { expect_true(exists("Change_Estimates")) expect_equal(attributes(Change_Estimates$catsum)$class, "data.frame") expect_equal(attributes(Change_Estimates$contsum_mean)$class, "data.frame") expect_equal(attributes(Change_Estimates$contsum_median)$class, "data.frame") expect_equal(nrow(Change_Estimates$catsum), 2) expect_equal(nrow(Change_Estimates$contsum_mean), 1) expect_equal(nrow(Change_Estimates$contsum_median), 2) }) Change_Estimates <- change_analysis( dframe = dframe, vars_cat = vars_cat, vars_cont = vars_cont, test = c("mean", "median"), subpops = subpops, surveyID = "YEAR", siteID = "UNIQUE_ID", weight = "WGT_TP", xcoord = "XCOORD", ycoord = "YCOORD", clusterID = "clusterID", weight1 = "weight1", xcoord1 = "xcoord1", ycoord1 = "ycoord1", vartype = "SRS" ) test_that("Change: Unstratified two-stage analysis", { expect_true(exists("Change_Estimates")) expect_equal(attributes(Change_Estimates$catsum)$class, "data.frame") expect_equal(attributes(Change_Estimates$contsum_mean)$class, "data.frame") expect_equal(attributes(Change_Estimates$contsum_median)$class, "data.frame") expect_equal(nrow(Change_Estimates$catsum), 2) expect_equal(nrow(Change_Estimates$contsum_mean), 1) expect_equal(nrow(Change_Estimates$contsum_median), 2) }) Change_Estimates <- change_analysis( dframe = dframe, vars_cat = vars_cat, vars_cont = vars_cont, test = c("mean", "median"), subpops = subpops, surveyID = "YEAR", siteID = "UNIQUE_ID", weight = "WGT_TP", xcoord = "XCOORD", ycoord = "YCOORD", clusterID = "clusterID", weight1 = "weight1", xcoord1 = "xcoord1", ycoord1 = "ycoord1", popsize = popsize, vartype = "SRS" ) test_that("Change: with known population sizes", { expect_true(exists("Change_Estimates")) expect_equal(attributes(Change_Estimates$catsum)$class, "data.frame") expect_equal(attributes(Change_Estimates$contsum_mean)$class, "data.frame") expect_equal(attributes(Change_Estimates$contsum_median)$class, "data.frame") expect_equal(nrow(Change_Estimates$catsum), 2) expect_equal(nrow(Change_Estimates$contsum_mean), 1) expect_equal(nrow(Change_Estimates$contsum_median), 2) }) Change_Estimates <- change_analysis( dframe = dframe, vars_cat = vars_cat, vars_cont = vars_cont, test = c("mean", "median"), subpops = subpops, surveyID = "YEAR", siteID = "UNIQUE_ID", weight = "WGT_TP", xcoord = "XCOORD", ycoord = "YCOORD", clusterID = "clusterID", weight1 = "weight1", xcoord1 = "xcoord1", ycoord1 = "ycoord1", fpc = fpc3, vartype = "SRS" ) test_that("Change: with finite population correction factor", { expect_true(exists("Change_Estimates")) expect_equal(attributes(Change_Estimates$catsum)$class, "data.frame") expect_equal(attributes(Change_Estimates$contsum_mean)$class, "data.frame") expect_equal(attributes(Change_Estimates$contsum_median)$class, "data.frame") expect_equal(nrow(Change_Estimates$catsum), 2) expect_equal(nrow(Change_Estimates$contsum_mean), 1) expect_equal(nrow(Change_Estimates$contsum_median), 2) }) Change_Estimates <- change_analysis( dframe = dframe, vars_cat = vars_cat, vars_cont = vars_cont, test = c("mean", "median"), subpops = subpops, surveyID = "YEAR", siteID = "UNIQUE_ID", weight = "WGT_TP", xcoord = "XCOORD", ycoord = "YCOORD", stratumID = "LAKE_ORGN", clusterID = "clusterID", weight1 = "weight1", xcoord1 = "xcoord1", ycoord1 = "ycoord1", vartype = "SRS" ) test_that("Change: Stratified two-stage analysis", { expect_true(exists("Change_Estimates")) expect_equal(attributes(Change_Estimates$catsum)$class, "data.frame") expect_equal(attributes(Change_Estimates$contsum_mean)$class, "data.frame") expect_equal(attributes(Change_Estimates$contsum_median)$class, "data.frame") expect_equal(nrow(Change_Estimates$catsum), 2) expect_equal(nrow(Change_Estimates$contsum_mean), 1) expect_equal(nrow(Change_Estimates$contsum_median), 2) }) Change_Estimates <- change_analysis( dframe = dframe, vars_cat = vars_cat, vars_cont = vars_cont, test = c("mean", "median"), subpops = subpops, surveyID = "YEAR", siteID = "UNIQUE_ID", weight = "WGT_TP", xcoord = "XCOORD", ycoord = "YCOORD", stratumID = "LAKE_ORGN", clusterID = "clusterID", weight1 = "weight1", xcoord1 = "xcoord1", ycoord1 = "ycoord1", popsize = popsize, vartype = "SRS" ) test_that("Change: with known population sizes", { expect_true(exists("Change_Estimates")) expect_equal(attributes(Change_Estimates$catsum)$class, "data.frame") expect_equal(attributes(Change_Estimates$contsum_mean)$class, "data.frame") expect_equal(attributes(Change_Estimates$contsum_median)$class, "data.frame") expect_equal(nrow(Change_Estimates$catsum), 2) expect_equal(nrow(Change_Estimates$contsum_mean), 1) expect_equal(nrow(Change_Estimates$contsum_median), 2) }) Change_Estimates <- change_analysis( dframe = dframe, vars_cat = vars_cat, vars_cont = vars_cont, test = c("mean", "median"), subpops = subpops, surveyID = "YEAR", siteID = "UNIQUE_ID", weight = "WGT_TP", xcoord = "XCOORD", ycoord = "YCOORD", stratumID = "LAKE_ORGN", clusterID = "clusterID", weight1 = "weight1", xcoord1 = "xcoord1", ycoord1 = "ycoord1", fpc = fpc4b, vartype = "SRS" ) test_that("Change: with finite population correction factor", { expect_true(exists("Change_Estimates")) expect_equal(attributes(Change_Estimates$catsum)$class, "data.frame") expect_equal(attributes(Change_Estimates$contsum_mean)$class, "data.frame") expect_equal(attributes(Change_Estimates$contsum_median)$class, "data.frame") expect_equal(nrow(Change_Estimates$catsum), 2) expect_equal(nrow(Change_Estimates$contsum_mean), 1) expect_equal(nrow(Change_Estimates$contsum_median), 2) })
.diff.timeSeries <- function(x, lag = 1, diff = 1, trim = FALSE, pad = NA, ...) { stopifnot(is.timeSeries(x)) Title <- x@title Documentation <- x@documentation y <- getDataPart(x) z <- diff(y, lag = lag, difference = diff) diffNums = dim(y)[1] - dim(z)[1] if (!trim) { zpad <- matrix(0*y[1:diffNums, ] + pad, nrow = diffNums) z <- rbind(zpad, z) } pos <- if (!trim) x@positions else x@positions[-(1:diffNums)] df <- x@recordIDs if (trim && sum(dim(df)) > 0) { df <- df[-seq.int(diffNums), , drop = FALSE] rownames(df) <- seq.int(NROW(df)) } ans <- timeSeries(data = z, charvec = pos, units = colnames(z), format = x@format, zone = x@FinCenter, FinCenter = x@FinCenter, recordIDs = df) ans@title <- Title ans@documentation <- Documentation ans } setMethod("diff", "timeSeries", function(x, lag = 1, diff = 1, trim = FALSE, pad = NA, ...) .diff.timeSeries(x, lag, diff, trim, pad, ...) ) diff.timeSeries <- function(x, ...) .diff.timeSeries(x, ...)
mapdeck <- function( data = NULL, token = get_access_token( api = 'mapbox' ), width = NULL, height = NULL, padding = 0, style = 'mapbox://styles/mapbox/streets-v9', pitch = 0, zoom = 0, bearing = 0, libraries = NULL, max_zoom = 20, min_zoom = 0, max_pitch = 60, min_pitch = 0, location = c(0, 0), show_view_state = FALSE, repeat_view = FALSE ) { x = list( access_token = force( token ) , style = force( style ) , pitch = force( pitch ) , zoom = force( zoom ) , location = force( as.numeric( location ) ) , bearing = force( bearing ) , max_zoom = force( max_zoom ) , min_zoom = force( min_zoom ) , max_pitch = force( max_pitch ) , min_pitch = force( min_pitch ) , show_view_state = force( show_view_state ) , repeat_view = force( repeat_view ) ) mapdeckmap <- htmlwidgets::createWidget( name = 'mapdeck', x = structure( x, mapdeck_data = data ), width = width, height = height, package = 'mapdeck', sizingPolicy = htmlwidgets::sizingPolicy( defaultWidth = '100%', defaultHeight = 800, padding = padding, browser.fill = FALSE ) ) mapdeckmap <- add_dependencies( mapdeckmap ) mapdeckmap$dependencies <- c( if ('h3' %in% libraries) mapdeckH3JSDependency() else NULL, mapdeckmap$dependencies , mapboxgl() , mapdeck_css() , mapdeck_js() , htmlwidgets_js() ) return(mapdeckmap) } update_style <- function( map, style ) { invoke_method( map, "md_update_style", style ) } mapdeckOutput <- function(outputId, width = '100%', height = '400px'){ htmlwidgets::shinyWidgetOutput(outputId, 'mapdeck', width, height, package = 'mapdeck') } renderMapdeck <- function(expr, env = parent.frame(), quoted = FALSE) { if (!quoted) { expr <- substitute(expr) } htmlwidgets::shinyRenderWidget(expr, mapdeckOutput, env, quoted = TRUE) } mapdeck_update <- function( data = NULL, map_id, session = shiny::getDefaultReactiveDomain(), deferUntilFlush = TRUE, map_type = c("mapdeck_update", "google_map_update") ) { map_type <- match.arg( map_type ) if (is.null(session)) { stop("mapdeck - mapdeck_update must be called from the server function of a Shiny app") } structure( list( session = session, id = map_id, x = structure( list(), mapdeck_data = data ), deferUntilFlush = deferUntilFlush, dependencies = NULL ), class = c(map_type) ) } mapdeck_view <- function( map, location = NULL, zoom = NULL, pitch = NULL, bearing = NULL, duration = NULL, transition = c("linear", "fly") ) { transition <- match.arg(transition) invoke_method( map, 'md_change_location', map_type( map ) , as.numeric( location ), zoom, pitch, bearing, duration, transition ) } get_map_data <- function( map ) { attr( map$x, "mapdeck_data", exact = TRUE ) } map_type <- function( map ) { map_type <- attr( map, "class") if( any( c("mapdeck", "mapdeck_update") %in% map_type ) ) return( "mapdeck" ) if( any( c("google_map", "google_map_update") %in% map_type ) ) return( "google_map" ) return(NULL) }
source(system.file(file.path('tests', 'testthat', 'test_utils.R'), package = 'nimble')) RwarnLevel <- options('warn')$warn options(warn = 1) nimbleVerboseSetting <- nimbleOptions('verbose') nimbleOptions(verbose = FALSE) context('Testing of numeric, integer, logical, matrix and array allocation') numericTests <- list( list(name = 'numeric: length', expr = quote(out <- numeric(5)), outputType = quote(double(1) ), args = list(), setArgVals = quote({}) ), list(name = 'numeric: length 0', expr = quote({ out <- nimNumeric(length = 0) }), outputType = quote(double(1)) ), list(name = 'numeric: length, scalar value', expr = quote(out <- nimNumeric(5, value = 1.5)), outputType = quote(double(1)) ), list(name = 'numeric: length, value scalar, recycle = FALSE, fillZeros = TRUE', expr = quote(out <- nimNumeric(5, value = 2, recycle = FALSE, fillZeros = TRUE)), outputType = quote(double(1) ), args = list(), setArgVals = quote({}) ), list(name = 'numeric: length, scalar value, init=FALSE', expr = quote({out <- nimNumeric(5, value = 1.5, init = FALSE); out[1:5] <- .123}), outputType = quote(double(1)) ), list(name = 'numeric: length, init = FALSE', expr = quote({out <- nimNumeric(5, init = FALSE); out[1:5] <- .123}), outputType = quote(double(1)) ), list(name = 'numeric: length expression, scalar value expression, init expression', expr = quote({ a <- 2:4 b <- rnorm(5) c <- 1:10 out <- nimNumeric(sum(a) + 1, value = mean(b) + 0.5, init = (c > 2)[4]); }), outputType = quote(double(1)) ), list(name = 'numeric: length, vector value', expr = quote({ v <- rnorm(5) out <- nimNumeric(5, value = v); }), outputType = quote(double(1)) ), list(name = 'numeric: length, vector value expression', expr = quote({ v <- rnorm(5) out <- nimNumeric(5, value = exp(v) + 1); }), outputType = quote(double(1)) ), list(name = 'numeric: length, vector value with too few elements', expr = quote({ v <- rnorm(4) out <- nimNumeric(5, value = v); }), outputType = quote(double(1)) ), list(name = 'numeric: length vector value with different types', expr = quote({ v <- nimInteger(5, value = 1:5) out <- nimNumeric(5, value = v); }), outputType = quote(double(1)) ), list(name = 'numeric: length vector value with too many elements', expr = quote({ v <- rnorm(6) out <- nimNumeric(5, value = v); }), outputType = quote(double(1)) ), list(name = 'numeric: length, matrix value', expr = quote({ v <- matrix(rnorm(6), nrow = 2) out <- nimNumeric(6, value = v); }), outputType = quote(double(1)) ) ) integerTests <- list( list(name = 'integer: length', expr = quote(out <- integer(5)), outputType = quote(integer(1) ), args = list(), setArgVals = quote({}) ), list(name = 'integer: length, scalar value', expr = quote(out <- nimInteger(5, value = 1.5)), outputType = quote(integer(1)) ), list(name = 'integer: length, value scalar, recycle = FALSE, fillZeros = TRUE', expr = quote(out <- nimInteger(5, value = 2, recycle = FALSE, fillZeros = TRUE)), outputType = quote(integer(1) ), args = list(), setArgVals = quote({}) ), list(name = 'integer: length, scalar value, init=FALSE', expr = quote({out <- nimInteger(5, value = 1.5, init = FALSE); out[1:5] <- 123}), outputType = quote(integer(1)), checkEqual = TRUE ), list(name = 'integer: length, init = FALSE', expr = quote({out <- nimInteger(5, init = FALSE); out[1:5] <- 123}), outputType = quote(integer(1)), checkEqual = TRUE ), list(name = 'integer: length expression, scalar value expression, init expression', expr = quote({ a <- 2:4 b <- rnorm(5) c <- 1:10 out <- nimInteger(sum(a) + 1, value = round(mean(b)), init = (c > 2)[4]); }), outputType = quote(integer(1)) ), list(name = 'integer: length, vector value', expr = quote({ v <- rpois(5, lambda = 12.3) out <- nimInteger(5, value = v); }), outputType = quote(integer(1)) ), list(name = 'integer: length, vector value expression', expr = quote({ v <- rpois(5, lambda = 12.3) out <- nimInteger(5, value = exp(v) + 1); }), outputType = quote(integer(1)) ), list(name = 'integer: length, vector value with too few elements', expr = quote({ v <- rpois(4, lambda = 12.3) out <- nimInteger(5, value = v); }), outputType = quote(integer(1)) ), list(name = 'integer: length vector value with different types', expr = quote({ v <- nimInteger(5, value = 1:5) out <- nimInteger(5, value = v); }), outputType = quote(integer(1)) ), list(name = 'integer: length vector value with too many elements', expr = quote({ v <- rpois(6, lambda = 12.3) out <- nimInteger(5, value = v); }), outputType = quote(integer(1)) ), list(name = 'integer: length, matrix value', expr = quote({ v <- matrix(rpois(6, lambda = 12.3), nrow = 2) out <- nimInteger(6, value = v); }), outputType = quote(integer(1)) ) ) logicalTests <- list( list(name = 'logical: length', expr = quote(out <- logical(5)), outputType = quote(logical(1) ), args = list(), setArgVals = quote({}) ), list(name = 'logical: length, scalar value', expr = quote(out <- nimLogical(5, value = 1.5)), outputType = quote(logical(1)) ), list(name = 'logical: length, value scalar, recycle = FALSE, fillZeros = TRUE', expr = quote(out <- nimLogical(5, value = TRUE, recycle = FALSE, fillZeros = TRUE)), outputType = quote(logical(1) ), args = list(), setArgVals = quote({}) ), list(name = 'logical: length, scalar value, init=FALSE', expr = quote({out <- nimLogical(5, value = FALSE, init = FALSE); out[1:5] <- TRUE}), outputType = quote(logical(1)) ), list(name = 'logical: length, init = FALSE', expr = quote({out <- nimLogical(5, init = FALSE); out[1:5] <- TRUE}), outputType = quote(logical(1)) ), list(name = 'logical: length expression, scalar value expression, init expression', expr = quote({ a <- 2:4 b <- rnorm(5) c <- 1:10 out <- nimLogical(sum(a) + 1, value = mean(b) > 0, init = (c > 2)[4]); }), outputType = quote(logical(1)) ), list(name = 'logical: length, vector value', expr = quote({ v <- rpois(5, lambda = 12.3) > 12.3 out <- nimLogical(5, value = v); }), outputType = quote(logical(1)) ), list(name = 'logical: length, vector value expression', expr = quote({ v <- rpois(5, lambda = 12.3) > 12.3 out <- nimLogical(5, value = !v); }), outputType = quote(logical(1)) ), list(name = 'logical: length, vector value with too few elements', expr = quote({ v <- rpois(4, lambda = 12.3) > 12.3 out <- nimLogical(5, value = v); }), outputType = quote(logical(1)) ), list(name = 'logical: length vector value with different types', expr = quote({ v <- nimLogical(5, value = c(TRUE, TRUE, rep(FALSE, 2), TRUE)) out <- nimLogical(5, value = v); }), outputType = quote(logical(1)) ), list(name = 'logical: length vector value with too many elements', expr = quote({ v <- rpois(6, lambda = 12.3) > 12.3 out <- nimLogical(5, value = v); }), outputType = quote(logical(1)) ), list(name = 'logical: length, matrix value', expr = quote({ v <- matrix(rpois(6, lambda = 12.3) > 12.3, nrow = 2) out <- nimLogical(6, value = v); }), outputType = quote(logical(1)) ) ) matrixTests <- list( list(name = 'matrix', expr = quote({ out <- nimMatrix(6, nrow = 2); }), outputType = quote(double(2)) ), list(name = 'matrix', expr = quote({ out <- nimMatrix(6, ncol = 2); }), outputType = quote(double(2)) ), list(name = 'matrix size 0', expr = quote({ out <- nimMatrix(type = 'double', nrow = 0, ncol = 0) }), outputType = quote(double(2)) ), list(name = 'matrix, recycle = FALSE', expr = quote({ out <- nimMatrix(6, ncol = 2, recycle = FALSE); }), outputType = quote(double(2)) ), list(name = 'matrix, recycle = FALSE', expr = quote({ out <- nimMatrix(6, nrow = 2, recycle = FALSE); }), outputType = quote(double(2)) ), list(name = 'matrix, recycle = FALSE', expr = quote({ out <- nimMatrix(6, ncol = 3, nrow = 2, recycle = FALSE); }), outputType = quote(double(2)) ), list(name = 'matrix', expr = quote({ out <- nimMatrix(6, ncol = 2, nrow = 3); }), outputType = quote(double(2)) ), list(name = 'matrix no init', expr = quote({ test <- nimMatrix(6, ncol = 3, init = FALSE); out <- dim(test) }), outputType = quote(integer(1)) ), list(name = 'matrix, scalar value, in exression', expr = quote({ out <- nimMatrix(6, ncol = 3, nrow = 2)^2; }), outputType = quote(double(2)) ), list(name = 'matrix vector init', expr = quote({ out <- nimMatrix(1:6, ncol = 3); }), outputType = quote(double(2)) ), list(name = 'matrix, vector value, in exression', expr = quote({ out <- nimMatrix(1:6, ncol = 3, nrow = 2)^2; }), outputType = quote(double(2)) ), list(name = 'matrix matrix init', expr = quote({ initMat <- nimMatrix(1:6, nrow = 3); out <- nimMatrix(initMat, nrow = 2); }), outputType = quote(double(2)) ), list(name = 'matrix vector no sizes given', expr = quote({ out <- nimMatrix(1:6) }), outputType = quote(double(2)) ), list(name = 'matrix vector init too big', expr = quote({ out <- nimMatrix(1:6, nrow = 2) }), outputType = quote(double(2)) ), list(name = 'matrix vector init', expr = quote({ out <- nimMatrix(1:6, nrow = 3); }), outputType = quote(double(2)) ), list(name = 'matrix vector init, extraneous arg', expr = quote({ out <- nimMatrix(1:6, nrow = 2, recycle = FALSE); }), outputType = quote(double(2)) ), list(name = 'matrix vector init', expr = quote({ out <- nimMatrix(1:6, ncol = 2, nrow = 3); }), outputType = quote(double(2)) ), list(name = 'matrix vector init too small', expr = quote({ out <- nimMatrix(1:6, nrow = 3, ncol = 3); }), outputType = quote(double(2)) ), list(name = 'matrix vector init too big', expr = quote({ out <- nimMatrix(1:6, nrow = 2, ncol = 2) }), outputType = quote(double(2)) ), list(name = 'matrix vector init incongruous size', expr = quote({ out <- nimMatrix(1:7, nrow = 3); }), outputType = quote(double(2)) ), list(name = 'matrix vector init too small, recycle=FALSE', expr = quote({ out <- nimMatrix(1:6, nrow = 3, ncol = 3, recycle = FALSE); }), outputType = quote(double(2)) ), list(name = 'matrix vector init too small, recycle=FALSE, fillZeros = FALSE (ignored)', expr = quote({ out <- nimMatrix(1:6, nrow = 3, ncol = 3, recycle = FALSE, fillZeros = FALSE); }), outputType = quote(double(2)) ) ) arrayTests1D <- list( list(name = 'array 1D', expr = quote({ out <- nimArray(6, dim = 2); }), outputType = quote(double(1)) ), list(name = 'array 1D, recycle = FALSE', expr = quote({ out <- nimArray(6, dim = 2, recycle = FALSE); }), outputType = quote(double(1)) ), list(name = 'array 1D, value scalar, fillZeros = TRUE (but recycle=TRUE takes precedence)', expr = quote({ out <- nimArray(1.23, dim = 2, fillZeros = TRUE); }), outputType = quote(double(1)) ), list(name = 'array 1D, value scalar, fillZeros = TRUE, recycle = FALSE', expr = quote({ out <- nimArray(1.23, dim = 2, fillZeros = TRUE, recycle = FALSE); }), outputType = quote(double(1)) ), list(name = 'array 1D (c() notation)', expr = quote({ out <- nimArray(6, dim = c(2)); }), outputType = quote(double(1)) ), list(name = 'array 1D (dim vector)', expr = quote({ dim <- c(2) out <- nimArray(6, dim = dim, nDim = 1); }), outputType = quote(double(1)) ), list(name = 'array 1D in expression', expr = quote({ out <- nimArray(6, dim = 2)^2; }), outputType = quote(double(1)) ), list(name = 'array 1D, value vector', expr = quote({ out <- nimArray(rnorm(2), dim = 2); }), outputType = quote(double(1)) ), list(name = 'array 1D, value vector, in expression', expr = quote({ out <- nimArray(rnorm(2), dim = 2)^2; }), outputType = quote(double(1)) ), list(name = 'array 1D, value vector, recycle = TRUE', expr = quote({ out <- nimArray(rnorm(2), dim = 4, recycle = TRUE); }), outputType = quote(double(1)) ), list(name = 'array 1D, value vector, fillZeros = TRUE (but recycle=TRUE has precedence)', expr = quote({ out <- nimArray(rnorm(2), dim = 4, fillZeros = TRUE); }), outputType = quote(double(1)) ), list(name = 'array 1D, value vector, fillZeros = TRUE, recycle=FALSE', expr = quote({ out <- nimArray(rnorm(2), dim = 4, fillZeros = TRUE, recycle = FALSE); }), outputType = quote(double(1)) ) ) arrayTests3D <- list( list(name = 'array 3D', expr = quote({ out <- nimArray(6, dim = c(2, 3, 4)); }), outputType = quote(double(3)) ), list(name = 'array 3D size 0', expr = quote({ out <- nimArray(type = 'double', dim = c(0,0,0)) }), outputType = quote(double(3)) ), list(name = 'array 3D, recycle = FALSE', expr = quote({ out <- nimArray(6, dim = c(2, 3, 4), recycle = FALSE); }), outputType = quote(double(3)) ), list(name = 'array 3D, value scalar, fillZeros = TRUE (but recycle=TRUE takes precedence)', expr = quote({ out <- nimArray(1.23, dim = c(2, 3, 4), fillZeros = TRUE); }), outputType = quote(double(3)) ), list(name = 'array 3D, value scalar, fillZeros = TRUE, recycle = FALSE', expr = quote({ out <- nimArray(1.23, dim = c(2, 3, 4), fillZeros = TRUE, recycle = FALSE); }), outputType = quote(double(3)) ), list(name = 'array 3D (dim vector)', expr = quote({ dim <- c(2, 3, 4) out <- nimArray(6, dim = dim, nDim = 3); }), outputType = quote(double(3)) ), list(name = 'array 3D in expression', expr = quote({ out <- nimArray(6, dim = c(2, 3, 4))[,2,]^2; }), outputType = quote(double(2)) ), list(name = 'array 3D, value vector in bracket expression', expr = quote({ out <- nimArray(1:7, dim = c(3, 4, 2))[,2,] }), outputType = quote(double(2)) ), list(name = 'array 3D, value vector', expr = quote({ out <- nimArray(rnorm(2*3*4), c(2, 3, 4)); }), outputType = quote(double(3)) ), list(name = 'array 3D, value vector, recycle = TRUE', expr = quote({ out <- nimArray(rnorm(2), dim = c(2, 3, 4), recycle = TRUE); }), outputType = quote(double(3)) ), list(name = 'array 3D, value vector, fillZeros = TRUE (but recycle=TRUE has precedence)', expr = quote({ out <- nimArray(rnorm(2), dim = c(2, 3, 4), fillZeros = TRUE); }), outputType = quote(double(3)) ), list(name = 'array 3D, value vector, fillZeros = TRUE, recycle=FALSE', expr = quote({ out <- nimArray(rnorm(2), dim = c(2, 3, 4), fillZeros = TRUE, recycle = FALSE); }), outputType = quote(double(3)) ), list(name = 'array matrix init', expr = quote({ initMat <- nimMatrix(1:18, nrow = 3); out <- nimArray(initMat, dim = c(3,3,2)); }), outputType = quote(double(3)) ), list(name = 'array 3D too few values', expr = quote({ out <- nimArray(1:9, dim = c(3,3,2)); }), outputType = quote(double(3)) ), list(name = 'array 3D, value vector incongruous to dims', expr = quote({ out <- nimArray(1:7, dim = c(3, 4, 2)) }), outputType = quote(double(3)) ) ) arrayTests2D <- list( list(name = 'array 2D', expr = quote({ out <- nimArray(6, dim = c(2, 3)); }), outputType = quote(double(2)) ), list(name = 'array 2D, recycle = FALSE', expr = quote({ out <- nimArray(6, dim = c(2, 3), recycle = FALSE); }), outputType = quote(double(2)) ), list(name = 'array 2D, value scalar, fillZeros = TRUE (but recycle=TRUE takes precedence)', expr = quote({ out <- nimArray(1.23, dim = c(2, 3), fillZeros = TRUE); }), outputType = quote(double(2)) ), list(name = 'array 2D, value scalar, fillZeros = TRUE, recycle = FALSE', expr = quote({ out <- nimArray(1.23, dim = c(2, 3), fillZeros = TRUE, recycle = FALSE); }), outputType = quote(double(2)) ), list(name = 'array 2D (dim vector)', expr = quote({ dim <- c(2, 3) out <- nimArray(6, dim = dim, nDim = 2); }), outputType = quote(double(2)) ), list(name = 'array 2D in expression', expr = quote({ out <- nimArray(6, dim = c(2, 3))^2; }), outputType = quote(double(2)) ), list(name = 'array 2D, value vector', expr = quote({ out <- nimArray(rnorm(2), dim = c(2, 3)); }), outputType = quote(double(2)) ), list(name = 'array 2D, value vector, recycle = TRUE', expr = quote({ out <- nimArray(rnorm(2), dim = c(2, 3), recycle = TRUE); }), outputType = quote(double(2)) ), list(name = 'array 2D, value vector, fillZeros = TRUE (but recycle=TRUE has precedence)', expr = quote({ out <- nimArray(rnorm(2), dim = c(2, 3), fillZeros = TRUE); }), outputType = quote(double(2)) ), list(name = 'array 2D, value vector, fillZeros = TRUE, recycle=FALSE', expr = quote({ out <- nimArray(rnorm(2), dim = c(2, 3), fillZeros = TRUE, recycle = FALSE); }), outputType = quote(double(2)) ), list(name = 'array 2D, value vector with indexed block expression', expr = quote({ out <- nimArray(1:7, dim = c(3, 4))[,2]^2 }), outputType = quote(double(1)) ), list(name = 'array matrix init', expr = quote({ initMat <- nimMatrix(1:6, nrow = 3); out <- nimArray(initMat, dim = c(3,3)); }), outputType = quote(double(2)) ), list(name = 'array 2D too few values', expr = quote({ out <- nimArray(1:6, dim = c(3,3)); }), outputType = quote(double(2)) ) ) setSize1D <- list( list(name = 'setSize 1D', expr = quote({ out <- nimNumeric(4, value = 1:2) setSize(out, 7) }), outputType = quote(double(1)) ), list(name = 'setSize 1D dim expresion', expr = quote({ out <- nimNumeric(4, value = 1:2) z <- rpois(2, lambda = 1) setSize(out, 1 + sum(z)) }), outputType = quote(double(1)) ), list(name = 'setSize 1D to 0', expr = quote({ out <- nimNumeric(4, value = 1:2) setSize(out, 0) }), outputType = quote(double(1)) ), list(name = 'setSize 1D, copy=FALSE (default fillValues = TRUE)', expr = quote({ out <- nimNumeric(4, value = 1:2) setSize(out, 7, copy=FALSE) }), outputType = quote(double(1)) ), list(name = 'setSize 1D, (default copy = TRUE), fillZeros = FALSE', expr = quote({ v <- nimNumeric(4, value = 1:2) setSize(v, 7, fillZeros = FALSE) out <- v[1:4] }), outputType = quote(double(1)) ), list(name = 'setSize 1D, copy=FALSE, fillZeros = FALSE', expr = quote({ v <- nimNumeric(4, value = 1:2) setSize(v, 7, copy = FALSE, fillZeros = FALSE) out <- length(v) }), outputType = quote(integer(0)) ) ) setSize1Dinteger <- list( list(name = 'setSize integer 1D', expr = quote({ out <- nimInteger(4, value = 1:2) setSize(out, 7) }), outputType = quote(integer(1)) ), list(name = 'setSize integer 1D dim expresion', expr = quote({ out <- nimInteger(4, value = 1:2) z <- rpois(2, lambda = 1) setSize(out, 1 + sum(z)) }), outputType = quote(integer(1)) ), list(name = 'setSize integer 1D to 0', expr = quote({ out <- nimInteger(4, value = 1:2) setSize(out, 0) }), outputType = quote(integer(1)) ), list(name = 'setSize integer 1D, copy=FALSE (default fillValues = TRUE)', expr = quote({ out <- nimInteger(4, value = 1:2) setSize(out, 7, copy=FALSE) }), outputType = quote(integer(1)) ), list(name = 'setSize integer 1D, (default copy = TRUE), fillZeros = FALSE', expr = quote({ v <- nimInteger(4, value = 1:2) setSize(v, 7, fillZeros = FALSE) out <- v[1:4] }), outputType = quote(integer(1)) ), list(name = 'setSize integer 1D, copy=FALSE, fillZeros = FALSE', expr = quote({ v <- nimInteger(4, value = 1:2) setSize(v, 7, copy = FALSE, fillZeros = FALSE) out <- length(v) }), outputType = quote(integer(0)) ) ) setSize2D <- list( list(name = 'setSize 2D', expr = quote({ out <- nimMatrix(1:5, nrow = 2, ncol = 3) setSize(out, c(3, 7)) }), outputType = quote(double(2)) ), list(name = 'setSize 2D dim expresion', expr = quote({ out <- nimMatrix(1:5, nrow = 2, ncol = 3) z <- rpois(2, lambda = 1) setSize(out, c(3, 1 + sum(z))) }), outputType = quote(double(2)) ), list(name = 'setSize 2D to 0', expr = quote({ out <- nimMatrix(1:5, nrow = 2, ncol = 3) setSize(out, c(0, 0)) }), outputType = quote(double(2)) ), list(name = 'setSize 2D, copy=FALSE (default fillValues = TRUE)', expr = quote({ out <- nimMatrix(1:5, nrow = 2, ncol = 3) setSize(out, c(3,7), copy=FALSE) }), outputType = quote(double(2)) ), list(name = 'setSize 2D, (default copy = TRUE), fillZeros = FALSE', expr = quote({ v <- nimMatrix(1:5, nrow = 2, ncol = 3) setSize(v, c(3,7), fillZeros = FALSE) out <- v[1:3, 1:2] }), outputType = quote(double(2)) ), list(name = 'setSize 2D, copy=FALSE, fillZeros = FALSE', expr = quote({ v <- nimMatrix(1:5, nrow = 2, ncol = 3) setSize(v, c(3,7), copy = FALSE, fillZeros = FALSE) out <- nimDim(v) }), outputType = quote(integer(1)) ) ) setSize3D <- list( list(name = 'setSize 3D', expr = quote({ out <- nimArray(1:5, dim = c(2,3,1)) setSize(out, c(7, 2, 2)) }), outputType = quote(double(3)) ), list(name = 'setSize 3D dim expresion', expr = quote({ out <- nimArray(1:5, dim = c(2,3,1)) z <- rpois(2, lambda = 1) setSize(out, c(3, 1 + sum(z), 2)) }), outputType = quote(double(3)) ), list(name = 'setSize 3D to 0', expr = quote({ out <- nimArray(1:5, dim = c(2,3,1)) setSize(out, c(0, 0, 0)) }), outputType = quote(double(3)) ), list(name = 'setSize 3D, copy=FALSE (default fillValues = TRUE)', expr = quote({ out <- nimArray(1:5, dim = c(2,3,1)) setSize(out, c(7, 2, 2), copy=FALSE) }), outputType = quote(double(3)) ), list(name = 'setSize 3D, (default copy = TRUE), fillZeros = FALSE', expr = quote({ v <- nimArray(1:5, dim = c(2,3,1)) setSize(v, c(3, 2, 2), fillZeros = FALSE) out <- v[1:3, 1:2, 1] }), outputType = quote(double(2)) ), list(name = 'setSize 3D, copy=FALSE, fillZeros = FALSE', expr = quote({ v <- nimArray(1:5, dim = c(2,3,1)) setSize(v, c(3, 7, 2), copy = FALSE, fillZeros = FALSE) out <- nimDim(v) }), outputType = quote(integer(1)) ) ) expectedCompilerErrors <- list( list(name = 'numeric: fail for length given as vector', expr = quote({ a <- 2:4 out <- nimNumeric(a, value = 1.5); }), outputType = quote(double(1)), expectedCompilerError = TRUE ), list(name = 'numeric: fail for init given as vector', expr = quote({ b <- c(TRUE, FALSE, TRUE) out <- nimNumeric(3, value = 1.5, init = b); }), outputType = quote(double(1)), expectedCompilerError = TRUE ), list(name = 'integer: fail for length given as vector', expr = quote({ a <- 2:4 out <- nimInteger(a, value = 15); }), outputType = quote(integer(1)), expectedCompilerError = TRUE ), list(name = 'integer: fail for init given as vector', expr = quote({ b <- c(TRUE, FALSE, TRUE) out <- nimInteger(3, value = 15, init = b); }), outputType = quote(integer(1)), expectedCompilerError = TRUE ), list(name = 'logical: fail for length given as vector', expr = quote({ a <- 2:4 out <- nimLogical(a, value = TRUE); }), outputType = quote(logical(1)), expectedCompilerError = TRUE ), list(name = 'logical: fail for init given as vector', expr = quote({ b <- c(TRUE, FALSE, TRUE) out <- nimLogical(3, value = TRUE, init = b); }), outputType = quote(logical(1)), expectedCompilerError = TRUE ), list(name = 'array 1D (dim vector without nDim: safe compiler fail)', expr = quote({ dim <- c(2) out <- nimArray(6, dim = dim); }), outputType = quote(double(1)), expectedCompilerError = TRUE ), list(name = 'array 3D (dim vector without nDim: safe compiler fail)', expr = quote({ dim <- c(2, 3, 4) out <- nimArray(6, dim = dim); }), outputType = quote(double(3)), expectedCompilerError = TRUE ), list(name = 'array 2D (dim vector without nDim: safe compiler fail)', expr = quote({ dim <- c(2, 3) out <- nimArray(6, dim = dim); }), outputType = quote(double(2)), expectedCompilerError = TRUE ) ) numericTestResults <- test_coreRfeature_batch(numericTests, 'numericTests') numericTestResults <- test_coreRfeature_batch(integerTests, 'integerTests') logicalTestResults <- test_coreRfeature_batch(logicalTests, 'logicalTests') matrixTestResults <- test_coreRfeature_batch(matrixTests, 'matrixTests') array1DTestResults <- test_coreRfeature_batch(arrayTests1D, 'arrayTests1D') array2DTestResults <- test_coreRfeature_batch(arrayTests2D, 'arrayTests2D') array3DTestResults <- test_coreRfeature_batch(arrayTests3D, 'arrayTests3D') setSize1DResults <- test_coreRfeature_batch(setSize1D, 'setSize1D') setSize1DintegerResults <- test_coreRfeature_batch(setSize1Dinteger, 'setSize1Dinteger') setSize2DResults <- test_coreRfeature_batch(setSize2D, 'setSize2D') setSize3DResults <- test_coreRfeature_batch(setSize3D, 'setSize3D') allocationExpectedCompilerFailures <- lapply(expectedCompilerErrors, test_coreRfeature) options(warn = RwarnLevel) nimbleOptions(verbose = nimbleVerboseSetting)
.problemparameters = function(t_ind, dist_mat, subset_weight, n_controls, total_groups, mom_covs, mom_tols, mom_targets, ks_covs, ks_n_grid, ks_tols, exact_covs, near_exact_covs, near_exact_devs, fine_covs, near_fine_covs, near_fine_devs, near_covs, near_pairs, near_groups, far_covs, far_pairs, far_groups, use_controls, approximate) { n_t = sum(t_ind) n_c = length(t_ind)-n_t n_dec_vars = n_t*n_c n_mom_covs = 0 if(!is.null(mom_covs)) { n_mom_covs = ncol(mom_covs) } n_ks_covs = 0 if(!is.null(ks_covs)) { n_ks_covs = ncol(ks_covs) if ((length(ks_n_grid)==1) && (n_ks_covs > 1)) { ks_n_grid = rep(ks_n_grid, n_ks_covs) } } ks_covs_aux = NULL if (is.null(ks_covs)) { max_ks_n_grid = 0 } if (!is.null(ks_covs)) { max_ks_n_grid = max(ks_n_grid) ks_grid = matrix(0, nrow = max_ks_n_grid, ncol = n_ks_covs) for (i in 1:n_ks_covs) { ks_covs_t_aux = ks_covs[, i][t_ind==1] ks_grid_aux = quantile(ks_covs_t_aux, probs = seq(1/ks_n_grid[i], 1, 1/ks_n_grid[i])) ks_grid_aux = c(ks_grid_aux, rep(0, max_ks_n_grid-ks_n_grid[i])) ks_grid[, i] = ks_grid_aux } ks_covs_aux = matrix(0, nrow = length(t_ind), ncol = max_ks_n_grid*n_ks_covs) for (i in 1:n_ks_covs) { k = (i-1)*max_ks_n_grid for (j in 1:max_ks_n_grid) { ks_covs_aux[, j+k][ks_covs[, i]<ks_grid[j, i]] = 1 } } } if (is.null(dist_mat)) { if (approximate == 1 | n_controls == 1) { cvec = -(1*rep(1, n_t*n_c)) } else { cvec = c(-(1*rep(1, n_t*n_c)), rep(0, n_t)) } } if (!is.null(dist_mat)) { if (approximate == 1 | n_controls == 1) { cvec = as.vector(matrix(t(dist_mat), nrow = 1, byrow = TRUE))-(subset_weight*rep(1, n_t*n_c)) } else { cvec = c(as.vector(matrix(t(dist_mat), nrow = 1, byrow = TRUE))-(subset_weight*rep(1, n_t*n_c)), rep(0, n_t)) } } constraintmat_out = .constraintmatrix(t_ind, n_controls, total_groups, mom_covs, mom_tols, mom_targets, ks_covs, ks_covs_aux, ks_n_grid, ks_tols, exact_covs, near_exact_covs, near_exact_devs, fine_covs, near_fine_covs, near_fine_devs, near_covs, near_pairs, near_groups, far_covs, far_pairs, far_groups, use_controls, approximate) cnstrn_mat = constraintmat_out$cnstrn_mat bvec_7 = constraintmat_out$bvec_7 bvec_8 = constraintmat_out$bvec_8 rows_ind_far_pairs = constraintmat_out$rows_ind_far_pairs rows_ind_near_pairs = constraintmat_out$rows_ind_near_pairs if (approximate == 1 | n_controls == 1) { bvec = c(rep(n_controls, n_t), rep(1, n_c)) } else { bvec = c(rep(0, n_t), rep(1, n_c)) } if (!is.null(mom_covs) & is.null(mom_targets)) { bvec = c(bvec, rep(0, 2*n_mom_covs)) } if (!is.null(ks_covs)) { bvec = c(bvec, rep(0, 2*n_ks_covs*max_ks_n_grid)) } if (!is.null(mom_covs) & !is.null(mom_targets)) { bvec = c(bvec, rep(0, 4*n_mom_covs)) } if (!is.null(exact_covs)) { bvec = c(bvec, rep(0, ncol(exact_covs))) } if (!is.null(near_exact_covs)) { bvec = c(bvec, near_exact_devs) } if (!is.null(fine_covs)) { bvec = c(bvec, bvec_7) } if (!is.null(near_fine_covs)) { n_near_fine_covs = ncol(near_fine_covs) near_fine_devs_aux = NULL for (j in 1:n_near_fine_covs) { near_fine_cov = near_fine_covs[, j] near_fine_devs_aux = c(near_fine_devs_aux, rep(near_fine_devs[j], length(names(table(near_fine_cov))) )) } bvec_8_aux = rep(NA, length(bvec_8)*2) bvec_8_aux[1:length(bvec_8)] = -near_fine_devs_aux bvec_8_aux[(length(bvec_8)+1):(2*length(bvec_8))] = near_fine_devs_aux bvec = c(bvec, bvec_8_aux) } if (!is.null(far_covs)) { n_far_covs = ncol(far_covs) for (j in 1:n_far_covs) { if (!is.null(far_groups)) { bvec = c(bvec, rep(0, 1)) } if (!is.null(far_pairs) && rows_ind_far_pairs[[j]] != -1) { bvec = c(bvec, rep(0, length(table(rows_ind_far_pairs[[j]])))) } } } if (!is.null(near_covs)) { n_near_covs = ncol(near_covs) for (j in 1:n_near_covs) { if (!is.null(near_groups)) { bvec = c(bvec, rep(0, 1)) } if (!is.null(near_pairs) && rows_ind_near_pairs[[j]] != -1) { bvec = c(bvec, rep(0, length(table(rows_ind_near_pairs[[j]])))) } } } if (!is.null(use_controls)) { bvec = c(bvec, sum(use_controls)) } if (!is.null(total_groups)) { if (!is.null(n_controls)) { bvec = c(bvec, total_groups*n_controls) } else { bvec = c(bvec, total_groups) } } if (approximate == 1 | n_controls == 1) { ub = rep(1, n_t*n_c) } else { ub = c(rep(1, n_t*n_c), rep(1, n_t)) } if (approximate == 1 | n_controls == 1) { sense = c(rep("L", n_t), rep("L", n_c), rep("L", 2*n_mom_covs*(is.null(mom_targets))), rep("L", 2*n_ks_covs*max_ks_n_grid)) } else { sense = c(rep("E", n_t), rep("L", n_c), rep("L", 2*n_mom_covs*(is.null(mom_targets))), rep("L", 2*n_ks_covs*max_ks_n_grid)) } if (!is.null(mom_covs) & !is.null(mom_targets)) { sense = c(sense, rep("L", 4*n_mom_covs)) } if (!is.null(exact_covs)) { sense = c(sense, rep("E", ncol(exact_covs))) } if (!is.null(near_exact_covs)) { sense = c(sense, rep("L", ncol(near_exact_covs))) } if (!is.null(fine_covs)) { sense = c(sense, rep("E", length(bvec_7))) } if (!is.null(near_fine_covs)) { sense = c(sense, rep("G", length(bvec_8)), rep("L", length(bvec_8))) } if (!is.null(far_covs)) { n_far_covs = ncol(far_covs) for (j in 1:n_far_covs) { if (!is.null(far_groups)) { sense = c(sense, rep("G", 1)) } if (!is.null(far_pairs) && rows_ind_far_pairs[[j]] != -1) { sense = c(sense, rep("E", length(table(rows_ind_far_pairs[[j]])))) } } } if (!is.null(near_covs)) { n_near_covs = ncol(near_covs) for (j in 1:n_near_covs) { if (!is.null(near_groups)) { sense = c(sense, rep("L", 1)) } if (!is.null(near_pairs) && rows_ind_near_pairs[[j]] != -1) { sense = c(sense, rep("E", length(table(rows_ind_near_pairs[[j]])))) } } } if (!is.null(use_controls)) { sense = c(sense, "E") } if (!is.null(total_groups)) { sense = c(sense, "E") } if (approximate == 1) { vtype = rep("C", n_t*n_c) } else if (n_controls == 1) { vtype = rep("B", n_t*n_c) } else { vtype = c(rep("B", n_t*n_c), rep("B", n_t)) } c_index = rep(1:n_c, n_t) return(list(n_t = n_t, n_c = n_c, cvec = cvec, Amat = cnstrn_mat, bvec = bvec, ub = ub, sense = sense, vtype = vtype, c_index = c_index)) }
"cc.genes" "cc.genes.updated.2019"
lsodar <- function(y, times, func, parms, rtol=1e-6, atol=1e-6, jacfunc=NULL, jactype = "fullint", rootfunc=NULL, verbose=FALSE, nroot = 0, tcrit = NULL, hmin=0, hmax=NULL, hini=0, ynames=TRUE, maxordn = 12, maxords = 5, bandup = NULL, banddown = NULL, maxsteps = 5000, dllname=NULL,initfunc=dllname, initpar=parms, rpar=NULL, ipar=NULL, nout=0, outnames=NULL, forcings=NULL, initforc = NULL, fcontrol=NULL, events=NULL, lags = NULL, ...) { if (is.list(func)) { if (!is.null(jacfunc) & "jacfunc" %in% names(func)) stop("If 'func' is a list that contains jacfunc, argument 'jacfunc' should be NULL") if (!is.null(rootfunc) & "rootfunc" %in% names(func)) stop("If 'func' is a list that contains rootfunc, argument 'rootfunc' should be NULL") if (!is.null(initfunc) & "initfunc" %in% names(func)) stop("If 'func' is a list that contains initfunc, argument 'initfunc' should be NULL") if (!is.null(dllname) & "dllname" %in% names(func)) stop("If 'func' is a list that contains dllname, argument 'dllname' should be NULL") if (!is.null(initforc) & "initforc" %in% names(func)) stop("If 'func' is a list that contains initforc, argument 'initforc' should be NULL") if (!is.null(events$func) & "eventfunc" %in% names(func)) stop("If 'func' is a list that contains eventfunc, argument 'events$func' should be NULL") if ("eventfunc" %in% names(func)) { if (! is.null(events)) events$func <- func$eventfunc else events <- list(func = func$eventfunc) } if (!is.null(func$jacfunc)) jacfunc <- func$jacfunc if (!is.null(func$rootfunc)) rootfunc <- func$rootfunc if (!is.null(func$initfunc)) initfunc <- func$initfunc if (!is.null(func$dllname)) dllname <- func$dllname if (!is.null(func$initforc)) initforc <- func$initforc func <- func$func } hmax <- checkInput (y, times, func, rtol, atol, jacfunc, tcrit, hmin, hmax, hini, dllname) n <- length(y) if (!is.numeric(maxordn)) stop("`maxordn' must be numeric") if(maxordn < 1 || maxordn > 12) stop("`maxord' must be >1 and <=12") if (!is.numeric(maxords)) stop("`maxords' must be numeric") if(maxords < 1 || maxords > 5) stop("`maxords' must be >1 and <=5") if (jactype == "fullint" ) jt <- 2 else if (jactype == "fullusr" ) jt <- 1 else if (jactype == "bandusr" ) jt <- 4 else if (jactype == "bandint" ) jt <- 5 else stop("'jactype' must be one of 'fullint', 'fullusr', 'bandusr' or 'bandint'") if (jt %in% c(4,5) && is.null(bandup)) stop("'bandup' must be specified if banded Jacobian") if (jt %in% c(4,5) && is.null(banddown)) stop("'banddown' must be specified if banded Jacobian") if (is.null(banddown)) banddown <-1 if (is.null(bandup )) bandup <-1 if (jt %in% c(1,4) && is.null(jacfunc)) stop ("'jacfunc' NOT specified; either specify 'jacfunc' or change 'jactype'") Ynames <- attr(y,"names") JacFunc <- NULL RootFunc <- NULL flist<-list(fmat=0,tmat=0,imat=0,ModelForc=NULL) ModelInit <- NULL Eventfunc <- NULL events <- checkevents(events, times, Ynames, dllname, TRUE) if (! is.null(events$newTimes)) times <- events$newTimes if (jt == 4 && banddown>0) erow<-matrix(data=0, ncol=n, nrow=banddown) else erow<-NULL if (is.character(func) | inherits(func, "CFunc")) { DLL <- checkDLL(func,jacfunc,dllname, initfunc,verbose,nout, outnames) if (!is.null(rootfunc)) { if (!is.character(rootfunc) & !inherits(rootfunc, "CFunc")) stop("If 'func' is dynloaded, so must 'rootfunc' be") rootfuncname <- rootfunc if (inherits(rootfunc, "CFunc")) RootFunc <- body(rootfunc)[[2]] else if (is.loaded(rootfuncname, PACKAGE = dllname)) { RootFunc <- getNativeSymbolInfo(rootfuncname, PACKAGE = dllname)$address } else stop(paste("root function not loaded in DLL",rootfunc)) if (nroot == 0) stop("if 'rootfunc' is specified in a DLL, then 'nroot' should be > 0") } ModelInit <- DLL$ModelInit Func <- DLL$Func JacFunc <- DLL$JacFunc Nglobal <- DLL$Nglobal Nmtot <- DLL$Nmtot if (! is.null(forcings)) flist <- checkforcings(forcings,times,dllname,initforc,verbose,fcontrol) if (is.null(ipar)) ipar<-0 if (is.null(rpar)) rpar<-0 Eventfunc <- events$func if (is.function(Eventfunc)) rho <- environment(Eventfunc) else rho <- NULL } else { if(is.null(initfunc)) initpar <- NULL rho <- environment(func) if (ynames) { Func <- function(time,state) { attr(state,"names") <- Ynames unlist(func (time,state,parms,...)) } Func2 <- function(time,state) { attr(state,"names") <- Ynames func (time,state,parms,...) } JacFunc <- function(time,state){ attr(state,"names") <- Ynames rbind(jacfunc(time,state,parms,...),erow) } RootFunc <- function(time,state) { attr(state,"names") <- Ynames rootfunc(time,state,parms,...) } if (! is.null(events$Type)) if (events$Type == 2) Eventfunc <- function(time,state) { attr(state,"names") <- Ynames events$func(time,state,parms,...) } } else { Func <- function(time,state) unlist(func (time,state,parms,...)) Func2 <- function(time,state) func (time,state,parms,...) JacFunc <- function(time,state) rbind(jacfunc(time,state,parms,...),erow) RootFunc <- function(time,state) rootfunc(time,state,parms,...) if (! is.null(events$Type)) if (events$Type == 2) Eventfunc <- function(time,state) events$func(time,state,parms,...) } FF <- checkFunc(Func2,times,y,rho) Nglobal<-FF$Nglobal Nmtot <- FF$Nmtot if (! is.null(events$Type)) if (events$Type == 2) checkEventFunc(Eventfunc,times,y,rho) if (! is.null(rootfunc)) { tmp2 <- eval(rootfunc(times[1],y,parms,...), rho) if (!is.vector(tmp2)) stop("root function 'rootfunc' must return a vector\n") nroot <- length(tmp2) } else nroot = 0 if (jt %in% c(1,4)) { tmp <- eval(JacFunc(times[1], y), rho) if (!is.matrix(tmp)) stop("Jacobian function, 'jacfunc' must return a matrix\n") dd <- dim(tmp) if((jt ==4 && any(dd != c(bandup+banddown+1,n))) || (jt ==1 && any(dd != c(n,n)))) stop("Jacobian dimension not ok") } } if(jt %in% c(1,2)) lmat <- n^2+2 else if(jt %in% c(4,5)) lmat <- (2*banddown+bandup+1)*n+2 lrn = 20+n*(maxordn+1)+ 3*n +3*nroot lrs = 20+n*(maxords+1)+ 3*n +lmat+3*nroot lrw = max(lrn,lrs) liw = 20 + n iwork <- vector("integer",20) rwork <- vector("double",20) rwork[] <- 0. iwork[] <- 0 iwork[1] <- banddown iwork[2] <- bandup iwork[6] <- maxsteps if (maxordn != 12) iwork[8] <- maxordn if (maxords != 5) iwork[9] <- maxords if (verbose) iwork[5] = 1 if(! is.null(tcrit)) rwork[1] <- tcrit rwork[5] <- hini rwork[6] <- hmax rwork[7] <- hmin if (! is.null(times)) itask <- ifelse (is.null (tcrit), 1,4) else itask <- ifelse (is.null (tcrit), 2,5) if(is.null(times)) times<-c(0,1e8) if (verbose) printtask(itask,func,jacfunc) storage.mode(y) <- storage.mode(times) <- "double" IN <-4 lags <- checklags(lags, dllname) on.exit(.C("unlock_solver")) out <- .Call("call_lsoda",y,times,Func,initpar, rtol, atol, rho, tcrit, JacFunc, ModelInit, Eventfunc, as.integer(verbose), as.integer(itask), as.double(rwork), as.integer(iwork), as.integer(jt),as.integer(Nglobal), as.integer(lrw),as.integer(liw),as.integer(IN),RootFunc, as.integer(nroot), as.double (rpar), as.integer(ipar), 0L, flist, events, lags, PACKAGE="deSolve") iroot <- attr(out, "iroot") out <- saveOut(out, y, n, Nglobal, Nmtot, func, Func2, iin=c(1,12:21), iout=c(1:3,14,5:9,15:16),nr = 5) attr(out, "iroot") <- iroot attr(out, "type") <- "lsodar" if (verbose) diagnostics(out) return(out) }
open_in_pubmed <- function(pubmed_id) { if (!(rlang::is_double(pubmed_id) || rlang::is_integer(pubmed_id) || rlang::is_character(pubmed_id) )) stop("pubmed_id must be a vector of numbers.") if (rlang::is_double(pubmed_id) || rlang::is_integer(pubmed_id)) pubmed_id2 <- as.character(pubmed_id) else pubmed_id2 <- pubmed_id if (any(!is_pubmed_id(pubmed_id2))) stop("These are not valid PubMed IDs: ", concatenate::cc_and(pubmed_id[!is_pubmed_id(pubmed_id2)], oxford = TRUE), ".") if (interactive()) { urls <- glue::glue("https://pubmed.ncbi.nlm.nih.gov/{pubmed_id2}") purrr::walk(urls, utils::browseURL) return(invisible(TRUE)) } else { return(invisible(TRUE)) } }
download_fsl = function( os = c("macosx", "redhat5", "redhat6", "centos5", "centos6", "debian", "ubuntu"), outdir = tempdir(), overwrite = TRUE, ... ) { os = match.arg(os) if (os %in% c("debian", "ubuntu")) { message("Please install using neurodebian"); browseURL("http://neuro.debian.net/pkgs/fsl.html") } os = sub("redhat", "centos", os) stub = "http://fsl.fmrib.ox.ac.uk/fsldownloads/fsl-" version = readLines("http://fsl.fmrib.ox.ac.uk/fsldownloads/latest-version.txt") app = ".tar.gz" if (grepl("centos", os)) { app = "_64.tar.gz" } html = paste0(stub, version, "-", os, app) destfile = file.path(outdir, basename(html)) if (file.exists(destfile) & !overwrite) { return(destfile) } res = download.file(url = html, destfile = destfile, ...) return(destfile) }
NewInput.MMInf <- function(lambda=0, mu=0, n=0) { res <- list(lambda = lambda, mu = mu, n = n) class(res) <- "i_MMInf" res } CheckInput.i_MMInf <- function(x, ...) { MMInf_class <- "The class of the object x has to be M/M/Inf (i_MMInf)" MMInf_anomalous <- "Some value of lambda, mu, or n is anomalous. Check the values." if (!inherits(x, "i_MMInf")) stop(MMInf_class) if (is.anomalous(x$lambda) || is.anomalous(x$mu) || is.anomalous(x$n)) stop(MMInf_anomalous) if (x$mu <= 0) stop(ALL_mu_positive) if (x$lambda < 0) stop(ALL_lambda_zpositive) if (!is.wholenumber(x$n)) stop(ALL_n_integer) } QueueingModel.i_MMInf <- function(x, ...) { CheckInput.i_MMInf(x, ...) W <- 1 / x$mu L <- x$lambda * W Throughput <- x$lambda if (x$n < 0) Pn <- numeric() else Pn <- sapply(0:x$n, dpois, L) FW <- function(t){ exp(x$mu) } FWq <- function(t){ 0 } Lq <- 0 Wq <- 0 Lqq <- NA Wqq <- NA VN <- L VNq <- 0 VT <- 1/(x$mu^2) VTq <- 0 res <- list( Inputs=x, RO = L, Lq = Lq, VNq = VNq, Wq = Wq, VTq = VTq, Throughput = Throughput, L = L, VN = VN, W = W, VT = VT, Lqq = Lqq, Wqq = Wqq, Pn = Pn, Qn = Qn, FW = FW, FWq = FWq ) class(res) <- "o_MMInf" res } Inputs.o_MMInf <- function(x, ...) { x$Inputs } L.o_MMInf <- function(x, ...) { x$L } VN.o_MMInf <- function(x, ...) { x$VN } W.o_MMInf <- function(x, ...) { x$W } VT.o_MMInf <- function(x, ...) { x$VT } RO.o_MMInf <- function(x, ...) { x$RO } Lq.o_MMInf <- function(x, ...) { x$Lq } VNq.o_MMInf <- function(x, ...) { x$VNq } Wq.o_MMInf <- function(x, ...) { x$Wq } VTq.o_MMInf <- function(x, ...) { x$VTq } Wqq.o_MMInf <- function(x, ...) { x$Wqq } Lqq.o_MMInf <- function(x, ...) { x$Lqq } Pn.o_MMInf <- function(x, ...) { x$Pn } Qn.o_MMInf <- function(x, ...) { x$Qn } Throughput.o_MMInf <- function(x, ...) { x$Throughput } Report.o_MMInf <- function(x, ...) { reportAux(x) } summary.o_MMInf <- function(object, ...) { aux <- list(el=CompareQueueingModels(object)) class(aux) <- "summary.o_MM1" aux } print.summary.o_MMInf <- function(x, ...) { print_summary(x, ...) }
test.kulczynski <- function() { dataPath <- file.path(path.package(package="clusterCrit"),"unitTests","data","testsExternal100.Rdata") load(file=dataPath, envir=.GlobalEnv) idx <- extCriteria(clus_p2, clus_p3, c("Kulczynski")) val <- 0.428073406219482 cat(paste("\nShould be =",val,"\n")) cat(paste("\nFound idx =",idx,"\n")) checkEqualsNumeric(idx[[1]],val) }
NULL dbinom_sparseLocalSCR <- nimbleFunction( run = function( x = double(1), detNums = double(0), detIndices = double(1), size = double(1), p0 = double(0), sigma = double(0), s = double(1), trapCoords = double(2), localTrapsIndices = double(2), localTrapsNum = double(1), resizeFactor = double(0, default = 1), habitatGrid = double(2), indicator = double(0, default = 1.0), log = integer(0, default = 0) ) { returnType(double(0)) if(indicator == 0){ if(detNums == 0){ if(log == 0) return(1.0) else return(0.0) } else { if(log == 0) return(0.0) else return(-Inf) } } sID <- habitatGrid[trunc(s[2]/resizeFactor)+1, trunc(s[1]/resizeFactor)+1] theseLocalTraps <- localTrapsIndices[sID,1:localTrapsNum[sID]] if(detNums > 0){ for(r in 1:detNums){ if(sum(detIndices[r] == theseLocalTraps) == 0){ if(log == 0) return(0.0) else return(-Inf) } } } alpha <- -1.0 / (2.0 * sigma * sigma) logProb <- 0.0 detIndices1 <- c(detIndices,0) count <- 1 for(r in 1:localTrapsNum[sID]){ if(theseLocalTraps[r] == detIndices1[count]){ d2 <- pow(trapCoords[theseLocalTraps[r],1] - s[1], 2) + pow(trapCoords[theseLocalTraps[r],2] - s[2], 2) p <- p0 * exp(alpha * d2) logProb <- logProb + dbinom(x[count], prob = p, size = size[theseLocalTraps[r]], log = TRUE) count <- count + 1 }else{ d2 <- pow(trapCoords[theseLocalTraps[r],1] - s[1], 2) + pow(trapCoords[theseLocalTraps[r],2] - s[2], 2) p <- p0 * exp(alpha * d2) logProb <- logProb + dbinom(0, prob = p, size = size[theseLocalTraps[r]], log = TRUE) } } if(log)return(logProb) return(exp(logProb)) }) rbinom_sparseLocalSCR <- nimbleFunction( run = function( n = double(0, default = 1), detNums = double(0), detIndices = double(1), size = double(1), p0 = double(0), sigma = double(0), s = double(1), trapCoords = double(2), localTrapsIndices = double(2), localTrapsNum = double(1), resizeFactor = double(0, default = 1), habitatGrid = double(2), indicator = double(0, default = 1.0) ) { returnType(double(1)) if(n >= 0) stop("Random generation for the dbinom_sparseLocalSCR distribution is not currently supported") dummyOut <- detIndices return(dummyOut) })
hmmviterbi2.cont <- function(y, M, workparm, zero_init, emit_x=NULL,zeroinfl_x=NULL,timeindex, plot=FALSE, xlim=NULL, ylim=NULL, ...){ if(floor(M)!=M | M<2) stop("The number of latent states must be an integer greater than or equal to 2!") if(length(zero_init)!=M) stop("The dimension of zero_init is not M!") ntimes <- length(y) state <- rep(NA, sum(ntimes)) tempmat <- matrix(0,nrow=length(y),ncol=1) ncovprior <- 0 covprior <- tempmat ncovtpm <- 0 covtpm <- tempmat if(is.null(emit_x)){ ncovemit <- 0 covemit <- ncol(emit_x) }else{ ncovemit <- ncol(emit_x) covemit <- emit_x } if(is.null(zeroinfl_x)){ ncovzeroinfl <- 0 covzeroinfl <- tempmat }else{ ncovzeroinfl <- ncol(zeroinfl_x) covzeroinfl <- zeroinfl_x } vdiff <- diff(timeindex) udiff <- sort(unique(vdiff)) tpm_init <- retrieve_cov_cont(workparm,M,ncovemit+1)$gamma expms <- getallexpm(tpm_init, udiff) state <- hmm_cov_viterbi_cont(workparm, M,y,ncovprior,covprior, ncovtpm,covtpm,ncovzeroinfl,covzeroinfl, ncovemit,covemit, zero_init, timeindex, udiff, expms) if(plot==TRUE){ xlimit <- rep(NA,2) ylimit <- rep(NA,2) if(is.null(xlim)){ xlimit[1] <- 0 xlimit[2] <- sum(ntimes) }else{xlimit <- xlim} if(is.null(ylim)){ ylimit[1] <- 0 ylimit[2] <- max(y) * 1.3 }else{ylimit <- ylim} temp <- y[1:min(length(y),floor(xlimit[2]))] plot(temp, xlim=xlimit, ylim=ylimit, type="l",...) points(1:length(temp),rep(ylimit[1],length(temp)), pch=16,cex=0.8,col=state+1) legend <- NULL for(i in 1:M) legend <- c(legend,paste("state ",i,sep="")) legend("top",legend,pch=16,col=2:(M+1),bty="n",cex=0.9, ncol=M,xpd=TRUE) } return(state) }
assignClusterNames <- function(out, lab_no, beta_weights, vocab){ members <- c() for(i in seq(length(out$children))){ if (!('size' %in% names(out$children[[i]]))) out$children[[i]] <- assignClusterNames(out$children[[i]], lab_no, beta_weights, vocab) } for(i in seq(length(out$children))){ members <- c(members, out$children[[i]]$topic_no) } out$topic_no <- members margins <- marginalize(members, beta_weights$beta, beta_weights$weights) labels <- vocab[margins$indices[1:lab_no]] out$name <- paste(sample(labels, lab_no), collapse=", ") return(out) }
recode_delete <- function(input, codes, filter = TRUE, output = NULL, childrenReplaceParents = TRUE, recursiveDeletion = FALSE, decisionLabel = NULL, justification = NULL, justificationFile = NULL, preventOverwriting = rock::opts$get('preventOverwriting'), encoding = rock::opts$get('encoding'), silent = rock::opts$get('silent')) { return( generic_recoding( input = input, codes = codes, filter = filter, func = changeSource_uncode, output = output, decisionLabel = decisionLabel, justification = justification, justificationFile = justificationFile, preventOverwriting = preventOverwriting, encoding = encoding, silent = silent, childrenReplaceParents = childrenReplaceParents, recursiveDeletion = recursiveDeletion ) ); } changeSource_uncode <- function(input, codes, filter, childrenReplaceParents = TRUE, recursiveDeletion = FALSE, silent = rock::opts$get('silent')) { codeDelimiters <- rock::opts$get("codeDelimiters"); validCodeCharacters <- rock::opts$get("validCodeCharacters"); inductiveCodingHierarchyMarker <- rock::opts$get("inductiveCodingHierarchyMarker"); if (length(codes) > 1) { msg("Multiple codes to remove have been specified: starting ", "sequential removal of ", length(codes), " codes.\n\n", silent=silent); for (i in seq_along(codes)) { input <- changeSource_uncode( input = input, codes = codes[i], filter = filter, childrenReplaceParents = childrenReplaceParents, recursiveDeletion = recursiveDeletion, silent = silent ); } } else { cleanCode <- cleanCode(codes); if (!silent) { cat0("Removing all occurrences of code '", cleanCode, "'.\n"); cat0("If this code has code descendency (i.e. a child code, grandchild ", "code, etc), the direct child code will "); if (childrenReplaceParents) { cat0("replace the removed code.\n") } else { cat0("also be removed, as will all further descendents.\n"); } cat0("If this code has code ancestry (i.e. a (partial) path to the ", "code root is specified with a parent code, potential grandparent ", "code, etc), the ancestry specified in that coding instance will ", "be "); if (recursiveDeletion) { cat0("removed as well, as if the code had never been applied.\n") } else { cat0("retained, so the utterance will remain coded with the ", "parent code (and any ancestry of that parent code will ", "also be retained in that coding instance).\n"); } } filteredUtterances <- input[filter]; utterancesWithMatches <- grep( cleanCode, filteredUtterances ); if (!silent) { cat0("Out of the ", length(input), " utterances in the provided source, ", sum(filter), " are selected by the filter, ", length(utterancesWithMatches), " of which contain the code text.\n"); } regexToDeleteSingularOccurrence <- paste0( "\\s?", escapeRegexCharacterClass(codeDelimiters[1]), cleanCode, escapeRegexCharacterClass(codeDelimiters[2]) ); regexToDeleteLeafOccurrence <- paste0( "(\\s?", escapeRegexCharacterClass(codeDelimiters[1]), validCodeCharacters, "*)", inductiveCodingHierarchyMarker, cleanCode, escapeRegexCharacterClass(codeDelimiters[2]) ); regexToDeleteRecursively <- paste0( "\\s?", escapeRegexCharacterClass(codeDelimiters[1]), validCodeCharacters, "*", cleanCode, validCodeCharacters, "*", escapeRegexCharacterClass(codeDelimiters[2]) ); regexToDeleteIfDescendentsExist <- paste0( "(\\s?", escapeRegexCharacterClass(codeDelimiters[1]), validCodeCharacters, "*)", cleanCode, inductiveCodingHierarchyMarker, "(", validCodeCharacters, "*", escapeRegexCharacterClass(codeDelimiters[2]), ")" ); for (i in seq_along(utterancesWithMatches)) { currentUtterance <- filteredUtterances[utterancesWithMatches[i]]; currentUtterance <- gsub( regexToDeleteSingularOccurrence, "", currentUtterance ); if (recursiveDeletion) { currentUtterance <- gsub( regexToDeleteRecursively, "", currentUtterance ); } else { currentUtterance <- gsub( regexToDeleteLeafOccurrence, paste0("\\1", escapeRegexCharacterClass(codeDelimiters[2])), currentUtterance ); if (grepl(paste0(cleanCode, inductiveCodingHierarchyMarker), currentUtterance)) { if (childrenReplaceParents) { currentUtterance <- gsub( regexToDeleteIfDescendentsExist, "\\1\\2", currentUtterance ); } else { currentUtterance <- gsub( regexToDeleteIfDescendentsExist, paste0("\\1", escapeRegexCharacterClass(codeDelimiters[2])), currentUtterance ); } } } if (!silent) { if (identical(currentUtterance, filteredUtterances[utterancesWithMatches[i]])) { cat0("--UNCHANGED: ", currentUtterance, "\n"); } else { cat0("--------PRE: ", currentUtterance, "\n", " POST: ", filteredUtterances[utterancesWithMatches[i]], "\n"); } } filteredUtterances[utterancesWithMatches[i]] <- currentUtterance; } oldInput <- input; input[filter] <- filteredUtterances; diffCount <- sum(input != oldInput); if (!silent) { cat0("Deleted ", diffCount, " occurrences of code '", codes, "'.\n\n"); } } return(input); }
nightly <- function(trigElement, bodyColor = " htmltools::tags$script(htmltools::HTML(glue::glue( " var nightModeConfig = {{ body: '{bodyColor}', texts: '{txtColor}', inputs: {{ color: '{inpTxtColor}', backgroundColor: '{inpBgColor}', }} }}; var Nightly = new Nightly(nightModeConfig, true); document.getElementById('{trigElement}').addEventListener('click', function(){{ Nightly.toggle(); }}); " ))) }
context("Fst Hudson all SNPs") test_that("calculate Fst Hudson for all SNPs",{ data(example_SNP) idx1 <- which(sample_labels == 'pop1') idx2 <- which(sample_labels == 'pop2') fst.pairwise <- fst.each.snp.hudson(simsnp$snp, idx1, idx2) expect_equal(fst.pairwise[1], 0.007396462) expect_equal(fst.pairwise[2], 0.09957484) expect_length(fst.pairwise, 2000) })
gskmeans <- function(data, k=2, ...){ mydata = prec_input_sphere(as.matrix(data)) myk = max(1, round(k)) params = list(...) pnames = names(params) if ("maxiter"%in%pnames){ myiter = max(5, round(params$maxiter)) } else { myiter = 10 } if ("abstol"%in%pnames){ myeps = max(params$abstol, .Machine$double.eps) } else { myeps = sqrt(.Machine$double.eps) } if ("init"%in% pnames){ myinit = match.arg(tolower(params$init), c("kmeans","gmm")) } else { myinit = "kmeans" } if ("verbose"%in%pnames){ myprint = as.logical(params$verbose) } else { myprint = FALSE } cpprun = sp_gskmeans(mydata, myk, myinit, myiter, myeps, myprint) output = list() output$cluster = round(as.vector(cpprun$cluster+1)) output$cost = as.double(cpprun$cost) output$means = cpprun$means output$algorithm = "gskmeans" return(structure(output, class="T4cluster")) }
library('mfx') set.seed(12345) n = 1000 x = rnorm(n) y = rbeta(n, shape1 = plogis(1 + 0.5 * x), shape2 = (abs(0.2*x))) y = (y*(n-1)+0.5)/n data = data.frame(y,x) betamfx(y~x|x, data=data)
dbQuoteString_PqConnection_character <- function(conn, x, ...) { if (length(x) == 0) return(SQL(character())) if (is(conn, "RedshiftConnection")) { out <- paste0("'", gsub("(['\\\\])", "\\1\\1", enc2utf8(x)), "'") out[is.na(x)] <- "NULL::varchar(max)" } else { out <- connection_quote_string(conn@ptr, enc2utf8(x)) } SQL(out) } setMethod("dbQuoteString", c("PqConnection", "character"), dbQuoteString_PqConnection_character)
poisregmixEM = function (y, x, lambda = NULL, beta = NULL, k = 2, addintercept = TRUE, epsilon = 1e-08, maxit = 10000, verb=FALSE) { if (addintercept) { x = cbind(1, x) } else x = as.matrix(x) n <- length(y) p <- ncol(x) tmp <- poisregmix.init(y=y, x=x, lambda=lambda, beta=beta, k=k) lambda <- tmp$lambda beta <- tmp$beta k <- tmp$k xbeta <- x %*% beta z <- matrix(0, n, k) diff <- 1 iter <- 0 comp <- t(t(dpois(y, exp(xbeta))) * lambda) compsum <- apply(comp, 1, sum) obsloglik <- sum(log(compsum)) ll <- obsloglik restarts <- 0 while (diff > epsilon && iter < maxit) { j.star = apply(xbeta, 1, which.max) for (i in 1:n) { for (j in 1:k) { z[i, j] = lambda[j]/lambda[j.star[i]] * exp(y[i] * (xbeta[i, j] - xbeta[i, j.star[i]]) + exp(xbeta[i, j.star[i]]) - exp(xbeta[i, j])) } } z = z/apply(z, 1, sum) z[,k]=1-apply(as.matrix(z[,(1:(k-1))]),1,sum) if(sum(is.na(z))>0){ cat("Need new starting values due to underflow...","\n") restarts <- restarts + 1 if(restarts>15) stop("Too many tries!") tmp <- poisregmix.init(y=y, x=x, k=k) lambda <- tmp$lambda beta <- tmp$beta k <- tmp$k diff <- 1 iter <- 0 xbeta <- x %*% beta comp <- t(t(dpois(y, exp(xbeta))) * lambda) compsum <- apply(comp, 1, sum) obsloglik <- sum(log(compsum)) ll <- obsloglik } else{ lambda <- apply(z, 2, mean) lm.out <- lapply(1:k, function(j) try(glm.fit(x, y, weights = z[, j], family = poisson()) ,silent=TRUE)) beta = sapply(lm.out,coef) xbeta <- x %*% beta comp <- t(t(dpois(y, exp(xbeta))) * lambda) compsum <- apply(comp, 1, sum) newobsloglik <- sum(log(compsum)) if(abs(newobsloglik)==Inf || is.na(newobsloglik) || newobsloglik < obsloglik){ cat("Need new starting values due to singularity...","\n") restarts <- restarts + 1 if(restarts>15) stop("Too many tries!") tmp <- poisregmix.init(y=y, x=x, k=k) lambda <- tmp$lambda beta <- tmp$beta k <- tmp$k diff <- 1 iter <- 0 xbeta <- x %*% beta comp <- t(t(dpois(y, exp(xbeta))) * lambda) compsum <- apply(comp, 1, sum) obsloglik <- sum(log(compsum)) ll <- obsloglik } else{ diff <- newobsloglik - obsloglik obsloglik <- newobsloglik ll <- c(ll, obsloglik) iter <- iter + 1 if (verb) { cat("iteration=", iter, "diff=", diff, "log-likelihood", obsloglik, "\n") } } } } if (iter == maxit) { cat("WARNING! NOT CONVERGENT!", "\n") } cat("number of iterations=", iter, "\n") beta <- matrix(beta,ncol=k) rownames(beta) <- c(paste("beta", ".", 0:(p-1), sep = "")) colnames(beta) <- c(paste("comp", ".", 1:k, sep = "")) colnames(z) <- c(paste("comp", ".", 1:k, sep = "")) a=list(x=x, y=y, lambda = lambda, beta = beta, loglik = obsloglik, posterior = z, all.loglik=ll, restarts=restarts, ft="poisregmixEM") class(a) = "mixEM" a }
age_pyramid <- function(data, age_group = "age_group", split_by = "sex", stack_by = NULL, count = NULL, proportional = FALSE, na.rm = TRUE, show_midpoint = TRUE, vertical_lines = FALSE, horizontal_lines = TRUE, pyramid = TRUE, pal = NULL) { stop_if_not_df_or_svy(data, deparse(substitute(data))) age_group <- get_var(data, !!rlang::enquo(age_group)) split_by <- get_var(data, !!rlang::enquo(split_by)) stack_by <- get_var(data, !!rlang::enquo(stack_by)) count <- get_var(data, !!rlang::enquo(count)) if (!is.factor(as.data.frame(data)[[age_group]])) { stop("age group must be a factor") } if (length(stack_by) == 0) { stack_by <- split_by } ag <- rlang::sym(age_group) sb <- rlang::sym(split_by) st <- rlang::sym(stack_by) if (length(count) == 0) { plot_data <- aggregate_by_age( data, age_group = age_group, stack_by = stack_by, split_by = split_by, proportional = proportional, na.rm = na.rm ) } else { plot_data <- dplyr::rename(data, n = !!rlang::sym(count)) } age_levels <- levels(plot_data[[age_group]]) max_age_group <- age_levels[length(age_levels)] split_levels <- plot_data[[split_by]] split_levels <- if (is.factor(split_levels)) levels(split_levels) else unique(split_levels) split_levels <- split_levels[!is.na(split_levels)] stk_levels <- plot_data[[stack_by]] stk_levels <- if (is.factor(stk_levels)) levels(stk_levels) else unique(stk_levels) stopifnot(length(split_levels) >= 1L) split_measured_binary <- pyramid && length(split_levels) == 2L if (split_measured_binary) { maxdata <- dplyr::group_by(plot_data, !!ag, !!sb, .drop = FALSE) } else { maxdata <- dplyr::group_by(plot_data, !!ag, .drop = FALSE) } maxdata <- dplyr::tally(maxdata, wt = !!quote(n), name = "n") max_n <- max(abs(maxdata[["n"]]), na.rm = TRUE) if (proportional) { lab_fun <- function(i) scales::percent(abs(i)) y_lab <- "proportion" } else { lab_fun <- function(i) format(abs(i), big.mark = ",", trim = TRUE) y_lab <- "counts" } stopifnot(is.finite(max_n), max_n > 0) the_breaks <- pretty(c(0, max_n), min.n = 5) the_breaks <- if (split_measured_binary) c(-rev(the_breaks[-1]), the_breaks) else the_breaks if (split_measured_binary) { plot_data[["n"]] <- ifelse(plot_data[[split_by]] == split_levels[[1L]], -1L, 1L) * plot_data[["n"]] maxdata[["d"]] <- ifelse(maxdata[[split_by]] == split_levels[[1L]], -1L, 0L) * maxdata[["n"]] maxdata <- dplyr::summarise(maxdata, center = sum(!!quote(d)) + sum(!!quote(n)) / 2) } else { maxdata[["center"]] <- maxdata[["n"]] / 2 } pyramid <- ggplot(plot_data, aes(x = !!ag, y = !!quote(n))) + theme(axis.line.y = element_blank()) + labs(y = y_lab) pal <- if (is.function(pal)) pal(length(stk_levels)) else pal if (!split_measured_binary) { maxdata[["zzzzz_alpha"]] <- "Total" pyramid <- pyramid + geom_col(aes(alpha = !!quote(zzzzz_alpha)), fill = "grey80", color = "grey20", data = maxdata) } pyramid <- pyramid + geom_col(aes(group = !!sb, fill = !!st), color = "grey20") + coord_flip() if (is.null(pal)) { pyramid <- pyramid + scale_fill_brewer(type = "qual", guide = guide_legend(order = 1)) } else { pyramid <- pyramid + scale_fill_manual(values = pal, guide = guide_legend(order = 1)) } EXPANSION <- if (utils::packageVersion("ggplot2") < "3.3.0") ggplot2::expand_scale else ggplot2::expansion pyramid <- pyramid + scale_y_continuous( limits = if (split_measured_binary) range(the_breaks) else c(0, max_n), breaks = the_breaks, labels = lab_fun, expand = EXPANSION(mult = 0.02, add = 0) ) + scale_x_discrete(drop = FALSE) if (!split_measured_binary) { pyramid <- pyramid + facet_wrap(split_by) + scale_alpha_manual(values = 0.5, guide = guide_legend(title = NULL, order = 3)) } if (vertical_lines == TRUE) { pyramid <- pyramid + geom_hline(yintercept = the_breaks, linetype = "dotted", colour = "grey50") } if (show_midpoint) { maxdata <- dplyr::arrange(maxdata, !!ag) maxdata[["x"]] <- seq_along(maxdata[[age_group]]) - 0.25 maxdata[["xend"]] <- maxdata[["x"]] + 0.5 maxdata[["halfway"]] <- "midpoint" pyramid <- pyramid + geom_segment(aes( x = !!quote(x), xend = !!quote(xend), y = !!quote(center), yend = !!quote(center), linetype = !!quote(halfway) ), color = "grey20", key_glyph = "vpath", data = maxdata ) + scale_linetype_manual(values = "dashed", guide = guide_legend(title = NULL, order = 2)) } if (split_measured_binary && stack_by != split_by) { pyramid <- pyramid + annotate( geom = "label", x = max_age_group, y = -diff(the_breaks)[1], vjust = 0.5, hjust = 1, label = split_levels[[1]] ) + annotate( geom = "label", x = max_age_group, y = diff(the_breaks)[1], vjust = 0.5, hjust = 0, label = split_levels[[2]] ) } if (horizontal_lines == TRUE) { pyramid <- pyramid + theme(panel.grid.major.y = element_line(linetype = 2)) } pyramid <- pyramid + geom_hline(yintercept = 0) pyramid }
densityplot.lambdaReg <- function(x, by = "column", col, xlim, ylim, main = "", sub = NULL, xlab, ylab, lty = par("lty"), lwd = par("lwd"), ...) { readpars <- par(no.readonly = TRUE) idx <- dimnames(x$lambda) lidx <- sapply(idx, length) names(lidx) <- names(idx) <- c("rows", "columns") dens <- array(NA, dim = lidx, dimnames = idx) for (i in idx[[2]]) { for (j in idx[[1]]) dens[j,i] <- dnorm(x$lambda[j,i], mean = x$lambda[j,i], sd = x$se[j,i]) } if (missing(xlim)) { tmpL <- x$lambda - 3*x$se tmpH <- x$lambda + 3*x$se xlim <- c(min(tmpL), max(tmpH)) } if (by == "row") { par(mfrow = c(lidx[1], 1), ...) if (missing(ylim)) { ylim <- apply(dens, 1, max) } if (missing(xlab)) { xlab <- paste("Percentage", unlist(idx[[1]])) } else if (length(xlab) != length(idx[[1]])) { warning(paste("xlab needs to be", lidx[1], "long")) xlab <- rep(xlab, lidx[1])[1:lidx[1]] } if (missing(col)) { col <- rainbow(lidx[2]) } else { if (length(col) < lidx[2]) col <- rep(col, idx[[2]])[1:lidx[2]] if (length(col) > lidx[2]) col <- col[1:lidx[2]] } names(col) <- idx[[2]] names(xlab) <- idx[[1]] for (ii in idx[[1]]) { x1 <- seq(tmpL[ii,1], tmpH[ii,1], by = 0.001) d1 <- dnorm(x1, mean = x$lambda[ii,1], sd = x$se[ii,1]) plot(x1, d1, type = "l", xlim = xlim, col = col[1], ylim = c(0, max(ylim[ii])), main = main, sub = sub, xlab = xlab[ii], ylab = "Density", lty = lty, lwd = lwd) for (jj in idx[[2]][2:lidx[2]]) { x1 <- seq(tmpL[ii,jj], tmpH[ii,jj], by = 0.001) d1 <- dnorm(x1, mean = x$lambda[ii,jj], sd = x$se[ii,jj]) lines(x1, d1, lty = lty, lwd = lwd, col = col[jj]) } abline(v = 0, col = "grey50") abline(v = 1, col = "grey50") } } if (by == "column") { par(mfrow = c(lidx[2], 1), ...) if (missing(ylim)) { ylim <- apply(dens, 2, max) } if (missing(xlab)) { xlab <- paste("Percentage", unlist(idx[[2]])) } else { if (length(xlab) != lidx[1]) { warning(paste("xlab needs to be", lidx[1], "long")) xlab <- rep(xlab, lidx[2])[1:lidx[2]] } } if (missing(col)) { col <- rainbow(lidx[1]) } else { if (length(col) < lidx[1]) col <- rep(col, idx[[1]])[1:lidx[1]] if (length(col) > lidx[1]) col <- col[1:lidx[1]] } names(col) <- idx[[1]] names(xlab) <- idx[[2]] for (ii in idx[[2]]) { x1 <- seq(tmpL[1,ii], tmpH[1,ii], by = 0.001) d1 <- dnorm(x1, mean = x$lambda[1,ii], sd = x$se[1,ii]) plot(x1, d1, type = "l", xlim = xlim, col = col[1], ylim = c(0, max(ylim[ii])), main = main, sub = sub, xlab = xlab[ii], ylab = "Density", lty = lty, lwd = lwd) for (jj in idx[[1]][2:lidx[1]]) { x1 <- seq(tmpL[jj,ii], tmpH[jj,ii], by = 0.001) d1 <- dnorm(x1, mean = x$lambda[jj,ii], sd = x$se[jj,ii]) lines(x1, d1, lty = lty, lwd = lwd, col = col[jj]) } abline(v = 0, col = "grey50") abline(v = 1, col = "grey50") } } return(invisible(x)) par(readpars) }
LearnerRegrLM = R6Class("LearnerRegrLM", inherit = LearnerRegr, public = list( initialize = function() { ps = ps( df = p_dbl(default = Inf, tags = "predict"), interval = p_fct(c("none", "confidence", "prediction"), tags = "predict"), level = p_dbl(default = 0.95, tags = "predict"), model = p_lgl(default = TRUE, tags = "train"), offset = p_lgl(tags = "train"), pred.var = p_uty(tags = "predict"), qr = p_lgl(default = TRUE, tags = "train"), scale = p_dbl(default = NULL, special_vals = list(NULL), tags = "predict"), singular.ok = p_lgl(default = TRUE, tags = "train"), x = p_lgl(default = FALSE, tags = "train"), y = p_lgl(default = FALSE, tags = "train") ) super$initialize( id = "regr.lm", param_set = ps, predict_types = c("response", "se"), feature_types = c("logical", "integer", "numeric", "factor", "character"), properties = c("weights", "loglik"), packages = c("mlr3learners", "stats"), man = "mlr3learners::mlr_learners_regr.lm" ) }, loglik = function() { extract_loglik(self) } ), private = list( .train = function(task) { pv = self$param_set$get_values(tags = "train") if ("weights" %in% task$properties) { pv = insert_named(pv, list(weights = task$weights$weight)) } invoke(stats::lm, formula = task$formula(), data = task$data(), .args = pv, .opts = opts_default_contrasts) }, .predict = function(task) { pv = self$param_set$get_values(tags = "predict") newdata = ordered_features(task, self) se_fit = self$predict_type == "se" prediction = invoke(predict, object = self$model, newdata = newdata, se.fit = se_fit, .args = pv) if (se_fit) { list(response = unname(prediction$fit), se = unname(prediction$se.fit)) } else { list(response = unname(prediction)) } } ) )
library("aroma.affymetrix") verbose <- Verbose(threshold=-10, timestamp=TRUE) options(width=60) chipType <- "GenomeWideSNP_6" cdfTags <- "Full" fullname <- "Henrik Bengtsson" user <- "HB" email <- getOption(aromaSettings, "user/email") if (is.null(email)) { email <- "[email protected]" } naVersion <- "32" genomeVersion <- "hg19" datestamp <- format(Sys.Date(), format="%Y%m%d") cdf <- AffymetrixCdfFile$byChipType(chipType, tags=cdfTags) rm(csvList) print(cdf) csvList <- list() tagsList <- c( main=sprintf(".na%s", naVersion), cn=sprintf(".cn.na%s", naVersion) ) for (key in names(tagsList)) { tags <- tagsList[[key]] pathname <- AffymetrixNetAffxCsvFile$findByChipType(chipType, tags=tags) if (isFile(pathname)) { csvList[[key]] <- AffymetrixNetAffxCsvFile(pathname) } rm(tags) } print(csvList) tags <- sprintf("na%s,%s,%s%s", naVersion, genomeVersion, user, datestamp) tags <- c("TEST-ONLY", tags) ugp <- AromaUgpFile$allocateFromCdf(cdf, tags=tags, overwrite=TRUE) print(ugp) for (kk in seq_along(csvList)) { csv <- csvList[[kk]] print(csv) units <- importFrom(ugp, csv, verbose=verbose) str(units) } srcFileTags <- list() srcFiles <- c(list(cdf), csvList) for (kk in seq_along(srcFiles)) { srcFile <- srcFiles[[kk]] tags <- list( filename=getFilename(srcFile), filesize=getFileSize(srcFile), checksum=getChecksum(srcFile) ) srcFileTags[[kk]] <- tags } print(srcFileTags) footer <- readFooter(ugp) footer$createdBy <- list( fullname = fullname, email = email ) names(srcFileTags) <- sprintf("srcFile%d", seq_along(srcFileTags)) footer$srcFiles <- srcFileTags writeFooter(ugp, footer) ugp <- AromaUgpFile$byChipType("GenomeWideSNP_6,Full", tags="TEST-ONLY") print(ugp) print(table(ugp[,1], exclude=NULL))
subsetFunc = function(array.in, gname, path) { if (length(dim(array.in)) == 3) { v = array.in[gname, , path] resnames = colnames(array.in[gname, , path, drop = FALSE]) names(v) = resnames } if (length(dim(array.in)) == 2) { v = as.vector(array.in[path, ]) resnames = colnames(array.in) names(v) = resnames } return(v) }
data("academic_awards") academic_awards$zmath <- scale(academic_awards$math) model <- glm(num_awards ~ prog + zmath + prog * zmath, family = "poisson", data = academic_awards) strest <- model$coefficients[c(4,5,6)] strcovmtrx <- vcov(model)[c(4,5,6), c(4,5,6)] constr <- matrix(c(1, 0, 0, 1, 1, 0, 1, 0, 1), nrow = 3, ncol = 3, byrow = TRUE) rhs <- rep(0, 3) nec <- 3 H1 <- gorica:::ormle(est = strest, covmtrx = strcovmtrx, constr = constr, nec = nec, rhs = rhs) H1_char <- "zmath = 0 & zmath + progGeneral:zmath = 0 & zmath + progVocational:zmath =0" parsed_hyp1 <- bain:::parse_hypothesis(names(strest), H1_char) test_that("Parsed H1 correct", { expect_equivalent(constr, parsed_hyp1$hyp_mat[[1]][1:3, 1:3]) expect_equivalent(rhs, parsed_hyp1$hyp_mat[[1]][1:3, 4]) expect_equivalent(nec, parsed_hyp1$n_ec) }) constr <- matrix(c(0, 1, -1, 0, 0, 1), nrow = 2, ncol = 3, byrow = TRUE) rhs <- rep(0, 2) nec <- 0 H2 <- gorica:::ormle(est = strest, covmtrx = strcovmtrx, constr = constr, nec = nec, rhs = rhs) H2_char <- "progGeneral:zmath > progVocational:zmath & progVocational:zmath > 0" parsed_hyp2 <- bain:::parse_hypothesis(names(strest), H2_char) test_that("Parsed H2 correct", { expect_equivalent(constr, parsed_hyp2$hyp_mat[[1]][1:2, 1:3]) expect_equivalent(rhs, parsed_hyp2$hyp_mat[[1]][1:2, 4]) expect_equivalent(nec, parsed_hyp2$n_ec) }) constr <- matrix(c(0, 0, -1), nrow = 1, ncol = 3, byrow = TRUE) rhs <- rep(0, 1) nec <- 0 H3 <- gorica:::ormle(est = strest, covmtrx = strcovmtrx, constr = constr, nec = nec, rhs = rhs) H3_char <- "progVocational:zmath < 0" parsed_hyp3 <- bain:::parse_hypothesis(names(strest), H3_char) test_that("Parsed H3 correct", { expect_equivalent(constr, parsed_hyp3$hyp_mat[[1]][1, 1:3]) expect_equivalent(rhs, parsed_hyp3$hyp_mat[[1]][1, 4]) expect_equivalent(nec, parsed_hyp3$n_ec) }) constr <- matrix(c(rep(0, 3)), nrow = 1, ncol = 3, byrow = TRUE) rhs <- rep(0, 1) nec <- 0 Hu <- gorica:::ormle(est = strest, covmtrx = strcovmtrx, constr = constr, nec = nec, rhs = rhs) set.seed(111) man_gorica <- gorica:::compare_hypotheses.ormle(H1, H2, H3, Hu, iter = 100000) res_gorica <- gorica(model, "zmath = 0 & zmath + progGeneral:zmath = 0 & zmath + progVocational:zmath =0; progGeneral:zmath > progVocational:zmath & progVocational:zmath > 0; progVocational:zmath < 0", iter = 100000) test_that("Manual and package version yield same loglik", { expect_equivalent(man_gorica$comparisons$loglik, res_gorica$fit$loglik, tolerance = .01) }) test_that("Manual and package version yield same penalty", { expect_equivalent(man_gorica$comparisons$penalty, res_gorica$fit$penalty, tolerance = .01) }) test_that("Manual and package version yield same gorica", { expect_equivalent(man_gorica$comparisons$gorica, res_gorica$fit$gorica, tolerance = .01) }) test_that("Manual and package version yield same weights", { expect_equivalent(gorica:::compute_weights(man_gorica$comparisons$gorica), gorica:::compute_weights(res_gorica$fit$gorica), tolerance = .01) })
ping_gh_repo <- function(repo, newline = FALSE) { query <- glue::glue("GET /repos/{repo}") for (iter in seq(1:5)) { result <- try(gh::gh(query), silent = TRUE) if (!is(result, "try-error")) { return(TRUE) } Sys.sleep(1) } if (newline) { cat("\n\n") } usethis::ui_oops(glue::glue( "GitHub repository {usethis::ui_value(repo)} does not exist" )) return(FALSE) } get_gh_license <- function(repo) { query <- glue::glue("GET /repos/{repo}/license") result <- try(gh::gh(query), silent = TRUE) if (is(result, "try-error")) { license <- NA } else { license <- result$license$spdx_id } return(license) }
source("inst/fannie_mae/0_setup.r") fm_with_harp = disk.frame(file.path(outpath, "fm_with_harp")) head(fm_with_harp) nrow(fm_with_harp) system.time(a_wh1 <- fm_with_harp %>% srckeep(c("default_12m","monthly.rpt.prd")) %>% group_by(monthly.rpt.prd) %>% summarise( N = n(), n_defaults = sum(default_12m, na.rm = T)) %>% collect(parallel = T) %>% group_by(monthly.rpt.prd) %>% summarise( odr = sum(n_defaults)/sum(N) ) %>% rename( Date = monthly.rpt.prd, `Observed Default Rate%` = odr )) a_wh2 = a_wh1 %>% gather(key = type, value=rate, -Date) ggplot(a_wh2) + geom_line(aes(x=Date, y = rate, colour = type)) + ggtitle("Fannie Mae Observed Default Rate over time & HARP Conversion Rate")
draw.polygons = function(summary.zeta.scores) { for(current.subset in c("primary","secondary")) { current.cloud = (summary.zeta.scores[grep(current.subset,summary.zeta.scores[,3]),1:2]) current.cloud = as.numeric(as.matrix(current.cloud)) current.cloud = matrix(current.cloud,ncol=2) current.cloud = as.data.frame(current.cloud) colnames(current.cloud) = c("x","y") a1 = current.cloud[current.cloud[,1] == max(current.cloud[,1]),] a1 = a1[a1$y == max(a1$y),] a1 = a1[1,] a2 = current.cloud[current.cloud[,1] == min(current.cloud[,1]),] a2 = a2[a2$y == min(a2$y),] a2 = a2[1,] a.i = a1 a.j = a2 vertexes.of.polygon = a1 for(o in 1: length(current.cloud[,1]) ) { for(m in 1: length(current.cloud[,1]) ) { does.the.point.fit = a.j if(a.i$x == a.j$x) {a.i$x = a.i$x + a.i$x *0.01} steepness = (a.i$y-a.j$y)/((a.i$x-a.j$x) + 0.000001) offset = a.j$y - (steepness * a.j$x) current.line = steepness + offset for(n in 1: length(current.cloud[,1]) ) { current.point = current.cloud[n,] if(current.point$x * steepness + offset > current.point$y + current.point$y * .01) { a.j = current.point break } } if(a.j$y == does.the.point.fit$y && a.j$x == does.the.point.fit$x) { break } } vertexes.of.polygon = rbind(vertexes.of.polygon, a.j) if(a.j$y == a2$y && a.j$x == a2$x) { break } a.i = a.j a.j = a2 } a.i = a2 a.j = a1 for(o in 1: length(current.cloud[,1]) ) { for(m in 1: length(current.cloud[,1]) ) { does.the.point.fit = a.j if(a.i$x == a.j$x) {a.i$x = a.i$x - a.i$x *0.01} steepness = (a.i$y-a.j$y)/((a.i$x-a.j$x) + 0.000001) offset = a.j$y - (steepness * a.j$x) current.line = steepness + offset for(n in 1: length(current.cloud[,1]) ) { current.point = current.cloud[n,] if(current.point$x * steepness + offset < current.point$y - current.point$y * .01) { a.j = current.point break } } if(a.j$y == does.the.point.fit$y && a.j$x == does.the.point.fit$x) { break } } vertexes.of.polygon = rbind(vertexes.of.polygon, a.j) if(a.j$y == a1$y && a.j$x == a1$x) { break } a.i = a.j a.j = a1 } if(current.subset == "primary") { polygon.primary = vertexes.of.polygon } else { polygon.secondary = vertexes.of.polygon } } polygon(polygon.primary,col=rgb(0,0,0,0.1),border=2) polygon(polygon.secondary,col=rgb(0,0,0,0.1),border=3) }
summary.flic <- function(object, ...) { cat("Firth's logistic regression with intercept correction\n\n") summary.logistf(object) }
plot.OKriglistplus <- function(x, digits = 4, which = 1, ...) { zut <- x[c("y", "fitted.values")] class(zut) <- c("OKrig") plot(zut, ...) }
dualpathTall <- function(y, D, Q1, Q2, R, q0, approx=FALSE, maxsteps=2000, minlam=0, rtol=1e-7, btol=1e-7, verbose=FALSE, object=NULL) { if (is.null(object)) { m = nrow(D) n = ncol(D) q = 0 z = Backsolve(R,y,q) uhat = Q1%*%z ihit = which.max(abs(uhat)) hit = abs(uhat[ihit]) s = sign(uhat[ihit]) if (verbose) { cat(sprintf("1. lambda=%.3f, adding coordinate %i, |B|=%i...", hit,ihit,1)) } buf = min(maxsteps,1000) u = matrix(0,m,buf) lams = numeric(buf) h = logical(buf) df = numeric(buf) lams[1] = hit h[1] = TRUE df[1] = q0 u[,1] = uhat r = 1 B = ihit I = Seq(1,m)[-ihit] D1 = D[-ihit,,drop=FALSE] D2 = D[ihit,,drop=FALSE] k = 2 } else { lambda = NULL for (j in 1:length(object)) { if (names(object)[j] != "pathobjs") { assign(names(object)[j], object[[j]]) } } for (j in 1:length(object$pathobjs)) { assign(names(object$pathobjs)[j], object$pathobjs[[j]]) } lams = lambda } tryCatch({ while (k<=maxsteps && lams[k-1]>=minlam) { if (k > length(lams)) { buf = length(lams) lams = c(lams,numeric(buf)) h = c(h,logical(buf)) df = c(df,numeric(buf)) u = cbind(u,matrix(0,m,buf)) } if (h[k-1]) { x = downdateT(Q1,Q2,R,ihit) Q1 = x$Q1 Q2 = x$Q2 R = x$R if (nrow(R)==0) { q = q+1 } else if (nrow(R)==n-q-1) { x = maketri3(y,D1,D2,R,q) y = x$y D1 = x$D1 D2 = x$D2 R = x$R q = q+1 } else if (nrow(R)>=n-q) { d = diag(R[Seq(1,n-q),Seq(q+1,n),drop=FALSE]) if (min(abs(d))<rtol) { i = max(which(abs(d)<rtol)) x = maketri4(y,D1,D2,Q1,Q2,R,q,i) y = x$y D1 = x$D1 D2 = x$D2 Q1 = x$Q1 Q2 = x$Q2 R = x$R q = q+1 } } } else { x = updateT(y,D1,D2,Q1,Q2,R,q,D1[m-r,]) y = x$y D1 = x$D1 D2 = x$D2 Q1 = x$Q1 Q2 = x$Q2 R = x$R if (q==0 || abs(R[1,q])<rtol) { x = maketri4(y,D1,D2,Q1,Q2,R,q,1) y = x$y D1 = x$D1 D2 = x$D2 Q1 = x$Q1 Q2 = x$Q2 R = x$R } else { q = q-1 } } if (r<m && min(abs(diag(R[Seq(1,n-q),Seq(q+1,n),drop=FALSE])))<rtol) { if (verbose) { cat("\n(Recomputing QR factorization, for numerical stability...)") } x = qr(D1[,Seq(q+1,n)]) Q = qr.Q(x,complete=TRUE) Q1 = Q[,Seq(1,min(n,m-r)),drop=FALSE] Q2 = Q[,Seq(min(n,m-r)+1,m-r),drop=FALSE] R = qr.R(x,complete=TRUE) R = cbind(matrix(0,min(n,m-r),q),R[Seq(1,min(n,m-r)),]) } Ds = t(D2)%*%s if (r==m) { a = b = numeric(0) hit = 0 } else { z = Backsolve(R,y,q) a = Q1%*%z z = Backsolve(R,Ds,q) b = Q1%*%z shits = Sign(a) hits = a/(b+shits) hits[hits>lams[k-1]+btol] = 0 hits[hits>lams[k-1]] = lams[k-1] ihit = which.max(hits) hit = hits[ihit] shit = shits[ihit] } if (r==0 || approx) { leave = 0 } else { if (nrow(R)>=n-q) { c = d = leaves = rep(0,r) } else { c = s*(D2%*%(y-t(D1)%*%a)) d = s*(D2%*%(Ds-t(D1)%*%b)) leaves = c/d leaves[c>=0] = 0 } leaves[leaves>lams[k-1]+btol] = 0 leaves[leaves>lams[k-1]] = lams[k-1] ileave = which.max(leaves) leave = leaves[ileave] } if (hit<=0 && leave<=0) break if (hit > leave) { lams[k] = hit h[k] = TRUE df[k] = q0+q uhat = numeric(m) uhat[B] = hit*s uhat[I] = a-hit*b u[,k] = uhat r = r+1 B = c(B,I[ihit]) I = I[-ihit] s = c(s,shit) D2 = rbind(D2,D1[ihit,]) D1 = D1[-ihit,,drop=FALSE] if (verbose) { cat(sprintf("\n%i. lambda=%.3f, adding coordinate %i, |B|=%i...", k,hit,B[r],r)) } } else { lams[k] = leave h[k] = FALSE df[k] = q0+q uhat = numeric(m) uhat[B] = leave*s uhat[I] = a-leave*b u[,k] = uhat r = r-1 I = c(I,B[ileave]) B = B[-ileave] s = s[-ileave] D1 = rbind(D1,D2[ileave,]) D2 = D2[-ileave,,drop=FALSE] if (verbose) { cat(sprintf("\n%i. lambda=%.3f, deleting coordinate %i, |B|=%i...", k,leave,I[m-r],r)) } } k = k+1 } }, error = function(err) { err$message = paste(err$message,"\n(Path computation has been terminated;", " partial path is being returned.)",sep="") warning(err)}) lams = lams[Seq(1,k-1)] h = h[Seq(1,k-1)] df = df[Seq(1,k-1),drop=FALSE] u = u[,Seq(1,k-1),drop=FALSE] pathobjs = list(type="tall", r=r, B=B, I=I, Q1=Q1, approx=approx, Q2=Q2, k=k, df=df, D1=D1, D2=D2, ihit=ihit, m=m, n=n, q=q, h=h, R=R, q0=q0, rtol=rtol, btol=btol, s=s, y=y) if (k>maxsteps) { if (verbose) { cat(sprintf("\nReached the maximum number of steps (%i),",maxsteps)) cat(" skipping the rest of the path.") } completepath = FALSE } else if (lams[k-1]<minlam) { if (verbose) { cat(sprintf("\nReached the minimum lambda (%.3f),",minlam)) cat(" skipping the rest of the path.") } completepath = FALSE } else completepath = TRUE if (verbose) cat("\n") colnames(u) = as.character(round(lams,3)) return(list(lambda=lams,beta=NA,fit=NA,u=u,hit=h,df=df,y=NA, completepath=completepath,bls=NA,pathobjs=pathobjs)) }
povcalnet_wb <- function(povline = 1.9, year = "all", url = "http://iresearch.worldbank.org", format = "csv") { query <- paste0("GroupedBy=WB&YearSelected=", year, "&PovertyLine=", povline, "&Countries=all&format=", format) url <- httr::modify_url(url, path = api_handle(), query = query) res <- httr::GET(url = url) res <- httr::content(res, as = "text", encoding = "UTF-8" ) if (res == "") { out <- handle_empty_response(res, aggregate = TRUE) } else { if (format == "json") { out <- tibble::as_tibble(jsonlite::fromJSON(res, simplifyDataFrame = TRUE)) out <- out$PovResult } else { out <- readr::read_csv(res) } } out <- format_data(out, coverage = "all", aggregate = TRUE) return(out) }
ediff <- function(x, lag=1, differences=1, pad=c("head","tail","symmetric"), pad.value = NA, frontPad, ...) { pad <- match.arg(pad) res <- diff(x, lag=lag, difference=differences, ...) p1 <- max(ceiling(lag*differences / 2), ceiling(nrow(x) / 2)) p2 <- max(floor(lag*differences / 2), floor(nrow(x) / 2)) if (p1 != p2 && pad == "symmetric") { warning("padding not quite symmetric since lag * differences is odd") } if (is.matrix(res)) { pad1 <- matrix(pad.value, nrow=p1, ncol=ncol(res)) pad1 <- matrix(pad.value, nrow=p2, ncol=ncol(res)) FUN <- rbind } else { pad1 <- rep(pad.value, p1) pad2 <- rep(pad.value, p2) FUN <- c } res <- switch(pad, head = FUN(pad1, pad2, res), tail = FUN(res, pad1, pad2), symmetric = FUN(pad1, res, pad2) ) res }
SparamG.S <- function(X,y,delta,N,q,sigma0,MAXIT,TOL,ialg=3,seed=153) { X <- as.matrix(X); n <- length(y); p <- ncol(X); b <- 0.5 zbet <- BtamatG(X,y,delta,N,q,MAXIT,TOL,seed=seed) beta <- zbet$beta gamok <- 0 s0 <- 1 kappa <- 9.E9 smink <- 9.E9 mes2 <- integer(4) cat(".") flush.console() now <- Sys.time() now <- now+6 for (j in 1:N) { betj <- matrix(beta[j,],nrow=N,ncol=p,byrow=TRUE) if (gamok==0) { gamj <- sweep(beta,2,beta[j,]) nu <- apply(gamj,1,Nrm2)} betgamj <- betj B <- (1:N)[nu <= kappa] ni <- length(B) if (ni==0) next betgamb <- betgamj[B,] tmp <- s.eq.Gauss(X,y,ni,delta,sigma0,b,betgamb,MAXIT,TOL,s0=s0, ipsi=4,xk=1.5477,lint=1,ialg=ialg,meth=4) sj <- tmp$S mes2 <- mes2+tmp$mes2 Sj <- rep(100000,N) gamjb <- gamj[B,] betjb <- betj[B,] tmp <- S.eq.Gauss(X,y,ni,delta,sj,sigma0,b,betjb,gamjb,MAXIT,TOL, ipsi=4,xk=1.5477,lint=1,ialg=ialg) Sj[B] <- tmp$S mes2 <- mes2+tmp$mes2 omega <- min(Sj) kStar <- (1:N)[Sj==omega] numin <- nu[kStar] nustar <- min(numin) kstar <- (kStar)[numin==nustar] if (abs(nustar-kappa)<1e-6 & omega>smink) next Bbar <- setdiff(1:N,B) truemin <- 1 if (length(Bbar)>0) for (k in Bbar) { tmp <- s.eq.Gauss(X,y,1,delta,sigma0,b,betgamj[k,],MAXIT,TOL,s0=s0, ipsi=4,xk=1.5477,lint=1,ialg=ialg,meth=4) sk <- tmp$S; mes2 <- mes2+tmp$mes2 tmp <- S.eq.Gauss(X,y,1,delta,sk,sigma0,b,betj[k,],gamj[k,],MAXIT,TOL, ipsi=4,xk=1.5477,lint=1,ialg=ialg) tst <- tmp$S; mes2 <- mes2+tmp$mes2 if (tst < omega) {truemin <- 0; break} } if (truemin==1) { smink <- omega Jstar <- j Kstar <- kstar ind <- match(kstar,B,nomatch=0) Smin <- sj[ind] smin <- Sj[kstar] gamin <- gamj kappa <- nustar } if (Sys.time() >= now) {cat("."); flush.console(); now <- now+6} } cat("\n"); flush.console() cmes2 <- c(as.character(mes2)," ") Smin <- Smin[1] Eqexit <- paste(c("Normal (","Nit=Maxit (","f(a)*f(b)>0 (","|f(a)-f(b)|<tl ("," "), cmes2,sep="",collapse=") ") Bmin0 <- beta[Jstar,] Smin0 <- Smin zres <- list(Bmin=Bmin0,Smin=Smin0,smin=smin,beta=beta,gama=gamin,kappa=kappa, Jstar=Jstar,Kstar=Kstar,Eqexit=Eqexit) zres}
library(lgpr) context("Inverse-gamma distribution") test_that("inverse gamma density works and errors correctly", { a <- 2 b <- 3 diff <- abs(dinvgamma_stanlike(1, a, b) - 0.4480836) expect_lt(diff, 1e-6) expect_error(dinvgamma_stanlike(1, -1, 2)) expect_error(dinvgamma_stanlike(1, 2, -1)) }) test_that("inverse gamma quantile works and errors correctly", { a <- 2 b <- 3 diff <- abs(qinvgamma_stanlike(0.9, a, b) - 5.641095) expect_lt(diff, 1e-6) expect_error(qinvgamma_stanlike(0.9, -1, 2)) expect_error(qinvgamma_stanlike(0.9, 2, -1)) expect_error(qinvgamma_stanlike(-0.1, 2, 2)) expect_error(qinvgamma_stanlike(1.5, 2, 2)) }) test_that("plotting the inverse gamma distribution works", { a <- 2 b <- 3 p1 <- plot_invgamma(a, b) p2 <- plot_invgamma(a, b, return_quantiles = TRUE) c1 <- as.character(class(p1)) c2 <- as.character(class(p2$plot)) expect_equal(c1, c("gg", "ggplot")) expect_equal(c2, c("gg", "ggplot")) expect_error(plot_invgamma(a, b, IQR = 1.5)) })
curvesegslope <- function(curve.fpr,curve.tpr){ curve.segslope=c() for (i in 1:(dim(curve.fpr)-1)) { if (curve.fpr[i]!=curve.fpr[i+1]) curve.segslope[i]=(curve.tpr[i]-curve.tpr[i+1])/(curve.fpr[i]-curve.fpr[i+1]) else curve.segslope[i]=-Inf } return(curve.segslope) }
timestamp <- Sys.time() library(caret) library(plyr) library(recipes) library(dplyr) model <- "sdwd" set.seed(1) training <- twoClassSim(50, linearVars = 2) testing <- twoClassSim(500, linearVars = 2) trainX <- training[, -ncol(training)] trainY <- training$Class rec_cls <- recipe(Class ~ ., data = training) %>% step_center(all_predictors()) %>% step_scale(all_predictors()) cctrl1 <- trainControl(method = "cv", number = 3, returnResamp = "all", classProbs = TRUE, summaryFunction = twoClassSummary) cctrl2 <- trainControl(method = "LOOCV", classProbs = TRUE, summaryFunction = twoClassSummary) cctrl3 <- trainControl(method = "none", classProbs = TRUE, summaryFunction = twoClassSummary) cctrlR <- trainControl(method = "cv", number = 3, returnResamp = "all", search = "random") set.seed(849) test_class_cv_model <- train(trainX, trainY, method = "sdwd", trControl = cctrl1, metric = "ROC", preProc = c("center", "scale")) set.seed(849) test_class_cv_form <- train(Class ~ ., data = training, method = "sdwd", trControl = cctrl1, metric = "ROC", preProc = c("center", "scale")) test_class_pred <- predict(test_class_cv_model, testing[, -ncol(testing)]) test_class_prob <- predict(test_class_cv_model, testing[, -ncol(testing)], type = "prob") test_class_pred_form <- predict(test_class_cv_form, testing[, -ncol(testing)]) test_class_prob_form <- predict(test_class_cv_form, testing[, -ncol(testing)], type = "prob") set.seed(849) test_class_rand <- train(trainX, trainY, method = "sdwd", trControl = cctrlR, tuneLength = 4, preProc = c("center", "scale")) set.seed(849) test_class_loo_model <- train(trainX, trainY, method = "sdwd", trControl = cctrl2, metric = "ROC", preProc = c("center", "scale")) set.seed(849) test_class_none_model <- train(trainX, trainY, method = "sdwd", trControl = cctrl3, tuneGrid = test_class_cv_model$bestTune, metric = "ROC", preProc = c("center", "scale")) test_class_none_pred <- predict(test_class_none_model, testing[, -ncol(testing)]) test_class_none_prob <- predict(test_class_none_model, testing[, -ncol(testing)], type = "prob") set.seed(849) test_class_rec <- train(x = rec_cls, data = training, method = "sdwd", trControl = cctrl1, metric = "ROC") if( !isTRUE( all.equal(test_class_cv_model$results, test_class_rec$results)) ) stop("CV weights not giving the same results") test_class_imp_rec <- varImp(test_class_rec) test_class_pred_rec <- predict(test_class_rec, testing[, -ncol(testing)]) test_class_prob_rec <- predict(test_class_rec, testing[, -ncol(testing)], type = "prob") test_levels <- levels(test_class_cv_model) if(!all(levels(trainY) %in% test_levels)) cat("wrong levels") test_class_predictors1 <- predictors(test_class_cv_model) tests <- grep("test_", ls(), fixed = TRUE, value = TRUE) sInfo <- sessionInfo() timestamp_end <- Sys.time() save(list = c(tests, "sInfo", "timestamp", "timestamp_end"), file = file.path(getwd(), paste(model, ".RData", sep = ""))) if(!interactive()) q("no")
xewma.ad <- function(l, c, mu1, mu0=0, zr=0, z0=0, sided="one", limits="fix", steady.state.mode="conditional", r=40) { if ( l<=0 || l>1 ) stop("l has to be between 0 and 1") if ( c<=0 ) warning("usually, c has to be positive") if ( zr>c & sided=="one" ) stop("wrong reflexion border") if ( r<4 ) stop("r is too small") ctyp <- pmatch(sided, c("one", "two")) - 1 if (is.na(ctyp)) stop("invalid ewma type") ltyp <- pmatch(limits, c("fix","vacl","fir","both","Steiner","stat")) - 1 if ( is.na(ltyp) ) stop("invalid limits type") if ( (sided=="one") & !(limits %in% c("fix", "vacl", "stat")) ) stop("not supported for one-sided EWMA (not reasonable or not implemented yet") styp <- pmatch(steady.state.mode, c("conditional", "cyclical")) - 1 if (is.na(styp)) stop("invalid steady.state.mode") if ( abs(z0) > abs(c) ) stop("wrong restarting value") ad <- .C("xewma_ad", as.integer(ctyp), as.double(l), as.double(c), as.double(zr), as.double(mu0), as.double(mu1), as.double(z0), as.integer(ltyp), as.integer(styp), as.integer(r), ans=double(length=1), PACKAGE="spc")$ans names(ad) <- "ad" return (ad) }
context("updateParVals") test_that("updateParVals works", { pa = list(a = 1, b = 2, d = 4, e = 5) pb = list(a = 0, c = 3) ps = makeParamSet( makeIntegerParam("a"), makeIntegerParam("b", requires = quote(a == 1)), makeIntegerParam("c"), makeIntegerParam("d"), makeIntegerParam("e", requires = quote(f == TRUE)), makeLogicalParam("f", default = TRUE)) pc = updateParVals(ps, pa, pb) expect_equal(pc, list(a = 0, c = 3, d = 4, e = 5)) expect_warning(updateParVals(ps, pa, pb, warn = TRUE), "ParamSetting b=2") pb2 = list(a = 0, f = FALSE) pc2 = updateParVals(ps, pa, pb2) expect_equal(pc2, list(a = 0, f = FALSE, d = 4)) expect_equal(updateParVals(ps, pa, list()), pa) expect_equal(updateParVals(ps, list(), pb), pb) pa = list(a = 1, b = 2, c = 0.5, d = 4) pb = list(a = -3) ps = makeParamSet( makeIntegerParam("a", requires = quote(e == TRUE)), makeIntegerParam("b", requires = quote(a == 1)), makeNumericParam("c"), makeIntegerParam("d", requires = quote(b == 2)), makeLogicalParam("e", default = TRUE)) pc = updateParVals(ps, pa, pb) expect_equal(pc, list(a = -3, c = 0.5)) ps = makeParamSet( makeIntegerParam("a", default = 1L, requires = quote(b == 2)), makeIntegerParam("b", default = 2L, requires = quote(c == TRUE)), makeLogicalParam("c", default = TRUE)) pa = list(a = 1, b = 2, c = TRUE) pb = list(b = 3) pc = updateParVals(ps, pa, pb) expect_equal(pc, list(b = 3, c = TRUE)) })
pkm <- function(formula_p, formula_k = NULL, data, obsCol = NULL, kFixed = NULL, allCombos = FALSE, sizeCol = NULL, CL = 0.90, kInit = 0.7, quiet = FALSE, ...){ if (!is.null(kFixed) && !is.numeric(kFixed)) stop("kFixed must be NULL or numeric") if (any(na.omit(kFixed) < 0 | na.omit(kFixed) > 1)){ badk <- names(which(na.omit(kFixed) < 0 | na.omit(kFixed) > 1)) stop("invalid k for ", paste0(badk, collapse = ", ")) } if (is.null(allCombos) || is.na(allCombos) || !is.logical(allCombos)){ stop("allCombos must be TRUE or FALSE") } if (is.null(sizeCol) || is.na(sizeCol)){ if (!allCombos){ out <- pkm0(formula_p = formula_p, formula_k = formula_k, data = data, obsCol = obsCol, kFixed = kFixed, CL = CL, kInit = kInit, quiet = quiet) } else { out <- pkmSet(formula_p = formula_p, formula_k = formula_k, data = data, obsCol = obsCol, kFixed = kFixed, kInit = kInit, CL = CL, quiet = quiet) } } else { out <- pkmSize(formula_p = formula_p, formula_k = formula_k, data = data, obsCol = obsCol, kFixed = kFixed, sizeCol = sizeCol, allCombos = allCombos, CL = CL, kInit = kInit, quiet = quiet) } return(out) } pkm0 <- function(formula_p, formula_k = NULL, data, obsCol = NULL, kFixed = NULL, kInit = 0.7, CL = 0.90, quiet = FALSE){ i <- sapply(data, is.factor) data[i] <- lapply(data[i], as.character) if (!is.null(kFixed) && is.na(kFixed)) kFixed <- NULL if (!is.null(kFixed) && !is.numeric(kFixed)) stop("kFixed must be NULL or numeric") if (!is.null(kFixed) && (kFixed < 0 | kFixed > 1)){ stop("invalid fixed value for k") } if(any(! obsCol %in% colnames(data))){ stop("Observation column provided not in data.") } if (length(obsCol) == 0){ obsCol <- grep("^[sS].*[0-9]$", names(data), value = TRUE) nobsCol <- length(obsCol) if (nobsCol == 0){ stop("No obsCol provided and no appropriate column names found.") } } predCheck <- c(all.vars(formula_p[[3]]), all.vars(formula_k[[3]])) if (any(!(predCheck %in% colnames(data)))){ stop("User-supplied formula includes predictor(s) not found in data.") } if (length(kFixed) >= 1){ if (!is.numeric(kFixed[1])){ stop("User-supplied kFixed must be numeric (or NULL)") } if (length(kFixed) > 1){ kFixed <- kFixed[1] if (!quiet){ message("Vector-valued kFixed. Only the first element will be used.") } } if (kFixed < 0 || kFixed > 1){ stop("User-supplied kFixed is outside the supported range [0, 1].") } if (length(formula_k) > 0 & quiet == FALSE){ message("Formula and fixed value provided for k, fixed value used.") formula_k <- NULL } } pOnly <- FALSE if (is.null(kFixed)){ if (length(obsCol) == 1){ if (!is.null(formula_k) && is.language(formula_k) && quiet == FALSE){ message("Only one search occasion per carcass. k not estimated.") } pOnly <- TRUE formula_k <- NULL kFixed <- 1 } else { if(is.null(formula_k) || !is.language(formula_k)){ pOnly <- TRUE obsCol <- obsCol[1] message("p is estimated from data in first search occasion only.") formula_k <- NULL kFixed <- 1 } } } nsearch <- length(obsCol) if (ncol(data) == nsearch) data$id <- 1:nrow(data) obsData <- as.matrix(data[ , obsCol], ncol = nsearch) if (!is.numeric(obsData)){ obsData[!is.na(obsData) & !(obsData %in% as.character(0:1))] <- NA obsData <- matrix(as.numeric(obsData), ncol = nsearch) } else { obsData[!(obsData %in% 0:1)] <- NA } onlyNA <- (rowSums(is.na(obsData)) == nsearch) obsData <- as.matrix(obsData[!onlyNA, ], ncol = nsearch) data00 <- data[!onlyNA, ] data0 <- data00 ncarc <- nrow(obsData) preds_p <- all.vars(formula_p[[3]]) formulaRHS_p <- formula(delete.response(terms(formula_p))) levels_p <- .getXlevels(terms(formulaRHS_p), data0) preds_k <- character(0) if (is.language(formula_k)){ preds_k <- all.vars(formula_k[[3]]) formulaRHS_k <- formula(delete.response(terms(formula_k))) levels_k <- .getXlevels(terms(formulaRHS_k), data0) } if (length(kFixed) == 1){ preds_k <- character(0) formulaRHS_k <- formula(~1) formula_k <- c(fixedk = kFixed) levels_k <- .getXlevels(terms(formulaRHS_k), data0) } preds <- unique(c(preds_p, preds_k)) for (pri in preds) if (is.numeric(data0[ , pri])) data0[ , pri] <- paste0("_", data0[ , pri]) cells <- combinePreds(preds, data0) ncell <- nrow(cells) cellNames <- cells$CellNames cellMM_p <- model.matrix(formulaRHS_p, cells) cellMM_k <- model.matrix(formulaRHS_k, cells) cellMM <- cbind(cellMM_p, cellMM_k) if (length(preds) == 0){ carcCells0 <- rep("all", ncarc) } else if (length(preds) == 1){ carcCells0 <- data0[ , preds] } else if (length(preds) > 1){ carcCells0 <- do.call(paste, c(data0[ , preds], sep = '.')) } pInitCellMean <- tapply(data0[ , obsCol[1]], INDEX = carcCells0, FUN = mean, na.rm = TRUE) fixBadCells <- NULL if (NCOL(cellMM_p) == prod(unlist(lapply(levels_p, length))) & any(pInitCellMean %in% 0:1)){ if (length(preds_p) == 0){ if (all(data0[ , obsCol[1]] == 1) || all(data0[ , obsCol[1]] == 0)){ data0 <- rbind(data0, data0) data0[1, obsCol[1]] <- 1 - data0[1, obsCol[1]] if (length(obsCol) > 1 && data0[1, obsCol[1]] == 1){ data0[1, obsCol[-1]] <- NA } fixBadCells <- "all" } } else { fixBadCells <- names(pInitCellMean)[pInitCellMean %in% 0:1] badCells <- cells[cells$CellNames %in% fixBadCells, ] badCells$CellNames <- NULL for (ci in 1:NROW(badCells)){ cellind <- which(matrixStats::colProds( t(data0[ , colnames(badCells)]) == as.character(badCells[ci, ])) == 1) data0 <- rbind(data0[cellind, ], data0) data0[1, obsCol[1]] <- 1 - data0[1, obsCol[1]] if (data0[1, obsCol[1]] == 1 & length(obsCol) > 1){ data0[1, obsCol[-1]] <- NA } } } } else if (length(preds_p) == 2 & NCOL(cellMM_p) < prod(unlist(lapply(levels_p, length)))){ for (predi in names(levels_p)){ for (li in levels_p[[predi]]){ cellind <- which(data0[ , predi] == li) if (all(data0[cellind, obsCol[1]] == 0) | all(data0[cellind, obsCol[1]] == 1)) stop("Initial search has all 0s or 1s for ", preds_p[1], " = ", li, " in additive model.") } } } obsData <- as.matrix(data0[ , obsCol]) colnames(obsData) <- obsCol misses <- matrixStats::rowCounts(obsData, value = 0, na.rm =T) foundOn <- matrixStats::rowMaxs( obsData * matrixStats::rowCumsums(1 * !is.na(obsData)), na.rm = T) dataMM_p <- model.matrix(formulaRHS_p, data0) dataMM_k <- model.matrix(formulaRHS_k, data0) dataMM <- t(cbind(dataMM_p, dataMM_k)) nbeta_k <- ncol(dataMM_k) nbeta_p <- ncol(dataMM_p) nbeta <- nbeta_p + nbeta_k if (length(preds) == 0){ carcCells <- rep("all", dim(data0)[1]) } else if (length(preds) == 1){ carcCells <- data0[ , preds] } else if (length(preds) > 1){ carcCells <- do.call(paste, c(data0[ , preds], sep = '.')) } cellByCarc <- match(carcCells, cellNames) pInitCellMean <- tapply(data0[ , obsCol[1]], INDEX = carcCells, FUN = mean, na.rm = TRUE) pInit <- as.vector(pInitCellMean[match(carcCells, names(pInitCellMean))]) pInit[which(pInit < 0.1)] <- 0.1 pInit[which(pInit > 0.9)] <- 0.9 cellMatrix_p <- solve(t(dataMM_p) %*% dataMM_p) cellImpact_p <- t(dataMM_p) %*% logit(pInit) betaInit_p <- cellMatrix_p %*% cellImpact_p betaInit_k <- logit(rep(kInit, nbeta_k)) betaInit <- c(betaInit_p, betaInit_k) if (length(kFixed) == 1){ betaInit <- betaInit[-length(betaInit)] } for (ki in 1:3){ MLE <- tryCatch( optim(par = betaInit, fn = pkLogLik, hessian = TRUE, cellByCarc = cellByCarc, misses = misses, maxmisses = max(misses), foundOn = foundOn, cellMM = cellMM, nbeta_p = nbeta_p, kFixed = kFixed, method = "BFGS"), error = function(x) {NA} ) if (length(MLE) == 1 && is.na(MLE)) stop("Failed optimization.") varbeta <- tryCatch(solve(MLE$hessian), error = function(x) {NA}) if (is.na(varbeta)[1]) stop("Unable to estimate variance.") if (sum(diag(varbeta) < 0) > 0) { if (ki == 1) { betaInit_k <- logit(rep(0.05, nbeta_k)) betaInit <- c(betaInit_p, betaInit_k) } else if (ki == 2) { betaInit_k <- logit(rep(0.95, nbeta_k)) betaInit <- c(betaInit_p, betaInit_k) } else { stop("Unable to estimate k") } } else { break } } convergence <- MLE$convergence betahat <- MLE$par if (is.null(fixBadCells)){ llik <- -MLE$value } else { obsData <- as.matrix(data00[ , obsCol]) colnames(obsData) <- obsCol misses <- matrixStats::rowCounts(obsData, value = 0, na.rm =T) foundOn <- matrixStats::rowMaxs( obsData * matrixStats::rowCumsums(1 * !is.na(obsData)), na.rm = T) if (length(preds) == 0){ carcCells <- rep("all", dim(data00)[1]) } else if (length(preds) == 1){ carcCells <- data00[ , preds] } else if (length(preds) > 1){ carcCells <- do.call(paste, c(data00[ , preds], sep = '.')) } cellByCarc <- match(carcCells, cellNames) llik <- -pkLogLik(misses = misses, foundOn = foundOn, beta = betahat, nbeta_p = nbeta_p, cellByCarc = cellByCarc, maxmisses = max(misses), cellMM = cellMM, kFixed = kFixed) ncarc <- nrow(obsData) } nparam <- length(betahat) AIC <- 2*nparam - 2*llik AICcOffset <- (2 * nparam * (nparam + 1)) / (nrow(obsData) - nparam - 1) AICc <- round(AIC + AICcOffset, 2) AIC <- round(AIC, 2) betahat_p <- betahat[1:nbeta_p] names(betahat_p) <- colnames(dataMM_p) betahat_k <- NULL if (length(kFixed) == 0){ betahat_k <- betahat[(nbeta_p + 1):(nbeta)] names(betahat_k) <- colnames(dataMM_k) } varbeta_p <- varbeta[1:nbeta_p, 1:nbeta_p] cellMean_p <- cellMM_p %*% betahat_p cellVar_p <- cellMM_p %*% varbeta_p %*% t(cellMM_p) cellSD_p <- suppressWarnings(sqrt(diag(cellVar_p))) if (is.null(kFixed) || is.na(kFixed)){ which_k <- (nbeta_p + 1):(nbeta) varbeta_k <- varbeta[which_k, which_k] cellMean_k <- cellMM_k %*% betahat_k cellVar_k <- cellMM_k %*% varbeta_k %*% t(cellMM_k) cellSD_k <- suppressWarnings(sqrt(diag(cellVar_k))) } else { cellMean_k <- rep(logit(kFixed), ncell) cellSD_k <- rep(0, ncell) } probs <- list(0.5, (1 - CL) / 2, 1 - (1 - CL) / 2) cellTable_p <- lapply(probs, qnorm, mean = cellMean_p, sd = cellSD_p) cellTable_p <- matrix(unlist(cellTable_p), ncol = 3) cellTable_p <- round(alogit(cellTable_p), 6) colnames(cellTable_p) <- c("p_median", "p_lwr", "p_upr") cell_n <- as.numeric(table(carcCells0)[cellNames]) names(cell_n) <- NULL if (!pOnly){ cellTable_k <- lapply(probs, qnorm, mean = cellMean_k, sd = cellSD_k) cellTable_k <- matrix(unlist(cellTable_k), nrow = ncell, ncol = 3) cellTable_k <- round(alogit(cellTable_k), 6) colnames(cellTable_k) <- c("k_median", "k_lwr", "k_upr") cellTable <- data.frame( cell = cellNames, n = cell_n, cellTable_p, cellTable_k) } else { cellTable <- data.frame(cell = cellNames, n = cell_n, cellTable_p) } output <- list() output$call <- match.call() output$data <- data output$data0 <- data00 output$formula_p <- formula_p if (!pOnly) output$formula_k <- formula_k output$predictors <- preds output$predictors_p <- preds_p if (!pOnly) output$predictors_k <- preds_k output$AIC <- AIC output$AICc <- AICc output$convergence <- convergence output$varbeta <- varbeta output$cellMM_p <- cellMM_p if (!pOnly) output$cellMM_k <- cellMM_k output$nbeta_p <- nbeta_p if (!pOnly) output$nbeta_k <- nbeta_k output$betahat_p <- betahat_p if (!pOnly) output$betahat_k <- betahat_k output$levels_p <- levels_p if (!pOnly) output$levels_k <- levels_k output$cells <- cells output$ncell <- ncell output$cell_pk <- cellTable output$CL <- CL output$observations <- obsData if (!pOnly) output$kFixed <- kFixed output$carcCells <- carcCells output$loglik <- llik output$pOnly <- pOnly if (is.null(fixBadCells)) data_adj <- NULL output$data_adj <- data0 output$fixBadCells <- fixBadCells class(output) <- c("pkm", "list") attr(output, "hidden") <- c("data", "data0", "predictors_p", "predictors_k", "kFixed", "betahat_p", "betahat_k", "cellMM_p", "cellMM_k", "nbeta_p", "nbeta_k", "varbeta", "levels_p", "levels_k", "carcCells", "AIC", "cells", "ncell", "observations", "loglik", "pOnly", "data_adj", "fixBadCells") return(output) } print.pkm <- function(x, ...){ hid <- attr(x, "hidden") notHid <- !names(x) %in% hid print(x[notHid]) } pkLogLik <- function(misses, foundOn, beta, nbeta_p, cellByCarc, maxmisses, cellMM, kFixed = NULL){ if (!is.null(kFixed) && is.na(kFixed)) kFixed <- NULL if (length(kFixed) == 1){ beta <- c(beta, logit(kFixed)) } ncell <- nrow(cellMM) nbeta <- length(beta) which_p <- 1:nbeta_p which_k <- (nbeta_p + 1):nbeta beta_p <- beta[which_p] beta_k <- beta[which_k] Beta <- matrix(0, nrow = nbeta, ncol = 2) Beta[which_p, 1] <- beta[which_p] Beta[which_k, 2] <- beta[which_k] pk <- alogit(cellMM %*% Beta) p <- pk[ , 1] k <- pk[ , 2] powk <- matrix(k, nrow = ncell, ncol = maxmisses + 1) powk[ , 1] <- 1 powk <- matrixStats::rowCumprods(powk) pmiss <- matrix(1 - (p * powk[ , 1:(maxmisses + 1)]), nrow = ncell) pmiss <- matrixStats::rowCumprods(pmiss) pfind <- matrixStats::rowDiffs(1 - pmiss) pfind_si <- cbind(pk[ , 1], pfind) notFoundCell <- cellByCarc[foundOn == 0] notFoundMisses <- misses[foundOn == 0] notFoundCellMisses <- cbind(notFoundCell, notFoundMisses) foundCell <- cellByCarc[foundOn > 0] foundFoundOn <- foundOn[foundOn > 0] foundCellFoundOn <- cbind(foundCell, foundFoundOn) ll_miss <- sum(log(pmiss[notFoundCellMisses])) ll_found <- sum(log(pfind_si[foundCellFoundOn])) nll_total <- -(ll_miss + ll_found) return(nll_total) } pkmSet <- function(formula_p, formula_k = NULL, data, obsCol = NULL, kFixed = NULL, kInit = 0.7, CL = 0.90, quiet = FALSE){ if (!is.null(kFixed) && is.na(kFixed)) kFixed <- NULL if (length(kFixed) > 0){ if (length(kFixed) > 1){ warning( "More than one fixed kFixed value provided by user. ", "Only the first element will be used." ) kFixed <- kFixed[1] } if (is.numeric(kFixed) && !is.na(kFixed) && length(formula_k) > 0){ if(quiet == FALSE){ message("Formula and fixed value provided for k, fixed value used.") } formula_k <- NULL } } if (sum(obsCol %in% colnames(data)) == 1 & length(formula_k) > 0){ if (quiet == FALSE){ message("Only one search occasion for each carcass; k not estimated.") } formula_k <- NULL } unfixk <- FALSE if (length(formula_k) == 0){ if (length(kFixed) == 0){ kFixed <- 0.5 unfixk <- TRUE } } terms_p <- attr(terms(formula_p), "term.labels") if (length(formula_k) == 0){ terms_k <- NULL } else { terms_k <- attr(terms(formula_k), "term.labels") } nterms_p <- length(terms_p) nterms_k <- length(terms_k) nformula_p <- 2^(nterms_p) nformula_k <- 2^(nterms_k) dropComplex_p <- rep(1:nterms_p, choose(nterms_p, 1:nterms_p)) dropWhich_p <- numeric(0) if (nterms_p > 0){ for (termi in 1:nterms_p){ specificDrop <- seq(1, choose(nterms_p, (1:nterms_p)[termi])) dropWhich_p <- c(dropWhich_p, specificDrop) } } optionFormula_p <- vector("list", nformula_p) optionFormula_p[[1]] <- formula_p keepFormula_p <- rep(TRUE, nformula_p) if (nformula_p > 1){ for (formi in 2:nformula_p){ termDropComplex <- combn(terms_p, dropComplex_p[formi - 1]) termDropSpec <- termDropComplex[ , dropWhich_p[formi - 1]] termDrop <- paste(termDropSpec, collapse = " - ") formulaUpdate <- paste(format(~.), "-", termDrop) updatedFormula <- update.formula(formula_p, formulaUpdate) optionFormula_p[[formi]] <- updatedFormula keepFormula_p[formi] <- checkComponents(updatedFormula) } nkeepFormula_p <- sum(keepFormula_p) whichKeepFormula_p <- which(keepFormula_p == TRUE) keptFormula_p <- vector("list", nkeepFormula_p) for (kepti in 1:nkeepFormula_p){ keptFormula_p[[kepti]] <- optionFormula_p[[whichKeepFormula_p[kepti]]] } } else { keptFormula_p <- optionFormula_p } dropComplex_k <- rep(1:nterms_k, choose(nterms_k, 1:nterms_k)) dropWhich_k <- numeric(0) if (nterms_k > 0){ for (termi in 1:nterms_k){ specificDrop <- seq(1, choose(nterms_k, (1:nterms_k)[termi])) dropWhich_k <- c(dropWhich_k, specificDrop) } } optionFormula_k <- vector("list", nformula_k) optionFormula_k[[1]] <- formula_k keepFormula_k <- rep(TRUE, nformula_k) if (nformula_k > 1){ for (formi in 2:nformula_k){ termDropComplex <- combn(terms_k, dropComplex_k[formi - 1]) termDropSpec <- termDropComplex[ , dropWhich_k[formi - 1]] termDrop <- paste(termDropSpec, collapse = " - ") formulaUpdate <- paste(format(~.), "-", termDrop) updatedFormula <- update.formula(formula_k, formulaUpdate) optionFormula_k[[formi]] <- updatedFormula keepFormula_k[formi] <- checkComponents(updatedFormula) } nkeepFormula_k <- sum(keepFormula_k) whichKeepFormula_k <- which(keepFormula_k == TRUE) keptFormula_k <- vector("list", nkeepFormula_k) for (kepti in 1:nkeepFormula_k){ keptFormula_k[[kepti]] <- optionFormula_k[[whichKeepFormula_k[kepti]]] } } else { keptFormula_k <- optionFormula_k } if (length(kFixed) == 1){ keptFormula_k <- NA } expandedKeptFormulae <- expand.grid(keptFormula_p, keptFormula_k) keptFormula_p <- expandedKeptFormulae[ , 1] keptFormula_k <- expandedKeptFormulae[ , 2] if (length(kFixed) == 1){ keptFormula_k <- NULL } if (unfixk == TRUE){ kFixed <- NULL } nmod <- nrow(expandedKeptFormulae) output <- vector("list", nmod) for (modi in 1:nmod){ formi_p <- keptFormula_p[modi][[1]] formi_k <- keptFormula_k[modi][[1]] pkm_i <- tryCatch( pkm(formula_p = formi_p, formula_k = formi_k, data = data, obsCol = obsCol, kFixed = kFixed, CL = CL, kInit = kInit, quiet = quiet), error = function(x) { paste("Failed model fit: ", geterrmessage(), sep = "") } ) name_p <- paste(format(formi_p), collapse = "") name_p <- gsub(" ", "", name_p) name_k <- paste(format(formi_k), collapse = "") name_k <- gsub(" ", "", name_k) if (length(kFixed) == 1){ name_k <- paste("k fixed at ", kFixed, sep = "") } modName <- paste(name_p, "; ", name_k, sep = "") modName <- gsub("NULL", "k not estimated", modName) output[[modi]] <- pkm_i names(output)[modi] <- modName } class(output) <- c("pkmSet", "list") return(output) } pkmSize <- function(formula_p, formula_k = NULL, data, kFixed = NULL, obsCol = NULL, sizeCol = NULL, allCombos = FALSE, kInit = 0.7, CL = 0.90, quiet = FALSE){ if (length(sizeCol) == 0 || is.na(sizeCol)){ pkfunc <- ifelse(allCombos, "pkmSet", "pkm0") out <- list() out[["all"]] <- get(pkfunc)(formula_p = formula_p, formula_k = formula_k, data = data, obsCol = obsCol, kFixed = kFixed, kInit = kInit, CL = CL, quiet = quiet ) class(out) <- c(ifelse(allCombos, "pkmSetSize", "pkmSize"), "list") return(out) } if (!(sizeCol %in% colnames(data))){ stop("sizeCol not in data set.") } sizeclasses <- sort(unique(as.character(data[ , sizeCol]))) if (all(is.na(kFixed))){ kFixed <- NULL } if (length(kFixed) >= 1){ kFixed <- kFixed[!is.na(kFixed)] if (length(kFixed) == 1 && is.null(names(kFixed))){ kFixed <- rep(kFixed, length(sizeclasses)) names(kFixed) <- sizeclasses if (quiet == FALSE){ message("One unnamed kFixed value provided by user. ", "All classes are assumed to have kFixed = ", kFixed[1], ". ", "To specify specific classes to apply kFixed values to, ", "class names must be provided in kFixed vector." ) } } else { if (is.null(names(kFixed)) || !all(names(kFixed) %in% sizeclasses)){ stop("kFixed names must be names of carcass classes.") } } } if (!allCombos){ if ("list" %in% intersect(class(formula_p), class(formula_k))){ if (!setequal(names(formula_p), names(formula_k)) || !setequal(names(formula_p), unique(data[ , sizeCol]))){ stop("p and k formula names must match carcass classes") } formlist <- TRUE } else { formlist <- FALSE } } out <- list() for (sci in sizeclasses){ if (allCombos){ out[[sci]] <- pkmSet(formula_p = formula_p, formula_k = formula_k, data = data[data[, sizeCol] == sci, ], obsCol = obsCol, kFixed = kFixed[sci], CL = CL, kInit = kInit, quiet = quiet) } else { if (formlist){ out[[sci]] <- pkm0( formula_p = formula_p[[sci]], formula_k = formula_k[[sci]], data = data[data[, sizeCol] == sci, ], obsCol = obsCol, kFixed = kFixed[sci], CL = CL, kInit = kInit, quiet = quiet ) } else { out[[sci]] <- pkm0( formula_p = formula_p, formula_k = formula_k, data = data[data[, sizeCol] == sci, ], obsCol = obsCol, kFixed = kFixed[sci], CL = CL, kInit = kInit, quiet = quiet ) } } } class(out) <- c(ifelse(allCombos, "pkmSetSize", "pkmSize"), "list") return(out) } aicc.pkmSet <- function(x, ... , quiet = FALSE, app = FALSE){ pkmset <- x nmod <- length(pkmset) formulas <- names(pkmset) formulas_p <- rep(NA, nmod) formulas_k <- rep(NA, nmod) AICc <- rep(NA, nmod) deltaAICc <- rep(NA, nmod) if (nmod == 1){ splitFormulas <- strsplit(formulas, "; ")[[1]] formulas_p <- splitFormulas[1] formulas_k <- splitFormulas[2] AICc <- tryCatch(pkmset[[1]]$AICc, error = function(x) {1e7}) deltaAICc <- 0 AICcOrder <- 1 } else { for (modi in 1:nmod){ splitFormulas_i <- strsplit(formulas[modi], "; ")[[1]] formulas_p[modi] <- splitFormulas_i[1] formulas_k[modi] <- splitFormulas_i[2] AICc[modi] <- tryCatch(pkmset[[modi]]$AICc, error = function(x) {1e7}) } AICcOrder <- order(AICc) deltaAICc <- round(AICc - min(AICc), 2) which_fails <- which(AICc == 1e7) AICc[which_fails] <- NA deltaAICc[which_fails] <- NA } if (app){ formulas_p <- gsub("~ 1", "~ constant", formulas_p) formulas_k <- gsub("~ 1", "~ constant", formulas_k) } output <- data.frame(formulas_p, formulas_k, AICc, deltaAICc) output <- output[AICcOrder, ] colnames(output) <- c("p Formula", "k Formula", "AICc", "\u0394AICc") whichAICcNA <- which(is.na(output$AICc)) whichAICcMax <- which(output$AICc == 1e7) if (length(whichAICcNA) > 0 & quiet == FALSE){ message("Models with incorrect specification were removed from output.") output <- output[-whichAICcNA, ] } if (length(whichAICcMax) > 0 & quiet == FALSE){ message("Models that failed during fit were removed from output.") output <- output[-whichAICcMax, ] } class(output) <- c("corpus_frame", "data.frame") return(output) } aicc.pkm <- function(x,...){ return( data.frame(cbind( "formula_p" = deparse(x$formula_p), "formula_k" = deparse(x$formula_k), "AICc" = x$AICc )) ) } aicc.pkmSetSize <- function(x, ... ){ return(lapply(x, FUN = function(y){ class(y) <- c("pkmSet", "list") aicc(y) })) } aicc.pkmSize <- function(x, ... ){ return(lapply(x, FUN = function(y){ class(y) <- c("pkm", "list") aicc(y) })) } rpk <- function(n, model){ if (!"pkm" %in% class(model)) stop("model not of class pkm") if (anyNA(model$varbeta) || sum(diag(model$varbeta) < 0) > 0){ stop("Variance in pkm not well-defined. Cannot simulate.") } if (model$pOnly){ stop("k not included in 'model'. Cannot simulate pk.") } else { which_beta_k <- (model$nbeta_p + 1):(model$nbeta_p + model$nbeta_k) } sim_beta <- mvtnorm::rmvnorm(n, mean = c(model$betahat_p, model$betahat_k), sigma = model$varbeta, method = "svd") sim_p <- as.matrix(alogit(sim_beta[ , 1:model$nbeta_p] %*% t(model$cellMM_p))) colnames(sim_p) <- model$cells$CellNames if (is.null(model$kFixed) || is.na(model$kFixed)){ sim_k <- as.matrix(alogit(sim_beta[ , which_beta_k] %*% t(model$cellMM_k))) } else { sim_k <- matrix(model$kFixed, ncol = model$ncell, nrow = n) } colnames(sim_k) <- model$cells$CellNames output <- lapply(model$cells$CellNames, function(x) cbind(p = sim_p[, x], k = sim_k[, x])) names(output) <- model$cells$CellNames return(output) } qpk <- function(p, model){ if (!"pkm" %in% class(model)) stop("model not of class pkm") if (!is.numeric(p) || !is.vector(p)) stop("p must be a numeric vector") if (any(is.na(p))) stop("p must be numeric with no NA") if (max(p) >= 1 | min(p) <= 0) stop("p must be in (0, 1)") qp <- with(model, { varbeta_p <- varbeta[1:nbeta_p, 1:nbeta_p] cellMean_p <- cellMM_p %*% betahat_p cellVar_p <- cellMM_p %*% varbeta_p %*% t(cellMM_p) cellSD_p <- suppressWarnings(sqrt(diag(cellVar_p))) probs <- list(0.5, (1 - CL) / 2, 1 - (1 - CL) / 2) lapply(lapply(p, qnorm, mean = cellMean_p, sd = cellSD_p), alogit) }) if (!model$pOnly){ qk <- with(model, { if (!exists("kFixed") || is.null(kFixed) || is.na(kFixed)){ which_k <- (nbeta_p + 1):(nbeta_p + nbeta_k) varbeta_k <- varbeta[which_k, which_k] cellMean_k <- cellMM_k %*% betahat_k cellVar_k <- cellMM_k %*% varbeta_k %*% t(cellMM_k) cellSD_k <- suppressWarnings(sqrt(diag(cellVar_k))) } else { cellMean_k <- rep(logit(kFixed), ncell) cellSD_k <- rep(0, ncell) } lapply(lapply(p, qnorm, mean = cellMean_k, sd = cellSD_k), alogit) }) out <- list( p = matrix(unlist(qp), nrow = model$ncell), k = matrix(unlist(qk), nrow = model$ncell)) rownames(out[["p"]]) <- rownames(out[["k"]]) <- model$cells$CellNames colnames(out[["p"]]) <- colnames(out[["k"]]) <- paste0("q", p) return(out) } else { qp <- matrix(unlist(qp), nrow = model$ncell) rownames(qp) <- model$cells$CellNames colnames(qp) <- paste0("q", p) return(qp) } } pkmFail <- function(pkmod){ !("pkm" %in% class(pkmod)) || anyNA(pkmod) || sum(diag(pkmod$varbeta) < 0) > 0 } pkmSetFail <- function(pkmSetToCheck){ unlist(lapply(pkmSetToCheck, pkmFail)) } pkmSetSizeFail <- function(pkmSetSizeToCheck){ lapply(pkmSetSizeToCheck, pkmSetFail) } pkmSetAllFail <- function(pkmSetToCheck){ modchecks <- unlist(lapply(pkmSetToCheck, pkmFail)) if (length(modchecks) == sum(modchecks)){ return(TRUE) } FALSE } pkmSetFailRemove <- function(pkmSetToTidy){ out <- pkmSetToTidy[!pkmSetFail(pkmSetToTidy)] class(out) <- c("pkmSet", "list") return(out) } pkmSetSizeFailRemove <- function(pkmSetSizeToTidy){ out <- list() for (sci in names(pkmSetSizeToTidy)){ out[[sci]] <- pkmSetFailRemove(pkmSetSizeToTidy[[sci]]) } class(out) <- c("pkmSetSize", "list") return(out) } SEsi <- function(days, pk){ if (is.null(dim(pk)) || nrow(pk) == 1) return (SEsi0(days, pk)) npk <- nrow(pk) nsearch <- length(days) - 1 ind1 <- rep(1:nsearch, times = nsearch:1) ind2 <- ind1 + 1 ind3 <- unlist(lapply(1:nsearch, function(x) x:nsearch)) + 1 schedule <- cbind(days[ind1], days[ind2], days[ind3]) schedule.index <- cbind(ind1, ind2, ind3) nmiss <- schedule.index[, 3] - schedule.index[, 2] maxmiss <- max(nmiss) if (maxmiss == 0) { pfind.si <- pk[, 1] } else if (maxmiss == 1) { pfind.si <- cbind(pk[, 1], (1 - pk[, 1]) * pk[, 2] * pk[, 1]) } else { powk <- array(rep(pk[, 2], maxmiss + 1), dim = c(npk, maxmiss + 1)) powk[ , 1] <- 1 powk <- matrixStats::rowCumprods(powk) pfind.si <- pk[, 1] * powk * cbind( rep(1, npk), matrixStats::rowCumprods(1 - (pk[, 1] * powk[, 1:maxmiss])) ) } return(t(pfind.si)) } SEsi0 <- function(days, pk){ nsearch <- length(days) - 1 ind1 <- rep(1:nsearch, times = nsearch:1) ind2 <- ind1 + 1 ind3 <- unlist(lapply(1:nsearch, function(x) x:nsearch)) + 1 schedule <- cbind(days[ind1], days[ind2], days[ind3]) schedule.index <- cbind(ind1, ind2, ind3) nmiss <- schedule.index[, 3] - schedule.index[, 2] maxmiss <- max(nmiss) if (maxmiss == 0) { pfind.si <- pk[1] } else if (maxmiss == 1) { pfind.si <- c(pk[1], (1 - pk[1]) * pk[2] * pk[1]) } else { powk <- rep(pk[2], maxmiss + 1) powk[1] <- 1 powk <- cumprod(powk) pfind.si <- pk[1] * powk * c(1, cumprod(1 - (pk[1] * powk[1:maxmiss]))) } return(pfind.si) }
test_that("`m_vector3()` create a 3 dimensional vector", { vector3 <- m_vector3(1, 2, 3) expect_s3_class(vector3, "Vector3") expect_equal(vector3$x, 1) expect_equal(vector3$y, 2) expect_equal(vector3$z, 3) expect_error(m_vector3(1)) expect_error(m_vector3(1, 2)) expect_error(m_vector3("a", "b", "c")) })
best_binomial_bandit_sim <- function(x, n, alpha = 1, beta = 1, ndraws = 5000 ) { return(prob_winner(sim_post(x,n,alpha,beta,ndraws))) }
computeCardio <- function(data = NULL, Vegetables, Fruit, OliveOil, OOmeasure = "gr", Legumes, Fish, Meat, RefinedRice, RefinedBread, WholeBread, Wine, frequency = "percent", output = "percent", rm.na = FALSE) { arguments <- as.list( match.call() ) Fruit <- eval(arguments$Fruit, data) Vegetables <- eval(arguments$Vegetables, data) OliveOil <- eval(arguments$OliveOil, data) Legumes <- eval(arguments$Legumes, data) Fish <- eval(arguments$Fish, data) Wine <- eval(arguments$Wine, data) Meat <- eval(arguments$Meat, data) RefinedRice <- eval(arguments$RefinedRice, data) RefinedBread <- eval(arguments$RefinedBread, data) WholeBread <- eval(arguments$WholeBread, data) if(is.null(frequency)){stop("please, provide the frequency of consumption in which the data is tabulated with the 'frequency' argument. Accepted values are 'daily', 'weekly' and 'monthly'")} if(frequency == "weekly" || frequency == "monthly"){ Vars <- list(Vegetables = Vegetables, Fuit = Fruit, OliveOil = OliveOil, Legumes = Legumes, Fish = Fish, Meat = Meat, RefinedRice = RefinedRice, RefinedBread = RefinedBread, WholeBread = WholeBread, Wine = Wine) Vars <- periodicity(Vars, OriginalFreq = frequency, TargetFreq = "daily") Vegetables <- Vars$Vegetables Fruit <- Vars$Fruit OliveOil <- Vars$OliveOil Legumes <- Vars$Legumes Fish <- Vars$Fish Meat <- Vars$Meat RefinedRice <- Vars$RefinedRice RefinedBread <- Vars$RefinedBread WholeBread <- Vars$WholeBread Wine <- Vars$Wine } else { if(frequency != "daily"){stop("accepted values for 'frequency' argument are 'daily', 'weekly' and 'monthly'")} } if(OOmeasure == "gr") {OliveOil <- OliveOil/0.918/15} else { if(OOmeasure == "ml") {OliveOil <- OliveOil/15} else { if(OOmeasure == "serving") {"no conversion needed"} else {stop("check units of Olive Oil") } } } OOscore <- numeric() OOscore[OliveOil < 1] <- 0 OOscore[OliveOil >= 1] <- 1 Frscore <- numeric() Frscore[Fruit < 1] <- 0 Frscore[Fruit >= 1] <- 1 Vscore <- numeric() Vscore[Vegetables < 1] <- 0 Vscore[Vegetables >= 1] <- 1 FVscore <- numeric() FVscore[Frscore == 1 & Vscore == 1] <- 1 FVscore[Frscore == 0 | Vscore == 0] <- 0 LegumesWeek <- 7 * Legumes Lscore <- numeric() Lscore[LegumesWeek < 2] <- 0 Lscore[LegumesWeek >= 2] <- 1 FishWeek <- 7 * Fish Fiscore <- numeric() Fiscore[FishWeek < 3] <- 0 Fiscore[FishWeek >= 3] <- 1 Wscore <- numeric() Wscore[Wine < 1] <- 0 Wscore[Wine >= 1] <- 1 RefinedRiceW <- 7 * RefinedRice WholeBreadW <- 7 * WholeBread Rscore <- numeric() Rscore <- ifelse((RefinedBread < 1 & RefinedRiceW < 7) | (WholeBreadW > 5), 1, 0) score <- data.frame(OOscore, Frscore, Vscore, FVscore, Lscore, Fiscore, Wscore, Rscore) score$absolute <- apply(score, 1, function(x) sum(x, na.rm = rm.na)) score$percent <- round(100 * score$absolute / 9, 1) if(missing(output) || output == "percent") {return(score$percent) } else { if(output == "absolute") {return(score$absolute) } else { if(output == "data.frame") {return(score) } else { stop("please, select a valid output argument, admited values are 'percent' -default-, 'absolute' and 'data.frame' " ) } } } }
convert_intent = function(intent) { namer = switch( intent, 'NIFTI_INTENT_POINTSET' = "pointset", 'NIFTI_INTENT_TRIANGLE' = "triangle", 'NIFTI_INTENT_NODE_INDEX' = "node_index", 'NIFTI_INTENT_VECTOR' = "vector", 'NIFTI_INTENT_NORMAL' = "normal", 'NIFTI_INTENT_NONE' = "unknown", 'NIFTI_INTENT_SHAPE' = "shape", "NIFTI_INTENT_LABEL" = "labels", "NIFTI_INTENT_TIME_SERIES" = "timeseries", "NIFTI_INTENT_RGB_VECTOR" = "rgb", "NIFTI_INTENT_RGBA_VECTOR" = "rgba", "NIFTI_INTENT_GENMATRIX" = "genmatrix", "NIFTI_INTENT_CORREL" = "correl", "NIFTI_INTENT_TTEST" = "ttest", "NIFTI_INTENT_FTEST" = "ftest", "NIFTI_INTENT_ZSCORE" = "zscore", "NIFTI_INTENT_CHISQ" = "chisq", "NIFTI_INTENT_BETA" = "beta", "NIFTI_INTENT_BINOM" = "binom", "NIFTI_INTENT_GAMMA" = "gamma", "NIFTI_INTENT_POISSON" = "poisson", "NIFTI_INTENT_FTEST_NONC" = "ftest_nonc", "NIFTI_INTENT_CHISQ_NONC" = "chisq_nonc", "NIFTI_INTENT_LOGISTIC" = "logistic", "NIFTI_INTENT_LAPLACE" = "laplace", "NIFTI_INTENT_UNIFORM" = "uniform", "NIFTI_INTENT_TTEST_NONC" = "ttest_nonc", "NIFTI_INTENT_WEIBULL" = "weibull", "NIFTI_INTENT_CHI" = "chi", "NIFTI_INTENT_INVGAUSS" = "invgauss", "NIFTI_INTENT_EXTVAL" = "extval", "NIFTI_INTENT_PVAL" = "pval", "NIFTI_INTENT_LOGPVAL" = "logpval", "NIFTI_INTENT_LOG10PVAL" = "log10pval", "NIFTI_INTENT_ESTIMATE" = "estimate", "NIFTI_INTENT_NEURONAME" = "neuroname", "NIFTI_INTENT_SYMMATRIX" = "symmatrix", "NIFTI_INTENT_DISPVECT" = "dispvect", "NIFTI_INTENT_QUATERNION" = "quads", "NIFTI_INTENT_DIMLESS" = "dimless" ) if (is.null(namer)) { namer = "unknown" } return(namer) }
extract.name.from.special <- function(x,pattern="[()]"){ if (length(x)==1) rev(unlist(strsplit(x,pattern)))[1] else as.character(sapply(x,extract.name.from.special)) }
bea <- function(a, istart = 0, jstart = 0) { if (!is.matrix(a)) stop("First input argument must be a matrix.\n") n <- nrow(a) m <- ncol(a) b <- matrix(0.0, n, m) mode(a) <- "single" mode(b) <- "single" ib <- integer(n) jb <- integer(m) ifin <- integer(n) jfin <- integer(m) ener <- 0.0 if (istart == 0) istart <- floor(runif(1, 1, n)) if (jstart == 0) jstart <- floor(runif(1, 1, m)) bea1 <- .Fortran( "rbea", n = as.integer(n), m = as.integer(m), a = as.matrix(a), istart = as.integer(istart), b = as.matrix(b), ib = as.integer(ib), ifin = as.integer(ifin), PACKAGE = "seriation" ) a <- bea1$b bea2 <- .Fortran( "cbea", n = as.integer(n), m = as.integer(m), a = as.matrix(a), jstart = as.integer(jstart), b = as.matrix(b), jb = as.integer(jb), jfin = as.integer(jfin), PACKAGE = "seriation" ) energy <- .Fortran( "energy", n = as.integer(n), m = as.integer(m), b = as.matrix(bea2$b), ener = as.single(ener), PACKAGE = "seriation" ) list( b = bea2$b, ib = bea1$ib, jb = bea2$jb, e = energy$ener ) }
SEMUPDATE <- function(agentID){ semUpdateAge=world$semUpdateAge; deathAge=world$deathAge; nNouns=world$nNouns; nVerbs=world$nVerbs; local=world$local agent=population[[agentID]] if(agent$semupdate==0){ if(agent$age>semUpdateAge*deathAge){ agent=VERBDESEMANTICIZATION(agent) agent=NOUNDESEMANTICIZATION(agent) agent=FUSE(agent) agent=PERSONUPDATE(agent) agent$semupdate=1 } } agent$nouns=agent$nouns[agent$nouns$semanticWeight>0,] if(nrow(agent$nouns)<nNouns){ newNouns=NOUNS(nNouns-nrow(agent$nouns), local=FALSE) newNouns$ID=max(agent$nouns$ID)+(1:nrow(newNouns)) agent$nouns=rbind(agent$nouns, newNouns) } if(local==TRUE){ if(!1%in%agent$nouns$person){ agent$nouns[MAX(VMATCH(rep(1, length(grep('D\\d', names(agent$nouns)))), agent$nouns[, grep('D\\d', names(agent$nouns))]), 1, forceChoice=TRUE),]$person=1 } if(!2%in%agent$nouns$person){ agent$nouns[MAX(VMATCH(rep(1, length(grep('D\\d', names(agent$nouns)))), agent$nouns[, grep('D\\d', names(agent$nouns))]), 2, forceChoice=TRUE),]$person=2 } } agent$verbs=agent$verbs[agent$verbs$semanticWeight>0,] if(nrow(agent$verbs)<nVerbs){ newNouns=VERBS(nNouns-nrow(agent$verbs)) newNouns$ID=max(agent$verbs$ID)+(1:nrow(newNouns)) agent$verbs=rbind(agent$verbs, newNouns) } population[[agentID]]=agent population<<-population }
CreateQualificationType <- createqual <- function (name, description, status, keywords = NULL, retry.delay = NULL, test = NULL, answerkey = NULL, test.duration = NULL, auto = NULL, auto.value = NULL, verbose = getOption('pyMTurkR.verbose', TRUE)) { GetClient() if(!status %in% c("Active", "Inactive")) stop("QualificationTypeStatus must be Active or Inactive") args <- list() fun <- pyMTurkR$Client$create_qualification_type args <- c(args, list(Name = name, Description = description, QualificationTypeStatus = status)) if(!is.null(keywords)){ args <- c(args, list(Keywords = keywords)) } if(!is.null(test) & is.null(test.duration)){ stop("If test is specified then test.duration must be too") } else if(is.null(test) & !is.null(test.duration)){ stop("If test.duration is specified then test must be too") } else if(!is.null(test) & !is.null(test.duration)){ args <- c(args, list(TestDurationInSeconds = as.integer(test.duration), Test = test)) } if(is.null(test) & !is.null(answerkey)){ stop("If answerkey is specified then test must be too") } else if(!is.null(test) & !is.null(answerkey)){ args <- c(args, list(AnswerKey = answerkey)) } if(!is.null(auto)){ if(is.na(as.logical(auto))){ stop("auto must be TRUE or FALSE") } args <- c(args, list(AutoGranted = as.logical(auto))) } if(!is.null(auto.value)){ if(is.na(as.integer(auto.value))){ stop("auto.value must be an integer") } args <- c(args, list(AutoGrantedValue = as.integer(auto.value))) } if(!is.null(retry.delay)){ if(is.na(as.integer(retry.delay)) | as.integer(retry.delay) < 0){ stop("retry.delay must be a positive integer") } args <- c(args, list(RetryDelayInSeconds = as.integer(retry.delay))) } response <- try( do.call('fun', args), silent = !verbose ) if(class(response) == "try-error") { stop("Unable to create qualification") } else { qualid <- response$QualificationType$QualificationTypeId info <- emptydf(0, 13, c("QualificationTypeId", "CreationTime", "Name", "Description", "Keywords", "QualificationTypeStatus", "AutoGranted", "AutoGrantedValue", "IsRequestable", "RetryDelayInSeconds", "TestDurationInSeconds", "Test", "AnswerKey")) info[1,]$QualificationTypeId <- response$QualificationType$QualificationTypeId info[1,]$CreationTime <- reticulate::py_to_r(response$QualificationType$CreationTime) info[1,]$Name <- response$QualificationType$Name info[1,]$Description <- response$QualificationType$Description if(!is.null(keywords)){ info[1,]$Keywords <- keywords } info[1,]$QualificationTypeStatus <- response$QualificationType$QualificationTypeStatus info[1,]$AutoGranted <- response$QualificationType$AutoGranted if(!is.null(auto.value)){ info[1,]$AutoGrantedValue <- auto.value } info[1,]$IsRequestable <- response$QualificationType$IsRequestable if(!is.null(retry.delay)){ info[1,]$RetryDelayInSeconds <- retry.delay } if(!is.null(test)){ info[1,]$Test <- test } if(!is.null(answerkey)){ info[1,]$AnswerKey <- answerkey } if(!is.null(test.duration)){ info[1,]$TestDurationInSeconds <- test.duration } message("QualificationType Created: ", response$QualificationType$QualificationTypeId) return(info) } }
expected <- eval(parse(text="c(\"NA\", \"a\", \"b\", \"c\", \"d\", \"<NA>\")")); test(id=0, code={ argv <- eval(parse(text="list(c(\"NA\", \"a\", \"b\", \"c\", \"d\", NA), 0L, \"\", 0L, TRUE)")); .Internal(`encodeString`(argv[[1]], argv[[2]], argv[[3]], argv[[4]], argv[[5]])); }, o=expected);
calc_3d <- function(BAF, LRR, chr, x, GT, seg_raw){ tt = exp(-(0:6-1)^2);prior_f = tt%*%t(tt);lp_2d = -log(prior_f)*1e-3 rtt = exp(-(6:0-1)^2);rprior_f = rtt%*%t(rtt);rlp_2d = -log(rprior_f)*1e-3 gt = (GT=='BB')*2+(GT=='AB')*1.5+(GT=='AA')-1;gt[gt==(-1)]=NA data= data.frame(x,chr,2*2^(LRR),GT,BAF) var = get_var_tcn_baf(LRR,BAF,gt) var_tcn=var[1]; var_baf=var[2] scale_max = mean(2*2^LRR,na.rm=TRUE); scale_min = scale_max/6 delta = 0.008 ITB = combine_close_seg(seg_raw,var_baf,data,delta=delta) IT_new = ITB[,1:7]; B_new = ITB[,1:7+7] id_excl = which(IT_new[,5]<.05) if(length(id_excl)>0){IT_new = IT_new[-id_excl,];B_new = B_new[-id_excl,]} temp <- data.frame(scale_max, scale_min, var_baf, var_tcn) res3d=sel_scale_2d(cnMax=6,pscnMax=6,ngrid = 100,nslaves = 50,B_new = B_new, IT_new = IT_new, temp = temp) B_new[,7] = B_new[,7]*5 n_seg = nrow(IT_new) L_tot_3d_scale1 = array(0,dim=c(n_seg,100,34,51)) L_tot_3d_scale2 = array(0,dim=c(n_seg,100,34,51)) for(i in 1:n_seg){ L_tot_3d_scale1[i,,,]= calcll_p3(as.numeric(IT_new[i,]),as.numeric(B_new[i,]),var_baf,var_tcn,res3d$scale2d[1],6,6) L_tot_3d_scale2[i,,,]= calcll_p3(as.numeric(IT_new[i,]),as.numeric(B_new[i,]),var_baf,var_tcn,res3d$scale2d[2],6,6) } L_sum_3d_scale1 = apply(L_tot_3d_scale1,c(2,3,4),sum) L_sum_3d_scale2 = apply(L_tot_3d_scale2,c(2,3,4),sum) sol1_pct = which(L_sum_3d_scale1<min(L_sum_3d_scale1)+.000000001,arr.ind=TRUE) - 1 sol1_scale = res3d$scale2d[1] sol2_pct = which(L_sum_3d_scale2<min(L_sum_3d_scale2)+.000000001,arr.ind=TRUE) - 1 sol2_scale = res3d$scale2d[2] return (list(sol1_pct = sol1_pct, sol1_scale = sol1_scale, sol2_pct = sol2_pct, sol2_scale = sol2_scale, segmentation = seg_raw)) }
RegEstimate <- function(x=1:10) { if (!("manipulate" %in% installed.packages())) { return(cat(paste0("You must be on R Studio with package manipulate installed\n", "in order to run this function."))) } manipulate( a=slider(-1,1,step=0.1,initial=0,label="True Intercept a"), b=slider(-3,3,step=0.1,initial=1,label="True Slope b"), s=slider(0,4,step=0.1,initial=2,label="Likely Error Size"), coefs=checkbox(FALSE,"Print Coefficient Information"), {n <- length(x) y=a+b*x+rnorm(n,mean=0,sd=s) ymin <- min(a+b*x)-4*s ymax <- max(a+b*x)+4*s mod <- lm(y~x) ahat <- round(coef(mod)[1],2) bhat <- round(coef(mod)[2],2) plot(x,y,col="blue",pch=16, ylim=c(ymin,ymax)) mtext(bquote(hat(a) == .(ahat)), line= 2) mtext(bquote(hat(b) == .(bhat)), line= 0.5) abline(a,b,col="red") abline(coef(mod),col="blue",lty=2) if (coefs) { print(summary(mod)$coefficients) cat("\n \n") } } ) } if(getRversion() >= "2.15.1") utils::globalVariables(c("a","b","s","coefs"))
gbm <- function(formula = formula(data), distribution = "bernoulli", data = list(), weights, subset = NULL, offset = NULL, var.monotone = NULL, n.trees = 100, interaction.depth = 1, n.minobsinnode = 10, shrinkage = 0.001, bag.fraction = 0.5, train.fraction = 1.0, mFeatures = NULL, cv.folds=0, keep.data = TRUE, verbose = FALSE, class.stratify.cv=NULL, n.cores=NULL, par.details=getOption('gbm.parallel'), fold.id = NULL, tied.times.method="efron", prior.node.coeff.var=1000, strata=NA, obs.id=1:nrow(data)) { the_call <- match.call() mf <- match.call(expand.dots = FALSE) m <- match(c("formula", "data", "weights", "offset"), names(mf), 0) mf <- mf[c(1, m)] mf$drop.unused.levels <- TRUE mf$na.action <- na.pass mf[[1]] <- as.name("model.frame") m <- mf mf <- eval(mf, parent.frame()) Terms <- attr(mf, "terms") y <- model.response(mf) w <- model.weights(mf) offset_mf <- model.offset(mf) if (!missing(n.cores)) { if (!missing(par.details)) { stop("You have provided both n.cores and par.details") } message("n.cores is deprecated, please use par.details") par.details <- gbmParallel(num_threads=n.cores) } if(is.null(class.stratify.cv)) class.stratify.cv <- FALSE var.names <- attributes(Terms)$term.labels x <- model.frame(terms(reformulate(var.names)), data, na.action=na.pass) if(!is.null(w)) { weights <- w } else { weights <- rep(1, length(obs.id)) } if(!is.null(offset_mf)){ offset <- offset_mf } else { offset <- rep(0, length(obs.id)) } if(cv.folds == 0) cv.folds <- 1 if(missing(distribution)) {distribution <- guess_distribution(y)} if (is.character(distribution)){ distribution <- list(name=distribution)} dist_obj <- create_dist_obj_for_gbmt_fit(distribution, tied.times.method, strata, prior.node.coeff.var) if(is.null(mFeatures)) mFeatures <- ncol(x) params <- training_params(num_trees=n.trees, interaction_depth=interaction.depth, min_num_obs_in_node=n.minobsinnode, shrinkage=shrinkage, bag_fraction=bag.fraction, id=obs.id, num_train=round(train.fraction*length(unique(obs.id))), num_features=mFeatures) check_cv_parameters(cv.folds, class.stratify.cv, fold.id, params) if (!is.null(fold.id)) { if (length(fold.id) != nrow(x)){ stop("fold.id inequal to number of rows.") } num_inferred_folds <- length(unique(fold.id)) if (cv.folds != num_inferred_folds) { warning("CV folds changed from ", cv.folds, " to ", num_inferred_folds, " because of levels in fold.id.") } cv.folds <- num_inferred_folds fold.id <- as.numeric(as.factor(fold.id)) } dist_obj <- determine_groups(data, y, dist_obj) weights <- weight_group_consistency(dist_obj, weights) params <- update_num_train_groups(params, dist_obj) gbm_fit_obj <- gbmt_fit(x, y, dist_obj, weights, offset, params, as.character(formula[[2]]), var.monotone, var.names, keep.data, cv.folds, class.stratify.cv, fold.id, par.details, verbose) gbm_fit_obj$model <- m gbm_fit_obj$Terms <- Terms gbm_fit_obj$call <- the_call gbm_fit_obj$is_verbose <- verbose return(gbm_fit_obj) }
BCfit <- function(y, X, covlist, R, z, mu, updateR, iters, thin = 1, burn = 0, priW = c(nrow(z) + 2 * ncol(z), 2 * ncol(z)), verbose = 0) { spnames <- colnames(y) y <- t(y) nsp <- dim(y)[1] n <- dim(y)[2] iR <- solve(R) e <- z - mu nsamp <- (iters - burn) %/% thin output <- list( R = array(NA, dim = c(nsamp, ((nsp * nsp - nsp) / 2))), B = NULL, z = array(NA, dim = c(nsamp, n, nsp)), burn = burn, thin = thin ) for (i in 1:nsp) { temp <- matrix(NA, nsamp, length(covlist[[i]])) colnames(temp) <- colnames(X)[covlist[[i]]] output$B[[spnames[i]]] <- temp } rm(temp) nam <- rep(NA, n * n) for (i in 1:nsp) { for (j in 1:nsp) { nam[(i - 1) * nsp + j] <- paste(spnames[i], "_", spnames[j], sep="") } } colnames(output$R) <- nam[which(upper.tri(diag(nsp)))] dimnames(output$z)[[3]] <- spnames rec <- 0 start <- Sys.time() for (iter in 1:iters) { trunc <- find_trunc(mu, y) e <- sample_e(e, trunc, iR) z <- mu + e mulis<- sample_mu(z, X, covlist) mu <- mulis[[1]] e <- z - mu if (updateR) { R <- sample_R(z - mu, priW) iR <- chol2inv(chol(R)) } if(verbose == 2){ message(iter) } if(verbose > 0 & iter == burn){ message("burn-in complete") } if (iter %% thin == 0 & iter > burn) { if(verbose == 1){ message(iter) } rec <- rec + 1 output$R[rec, ] <- R[upper.tri(R)] output$z[rec, , ] <- z for (i in 1:nsp) { output$B[[i]][rec, ] <- mulis[[2]][[i]] } } } output }
context("File info operations") test_that("Test that selecting/renaming file info works", { iso_file1 <- make_di_data_structure("NA") iso_file1$read_options$file_info <- TRUE iso_file1$file_info$new_info <- 42 iso_file2 <- iso_file3 <- iso_file1 iso_file1$file_info$file_id <- "A" iso_file2$file_info$file_id <- "B" iso_file2$file_info$new_info2 <- 2 iso_file3$file_info$file_id <- "C" iso_file3$file_info$new_info3 <- 3 iso_files <- c(iso_file1, iso_file2, iso_file3) expect_error(iso_select_file_info(42), "not defined") expect_error(iso_select_file_info(iso_file1, new = file_id), "renaming.*not allowed") expect_error(iso_select_file_info(iso_files, new = file_id), "renaming.*not allowed") expect_warning(iso_select_file_info(iso_files, y = DNE), "doesn't exist") expect_warning(iso_select_file_info(iso_files, y = DNE, file_specific = TRUE), "doesn't exist") expect_error(iso_select_file_info(iso_files, y = new_info, y = new_info2), "renamed columns must be unique") expect_message(iso_select_file_info(iso_files, y = new_info, y = new_info2, file_specific = TRUE, cols_must_exist = FALSE), "selecting/renaming") expect_message(iso_select_file_info(iso_file1), "keeping only 'file_id'") expect_silent(iso_select_file_info(iso_file1, quiet = TRUE)) expect_silent(select(iso_file1)) expect_message(iso_select_file_info(iso_file1, newer_info = new_info), "1 data file.*'new_info'->'newer_info'") expect_message(iso_select_file_info(iso_file1, newer_info = new_info, file_specific = TRUE), "1 data file.*'new_info'->'newer_info'") expect_message(iso_select_file_info(iso_files, newer_info = new_info2), "3 data file.*'new_info2'->'newer_info'") expect_message(iso_select_file_info(iso_files, newer_info = new_info2, file_specific = TRUE), "2 file.*'file_id'.*1 file.*'file_id', 'new_info2'->'newer_info'") expect_message(iso_select_file_info(iso_files, newer_info = new_info), "3 data file.*'new_info'->'newer_info'") expect_message(iso_select_file_info(iso_files, newer_info = new_info, file_specific = TRUE), "3 file.*'new_info'->'newer_info'") expect_message(iso_select_file_info(iso_files, y = new_info2, y = new_info3, file_specific = TRUE), "1 file.*'file_id'.*1 file.*'file_id', 'new_info2'->'y'.*1 file.*'file_id', 'new_info3'->'y'") expect_equal( iso_select_file_info(iso_files, y = new_info2, y = new_info3, file_specific = TRUE) %>% iso_get_file_info(), tibble(file_id = c("A", "B", "C"), y = c(NA, 2, 3)) ) expect_equal( iso_select_file_info(iso_files, -starts_with("file"), -new_info) %>% iso_get_file_info(), tibble(file_id = c("A", "B", "C"), new_info2 = c(NA, 2, NA), new_info3 = c(NA, NA, 3)) ) expect_equal( iso_select_file_info(iso_files, -starts_with("file"), -new_info, file_specific = TRUE) %>% iso_get_file_info(), tibble(file_id = c("A", "B", "C"), new_info2 = c(NA, 2, NA), new_info3 = c(NA, NA, 3)) ) expect_equal( iso_select_file_info(iso_files, newer_info = new_info) %>% iso_get_file_info(), tibble(file_id = c("A", "B", "C"), newer_info = 42) ) expect_equal( iso_select_file_info(iso_files, newer_info = new_info, file_specific = TRUE) %>% iso_get_file_info(), tibble(file_id = c("A", "B", "C"), newer_info = 42) ) expect_equal( iso_select_file_info(iso_files, newest_info = new_info, new_info2, new_info2 = new_info3, file_specific = TRUE) %>% iso_get_file_info(), tibble(file_id = c("A", "B", "C"), newest_info = 42, new_info2 = c(NA, 2, 3)) ) expect_error(iso_rename_file_info(42), "not defined") expect_error(iso_rename_file_info(iso_file1, new = file_id), "renaming.*not allowed") expect_error(iso_rename_file_info(iso_files, new = file_id), "renaming.*not allowed") expect_error(iso_rename_file_info(iso_files, new_info = new_info2), class = "vctrs_error_names_must_be_unique", "must be unique") expect_error(iso_rename_file_info(iso_files, y = new_info, y = new_info2), "must be unique") expect_message(iso_rename_file_info(iso_file1), "renaming.*1 data file") expect_silent(iso_rename_file_info(iso_file1, quiet = TRUE)) expect_silent(rename(iso_file1)) expect_message(iso_rename_file_info(iso_file1, newer_info = new_info), "renaming.*1.*file.*'new_info'->'newer_info'") expect_message(iso_rename_file_info(iso_files, newer_info = new_info2), "renaming.*3.*file.*'new_info2'->'newer_info'") expect_error(iso_rename_file_info(iso_files, y = new_info2, y = new_info3), "renamed columns must be unique") expect_message(iso_rename_file_info(iso_files, y = new_info2, y = new_info3, file_specific = TRUE), "1 file.*'new_info2'->'y'.*1 file.*'new_info3'->'y'") expect_equal( iso_rename_file_info(iso_files, y = new_info2, y = new_info3, file_specific = TRUE) %>% iso_get_file_info() %>% select(file_id, new_info, y), tibble(file_id = c("A", "B", "C"), new_info = 42, y = c(NA, 2, 3)) ) expect_equal( iso_rename_file_info(iso_files, newer_info = new_info) %>% iso_get_file_info() %>% select(file_id, newer_info), tibble(file_id = c("A", "B", "C"), newer_info = 42) ) expect_equal( iso_rename_file_info(iso_files, newest_info = new_info, new_info2 = new_info3, file_specific = TRUE) %>% iso_get_file_info() %>% select(file_id, newest_info, new_info2), tibble(file_id = c("A", "B", "C"), newest_info = 42, new_info2 = c(NA, 2, 3)) ) }) test_that("Test that filtering by file info works", { iso_file1 <- make_di_data_structure("NA") iso_file1$read_options$file_info <- TRUE iso_file1$file_info$new_info <- 42 iso_file2 <- iso_file3 <- iso_file1 iso_file1$file_info$file_id <- "A" iso_file2$file_info$file_id <- "B" iso_file3$file_info$file_id <- "C" expect_error(iso_filter_files(42), "not defined") iso_files <- c(iso_file1, iso_file2, iso_file3) expect_silent(filter(iso_files)) expect_message(iso_filter_files(iso_files), "applying.*filter") expect_silent(iso_filter_files(iso_files, quiet = TRUE)) expect_equal(filter(iso_files), iso_files) expect_equal(filter(iso_files, new_info == 42), iso_files) expect_equal(filter(iso_file1, new_info == 42), iso_file1) expect_null(filter(iso_files, new_info != 42)) expect_null(filter(iso_file1, new_info != 42)) expect_equal(filter(iso_files, file_id == "A"), c(iso_file1)) expect_null(filter(iso_files, file_id == "DNE")) expect_error(filter(iso_files, dne == 5)) expect_equal(filter(iso_files, file_id != "A"), iso_filter_files(iso_files, file_id != "A")) }) test_that("Test that mutating file info works", { iso_file1 <- make_di_data_structure("NA") iso_file1$read_options$file_info <- TRUE iso_file1$file_info$new_info <- 42 iso_file2 <- iso_file3 <- iso_file1 iso_file1$file_info$file_id <- "A" iso_file2$file_info$file_id <- "B" iso_file2$file_info$new_info2 <- 2 iso_file3$file_info$file_id <- "C" iso_file3$file_info$new_info3 <- 3 expect_error(iso_mutate_file_info(42), "not defined") iso_files <- c(iso_file1, iso_file2, iso_file3) expect_silent(mutate(iso_files)) expect_message(iso_mutate_file_info(iso_files), "mutating") expect_silent(iso_mutate_file_info(iso_files, quiet = TRUE)) expect_equal( mutate(iso_files) %>% iso_get_file_info(), iso_files %>% iso_get_file_info()) expect_equal( mutate(iso_files, new_info = as.character(new_info)) %>% iso_get_file_info(), iso_files %>% iso_get_file_info() %>% mutate(new_info = as.character(new_info))) expect_equal( mutate(iso_files, new_info = iso_double_with_units(1:3, "s")) %>% iso_get_file_info(), iso_files %>% iso_get_file_info() %>% mutate(new_info = iso_double_with_units(1:3, "s"))) expect_true( iso_is_file_list( mutated_iso_files <- mutate(iso_files, newest_info = case_when(new_info2 == 2 ~ 20, new_info3 == 3 ~ 30, TRUE ~ 00))) ) expect_equal( mutated_iso_files %>% iso_get_file_info(), iso_files %>% iso_get_file_info() %>% mutate(newest_info = case_when(new_info2 == 2 ~ 20, new_info3 == 3 ~ 30, TRUE ~ 00)) ) expect_true(is.character(mutated_iso_files[[1]]$file_info$file_id)) expect_true(is.na(mutated_iso_files[[1]]$file_info$file_root)) expect_true(is.list(mutated_iso_files[[1]]$file_info$new_info)) expect_true(is.list(mutated_iso_files[[1]]$file_info$newest_info)) expect_equal( mutate(iso_files, newest_info = "A") %>% iso_get_file_info(), iso_mutate_file_info(iso_files, newest_info = "A") %>% iso_get_file_info()) expect_error(iso_set_file_root(iso_files, root = NULL), "must supply.*file root") expect_error(iso_set_file_root(iso_files, root = "root", remove_embedded_root = 1:2), "only.*single value") expect_message(rerooted_files <- iso_set_file_root(iso_files, root = "test"), "setting file root for 3 data file.*to.*test") expect_equal(iso_get_file_info(rerooted_files, c(file_root, file_path)), iso_get_file_info(iso_files, c(file_root, file_path)) %>% mutate(file_root = "test")) iso_files[[1]]$file_info$file_path <- "A/B/C/a.cf" iso_files[[2]]$file_info$file_path <- "A/B/C/D/b.cf" iso_files[[3]]$file_info$file_path <- "A/B/c.df" expect_warning(rerooted_files <- iso_set_file_root(iso_files, remove_embedded_root = "DNE"), "3/3 file paths do not include the embedded root") expect_equal(iso_get_file_info(rerooted_files, c(file_root, file_path)), iso_get_file_info(iso_files, c(file_root, file_path)) %>% mutate(file_root = ".")) expect_warning(rerooted_files <- iso_set_file_root(iso_files, root = "test", remove_embedded_root = "A/B/C"), "1/3 file paths do not include the embedded root") expect_equal(iso_get_file_info(rerooted_files, c(file_root, file_path)), iso_get_file_info(iso_files, c(file_root, file_path)) %>% mutate(file_path = str_replace(file_path, "A/B/C/", ""), file_root = "test")) expect_message(rerooted_files <- iso_set_file_root(iso_files, remove_embedded_root = "A/B"), "setting file root for 3 data file.*removing embedded root.*A/B") expect_message(rerooted_files <- iso_set_file_root(iso_files, root = "test", remove_embedded_root = "././A/B"), "setting file root for 3 data file.*to.*test.*removing embedded root.*A/B") expect_equal(iso_get_file_info(rerooted_files, c(file_root, file_path)), iso_get_file_info(iso_files, c(file_root, file_path)) %>% mutate(file_path = str_replace(file_path, "A/B/", ""), file_root = "test")) }) test_that("Test that file info parsing works", { iso_file1 <- make_di_data_structure("NA") iso_file1$read_options$file_info <- TRUE iso_file1$file_info$new_info <- 42.0 iso_file2 <- iso_file3 <- iso_file1 iso_file1$file_info$file_id <- "A" iso_file2$file_info$file_id <- "B" iso_file2$file_info$new_info2 <- "2" iso_file3$file_info$file_id <- "C" iso_file3$file_info$new_info3 <- "2019-01-01 01:01" iso_files <- c(iso_file1, iso_file2, iso_file3) expect_error(iso_parse_file_info(42), "not defined") expect_error(iso_parse_file_info(iso_files, number = new_info, integer = new_info), "cannot convert.*to multiple formats") expect_warning(iso_parse_file_info(iso_files, integer = new_info), "missing automatic parsers") expect_warning(iso_parse_file_info(iso_files, datetime = new_info), "missing automatic parsers") expect_warning(iso_parse_file_info(iso_files, integer = new_info3), "parsing failure") expect_warning(iso_parse_file_info(iso_files, double = new_info3), "parsing failure") expect_warning(iso_parse_file_info(iso_files, datetime = new_info2), "parsing failure") expect_message(no_effect_isos <- iso_parse_file_info(iso_files), "parsing 0.*for 3 data file") expect_silent(iso_parse_file_info(iso_files, quiet = TRUE)) expect_message(text_isos <- iso_parse_file_info(iso_files, text = starts_with("new")), "parsing 1.*for 3 data file") expect_message(iso_parse_file_info(iso_files, text = starts_with("new")), "to text.*new_info") expect_message(iso_parse_file_info(iso_files, text = starts_with("new")), "already the target data type.*new_info2.*new_info3") expect_message(number_isos <- iso_parse_file_info(iso_files, number = c(new_info2, new_info3)), "to number.*new_info2.*new_info3") expect_message(integer_isos <- iso_parse_file_info(iso_files, integer = new_info2), "to integer.*new_info2") expect_message(double_isos <- iso_parse_file_info(iso_files, double = new_info2), "to double.*new_info2") expect_message(datetime_isos <- iso_parse_file_info(iso_files, datetime = new_info3), "to datetime.*new_info3") expect_equal(iso_get_file_info(no_effect_isos), iso_get_file_info(iso_files)) expect_equal(iso_get_file_info(text_isos), iso_get_file_info(iso_files) %>% mutate(new_info = as.character(new_info))) expect_equal(iso_get_file_info(number_isos), iso_get_file_info(iso_files) %>% mutate(new_info2 = parse_number(new_info2), new_info3 = parse_number(new_info3))) expect_equal(iso_get_file_info(integer_isos), iso_get_file_info(iso_files) %>% mutate(new_info2 = parse_integer(new_info2))) expect_equal(iso_get_file_info(double_isos), iso_get_file_info(iso_files) %>% mutate(new_info2 = parse_double(new_info2))) expect_equal(iso_get_file_info(datetime_isos)$new_info3, (iso_get_file_info(iso_files) %>% mutate(new_info3 = parse_datetime(new_info3) %>% lubridate::with_tz(Sys.timezone())))$new_info3) }) test_that("Test that file info addition works", { file_info <- tibble( file_id = letters[1:6], y = rep(LETTERS[1:2], each = 3), ) new_info <- tibble( file_id = c(NA, NA, letters[2:4]), y = c(LETTERS[1:2], NA, "", "X"), info = paste("new", 1:length(y)) ) expect_error(iso_add_file_info(), "without parameters") expect_error(iso_add_file_info(42), "not defined") expect_error(iso_add_file_info(tibble()), "no new_file_info supplied") expect_error(iso_add_file_info(tibble(), tibble()), "specify at least one set of join_by") expect_error(iso_add_file_info(tibble(), tibble(), "x"), "file_id column") expect_error(iso_add_file_info(file_info, new_info, "NA"), "join_by.*must exist.*missing.*NA") expect_error(iso_add_file_info(file_info, select(new_info, -y), "y"), "join_by.*must exist.*missing in new file info.*y") expect_error(iso_add_file_info(select(file_info, -y), new_info, "y"), "join_by.*must exist.*missing in existing file info.*y") expect_error( iso_add_file_info(file_info, new_info[c(1,1,2), ], by1 = "y"), "would create duplicate entries") expect_warning( out <- iso_add_file_info(file_info, select(new_info, -info), "y"), "no new information.*returning data unchanged" ) expect_equal(out, file_info) expect_message( df_out <- iso_add_file_info(file_info, new_info, by1 = "y", by2 = "file_id"), "adding.*'info'.*to 6 data file.*joining by 'y' then 'file_id'" ) expect_message( iso_add_file_info(file_info, new_info, by1 = "y", by2 = "file_id"), "'y' join.*2/3 new info.*matched 6.*3.*also matched.*subsequent joins" ) expect_message( iso_add_file_info(file_info, new_info, by1 = "y", by2 = "file_id"), "'file_id' join.*3/3 new info.*matched 3" ) expect_message( iso_add_file_info(file_info, new_info, by1 = "y", by2 = c("file_id", "y")), "adding.*to 6 data file.*joining by 'y' then 'file_id'\\+'y'" ) expect_message( iso_add_file_info(file_info, new_info, by1 = "y", by2 = c("file_id", "y")), "'y' join.*2/3 new info.*matched 6" ) expect_message( iso_add_file_info(file_info, new_info, by1 = "y", by2 = c("file_id", "y")), "'file_id'\\+'y' join.*0/1 new info.*matched 0" ) iso_add_file_info( mutate(file_info, y = rep(c(TRUE, FALSE), each = 3)), mutate(new_info, y = c(TRUE, FALSE, NA, NA, NA)), by1 = "y", by2 = "file_id" ) template <- make_cf_data_structure("NA") template$read_options$file_info <- TRUE iso_files <- map(split(file_info, seq(nrow(file_info))), ~{ x <- template; x$file_info <- .x; x }) %>% iso_as_file_list() expect_message( iso_files_out <- iso_add_file_info(iso_files, new_info, by1 = "y", by2 = "file_id"), "adding.*'info'.*to 6 data file.*joining by 'y' then 'file_id'" ) expect_message( iso_add_file_info(iso_files, new_info, by1 = "y", by2 = "file_id"), "'y' join.*2/3 new info.*matched 6.*3.*also matched.*subsequent joins" ) expect_message( iso_add_file_info(iso_files, new_info, by1 = "y", by2 = "file_id"), "'file_id' join.*3/3 new info.*matched 3" ) expect_equal(iso_files_out %>% iso_get_file_info(), df_out) })
psiFit <- function(data, modelPsi1, modelPsi2, dObj) { dat0 <- data[ {data[,dObj$A] == 0L} & {data[,dObj$Gam] != 0L},] grp1 <- {data[,dObj$A] == 0L} & {data[,dObj$Gam] == 1L} means1 <- colMeans(x = data[grp1,]) grp2 <- {data[,dObj$A] == 0L} & {data[,dObj$Gam] == 2L} means2 <- colMeans(x = data[grp2,]) modelPsi1 <- update.formula(old = modelPsi1, new = NULL ~ .) modelPsi2 <- update.formula(old = modelPsi2, new = NULL ~ .) modelPsi1 <- paste0(dObj$Psi, "~", as.character(x = modelPsi1)[2L]) modelPsi1 <- as.formula(object = modelPsi1) modelPsi2 <- paste0(dObj$Psi, "~", as.character(x = modelPsi2)[2L]) modelPsi2 <- as.formula(object = modelPsi2) logist1 <- tryCatch(expr = glm(formula = modelPsi1, data = data[grp1,], family = 'binomial'), error = function(e) { message("unable to obtain fit for psi1") stop(e$message, call. = FALSE) }) if (any(is.na(x = logist1$coef))) { stop("glm fit returns NA coefficients for modelPsiGam1", call. = FALSE) } logist2 <- tryCatch(expr = glm(formula = modelPsi2, data = data[grp2,], family = 'binomial'), error = function(e) { message("unable to obtain fit for psi2") stop(e$message, call. = FALSE) }) if (any(is.na(x = logist2$coef))) { stop("glm fit returns NA coefficients for modePsiGam2", call. = FALSE) } pPsi1 <- stats::predict.glm(object = logist1, newdata = data, type = "response") pPsi2 <- stats::predict.glm(object = logist2, newdata = data, type = "response") pPsi1.mean <- stats::predict.glm(object = logist1, newdata = as.data.frame(t(x = means1)), type = "response") pPsi2.mean <- stats::predict.glm(object = logist2, newdata = as.data.frame(t(x = means2)), type = "response") pPsi1.stab <- pPsi1.mean / pPsi1 pPsi2.stab <- pPsi2.mean / pPsi2 return( list("pPsi1.stab" = pPsi1.stab, "pPsi2.stab" = pPsi2.stab) ) }
diffmean <- function( x, ..., data=parent.frame(), only.2=TRUE ) { m <- mean_(x, ..., data=data) nms <- names(m) res <- diff(m) names(res) <- if (length(nms) < 3) "diffmean" else paste(tail(nms,-1), head(nms, -1), sep="-") if (length(nms) > 2 && only.2) { stop("To compare more than two means, set only.2=FALSE") } res } diffprop <- function( x, ..., data = parent.frame(), only.2 = TRUE ) { p <- prop(x, ..., data = data) nms <- names(p) res <- diff(p) names(res) <- if (length(nms) < 3) "diffprop" else paste(tail(nms,-1), head(nms, -1), sep="-") if (length(nms) > 2 && only.2) { stop("To compare more than two proportions, set only.2=FALSE") } res }
grep_or <- function (x, patterns) { lp = lapply(patterns, function(i) grepl(i, x)) res = 0 for (i in lp) res = res + i x[res > 0] }
getCacheFilename <- function(query, dir=getwd(), ext='csv', ...) { parms = getParameters(query) parmvals = unlist(list(...)) filename = paste(dir, '/', query, sep='') if(length(parms) > 0) { for(i in 1:length(parms)) { filename = paste(filename, parms[i], parmvals[parms[i]], sep='.') } } if(nchar(filename) >= 251) { warning(paste0('The cached filename is longer than 255 characters. ', 'This will cause an error on some operating systems. Consider ', 'specifying your own filename parameter. The filename will be ', 'truncated to 255 characters.')) filename <- substr(filename, 1, 251) } filename = paste(filename, ext, sep='.') return(filename) }
rCommunity <- function(n, size = sum(NorP), NorP = 1, BootstrapMethod = "Chao2015", S = 300, Distribution = "lnorm", sd = 1, prob = 0.1, alpha=40, CheckArguments = TRUE) { if (CheckArguments) CheckentropartArguments() Ps <- Ns <- NULL if (length(NorP) == 1) { if (Distribution == "lseries") { LSabundance <- function(N, alpha) { x <- N/(N+alpha) u <- stats::runif(1) k <- 1 P <- -x/log(1-x) F <- P while (u >= F) { P <- P*k*x/(k+1) k <- k+1 F <- F+P } return(k) } Ns <-replicate(n, replicate(round(-alpha*log(alpha/(size+alpha))), LSabundance(size, alpha))) } else { Ps <- switch(Distribution, geom = prob/(1-(1-prob)^S)*(1-prob)^(0:(S-1)), lnorm = (stats::rlnorm(S, 0, sd) -> Nslnorm)/sum(Nslnorm), bstick = c(cuts <- sort(stats::runif(S-1)), 1)- c(0, cuts) ) } } else { if (abs(sum(NorP) - 1) < length(NorP)*.Machine$double.eps) { Ps <- NorP } else { if (BootstrapMethod == "Chao2015") { Ps <- as.ProbaVector(NorP, Correction = "Chao2015", Unveiling = "geom", CheckArguments = FALSE) } if (BootstrapMethod == "Chao2013") { Ps <- as.ProbaVector(NorP, Correction = "Chao2013", Unveiling = "unif", CheckArguments = FALSE) } if (BootstrapMethod == "Marcon") { Ps <- NorP/sum(NorP) } } } if (is.null(Ps) & is.null(Ns)) { warning ("The distribution to simulate has not been recognized") return(NA) } if (is.null(Ns)) { Ns <- stats::rmultinom(n, size, Ps) } if (n > 1) { return(MetaCommunity(Ns)) } else { return(as.AbdVector(Ns, Round = TRUE)) } }
vitality.4p <- function(time = 0:(length(sdata)-1), sdata, init.params = FALSE, lower = c(0, 0, 0, 0), upper = c(100,50,100,50), rc.data = FALSE, se = FALSE, datatype = c("CUM", "INC"), ttol = 1e-6, pplot = TRUE, Iplot = FALSE, Mplot = FALSE, tlab = "years", silent = FALSE) { datatype <- match.arg(datatype) if (length(time) != length(sdata)) { stop("time and sdata must have the same length") } in.time <- time dTmp <- dataPrep(time, sdata, datatype, rc.data) time <- dTmp$time sfract <- dTmp$sfract x1 <- dTmp$x1 x2 <- dTmp$x2 Ni <- dTmp$Ni rc.data <- dTmp$rc.data if(in.time[1]>0){ time <- time[-1] sfract <- sfract[-1] x1 <- c(x1[-c(1,length(x1))], x1[1]) x2 <- c(x2[-c(1,length(x2))], 0) Ni <- Ni[-1] rc.data <- rc.data[-1] } if(length(init.params) == 1) { ii <- indexFinder(sfract, 0.5) if (ii == -1) { warning("ERROR: no survival fraction data below the .5 level.\n Cannot use the initial r s k u estimator. You must supply initial r s k u estimates") return(-1) } else rsk <- c(1/time[ii], 0.01, 0.1, 0.1) } else { rsk <- init.params } if (rsk[1] == -1) { stop } if (silent == FALSE) { print(cbind(c("Initial r", "initial s", "initial lambda", "initial beta"), rsk)) } dtfm <- data.frame(x1 = x1, x2 = x2, Ni = Ni) fit.nlm <- nlminb(start = rsk, objective = logLikelihood.4p, lower = lower, upper = upper, xx1 = x1, xx2 = x2, NNi = Ni) r.final <- fit.nlm$par[1] s.final <- abs(fit.nlm$par[2]) lambda.final <- fit.nlm$par[3] beta.final <- fit.nlm$par[4] mlv <- fit.nlm$obj if (silent == FALSE) {print(cbind(c("estimated r", "estimated s", "estimated lambda", "estimated beta", "minimum -loglikelihood value"), c(r.final, s.final, lambda.final, beta.final, mlv)))} if (se != FALSE) { s.e. <- stdErr.4p(r.final, s.final, lambda.final, beta.final, x1, x2, Ni, se) if (silent == FALSE){print(cbind(c("sd for r", "sd for s", "sd for lambda", "sd for beta"), s.e.))} } if (pplot != FALSE) { plotting.4p(r.final, s.final, lambda.final, beta.final, mlv, time, sfract, x1, x2, Ni, pplot, Iplot, Mplot, tlab, rc.data) } sd <- 5 if(se != F ) { params <- c(r.final, s.final, lambda.final, beta.final) pvalue <- c(1-pnorm(r.final/s.e.[1]), 1-pnorm(s.final/s.e.[2]), 1-pnorm(lambda.final/s.e.[3]), 1-pnorm(beta.final/s.e.[4])) std <- c(s.e.[1], s.e.[2], s.e.[3], s.e.[4]) out <- signif(cbind(params, std, pvalue), sd) return(out) } else { return(signif(c(r.final, s.final, lambda.final, beta.final), sd)) } } plotting.4p <- function(r.final, s.final, lambda.final, beta.final, mlv, time, sfract, x1, x2, Ni, pplot, Iplot, Mplot, tlab, rc.data) { if (pplot != FALSE) { ext <- max(pplot, 1) par(mfrow = c(1, 1)) len <- length(time) tmax <- ext * time[len] plot(time, sfract/sfract[1], xlab = tlab, ylab = "survival fraction", ylim = c(0, 1), xlim = c(min(time), tmax), col = 1) xxx <- seq(min(time), tmax, length = 200) xxx1 <- c(0, xxx[-1]) lines(xxx, SurvFn.4p(xxx1, r.final, s.final, lambda.final, beta.final), col = 2, lwd=2) lines(xxx, SurvFn.in.4p(xx=xxx1, r=r.final, s=s.final), col=3, lwd=2, lty=3) lines(xxx, SurvFn.ex.4p(xx=xxx1, r=r.final, s=s.final, lambda = lambda.final, beta = beta.final), col=4, lwd=2, lty=2) title("Cumulative Survival Data and Vitality Model Fitting") legend(x="bottomleft", legend=c("Total", "Intrinsic", "Extrinsic"), lty=c(1, 3, 2), col=c(2,3,4), bty="n", lwd=c(2,2,2)) } if ( Mplot != FALSE) { lx <- round(sfract*100000) lx <- c(lx,0) ndx <- -diff(lx) lxpn <- lx[-1] n <- c(diff(time), 1000) nax <- .5*n nLx <- n * lxpn + ndx * nax mu.x <- ndx/nLx mu.x[length(mu.x)] <- NA ext <- max(pplot, 1) par(mfrow = c(1, 1)) len <- length(time) tmax <- ext * time[len] xxx <- seq(min(time), tmax, length = 200) xxx1 <- xxx mu.i <- mu.vd1.4p(xxx1, r.final, s.final) mu.e <- mu.vd2.4p(xxx1, r.final, lambda.final, beta.final) mu.t <- mu.vd.4p(xxx1, r.final, s.final, lambda.final, beta.final) plot(time, mu.x, xlim = c(time[1], tmax), xlab = tlab, ylab = "estimated mortality rate", log = "y", main = "Log Mortality Data and Vitality Model Fitting", ylim=c(min(mu.x,mu.t,na.rm=T),max(mu.x,mu.t,na.rm=T))) lines(xxx, mu.t, col = 2, lwd=2) lines(xxx, mu.i, col=3, lwd=2, lty=3) lines(xxx, mu.e, col=4, lwd=2, lty=2) legend(x="bottomright", legend=c("data (approximate)", expression(mu[total]), expression(mu[i]), expression(mu[e])), lty=c(NA, 1, 3, 2), pch=c(1,NA,NA,NA), col=c(1,2,3,4), bty="n", lwd=c(1,2,2,2)) } if (Iplot != FALSE) { par(mfrow = c(1, 1)) ln <- length(Ni)-1 x1 <- x1[1:ln] x2 <- x2[1:ln] Ni <- Ni[1:ln] ln <- length(Ni) scale <- max( (x2-x1)[Ni == max(Ni)] ) ext <- max(pplot, 1) npt <- 200*ext xxx <- seq(x1[1], x2[ln]*ext, length = npt) xx1 <- xxx[1:(npt-1)] xx2 <- xxx[2:npt] sProbI <- survProbInc.4p(r.final, s.final, lambda.final, beta.final, xx1, xx2) ytop <- 1.1 * max(max(sProbI/(xx2-xx1)), Ni/(x2-x1)) * scale plot((x1+x2)/2, Ni*scale/(x2-x1), ylim = c(0, ytop), xlim = c(x1[1], ext*x2[ln]), xlab = tlab, ylab = "incremental mortality") title("Probability Density Function") lines((xx1+xx2)/2, sProbI*scale/(xx2-xx1), col=2) } } SurvFn.in.4p <- function(xx, r, s) { yy <- s^2*xx tmp1 <- sqrt(1/yy) * (1 - xx * r) tmp2 <- sqrt(1/yy) * (1 + xx * r) tmp3 <- 2*r/(s*s) if (tmp3 > 250) { q <- tmp3/250 if (tmp3 > 1500) { q <- tmp3/500 } valueFF <- (1.-(pnorm(-tmp1) + (exp(tmp3/q) *pnorm(-tmp2)^(1/q))^(q))) } else { valueFF <- (1.-(pnorm(-tmp1) + exp(tmp3) *pnorm(-tmp2))) } if ( all(is.infinite(valueFF)) ) { warning(message = "Inelegant exit caused by overflow in evaluation of survival function. Check for right-censored data. Try other initial values.") } return(valueFF) } SurvFn.ex.4p <- function(xx, r, s, lambda, beta) { yy <- s^2*xx tmp1 <- sqrt(1/yy) * (1 - xx * r) tmp2 <- sqrt(1/yy) * (1 + xx * r) tmp3 <- 2*r/(s*s) if (tmp3 > 250) { q <- tmp3/250 if (tmp3 > 1500) { q <- tmp3/500 } valueFF <- exp(-lambda*exp(-1/beta)/(r/beta)*(exp(r*xx/beta)-1)) } else { valueFF <-exp(-lambda*exp(-1/beta)/(r/beta)*(exp(r*xx/beta)-1)) } if ( all(is.infinite(valueFF)) ) { warning(message = "Inelegant exit caused by overflow in evaluation of survival function. Check for right-censored data. Try other initial values.") } return(valueFF) } survProbInc.4p <- function(r, s, lambda, beta, xx1, xx2){ value.iSP <- -(SurvFn.4p(xx2, r, s, lambda, beta) - SurvFn.4p(xx1, r, s, lambda, beta)) value.iSP[value.iSP < 1e-18] <- 1e-18 value.iSP } logLikelihood.4p <- function(par, xx1, xx2, NNi) { iSP <- survProbInc.4p(par[1], par[2], par[3], par[4], xx1, xx2) loglklhd <- -NNi*log(iSP) return(sum(loglklhd)) } stdErr.4p <- function(r, s, k, u, x1, x2, Ni, pop) { LL <- function(a, b, c, d, r, s, k, u, x1, x2, Ni) {logLikelihood.4p(c(r+a, s+b, k+c, u+d), x1, x2, Ni)} hess <- matrix(0, nrow = 4, ncol = 4) h <- .001 hr <- abs(h*r) hs <- h*s*.1 hk <- h*k*.1 hu <- h*u*.1 f0 <- LL(-2*hr, 0, 0, 0, r, s, k, u, x1, x2, Ni) f1 <- LL(-hr, 0, 0, 0, r, s, k, u, x1, x2, Ni) f2 <- LL(0, 0, 0, 0, r, s, k, u, x1, x2, Ni) f3 <- LL(hr, 0, 0, 0, r, s, k, u, x1, x2, Ni) f4 <- LL(2*hr, 0, 0, 0, r, s, k, u, x1, x2, Ni) fp0 <- (-25*f0 +48*f1 -36*f2 +16*f3 -3*f4)/(12*hr) fp1 <- (-3*f0 -10*f1 +18*f2 -6*f3 +f4)/(12*hr) fp3 <- (-f0 +6*f1 -18*f2 +10*f3 +3*f4)/(12*hr) fp4 <- (3*f0 -16*f1 +36*f2 -48*f3 +25*f4)/(12*hr) LLrr <- (fp0 -8*fp1 +8*fp3 -fp4)/(12*hr) f0 <- LL(0, -2*hs, 0, 0, r, s, k, u, x1, x2, Ni) f1 <- LL(0, -hs, 0, 0, r, s, k, u, x1, x2, Ni) f3 <- LL(0, hs, 0, 0, r, s, k, u, x1, x2, Ni) f4 <- LL(0, 2*hs, 0, 0, r, s, k, u, x1, x2, Ni) fp0 <- (-25*f0 +48*f1 -36*f2 +16*f3 -3*f4)/(12*hs) fp1 <- (-3*f0 -10*f1 +18*f2 -6*f3 +f4)/(12*hs) fp3 <- (-f0 +6*f1 -18*f2 +10*f3 +3*f4)/(12*hs) fp4 <- (3*f0 -16*f1 +36*f2 -48*f3 +25*f4)/(12*hs) LLss <- (fp0 -8*fp1 +8*fp3 -fp4)/(12*hs) f0 <- LL(0, 0, -2*hk, 0, r, s, k, u, x1, x2, Ni) f1 <- LL(0, 0, -hk, 0, r, s, k, u, x1, x2, Ni) f3 <- LL(0, 0, hk, 0, r, s, k, u, x1, x2, Ni) f4 <- LL(0, 0, 2*hk, 0, r, s, k, u, x1, x2, Ni) fp0 <- (-25*f0 +48*f1 -36*f2 +16*f3 -3*f4)/(12*hk) fp1 <- (-3*f0 -10*f1 +18*f2 -6*f3 +f4)/(12*hk) fp3 <- (-f0 +6*f1 -18*f2 +10*f3 +3*f4)/(12*hk) fp4 <- (3*f0 -16*f1 +36*f2 -48*f3 +25*f4)/(12*hk) LLkk <- (fp0 -8*fp1 +8*fp3 -fp4)/(12*hk) f0 <- LL(0, 0, 0, -2*hu, r, s, k, u, x1, x2, Ni) f1 <- LL(0, 0, 0, -hu, r, s, k, u, x1, x2, Ni) f3 <- LL(0, 0, 0, hu, r, s, k, u, x1, x2, Ni) f4 <- LL(0, 0, 0, 2*hu, r, s, k, u, x1, x2, Ni) fp0 <- (-25*f0 +48*f1 -36*f2 +16*f3 -3*f4)/(12*hu) fp1 <- (-3*f0 -10*f1 +18*f2 -6*f3 +f4)/(12*hu) fp3 <- (-f0 +6*f1 -18*f2 +10*f3 +3*f4)/(12*hu) fp4 <- (3*f0 -16*f1 +36*f2 -48*f3 +25*f4)/(12*hu) LLuu <- (fp0 -8*fp1 +8*fp3 -fp4)/(12*hu) m1 <- LL(hr, hs, 0, 0, r, s, k, u, x1, x2, Ni) m2 <- LL(-hr, hs, 0, 0, r, s, k, u, x1, x2, Ni) m3 <- LL(-hr, -hs, 0, 0, r, s, k, u, x1, x2, Ni) m4 <- LL(hr, -hs, 0, 0, r, s, k, u, x1, x2, Ni) LLrs <- (m1 -m2 +m3 -m4)/(4*hr*hs) m1 <- LL(hr, 0, 0, hu, r, s, k, u, x1, x2, Ni) m2 <- LL(-hr, 0, 0, hu, r, s, k, u, x1, x2, Ni) m3 <- LL(-hr, 0, 0, -hu, r, s, k, u, x1, x2, Ni) m4 <- LL(hr, 0, 0, -hu, r, s, k, u, x1, x2, Ni) LLru <- (m1 -m2 +m3 -m4)/(4*hr*hu) m1 <- LL(0, hs, 0, hu, r, s, k, u, x1, x2, Ni) m2 <- LL(0, -hs, 0, hu, r, s, k, u, x1, x2, Ni) m3 <- LL(0, -hs, 0, -hu, r, s, k, u, x1, x2, Ni) m4 <- LL(0, hs, 0, -hu, r, s, k, u, x1, x2, Ni) LLsu <- (m1 -m2 +m3 -m4)/(4*hu*hs) m1 <- LL(hr, 0, hk, 0, r, s, k, u, x1, x2, Ni) m2 <- LL(-hr, 0, hk, 0, r, s, k, u, x1, x2, Ni) m3 <- LL(-hr, 0, -hk, 0, r, s, k, u, x1, x2, Ni) m4 <- LL(hr, 0, -hk, 0, r, s, k, u, x1, x2, Ni) LLrk <- (m1 -m2 +m3 -m4)/(4*hr*hk) m1 <- LL(0, hs, hk, 0, r, s, k, u, x1, x2, Ni) m2 <- LL(0, -hs, hk, 0, r, s, k, u, x1, x2, Ni) m3 <- LL(0, -hs, -hk, 0, r, s, k, u, x1, x2, Ni) m4 <- LL(0, hs, -hk, 0, r, s, k, u, x1, x2, Ni) LLsk <- (m1 -m2 +m3 -m4)/(4*hs*hk) m1 <- LL(0, 0, hk, hu, r, s, k, u, x1, x2, Ni) m2 <- LL(0, 0, hk, -hu, r, s, k, u, x1, x2, Ni) m3 <- LL(0, 0, -hk, -hu, r, s, k, u, x1, x2, Ni) m4 <- LL(0, 0, -hk, hu, r, s, k, u, x1, x2, Ni) LLku <- (m1 -m2 +m3 -m4)/(4*hu*hk) diag(hess) <- c(LLrr, LLss, LLkk, LLuu)*pop hess[2, 1] = hess[1, 2] <- LLrs*pop hess[3, 1] = hess[1, 3] <- LLrk*pop hess[3, 2] = hess[2, 3] <- LLsk*pop hess[4, 1] = hess[1, 4] <- LLru*pop hess[4, 2] = hess[2, 4] <- LLsu*pop hess[4, 3] = hess[3, 4] <- LLku*pop hessInv <- solve(hess) sz <- 4 corr <- matrix(0, nrow = sz, ncol = sz) for (i in 1:sz) { for (j in 1:sz) { corr[i, j] <- hessInv[i, j]/sqrt(abs(hessInv[i, i]*hessInv[j, j])) } } if ( abs(corr[2, 1]) > .98 ) { warning("WARNING: parameters r and s appear to be closely correlated for this data set. s.e. may fail for these parameters.") } if ( sz == 4 && abs(corr[3, 2]) > .98 ) { warning("WARNING: parameters s and lambda appear to be closely correlated for this data set. s.e. may fail for these parameters.") } if ( sz == 4 && abs(corr[3, 1]) > .98 ) { warning("WARNING: parameters r and lambda appear to be closely correlated for this data set. s.e. may fail for these parameters.") } if ( sz == 4 && abs(corr[4, 2]) > .98 ) { warning("WARNING: parameters s and beta appear to be closely correlated for this data set. s.e. may fail for these parameters.") } if ( sz == 4 && abs(corr[4, 1]) > .98 ) { warning("WARNING: parameters r and beta appear to be closely correlated for this data set. s.e. may fail for these parameters.") } se <- sqrt(diag(hessInv)) if( sum( is.na(se) ) > 0 ) { seNA <- is.na(se) se12 <- sqrt(diag(solve(hess[c(1, 2) , c(1, 2) ]))) se13 <- sqrt(diag(solve(hess[c(1, 3) , c(1, 3) ]))) se23 <- sqrt(diag(solve(hess[c(2, 3) , c(2, 3) ]))) se14 <- sqrt(diag(solve(hess[c(1, 4) , c(1, 4) ]))) se24 <- sqrt(diag(solve(hess[c(2, 4) , c(2, 4) ]))) se34 <- sqrt(diag(solve(hess[c(3, 4) , c(3, 4) ]))) if(seNA[1]) { if(!is.na(se12[1]) ){ se[1] = se12[1] warning("* s.e. for parameter r is approximate.") } else if(!is.na(se13[1])){ se[1] = se13[1] warning("* s.e. for parameter r is approximate.") } else if(!is.na(se14[1])){ se[1] = se14[1] warning("* s.e. for parameter r is approximate.") } else warning("* unable to calculate or approximate s.e. for parameter r.") } if(seNA[2]) { if(!is.na(se12[2]) ){ se[2] = se12[2] warning("* s.e. for parameter s is approximate.") } else if(!is.na(se23[1])){ se[2] = se23[1] warning("* s.e. for parameter s is approximate.") } else if(!is.na(se24[1])){ se[2] = se24[1] warning("* s.e. for parameter s is approximate.") } else warning("* unable to calculate or approximate s.e. for parameter s.") } if(seNA[3]) { if(!is.na(se13[2]) ){ se[3] = se13[2] warning("* s.e. for parameter lambda is approximate.") } else if(!is.na(se23[2])){ se[3] = se23[2] warning("* s.e. for parameter lambda is approximate.") } else if(!is.na(se34[1])){ se[3] = se34[1] warning("* s.e. for parameter lambda is approximate.") } else warning("* unable to calculate or approximate s.e. for parameter lambda.") } if(seNA[4]) { if(!is.na(se14[2]) ){ se[4] = se14[2] warning("* s.e. for parameter beta is approximate.") } else if(!is.na(se24[2])){ se[4] = se24[2] warning("* s.e. for parameter beta is approximate.") } else if(!is.na(se34[1])){ se[4] = se34[2] warning("* s.e. for parameter beta is approximate.") } else warning("* unable to calculate or approximate s.e. for parameter beta.") } } return(se) } SurvFn.4p <- function(xx,r,s,lambda,beta){ yy <- s^2*xx tmp1 <- sqrt(1/yy) * (1 - xx * r) tmp2 <- sqrt(1/yy) * (1 + xx * r) tmp3 <- 2*r/(s*s) if (tmp3 > 250) { q <- tmp3/250 if (tmp3 > 1500) { q <- tmp3/500 } valueFF <-(1.-(pnorm(-tmp1) + (exp(tmp3/q) *pnorm(-tmp2)^(1/q))^(q)))*exp(-lambda*exp(-1/beta)/(r/beta)*(exp(r*xx/beta)-1)) } else { valueFF <-(1.-(pnorm(-tmp1) + exp(tmp3) *pnorm(-tmp2)))*exp(-lambda*exp(-1/beta)/(r/beta)*(exp(r*xx/beta)-1)) } if ( all(is.infinite(valueFF)) ) { warning(message="Inelegant exit caused by overflow in evaluation of survival function. Check for right-censored data. Try other initial values.") } return(valueFF) } SurvFn.h.4p <- function(xx, r, s, u){ yy <- u^2+s^2*xx tmp1 <- sqrt(1/yy) * (1 - xx * r) tmp2 <- sqrt(1/yy) * (1 + xx * r+2*u^2*r/s^2) tmp3 <- 2*r/(s*s)+2*u^2*r^2/s^4 if (tmp3 > 250) { q <- tmp3/250 if (tmp3 > 1500) { q <- tmp3/500 } valueFF <- (1.-(pnorm(-tmp1) + (exp(tmp3/q) *pnorm(-tmp2)^(1/q))^(q))) } else { valueFF <- (1.-(pnorm(-tmp1) + exp(tmp3) *pnorm(-tmp2))) } if ( all(is.infinite(valueFF)) ) { warning(message = "Inelegant exit caused by overflow in evaluation of survival function. Check for right-censored data. Try other initial values.") } return(valueFF) }
t_prog <- function(N, m, cdiagn, creg, cdist) { d0 = 0.01 dmax = 130 V0 <- pi*(d0^3)/6 Vmax <- pi*(dmax^3)/6 repeat { vdiagn <- 1000*rlnorm(N, cdiagn[1], cdiagn[2]) vreg <- 1000*rlnorm(N, cdist[1], cdist[2]) vdist <- 1000*rlnorm(N, creg[1], creg[2]) if (V0<vdiagn & vdiagn<Vmax & V0<vdist & vdist<Vmax & V0<vreg & vreg<Vmax & vreg<vdist) break } Treg <- t_vol(vreg, m) Tdist <- t_vol(vdist, m) Tdiagn <- t_vol(vdiagn, m) Ddiagn <- ((6/pi)*vdiagn)^(1/3) if (Tdiagn < Treg) {stage = "localized"} else if (Tdiagn < Tdist) {stage = "regional"} else stage = "distant" return(list("Treg"=Treg, "Tdist"=Tdist, "Tdiagn"=Tdiagn, "Ddiagn"=Ddiagn, "stage" = stage)) }
ivmodel <- function(Y,D,Z,X,intercept=TRUE, beta0=0,alpha=0.05,k=c(0,1), manyweakSE = FALSE, heteroSE = FALSE, clusterID = NULL, deltarange = NULL, na.action = na.omit) { if(missing(Y)) stop("Y is missing!") if(missing(D)) stop("D is missing!") if(missing(Z)) stop("Z is missing!") if( (!is.vector(Y) && !is.matrix(Y) && !is.data.frame(Y)) || (is.matrix(Y) && ncol(Y) != 1) || (is.data.frame(Y) && ncol(Y) != 1) || (!is.numeric(Y))) stop("Y is not a numeric vector.") if( (!is.vector(D) && !is.matrix(D) && !is.data.frame(Y)) || (is.matrix(D) && ncol(D) != 1) || (is.data.frame(D) && ncol(D) != 1) || (!is.numeric(D))) stop("D is not a numeric vector.") Y = as.numeric(Y); D = as.numeric(D) if(length(Y) != length(D)) stop("Dimension of Y and D are not the same!") Z = data.frame(Z); stringIndex = sapply(Z,is.character); Z[stringIndex] = lapply(Z[stringIndex],as.factor) if(nrow(Z) != length(Y)) stop("Row dimension of Z and Y are not equal!") colnames(Z) = paste("Z",colnames(Z),sep="") if(!missing(X)) { X = data.frame(X); stringIndex = sapply(X,is.character); X[stringIndex] = lapply(X[stringIndex],as.factor) if(nrow(X) != length(Y)) stop("Row dimension of X and Y are not equal!") colnames(X) = paste("X",colnames(X),sep="") } if(intercept && !missing(X)) { constantXTrue = apply(X,2,function(x){length(unique(x)) == 1}) if(any(constantXTrue)) { warning("Trying to add the intercept term of ones, but X already contains a constant covariate! Check your X. For now, we'll not add an intercept term in X to avoid rank deficiency.") } else { X = data.frame(X,intercept=rep(1,nrow(X))) } } if(intercept && missing(X)) X = data.frame(intercept=rep(1,length(Y))) if(!missing(X)) { allDataOrig = cbind(Y,D,Z,X) } else { allDataOrig = cbind(Y,D,Z) } if(identical(na.action, na.fail) | identical(na.action, na.omit) | identical(na.action, na.pass)){ allDataOrig = na.action(allDataOrig) naindex = rep(TRUE, nrow(allDataOrig)) naindex[apply(is.na(allDataOrig), 1, any)] = NA }else if(identical(na.action, na.exclude)){ naindex = rep(TRUE, nrow(allDataOrig)) naindex[apply(is.na(allDataOrig), 1, any)] = NA allDataOrig = na.action(allDataOrig) }else{ stop("Wrong input of NA handling!") } ff = terms(Y ~ D + . -1,data=allDataOrig) mf = model.frame(ff,allDataOrig) Y = as.matrix(mf$Y); colnames(Y) = "Y" D = as.matrix(mf$D); colnames(D) = "D" allData = sparse.model.matrix(ff,allDataOrig); attr(allData,"assign") = NULL; attr(allData,"contrasts") = NULL Zindex = grep(paste("^",colnames(Z),sep="",collapse="|"),colnames(allData)) Z = allData[,Zindex,drop=FALSE]; colnames(Z) = sub("^Z","",colnames(Z)) if(!missing(X)) { Xindex = grep(paste("^",colnames(X),sep="",collapse="|"),colnames(allData)); X = allData[,Xindex,drop=FALSE]; colnames(X) = sub("^X","",colnames(X)) } if(nrow(Y) <= 1) stop("Too much missing data!") n = length(Y) if(!missing(X)){ qrX<-qr(X) p = qrrank(qrX) if(p==0) stop("vector in X are all 0") Yadj = as.matrix(qr.resid(qrX,Y)); Dadj = as.matrix(qr.resid(qrX,D)); Zadj = as.matrix(qr.resid(qrX,Z)) ZadjQR = qr(Zadj) L = qrrank(ZadjQR) if(L==0) stop("No useful instrumental variables") if(L==1) { Zadj = qr.Q(ZadjQR)[, 1:L] * as.numeric(qrRM(ZadjQR)[1:L,1:L]) } if(L<ncol(Z) && L> 1){ Zadj<-qr.Q(ZadjQR)[, 1:L]%*%qrRM(ZadjQR)[1:L, 1:L] } ZXQR = qr(cbind(Z,X)) ivmodelObject = list(call = match.call(),n=n,L=L,p=p,Y=Y,D=D,Z=Z,X=X,ZXQR=ZXQR,Yadj=Yadj,Dadj=Dadj,Zadj=Zadj, ZadjQR = ZadjQR) }else{ p = 0 Yadj = Y; Dadj = D; Zadj = as.matrix(Z) ZadjQR = qr(Zadj) L = qrrank(ZadjQR) if(L==0) stop("No useful instrumental variables") if(L == 1) { Z <- Zadj <-qr.Q(ZadjQR)[, 1:L] * as.numeric(qrRM(ZadjQR)[1:L, 1:L]) } if(L<ncol(Z) && L > 1) Z<-Zadj<-qr.Q(ZadjQR)[, 1:L]%*%qrRM(ZadjQR)[1:L, 1:L] ZXQR = qr(Z) ivmodelObject = list(call = match.call(),n=n,L=L,p=p,Y=Y,D=D,Z=Z,X=NA,ZXQR=ZXQR,Yadj=Yadj,Dadj=Dadj,Zadj=Zadj, ZadjQR = ZadjQR) } class(ivmodelObject) = "ivmodel" ivmodelObject$naindex = naindex ivmodelObject$alpha = alpha ivmodelObject$beta0 = beta0 ivmodelObject$deltarange = deltarange ivmodelObject$AR = AR.test(ivmodelObject,beta0=beta0,alpha=alpha) ivmodelObject$ARsens = ARsens.test(ivmodelObject,beta0=beta0,alpha=alpha,deltarange=deltarange) ivmodelObject$kClass = KClass(ivmodelObject,beta0=beta0,alpha=alpha,k=k,heteroSE=heteroSE,clusterID=clusterID) ivmodelObject$LIML = LIML(ivmodelObject,beta0=beta0,alpha=alpha,manyweakSE=manyweakSE,heteroSE=heteroSE,clusterID=clusterID) ivmodelObject$Fuller = Fuller(ivmodelObject,beta0=beta0,alpha=alpha,manyweakSE=manyweakSE,heteroSE=heteroSE,clusterID=clusterID) ivmodelObject$CLR = CLR(ivmodelObject,beta0=beta0,alpha=alpha) return(ivmodelObject) }
orderscoreBase<-function(n,scorenodes,scorepositions,parenttable,aliases,numparents,rowmaps, scoretable,scoresmatrices,permy) { orderscores<-vector("double",n) therows<-vector("integer",n) k<-1 for (i in scorenodes){ position<-scorepositions[k] if (position==n) { orderscores[i]<-scoretable[[i]][1,1] therows[i]<-c(2^numparents[i]) } else { bannednodes<-permy[1:position] allowednodes<-permy[(position+1):n] bannedpool<-which(aliases[[i]]%in%bannednodes) if (numparents[i]==0||length(bannedpool)==0) { therows[i]<-c(1) } else { therows[i]<-rowmaps[[i]]$backwards[sum(2^bannedpool)/2+1] } orderscores[i]<-scoresmatrices[[i]][therows[i],1] } k<-k+1 } scores<-list() scores$therow<-therows scores$totscores<-orderscores return(scores) } orderscorePlus1<-function(n,scorenodes,scorepositions,parenttable,aliases,numparents, rowmaps,plus1lists,scoretable,scoresmatrices,permy) { orderscores<-vector("double",n) allowedscorelists<-vector("list",n) therows<-vector("integer",n) k<-1 for (i in scorenodes){ position<-scorepositions[k] if (position==n) { orderscores[i]<-scoretable[[i]][[1]][1,1] allowedscorelists[[i]]<-c(1) therows[i]<-c(2^numparents[i]) } else { bannednodes<-permy[1:position] allowednodes<-permy[(position+1):n] bannedpool<-which(aliases[[i]]%in%bannednodes) if (numparents[i]==0||length(bannedpool)==0) { therows[i]<-c(1) } else { therows[i]<-rowmaps[[i]]$backwards[sum(2^bannedpool)/2+1] } allowedscorelists[[i]]<-c(1,which(plus1lists$parents[[i]]%in%allowednodes)+1) scoresvec<-scoresmatrices[[i]][therows[i],allowedscorelists[[i]]] maxallowed<-max(scoresvec) orderscores[i]<-maxallowed+log(sum(exp(scoresvec-maxallowed))) } k<-k+1 } scores<-list() scores$therow<-therows scores$allowedlists<-allowedscorelists scores$totscores<-orderscores return(scores) } positionscorePlus1<-function(n,nsmall,currentscore,positionx,permy,aliases,rowmaps,plus1lists,numparents, scoretable,scoresmatrices) { vectorx<-vector(length=nsmall) vectorall<-vector(length=nsmall) base<-currentscore$totscores totalall<-vector(length=nsmall) totalall[positionx]<-sum(base) x<-permy[positionx] vectorx[positionx]<-base[x] allowedlistx<-list() allowedlisty<-list() therowx<-vector() therowy<-vector() if (positionx>1) { rightpart<-permy[-positionx] for (i in (positionx-1):1) { nodey<-permy[i] if (numparents[x]==0||i==1) { therowx[i]<-c(1) } else { bannedpool<-which(aliases[[x]]%in%permy[1:(i-1)]) if (length(bannedpool)==0) { therowx[i]<-c(1) } else { therowx[i]<-rowmaps[[x]]$backwards[sum(2^bannedpool)/2+1] } } allowedlistx[[i]]<-c(1,which(plus1lists$parents[[x]]%in%c(permy[(i+1):n],nodey))+1) scoresvec<-scoresmatrices[[x]][therowx[i],allowedlistx[[i]]] maxallowed<-max(scoresvec) vectorx[i]<-maxallowed+log(sum(exp(scoresvec-maxallowed))) newpos<-i+1 if(newpos==n) { vectorall[nodey]<-scoretable[[nodey]][[1]][1,1] allowedlisty[[nodey]]<-c(1) therowy[nodey]<-c(2^numparents[nodey]) } else { bannedpool<-which(aliases[[nodey]]%in%c(permy[1:(i-1)],x)) if (numparents[nodey]==0||length(bannedpool)==0) { therowy[nodey]<-c(1) } else { therowy[nodey]<-rowmaps[[nodey]]$backwards[sum(2^bannedpool)/2+1] } if (newpos==n) {allowedlisty[[nodey]]<-c(1)} else { allowedlisty[[nodey]]<-c(1,which(plus1lists$parents[[nodey]]%in%rightpart[(newpos):(n-1)])+1) } scoresvec<-scoresmatrices[[nodey]][therowy[nodey],allowedlisty[[nodey]]] maxallowed<-max(scoresvec) vectorall[nodey]<-maxallowed+log(sum(exp(scoresvec-maxallowed))) } totalall[i]<-totalall[i+1]-vectorx[i+1]+vectorx[i]-base[nodey]+vectorall[nodey] } } if (positionx < nsmall) { for (i in (positionx+1):nsmall) { nodey<-permy[i] if (numparents[x]==0) { therowx[i]<-c(1) } else if (i==n) { vectorall[x]<-scoretable[[x]][[1]][1,1] therowx[i]<-c(2^numparents[x]) } else { bannedpool<-which(aliases[[x]]%in%permy[1:i]) if (length(bannedpool)==0) { therowx[i]<-c(1) } else { therowx[i]<-rowmaps[[x]]$backwards[sum(2^bannedpool)/2+1] } } if (i==n) { allowedlistx[[i]]<-c(1)} else { allowedlistx[[i]]<-c(1,which(plus1lists$parents[[x]]%in%permy[(i+1):n])+1) } scoresvec<-scoresmatrices[[x]][therowx[i],allowedlistx[[i]]] maxallowed<-max(scoresvec) vectorx[i]<-maxallowed+log(sum(exp(scoresvec-maxallowed))) newpos<-i-1 if (newpos==1) { therowy[nodey]<-c(1) } else { bannedpool<-which(aliases[[nodey]]%in%((permy[1:newpos])[-positionx])) if (numparents[nodey]==0||length(bannedpool)==0) { therowy[nodey]<-c(1) } else { therowy[nodey]<-rowmaps[[nodey]]$backwards[sum(2^bannedpool)/2+1] } } allowedlisty[[nodey]]<-c(1,which(plus1lists$parents[[nodey]]%in%c(permy[i:n],x))+1) scoresvec<-scoresmatrices[[nodey]][therowy[nodey],allowedlisty[[nodey]]] maxallowed<-max(scoresvec) vectorall[nodey]<-maxallowed+log(sum(exp(scoresvec-maxallowed))) totalall[i]<-totalall[i-1]-vectorx[i-1]+vectorx[i]-base[nodey]+vectorall[nodey] } } totalmax<-max(totalall) allscore<-totalmax+log(sum(exp(totalall-totalmax))) maxi<-sample.int(nsmall,1,prob=exp(totalall-allscore)) res<-list() if (maxi==positionx) { res$score<-currentscore res$order<-permy res$tot<-totalall[positionx] return(res) } else if (maxi>positionx) { newscore<-currentscore newscore$therow[x]<-therowx[maxi] newscore$allowedlists[[x]]<-allowedlistx[[maxi]] newscore$totscores[x]<-vectorx[maxi] updatenodes<-permy[(positionx+1):maxi] newscore$therow[updatenodes]<-therowy[updatenodes] newscore$allowedlists[updatenodes]<-allowedlisty[updatenodes] newscore$totscores[updatenodes]<-vectorall[updatenodes] res$score<-newscore res$order<-movenode(permy,positionx,maxi,n) res$tot<-totalall[maxi] return(res) } else { newscore<-currentscore newscore$therow[x]<-therowx[maxi] newscore$allowedlists[[x]]<-allowedlistx[[maxi]] newscore$totscores[x]<-vectorx[maxi] updatenodes<-permy[maxi:(positionx-1)] newscore$therow[updatenodes]<-therowy[updatenodes] newscore$allowedlists[updatenodes]<-allowedlisty[updatenodes] newscore$totscores[updatenodes]<-vectorall[updatenodes] res$score<-newscore res$order<-movenode(permy,positionx,maxi,n) res$tot<-totalall[maxi] return(res) } } positionscorebase<-function(n,nsmall,currentscore,positionx,permy,aliases,rowmaps,numparents, scoretable,scoresmatrices) { vectorx<-vector(length=nsmall) vectorall<-vector(length=nsmall) base<-currentscore$totscores totalall<-vector(length=nsmall) totalall[positionx]<-sum(base) x<-permy[positionx] vectorx[positionx]<-base[x] therowx<-vector() therowy<-vector() if (positionx>1) { rightpart<-permy[-positionx] for (i in (positionx-1):1) { nodey<-permy[i] if (numparents[x]==0||i==1) { therowx[i]<-c(1) } else { bannedpool<-which(aliases[[x]]%in%permy[1:(i-1)]) if (length(bannedpool)==0) { therowx[i]<-c(1) } else { therowx[i]<-rowmaps[[x]]$backwards[sum(2^bannedpool)/2+1] } } scoresvec<-scoresmatrices[[x]][therowx[i],1] maxallowed<-max(scoresvec) vectorx[i]<-maxallowed+log(sum(exp(scoresvec-maxallowed))) newpos<-i+1 if(newpos==n) { vectorall[nodey]<-scoretable[[nodey]][1,1] therowy[nodey]<-c(2^numparents[nodey]) } else { bannedpool<-which(aliases[[nodey]]%in%c(permy[1:(i-1)],x)) if (numparents[nodey]==0||length(bannedpool)==0) { therowy[nodey]<-c(1) } else { therowy[nodey]<-rowmaps[[nodey]]$backwards[sum(2^bannedpool)/2+1] } scoresvec<-scoresmatrices[[nodey]][therowy[nodey],1] maxallowed<-max(scoresvec) vectorall[nodey]<-maxallowed+log(sum(exp(scoresvec-maxallowed))) } totalall[i]<-totalall[i+1]-vectorx[i+1]+vectorx[i]-base[nodey]+vectorall[nodey] } } if (positionx < nsmall) { for (i in (positionx+1):nsmall) { nodey<-permy[i] if (numparents[x]==0) { therowx[i]<-c(1) } else if (i==n) { vectorall[x]<-scoretable[[x]][1,1] therowx[i]<-c(2^numparents[x]) } else { bannedpool<-which(aliases[[x]]%in%permy[1:i]) if (length(bannedpool)==0) { therowx[i]<-c(1) } else { therowx[i]<-rowmaps[[x]]$backwards[sum(2^bannedpool)/2+1] } } scoresvec<-scoresmatrices[[x]][therowx[i],1] maxallowed<-max(scoresvec) vectorx[i]<-maxallowed+log(sum(exp(scoresvec-maxallowed))) newpos<-i-1 if (newpos==1) { therowy[nodey]<-c(1) } else { bannedpool<-which(aliases[[nodey]]%in%((permy[1:newpos])[-positionx])) if (numparents[nodey]==0||length(bannedpool)==0) { therowy[nodey]<-c(1) } else { therowy[nodey]<-rowmaps[[nodey]]$backwards[sum(2^bannedpool)/2+1] } } scoresvec<-scoresmatrices[[nodey]][therowy[nodey],1] maxallowed<-max(scoresvec) vectorall[nodey]<-maxallowed+log(sum(exp(scoresvec-maxallowed))) totalall[i]<-totalall[i-1]-vectorx[i-1]+vectorx[i]-base[nodey]+vectorall[nodey] } } totalmax<-max(totalall) allscore<-totalmax+log(sum(exp(totalall-totalmax))) maxi<-sample.int(nsmall,1,prob=exp(totalall-allscore)) res<-list() if (maxi==positionx) { res$score<-currentscore res$order<-permy res$tot<-totalall[positionx] return(res) } else if (maxi>positionx) { newscore<-currentscore newscore$therow[x]<-therowx[maxi] newscore$totscores[x]<-vectorx[maxi] updatenodes<-permy[(positionx+1):maxi] newscore$therow[updatenodes]<-therowy[updatenodes] newscore$totscores[updatenodes]<-vectorall[updatenodes] res$score<-newscore res$order<-movenode(permy,positionx,maxi,n) res$tot<-totalall[maxi] return(res) } else { newscore<-currentscore newscore$therow[x]<-therowx[maxi] newscore$totscores[x]<-vectorx[maxi] updatenodes<-permy[maxi:(positionx-1)] newscore$therow[updatenodes]<-therowy[updatenodes] newscore$totscores[updatenodes]<-vectorall[updatenodes] res$score<-newscore res$order<-movenode(permy,positionx,maxi,n) res$tot<-totalall[maxi] return(res) } }
bcdcor <- function(x, y) { dcorU(x, y) } dcovU <- function(x, y) { if (!inherits(x, "dist")) x <- dist(x) if (!inherits(y, "dist")) y <- dist(y) x <- as.matrix(x) y <- as.matrix(y) n <- nrow(x) m <- nrow(y) if (n != m) stop("sample sizes must agree") if (! (all(is.finite(c(x, y))))) stop("data contains missing or infinite values") estimates <- dcovU_stats(x, y) return (estimates[1]) } dcorU <- function(x, y) { if (!inherits(x, "dist")) x <- dist(x) if (!inherits(y, "dist")) y <- dist(y) x <- as.matrix(x) y <- as.matrix(y) n <- nrow(x) m <- nrow(y) if (n != m) stop("sample sizes must agree") if (! (all(is.finite(c(x, y))))) stop("data contains missing or infinite values") estimates <- dcovU_stats(x, y) return (estimates[2]) }