code
stringlengths
1
13.8M
wordStem <- function(words, language = "porter") { words <- as.character(words) language <- as.character(language[1]) .Call("R_stemWords", words, language, PACKAGE="SnowballC") } getStemLanguages <- function() { .Call("R_getStemLanguages", PACKAGE="SnowballC") }
indexSpec <- function( files, noise="/volumes/AAO/nhm-unp-1/_noise.wav", wl=256 ){ sf <-normalize(readWave(files[1])) s <- spectro(sf, [email protected], plot=FALSE, wl=wl) bins <- length(s$freq) nw <- readWave(noise) ns <- meanspec(nw, [email protected], plot=FALSE, wl=wl) aci <- entropy <- power <- matrix(, ncol=bins, nrow = length(files)) for (i in 1:length(files)) { print(i) wave <- normalize(readWave(files[i])) spec <- spectro(wave, plot=FALSE, wl=wl) for (j in 1:bins) { spec$amp[,j] <- spec$amp[,j] - ns[,2] } power[i,] <- rowMeans(spec$amp^2) aci_t <- entropy_t <- vector(mode="numeric", length=bins) for (j in 1:bins) { aci_t[j] <- sum(abs(spec$amp[j,] - rev(spec$amp[j,])))/abs(sum(spec$amp[j,])) entropy_t[j] <- entropy(spec$amp[,j]) } aci[i,] <- aci_t entropy[i,] <- entropy_t } power_s <- power/max(unlist(power)) aci_s <- aci/max(unlist(aci)) entropy_s <- entropy(max(unlist(entropy))) fcis_data <- rgb(power_s, aci_s, entropy_s) dim(fcis_data) <- dim (power_s) ret = list(power=power, aci=aci, entropy=entropy, fcis_data=t(fcis_data)) return(ret) }
knitr::opts_chunk$set( collapse = TRUE, comment = " ) library(mets) library(mets) options(warn=-1) set.seed(1000) n <- 1000 k <- 5 theta <- 2 data <- simClaytonOakes(n,k,theta,0.3,3) out <- phreg(Surv(time,status)~x+cluster(cluster),data=data) summary(out) rob <- robust.phreg(out) betaiid <- iid(out) head(betaiid) crossprod(betaiid)^.5 bplot(rob,se=TRUE,robust=TRUE,col=3) pp <- predict(out,data[1:20,],se=TRUE,robust=TRUE) plot(pp,se=TRUE,whichx=1:10) tt <- twostageMLE(out,data=data) summary(tt) gout <- gof(out) gout plot(gout) out <- phreg(Surv(time,status)~x+strata(cluster),data=data) summary(out) sessionInfo()
CreateHypotMatrix <- function(modularity.hypot){ if(is.null(dim(modularity.hypot))) return(outer(modularity.hypot, modularity.hypot)) num.hyp <- dim (modularity.hypot) [2] num.traits <- dim (modularity.hypot) [1] m.hyp.list <- alply(modularity.hypot, 2, function(x) outer(x, x)) m.hyp.list[[num.hyp+1]] <- matrix(as.integer (as.logical (Reduce ("+", m.hyp.list[1:num.hyp]))), num.traits, num.traits, byrow=T) return(m.hyp.list[1:(num.hyp+1)]) } CombineHypot <- function(modularity.hypot){ n.hypots = dim(modularity.hypot)[2] if(is.null(n.hypots)) { cor.hypot = CreateHypotMatrix(modularity.hypot) diag(cor.hypot) <- 1 return(cor.hypot) } if(is.null(colnames(modularity.hypot))) colnames(modularity.hypot) <- 1:n.hypots counter = BinToDec(rep(1, n.hypots)) hypot_list = list(null = diag(dim(modularity.hypot)[1])) k = 2 for(i in seq(counter)){ mask = DecToBin(i) mask = as.logical(as.numeric((mask[(32-(n.hypots-1)):32]))) if(sum(mask) > 1) new_hypot = CreateHypotMatrix(modularity.hypot[,mask])[[sum(mask)+1]] else new_hypot = CreateHypotMatrix(modularity.hypot[,mask]) diag(new_hypot) <- 1 if(!any(laply(hypot_list, function(x) all(x == new_hypot)))){ hypot_list[[k]] = new_hypot names(hypot_list)[[k]] <- paste(colnames(modularity.hypot)[mask], collapse = "_") k = k + 1 } } hypot_list } Partition2HypotMatrix <- function(x){ sapply(unique(x), function(i) as.numeric(x == i)) } BinToDec <- function(x) sum(2^(which(rev(unlist(strsplit(as.character(x), "")) == 1))-1)) DecToBin <- function(x) sapply(strsplit(paste(rev(intToBits(x))),""),`[[`,2)
get_hitchip_taxonomy <- function(chip, phylogeny.version = "full", data.dir = NULL) { hitchip.taxonomy <- NULL if (is.null(data.dir)) { data.dir <- system.file("extdata", package = "microbiome") } if (chip == "HITChip") { load(system.file("data/hitchip.taxonomy.rda", package = "microbiome")) tax.table <- hitchip.taxonomy[[phylogeny.version]] } else { message(paste("get_hitchip_taxonomy not implemented for", chip)) tax.table <- NULL } df <- as.data.frame(tax.table) df }
Hilbert <- function(n) { n <- as.integer(n) i <- seq_len(n) new("dpoMatrix", x = c(1/outer(i - 1L, i, "+")), Dim = c(n,n)) }
summary.lefkoCondMat <- function(object, ...) { histmatrices <- object$Mcond condmatrices <- histmatrices[[1]] firstcondmat <- condmatrices[[1]] numhistmats <- length(histmatrices) prevstages <- length(condmatrices) matdim <- dim(firstcondmat) writeLines(paste0("\nThis lefkoCondMat object contains ", prevstages, " conditional matrices per historical matrix,")) writeLines(paste0("It covers ", numhistmats, " main historical matrices.")) writeLines(paste0("Each conditional matrix is a square matrix with ", matdim[1], " rows and columns, and a total of ", matdim[1]*matdim[1], " elements.")) writeLines(paste0("\nThe order of conditional matrices corresponding to stage in occasion t-1 is:\n", paste(object$ahstages$stage, collapse = " "))) writeLines("\nThe order of historical matrices is: \n") print.data.frame(object$labels) writeLines("\nThe order of conditional matrices matches the stage column in object $ahstages.") writeLines("The order of historical matrices follows that shown in object $labels.") } image3 <- function(mats, ...) UseMethod("image3") image3.lefkoMat <- function(mats, used = "all", type = "A", ...) { allmats <- c(1:length(mats$A)) if (!is.character(type)) { stop("Please enter A, F, or U for type option.", call. = FALSE) } type <- tolower(type) if (!is.element(type, c("a", "u", "f"))) { stop("Please enter A, F, or U for type option.", call. = FALSE) } if (all(is.character(used))) { if (all(tolower(used) != "all")) { stop("Value entered for matrix option not recognized.", call. = FALSE) } else { chosen_mat <- allmats } } else if (is.numeric(used) & is.element(used, allmats)) { chosen_mat <- used } else { stop("Value entered for matrix option not recognized.", call. = FALSE) } if (type == "u") { chosen_list <- mats$U[chosen_mat] } else if (type == "f") { chosen_list <- mats$F[chosen_mat] } else { chosen_list <- mats$A[chosen_mat] } lapply(chosen_list, function(X) {SparseM::image(SparseM::as.matrix.csr(X), col =c("white", "red"))}) } image3.matrix <- function(mats, ...) { SparseM::image(SparseM::as.matrix.csr(mats), col =c("white", "red")) } image3.list <- function(mats, used = "all", ...) { allmats <- c(1:length(mats)) if (all(is.character(used))) { if (all(tolower(used) != "all")) { stop("Value entered for matrix option not recognized.", call. = FALSE) } else { chosen_mat <- allmats } } else if (is.numeric(used) & is.element(used, allmats)) { chosen_mat <- used } else { stop("Value entered for matrix option not recognized.", call. = FALSE) } chosen_list <- mats[chosen_mat] lapply(chosen_list, function(X) { if (!is.matrix(X)) { stop("Chosen elements include non-matrix objects. Please choose only list elements containing matrix objects.", call. = FALSE) } SparseM::image(SparseM::as.matrix.csr(X), col =c("white", "red"))} ) } image3.lefkoSens <- function(mats, used = "all", type = "a", ...) { allahmats <- c(1:length(mats$ah_sensmats)) allhmats <- c(1:length(mats$h_sensmats)) allmats <- c(1:max(c(allahmats, allhmats))) if (!is.character(type)) { stop("Please enter a or h for type option.", call. = FALSE) } type <- tolower(type) if (!is.element(type, c("a", "h"))) { stop("Please enter a or h for type option.", call. = FALSE) } if (all(is.character(used))) { if (all(tolower(used) != "all")) { stop("Value entered for matrix option not recognized.", call. = FALSE) } else { chosen_mat <- allmats } } else if (is.numeric(used) & is.element(used, allmats)) { chosen_mat <- used } else { stop("Value entered for matrix option not recognized.", call. = FALSE) } if (type == "h") { if (any(is.null(mats$h_sensmats))) { stop("This object does not appear to have historical sensitivity matrices. Please try ahistorical option.", call. = FALSE) } chosen_list <- mats$h_sensmats[chosen_mat] } else { if (any(is.null(mats$ah_sensmats))) { warning("This object does not appear to have ahistorical sensitivity matrices. Will use historical sensitivity matrices instead.", call. = FALSE) chosen_list <- mats$h_sensmats[chosen_mat] } else { chosen_list <- mats$ah_sensmats[chosen_mat] } } lapply(chosen_list, function(X) {SparseM::image(SparseM::as.matrix.csr(X), col =c("white", "red"))}) } image3.lefkoElas <- function(mats, used = "all", type = "a", ...) { allahmats <- c(1:length(mats$ah_elasmats)) allhmats <- c(1:length(mats$h_elasmats)) allmats <- c(1:max(c(allahmats, allhmats))) if (!is.character(type)) { stop("Please enter a or h for type option.", call. = FALSE) } type <- tolower(type) if (!is.element(type, c("a", "h"))) { stop("Please enter a or h for type option.", call. = FALSE) } if (all(is.character(used))) { if (all(tolower(used) != "all")) { stop("Value entered for matrix option not recognized.", call. = FALSE) } else { chosen_mat <- allmats } } else if (is.numeric(used) & is.element(used, allmats)) { chosen_mat <- used } else { stop("Value entered for matrix option not recognized.", call. = FALSE) } if (type == "h") { if (any(is.null(mats$h_elasmats))) { stop("This object does not appear to have historical sensitivity matrices. Please try ahistorical option.", call. = FALSE) } chosen_list <- mats$h_elasmats[chosen_mat] } else { if (any(is.null(mats$ah_elasmats))) { warning("This object does not appear to have ahistorical sensitivity matrices. Will use historical sensitivity matrices instead.", call. = FALSE) chosen_list <- mats$h_elasmats[chosen_mat] } else { chosen_list <- mats$ah_elasmats[chosen_mat] } } lapply(chosen_list, function(X) {SparseM::image(SparseM::as.matrix.csr(X), col =c("white", "red"))}) } diff_lM <- function(mpm1, mpm2) { if (is.null(mpm1) | is.null(mpm2)) { stop("Function diff_lM() requires two lefkoMat objects as input.", call. = FALSE) } else if (all(is.na(mpm1)) | all(is.na(mpm2))) { stop("Function diff_lM() requires two lefkoMat objects as input.", call. = FALSE) } if (class(mpm1) != "lefkoMat" | class(mpm2) != "lefkoMat") { stop("Function diff_lM() requires two lefkoMat objects as input.", call. = FALSE) } if (length(mpm1$A) != length(mpm2$A)) { stop("Objects mpm1 and mpm2 must have the same number of matrices.", call. = FALSE) } if (dim(mpm1$A[[1]])[1] != dim(mpm2$A[[1]])[1]) { stop("Objects mpm1 and mpm2 must include matrices of the same dimensions.", call. = FALSE) } new_diffs_A <- lapply(c(1:length(mpm1$A)), function(X) { newmat <- mpm1$A[[X]] - mpm2$A[[X]] return(newmat) }) new_diffs_U <- lapply(c(1:length(mpm1$A)), function(X) { newmat <- mpm1$U[[X]] - mpm2$U[[X]] return(newmat) }) new_diffs_F <- lapply(c(1:length(mpm1$A)), function(X) { newmat <- mpm1$F[[X]] - mpm2$F[[X]] return(newmat) }) if (any((mpm1$labels$year2 - mpm2$labels$year2) != 0)) { warning("Input lefkoMat objects have seemingly different labels objects.", call. = FALSE) } output <- list(A = new_diffs_A, U = new_diffs_U, F = new_diffs_F, hstages1 = mpm1$hstages, hstages2 = mpm2$hstages, ahstages1 = mpm1$ahstages, ahstages2 = mpm2$ahstages, labels1 = mpm1$labels, labels2 = mpm2$labels) class(output) <- "lefkoDiff" return(output) }
as.data.frame.sscurves <- function(x, row.names = NULL, optional = FALSE, raw_curves = NULL, ...) { arglist <- .get_dataframe_arglist(attr(x, "args"), def_raw_curves = TRUE, ...) .dataframe_common(x, raw_curves = arglist[["raw_curves"]], ...) } as.data.frame.mscurves <- function(x, row.names = NULL, optional = FALSE, raw_curves = NULL, ...) { arglist <- .get_dataframe_arglist(attr(x, "args"), def_raw_curves = TRUE, ...) .dataframe_common(x, raw_curves = arglist[["raw_curves"]], ...) } as.data.frame.smcurves <- function(x, row.names = NULL, optional = FALSE, raw_curves = NULL, ...) { arglist <- .get_dataframe_arglist(attr(x, "args"), def_raw_curves = raw_curves, ...) .dataframe_common(x, raw_curves = arglist[["raw_curves"]], ...) } as.data.frame.mmcurves <- function(x, row.names = NULL, optional = FALSE, raw_curves = NULL, ...) { arglist <- .get_dataframe_arglist(attr(x, "args"), def_raw_curves = raw_curves, ...) .dataframe_common(x, raw_curves = arglist[["raw_curves"]], ...) } as.data.frame.sspoints <- function(x, row.names = NULL, optional = FALSE, raw_curves = NULL, ...) { arglist <- .get_dataframe_arglist(attr(x, "args"), def_raw_curves = TRUE, ...) .dataframe_common(x, mode = "basic", raw_curves = arglist[["raw_curves"]], ...) } as.data.frame.mspoints <- function(x, row.names = NULL, optional = FALSE, raw_curves = NULL, ...) { arglist <- .get_dataframe_arglist(attr(x, "args"), def_raw_curves = TRUE, ...) .dataframe_common(x, mode = "basic", raw_curves = arglist[["raw_curves"]], ...) } as.data.frame.smpoints <- function(x, row.names = NULL, optional = FALSE, raw_curves = NULL, ...) { arglist <- .get_dataframe_arglist(attr(x, "args"), def_raw_curves = raw_curves, ...) .dataframe_common(x, mode = "basic", raw_curves = arglist[["raw_curves"]], ...) } as.data.frame.mmpoints <- function(x, row.names = NULL, optional = FALSE, raw_curves = NULL, ...) { arglist <- .get_dataframe_arglist(attr(x, "args"), def_raw_curves = raw_curves, ...) .dataframe_common(x, mode = "basic", raw_curves = arglist[["raw_curves"]], ...) } as.data.frame.aucroc <- function(x, row.names = NULL, optional = FALSE, ...) { x$uaucs }
context("formulas") test_that("add_predictors() combines predictors", { expect_identical(add_predictors(~1, ~2, ~3), ~1 + 2 + 3) }) test_that("add_predictors() combines with fun", { expect_identical(add_predictors(~1, ~2, ~3, fun = "*"), ~1 * 2 * 3) }) test_that("add_predictors() handles lhss", { expect_identical(add_predictors(lhs ~ 1, ~2), lhs ~ 1 + 2) expect_identical(add_predictors(lhs1 ~ 1, lhs2 ~ 2), lhs1 ~ 1 + 2) }) test_that("merge_formula() handles lhss", { expect_identical(merge_formulas(lhs ~ rhs, lhs ~ rhs), lhs ~ rhs + rhs) expect_error(merge_formulas(lhs ~ rhs, other_lhs ~ rhs), "must be identical") }) test_that("merging formulas fail when scope conflicts within symbols", { env <- new.env(parent = emptyenv()) env$object <- list() object <- list() f_conflict <- new_formula(NULL, quote(object), env = env) expect_error(merge_envs(~object, f_conflict), "conflict for the symbol 'object'") }) test_that("merging formulas fail when scope conflicts between symbols", { env1 <- new.env(parent = emptyenv()) env1$object <- list() env2 <- new.env(parent = emptyenv()) env2$other_object <- list() f1 <- new_formula(NULL, quote(list(object)), env = env1) f2 <- new_formula(NULL, quote(list(other_object)), env = env2) expect_error(merge_envs(f1, f2), "conflict across symbols") }) test_that("formulas() fails when supplied non-formula objects", { expect_error(formulas(~lhs, NULL), "must contain only formulas") }) test_that("formulas() combines the lhs", { expect_equal(formulas(~lhs, a = ~1, b = other ~ 2), list(a = lhs ~ 1, b = lhs ~ 2)) }) test_that("bytecoded fit_with() works", { bc_fit_with <- compiler::cmpfun(fit_with) fit <- bc_fit_with(mtcars, lm, list(disp ~ drat)) expect_is(fit[[1]], "lm") })
mapcurves_calc = function(x, y, x_name, y_name, precision = NULL){ UseMethod("mapcurves_calc") } mapcurves_calc.sf = function(x, y, x_name, y_name, precision = NULL){ stopifnot(inherits(st_geometry(x), "sfc_POLYGON") || inherits(st_geometry(x), "sfc_MULTIPOLYGON")) stopifnot(inherits(st_geometry(y), "sfc_POLYGON") || inherits(st_geometry(y), "sfc_MULTIPOLYGON")) stopifnot(st_crs(x) == st_crs(y) || !all(is.na(st_crs(x)), is.na(st_crs(y)))) x_name = enquo(x_name) y_name = enquo(y_name) x = select(x, map1 := !!x_name) x = mutate_if(x, is.factor, as.character) x = mutate_if(x, is.numeric, as.character) suppressWarnings({x = st_cast(x, "POLYGON")}) y = select(y, map2 := !!y_name) y = mutate_if(y, is.factor, as.character) y = mutate_if(y, is.numeric, as.character) suppressWarnings({y = st_cast(y, "POLYGON")}) if(!is.null(precision)){ x = st_set_precision(x, precision) y = st_set_precision(y, precision) } suppressWarnings({z = st_intersection(x, y)}) z = st_collection_extract(z) z_df = intersection_prep(z) z = z_df^2 / tcrossprod(rowSums(z_df), colSums(z_df)) mapcurves_result = mapcurves(z = z) result = list(map1 = x, map2 = y, ref_map = mapcurves_result$ref_map, gof = mapcurves_result$gof) class(result) = c("mapcurves_vector") return(result) } mapcurves_calc.stars = function(x, y, x_name = NULL, y_name = NULL, precision = NULL){ mapcurves_calc(methods::as(x, "Raster"), methods::as(y, "Raster"), x_name = x_name, y_name = y_name, precision = precision) } mapcurves_calc.SpatRaster = function(x, y, x_name = NULL, y_name = NULL, precision = NULL){ mapcurves_calc(methods::as(x, "Raster"), methods::as(y, "Raster"), x_name = x_name, y_name = y_name, precision = precision) } mapcurves_calc.RasterLayer = function(x, y, x_name = NULL, y_name = NULL, precision = NULL){ stopifnot(inherits(x, "RasterLayer")) stopifnot(inherits(y, "RasterLayer")) z = stack(x, y) z_df = t(crosstab(z)) z = z_df^2 / tcrossprod(rowSums(z_df), colSums(z_df)) mapcurves_result = mapcurves(z = z) result = list(map1 = x, map2 = y, ref_map = mapcurves_result$ref_map, gof = mapcurves_result$gof) class(result) = c("mapcurves_vector") return(result) } format.mapcurves_vector = function(x, ...){ paste("The MapCurves results:\n\n", "The goodness of fit:", round(x$gof, 2), "\n", "Reference map:", x$ref_map, "\n\n", "The spatial objects can be retrieved with:\n", "$map1", "- the first map\n", "$map2", "- the second map") } print.mapcurves_vector = function(x, ...){ cat(format(x, ...), "\n") }
plot.spFSR <- function(x, errorBar = FALSE, annotateBest = FALSE, se = FALSE, ...){ if( !inherits(x, 'spFSR') ){ stop('Not a spFSR object.') } stopifnot( is.logical(errorBar) ) stopifnot( is.logical(annotateBest) ) stopifnot( is.logical(se) ) Values <- x$iter.results$values Iterations <- c( 1:length(Values) ) if( !errorBar ){ plot(Iterations, Values, ...) }else{ sdev <- x$iter.results$stds if(se){ sdev <- sdev/sqrt( length(x$iter.results$importances[[1]]) ) } upper <- Values + sdev lower <- Values - sdev plot(Iterations, Values, ylim = c( min(lower), max(upper) ), ...) arrows(x0 = Iterations, y0 = lower, y1 = upper, code = 0) points(lower, pch = '-', cex = 1.5, col = 'red') points(upper, pch = '-', cex = 1.5, col = 'red') } if( annotateBest ){ if( x$measure$minimize ){ v <- which.min(Values) h <- min(Values) }else{ v <- which.max(Values) h <- max(Values) } abline( v = v, lty = 'dashed' ) abline( h = h, lty = 'dashed') } }
prepare_sizeDist <- function( size_dist = NULL, sp_names = c('Fagus sylvatica', 'Pinus sylvestris') ){ if( any( is.null(sp_names), is.na(sp_names), length(sp_names)==0L) ){ stop( 'sp_names must be provided according to the species table.' ) } size_dist_out = sizeDist.default['parameter'] size_dist_out[sp_names] <- NA_real_ size_dist_out[sp_names] <- as.numeric( sizeDist.default$default ) if( !is.null(size_dist) ){ if( !identical( c("parameter"), colnames(size_dist)[1]) ){ stop( 'First column name of the parameters table must correspond to: parameter' ) } if( !all( size_dist$parameter %in% sizeDist.default$parameter) ){ stop( paste0('size_dist input table must contains only parameters presend in: ', paste(sizeDist.default$parameter, collapse = ','),'. Check `param_info`` for more details.' )) } sp_names_replace = sp_names[sp_names %in% colnames(size_dist)] size_dist_out[match(size_dist$parameter, size_dist_out$parameter), sp_names_replace] <- size_dist[,sp_names_replace] } return( size_dist_out ) }
mixdir_vi_dp <- function(X, n_latent, alpha, beta, categories, max_iter, epsilon, kappa1_init=NULL, kappa2_init=NULL, zeta_init=NULL, phi_init=NULL, verbose=FALSE){ n_ind <- nrow(X) n_quest <- ncol(X) n_cat <- max(X, na.rm=TRUE) if(is.null(alpha) || length(alpha) == 0){ alpha1 <- 1 alpha2 <- 1 }else if(length(alpha) == 2){ alpha1 <- alpha[1] alpha2 <- alpha[2] }else{ warning(paste0("alpha shoul only be a vector of 2 values. Using alpha1=alpha2=alpha[1]=", alpha[1])) alpha1 <- alpha[1] alpha2 <- alpha[1] } if(is.null(beta) || length(beta) == 0){ beta <- 0.1 }else if(length(beta) == 1){ beta <- beta[1] }else{ warning(paste0("beta should only be a single value. Using beta=beta[1]=", beta[1])) beta <- beta[1] } if(is.null(kappa1_init)){ kappa1_init <- rep(1, n_latent) } if(is.null(kappa2_init)){ kappa2_init <- rep(1, n_latent) } if(is.null(zeta_init)){ zeta_init <- extraDistr::rdirichlet(n_ind, rep(1, n_latent)) } if(is.null(phi_init)){ phi_init <- lapply(1:n_quest, function(j) lapply(1:n_latent, function(k) { x <- sample(1:3, size=length(categories[[j]]), replace=TRUE) x })) }else{ for(k in 1:n_latent){ phi_init_elem_lengths <- sapply(phi_init, function(x) length(x[[k]])) if(! all(phi_init_elem_lengths == sapply(categories, length))){ stop(paste0("phi_init has the wrong number of elements for feature: ", paste0(which(phi_init_elem_lengths != sapply(categories, length)), collapse = ", "))) } } } kappa1 <-kappa1_init kappa2 <-kappa2_init zeta <- zeta_init phi <- phi_init phia <- conv_phi_to_array(phi, n_quest, n_latent) iter <- 1 converged <- FALSE elbo_hist <- rep(NA, max_iter) while(iter <= max_iter & ! converged){ kappa1 <- alpha1 + colSums(zeta) summed_up_phi <- t(apply(zeta, 1, function(row) c(rev(cumsum(rev(row))), 0)))[, 2:(n_latent+1)] kappa2 <- alpha2 + colSums(summed_up_phi) zeta <- update_zeta_dp_cpp(zeta, X, phia, kappa1, kappa2, n_ind, n_quest, n_latent, n_cat) if(any(rowSums(zeta) == 0)){ stop(paste0("There was an underflow in the calculation of zeta. Cannot continue.\n", "The problem probably came from the large number of columns in the input ", "data (", (ncol(X)), "). Is it possible that you want to work on t(X)?")) } zeta <- zeta / rowSums(zeta) zeta <- zeta[, order(-colSums(zeta))] for(j in 1:n_quest){ for(k in 1:n_latent){ for(r in seq_along(categories[[j]])){ phi[[j]][[k]][r] <- sum(zeta[ ,k] * (X[, j] == r), na.rm=TRUE) + beta } } } phia <- conv_phi_to_array(phi, n_quest, n_latent) elbo <- dp_expec_log_v(kappa1, kappa2, rep(alpha1, length(kappa1)), rep(alpha2, length(kappa2))) + sum(sapply(1:n_ind, function(i)dp_expec_log_zi(zeta[i, ], kappa1, kappa2))) + sum(sapply(1:n_quest, function(j) sum(sapply(1:n_latent, function(k) expec_log_ujk(phi[[j]][[k]], rep(beta, length(categories[[j]]))) )))) + expec_log_x_cpp(X, phia, zeta, n_quest, n_latent, n_cat) + dp_entrop_v(kappa1, kappa2) + sum(sapply(1:n_ind, function(i) entrop_zeta(zeta[i, ]))) + sum(sapply(1:n_quest, function(j) sum(sapply(1:n_latent, function(k) entrop_phi(phi[[j]][[k]]) )))) if(iter != 1 && ! is.infinite(elbo) && elbo - elbo_hist[iter - 1] < - epsilon) warning(paste0("The ELBO decreased. This should not happen, it might be due to numerical instabilities or a bug in the code. ", "Please contact the maintainer to report this.\n")) if(iter != 1 && ! is.infinite(elbo) && elbo - elbo_hist[iter - 1] < epsilon) converged <- TRUE if(verbose && iter %% 10 == 0) message(paste0("Iter: ", iter, " ELBO: ", formatC(elbo, digits=8))) elbo_hist[iter] <- elbo iter <- iter + 1 } elbo_hist <- elbo_hist[! is.na(elbo_hist)] U <- lapply(1:n_quest, function(j) lapply(1:n_latent, function(k) { x <- rep(NA, times=length(categories[[j]])) names(x) <- categories[[j]] x })) names(U) <- colnames(X) for(j in 1:n_quest){ for(k in 1:n_latent){ U[[j]][[k]] <- (phi[[j]][[k]]) / sum(phi[[j]][[k]]) names(U[[j]][[k]]) <- categories[[j]] } } kappa1 <- alpha1 + colSums(zeta) summed_up_phi <- t(apply(zeta, 1, function(row) c(rev(cumsum(rev(row))), 0)))[, 2:(n_latent+1)] kappa2 <- alpha2 + colSums(summed_up_phi) nu <- kappa1/(kappa1 + kappa2) lambda <- sapply(1:n_latent, function(k){ nu[k] * (if(k > 1) prod((1-nu[1:(k-1)])) else 1) }) if(lambda[n_latent] > 0.01){ warning("The model put considerable weight on the last component. Consider re-running the model with an increased number of latent categories.") } prob_z <- matrix(vapply(seq_along(lambda), function(k){ lambda[k] * exp(rowSums(log(matrix(vapply(colnames(X), function(j){ ifelse(is.na(X[ ,j]), 1, U[[j]][[k]][X[, j]]) }, FUN.VALUE=rep(0.0, times=n_ind)), nrow=n_ind)))) }, FUN.VALUE=rep(0.0, times=n_ind)), nrow=n_ind) prob_z <- prob_z / rowSums(prob_z) list( converged=converged, convergence=elbo_hist, ELBO=elbo, lambda=lambda, pred_class=apply(prob_z, 1, which.max), class_prob=prob_z, category_prob=U, specific_params=list( kappa1=kappa1, kappa2=kappa2, phi=phi ) ) } dp_expec_log_v <- function(kappa_a, kappa_b, alpha, beta){ sum(sapply(1:(length(alpha)), function(k){ (alpha[k] - 1) * (digamma(kappa_a[k]) - digamma(kappa_a[k] + kappa_b[k])) + (beta[k] - 1) * (digamma(kappa_b[k]) - digamma(kappa_a[k] + kappa_b[k])) })) } dp_expec_log_zi <- function(zeta_i, kappa_a, kappa_b){ sum(sapply(1:length(zeta_i), function(k){ if(k != length(zeta_i)){ sum(zeta_i[(k+1):length(zeta_i)]) * (digamma(kappa_b[k]) - digamma(kappa_a[k] + kappa_b[k])) + zeta_i[k] * (digamma(kappa_a[k]) - digamma(kappa_a[k] + kappa_b[k])) }else { zeta_i[k] * (digamma(kappa_a[k]) - digamma(kappa_a[k] + kappa_b[k])) } })) } dp_entrop_v <- function(kappa_a, kappa_b){ sum(sapply(1:(length(kappa_a)), function(k){ lgamma(kappa_a[k]) + lgamma(kappa_b[k]) - lgamma(kappa_a[k] + kappa_b[k]) - (kappa_a[k] - 1) * digamma(kappa_a[k]) - (kappa_b[k] - 1) * digamma(kappa_b[k]) + (kappa_a[k] + kappa_b[k] - 2) * digamma(kappa_a[k] + kappa_b[k]) })) }
knitr::opts_chunk$set( collapse = TRUE, comment = " ) library(R2019nCoV) x <- get_2019nCoV() map <- getMap(x) map Seq <- getSeq()
Robins.CI = function(data,level) { m0 = data[2,1]/(data[2,1]+data[2,2]) m1 = data[1,1]/(data[1,1]+data[1,2]) n = sum(data) tau.hat = m1-m0 if (m1 >= m0) { r = ((2*m0-m1)*(1-m1)-m0*(1-m0))/n} if (m1 < m0) { r = ((2*m1-m0)*(1-m0)-m1*(1-m1))/n} se = sqrt(m0*(1-m0)/(data[2,1]+data[2,2])+m1*(1-m1)/(data[1,1]+data[1,2])+r) lower = max(tau.hat-qnorm(1-level/2)*se,-1) upper = min(tau.hat+qnorm(1-level/2)*se,1) output.all = list(tau.hat=tau.hat,lower=lower,upper=upper) return(output.all) } AE.CI = function(data,level) { n = sum(data) m = sum(data[1,]) tau.hat = data[1,1]/m-data[2,1]/(n-m) f = double() A1 = -data[1,2]:data[1,1] for (i in (1:length(A1))) { j = data j[1,1]=j[1,1]-A1[i] j[1,2]=j[1,2]+A1[i] f[i] = fisher.test(j)$p.value } lower1 = min(A1[f>=(level/2)]) upper1 = max(A1[f>=(level/2)]) g = double() A0 = -data[2,1]:data[2,2] for (i in (1:length(A0))) { j = data j[2,1]=j[2,1]+A0[i] j[2,2]=j[2,2]-A0[i] g[i] = fisher.test(j)$p.value } lower2 = min(A0[g>=(level/2)]) upper2 = max(A0[g>=(level/2)]) lower = (lower1+lower2)/n upper = (upper1+upper2)/n output.all = list(tau.hat=tau.hat,lower=lower,upper=upper) return(output.all) } library('gtools') nchoosem = function(n,m) { c = choose(n,m) trt = combinations(n,m) Z = matrix(NA,c,n) for (i in 1:c) { Z[i,trt[i,]] = 1 Z[i,-trt[i,]] = 0 } return(Z) } comb = function(n,m,nperm) { trt = matrix(NA,nperm,m) for (i in 1:nperm) { trt[i,] = sample(n,m) } Z = matrix(NA,nperm,n) for (i in 1:nperm) { Z[i,trt[i,]] = 1 Z[i,-trt[i,]] = 0 } return(Z) } library('compiler') pval2 = function(y.1,y.0,delta0,Z) { m = length(y.1[is.na(y.1)==0]) n = m+length(y.0[is.na(y.0)==0]) tau.hat = mean(y.1[is.na(y.1)==0])-mean(y.0[is.na(y.0)==0]) dat = matrix(NA,n,3) dat[,3] = delta0 dat[1:m,1] = y.1[1:m] dat[(m+1):n,2] = y.0[(m+1):n] dat[1:m,2] = y.1[1:m]-delta0[1:m] dat[(m+1):n,1] = y.0[(m+1):n]+delta0[(m+1):n] tau0 = mean(dat[,3]) t.c = Z%*%dat[,1]/(m)-(1-Z)%*%dat[,2]/(n-m) p = mean(round(abs(t.c-tau0),15)>=round(abs(tau.hat-tau0),15)) output.all = list(p,tau0,tau.hat,t.c) names(output.all) = list("p","tau0","tau.hat","t.c") return(output.all) } pval = cmpfun(pval2) Perm.CI2 = function(data,level,nperm) { m = sum(data[1,]) n = m+sum(data[2,]) a = data[1,1] b = data[1,2] c = data[2,1] d = data[2,2] y.1 = c(rep(1,data[1,1]),rep(0,data[1,2]),rep(NA,n-m)) y.0 = c(rep(NA,m),rep(1,data[2,1]),rep(0,data[2,2])) Z.obs = c(rep(1,m),rep(0,n-m)) Y.obs = c(rep(1,a),rep(0,b),grep(1,c),rep(0,d)) tau.hat = mean(y.1[is.na(y.1)==0])-mean(y.0[is.na(y.0)==0]) d1 = matrix(0,a,a) d1[col(d1) >= row(d1)] = 1 d1 = cbind(rep(0,a),d1) d2 = matrix(0,b,b) d2[col(d2) >= row(d2)] = -1 d2 = cbind(rep(0,b),d2) d3 = matrix(0,c,c) d3[col(d3) >= row(d3)] = -1 d3 = cbind(rep(0,c),d3) d4 = matrix(0,d,d) d4[col(d4) >= row(d4)] = 1 d4 = cbind(rep(0,d),d4) C = choose(n,m) if (C<=nperm) Z = nchoosem(n,m) else Z = comb(n,m,nperm) p = double() tau0 = double() for (g in 1:(a+1)) { for (h in 1:(b+1)) { for (i in 1:(c+1)) { for (j in 1:(d+1)) { k = pval(y.1,y.0,c(d1[,g],d2[,h],d3[,i],d4[,j]),Z) p = c(p,k$p) tau0 = c(tau0,k$tau0) } } } } lower = min(tau0[p>=level]) upper = max(tau0[p>=level]) output.all = list(tau.hat=tau.hat,lower=lower,upper=upper) return(output.all) } Perm.CI = cmpfun(Perm.CI2) Perm.CI.RLH <- function(data,level,verbose=FALSE,total_tests=NA) { a = data[1,1] b = data[1,2] c = data[2,1] d = data[2,2] if (is.na(total_tests)) { result_raw <- .CI_2by2_chiba_tau_v7_approx(a, b, c, d, level, max(data)^3) } else { result_raw <- .CI_2by2_chiba_tau_v7_approx(a, b, c, d, level, total_tests) } result <- result_raw[1:3] result <- c(result, (a/(a+b))-(c/(c+d)) ) names(result) <- c("Chiba", "RLH", "Blaker", "tau.hat") if (verbose) { alln.list <- lapply(1:length(result_raw[[9]]),function(i) { c(unlist(result_raw[[9]][i]),unlist(result_raw[[10]][i])) }) alln.df <- data.frame(do.call(rbind,alln.list)); rm(alln.list) colnames(alln.df) <- c("n11","n10","n01","n00", "pv_Chiba_L","pv_Chiba_U", "pv_RLH","pv_Blaker") result <- c(result, NA) result[[5]] <- alln.df names(result)[length(result)] <- "p_values" } return(result) }
SIPC.AMMI <- function(model, n, alpha = 0.05, ssi.method = c("farshadfar", "rao"), a = 1) { if (!is(model, "AMMI")) { stop('"model" is not of class "AMMI"') } if (!(0 < alpha && alpha < 1)) { stop('"alpha" should be between 0 and 1 (0 < alpha < 1)') } if (missing(n) || is.null(n)) { n <- sum(model$analysis$Pr.F <= alpha, na.rm = TRUE) } if (n %% 1 != 0 && length(n) != 1) { stop('"n" is not an integer vector of unit length') } if (n > nrow(model$analysis)) { stop('"n" is greater than the number of IPCs in "model"') } ssi.method <- match.arg(ssi.method) yresp <- setdiff(colnames(model$means), c("ENV", "GEN", "RESIDUAL")) A <- model$biplot A <- A[A[, 1] == "GEN", -c(1, 2)] A <- A[, 1:n] SIPC <- unname(rowSums(apply(A, 2, FUN = abs))) B <- model$means W <- aggregate(B[, yresp], by = list(model$means$GEN), FUN = mean, na.rm = TRUE) SSI_SIPC <- SSI(y = W$x, sp = SIPC, gen = W$Group.1, method = ssi.method, a = a) ranking <- SSI_SIPC colnames(ranking) <- c("SIPC", "SSI", "rSIPC", "rY", "means") return(ranking) }
setConstructorS3("CbsSegmentationDataFile", function(...) { extend(SegmentationDataFile(...), "CbsSegmentationDataFile") }) setMethodS3("loadFit", "CbsSegmentationDataFile", function(this, ...) { pathname <- getPathname(this) loadObject(pathname) }, protected=TRUE)
example <- function(topic, package = NULL, lib.loc = NULL, character.only = FALSE, give.lines = FALSE, local = FALSE, echo = TRUE, verbose = getOption("verbose"), setRNG = FALSE, ask = getOption("example.ask"), prompt.prefix = abbreviate(topic, 6), run.dontrun = FALSE, run.donttest = interactive()) { if (!character.only) { topic <- substitute(topic) if(!is.character(topic)) topic <- deparse(topic)[1L] } pkgpaths <- find.package(package, lib.loc, verbose = verbose) file <- index.search(topic, pkgpaths, firstOnly=TRUE) if(!length(file)) { warning(gettextf("no help found for %s", sQuote(topic)), domain = NA) return(invisible()) } if(verbose) cat("Found file =", sQuote(file), "\n") packagePath <- dirname(dirname(file)) pkgname <- basename(packagePath) lib <- dirname(packagePath) tf <- tempfile("Rex") tools::Rd2ex(.getHelpFile(file), tf, commentDontrun = !run.dontrun, commentDonttest = !run.donttest) if (!file.exists(tf)) { if(give.lines) return(character()) warning(gettextf("%s has a help file but no examples", sQuote(topic)), domain = NA) return(invisible()) } on.exit(unlink(tf)) if(give.lines) return(readLines(tf)) if(pkgname != "base") library(pkgname, lib.loc = lib, character.only = TRUE) if(!is.logical(setRNG) || setRNG) { if((exists(".Random.seed", envir = .GlobalEnv))) { oldSeed <- get(".Random.seed", envir = .GlobalEnv) on.exit(assign(".Random.seed", oldSeed, envir = .GlobalEnv), add = TRUE) } else { oldRNG <- RNGkind() on.exit(RNGkind(oldRNG[1L], oldRNG[2L], oldRNG[3L]), add = TRUE) } if(is.logical(setRNG)) { RNGkind("default", "default", "default") set.seed(1) } else eval(setRNG) } zz <- readLines(tf, n = 1L) skips <- 0L if (echo) { zcon <- file(tf, open="rt") while(length(zz) && !length(grep("^ skips <- skips + 1L zz <- readLines(zcon, n=1L) } close(zcon) } if(ask == "default") ask <- echo && grDevices::dev.interactive(orNone = TRUE) if(ask) { if(.Device != "null device") { oldask <- grDevices::devAskNewPage(ask = TRUE) if(!oldask) on.exit(grDevices::devAskNewPage(oldask), add = TRUE) } op <- options(device.ask.default = TRUE) on.exit(options(op), add = TRUE) } source(tf, local, echo = echo, prompt.echo = paste0(prompt.prefix, getOption("prompt")), continue.echo = paste0(prompt.prefix, getOption("continue")), verbose = verbose, max.deparse.length = Inf, encoding = "UTF-8", skip.echo = skips, keep.source=TRUE) }
skip_if_not_installed("nnet") test_that("autotest", { learner = mlr3::lrn("classif.nnet") expect_learner(learner) result = run_autotest(learner) expect_true(result, info = result$error) })
table_string <- function (str) { read.table( textConnection(str), blank.lines.skip = TRUE, header = TRUE, stringsAsFactors = FALSE) } mfdb_populate_example_data <- function (mdb) { mfdb_import_area(mdb, data.frame( id = c(1,2,3), name = c('45G01', '45G02', '45G03'), size = c(5))) mfdb_import_temperature(mdb, data.frame( year = rep(c(1998, 1999), each = 12), month = c(1:12, 1:12), areacell = c(rep('45G01', times = 24)), temperature = c(1:12, 25:36))) mfdb_import_division(mdb, list( divA = c('45G03'), divB = c('45G01', '45G02'), divC = c('45G01'))) mfdb_import_vessel_taxonomy(mdb, data.frame( name = c('1.RSH', '2.COM'), stringsAsFactors = FALSE )) mfdb_import_survey(mdb, data_source = "fleet_component_example", table_string(" year month areacell species vessel length age weight 1998 1 45G01 COD 1.RSH 21 2 210 1998 1 45G02 COD 2.COM 34 3 220 1998 1 45G03 COD 2.COM 34 3 230 1998 1 45G01 COD 2.COM 62 1 320 1998 1 45G02 COD 2.COM 53 1 330 1998 1 45G03 COD 2.COM 54 2 430 1998 1 45G01 COD 1.RSH 28 2 210 1998 1 45G02 COD 2.COM 34 3 220 1998 1 45G03 COD 1.RSH 24 3 230 1998 1 45G01 COD 1.RSH 12 1 320 1998 1 45G02 COD 2.COM 44 1 330 1998 1 45G03 COD 1.RSH 14 2 430 ")) }
body.model <- lm(Bodyfat ~ Weight + Abdomen, data = BodyFat) msummary(body.model) histogram( ~ resid(body.model), breaks = 10) xyplot(resid(body.model) ~ fitted(body.model), type = c("p", "r"), cex = 0.5)
influenceDiag.vglm <- function(model, approx = TRUE) { fam <- model@family@vfamily if(fam != 'betabinomial') stop('Only betabinomial models are admitted within VGAM package') Coefs <- coef(model) n.obs <- nobs(model) p <- model@rank DFbetas <- matrix(NA, nrow = n.obs, ncol = p) colnames(DFbetas) <- names(Coefs) w <- rep(1, n.obs) epsilon <- model@control$epsilon if(approx) epsilon <- 1e3 pb <- txtProgressBar(min = 0, max = n.obs, style = 3, char = "*", width = 30) for(i in 1:n.obs) { w.i <- w w.i[i] <- 1e-7 mod.i <- update(model, coefstart = Coefs, weights = w.i, epsilon = epsilon) DFbetas[i,] <- Coefs - coef(mod.i) setTxtProgressBar(pb, i) } hii <- hatvaluesvlm(model)[ ,1] Vb <- vcov(model) cookd <- apply((DFbetas %*% solve(Vb)) * DFbetas, MARGIN = 1, FUN = sum)/p out <- list(DFbeta = DFbetas, cookDist = cookd, leverage = hii, full.beta = coef(model), family = fam) attr(out, which = 'class') <- 'influence' out }
grpPUlasso <- function(X, z, py1, initial_coef = NULL, group = 1:ncol(X), penalty = NULL, lambda = NULL, nlambda = 100, lambdaMinRatio = ifelse(N < p, 0.05, 0.005), maxit = ifelse(method == "CD", 1000, N * 10), maxit_inner = 100000, weights = NULL, eps = 1e-04, inner_eps = 1e-02, verbose = FALSE, stepSize = NULL, stepSizeAdjustment = NULL, batchSize = 1, updateFrequency = N, samplingProbabilities = NULL, method = c("CD", "GD", "SGD", "SVRG", "SAG"), trace = c("none", "param", "fVal", "all") ) { N = nrow(X); p = ncol(X) input_check(X, z, group, penalty, stepSize, samplingProbabilities, weights) if (is.null(colnames(X))) { colnames(X) <- paste("V", 1:ncol(X), sep = "") } row_ordering = order(z, decreasing = T) col_ordering = order(group) ordering_res = ordering_data(row_ordering, col_ordering, X, z, group, weights) X_lu = ordering_res$X_lu z_lu = ordering_res$z_lu w_lu = ordering_res$w_lu group = ordering_res$group group0 = ordering_res$group0 remove(X, z, ordering_res) is.sparse = FALSE if (inherits(X_lu, "sparseMatrix")) { is.sparse = TRUE X_lu = as(X_lu, "CsparseMatrix") X_lu = as(X_lu, "dgCMatrix") } else if (inherits(X_lu, "dgeMatrix")) { X_lu = as.matrix(X_lu) } if (!(inherits(X_lu,"matrix") || inherits(X_lu, "dgCMatrix") )) { stop("X must be a matrix or a sparse matrix") } if (typeof(X_lu) != "double") { X_lu <- X_lu + 0.0 } if (!is.null(w_lu)) { weiOption <- TRUE w_lu <- w_lu / sum(w_lu) * length(w_lu) } else{ weiOption <- FALSE w_lu <- rep(1, N) } usestrongSet = ifelse(N < p, FALSE, TRUE) method = match.arg(method, choices = c("CD", "GD", "SGD", "SVRG", "SAG")) trace = match.arg(trace, choices = c("none", "param", "fVal", "all")) fitting_ls = fitting_setup( py1 = py1, lambda = lambda, lambdaMinRatio = lambdaMinRatio, nlambda = nlambda, initial_coef = initial_coef, group = group, penalty = penalty, p = p ) opt_ls = opt_option_setup( method = method, trace = trace, stepSize = stepSize, stepSizeAdjustment = stepSizeAdjustment, samplingProbabilities = samplingProbabilities ) if(weiOption&& (method != "CD")) { opt_ls$method = "CD" message("Currently the weight option is available for method == CD. Method switched to CD") } skip_fitting = getOption('PUlasso.skip_fitting') if(!is.sparse) { g <- LU_dense_cpp( X_ = X_lu, z_ = z_lu, icoef_ = fitting_ls$icoef, gsize_ = fitting_ls$gsize, pen_ = fitting_ls$pen, lambdaseq_ = fitting_ls$lambdaseq, user_lambdaseq_ = fitting_ls$user_lambdaseq, pathLength_ = nlambda, lambdaMinRatio_ = lambdaMinRatio, pi_ = py1, max_nUpdates_ = maxit, maxit_ = maxit_inner, wei_ = w_lu, weiOption_ = weiOption, tol_ = eps, inner_tol_ = inner_eps, useStrongSet_ = usestrongSet, verbose_ = verbose, stepSize_ = opt_ls$stepSize, stepSizeAdj_ = opt_ls$stepSizeAdjustment, batchSize_ = batchSize, updateFreq_ = updateFrequency, samplingProbabilities_ = opt_ls$samplingProbabilities, useLipschitz_ = opt_ls$use_Lipschitz_for_ss_or_sProb, method_ = method, trace_ = opt_ls$trace, skipFitting_ = skip_fitting ) } else{ g <- LU_sparse_cpp( X_ = X_lu, z_ = z_lu, icoef_ = fitting_ls$icoef, gsize_ = fitting_ls$gsize, pen_ = fitting_ls$pen, lambdaseq_ = fitting_ls$lambdaseq, user_lambdaseq_ = fitting_ls$user_lambdaseq, pathLength_ = nlambda, lambdaMinRatio_ = lambdaMinRatio, pi_ = py1, max_nUpdates_ = maxit, maxit_ = maxit_inner, wei_ = w_lu, weiOption_ = weiOption, tol_ = eps, inner_tol_ = inner_eps, useStrongSet_ = usestrongSet, verbose_ = verbose, stepSize_ = opt_ls$stepSize, stepSizeAdj_ = opt_ls$stepSizeAdjustment, batchSize_ = batchSize, updateFreq_ = updateFrequency, samplingProbabilities_ = opt_ls$samplingProbabilities, useLipschitz_ = opt_ls$use_Lipschitz_for_ss_or_sProb, method_ = method, trace_ = opt_ls$trace, skipFitting_ = skip_fitting ) } cpp_results = summary_cpp_results(g, method, trace, colnames = colnames(X_lu), group0 = group0) optResult = list( method = method, convergence = g$convFlag, fValues = g$fVals, subGradients = g$subgrads, stepSize = g$stepSize, samplingProbabilities = g$samplingProbabilities, std_coef_all = cpp_results$std_coef_all, fValues_all = cpp_results$fVals_all, maxit = maxit ) if(method %in% c("CD","GD")){ widx<-which(g$convFlag==1) if(length(widx)>0){ for(i in 1:length(widx)){ warning(paste("convergence failed at ",widx[i],"th lambda, ", cpp_results$iters[widx[i]],"th iterations",sep="")) } } }else{ if(verbose){ widx<-which(g$convFlag==0) if(length(widx)>0){ for(i in 1:length(widx)){ cat('|param.diff| < eps at',widx[i],'th lambda,', cpp_results$iters[widx[i]],'th iterations\n') } } } } result <- structure( list( coef = cpp_results$coef, std_coef = cpp_results$std_coef, lambda = g$lambda, nullDev = g$nullDev, deviance = g$deviance, optResult = optResult, iters = cpp_results$iters, call = match.call() ), class = "PUfit" ) return(result) }
library(NewmanOmics) data(LungPair) lung <- as.matrix(log2(1 + LungPair)) summary(lung) set.seed(12345) normal <- lung[, 1, drop=FALSE] tumor <- lung[, 2, drop=FALSE] ps <- pairedStat(normal, tumor) slotNames(ps) dim([email protected]) dim([email protected]) summary([email protected]) summary([email protected]) head([email protected]) head([email protected]) ps2 <- pairedStat(list(lung)) summary([email protected]) summary([email protected]) summary([email protected] - [email protected]) summary(pdiff <- [email protected] - [email protected]) plot([email protected], pdiff) abline(h=0) plot(ps) hist(ps)
expected <- eval(parse(text="list(structure(1:5, .Tsp = c(-1, 3, 1), class = \"ts\"), structure(1:5, .Tsp = c(1, 5, 1), class = \"ts\"))")); test(id=0, code={ argv <- eval(parse(text="list(structure(1:5, .Tsp = c(-1, 3, 1), class = \"ts\"), structure(1:5, .Tsp = c(1, 5, 1), class = \"ts\"))")); do.call(`list`, argv); }, o=expected);
snntsmarginallatitude <- function(data,cpars=1,M=c(0,0)){ auxcond<-sum(data>pi)+sum(data<0) if (auxcond>0) return("Latitude data must have values between 0 and pi") A <- matrix(0,nrow=M[2]+1,ncol=M[2]+1) for (k2 in 0:M[2]){ for (m2 in 0:M[2]){ if (abs(k2 - m2) != 1){ A[k2+1,m2+1] <- (2*pi)*((1 + cos((k2-m2)*pi))/(1 - ((k2-m2)^2))); } } } Ac<-chol(A) Acinv <- solve(Ac) cparsauxa <- cpars for (k1 in 0:M[1]){ cpars[(k1*(M[2]+1)+1):((k1+1)*(M[2]+1))] <- Acinv %*% cparsauxa[(k1*(M[2]+1)+1):((k1+1)*(M[2]+1))] } cparsaux<-matrix(cpars,nrow=M[1]+1,ncol=M[2]+1,byrow=TRUE) y<-rep(0,length(data)) for (j in 1:length(data)){ for (k1 in 0:M[1]){ for (k2 in 0:M[2]){ for (m2 in 0:M[2]){ y[j] <- y[j] + (2*pi)*sin(data[j])*cparsaux[k1+1,k2+1]*Conj(cparsaux[k1+1,m2+1])*(exp(1i*(k2-m2)*data[j])) } } } } return(Re(y)) }
AbstractGeom = ggproto("AbstractGeom", Geom, default_computed_aes = aes(), default_params = list( orientation = NA, na.rm = FALSE ), layer_args = list( show.legend = NA, inherit.aes = TRUE ), hidden_params = character(), deprecated_params = character(), orientation_options = list(), setup_params = function(self, data, params) { params = ggproto_parent(Geom, self)$setup_params(data, params) params = defaults(params, self$default_params) orientation_args = c(list(quote(data), quote(params)), self$orientation_options) params$flipped_aes = do.call(get_flipped_aes, orientation_args) params$orientation = get_orientation(params$flipped_aes) params }, setup_data = function(self, data, params) { data = ggproto_parent(Geom, self)$setup_data(data, params) data$flipped_aes = params$flipped_aes data }, parameters = function(self, extra = TRUE) { panel_args = names(ggproto_formals(self$draw_panel)) params = setdiff(panel_args, c(names(ggproto_formals(Geom$draw_group)), "...")) union(params, names(self$default_params)) } ) make_geom = function(geom, mapping = NULL, data = NULL, stat = "identity", position = "identity", ... ) { geom_name = substitute(geom) params = geom$default_params[!names(geom$default_params) %in% geom$hidden_params] params_to_defaults = lapply(params, to_expression) params_to_syms = syms(names(params_to_defaults)) names(params_to_syms) = names(params_to_defaults) args_to_defaults = lapply(geom$layer_args, to_expression) args_to_syms = syms(names(args_to_defaults)) names(args_to_syms) = names(args_to_defaults) new_function( c( pairlist2( mapping = mapping, data = data, stat = stat, position = position, ... =, ), params_to_defaults, args_to_defaults ), expr({ .Deprecated_arguments(!!geom$deprecated_params, ...) l = layer( data = data, mapping = mapping, geom = !!geom_name, stat = stat, position = position, !!!args_to_syms, params = list( !!!params_to_syms, ... ) ) !!( if (length(geom$default_computed_aes) > 0) { expr(add_default_computed_aesthetics(l, !!geom$default_computed_aes)) } else { quote(l) } ) }), env = parent.frame() ) } to_expression = function(x) { parse(text = deparse(x), keep.source = FALSE)[[1]] }
generateGrid <- function(order, level){ gridpoint.ls <- vector("list", order) bandwidth.ls <- vector("list", order) for(u in 1:order) { for(l in 1:level){ random.val <- sobol(n = max(3, (7-u))^min(u,5) * l, dim = u) random.val <- matrix(random.val, ncol = u) gridpoint.ls[[u]][[l]] <- random.val if(l == 1){ n <- nrow(random.val) D <- gridpoint.ls[[u]][[l]] if(u == 1) D <- matrix(D, ncol = 1) Points <- expand.grid((1:n), (1:n)) Points <- cbind(Points[, 2], Points[, 1]) Points <- Points[Points[, 2] > Points[, 1], ] junk <- (D[Points[, 2],,drop=FALSE] - D[Points[, 1],,drop=FALSE])^2 bandwidth.ls[[u]][l] <- 6 * u * min(sqrt(rowSums(junk))) }else{ bandwidth.ls[[u]][l] <- bandwidth.ls[[u]][1] / 2^(l-1) } } } for(u in 1:min(5, order)){ if(u == 1){ for(l in 1:level){ grid <- seq(0, 1, length = max((6-u),2)*2^(l-1)+1) grid.df <- data.frame(matrix(rep(grid, u), ncol = u)) gridpoint.ls[[u]][[l]] <- expand.grid(grid.df) bandwidth.ls[[u]][l] <- 6 * 1/(length(grid)-1) } }else{ grid <- seq(0, 1, length = max((6-u),2)+1) grid.df <- data.frame(matrix(rep(grid, u), ncol = u)) gridpoint.ls[[u]][[1]] <- expand.grid(grid.df) bandwidth.ls[[u]][1] <- 6 * 1/(length(grid)-1) } } return(list(gridpoint.ls = gridpoint.ls, bandwidth.ls = bandwidth.ls)) }
context("extractEnvObjectInformation") source_files <- c( 'sample-classes.R', 'AdditionTCFIP.R' ) source_package <- 'wyz.code.offensiveProgramming' sapply(source_files, function(e) { f <- findFilesInPackage(e, source_package) stopifnot(length(f) == 1) source(f) }) objects <- list( MyEnv(), FieldEnv(), MethodEnv(), EmptyEnv(), Zarg(), Zirg(), Zorg(), Zurg(), AdditionTCFIP() ) rv <- lapply(objects, extractEnvObjectInformation) test_that("extractEnvObjectInformation", { myf <- function(k) { expect_length(rv[[!!k]], ifelse(k %in% c(2, 4), 1L, 2L)) expect_true(is.list(rv[[!!k]])) } lapply(seq_len(length(rv)), myf) })
library(hamcrest) test.readGnuDataFrames <- function() { df <- readRDS("gnuRowNames.rds") assertThat(nrow(df), identicalTo(10L)) assertThat(attr(df, 'row.names'), identicalTo(1:10)) assertThat(df$a, identicalTo(1:10)) assertThat(df$b, identicalTo(factor(letters[1:10]))) }
Score_adjust_PPI <- function(scaled_node_score,scaled_edge_score,PPI,lam,subnet,num_random_sampling,best_score) { all_genes<-names(scaled_node_score) node_num<-length(subnet) genes_selected<-all_genes[subnet] edges_selected<- PPI[,1] %in% genes_selected & PPI[,2] %in% genes_selected num_edges_selected<-sum(edges_selected) random_score<-rep(0,num_random_sampling) for(i in 1:num_random_sampling){ sampled_edges <- sample(1:dim(PPI)[1],num_edges_selected) edge_score<-sum(scaled_edge_score[sampled_edges])/sqrt(num_edges_selected) sampled_nodes <- sample(1:length(all_genes),node_num) node_score<-sum(scaled_node_score[sampled_nodes])/sqrt(node_num) random_score[i]<- lam*edge_score + (1-lam)*node_score print(i) } mean<-mean(random_score) sd<-sd(random_score) adjusted_score<-(best_score-mean)/sd return (adjusted_score) }
DownDyadHi <- function(x, qmf) { d <- iconvv(MirrorFilt(qmf), lshift(x)) n <- length(d) return(d[seq(1, n - 1, 2)]) }
.options <- function(self, private, code) { l <- private$map() s <- paste0(sapply(names(l), function(x) sprintf("%s=%s", x, l[[x]])), collapse = "&") code <- paste0(code, collapse = "\n") sprintf("%s&code=%s", s, self$encode(code)) } .uri <- function(self, private, code) { sprintf("https://carbon.now.sh/?%s", self$options(code = code)) } .browse <- function(self, private) { utils::browseURL(self$uri()) } .encode <- function(self, private, URL, reserved, repeated) { if (!repeated && grepl("%[[:xdigit:]]{2}", URL, useBytes = TRUE)) { return(URL) } OK <- paste0( "[^", if (!reserved) { "][!();?" } , "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz0123456789._~-", "]" ) x <- strsplit(URL, "")[[1L]] z <- grep(OK, x) z <- sort(c(z, which(x %in% c("[", "]")))) if (length(z)) { y <- sapply(x[z], function(x) paste0("%25", toupper(as.character(charToRaw(x))), collapse = "" )) y <- gsub("%2527", "%27", y) x[z] <- y } paste(x, collapse = "") } .tiny <- function(self, private, clip = FALSE) { RET <- tinyurl(self$uri()) if (clip) { clipr::write_clip(RET) } return(RET) } .rtweet <- function(self, private, media, status = self$tweet_status, media_format = c("png", "gif"), ...) { td <- file.path(tempdir(), "rtweet_media") mf <- match.arg(media_format) dir.create(td, showWarnings = FALSE) on.exit(unlink(td, recursive = TRUE, force = TRUE), add = TRUE) if (inherits(media, "magick-image")) { if (mf == "gif") { anim <- magick::image_animate(media, fps = 1) magick::image_write( image = anim, path = file.path(td, sprintf("img01.%s", mf)), format = mf ) } else { invisible( lapply(seq_along(media), function(x) { magick::image_write( image = media[x], path = file.path(td, sprintf("img%02d.%s", x, mf)), format = mf ) }) ) } tds <- list.files(td, full.names = TRUE) } else { tds <- media } rtweet::post_tweet(status = status, media = tds, ...) } tinyurl <- function(uri){ host <- 'tinyurl.com' if(!httr::http_error(host)){ base <- sprintf('http://%s/api-create.php',host) uri <- httr::content(httr::GET(sprintf('%s?url=%s',base,uri))) } uri }
context("test-hl") library(VulnToolkit) test_that("fld.frq gives correct output", { expect_equal(fld.frq(2, 1:10, units = "percent"), 0.8) expect_equal(fld.frq(2, 1:10, units = "tides"), 9) expect_error(fld.frq("string", 1:10)) expect_error(fld.frq(2, "string")) expect_error(fld.frq(2, 1:10, units = "furlongs")) }) test_that("fld.dur gives correct output", { expect_equal(fld.dur(z = 2, level = 1:10), 0.8) expect_error(fld.dur(z = "string", level = 1:10)) expect_error(fld.dur(z = 2, level = "string")) }) test_that("HL gives correct output", { expect_error(HL("hello world")) expect_error(HL(1:10, "hello world")) expect_equal(nrow(HL(rep(c(c(1:100), c(100:1)), times = 400)[1:8761], seq.POSIXt(from = ISOdate(1910,1,1), to = ISOdate(1911,1,1), by = "hours"))), 1868) }) test_that("wave.dur gives correct output", { expect_error(wave.dur(elevation = c(), level = 1:10)) expect_equal(sum(wave.dur(level = 2, elevation = 1:10)), 1) expect_equal(sum(wave.dur(level = 2:10, elevation = 1:10)), 1) expect_equal(sum(wave.dur(level = c(NA, 2:10), elevation = 1:10)), 1) }) test_that("psmsl error checking", { expect_error(psmsl(type = "string")) expect_error(psmsl(interval = "string")) }) test_that("psmsl.stations error checking", { expect_error(psmsl.stations(type = "string")) expect_error(psmsl.stations(sort.by = "string")) }) test_that("noaa.parameters error checking", { expect_error(noaa.parameters(stn = "abcd")) }) test_that("noaa error checking", { expect_error(noaa(continuous = "string")) expect_error(noaa(units = "string")) expect_error(noaa(datum = "string")) expect_error(noaa(interval = "string")) expect_error(noaa(units = "feet", interval = "string")) expect_error(noaa(units = "meters", interval = "string")) expect_error(noaa(time = "string")) })
library(fdacluster) context("Center Method") test_that(" the warping methods work", { expect_equal(length( kma( x = aneurisk65$x, y = aneurisk65$y, seeds = NULL, n_clust = 2, center_method = "mean", use_verbose = FALSE ) ), 23) expect_equal(length( kma( x = aneurisk65$x, y = aneurisk65$y, seeds = NULL, n_clust = 2, center_method = "medoid", use_verbose = FALSE ) ), 23) })
.Random.seed <- c(403L, 10L, 238561690L, 947170652L, -923171745L, -802767819L, -311679028L, -566791390L, -1547653763L, 1461993079L, -140580962L, -1593178536L, 80097211L, 582189401L, -1706050840L, -1749433578L, 723666065L, 344824131L, 935375954L, -1692694812L, -609337049L, -1383845507L, -115427212L, 806255194L, -1048668507L, 489866431L, 284432198L, 1224791504L, -167475213L, -1435222255L, 1953939264L, -500005090L, 831371241L, 1897012507L, -1760839894L, -1160591284L, 108707855L, -1259697339L, 947166460L, -1834767534L, -419042099L, -94647161L, 108468078L, -97851064L, -1740550837L, -436105047L, -610217480L, -1853087450L, -2086518207L, -1320391725L, 1791826306L, -1009668684L, 1917450551L, 1322970157L, -691840700L, 1718849130L, -1705842475L, 1560413807L, 860214134L, 620168352L, 497655139L, 1932406273L, 1030221168L, 1034317070L, 1473916793L, 688148235L, -688222150L, -1085792452L, -1758520193L, 252719061L, 1622835692L, 240235330L, -115532643L, -873683689L, -1800184706L, 1484010552L, 999117595L, -830908295L, 1570308296L, -411006730L, 1947621681L, 1937437027L, -1567628494L, 1543335044L, 599627975L, -537967715L, 1402791700L, -1781686854L, -861094907L, 628462047L, 515839078L, 1444721648L, 739216659L, 770355889L, 1889131872L, 100389630L, -1837576567L, -122095173L, -728767606L, 1529399916L, -847182865L, 1042656293L, -997542692L, -607352142L, -1998230099L, 1077277031L, 502435470L, -185788568L, 802180971L, -2129716983L, 1311805336L, 587118278L, -846003167L, -1486892877L, 2136574498L, 36736020L, 1116233879L, 62837389L, -192822364L, -1553285750L, 801876469L, 1295483983L, -1626184874L, 806476288L, 701461315L, -1740680479L, 2052702288L, -2029543250L, 534631513L, 1351836779L, -705812006L, -1810369892L, -1371009889L, -578519307L, -1065630836L, 1087296098L, 1076389437L, 2048116919L, 855357278L, 867400344L, -1538921989L, 1135874969L, 1136684072L, -1914528554L, -2005350063L, -1813714941L, 58879890L, 1945517348L, -702508057L, 2055989309L, 360289972L, 1573436698L, 936726117L, 1291043583L, 1373607814L, -1680971504L, 1300781491L, 1334772305L, 285905408L, 1590759134L, 1506297129L, -1462318885L, -381546518L, 1618947980L, -2081398577L, -655892347L, -949279940L, 2118752786L, 88158477L, -1769850297L, -1325883346L, -813476472L, 1281010827L, 706414185L, -383788488L, 1132006118L, -1786894719L, -314545645L, 1883033026L, 963315316L, -1141139337L, 1281120621L, -814735868L, -1549677270L, -101143915L, -447405777L, 1462547510L, -1316204448L, -186255709L, 1776169409L, 745655728L, 1466762446L, -1272745415L, 224625739L, -1463695878L, 2120958204L, -1015163585L, 1106291221L, -1669668564L, -170962430L, 610345181L, -157600809L, -929575234L, 2120268024L, -171211045L, -228049607L, 2122238088L, -1308356554L, -1054841743L, 1342148259L, 1064362994L, -119974076L, -1116153849L, 553579997L, 1922413268L, -1403273734L, -1279250107L, 1743443359L, 1145284390L, 2023696304L, 181568595L, 2120286065L, 258061984L, 1584962110L, -176066231L, -2087776261L, -71380022L, -45093588L, -1678581457L, -1333331776L, 166851124L, 486316744L, -1003486534L, 135679120L, -963279124L, 201348692L, 18015890L, 1161955104L, -797911092L, -262354720L, 1721093826L, 387224616L, -1281000532L, -1422808388L, 153240050L, -498432464L, -50833500L, 384311736L, -1099646118L, 1491047568L, 580049788L, 616029972L, 660544834L, -235221248L, 269212604L, 51265360L, -889216734L, -394835384L, -1528637428L, -2142827428L, 946868690L, 1156609536L, -379326124L, -493190936L, -1558630150L, -351721776L, -1902638804L, 997382388L, -543658606L, -762009248L, -639113204L, 339184352L, -3505566L, 1224030888L, -1267451316L, 1188472700L, -998003406L, -661059984L, -1634026684L, -1216690216L, 2126724986L, 1745571376L, 1661401020L, 1396848212L, 1384884290L, -1224171360L, 439955132L, -1443493424L, 320865122L, -1251736856L, 614400204L, -981261828L, 478071282L, 486775424L, -752421388L, 1872856712L, 1571585850L, -664419504L, 1305351276L, 160536980L, -1600314286L, 1124198880L, 436747468L, -1338086240L, -1683540606L, -1203805976L, -1374069012L, -80270020L, 272186482L, 1078018160L, 1539790884L, -1386386376L, -1417939174L, -1772995376L, -1667090628L, 1899911060L, 1694043010L, -58920512L, 1555607100L, -1917057648L, 1171252770L, -1236116216L, 210044556L, 347838236L, -2099912558L, 558524800L, 1543683604L, 1307111208L, 1587139130L, 452302288L, -986216084L, 67077044L, 1182369810L, -500757024L, -90243124L, -1466081056L, -417105886L, -459554520L, 240344588L, 1346641724L, -1983366158L, -1752462608L, 892184132L, -598728104L, 1393819450L, 2118096368L, -623014212L, -1908352748L, 2142575298L, 891931744L, 141112188L, -1225947184L, -1046331102L, -203568472L, -1488243828L, -1791366980L, 324446002L, 524773952L, -1319623500L, 1941322312L, -641450566L, 2002557456L, 347564780L, -716887724L, 561201426L, -150757984L, 219405004L, 1381367392L, 1563754434L, -11518168L, -821899348L, 338326332L, -1245918862L, -717464784L, 1839842596L, 626637624L, 589616858L, -1172357232L, 1521528572L, -959618156L, 109344834L, -1177680640L, -503913412L, -1625251504L, 885942434L, -121513656L, 580888332L, -206613796L, -339325614L, 549543040L, 1580474452L, 456751080L, -1116454662L, 1757375312L, 1578000172L, -1611490956L, -1019507822L, 1818241120L, -1335007860L, -278742176L, 1387465186L, 117369768L, 1453595852L, 1579317244L, -229636686L, -1941836304L, 1896192964L, 1588927832L, 1186640250L, 1253092272L, -629177924L, 227338324L, -769470526L, -12756960L, -968664900L, 1358168656L, 1342204898L, -826439576L, 1163664460L, 1161492732L, 1656413170L, 1265531136L, 31678836L, 1900782600L, 317865914L, 1965593040L, -513901588L, -1138476652L, -789003822L, 1388802400L, 187182924L, 508209440L, -435816574L, -561533208L, -1219223316L, 1554310204L, 2092129138L, -146045328L, -982758364L, 330998584L, 626973850L, -1489130800L, -2108792644L, 1271676564L, 1248194178L, -1585129280L, 2008513340L, -1622471536L, 1449074210L, -1937596408L, 854017292L, 352617628L, -1004315118L, 364449664L, -1321409004L, 403931688L, -262153697L, -2021884552L, 1165851734L, 1902182627L, 1283262117L, 1501113154L, 2073788720L, -788145831L, 1927027403L, 645235516L, -1229362326L, -316241505L, 1418575913L, 1436588734L, -1750148180L, -984504067L, -1284668345L, 1545921328L, 27452494L, 530057339L, 2115374045L, -1874718198L, 1887917864L, -732722799L, -1899442301L, -1399364476L, 793297586L, 1583928839L, -429779375L, 1158376918L, -30359372L, -1991869243L, 227753487L, 1733506696L, -1881179226L, 806007635L, -2016240459L, 1497422354L, 782317536L, 712944201L, -1668177797L, 74903884L, 1920918746L, 929170639L, 2121584793L, 1147309230L, 1062156732L, 1448657453L, -1033996841L, 28056608L, -1982611074L, -291680437L, 188241229L, -1715397766L, 1133624760L, -923984031L, -360179949L, -1574195404L, -299598526L, -500403881L, -1178305375L, -1130338970L, -1602140316L, -305158507L, 1911463871L, 1115562840L, 1269358966L, -110435453L, -89882171L, -209828126L, 1565345616L, 1936179833L, 1785685419L, -705582308L, -1256588214L, 1901815871L, -1062340471L, 546315422L, -1539798708L, -2040409827L, 898383015L, -2089481264L, -301862034L, 921416219L, -1098542211L, 1576726890L, 1975726088L, -113551183L, -1148913885L, -2056645596L, -967686446L, -155229401L, -460593807L, -1969067082L, 1371885396L, 873171429L, 814232559L, -190643416L, 705741702L, -817889357L, 1976727317L, 1879482738L, 744302016L, -1856629207L, -1551783269L, 333845356L, -1280218246L, 878564527L, -1731420231L, -1223755314L, 1563008284L, 1118591117L, -1945201417L, -2046595072L, -2034126242L, -1325535957L, 1039978029L, 153286298L, -1462058408L, -22340159L, 1548362355L, -145875052L, -307499486L, 203215159L, -980369407L, 1369873670L, -1906259644L, -2058363787L, 459812319L, 1615788344L, 176714518L, 1228147491L, 373752037L, -917414654L, -2108395664L, -403501287L, -2089105653L, -580377604L, 609689642L, -2015130529L, -989068311L, 1907952894L, 255149292L, 1762736189L, -1106899961L, -1610754064L, 707421070L, -1604869701L, -1138942051L, -1999024822L, -1487354520L, -1161737391L, -1419876285L, 411611460L, -240760334L, -1447273529L, -364401263L, -438009578L, -1538125452L, 1730693125L, 1455329359L, -374336440L, 1967049190L, 446371603L, 622264437L, -1351269806L, -1377426272L, 1008795017L, 1775406523L, -143560383L)
kog.mwu <- function(data,gene2kog,Alternative="t") { rsq=data names(rsq)=c("seq","value") bads=which(rsq[,2]==Inf | rsq[,2]==(-Inf) | is.na(rsq[,2])) if (length(bads)>0) { rsq=rsq[-bads,]} kogs=gene2kog annotated=rsq[rsq[,1] %in% kogs[,1],] kogs=kogs[kogs[,1] %in% rsq[,1],] kogrows=match(kogs[,1],annotated[,1]) annotated=annotated[kogrows,] annotated$term=as.character(kogs[,2]) annotated$value=as.numeric(as.character(annotated[,2])) mwut.t=TRUE if (length(levels(as.factor(annotated[,2])))==2) { print("Binary classification detected; will perform Fisher's test"); mwut.t=F rr=kog.ft(annotated) } else { print("Continuous measure of interest: will perform MWU test"); rr=kog.mwut(annotated,Alternative) } return(rr) }
PAveDD <- function(PriceData, AveDD = 0.1, softBudget = FALSE, ...){ if(is.null(dim(PriceData))){ stop("Argument for 'PriceData' must be rectangular.\n") } if(any(is.na(PriceData))){ stop("NA-values contained in object for 'PriceData'.\n") } if(AveDD <= 0 || AveDD >= 1){ stop("Argument for 'AveDD' must be in the interval (0, 1).\n") } call <- match.call() RC <- as.matrix(returnseries(PriceData, method = "discrete", percentage = FALSE, compound = TRUE)) rownames(RC) <- NULL N <- ncol(RC) J <- nrow(RC) w <- rep(0, N) u <- rep(0, J) v <- rep(0, J) x <- c(w, u, v) obj <- c(as.numeric(RC[J, ]), rep(0, J), rep(0, J)) a1 <- cbind(diag(N), matrix(0, nrow = N, ncol = 2 * J)) d1 <- rep(">=", N) b1 <- rep(0, N) a2 <- c(rep(1, N), rep(0, 2 * J)) ifelse(softBudget, d2 <- "<=", d2 <- "==") b2 <- 1 a3 <- cbind(-1 * RC, diag(J), -1 * diag(J)) d3 <- rep("==", J) b3 <- rep(0, J) a4 <- c(rep(0, N), rep(0, J), rep(1 / J, J)) d4 <- "<=" b4 <- AveDD a5 <- cbind(-1 * RC, diag(J), matrix(0, nrow = J, ncol = J)) d5 <- rep(">=", J) b5 <- rep(0, J) D1 <- -1.0 * diag(J) udiag <- embed(1:J, 2)[, c(2, 1)] D1[udiag] <- 1 a6 <- cbind(matrix(0, ncol = N, nrow = J), D1, matrix(0, ncol = J, nrow = J)) a6 <- a6[-J, ] d6 <- rep(">=", J-1) b6 <- rep(0, J-1) Amat <- rbind(a1, a2, a3, a4, a5, a6) Dvec <- c(d1, d2, d3, d4, d5, d6) Bvec <- c(b1, b2, b3, b4, b5, b6) opt <- Rglpk_solve_LP(obj = obj, mat = Amat, dir = Dvec, rhs = Bvec, max = TRUE, ...) if(opt$status != 0){ warning(paste("GLPK had exit status:", opt$status)) } weights <- opt$solution[1:N] names(weights) <- colnames(PriceData) dd <- timeSeries(opt$solution[(N + J + 1):(N + J + J)], charvec = rownames(PriceData)) obj <- new("PortAdd", weights = weights, opt = opt, type = "average draw-down", call = call, AveDD = mean(dd), DrawDown = dd) return(obj) }
library(tidyverse) library(janitor) library(naniar) riskfactors <- brfss %>% tibble::as_tibble() %>% janitor::clean_names() %>% dplyr::rename(hispanic = hispanc2, veteran = veteran2, education = educa, employment = employ, income = income2, weight_lbs = weight2, height_inch = height3, health_general = genhlth, health_physical = physhlth, health_mental = menthlth, health_poor = poorhlth, health_cover = hlthplan, provide_care = caregive, activity_limited = qlactlm2, drink_any = drnkany4, drink_days = alcday4, drink_average = avedrnk2, smoke_100 = smoke100, smoke_days = smokday2, smoke_stop = stopsmk2, smoke_last = lastsmk1, diet_fruit = fruit, diet_salad = greensal, diet_potato = potatoes, diet_carrot = carrots, diet_vegetable = vegetabl, diet_juice = fruitjui, bmi = bmi4) %>% dplyr::select(state, sex, age, weight_lbs, height_inch, bmi, marital, pregnant, children, education, employment, income, veteran, hispanic, dplyr::everything()) %>% dplyr::mutate(bmi = bmi / 100) devtools::use_data(riskfactors, overwrite = TRUE)
get_definition <- function(x, name) { x$get_type(name) } for_onload(function() { " type __Schema { types: [__Type!]! queryType: __Type! mutationType: __Type directives: [__Directive!]! } " %>% gqlr_schema( "__Schema" = list( description = collapse( "A GraphQL Schema defines the capabilities of a GraphQL server. It ", "exposes all available types and directives on the server, as well as ", "the entry points for query, mutation, and subscription operations.", " Subscriptions are not implemented in gqlr." ), fields = list( "types" = "A list of all types supported by this server.", "queryType" = "The type that query operations will be rooted at.", "mutationType" = "The type that mutation operations will be rooted at.", "directives" = "A list of all directives supported by this server." ), resolve = function(null, schema) { list( types = function(z1, z2, z3) { all_types <- list() %>% append(names(schema$get_scalars())) %>% append(names(schema$get_objects())) %>% append(names(schema$get_interfaces())) %>% append(names(schema$get_unions())) %>% append(names(schema$get_enums())) %>% append(names(schema$get_input_objects())) %>% append(names(schema$get_values())) all_types }, queryType = function(z1, z2, z3) { query_type <- schema$get_query_object() query_type$name }, mutationType = function(z1, z2, z3) { mutation_type <- schema$get_mutation_object() if (is.null(mutation_type)) return(NULL) mutation_type$name }, directives = function(z1, z2, z3) { directives <- schema$get_directives() directives } ) } ) ) %>% get_definition("__Schema") -> Introspection__Schema " type __Type { kind: __TypeKind! name: String description: String fields(includeDeprecated: Boolean = false): [__Field!] interfaces: [__Type!] possibleTypes: [__Type!] enumValues(includeDeprecated: Boolean = false): [__EnumValue!] inputFields: [__InputValue!] ofType: __Type } " %>% gqlr_schema( "__Type" = list( resolve = function(type_obj, schema) { type_obj <- as_type(type_obj) ret <- list( kind = type_obj, name = function(z1, z2, z3) { if (inherits(type_obj, "ListType")) return(NULL) if (inherits(type_obj, "NonNullType")) return(NULL) name_value(type_obj) }, description = function(z1, z2, z3) { if (inherits(type_obj, "ListType")) return(NULL) if (inherits(type_obj, "NonNullType")) return(NULL) obj <- schema$get_type(type_obj) obj$description } ) if ( inherits(type_obj, "NonNullType") || inherits(type_obj, "ListType") ) { ret$ofType <- function(z1, z2, z3) { inner_type <- type_obj$type inner_type } return(ret) } if ( schema$is_object(type_obj) || schema$is_interface(type_obj) ) { ret$fields <- function(z1, args, z2) { include_deprecated <- args$includeDeprecated if (!is.null(include_deprecated)) { } obj <- ifnull( schema$get_object(type_obj), schema$get_interface(type_obj) ) fields <- obj$fields if (is.null(fields)) return(NULL) fields } } if (schema$is_object(type_obj)) { ret$interfaces <- function(z1, z2, z3) { obj <- schema$get_object(type_obj) obj_interfaces <- obj$interfaces if (is.null(obj_interfaces)) return(NULL) obj_interfaces } } if (schema$is_interface(type_obj)) { ret$possibleTypes <- function(z1, z2, z3) { possible_types <- schema$implements_interface(type_obj) if (is.null(possible_types)) return(NULL) possible_types } } else if (schema$is_union(type_obj)) { ret$possibleTypes <- function(z1, z2, z3) { union_obj <- schema$get_union(type_obj) union_type_names <- union_obj$types if (is.null(union_type_names)) return(NULL) union_type_names } } if (schema$is_enum(type_obj)) { ret$enumValues <- function(z1, args, z3) { include_deprecated <- args$includeDeprecated if (!is.null(include_deprecated)) { } enum_obj <- schema$get_enum(type_obj) enum_values <- enum_obj$values if (is.null(enum_values)) return(NULL) enum_values } } if (schema$is_input_object(type_obj)) { ret$inputFields <- function(z1, z2, z3) { input_obj <- schema$get_input_object(type_obj) input_obj_fields <- input_obj$fields if (is.null(input_obj_fields)) return(NULL) input_obj_fields } } ret } ) ) %>% get_definition("__Type") -> Introspection__Type " type __Field { name: String! description: String args: [__InputValue!]! type: __Type! isDeprecated: Boolean! deprecationReason: String } " %>% gqlr_schema( "__Field" = list( description = collapse( "Object and Interface types are described by a list of Fields, each of ", "which has a name, potentially a list of arguments, and a return type." ), fields = list( args = "returns a List of __InputValue representing the arguments this field accepts", type = "must return a __Type that represents the type of value returned by this field", isDeprecated = "returns true if this field should no longer be used, otherwise false", deprecationReason = "optionally provides a reason why this field is deprecated" ), resolve = function(field_obj, schema) { list( name = format(field_obj$name), description = field_obj$description, args = ifnull(field_obj$arguments, list()), type = field_obj$type, isDeprecated = FALSE, deprecationReason = NULL ) } ) ) %>% get_definition("__Field") -> Introspection__Field " type __InputValue { name: String! description: String type: __Type! defaultValue: String } " %>% gqlr_schema( "__InputValue" = list( description = collapse( "Arguments provided to Fields or Directives and the input fields of an ", "InputObject are represented as Input Values which describe their type ", "and optionally a default value." ), fields = list( type = "must return a __Type that represents the type this input value expects", defaultValue = collapse( "may return a String encoding (using the GraphQL language) of the default value used by ", "this input value in the condition a value is not provided at runtime. If this input ", "value has no default value, returns null." ) ), resolve = function(input_value, schema) { list( name = format(input_value$name), description = input_value$description, type = input_value$type, defaultValue = input_value$defaultValue$value ) } ) ) %>% get_definition("__InputValue") -> Introspection__InputValue " type __EnumValue { name: String! description: String isDeprecated: Boolean! deprecationReason: String } " %>% gqlr_schema( "__EnumValue" = list( description = collapse( "One possible value for a given Enum. Enum values are unique values, not ", "a placeholder for a string or numeric value. However an Enum value is ", "returned in a JSON response as a string." ), resolve = function(enum_value, schema) { list( name = format(enum_value$name), description = enum_value$description, isDeprecated = FALSE, deprecationReason = NULL ) } ) ) %>% get_definition("__EnumValue") -> Introspection__EnumValue " enum __TypeKind { SCALAR OBJECT INTERFACE UNION ENUM INPUT_OBJECT LIST NON_NULL } " %>% gqlr_schema( "__TypeKind" = list( description = "An enum describing what kind of type a given `__Type` is.", values = list( SCALAR = "Indicates this type is a scalar.", OBJECT = "Indicates this type is an object. `fields` and `interfaces` are valid fields.", INTERFACE = "Indicates this type is an interface. `fields` and `possibleTypes` are valid fields.", UNION = "Indicates this type is a union. `possibleTypes` is a valid field.", ENUM = "Indicates this type is an enum. `enumValues` is a valid field.", INPUT_OBJECT = "Indicates this type is an input object. `inputFields` is a valid field.", LIST = "Indicates this type is a list. `ofType` is a valid field.", NON_NULL = "Indicates this type is a non-null. `ofType` is a valid field." ), resolve = function(type_obj, schema) { if (inherits(type_obj, "NonNullType")) return("NON_NULL") if (inherits(type_obj, "ListType")) return("LIST") if (schema$is_scalar(type_obj)) return("SCALAR") if (schema$is_object(type_obj)) return("OBJECT") if (schema$is_interface(type_obj)) return("INTERFACE") if (schema$is_union(type_obj)) return("UNION") if (schema$is_enum(type_obj)) return("ENUM") if (schema$is_input_object(type_obj)) return("INPUT_OBJECT") str(type_obj) stop("this should not be reached") } ) ) %>% get_definition("__TypeKind") -> Introspection__TypeKind " type __Directive { name: String! description: String locations: [__DirectiveLocation!]! args: [__InputValue!]! } " %>% gqlr_schema( "__Directive" = list( description = collapse( "A Directive provides a way to describe alternate runtime execution and ", "type validation behavior in a GraphQL document.", "\n\nIn some cases, you need to provide options to alter GraphQL's ", "execution behavior in ways field arguments will not suffice, such as ", "conditionally including or skipping a field. Directives provide this by ", "describing additional information to the executor." ), fields = list( locations = collapse( "returns a List of __DirectiveLocation representing the valid locations ", "this directive may be placed" ), args = "returns a List of __InputValue representing the arguments this directive accepts" ), resolve = function(directive_obj, schema) { list( name = format(directive_obj$name), description = directive_obj$description, locations = lapply(directive_obj$locations, format), args = ifnull(directive_obj$arguments, list()) ) } ) ) %>% get_definition("__Directive") -> Introspection__Directive " enum __DirectiveLocation { QUERY MUTATION FIELD FRAGMENT_DEFINITION FRAGMENT_SPREAD INLINE_FRAGMENT } " %>% gqlr_schema( "__DirectiveLocation" = list( description = collapse( "A Directive can be adjacent to many parts of the GraphQL language, a ", "__DirectiveLocation describes one such possible adjacencies." ), values = list( QUERY = "Location adjacent to a query", MUTATION = "Location adjacent to a mutation", FIELD = "Location adjacent to a field", FRAGMENT_DEFINITION = "Location adjacent to a fragment definition", FRAGMENT_SPREAD = "Location adjacent to a fragment spread", INLINE_FRAGMENT = "Location adjacent to a inline fragment" ) ) ) %>% get_definition("__DirectiveLocation") -> Introspection__DirectiveLocation " type QueryRootFields { __schema: __Schema! __type(name: String!): __Type } " %>% gqlr_schema() %>% get_definition("QueryRootFields") -> Introspection__QueryRootFields Introspection__QueryRootFields$fields[[1]]$.show_in_format <- FALSE Introspection__QueryRootFields$fields[[1]]$.allow_double_underscore <- TRUE Introspection__QueryRootFields$fields[[2]]$.show_in_format <- FALSE Introspection__QueryRootFields$fields[[2]]$.allow_double_underscore <- TRUE Introspection__QueryRootFields$loc <- NULL Introspection__QueryRootFields$name$loc <- NULL Introspection__QueryRootFields$fields[[1]]$loc <- NULL Introspection__QueryRootFields$fields[[1]]$name$loc <- NULL Introspection__QueryRootFields$fields[[1]]$type$loc <- NULL Introspection__QueryRootFields$fields[[1]]$type$type$name$loc <- NULL Introspection__QueryRootFields$fields[[2]]$loc <- NULL Introspection__QueryRootFields$fields[[2]]$name$loc <- NULL Introspection__QueryRootFields$fields[[2]]$type$loc <- NULL Introspection__QueryRootFields$fields[[2]]$type$name$loc <- NULL Introspection__QueryRootFields$fields[[2]]$arguments[[1]]$loc <- NULL Introspection__QueryRootFields$fields[[2]]$arguments[[1]]$name$loc <- NULL Introspection__QueryRootFields$fields[[2]]$arguments[[1]]$type$loc <- NULL Introspection__QueryRootFields$fields[[2]]$arguments[[1]]$type$type$loc <- NULL Introspection__QueryRootFields$fields[[2]]$arguments[[1]]$type$type$name$loc <- NULL gqlr_env$completed_introspection <- TRUE })
golem_files <- function(react = FALSE, vue = FALSE, framework7 = FALSE){ base <- pkg_file("golem/javascript") if(any(react, vue, framework7)) fs::dir_create("srcjs") else fs::dir_copy(base, "srcjs") cli::cli_alert_success("Created {.file srcjs} directory") }
library("data.table") library("wyz.code.offensiveProgramming") library("wyz.code.rdoc") gc <- GenerationContext('inst/man-generated', overwrite_b_1 = TRUE, verbosity_b_1 = FALSE, useMarkers_b_1 = FALSE) target_package_name <- 'wyz.code.rdoc' source(findFilesInPackage('AdditionTCFIP.R', 'wyz.code.offensiveProgramming')[1]) ic <- InputContext(AdditionTCFIP(), packageName_s_1 = target_package_name) r <- produceManualPage(ic, gene = gc) interpretResults(r) source(findFilesInPackage('Addition_TCFI_Partial_R6.R', 'wyz.code.offensiveProgramming')[1]) ic <- InputContext(Addition_TCFI_Partial_R6$new(), packageName_s_1 = target_package_name) r <- produceManualPage(ic, gene = gc) interpretResults(r) source(findFilesInPackage('Addition_TCFI_Partial_S3.R', 'wyz.code.offensiveProgramming')[1]) ic <- InputContext(Addition_TCFI_Partial_S3(), packageName_s_1 = target_package_name) r <- produceManualPage(ic, gene = gc) interpretResults(r) source(findFilesInPackage('Addition_TCFI_Partial_S4.R', 'wyz.code.offensiveProgramming')[1]) ic <- InputContext(new('Addition_TCFI_Partial_S4'), packageName_s_1 = target_package_name) r <- produceManualPage(ic, gene = gc) interpretResults(r) source(findFilesInPackage('Addition_TCFI_Partial_RC.R', 'wyz.code.offensiveProgramming')[1]) ic <- InputContext(new('Addition_TCFI_Partial_RC'), packageName_s_1 = target_package_name) r <- produceManualPage(ic, gene = gc) interpretResults(r)
setClass("armacopula", contains = "tscopula", slots = list( name = "character", modelspec = "numeric", pars = "list" )) armacopula <- function(pars = list(ar = 0, ma = 0)) { if ("ar" %in% names(pars)) { arpars <- pars$ar if (is.null(arpars)) { stop("No NULL values for parameters; omit from list instead") } if (non_stat(arpars)) { stop("Non-stationary AR model") } p <- length(arpars) names(pars$ar) <- paste("ar", 1:p, sep = "") } else { p <- 0 } if ("ma" %in% names(pars)) { mapars <- pars$ma if (is.null(mapars)) { stop("No NULL values for parameters; omit from list instead") } if (non_invert(mapars)) { stop("Non-nvertible MA model") } q <- length(mapars) names(pars$ma) <- paste("ma", 1:q, sep = "") } else { q <- 0 } if ((p == 0) & (q == 0)) { stop("Specify named ar and/or ma parameters") } new("armacopula", name = paste("ARMA(", p, ",", q, ")", sep = ""), modelspec = c(p = p, q = q), pars = pars ) } setMethod("coef", "armacopula", function(object) { p <- object@modelspec[1] q <- object@modelspec[2] if (p > 0) { arpars <- object@pars$ar } else { arpars <- NULL } if (q > 0) { mapars <- object@pars$ma } else { mapars <- NULL } c(arpars, mapars) }) setMethod("show", c(object = "armacopula"), function(object) { cat("object class: ", is(object)[[1]], "\n", sep = "") cat("name: ", object@name, "\n", sep = "") cat("parameters: \n") print(coef(object)) }) non_stat <- function(ar) { status <- FALSE if (sum(ar^2) > 0) { roots <- polyroot(c(1, -ar)) if (min(abs(roots)) <= 1) { status <- TRUE } } status } non_invert <- function(ma) { status <- FALSE if (sum(ma^2) > 0) { roots <- polyroot(c(1, ma)) if (min(abs(roots)) <= 1) { status <- TRUE } } status } setMethod("sim", c(object = "armacopula"), function(object, n = 1000) { pnorm(arima.sim( model = object@pars, n = n, n.start = 10, sd = sigmastarma(object) )) }) sigmastarma <- function(x) { ar <- x@pars$ar ma <- x@pars$ma if (length(ar) == 0) { ar <- 0 } if (length(ma) == 0) { ma <- 0 } 1 / sqrt(ltsa::tacvfARMA(phi = ar, theta = -ma, maxLag = 0, sigma2 = 1)) } armacopula_objective <- function(theta, modelspec, u) { xdata <- qnorm(u) p <- modelspec[1] ar <- 0 q <- modelspec[2] ma <- 0 if (p > 0) { ar <- theta[1:p] } if (q > 0) { ma <- theta[(p + 1):(p + q)] } if (non_stat(ar) | non_invert(ma)) { output <- NA } else { sp <- starmaStateSpace(ar, ma, c(p, q)) ans <- FKF::fkf( a0 = sp$a0, P0 = sp$P0, dt = sp$dt, ct = sp$ct, Tt = sp$Tt, Zt = sp$Zt, HHt = sp$HHt, GGt = sp$GGt, yt = rbind(xdata) ) output <- -ans$logLik + sum(log(dnorm(xdata))) } return(output) } starmaStateSpace <- function(ar, ma, order) { p <- order[1] q <- order[2] m <- max(p, q + 1) allar <- rep(0, m) allma <- rep(0, m) if (p > 0) { allar[1:p] <- ar } if (q > 0) { allma[1:q] <- ma } Tt <- matrix(allar) Zt <- matrix(1) if (m > 1) { block1 <- diag(m - 1) block2 <- matrix(0, ncol = m - 1) rmat <- rbind(block1, block2) Tt <- cbind(Tt, rmat) Zt <- cbind(Zt, matrix(0, ncol = m - 1)) } ct <- matrix(0) dt <- matrix(0, nrow = m) GGt <- matrix(0) sigma2 <- ltsa::tacvfARMA(phi = ar, theta = -ma, maxLag = 0, sigma2 = 1) Hcontent <- 1 if (m > 1) { Hcontent <- c(1, allma[1:(m - 1)]) } H <- matrix(Hcontent, nrow = m) / sqrt(sigma2) HHt <- H %*% t(H) a0 <- rep(0, m) P0 <- matrix(solve(diag(1, m^2) - kronecker(Tt, Tt)) %*% as.vector(HHt), nrow = m, ncol = m ) return(list(a0 = a0, P0 = P0, ct = ct, dt = dt, Zt = Zt, Tt = Tt, GGt = GGt, HHt = HHt)) } kfilter <- function(x, y) { n <- length(y) ar <- x@pars$ar p <- x@modelspec[1] if (p == 0) { ar <- 0 } ma <- x@pars$ma q <- x@modelspec[2] if (q == 0) { ma <- 0 } sp <- starmaStateSpace(ar, ma, c(p, q)) ans <- FKF::fkf( a0 = sp$a0, P0 = sp$P0, dt = sp$dt, ct = sp$ct, Tt = sp$Tt, Zt = sp$Zt, HHt = sp$HHt, GGt = sp$GGt, yt = rbind(as.numeric(qnorm(y))) ) mu_t <- ans$at[1, 1:n] sigma_t <- sqrt(ans$Ft[1, 1, 1:n]) resid <- ans$vt[1, 1:n] if (inherits(x, "zoo")) { attributes(resid) <- attributes(x) attributes(mu_t) <- attributes(x) attributes(sigma_t) <- attributes(x) } fseries <- cbind(mu_t, sigma_t, resid) dimnames(fseries) <- list(NULL, c("mu_t", "sigma_t", "resid")) fseries } resid_armacopula <- function(object, data = NA, trace = FALSE){ series <- kfilter(object, data) if (trace) output <- series[, "mu_t"] else output <- series[, "resid"]/sigmastarma(object) output } setMethod("kendall", c(object = "armacopula"), function(object, lagmax = 20){ ar <- 0 ma <- 0 if (object@modelspec[1] > 0) ar <- object@pars$ar if (object@modelspec[2] > 0) ma <- object@pars$ma pacf <- ARMAacf(ar = ar, ma = ma, lag.max = lagmax, pacf = TRUE) tau <- (2/pi)*asin(pacf) tau } ) glag_for_armacopula <- function(copula, data, lagmax, glagplot = FALSE) { n <- length(data) k <- lagmax data <- cbind(as.numeric(data[1:(n - 1)]), as.numeric(data[2:n])) if (glagplot){ k <- min(k, 9) output <- vector(mode = "list", length = k) output[[1]] <- data } else{ output <- rep(NA, k) output[1] <- cor(data, method = "kendall")[1, 2] } ar <- 0 ma <- 0 if (copula@modelspec[1] > 0) ar <- copula@pars$ar if (copula@modelspec[2] > 0) ma <- copula@pars$ma pacf <- ARMAacf(ar = ar, ma = ma, lag.max = lagmax, pacf = TRUE) if (k >1){ for (i in 1:(k - 1)) { n <- dim(data)[1] model <- rvinecopulib::bicop_dist(family = "gauss", parameters = pacf[i]) data <- cbind(rvinecopulib::hbicop(data[(1:(n - 1)), ], model, cond_var = 2), rvinecopulib::hbicop(data[(2:n), ], model, cond_var = 1)) if (glagplot) output[[i+1]] <- data else output[i+1] <- cor(data, method = "kendall")[1, 2] } } output }
setGeneric( "wapply", function( object, ... ) { standardGeneric( "wapply" ) } ) setMethod( f = "wapply", signature = c( object = "WeaAna" ), definition = function( object, vars, period, FUN, ARGS = NULL, site.ARGS = NULL, res.name = "result", yrange = waGetPara( "yrange" ), as.data.frame = FALSE, extra = NULL) { res <- NULL if ( as.data.frame == TRUE ) { if ( length( period ) > 1 ) { stop( "Only one period supported for data frame results" ) } } else { res <- as.list( NULL ) for ( i in 1:length( vars ) ) { res[[i]] <- as.list( NULL ) } } for ( i in seq( along = vars ) ) { if ( is.na( res.name[i] ) ) { res.name[i] <- paste( "result", i, sep = "" ) } } if (!is.null(extra)) { extra <- as.data.frame(extra) } if ( is.null( FUN ) ) { stop( "FUN can not be NULL." ) } t.fun <- as.list( NULL ) if ( length( FUN ) > 1 ) { for ( i in seq( along = FUN ) ) { t.fun[[i]] <- FUN[[i]] } } else { t.fun[[1]] <- FUN } t.fun <- rep( t.fun, length.out = length( vars ) ) if ( length( period ) > 1 ) { old.period <- period period <- NULL period[[1]] <- old.period } period <- rep( period, length.out = length( vars ) ) period <- as.list( period ) if ( !is.null( ARGS ) ) ARGS <- rep( ARGS, length.out = length( vars ) ) if ( !is.null( site.ARGS ) ) { for ( i in seq( site.ARGS ) ) { site.ARGS[[i]] <- rep( site.ARGS[[i]], length.out = object@num ) } } if ( object@num == 0 ) { warning( "No weather records in this object." ) return( NULL ) } used.args <- 0 for ( i in 1:object@num ) { records <- getWeaAnaSiteByPos( object, i ) record <- records$value w.data <- getWeatherRecords( object[i], yrange = yrange, vars = vars ) n.vars <- names( w.data ) for ( j in seq( along = vars ) ) { if ( !( vars[j] %in% n.vars ) ) { warning( paste( "Variable(s) not exist, skip it:", paste( vars[j], collapse = ", " ) ) ) next() } key <- periodIndex( w.data$year, w.data$day, period[[j]] ) w.levels <- as.numeric( levels( as.factor( key ) ) ) if ( length( w.levels ) == 0 ) { warning( "No any levels which need to calculate. Skip this site." ) next() } site.res <- NULL site.res$Name = records$value@name site.res$Number = records$value@number site.res$Latitude = records$value@latitude site.res$Longitude = records$value@longitude site.res[[as.character( period[[j]][1] )]] = w.levels w.nlevels <- length( w.levels ) w.res <- NULL w.args <- ARGS[[j]] n.w.args <- names( w.args ) for ( m in seq( along = w.args ) ) { w.args[[m]] <- rep( w.args[[m]], length = used.args + w.nlevels ) } for ( k in 1:w.nlevels ) { l.data <- as.numeric( w.data[ key == w.levels[k], vars[j] ] ) l.args <- as.list( NULL ) l.args[[1]] <- l.data for ( m in seq( along = w.args ) ) { l.args[[n.w.args[m]]] <- w.args[[m]][k + used.args] } n.site.args <- names( site.ARGS ) for ( m in seq( along = site.ARGS ) ) { l.args[[n.site.args[m]]] <- site.ARGS[[m]][i] } l.res <- do.call( as.function( t.fun[[j]] ), l.args ) if ( length( l.res ) > 1 ) { warning( "Only first result is used." ) } w.res <- c( w.res, l.res[1] ) } used.args <- used.args + w.nlevels site.res[[res.name[j]]] <- w.res site.res <- as.data.frame( site.res, stringsAsFactors = FALSE ) if (!is.null(extra)) { names_site_res <- c(names(site.res), names(extra)) site.res <- cbind(site.res, extra[i,]) names(site.res) <- names_site_res } row.names( site.res ) <- seq( along = site.res[[1]] ) records$value@res[[res.name[j]]] <- site.res if ( as.data.frame == TRUE ) { if ( is.null( res ) ) { res <- site.res } else { res <- cbind( res, site.res[[6]] ) } } else { res[[j]] <- rbind( res[[j]], site.res ) } } } if ( as.data.frame == TRUE ) { res <- as.data.frame( res, stringsAsFactors = FALSE ) names( res ) <- c( "Name", "Number", "Latitude", "Longitude", period[[1]][1], res.name ) row.names( res ) <- seq( along = res[[1]] ) return( res ) } else { n.res <- NULL for ( i in 1:length( vars ) ) { temp <- as.data.frame( res[[i]], stringsAsFactors = FALSE ) row.names( temp ) <- seq( along = temp[[1]] ) registerRes( object, res.name[i], "data.frame" ) n.res[[res.name[i]]] <- temp } rm( res ) gc() if ( length( vars ) == 1 ) { return( n.res[[1]] ) } return( n.res ) } } )
default_max_iters <- function(numnode){ 2 * max(10, sqrt(numnode)) } default_alpha <- function(){ 10 }
FDistUlt<-function(X,n.obs=length(X),ref="OP",crt=1,plot=FALSE,subplot=FALSE,p.val_min=.05){ if(!is.numeric(ref)){}else{ if(ref>length(X)/3){warning("Number of clusters must be less than input length/3") return(NULL)}} desc<-function(X,fns=FALSE,ref.=ref,crt.=crt,subplot.=subplot,p.val_min.=p.val_min){ eval<-function(X,fns.=fns,crt.=crt,subplot.=subplot,p.val_min.=p.val_min){ FIT<-FDist(X,length(X),crit = crt,plot = subplot,p.val_min=p.val_min) FIT } div<-function(X,ref.=ref){ df<-data.frame(A=1:length(X),B=X) Enteros<-X-floor(X)==0 if(any(Enteros)){ if(all(Enteros)){ if(!is.numeric(ref)){ mod1<-mclust::Mclust(X,modelNames=c("E", "V"))$classification if(length(table(mod1))==1){ df$CL<-kmeans(df,2)$cluster }else{ df$CL<-mod1 } }else{ df$CL<-kmeans(df,ref)$cluster } }else{ df$CL<-ifelse(Enteros,1,2) } }else{ if(!is.numeric(ref)){ mod1<-mclust::Mclust(X)$classification if(length(table(mod1))==1){ df$CL<-kmeans(df,2)$cluster }else{ df$CL<-mod1 } }else{ df$CL<-kmeans(df,ref)$cluster } } CLS<-purrr::map(unique(df$CL),~df[df$CL==.x,2]) CLS return(CLS) } suppressWarnings(EV<-eval(X,fns)) if(is.null(EV)){ if(length(X)>40){ DV<-purrr::map(div(X),~desc(.x,fns)) return(DV) }else{ FN<-rnorm formals(FN)[1]<-length(X) formals(FN)[2]<-mean(X) formals(FN)[3]<-ifelse(length(X)==1,0,sd(X)) return(list(paste0("normal(",mean(X),",",ifelse(length(X)==1,0,sd(X)),")"),FN,FN(), data.frame(Dist="norm",AD_p.v=1,KS_p.v=1,estimate1=mean(X),estimate2=sd(X),estimateLL1=0,estimateLL2=1,PV_S=2) )) } }else{ return(EV) } } FCNS<-desc(X) flattenlist <- function(x){ morelists <- sapply(x, function(xprime) class(xprime)[1]=="list") out <- c(x[!morelists], unlist(x[morelists], recursive=FALSE)) if(sum(morelists)){ base::Recall(out) }else{ return(out) } } superficie<-flattenlist(FCNS) FUN<-superficie[purrr::map_lgl(superficie,~"function" %in% class(.x))] Global_FUN<-superficie[purrr::map_lgl(superficie,~"gl_fun" %in% class(.x))] Dist<-unlist(superficie[purrr::map_lgl(superficie,is.character)]) PLTS<-superficie[purrr::map_lgl(superficie,ggplot2::is.ggplot)] dfss<-superficie[purrr::map_lgl(superficie,~is.data.frame(.x))] PV<-do.call("rbind",dfss[purrr::map_lgl(dfss,~ncol(.x)==9)]) Len<-MA<-c() repp<-floor(n.obs/length(X))+1 for (OBS in 1:repp) { for (mst in 1:length(FUN)) { ljsd<-FUN[[mst]]() MA<-c(MA,ljsd) if(OBS==1){ Len<-c(Len,length(ljsd)/length(X)) } } } MA<-sample(MA,n.obs) pv1<-data.frame(Distribution=Dist[nchar(Dist)!=0],Dist_Prop=Len[nchar(Dist)!=0]) p.v<-try(cbind(pv1,PV)) if(assertthat::is.error(pv1)){p.v<-pv1} cp<-plt<-c() if(plot){ DF<-rbind(data.frame(A="Fit",DT=MA), data.frame(A="Real",DT=X)) plt <- ggplot2::ggplot(DF,ggplot2::aes(x=DF$DT,fill=DF$A)) + ggplot2::geom_density(alpha=0.55)+ggplot2::ggtitle("Original Dist.") plt } TPlts<-c() if(subplot){ cp<-cowplot::plot_grid(plotlist = PLTS, ncol = floor(sqrt(length(PLTS)))) } TPlts<-list(plt,cp) return(list(unlist(FUN),MA,p.v,TPlts,Global_FUN)) }
checkVars <- function(..., out = "assign", .env) { arg.list <- list(...) arg.names <- names(arg.list) arg.names2 <- as.character(eval(substitute(alist(...)))) if(is.null(arg.names)) { arg.names <- arg.names2 } else { arg.noname <- which(arg.names == "") arg.names[arg.noname] <- arg.names2[arg.noname] } names(arg.list) <- arg.names if ("assign" %in% out) { if (missing(.env) || !is.environment(.env)) { stop("argument \".env\" is missing or wrong type: Needs an environment.") } else { arg.list2 <- list(out = out, .env = .env) } } else { arg.list2 <- list(out = out) } tmp <- mapply(checkObject, obj = arg.list, obj.name = arg.names, MoreArgs = arg.list2, SIMPLIFY = FALSE) if("return" %in% out) { return(invisible(tmp)) } } checkObject <- function(obj, obj.name, ..., out = "return", .env) { arg.list <- list(...) arg.names <- names(arg.list) if (length(arg.list) > 1) { return(checkVars(..., out = out, .env = .env)) } if (length(arg.list) == 1) { obj <- arg.list[[1]] if (arg.names == "") { obj.name <- as.character(eval(substitute(alist(...)))) } else { obj.name <- arg.names[1] } } if (missing(obj.name)) { obj.name <- deparse(substitute(obj)) } out <- match.arg(out, c("return", "assign"), several.ok = TRUE) if (("assign" %in% out) & (missing(.env) || !is.environment(.env))) { stop("argument \".env\" is missing or wrong type: Needs an environment.") } bk <- c("ba", "bo", "da", "pa", "qs", "th", "tr") bd <- c("and", "nw") mod <- c("FM", "D", "IM") sel <- c(1, 2) poss.args <- c("y", "y.fm", "x.stat", "x.coint", "m", "model", "trend", "signif.level", "return.stats", "return.input", "deter", "kernel", "bandwidth", "demeaning", "t.test", "selector") obj.name <- match.arg(obj.name, choices = poss.args) if (testChoice(obj.name, c("y.fm", "x.coint", "deter"))) { assert(checkNumeric(obj), checkMatrix(obj), checkDataFrame(obj), .var.name = obj.name) if (testMatrix(obj) || testDataFrame(obj)) { if (nrow(obj) < ncol(obj)) { tmp <- t(as.matrix(obj)) } else { tmp <- as.matrix(obj) } } else { tmp <- matrix(obj, ncol = 1, dimnames = list(NULL, obj.name)) } } if (testChoice(obj.name, c("x.stat", "y"))) { assert(checkNumeric(obj), checkMatrix(obj), checkDataFrame(obj), .var.name = obj.name) if (testMatrix(obj) || testDataFrame(obj)) { if (nrow(obj) < ncol(obj)) { tmp <- t(as.matrix(obj[1, , drop = FALSE])) } else { tmp <- as.matrix(obj[, 1, drop = FALSE]) } if (nrow(obj) > 1 & ncol(obj) > 1) { if (nrow(obj) < ncol(obj)) { what <- "rows" hmany <- nrow(obj) } else { what <- "columns" hmany <- ncol(obj) } warning(obj.name, " has to many ", what, " (", hmany, ", but may have 1). Only the first one will be used.", call. = FALSE) } } else if (testNumeric(obj)) { tmp <- matrix(obj, ncol = 1, dimnames = list(NULL, obj.name)) } } if (obj.name == "m") { assertNumber(obj, lower = 0) tmp <- obj } if (obj.name == "model") { tmp <- match.arg(obj, mod) } if (obj.name == "signif.level") { assertNumber(obj, lower = 0.01, upper = 0.1) tmp <- obj } if (obj.name == "kernel") { tmp <- match.arg(obj[1], bk) } if (obj.name == "bandwidth") { if (is.character(obj)) { tmp <- match.arg(tolower(obj[1]), bd) } else { assertNumber(obj, lower = 0, finite = TRUE) tmp <- obj } } if (obj.name == "demeaning" || obj.name == "return.stats" || obj.name == "return.input" || obj.name == "t.test" || obj.name == "trend") { tmp <- as.logical(obj) assert(checkFlag(tmp), .var.name = obj.name) } if (obj.name == "selector") { tmp <- as.numeric(obj) assertSubset(tmp, sel) } if ("assign" %in% out) { assign(obj.name, value = tmp, envir = .env) } if ("return" %in% out) { return(invisible(tmp)) } } checkDoptions <- function(n.lag = NULL, n.lead = NULL, kmax = c("k4", "k12"), info.crit = c("AIC", "BIC")) { assert(checkNull(n.lag), checkNumber(n.lag, lower = 0)) assert(checkNull(n.lead), checkNumber(n.lead, lower = 0)) if (testNumber(n.lead) && testNumber(n.lag)) { n.lag <- as.integer(n.lag) n.lead <- as.integer(n.lead) kmax <- info.crit <- NULL } else { n.lag <- n.lead <- NULL kmax <- match.arg(kmax) info.crit <- match.arg(info.crit) } return(list(n.lag = n.lag, n.lead = n.lead, kmax = kmax, info.crit = info.crit)) }
gridinfer <- function (file = NULL, dntable = NULL, sp_row = TRUE, reciprocity = TRUE, criterion = "max", tolerance = sqrt(2), conditioned = TRUE, ...) { coords <- NULL if (is.null(dntable)) dntable <- read.table(file, ...) if(sp_row) m <- as.matrix(dntable) else m <- as.matrix(t(dntable)) if(any(m < 0)) stop("Sorry, but distributional matrix includes misleading negative entries\n") coords <- floor(t(m[1:2,,drop=FALSE])) if(any(duplicated(coords))) stop(paste("Each cell must be identified through an exclusive pair of coordinates\n", "Please, check your coordinates for duplciates")) m <- m[-(1:2),,drop = FALSE] & m[-(1:2),,drop =FALSE] if(!all(apply(m, 1, any))) stop("Error: you have included species without presences") dcells <- as.matrix(dist(coords)) if(conditioned) sm <- m %*% t(m) else sm <- matrix(TRUE, nrow(m), nrow(m)) if(reciprocity) oper <- "&" else oper <- "|" for(i in 1:(nrow(m)-1)) for(j in (i+1):nrow(m)) { sp1 <- apply(dcells[m[i,], m[j,], drop = FALSE], 1, min) sp2 <- apply(dcells[m[i,], m[j,], drop = FALSE], 2, min) if(!(eval(call(oper, eval(call(criterion, sp1)) <= tolerance, eval(call(criterion, sp2)) <= tolerance)) & sm[i, j])) sm[i,j] <- sm[j, i] <- FALSE } out <- list(sm = ifelse(sm, 1, 0), Label = rownames(m), occupancy = apply(m, 1, which), coords = coords, kind = "grids") class(out) <- "gridinference" return(out) }
setwd('inst/examples') for (tpl in list.files('../rmarkdown/templates', full.names = TRUE)) { f = list.files(tpl, '^skeleton[.]Rmd$', recursive = TRUE, full.names = TRUE) file.copy(f, paste0(basename(tpl), '.Rmd')) } options(htmltools.dir.version = FALSE) for (f in list.files('.', '[.]Rmd$')) { rmarkdown::render(f, output_options = list(self_contained = FALSE)) } writeLines(c( 'http://pagedown.netlify.com/* https://pagedown.rbind.io/:splat 301!', 'http://pagedown.rbind.io/* https://pagedown.rbind.io/:splat 301!' ), '_redirects')
setMethodS3("calmateByThetaAB", "array", function(data, references=NULL, ..., truncate=FALSE, refAvgFcn=NULL, flavor=c("v2", "v1"), verbose=FALSE) { if (!is.array(data)) { throw("Argument 'data' is not an array: ", class(data)[1]); } dim <- dim(data); dimnames <- dimnames(data); if (length(dim) != 3) { throw("Argument 'data' is not a 3-dimensional array: ", paste(dim, collapse="x")); } if (dim[2] != 2) { throw("Argument 'data' is not a Jx2xI-dimensional array: ", paste(dim, collapse="x")); } if (!is.null(dimnames[[2]])) { if (!identical(dimnames[[2]], c("A", "B"))) { throw("If given, the names of the allele (2nd) dimension of the Jx2xI-dimensional array (argument 'data') have to be 'A' & 'B': ", paste(dimnames[[2]], collapse=", ")); } } nbrOfSamples <- dim[3]; if (nbrOfSamples < 3) { throw("Argument 'data' contains less than three samples: ", nbrOfSamples); } if (is.null(references)) { references <- seq(length=nbrOfSamples); } else if (is.logical(references)) { if (length(references) != nbrOfSamples) { throw("Length of argument 'references' does not match the number of samples in argument 'data': ", length(references), " != ", nbrOfSamples); } references <- which(references); } else if (is.numeric(references)) { references <- as.integer(references); if (any(references < 1 | references > nbrOfSamples)) { throw(sprintf("Argument 'references' is out of range [1,%d]: %d", nbrOfSamples), length(references)); } } if (length(references) < 3) { throw("Argument 'reference' specify less than three reference samples: ", length(references)); } flavor <- match.arg(flavor); verbose <- Arguments$getVerbose(verbose); dimnames(data)[[2]] <- c("A", "B"); verbose && enter(verbose, "calmateByThetaAB()"); verbose && cat(verbose, "ASCN signals:"); verbose && str(verbose, data); verbose && cat(verbose, "Reference samples:"); verbose && str(verbose, references); verbose && enter(verbose, "Identifying non-finite data points"); ok <- (is.finite(data[,"A",,drop=FALSE]) & is.finite(data[,"B",,drop=FALSE])); dim(ok) <- dim(ok)[-2]; ok <- rowAlls(ok); verbose && summary(verbose, ok); hasNonFinite <- any(!ok); if (hasNonFinite) { verbose && enter(verbose, "Excluding non-finite data points"); dataS <- data[ok,,,drop=FALSE]; verbose && str(verbose, data); verbose && exit(verbose); dim <- dim(dataS); } else { verbose && cat(verbose, "All data points are finite."); dataS <- data; } verbose && exit(verbose); verbose && enter(verbose, "Fitting CalMaTe"); verbose && cat(verbose, "Algorithm flavor: ", flavor); if (flavor == "v2") { fitFcn <- fitCalMaTeV2; } else if (flavor == "v1") { fitFcn <- fitCalMaTeV1; } else { throw("Unknown algorithm flavor: ", flavor); } nbrOfSNPs <- dim(dataS)[1]; verbose && cat(verbose, "Number of SNPs: ", nbrOfSNPs); verbose && printf(verbose, "Number of SNPs left: "); dimnames(dataS) <- NULL; dimCjj <- dim(dataS)[-1]; for (jj in seq(length=nbrOfSNPs)) { if (verbose && (jj %% 500 == 1)) { writeRaw(verbose, sprintf("%d, ", nbrOfSNPs-jj+1)); } Cjj <- dataS[jj,,,drop=FALSE]; dim(Cjj) <- dimCjj; CCjj <- fitFcn(Cjj, references=references, ...); stopifnot(identical(dim(CCjj), dimCjj)); dataS[jj,,] <- CCjj; } if (verbose) writeRaw(verbose, "done.\n"); verbose && exit(verbose); if (hasNonFinite) { verbose && enter(verbose, "Expanding to array with non-finite"); dataC <- data; dataC[ok,,] <- dataS; verbose && str(verbose, dataC); verbose && exit(verbose); } else { dataC <- dataS; dimnames(dataC) <- dimnames(data); } rm(dataS); stopifnot(identical(dim(dataC), dim(data))); verbose && cat(verbose, "Calibrated ASCN signals:"); verbose && str(verbose, dataC); if (truncate){ dataC <- truncateThetaAB(dataC); verbose && cat(verbose, "Truncated ASCN signals:"); verbose && str(verbose, dataC); } if (!is.null(refAvgFcn)) { verbose && enter(verbose, "Standardize total copy numbers toward the average reference signals"); dataCR <- dataC[,,references,drop=FALSE]; yCR <- dataCR[,1,,drop=FALSE]+dataCR[,2,,drop=FALSE]; dim(yCR) <- dim(yCR)[-2]; yCR <- refAvgFcn(yCR, na.rm=TRUE); dataC <- 2 * dataC / yCR; verbose && exit(verbose); } dimnames(dataC) <- dimnames; verbose && cat(verbose, "Calibrated (A,B) signals:"); verbose && str(verbose, dataC); verbose && exit(verbose); dataC; })
relabelclusters <- function(refcluster, cluster) { res <- NULL k <- length(table(refcluster)) n <- length(refcluster) permut <- combinat::permn(1:k) npermut <- length(permut) kappas <- rep(NA, npermut) auxcluster <- list() kappas <- lapply(permut, FUN = function(x) { auxcluster <- rep(NA, n) for (j in 1:k) auxcluster[cluster == j] <- x[j] irr::kappa2(ratings = cbind(refcluster, auxcluster), weight = "equal")$value } ) kappas <- unlist(kappas) id <- which(kappas == max(kappas)) if (length(id) > 1) id <- sample(id, 1) kappa <- kappas[id] id <- permut[[id]] newcluster <- rep(NA, n) for (j in 1:k) newcluster[cluster == j] <- id[j] res$newcluster <- newcluster res$kappa <- kappa return(res) }
expect_as_vector <- function(x, y, ...) { expect_equal(as.vector(x), y, ...) } expect_data_frame <- function(x, y, ...) { expect_equal(as.data.frame(x), y, ...) } expect_r6_class <- function(object, class) { expect_s3_class(object, class) expect_s3_class(object, "R6") } expect_equal <- function(object, expected, ignore_attr = FALSE, ..., info = NULL, label = NULL) { if (inherits(object, "ArrowObject") && inherits(expected, "ArrowObject")) { mc <- match.call() expect_true( all.equal(object, expected, check.attributes = !ignore_attr), info = info, label = paste(rlang::as_label(mc[["object"]]), "==", rlang::as_label(mc[["expected"]])) ) } else { testthat::expect_equal(object, expected, ignore_attr = ignore_attr, ..., info = info, label = label) } } expect_type_equal <- function(object, expected, ...) { if (is.Array(object)) { object <- object$type } if (is.Array(expected)) { expected <- expected$type } expect_equal(object, expected, ...) } expect_match_arg_error <- function(object, values = c()) { expect_error(object, paste0("'arg' .*", paste(dQuote(values), collapse = ", "))) } expect_deprecated <- expect_warning verify_output <- function(...) { if (isTRUE(grepl("conda", R.Version()$platform))) { skip("On conda") } testthat::verify_output(...) } compare_dplyr_binding <- function(expr, tbl, skip_record_batch = NULL, skip_table = NULL, warning = NA, ...) { expr <- rlang::enquo(expr) expected <- rlang::eval_tidy(expr, rlang::new_data_mask(rlang::env(.input = tbl))) if (isTRUE(warning)) { warning <- "not supported (in|by) Arrow; pulling data into R" } skip_msg <- NULL if (is.null(skip_record_batch)) { expect_warning( via_batch <- rlang::eval_tidy( expr, rlang::new_data_mask(rlang::env(.input = record_batch(tbl))) ), warning ) expect_equal(via_batch, expected, ...) } else { skip_msg <- c(skip_msg, skip_record_batch) } if (is.null(skip_table)) { expect_warning( via_table <- rlang::eval_tidy( expr, rlang::new_data_mask(rlang::env(.input = arrow_table(tbl))) ), warning ) expect_equal(via_table, expected, ...) } else { skip_msg <- c(skip_msg, skip_table) } if (!is.null(skip_msg)) { skip(paste(skip_msg, collapse = "\n")) } } compare_dplyr_error <- function(expr, tbl, ...) { force(tbl) expr <- rlang::enquo(expr) msg <- tryCatch( rlang::eval_tidy(expr, rlang::new_data_mask(rlang::env(.input = tbl))), error = function(e) { msg <- conditionMessage(e) if (grepl("Problem while computing", msg[1])) { msg <- conditionMessage(e$parent) } pattern <- i18ize_error_messages() if (grepl(pattern, msg)) { msg <- sub(paste0("^.*(", pattern, ").*$"), "\\1", msg) } msg } ) expect_true(identical(typeof(msg), "character"), label = "dplyr on data.frame errored") expect_error( rlang::eval_tidy( expr, rlang::new_data_mask(rlang::env(.input = record_batch(tbl))) ), msg, ... ) expect_error( rlang::eval_tidy( expr, rlang::new_data_mask(rlang::env(.input = arrow_table(tbl))) ), msg, ... ) } compare_expression <- function(expr, vec, skip_array = NULL, skip_chunked_array = NULL, ignore_attr = FALSE, ...) { expr <- rlang::enquo(expr) expected <- rlang::eval_tidy(expr, rlang::new_data_mask(rlang::env(.input = vec))) skip_msg <- NULL if (is.null(skip_array)) { via_array <- rlang::eval_tidy( expr, rlang::new_data_mask(rlang::env(.input = Array$create(vec))) ) expect_as_vector(via_array, expected, ignore_attr, ...) } else { skip_msg <- c(skip_msg, skip_array) } if (is.null(skip_chunked_array)) { split_vector <- split_vector_as_list(vec) via_chunked <- rlang::eval_tidy( expr, rlang::new_data_mask(rlang::env(.input = ChunkedArray$create(split_vector[[1]], split_vector[[2]]))) ) expect_as_vector(via_chunked, expected, ignore_attr, ...) } else { skip_msg <- c(skip_msg, skip_chunked_array) } if (!is.null(skip_msg)) { skip(paste(skip_msg, collapse = "\n")) } } compare_expression_error <- function(expr, vec, skip_array = NULL, skip_chunked_array = NULL, ...) { expr <- rlang::enquo(expr) msg <- tryCatch( rlang::eval_tidy(expr, rlang::new_data_mask(rlang::env(.input = vec))), error = function(e) { msg <- conditionMessage(e) pattern <- i18ize_error_messages() if (grepl(pattern, msg)) { msg <- sub(paste0("^.*(", pattern, ").*$"), "\\1", msg) } msg } ) expect_true(identical(typeof(msg), "character"), label = "vector errored") skip_msg <- NULL if (is.null(skip_array)) { expect_error( rlang::eval_tidy( expr, rlang::new_data_mask(rlang::env(.input = Array$create(vec))) ), msg, ... ) } else { skip_msg <- c(skip_msg, skip_array) } if (is.null(skip_chunked_array)) { split_vector <- split_vector_as_list(vec) expect_error( rlang::eval_tidy( expr, rlang::new_data_mask(rlang::env(.input = ChunkedArray$create(split_vector[[1]], split_vector[[2]]))) ), msg, ... ) } else { skip_msg <- c(skip_msg, skip_chunked_array) } if (!is.null(skip_msg)) { skip(paste(skip_msg, collapse = "\n")) } } split_vector_as_list <- function(vec) { vec_split <- length(vec) %/% 2 vec1 <- vec[seq(from = min(1, length(vec) - 1), to = min(length(vec) - 1, vec_split), by = 1)] vec2 <- vec[seq(from = min(length(vec), vec_split + 1), to = length(vec), by = 1)] list(vec1, vec2) }
tfr <- "^runit\\..*\\.R" pkgDir<-'../../../' if (is.element('SoilR',installed.packages())){ devtools::uninstall(pkgDir) } devtools::install(pkgDir,quick=TRUE) require("parallel") require("RUnit") require("deSolve") require("devtools") require("SoilR") source("../testhelpers.R") alltests <- defineTestSuite( name="suite for manual testing with the SoilR package loaded", dirs=c("."), testFileRegexp = tfr, "test.NonlinearOperators" ) testResult <- runTestSuite(alltests) printTextProtocol(testResult,separateFailureList=TRUE) ef=getErrors(testResult) n=ef$nErr+ef$nFail if (n>0) {stop(1)}
format_date <- function(date) { WEEKDAYS <- c( "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" ) weekday <- WEEKDAYS[lubridate::wday(date, week_start = 1)] day <- format(date, "%d") month <- month.name[as.integer(format(date, "%m"))] year <- format(date, "%Y") return(paste( weekday, day, month, year )) }
predM <- function(p.m, p.r) { length <- length(p.m) result <- numeric(length) for (i in 1:length) { if (is.infinite(p.m[i]) & p.m[i] < 0) { result[i] <- 0 next } if (is.infinite(p.r[i]) & p.r[i] < 0) { result[i] <- 1 next } result[i] <- p.m[i] / (p.m[i] + p.r[i]) } result } predMV <- function(p.m, p.r) { length <- length(p.m) result <- numeric(length) for (i in 1:length) { if (is.infinite(p.m[i]) & p.m[i] < 0) { result[i] <- 0 next } if (is.infinite(p.r[i]) & p.r[i] < 0) { result[i] <- 1 next } result[i] <- 1 / (1 + exp(p.r[i] - p.m[i])) } result } fitStateMR <- function(data, theta, cutoff = 0.5, integrControl = integr.control()) { if (!is.matrix(data)) data <- as.matrix(data) dinc <- apply(data, 2, diff) integrControl <- unlist(integrControl) ncol_data <- ncol(data) cart_result <- fwd_bwd_mr(theta, dinc, integrControl) cart_fwd <- cart_result[, 1:2] cart_bwd <- cart_result[, 3:4] cart_result <- cart_fwd * cart_bwd predM <- predM(cart_result[, 1], cart_result[, 2]) cart_state <- ifelse(predM > cutoff, 1, 0) result <- cbind(data, cart_result, cart_state) colnames(result)[(ncol_data+1):(ncol_data+3)] <- c("p.m", "p.r", "states") as.data.frame(result) } fitViterbiMR <- function(data, theta, cutoff = 0.5, integrControl = integr.control()) { if (!is.matrix(data)) data <- as.matrix(data) dinc <- apply(data, 2, diff) integrControl <- unlist(integrControl) ncol_data <- ncol(data) cart_result <- viterbi_mr(theta, dinc, integrControl) predM <- predMV(cart_result[, 1], cart_result[, 2]) cart_state <- ifelse(predM > cutoff, 1, 0) result <- cbind(data, cart_result, cart_state) colnames(result)[(ncol_data+1):(ncol_data+3)] <- c("p.m", "p.r", "states") as.data.frame(result) } fitPartialViterbiMR <- function(data, theta, cutoff = 0.5, startpoint, pathlength, integrControl = integr.control()) { if (!is.matrix(data)) data <- as.matrix(data) nrow_data <- nrow(data) if (startpoint < 1 | startpoint > nrow_data) stop("start time point should be within data time interval.") if ((startpoint + pathlength - 1) > nrow_data) stop("end time point should be within data time interval.") dinc <- apply(data, 2, diff) integrControl <- unlist(integrControl) ncol_data <- ncol(data) cart_result <- partial_viterbi_mr(theta, dinc, integrControl, startpoint - 1, pathlength) predM <- predMV(cart_result[, 1], cart_result[, 2]) cart_state <- ifelse(predM > cutoff, 1, 0) result <- cbind(data[startpoint:(startpoint+pathlength-1), ], cart_result, cart_state) colnames(result)[(ncol_data+1):(ncol_data+3)] <- c("p.m", "p.r", "states") as.data.frame(result) }
options(width=87, digits=3, scipen=4) set.seed(61777369) library(broman) library(qtl) data(mapthis) summary(mapthis) par(mar=c(4.1,4.1,0.6,1.1)) plotMissing(mapthis, main="") par(mfrow=c(1,2), las=1, cex=0.8) plot(ntyped(mapthis), ylab="No. typed markers", main="No. genotypes by individual") plot(ntyped(mapthis, "mar"), ylab="No. typed individuals", main="No. genotypes by marker") mapthis <- subset(mapthis, ind=(ntyped(mapthis)>50)) nt.bymar <- ntyped(mapthis, "mar") todrop <- names(nt.bymar[nt.bymar < 200]) mapthis <- drop.markers(mapthis, todrop) cg <- comparegeno(mapthis) par(mar=c(4.1,4.1,0.1,0.6),las=1) hist(cg[lower.tri(cg)], breaks=seq(0, 1, len=101), xlab="No. matching genotypes", main="") rug(cg[lower.tri(cg)]) wh <- which(cg > 0.9, arr=TRUE) wh <- wh[wh[,1] < wh[,2],] wh g <- pull.geno(mapthis) table(g[144,], g[292,]) table(g[214,], g[216,]) table(g[238,], g[288,]) for(i in 1:nrow(wh)) { tozero <- !is.na(g[wh[i,1],]) & !is.na(g[wh[i,2],]) & g[wh[i,1],] != g[wh[i,2],] mapthis$geno[[1]]$data[wh[i,1],tozero] <- NA } mapthis <- subset(mapthis, ind=-wh[,2]) print(dup <- findDupMarkers(mapthis, exact.only=FALSE)) gt <- geno.table(mapthis) gt[gt$P.value < 0.05/totmar(mapthis),] todrop <- rownames(gt[gt$P.value < 1e-10,]) mapthis <- drop.markers(mapthis, todrop) g <- pull.geno(mapthis) gfreq <- apply(g, 1, function(a) table(factor(a, levels=1:3))) gfreq <- t(t(gfreq) / colSums(gfreq)) par(mfrow=c(1,3), las=1) for(i in 1:3) plot(gfreq[i,], ylab="Genotype frequency", main=c("AA", "AB", "BB")[i], ylim=c(0,1)) par(mar=rep(0.1,4), pty="s") triplot(labels=c("AA","AB","BB")) tripoints(gfreq, cex=0.8) tripoints(c(0.25, 0.5, 0.25), col="red", lwd=2, cex=1, pch=4) mapthis <- est.rf(mapthis) checkAlleles(mapthis, threshold=5) rf <- pull.rf(mapthis) lod <- pull.rf(mapthis, what="lod") par(mar=c(4.1,4.1,0.6,0.6), las=1, cex=0.8) plot(as.numeric(rf), as.numeric(lod), xlab="Recombination fraction", ylab="LOD score") lg <- formLinkageGroups(mapthis, max.rf=0.35, min.lod=6) table(lg[,2]) mapthis <- formLinkageGroups(mapthis, max.rf=0.35, min.lod=6, reorgMarkers=TRUE) par(mar=c(4.1,4.1,2.1,2.1), las=1) plotRF(mapthis, main="", alternate.chrid=TRUE) par(mar=c(4.1,4.1,1.1,0.6), las=1) rf <- pull.rf(mapthis) lod <- pull.rf(mapthis, what="lod") mn4 <- markernames(mapthis, chr=4) par(mfrow=c(2,1)) plot(rf, mn4[3], bandcol="gray70", ylim=c(0,1), alternate.chrid=TRUE) abline(h=0.5, lty=2) plot(lod, mn4[3], bandcol="gray70", alternate.chrid=TRUE) geno.crosstab(mapthis, mn4[3], mn4[1]) mn5 <- markernames(mapthis, chr=5) geno.crosstab(mapthis, mn4[3], mn5[1]) toswitch <- markernames(mapthis, chr=c(5, 7:11)) mapthis <- switchAlleles(mapthis, toswitch) mapthis <- est.rf(mapthis) par(mar=c(4.1,4.1,2.1,2.1), las=1) plotRF(mapthis, main="", alternate.chrid=TRUE) rf <- pull.rf(mapthis) lod <- pull.rf(mapthis, what="lod") par(mar=c(4.1,4.1,0.6,0.6), las=1, cex=0.8) plot(as.numeric(rf), as.numeric(lod), xlab="Recombination fraction", ylab="LOD score") lg <- formLinkageGroups(mapthis, max.rf=0.35, min.lod=6) table(lg[,2]) mapthis <- formLinkageGroups(mapthis, max.rf=0.35, min.lod=6, reorgMarkers=TRUE) mapthis <- est.rf(mapthis) par(mar=c(4.1,4.1,1.6,1.6), las=1) plotRF(mapthis, main="") file <- "Rcache/order5.RData" if(file.exists(file)) { load(file) } else { mapthis <- orderMarkers(mapthis, chr=5) save(mapthis, file=file) } pull.map(mapthis, chr=5) file <- "Rcache/rip5.RData" if(file.exists(file)) { load(file) } else { rip5 <- ripple(mapthis, chr=5, window=7) save(rip5, file=file) } summary(rip5) file <- "Rcache/rip5lik.RData" if(file.exists(file)) { load(file) } else { rip5lik <- ripple(mapthis, chr=5, window=4, method="likelihood", error.prob=0.005) save(rip5lik, file=file) } summary(rip5lik) compareorder(mapthis, chr=5, c(1:7,9,8), error.prob=0.01) compareorder(mapthis, chr=5, c(1:7,9,8), error.prob=0.001) compareorder(mapthis, chr=5, c(1:7,9,8), error.prob=0) mapthis <- switch.order(mapthis, chr=5, c(1:7,9,8), error.prob=0.005) pull.map(mapthis, chr=5) file <- "Rcache/order4.RData" if(file.exists(file)) { load(file) } else { mapthis <- orderMarkers(mapthis, chr=4) pull.map(mapthis, chr=4) save(mapthis, file=file) } pull.map(mapthis, chr=4) file <- "Rcache/rip4.RData" if(file.exists(file)) { load(file) } else { rip4 <- ripple(mapthis, chr=4, window=7) save(rip4, file=file) } summary(rip4) file <- "Rcache/rip4lik.RData" if(file.exists(file)) { load(file) } else { rip4lik <- ripple(mapthis, chr=4, window=4, method="likelihood", error.prob=0.005) save(rip4lik, file=file) } summary(rip4lik) mapthis <- switch.order(mapthis, chr=4, c(1:8,10,9), error.prob=0.005) pull.map(mapthis, chr=4) file <- "Rcache/order3.RData" if(file.exists(file)) { load(file) } else { mapthis <- orderMarkers(mapthis, chr=3) pull.map(mapthis, chr=3) save(mapthis, file=file) } pull.map(mapthis, chr=3) file <- "Rcache/rip3.RData" if(file.exists(file)) { load(file) } else { rip3 <- ripple(mapthis, chr=3, window=7) save(rip3, file=file) } summary(rip3) file <- "Rcache/rip3lik.RData" if(file.exists(file)) { load(file) } else { rip3lik <- ripple(mapthis, chr=3, window=4, method="likelihood", error.prob=0.005) save(rip3lik, file=file) } summary(rip3lik) file <- "Rcache/order2.RData" if(file.exists(file)) { load(file) } else { mapthis <- orderMarkers(mapthis, chr=2) pull.map(mapthis, chr=2) save(mapthis, file=file) } pull.map(mapthis, chr=2) file <- "Rcache/rip2.RData" if(file.exists(file)) { load(file) } else { rip2 <- ripple(mapthis, chr=2, window=7) save(rip2, file=file) } summary(rip2) file <- "Rcache/rip2lik.RData" if(file.exists(file)) { load(file) } else { rip2lik <- ripple(mapthis, chr=2, window=4, method="likelihood", error.prob=0.005) save(rip2lik, file=file) } summary(rip2lik) par(las=1, mar=c(4.1,4.1,1.1,0.1), cex=0.8) pat2 <- apply(rip2[,1:24], 1, paste, collapse=":") pat2lik <- apply(rip2lik[,1:24], 1, paste, collapse=":") rip2 <- rip2[match(pat2lik, pat2),] plot(rip2[,"obligXO"], rip2lik[,"LOD"], xlab="obligate crossover count", ylab="LOD score") file <- "Rcache/order1.RData" if(file.exists(file)) { load(file) } else { mapthis <- orderMarkers(mapthis, chr=1) pull.map(mapthis, chr=1) save(mapthis, file=file) } pull.map(mapthis, chr=1) file <- "Rcache/rip1.RData" if(file.exists(file)) { load(file) } else { rip1 <- ripple(mapthis, chr=1, window=7) save(rip1, file=file) } summary(rip1) file <- "Rcache/rip1lik.RData" if(file.exists(file)) { load(file) } else { rip1lik <- ripple(mapthis, chr=1, window=4, method="likelihood", error.prob=0.005) save(rip1lik, file=file) } summary(rip1lik) summaryMap(mapthis) firstsummary <- summaryMap(mapthis) par(las=1, mar=c(4.1,4.1,1.1,0.1), cex=0.8) plotMap(mapthis, main="", show.marker.names=TRUE) par(mar=c(4.1,4.1,1.6,1.6), las=1) plotRF(mapthis, main="") par(mar=c(4.1,4.1,1.6,1.6), las=1, pty="s", cex=0.8) messedup <- switch.order(mapthis, chr=1, c(1:11,23:33,12:22), error.prob=0.005) plotRF(messedup, chr=1, main="") par(las=1, mar=c(4.1,4.1,1.1,0.1), cex=0.8) plotMap(messedup, main="", show.marker.names=TRUE) file <- "Rcache/dropone.RData" if(file.exists(file)) { load(file) } else { dropone <- droponemarker(mapthis, error.prob=0.005) save(dropone, file=file) } par(mar=c(4.1,4.1,1.6,0.1), mfrow=c(2,1), cex=0.8) plot(dropone, lod=1, ylim=c(-100,0)) plot(dropone, lod=2, ylab="Change in chr length (cM)") summary(dropone, lod.column=2) badmar <- rownames(summary(dropone, lod.column=2))[1:3] mapthis <- drop.markers(mapthis, badmar) newmap <- est.map(mapthis, error.prob=0.005) mapthis <- replace.map(mapthis, newmap) summaryMap(mapthis) secondsummary <- summaryMap(mapthis) par(mar=c(4.1,4.1,0.6,0.6), cex=0.8) plot(countXO(mapthis), ylab="Number of crossovers") thecounts <- countXO(mapthis) worst <- rev(sort(thecounts, decreasing=TRUE)[1:2]) mapthis <- subset(mapthis, ind=(countXO(mapthis) < 50)) summary(rip <- ripple(mapthis, chr=5, window=7)) summary(rip <- ripple(mapthis, chr=5, window=2, method="likelihood", error.prob=0.005)) mapthis <- switch.order(mapthis, chr=5, c(1:7,9,8), error.prob=0.005) pull.map(mapthis, chr=5) newmap <- est.map(mapthis, error.prob=0.005) mapthis <- replace.map(mapthis, newmap) summaryMap(mapthis) thirdsummary <- summaryMap(mapthis) file <- "Rcache/errorrate.RData" if(file.exists(file)) { load(file) } else { loglik <- err <- c(0.001, 0.0025, 0.005, 0.0075, 0.01, 0.0125, 0.015, 0.0175, 0.02) for(i in seq(along=err)) { cat(i, "of", length(err), "\n") tempmap <- est.map(mapthis, error.prob=err[i]) loglik[i] <- sum(sapply(tempmap, attr, "loglik")) } lod <- (loglik - max(loglik))/log(10) save(err, lod, file=file) } par(mar=c(4.1,4.1,0.6,0.6), las=1) plot(err, lod, xlab="Genotyping error rate", xlim=c(0,0.02), ylab=expression(paste(log[10], " likelihood"))) file <- "Rcache/errorlod.RData" if(file.exists(file)) { load(file) } else { mapthis <- calc.errorlod(mapthis, error.prob=0.005) save(mapthis, file=file) } print(toperr <- top.errorlod(mapthis, cutoff=6)) par(mar=c(4.1,4.1,0.6,0.6), las=1, cex.axis=0.9) plotGeno(mapthis, chr=1, ind=toperr$id[toperr$chr==1], main="", cex=0.8, include.xo=FALSE, cutoff=6) mapthis.clean <- mapthis for(i in 1:nrow(toperr)) { chr <- toperr$chr[i] id <- toperr$id[i] mar <- toperr$marker[i] mapthis.clean$geno[[chr]]$data[mapthis$pheno$id==id, mar] <- NA } gt <- geno.table(mapthis, scanone.output=TRUE) par(mar=c(4.1,4.1,0.6,0.6), las=1, mfrow=c(2,1), cex=0.8) plot(gt, ylab=expression(paste(-log[10], " P-value"))) plot(gt, lod=3:5, ylab="Genotype frequency") abline(h=c(0.25, 0.5), lty=2, col="gray") par(las=1, mar=c(4.6,4.6,0.6,0.6), cex=0.8) plotMap(mapthis, main="", show.marker.names=TRUE)
NULL offspring = function(x, id, original.id = TRUE) { if (original.id) id = .internalID(x, id) p = x$pedigree offs_rows = p[, 1 + p[id, "SEX"]] == id if (original.id) x$orig.ids[offs_rows] else (1:x$nInd)[offs_rows] } spouses = function(x, id, original.id = TRUE) { internal_id = ifelse(original.id, .internalID(x, id), id) p = x$pedigree offs_rows = p[, 1 + p[internal_id, "SEX"]] == internal_id spou = unique.default(p[offs_rows, 4 - p[internal_id, "SEX"]]) if (original.id) return(x$orig.ids[spou]) else return(spou) } related.pairs = function(x, relation = c("parents", "siblings", "grandparents", "nephews_nieces", "cousins", "spouses", "unrelated"), available = F, interfam = c("none", "founders", "all"), ...) { relation = match.arg(relation) interfam = match.arg(interfam) func = function(...) get(relation)(...) if (is.linkdat.list(x)) { res = do.call(rbind, lapply(x, function(xx) related.pairs(xx, relation, available, ...) )) if (relation == "unrelated" && interfam != "none") { avail = lapply(x, function(xx) { ids = if (available) xx$available else xx$orig.ids if (interfam == "founders") ids = intersect(ids, xx$orig.ids[xx$founders]) if (length(ids) == 0) return(NULL) ids }) avail = avail[!sapply(avail, is.null)] fampairs = data.frame(t(.comb2(length(avail)))) interfam = do.call(rbind, lapply(fampairs, function(p) fast.grid(avail[p]))) res = rbind(res, interfam) } return(res) } res = NULL for (i in 1:x$nInd) { rels = func(x, i, original.id = F, ...) rels = rels[rels != i] res = rbind(res, cbind(rep.int(i, length(rels)), rels, deparse.level = 0)) } res[res[, 1] > res[, 2], ] = res[res[, 1] > res[, 2], 2:1] res = unique(res) if (available) { avail = .internalID(x, x$available) res = res[res[, 1] %in% avail & res[, 2] %in% avail, , drop = F] } res[] = x$orig.ids[res] res } unrelated = function(x, id, original.id = TRUE) { if (!original.id) id = x$orig.ids[id] ancs = c(id, ancestors(x, id)) rel = unique.default(unlist(lapply(ancs, function(a) c(a, descendants(x, a, original.id = TRUE))))) unrel = setdiff(x$orig.ids, rel) if (!original.id) unrel = .internalID(x, unrel) unrel } leaves = function(x) { p = as.matrix(x, FALSE) .mysetdiff(p[, "ID", drop = F], p[, c("FID", "MID")]) } parents = function(x, id, original.id = TRUE) { grandparents(x, id, degree = 1, original.id = original.id) } grandparents = function(x, id, degree = 2, original.id = TRUE) { if (original.id) id = .internalID(x, id) p = x$pedigree gp = id for (i in seq_len(degree)) gp = p[gp, 2:3] if (original.id) x$orig.ids[gp] else (1:x$nInd)[gp] } siblings = function(x, id, half = NA, original.id = TRUE) { if (original.id) id = .internalID(x, id) p = x$pedigree fa = p[id, "FID"] mo = p[id, "MID"] if (fa == 0 && mo == 0) return(numeric()) samefather = p[, "FID"] == fa samemother = p[, "MID"] == mo sib_rows = if (is.na(half)) samefather | samemother else if (half) xor(samefather, samemother) else samefather & samemother sib_rows[id] = FALSE if (original.id) x$orig.ids[sib_rows] else (1:x$nInd)[sib_rows] } cousins = function(x, id, degree = 1, removal = 0, half = NA, original.id = TRUE) { if (original.id) id = .internalID(x, id) gp = grandparents(x, id, degree = degree, original.id = FALSE) uncles = unique.default(unlist(lapply(gp, siblings, x = x, half = half, original.id = FALSE))) cous = uncles for (i in seq_len(degree + removal)) cous = unique.default(unlist(lapply(cous, offspring, x = x, original.id = FALSE))) if (original.id) cous = x$orig.ids[cous] cous } nephews_nieces = function(x, id, removal = 1, half = NA, original.id = TRUE) { cousins(x, id, degree = 0, removal = removal, half = half, original.id = original.id) } ancestors = function(x, id) { if (is.linkdat(x)) { p = x$pedigree orig_ids = x$orig.ids ids_int = .internalID(x, id) } else if (is.matrix(x) && c("ID", "FID", "MID") %in% colnames(x)) { p = x orig_ids = p[, "ID"] ids_int = match(id, orig_ids) } else stop("x must be either a linkdat object or a matrix whose colnames include 'ID', 'FID' and 'MID'") p = relabel(p, 1:nrow(p)) ancest = numeric(0) up1 = as.numeric(p[ids_int, c("FID", "MID")]) up1 = up1[up1 > 0 & up1 <= nrow(p)] up1 = up1[!duplicated.default(up1)] while (length(up1) > 0) { ancest = c(ancest, up1) up1 = .mysetdiff(as.numeric(p[up1, c("FID", "MID")]), ancest) } ancest = sort.int(ancest[(ancest != 0) & !duplicated(ancest)]) return(orig_ids[ancest]) } descendants = function(x, id, original.id = TRUE) { internal_id = ifelse(original.id, .internalID(x, id), id) nextgen <- desc <- offspring(x, internal_id, original.id = FALSE) while (TRUE) { nextgen <- unlist(lapply(nextgen, offspring, x = x, original.id = FALSE)) if (length(nextgen) == 0) break desc <- c(desc, nextgen) } desc = unique.default(sort.default(desc)) if (original.id) return(x$orig.ids[desc]) else return(desc) }
p_z <- function(x, ts = TRUE) { if(ts == TRUE) { return(qnorm(x/2, lower.tail = FALSE)) } else { return(qnorm(x, lower.tail = FALSE)) } }
context("Test ipinfo") test_that("data.frames can be returned from ip-info", { skip_on_cran() result <- ip_info("2607:FB90:426:DC1D:CFC4:4875:8BC2:4D93") expect_that(is.data.frame(result), equals(TRUE)) expect_that(nrow(result), equals(1)) }) test_that("data.frames with false entries can be returned from ip-info", { skip_on_cran() result <- ip_info(c("2607:FB90:426:DC1D:CFC4:4875:8BC2:4D93", "foo")) expect_that(is.data.frame(result), equals(TRUE)) expect_that(nrow(result), equals(2)) expect_true(any(is.na(result))) })
NULL US_countyNameToFIPS <- function( state = NULL, countyName = NULL ) { state <- as.character(state) if ( length(state) == 1 ) state <- rep(state, length.out = length(countyName) ) if ( length(state) != length(countyName) ) stop("Parameter 'state' must have the same length as 'countyName' or be of length 1") if ( state[1] %in% US_stateCodes$stateCode ) { stateFIPS <- US_stateCodeToFIPS(state) } else if ( tolower(state[1]) %in% tolower(US_stateCodes$stateName) ) { stateFIPS <- US_stateNameToFIPS(state) } else if ( state[1] %in% US_stateCodes$stateFIPS ) { stateFIPS <- state } else { stop(sprintf("state = \"%s\" is not recognized.", state)) } state_county_name <- paste0(stateFIPS, "_", countyName) %>% tolower() US_state_county_name <- paste0( MazamaSpatialUtils::US_countyCodes$stateFIPS, "_", MazamaSpatialUtils::US_countyCodes$countyName ) %>% tolower() indices <- match(state_county_name, US_state_county_name) countyFIPS <- MazamaSpatialUtils::US_countyCodes$countyFIPS[indices] return(countyFIPS) } US_countyFIPSToName <- function( state = NULL, countyFIPS = NULL ) { state <- as.character(state) if ( length(state) == 1 ) state <- rep(state, length.out = length(countyFIPS) ) if ( length(state) != length(countyFIPS) ) stop("Parameter 'state' must have the same length as 'countyFIPS' or be of length 1") if ( state[1] %in% US_stateCodes$stateCode ) { stateFIPS <- US_stateCodeToFIPS(state) } else if ( tolower(state[1]) %in% tolower(US_stateCodes$stateName) ) { stateFIPS <- US_stateNameToFIPS(state) } else if ( state[1] %in% US_stateCodes$stateFIPS ) { stateFIPS <- state } else { stop(sprintf("state = \"%s\" is not recognized.", state)) } state_county_FIPS <- paste0(stateFIPS, "_", countyFIPS) %>% tolower() US_state_county_FIPS <- paste0( MazamaSpatialUtils::US_countyCodes$stateFIPS, "_", MazamaSpatialUtils::US_countyCodes$countyFIPS ) %>% tolower() indices <- match(state_county_FIPS, US_state_county_FIPS) countyName <- MazamaSpatialUtils::US_countyCodes$countyName[indices] return(countyName) }
test_path_arguments<- function(root_path, file){ if(!is.null(root_path) & !is.null(file)){ status = 0 message(paste0("\nPlease, do not specify both the 'root_path' and 'file' parameters to the function. You can:\n", "1) Specify neither the 'root_path' nor the 'file' argument, in this case we will assume that data is in your working directory and the files are named exactly as they have been downloaded from the source.\n", "2) Specify only the 'root_path' argument, in this case we will assume that data is in the directory specified and it is exactly as it have been downloaded from the source.\n"), "3) Specify only the 'file' argument, in this case we will assume that data is in a .txt or .csv file stored in the adress specified by the 'file' parameter.") }else{ if(is.null(root_path) & is.null(file)){ status = 1 message(paste0("You haven't specified neither the 'root_path' nor ther 'file' parameters to the function. in this case we will assume that data is in your working directory and the files are named exactly as they have been downloaded from the source.\n")) }else{ if(is.null(file)){ status = 2 message(paste0("You have specified the 'root_path' argument, in this case we will assume that data is in the directory specified and it is exactly as it have been downloaded from the source.\n")) }else{ status = 3 message(paste0("You have specified the 'file' argument, in this case we will assume that data is in a .txt or .csv file stored in the adress specified by the 'file' parameter.\n")) if (!file.exists(file)) { stop("Data not found. Check if you have provided a valid address in the 'file' parameter" ) } } } } return(status) } read_fwf2 <- function(file, dic){ dict = nodic_overlap(dic) read = mapply(aux_read_fwf, file, dict) %>% dplyr::bind_cols() read = read[, dic$var_name] return(read) } nodic_overlap <- function(dic, init_pos = "int_pos", fin_pos = "fin_pos"){ dic = arrange(.data = dic, dic[[init_pos]]) overlap.pos = which(dic[[init_pos]][-1] - dic[[init_pos]][-length(dic[[init_pos]])] < dic[[fin_pos]][-length(dic[[fin_pos]])] - dic[[init_pos]][-length(dic[[init_pos]])] + 1) print(overlap.pos) if(length(overlap.pos) > 0){ dic.pos = dic dic.lis = list() dic.lis[[1]] = dic[-overlap.pos,] for(i in 1:length(overlap.pos)){ dic.lis[[i+1]] = dic[overlap.pos[i],] } } else { dic.lis = list() dic.lis[[1]] = dic } i = 1:length(dic.lis) names(dic.lis) = paste("V", i, sep = "") return(dic.lis) } get_available_datasets <- function(){ datasets_list<- list.files(system.file("extdata", package = "microdadosBrasil"), full.names = TRUE) %>% (function(x) return(grep("metadata_harmonization",x, value = T))) %>% str_split("/") %>% lapply(tail, c(n = 1)) %>% unlist %>% str_replace(pattern = "_.+", replacement = "") return(datasets_list) } get_available_periods <- function(dataset, fwfonly = FALSE){ md = is.data.frame(dataset) if(!md){ dataset = read_metadata(dataset) } if(!"period" %in% names(dataset)){ warning("metadata in wrong format") return(NULL) } if(fwfonly){ dataset = dataset %>% filter(format == "fwf") } periods = dataset$period return(periods) } get_available_filetypes<- function(dataset, period){ md = is.data.frame(dataset) if(!md){ dataset = read_metadata(dataset) } if(all(!grepl(pattern = "^ft_",names(dataset)))){ warning("metadata in wrong format") return(NULL) } filetypes = dataset[ dataset$period == period,] filetypes = subset(filetypes, select = !is.na(filetypes)[1,]) %>% names filetypes = subset(filetypes, grepl(filetypes, pattern = "^ft_")) filetypes = gsub(filetypes, pattern = "^ft_", replacement = "") return(filetypes) } as.object_size <- function(x) structure(x, class = "object_size")
chartsTabUI <- function(id, chart){ ns <- shiny::NS(id) header<-div(class=ns("header"), makeChartSummary(chart)) chartWrap<-chart$functions$ui(ns("chart-wrap")) return(list(header, chartWrap)) } chartsTab <- function(input, output, session, chart, data, mapping){ ns <- session$ns params <- reactive({ makeChartParams( data = data(), mapping = mapping(), chart = chart ) }) if(chart$type=="module"){ callModule(chart$functions$main, "chart-wrap", params) }else{ output[["chart-wrap"]] <- chart$functions$server( do.call( chart$functions$main, params() ) ) } insertUI( paste0(".",ns("header"), " .chart-header"), where="beforeEnd", ui=downloadButton(ns("scriptDL"), "R script", class="pull-right btn-xs dl-btn") ) mapping_list<-reactive({ mapping_list <- generateMappingList(mapping() %>% filter(.data$domain %in% chart$domain)) if(length(mapping_list)==1){ mapping_list <- mapping_list[[1]] } return(mapping_list) }) output$scriptDL <- downloadHandler( filename = paste0("sg-",chart$name,".R"), content = function(file) { writeLines(makeChartExport(chart, mapping_list()), file) } ) if(chart$type !="module"){ insertUI( paste0(".",ns("header"), " .chart-header"), where="beforeEnd", ui=downloadButton(ns("reportDL"), "html report", class="pull-right btn-primary btn-xs") ) output$reportDL <- downloadHandler( filename = paste0("sg-",chart$name,".html"), content = function(file) { templateReport <- system.file("report","safetyGraphicsReport.Rmd", package = "safetyGraphics") tempReport <- file.path(tempdir(), "report.Rmd") file.copy(templateReport, tempReport, overwrite = TRUE) report_params <- list( data = data(), mapping = mapping(), chart = chart ) rmarkdown::render( tempReport, output_file = file, params = report_params, envir = new.env(parent = globalenv()) ) } ) } }
get_probabilities <- function(bpc_object, n = 1000) { if (class(bpc_object) != 'bpc') stop('Error! The object is not of bpc class') model_type <- bpc_object$model_type stanfit <- get_stanfit(bpc_object) out <- NULL s <- get_sample_posterior(bpc_object, n = n) lookup <- bpc_object$lookup_table cluster_lookup <- bpc_object$cluster_lookup_table comb <- gtools::combinations( n = bpc_object$Nplayers, r = 2, v = lookup$Names, repeats.allowed = F ) newdata <- data.frame(comb) col_names <- c(bpc_object$call_arg$player1, bpc_object$call_arg$player0) colnames(newdata) <- col_names newdata <- as.data.frame(newdata) l <- nrow(newdata) predictors <- NULL if (stringr::str_detect(model_type, '-generalized')) { predictors <- bpc_object$predictors_df } if (stringr::str_detect(model_type, '-ordereffect')) { z <- data.frame(rep(0, l)) colnames(z) <- bpc_object$call_arg$z_player1 newdata <- cbind(newdata, z) } if (stringr::str_detect(model_type, '-U')) { cluster_lookup_table <- bpc_object$cluster_lookup_table ncluster <- nrow(cluster_lookup_table) comb_newdata <- NULL for (i in seq(1:ncluster)) { U <- data.frame(rep(cluster_lookup_table$Names[i], l)) colnames(U) <- bpc_object$call_arg$cluster comb_newdata <- rbind(comb_newdata, cbind(newdata, U)) } newdata <- comb_newdata } pred <- predict.bpc( bpc_object, newdata = newdata, n = n, predictors=predictors, return_matrix = T ) t <- NULL y_pred <- pred[, startsWith(colnames(pred), "y_pred")] ties_pred <- pred[, startsWith(colnames(pred), "ties_pred")] mean_ties <- apply(ties_pred, 2, mean) is_not_tie <- ties_pred != 1 mean_y <- c() for (i in 1:ncol(y_pred)) { mean_i <- mean(y_pred[is_not_tie[, i], i]) mean_y <- c(mean_y, mean_i) } mean_y <- apply(y_pred, 2, mean) t <- data.frame( i = newdata[, col_names[1]], j = newdata[, col_names[2]], i_beats_j = mean_y, i_ties_j = mean_ties ) %>% tibble::remove_rownames() if (stringr::str_detect(model_type, '-U')) { newdata_colnames <- colnames(newdata) U_name <- bpc_object$call_arg$cluster t_names <- colnames(t) t <- cbind(t, newdata[,U_name]) colnames(t) <- c(t_names,U_name) t <-t %>% dplyr::relocate(U_name, .after=.data$j) } if (stringr::str_detect(model_type, '-ordereffect')) { newdata_colnames <- colnames(newdata) z_name <- bpc_object$call_arg$z_player1 t_names <- colnames(t) t <- cbind(t, newdata[,z_name]) colnames(t) <- c(t_names,z_name) t <-t %>% dplyr::relocate(z_name, .after=.data$j) } if (startsWith(model_type, 'bt')) { t <- t %>% dplyr::select(-.data$i_ties_j) } out <- list(Table = t, Posterior = t(pred)) return(out) }
pedtodot <- function(pedfile,makeped=FALSE,sink=TRUE,page="B5", url="http://www.mrc-epid.cam.ac.uk",height=0.5,width=0.75,rotate=0,dir="none") { if (makeped) ped <- pedfile[,-c(5,6,7,9)] else ped <- pedfile pedigree <- ped[,1] member <- ped[,2] father <- ped[,3] mother <- ped[,4] sex <- ped[,5] aff <- ped[,6] page.int <- charmatch(page,c("A4","A5","B5","Legal","Letter","Executive")) pagesize <- c("8.2677165,11.692913", "5.83,8.27", "7.17,10.12", "8.5,14", "8.5,11", "7.25,10.5") ashape <- matrix(c( "m","box,regular=1", "1","box,regular=1", "f","circle", "2","circle"),ncol=2,byrow=T) ashade <- matrix(c( "y","style=filled,color=grey", "2","style=filled,color=grey", "n","style=\"setlinewidth(2)\"", "1","style=\"setlinewidth(2)\"", "x","green", "0","green"),ncol=2,byrow=T) ssize <- dim(ped)[1] shape <- shade <- rep('1',ssize) for (s in 1:ssize) { for (t in 1:4) if (sex[s]==ashape[t,1]) shape[s] <- ashape[t,2] for (t in 1:6) if (aff[s]==ashade[t,1]) shade[s] <- ashade[t,2] } uid <- unique(pedigree) for (j in 1:length(uid)) { if(sink) cat(paste("[",uid[j],"]",sep="")) if(sink) sink(paste(uid[j],".dot",sep="")) cat(paste("digraph ped_",uid[j],sep=""),"{\n") if (page!="") { if (is.na(page.int)) cat(paste("page=\"", page, "\"",sep="")," ;\n") else if (page.int>0) cat(paste("page=\"", pagesize[page.int], "\"",sep="")," ;\n") } cat("ratio=\"auto\" ;\n") cat("mincross = 2.0 ;\n") cat("label=\"pedigree",uid[j],"\" ;\n") cat(paste("rotate=",rotate,sep="")," ;\n") if(url!="") cat(paste("URL=\"",url,"\"",sep="")," ;\n") selected <- pedigree==uid[j] id.j <- member[selected] dad.j <- father[selected] mom.j <- mother[selected] sex.j <- sex[selected] aff.j <- aff[selected] shape.j <- shape[selected] shade.j <- shade[selected] n <- length(id.j) for (s in 1:n) cat(paste("\"", id.j[s], "\" [shape=", sep=""), shape.j[s], ",height=", height, ",width=",width, shade.j[s], "] ;\n") fid <- match(dad.j,id.j) mid <- match(mom.j,id.j) fid <- fid[!is.na(fid)] mid <- mid[!is.na(mid)] marriage <- matrix(rep(0,3*n*(n+1)/2),ncol=3) child <- array(rep('0',n*n*(n+1)/2+2),dim=c(n*(n+1)/2,n+2)) k <- 1 for (s in 1:n) { s1 <- fid[k] s2 <- mid[k] l <- min(s1,s2) u <- max(s1,s2) if (dad.j[s]!="x" && dad.j[s]!="0") { loc <- u*(u-1)/2 + l marriage[loc,1] <- s1 marriage[loc,2] <- s2 marriage[loc,3] <- marriage[loc,3] + 1 child[loc,marriage[loc,3]+2] <- id.j[s] k <- k + 1 } } marriage <- as.data.frame(marriage) child <- as.data.frame(child) married <- marriage[marriage[,3]>0,] n <- dim(married)[1] for (m in 1:n) { s1 <- married[m,1] s2 <- married[m,2] l <- min(s1,s2) u <- max(s1,s2) loc <- u*(u-1)/2 + l s1 <- id.j[s1] s2 <- id.j[s2] mating <- paste("\"", s1, "x", s2, "\"",sep="") cat(mating, "[shape=diamond,style=filled,label=\"\",height=.1,width=.1] ;\n") cat(paste("\"", s1, "\"",sep="")," -> ", mating, paste(" [dir=",dir, ",weight=1]",sep="")," ;\n") cat(paste("\"", s2, "\"",sep="")," -> ", mating, paste(" [dir=",dir, ",weight=1]",sep="")," ;\n") for (k in 1:married[m,3]) { cat(mating, " -> ",paste("\"", child[loc,k+2], "\"",sep=""), paste("[dir=",dir, ",weight=2]",sep="")," ;\n") } } cat("}\n") if(sink) sink() } cat("\n") }
rvn_annual_peak_event_error <- function(sim, obs, mm=9, dd=30, add_line = TRUE, add_labels = TRUE) { df.peak.event <- rvn_annual_peak_event(sim, obs, mm=mm, dd=dd)$df_peak_event errs <- (df.peak.event$sim.peak.event - df.peak.event$obs.peak.event)/df.peak.event$obs.peak.event * 100 text.labels <- year(df.peak.event$obs.dates) x.lab <- "Date (Water Year Ending)" y.lab <- "% Error in Event Peaks" title.lab <- "" if (add_line) { limit <- max(max(errs), abs(min(errs))) y.max <- max(0.5, limit) y.min <- min(-0.5, limit *-1) } else { y.max <- limit y.min <- limit*-1 } df.plot <- data.frame(cbind(text.labels,errs)) df.plot$text.labels <- as.factor(df.plot$text.labels) p1 <- ggplot(data=df.plot)+ geom_point(aes(x=text.labels,y=errs))+ scale_y_continuous(limits=c(y.min,y.max),name=y.lab)+ scale_x_discrete(name=x.lab)+ rvn_theme_RavenR() if (add_line) { p1 <- p1+ geom_hline(yintercept=0,linetype=2) } if (add_labels) { p1 <- p1+ geom_text(x= max(as.numeric(df.plot$text.labels)+0.5), y= y.max/2, label= "Overpredict", angle=90, vjust = 0.5, hjust = 0.5) p1 <- p1+ geom_text(x=max(as.numeric(df.plot$text.labels)+0.5), y= y.min/2, label="Underpredict", angle=90, vjust = 0.5, hjust = 0.5) } df <- data.frame(obs.dates = df.peak.event$obs.dates, errors = errs) return(list(df_peak_event_error = df,p1=p1)) }
copyToClipboard <- function(x, ...) { if (!exists("writeClipboard", getNamespace("utils"))) { stop("This function works only on windows systems") } UseMethod("copyToClipboard", x) invisible() } copyToClipboard.antaresDataList <- function(x, what, ...) { if (length(x) == 1) copyToClipboard(x[[1]]) else { if (missing(what)) { cat("Which element do you want to copy to clipboard ?\n") for (i in 1:length(x)) cat(i, ":", names(x)[i], "\n") what <- scan(what = numeric(), n = 1) } copyToClipboard(x[[what]]) } } copyToClipboard.data.frame <- function(x, ...) { if (nrow(x) > 50000) { x <- x[1:50000, ] warning("Table is too large. Only 50000 rows are copied to clipboard") } write.table(x, file = textConnection(".txt", "w", local=TRUE), sep="\t", row.names = FALSE, ...) utils::writeClipboard(.txt) } copyToClipboard.matrix <- function(x, ...) { if (nrow(x) > 50000) { x <- x[1:50000, ] warning("Matrix is too large. Only 50000 rows are copied to clipboard") } write.table(x, file = textConnection(".txt", "w", local=TRUE), sep="\t", row.names = FALSE, col.names = FALSE, ...) utils::writeClipboard(.txt) } copyToClipboard.default <- function(x, ...) { copyToClipboard(as.matrix(x), ...) }
HMM_based_method <- function(x, cut_points, distribution_class, min_m = 2, max_m = 6, n = 100, max_scaled_x = NA, names_activity_ranges = NA, discr_logL = FALSE, discr_logL_eps = 0.5, dynamical_selection = TRUE, training_method = "EM", Mstep_numerical = FALSE, BW_max_iter = 50, BW_limit_accuracy = 0.001, BW_print = TRUE, DNM_max_iter = 50, DNM_limit_accuracy = 0.001, DNM_print = 2, decoding_method = 'global', bout_lengths = NULL, plotting = 0) { if(is.null(bout_lengths)) { stop("Set variable 'bout_lengths' to use this function. See help-manual for further information. For example: bout_lengths=c(1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,12,13,20,21,40,41,60,61,80,81,120,121,240,241,480,481,1440,1,1440)") } scaling_observations <- function(x, max_scaled_x) { scaling_observations_factor <- max_scaled_x / max(x) scaled_x <- scaling_observations_factor * x return(list(original_x = x, scaling_observations_factor = scaling_observations_factor, scaled_x = scaled_x)) } original_x <- x if(!is.na(max_scaled_x)) { x <- scaling_observations(x = x, max_scaled_x = max_scaled_x) data_scale_factor <- x$scaling_observations_factor x <- x$scaled_x } if(distribution_class == "pois" | distribution_class == "genpois" | distribution_class == "bivariate_pois" | distribution_class == "geom") { x <- round(x) } trained_HMM_with_selected_m <- HMM_training(x = x, min_m = min_m, max_m = max_m, distribution_class = distribution_class, discr_logL = discr_logL, discr_logL_eps = discr_logL_eps, training_method = training_method, Mstep_numerical = Mstep_numerical, n = n, dynamical_selection = dynamical_selection, BW_max_iter = BW_max_iter, BW_limit_accuracy = BW_limit_accuracy, BW_print = BW_print, DNM_max_iter = DNM_max_iter, DNM_limit_accuracy = DNM_limit_accuracy, DNM_print = DNM_print)$trained_HMM_with_selected_m decoding <- HMM_decoding(x = x, m = trained_HMM_with_selected_m$m, delta = trained_HMM_with_selected_m$delta, gamma = trained_HMM_with_selected_m$gamma, distribution_class = trained_HMM_with_selected_m$distribution_class, distribution_theta = trained_HMM_with_selected_m$distribution_theta, decoding_method = decoding_method, discr_logL = discr_logL, discr_logL_eps = discr_logL_eps) if(!is.na(max_scaled_x)) { decoding$decoding_distr_means <- (1 / data_scale_factor) * decoding$decoding_distr_means }else{ decoding$decoding_distr_means <- decoding$decoding_distr_means } extendend_cut_off_point_method <- cut_off_point_method(x = original_x, hidden_PA_levels = decoding$decoding_distr_means , cut_points = cut_points, names_activity_ranges = names_activity_ranges, bout_lengths = bout_lengths, plotting = plotting) return(list(trained_HMM_with_selected_m = trained_HMM_with_selected_m, decoding = decoding, extendend_cut_off_point_method = extendend_cut_off_point_method)) }
'dst033'
stgmix <- function(mean, vcv, window, tlim, p0=0, p=NULL, sres=128, tres=sres, int=1) { if(!is.owin(window)) stop("'window' must be of spatstat class 'owin'") w <- window if(!is.matrix(mean)) stop("'mean' must be a matrix") if(nrow(mean)!=3) stop("'mean' is of incorrect dimension") n <- ncol(mean) if(int<=0) stop("'int' must be positive") if(sres<=1||tres<=0) stop("'sres' and 'tres' must be >= 1") if(length(p0)>1) p0 <- p0[1] if(!is.numeric(p0)) stop("'p0' must be numeric") if(p0<0||p0>1) stop("'p0' must be in [0,1]") if(is.null(p)) p <- rep((1-p0)/n,n) if(!is.numeric(p)) stop("'p' must be numeric") if(length(p)!=n) if(any(p<0)||any(p>1)) stop("all elements of 'p' must be in [0,1]") if(sum(c(p,p0))!=1) stop("'p0' and 'p' must sum to 1") if(!is.numeric(vcv)) stop("'vcv' must be numeric") if(is.array(vcv)){ if(!all(dim(vcv)==c(3,3,n))) stop("'vcv' must be an array of 3x3 matrices with layers matching the number of components") for(i in 1:n){ if((!isSymmetric(vcv[,,i]))||(det(vcv[,,i])<=0)) stop(paste("matrix",i,"in 'vcv' is invalid -- each must be symmetric and positive-definite")) } } else stop("'vcv' must be an array") if(!is.vector(tlim)) stop("'tlim' must be a vector") if(length(tlim)!=2) stop("'tlim' must be a vector of length 2") if(!is.numeric(tlim)) stop("'tlim' must be numeric") if(tlim[2]<=tlim[1]) stop("'tlim[2]' must be greater than 'tlim[1]'") w <- as.mask(window,dimyx=sres) x <- w$xcol y <- w$yrow xy <- expand.grid(x,y) xyinside <- inside.owin(x=xy[,1],y=xy[,2],w=w) xyin <- xy[xyinside,] tseq <- seq(tlim[1], tlim[2], length=tres+1) tstep <- (tlim[2] - tlim[1])/tres tt <- tseq[-(tres+1)] + 0.5*tstep varea <- w$xstep*w$ystep*tstep xyt <- expand.grid(x,y,tt) f <- dmvnorm(xyt,mean=mean[,1],sigma=vcv[,,1]) scale1 <- sum(f*xyinside*varea) if(scale1<0.01 && !inside.owin(mean[1,1],mean[2,1],w) && (mean[3,1]<tlim[1]||mean[3,1]>tlim[2])) warning("Component 1 may be out of range") f <- p[1] * f / scale1 if(n>1){ for(i in 2:n){ fAdd <- dmvnorm(xyt,mean=mean[,i],sigma=vcv[,,i]) scale <- sum(fAdd*xyinside*varea) if (scale<0.01 && !inside.owin(mean[1,i],mean[2,i],w) && (mean[3,i]<tlim[1]||mean[3,i]>tlim[2])) warning(paste("Component",i,"may be out of range")) fAdd <- p[i] * fAdd / scale f <- f + fAdd } } volume <- sum(varea*sum(xyinside)*tres) f <- (f+p0/volume)*int narep <- rep(1,length(xyinside)) narep[!xyinside] <- NA f.arr <- array(f*narep,dim=c(sres,sres,tres)) f.list <- solist() for(i in 1:tres){ f.list[[i]] <- im(t(f.arr[,,i]),xcol=x,yrow=y) f.list[[i]] <- f.list[[i]][w,drop=FALSE] } result <- list(a=f.arr,v=f.list,xcol=x,yrow=y,tlay=tt,W=window) class(result) <- "stim" return(result) }
anthro_zscore_subscapular_skinfold_for_age <- function(subskin, age_in_days, age_in_months, sex, flag_threshold = 5, growthstandards = growthstandards_ssanthro) { anthro_zscore_adjusted( name = "ss", measure = subskin, age_in_days = age_in_days, age_in_months = age_in_months, sex = sex, growthstandards = growthstandards, flag_threshold = flag_threshold, allowed_age_range = c(91, 1856) ) }
p2p_arrows<-function(x1,y1,x2,y2,space=0.05,col=par("fg"),...) { xspace<-(x2-x1)*space yspace<-(y2-y1)*space arrows(x1+xspace,y1+yspace,x2-xspace,y2-yspace,...) }
resetDummyProvider() cluster <- NULL serverData <- NULL verbose <- 0 test_that("DockerCluster constructor", { expect_error( provider <- DummyProvider() ,NA) expect_error( container <- DummyWorkerContainer() ,NA) expect_error( serverData <<- CloudPrivateServer( publicIp = "192.168.1.1", publicPort = 123, privateIp = "127.0.0.1", privatePort = 456, serverClientSameLAN = TRUE) ,NA) expect_error( cluster <<- makeDockerCluster( cloudProvider = provider, workerContainer = container, privateServerData = serverData, verbose = verbose) ,NA) }) test_that("DockerCluster server status", { expect_true(cluster$isServerRunning()) expect_true(cluster$clusterExists()) }) test_that("DockerCluster set worker number", { expect_error( cluster$setWorkerNumber(10), NA ) expect_identical(cluster$getWorkerNumbers(), list(initializing = 0L, running = 10L, expected = 10L)) }) test_that("DockerCluster stop server", { expect_error( cluster$stopServer(), NA ) expect_true(cluster$isServerRunning()) expect_true(cluster$clusterExists()) }) test_that("DockerCluster worker container", { container <- cluster@cloudProvider$workerContainer expect_equal(container$environment$serverIp, serverData$publicIp) expect_equal(container$environment$serverPort, serverData$publicPort) }) test_that("DockerCluster server container", { container <- cluster@cloudProvider$serverContainer expect_true(length(container$environment) == 0) }) test_that("DockerCluster register backend", { expect_error( cluster$registerBackend(), NA ) expect_error( cluster$deregisterBackend(), NA ) }) test_that("DockerCluster stop cluster", { expect_error( cluster$stopCluster(), NA ) expect_identical(cluster$getWorkerNumbers(), list(initializing = 0L, running = 0L, expected = 10L)) expect_true(cluster$isServerRunning()) expect_error( cluster$update(), NA ) }) test_that("DockerCluster cleanup", { cluster <<- NULL expect_error( gc(), NA ) })
acontext("variable value") test_that("selector.aes errors when no matching variable for value", { a.list <- list(c("clickSelects.variable", "clickSelects2.variable", "clickSelects2.value"), c("clickSelects.variable", "clickSelects2.variable", "clickSelects.value"), c("showSelected.variable", "showSelected2.variable", "showSelected2.value"), c("showSelected.variable", "showSelected2.variable", "showSelected.value"), c("clickSelects.variable", "showSelected2.variable", "clickSelects.value"), "showSelected.variable", "showSelected2.variable", "clickSelects.variable", "clickSelects2.variable", "showSelected.value", "showSelected2.value", "clickSelects.value", "clickSelects2.value") for(a.vec in a.list){ arg.list <- as.list(paste0("var", seq_along(a.vec))) names(arg.list) <- a.vec a <- do.call(aes_string, arg.list) expect_error({ selector.aes(a) }, ".variable or .value aes not found") } }) problems <- data.frame(problemStart=c(100, 200, 100, 150, 200, 250), problemEnd=c(200, 300, 150, 200, 250, 300), problem.i=c(1, 2, 1, 2, 3, 4), bases.per.problem=c(100, 100, 50, 50, 50, 50)) problems$problem.name <- with(problems, { sprintf("size.%d.problem.%d", bases.per.problem, problem.i) }) sizes <- data.frame(bases.per.problem=c(50, 100), problems=c(2, 4)) problems$peakStart <- problems$problemStart + 10 problems$peakEnd <- problems$problemEnd - 10 samples <- rbind(data.frame(problems, sample.id="sample1", peaks=1), data.frame(problems, sample.id="sample1", peaks=2), data.frame(problems, sample.id="sample2", peaks=2)) peaks <- expand.grid(peaks=0:2, problem.name=problems$problem.name) peaks$error.type <- c("false positive", "false negative", "correct") rownames(problems) <- problems$problem.name peaks$bases.per.problem <- problems[paste(peaks$problem.name), "bases.per.problem"] peak.problems <- rbind(data.frame(problems, peaks=1), data.frame(problems, peaks=2)) one.error <- data.frame(bases.per.problem=1:10, errors=rnorm(10), chunks="one") two.error <- data.frame(bases.per.problem=1:10, errors=rnorm(10), chunks="two") viz <- list(errorLines=ggplot()+ scale_color_manual(values=c(one="red", two="black"))+ scale_size_manual(values=c(one=1, two=2))+ geom_line(aes(bases.per.problem, errors, color=chunks, size=chunks), data=one.error)+ geom_line(aes(bases.per.problem, errors, color=chunks, size=chunks), data=two.error), problems=ggplot()+ ggtitle("select problem")+ geom_segment(aes(problemStart, problem.i, clickSelects=problem.name, showSelected=bases.per.problem, xend=problemEnd, yend=problem.i), size=5, data=data.frame(problems, sample.id="problems"))+ geom_text(aes(200, 5, label=paste("problem size", bases.per.problem), showSelected=bases.per.problem), data=data.frame(sizes, sample.id="problems"))+ geom_segment(aes(peakStart, problem.i, showSelected.variable=paste0(problem.name, "peaks"), showSelected.value=peaks, clickSelects=problem.name, showSelected2=bases.per.problem, xend=peakEnd, yend=problem.i), data=data.frame(peak.problems, sample.id="problems"), size=10, color="deepskyblue")+ geom_segment(aes(peakStart, 0, showSelected.variable=paste0(problem.name, "peaks"), showSelected.value=peaks, clickSelects=problem.name, showSelected2=bases.per.problem, xend=peakEnd, yend=0), data=samples, size=10, color="deepskyblue")+ theme_bw()+ theme(panel.margin=grid::unit(0, "cm"))+ facet_grid(sample.id ~ .), title="viz with .variable .value", sizes=ggplot()+ ggtitle("select problem size")+ geom_point(aes(bases.per.problem, problems, clickSelects=bases.per.problem), size=10, data=sizes), peaks=ggplot()+ ggtitle("select number of peaks")+ geom_point(aes(peaks, peaks, color=error.type, id=peaks, showSelected=problem.name, showSelected2=bases.per.problem, clickSelects.variable=paste0(problem.name, "peaks"), clickSelects.value=peaks), size=10, data=peaks)+ geom_text(aes(1, 3, label=problem.name, showSelected2=bases.per.problem, showSelected=problem.name), data=problems)) info <- animint2HTML(viz) test_that("No widgets for .variable .value selectors", { computed.vec <- getSelectorWidgets(info$html) expected.vec <- c( "chunks", "problem.name", "bases.per.problem", "error.type") expect_identical(sort(computed.vec), sort(expected.vec)) }) circle.xpath <- '//svg[@id="plot_peaks"]//circle' title.xpath <- paste0(circle.xpath, '//title') test_that("clickSelects.variable tooltip/title", { circle.list <- getNodeSet(info$html, circle.xpath) expect_equal(length(circle.list), 3) title.list <- getNodeSet(info$html, title.xpath) title.vec <- sapply(title.list, xmlValue) expect_identical(title.vec, paste("size.100.problem.1peaks", 0:2)) }) test_that("two lines rendered in first plot", { path.list <- getNodeSet( info$html, '//svg[@id="plot_errorLines"]//g[@class="PANEL1"]//path') style.strs <- sapply(path.list, function(x) xmlAttrs(x)["style"]) pattern <- paste0("(?<name>\\S+?)", ": *", "(?<value>.+?)", ";") style.matrices <- str_match_all_perl(style.strs, pattern) size.vec <- sapply(style.matrices, function(m)m["stroke-width", "value"]) size.num <- as.numeric(sub("px", "", size.vec)) expect_equal(size.num, c(1, 2)) color.vec <- sapply(style.matrices, function(m)m["stroke", "value"]) expect_color(color.vec, c("red", "black")) }) test_that(".variable and .value makes compiler create selectors", { selector.names <- sort(names(info$selectors)) problem.selectors <- paste0(problems$problem.name, "peaks") expected.names <- sort(c("problem.name", "error.type", "chunks", problem.selectors, "bases.per.problem")) expect_identical(selector.names, expected.names) selected <- sapply(info$selectors[problem.selectors], "[[", "selected") expect_true(all(selected == "1")) }) test_that(".variable and .value renders correctly at first", { node.list <- getNodeSet(info$html, '//g[@class="geom6_segment_problems"]//line') expect_equal(length(node.list), 2) }) test_that("clicking reduces the number of peaks", { no.peaks.html <- clickHTML(id=0) node.list <- getNodeSet(no.peaks.html, '//g[@class="geom6_segment_problems"]//line') expect_equal(length(node.list), 1) }) test_that("clicking increases the number of peaks", { more.peaks.html <- clickHTML(id=2) node.list <- getNodeSet(more.peaks.html, '//g[@class="geom6_segment_problems"]//line') expect_equal(length(node.list), 3) }) viz.for <- list(problems=ggplot()+ ggtitle("select problem")+ geom_segment(aes(problemStart, problem.i, clickSelects=problem.name, showSelected=bases.per.problem, xend=problemEnd, yend=problem.i), size=5, data=data.frame(problems, sample.id="problems"))+ geom_text(aes(200, 5, label=paste("problem size", bases.per.problem), showSelected=bases.per.problem), data=data.frame(sizes, sample.id="problems"))+ theme_bw()+ theme(panel.margin=grid::unit(0, "cm"))+ facet_grid(sample.id ~ .), title="viz with for loop", sizes=ggplot()+ ggtitle("select problem size")+ geom_point(aes(bases.per.problem, problems, clickSelects=bases.per.problem), size=10, data=sizes), peaks=ggplot()+ ggtitle("select number of peaks")+ geom_text(aes(1, 3, label=problem.name, showSelected=problem.name), data=problems)) pp.list <- split(peak.problems, peak.problems$problem.name) s.list <- split(samples, samples$problem.name) p.list <- split(peaks, peaks$problem.name) for(problem.name in names(p.list)){ s.name <- paste0(problem.name, "peaks") p <- p.list[[problem.name]] p[[s.name]] <- p$peaks pp <- pp.list[[problem.name]] pp[[s.name]] <- pp$peaks pp$problem.nodots <- gsub("[.]", "", pp$problem.name) s <- s.list[[problem.name]] s[[s.name]] <- s$peaks p$bases.per.problem <- pp$bases.per.problem[1] viz.for$problems <- viz.for$problems+ geom_segment(aes_string("peakStart", "problem.i", id="problem.nodots", showSelected=s.name, clickSelects="problem.name", showSelected2="bases.per.problem", xend="peakEnd", yend="problem.i"), data=data.frame(pp, sample.id="problems"), size=10, color="deepskyblue")+ geom_segment(aes_string("peakStart", "0", showSelected=s.name, clickSelects="problem.name", showSelected2="bases.per.problem", xend="peakEnd", yend="0"), data=s, size=10, color="deepskyblue") viz.for$peaks <- viz.for$peaks+ geom_point(aes_string("peaks", "peaks", showSelected="problem.name", showSelected2="bases.per.problem", clickSelects=s.name), size=10, data=p) } info <- animint2HTML(viz.for) test_that("Widgets for regular selectors", { computed.vec <- getSelectorWidgets(info$html) expected.vec <- c( "problem.name", "bases.per.problem", "size.100.problem.1peaks", "size.100.problem.2peaks", "size.50.problem.1peaks", "size.50.problem.2peaks", "size.50.problem.3peaks", "size.50.problem.4peaks") expect_identical(sort(computed.vec), sort(expected.vec)) }) chunk.counts <- function(html=getHTML()){ node.set <- getNodeSet(html, '//td[@class="downloaded"]') as.integer(sapply(node.set, xmlValue)) } test_that("counts of chunks downloaded or not at first", { value.vec <- chunk.counts() expect_equal(value.vec, c(1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0)) }) test_that("changing problem downloads one chunk", { clickID('size100problem2') Sys.sleep(1) value.vec <- chunk.counts() expect_equal(value.vec, c(1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0)) }) test_that("clickSelects tooltip/title", { circle.list <- getNodeSet(info$html, circle.xpath) expect_equal(length(circle.list), 3) title.list <- getNodeSet(info$html, title.xpath) title.vec <- sapply(title.list, xmlValue) expect_identical(title.vec, paste("size.100.problem.1peaks", 0:2)) })
DataSummaryGUI <- function(base.txt) { submit <- function() { if( !is.nothing) { data.select <- as.numeric( tkcurselection( data.listbox))+1 dd.cmd <- paste( "dd <- get( \"", full.list[ data.select], "\")", sep="") } else dd.cmd <- "dd <- in2extRemesData" eval( parse( text=dd.cmd)) write( dd.cmd, file="in2extRemes.log", append=TRUE) summaryCMD <- "print( summary( dd[[\"data\"]]))" eval( parse( text=summaryCMD)) write( summaryCMD, file="in2extRemes.log", append=TRUE) tkdestroy( base) invisible() } DataSummaryHelp <- function() { help.msg1 <- paste( " ", "This is a simple function that summarizes the entire selected data set and prints the summary to the console", " ", sep="\n") cat( help.msg1) invisible() } endprog <- function() { tkdestroy( base) } base <- tktoplevel() tkwm.title( base, "Data Summary") top.frm <- tkframe( base, borderwidth=2, relief="groove") bot.frm <- tkframe( base, borderwidth=2, relief="groove") data.listbox <- tklistbox( top.frm, yscrollcommand=function(...) tkset(data.scroll, ...), selectmode="single", width=20, height=5, exportselection=0) data.scroll <- tkscrollbar( top.frm, orient="vert", command=function(...) tkyview( data.listbox, ...)) temp <- ls(all.names=TRUE, name=".GlobalEnv") full.list <- character(0) is.nothing <- TRUE for( i in 1:length( temp)) { if( is.null( class( get( temp[i])))) next if( (class(get( temp[i]))[1] == "in2extRemesDataObject")) { tkinsert( data.listbox, "end", paste( temp[i])) full.list <- c( full.list, temp[i]) is.nothing <- FALSE } } tkpack( tklabel( top.frm, text="Data Object", padx=4), side="top") tkpack( data.listbox, data.scroll, side="left", fill="y") tkpack( top.frm) ok.but <- tkbutton( bot.frm, text="OK", command=submit) cancel.but <- tkbutton( bot.frm, text="Cancel", command=endprog) help.but <- tkbutton( bot.frm, text="Help", command=DataSummaryHelp) tkpack( ok.but, cancel.but, side="left") tkpack( help.but, side="right") tkbind( ok.but, "<Return>", submit) tkbind( cancel.but, "<Return>", endprog) tkbind( help.but, "<Return>", DataSummaryHelp) tkpack( top.frm, fill="x") tkpack( bot.frm, side="bottom") }
Sliding.Window <- function(VLF, seqlength, n = 30){ samples <- nrow(VLF) window <- matrix(0, nrow = samples, ncol = seqlength-n) colors <- c("blue", "red", "green", "purple") for(r in 1:samples){ for(i in 1:(seqlength-n)){ for(z in 0:(n-1)){ window[r,i] <- window[r,i] + VLF[r,i+z] } window[r,i] = window[r,i]/n } } theAxis = (c(1:(seqlength-n))/(seqlength-n))*100 plot(x = theAxis, window[1,], type = "l", ylab = "VLFs/Position", xlab = "Percentile Barcode Segment", main = bquote("Sliding Window Analysis of ntVLFs (Window, N =" ~ .(n)~")"), col = colors[1]) t = 2 while(t <= samples){ lines(x = theAxis, window[t,], type = "l", col = colors[t]) t <- t + 1 } if(samples > 1){ legend("topright", legend = rownames(VLF), col = colors[1:samples], lty = 1) } }
"pdfpe3" <- function(x,para) { if(! are.parpe3.valid(para)) return() names(para$para) <- NULL MU <- para$para[1] SIGMA <- para$para[2] GAMMA <- para$para[3] SMALL <- sqrt(.Machine$double.eps) if(abs(GAMMA) <= SMALL) return(dnorm(x, mean=MU, sd=SIGMA)) ALPHA <- 4/GAMMA^2 BETA <- (1/2) * SIGMA * abs(GAMMA) XI <- MU - 2 * SIGMA/GAMMA Y <- sign(GAMMA) * (x - XI) f <- dgamma(Y/BETA, ALPHA)/BETA names(f) <- NULL f[! is.finite(f)] <- NA f[is.na(f)] <- 0 return(f) }
source <- function(file, local = FALSE, echo = verbose, print.eval = echo, exprs, spaced = use_file, verbose = getOption("verbose"), prompt.echo = getOption("prompt"), max.deparse.length = 150, width.cutoff = 60L, deparseCtrl = "showAttributes", chdir = FALSE, encoding = getOption("encoding"), continue.echo = getOption("continue"), skip.echo = 0, keep.source = getOption("keep.source")) { envir <- if (isTRUE(local)) parent.frame() else if(identical(local, FALSE)) .GlobalEnv else if (is.environment(local)) local else stop("'local' must be TRUE, FALSE or an environment") if (!missing(echo)) { if (!is.logical(echo)) stop("'echo' must be logical") if (!echo && verbose) { warning("'verbose' is TRUE, 'echo' not; ... coercing 'echo <- TRUE'") echo <- TRUE } } if (verbose) { cat("'envir' chosen:") print(envir) } if(use_file <- missing(exprs)) { ofile <- file from_file <- FALSE srcfile <- NULL if(is.character(file)) { have_encoding <- !missing(encoding) && encoding != "unknown" if(identical(encoding, "unknown")) { enc <- utils::localeToCharset() encoding <- enc[length(enc)] } else enc <- encoding if(length(enc) > 1L) { encoding <- NA owarn <- options(warn = 2) for(e in enc) { if(is.na(e)) next zz <- file(file, encoding = e) res <- tryCatch(readLines(zz, warn = FALSE), error = identity) close(zz) if(!inherits(res, "error")) { encoding <- e; break } } options(owarn) } if(is.na(encoding)) stop("unable to find a plausible encoding") if(verbose) cat(gettextf('encoding = "%s" chosen', encoding), "\n", sep = "") if(file == "") { file <- stdin() srcfile <- "<stdin>" } else { filename <- file file <- file(filename, "r", encoding = encoding) on.exit(close(file)) if (isTRUE(keep.source)) { lines <- readLines(file, warn = FALSE) on.exit() close(file) srcfile <- srcfilecopy(filename, lines, file.mtime(filename)[1], isFile = TRUE) } else { from_file <- TRUE srcfile <- filename } loc <- utils::localeToCharset()[1L] encoding <- if(have_encoding) switch(loc, "UTF-8" = "UTF-8", "ISO8859-1" = "latin1", "unknown") else "unknown" } } else { lines <- readLines(file, warn = FALSE) srcfile <- if (isTRUE(keep.source)) srcfilecopy(deparse(substitute(file)), lines) else deparse(substitute(file)) } exprs <- if (!from_file) { if (length(lines)) .Internal(parse(stdin(), n = -1, lines, "?", srcfile, encoding)) else expression() } else .Internal(parse(file, n = -1, NULL, "?", srcfile, encoding)) on.exit() if (from_file) close(file) if (verbose) cat("--> parsed", length(exprs), "expressions; now eval(.)ing them:\n") if (chdir){ if(is.character(ofile)) { if(grepl("^(ftp|http|file)://", ofile)) warning("'chdir = TRUE' makes no sense for a URL") else if((path <- dirname(ofile)) != ".") { owd <- getwd() if(is.null(owd)) stop("cannot 'chdir' as current directory is unknown") on.exit(setwd(owd), add=TRUE) setwd(path) } } else { warning("'chdir = TRUE' makes no sense for a connection") } } } else { if(!missing(file)) stop("specify either 'file' or 'exprs' but not both") if(!is.expression(exprs)) exprs <- as.expression(exprs) } Ne <- length(exprs) if (echo) { sd <- "\"" nos <- "[^\"]*" oddsd <- paste0("^", nos, sd, "(", nos, sd, nos, sd, ")*", nos, "$") trySrcLines <- function(srcfile, showfrom, showto) { tryCatch(suppressWarnings(getSrcLines(srcfile, showfrom, showto)), error = function(e) character()) } } yy <- NULL lastshown <- 0 srcrefs <- attr(exprs, "srcref") if(verbose && !is.null(srcrefs)) { cat("has srcrefs:\n"); utils::str(srcrefs) } for (i in seq_len(Ne+echo)) { tail <- i > Ne if (!tail) { if (verbose) cat("\n>>>> eval(expression_nr.", i, ")\n\t =================\n") ei <- exprs[i] } if (echo) { nd <- 0 srcref <- if(tail) attr(exprs, "wholeSrcref") else if(i <= length(srcrefs)) srcrefs[[i]] if (!is.null(srcref)) { if (i == 1) lastshown <- min(skip.echo, srcref[3L]-1) if (lastshown < srcref[3L]) { srcfile <- attr(srcref, "srcfile") dep <- trySrcLines(srcfile, lastshown+1, srcref[3L]) if (length(dep)) { leading <- if(tail) length(dep) else srcref[1L]-lastshown lastshown <- srcref[3L] while (length(dep) && grepl("^[[:blank:]]*$", dep[1L])) { dep <- dep[-1L] leading <- leading - 1L } dep <- paste0(rep.int(c(prompt.echo, continue.echo), c(leading, length(dep)-leading)), dep, collapse="\n") nd <- nchar(dep, "c") } else srcref <- NULL } } if (is.null(srcref)) { if (!tail) { dep <- substr(paste(deparse(ei, width.cutoff = width.cutoff, control = deparseCtrl), collapse = "\n"), 12L, 1e+06L) dep <- paste0(prompt.echo, gsub("\n", paste0("\n", continue.echo), dep)) nd <- nchar(dep, "c") - 1L } } if (nd) { do.trunc <- nd > max.deparse.length dep <- substr(dep, 1L, if (do.trunc) max.deparse.length else nd) cat(if (spaced) "\n", dep, if (do.trunc) paste(if (grepl(sd, dep) && grepl(oddsd, dep)) " ...\" ..." else " ....", "[TRUNCATED] "), "\n", sep = "") } } if (!tail) { yy <- withVisible(eval(ei, envir)) i.symbol <- mode(ei[[1L]]) == "name" if (!i.symbol) { curr.fun <- ei[[1L]][[1L]] if (verbose) { cat("curr.fun:") utils::str(curr.fun) } } if (verbose >= 2) { cat(".... mode(ei[[1L]])=", mode(ei[[1L]]), "; paste(curr.fun)=") utils::str(paste(curr.fun)) } if (print.eval && yy$visible) { if(isS4(yy$value)) methods::show(yy$value) else print(yy$value) } if (verbose) cat(" .. after ", sQuote(deparse(ei, control = unique(c(deparseCtrl, "useSource")))), "\n", sep = "") } } invisible(yy) } withAutoprint <- function(exprs, evaluated = FALSE, local = parent.frame(), print. = TRUE, echo = TRUE, max.deparse.length = Inf, width.cutoff = max(20, getOption("width")), deparseCtrl = c("keepInteger", "showAttributes", "keepNA"), ...) { if(!evaluated) { exprs <- substitute(exprs) if(is.call(exprs)) { if(exprs[[1]] == quote(`{`)) exprs <- as.list(exprs[-1]) } } source(exprs = exprs, local = local, print.eval = print., echo = echo, max.deparse.length = max.deparse.length, width.cutoff = width.cutoff, deparseCtrl = deparseCtrl, ...) }
plot.msden <- function(x, what = c("z", "edge", "bw"), sleep = 0.2, override.par = TRUE, ...){ wha <- what[1] ellip <- list(...) if(is.null(ellip)) ellip <- list() if(is.null(ellip$box)) ellip$box <- FALSE if(is.null(ellip$ribargs)) ellip$ribargs <- list(box=TRUE) if(wha=="z"){ lst <- x$z } else if(wha=="edge"){ lst <- x$q if(is.null(lst)) stop("no edge correction present in multi-scale density object") } else if(wha=="bw"){ lst <- x$him if(is.null(ellip$zlim)) ellip$zlim <- range(lapply(lst,range)) } else { stop("invalid 'what'") } if(override.par) par(mfrow=c(1,1),mar=rep(2,4)) hv <- as.numeric(names(lst)) for(i in 1:length(lst)){ dev.hold() ellip$x <- lst[[i]] ellip$main <- paste("h0 =",round(hv[i],5)) do.call("plot.im",ellip) plot(as.polygonal(Window(x$pp)),add=TRUE) axis(1) axis(2) box(bty="l") dev.flush() Sys.sleep(sleep) } invisible(NULL) }
plot_qdis.lmvar <- function( object_1, object_2 = NULL, ...){ name_1 = deparse(substitute(object_1)) name_2 = deparse(substitute(object_2)) plot_qdis_lmlike( object_1, object_2, name_1, name_2) }
expected <- eval(parse(text="NULL")); test(id=0, code={ argv <- eval(parse(text="list(-1L, FALSE, FALSE, FALSE)")); .Internal(`sink`(argv[[1]], argv[[2]], argv[[3]], argv[[4]])); }, o=expected);
library(dplyr) data(mpg, package = "ggplot2") mpgman2 <- mpg %>% group_by(manufacturer, year) %>% dplyr::summarise( n = dplyr::n(), displ = mean(displ) ) mpgman2 hchart( mpgman2, "column", hcaes(x = manufacturer, y = n, group = year), colorKey = "displ", name = c("Year 1999", "Year 2008") ) %>% hc_colorAxis(min = 0, max = 5) hchart(iris, "point", hcaes(Sepal.Length, Sepal.Width)) %>% hc_colorAxis( minColor = "red", maxColor = "blue" ) n <- 5 stops <- data.frame( q = 0:n/n, c = c(" stringsAsFactors = FALSE ) stops <- list_parse2(stops) M <- round(matrix(rnorm(50*50), ncol = 50), 2) hchart(M) %>% hc_colorAxis(stops = stops)
insertMatBtoA <- function(A, B) { namesA <- rownames(A) namesB <- rownames(B) namesAinB <- namesA[namesA %in% namesB] namesA2 <- colnames(A) namesB2 <- colnames(B) namesAinB2 <- namesA2[namesA2 %in% namesB2] A[namesA %in% namesB, namesA2 %in% namesB2] <- B[match(namesAinB, namesB), match(namesAinB2, namesB2)] return(A) }
context("correlations output") x <- cat(" Correlations \n-------------------------------------------\nVariable Zero Order Partial Part \n-------------------------------------------\ndisp -0.848 -0.048 -0.019 \nhp -0.776 -0.224 -0.093 \nwt -0.868 -0.574 -0.285 \nqsec 0.419 0.219 0.091 \n-------------------------------------------") model <- lm(mpg ~ disp + hp + wt + qsec, data = mtcars) expect_output(print(olsrr::ols_correlations(model)), x)
options(digits=3) dataDir <- system.file("extdata", package = "qMRI") t1Names <- paste0("t1w_", 1:8, ".nii.gz") mtNames <- paste0("mtw_", 1:6, ".nii.gz") pdNames <- paste0("pdw_", 1:8, ".nii.gz") t1Files <- file.path(dataDir, t1Names) mtFiles <- file.path(dataDir, mtNames) pdFiles <- file.path(dataDir, pdNames) B1File <- file.path(dataDir, "B1map.nii.gz") maskFile <- file.path(dataDir, "mask.nii.gz") TE <- c(2.3, 4.6, 6.9, 9.2, 11.5, 13.8, 16.1, 18.4, 2.3, 4.6, 6.9, 9.2, 11.5, 13.8, 2.3, 4.6, 6.9, 9.2, 11.5, 13.8, 16.1, 18.4) TR <- rep(25, 22) FA <- c(rep(21, 8), rep(6, 6), rep(6, 8)) library(qMRI) mpm <- readMPMData(t1Files, pdFiles, mtFiles, maskFile, TR = TR, TE = TE, FA = FA, verbose = FALSE) modelMPM <- estimateESTATICS(mpm, method = "NLR", verbose = FALSE) setCores(2, reprt=FALSE) modelMPMQLsp1 <- smoothESTATICS(modelMPM, mpmData = extract(mpm, "ddata"), kstar = 16, alpha = 0.004, patchsize = 1, verbose = FALSE) mask <- extract(mpm,"mask") mask[,c(1:10,12:21),] <- FALSE mpm <- qMRI:::setMPMmask(mpm, mask) sigma <- array(50, mpm$sdim) modelMPMQL <- estimateESTATICS(mpm, method = "QL", sigma = sigma, L = 1, verbose = FALSE) library(adimpro) rimage.options(zquantiles = c(.01, .99), ylab = "z") par(mfrow = c(2, 4), mar = c(3, 3, 3, 1), mgp = c(2, 1, 0)) pnames <- c("T1", "MT", "PD", "R2star") for (i in 1:4) { modelCoeff <- extract(modelMPMQL,"modelCoeff") rimage(modelCoeff[i, , 11, ]) title(pnames[i]) } for (i in 1:4) { modelCoeff <- extract(modelMPMQLsp1,"modelCoeff") rimage(modelCoeff[i, , 11, ]) title(paste("smoothed", pnames[i])) } mpmsp1 <- mpm ddata <- extract(modelMPMQLsp1,"smoothedData") dim(ddata) <- c(dim(ddata)[1],prod(dim(ddata)[-1])) mpmsp1$ddata <- ddata[,mpm$mask] modelMPM2 <- estimateESTATICS(mpmsp1, method = "NLR", L = 1, verbose = FALSE) qMRIMaps <- calculateQI(modelMPM, b1File = B1File, TR2 = 3.4) qMRIQLMaps <- calculateQI(modelMPMQL, b1File = B1File, TR2 = 3.4) qMRIQLSmoothedp1Maps <- calculateQI(modelMPMQLsp1, b1File = B1File, TR2 = 3.4) qMRIMaps2 <- calculateQI(modelMPM2, b1File = B1File, TR2 = 3.4) library(oro.nifti) zlim <- matrix(c(0, 0, 0, 3000, 1.5, 35, 2, 10000), 4, 2) R1 <- readNIfTI(file.path(dataDir, "R1map.nii.gz")) R2star <- readNIfTI(file.path(dataDir, "R2starmap.nii.gz")) MT <- readNIfTI(file.path(dataDir, "MTmap.nii.gz")) PD <- readNIfTI(file.path(dataDir, "PDmap.nii.gz")) rimage.options(ylab = "z") par(mfrow = c(4, 4), mar = c(3, 3, 3, 1), mgp = c(2, 1, 0)) nmaps <- c("R1", "R2star", "MT", "PD") rimage(R1[, 11, ], zlim = zlim[1, ], main = paste("true", nmaps[1])) rimage(R2star[, 11, ], zlim = zlim[2, ], main = paste("true", nmaps[2])) rimage(MT[, 11, ], zlim = zlim[3, ], main = paste("true", nmaps[3]), col = colMT) rimage(PD[, 11, ], zlim = zlim[4, ], main = paste("true", nmaps[4])) qmap1 <- extract(qMRIQLMaps, nmaps) for (i in 1:4) rimage(qmap1[[i]][, 11, ], zlim = zlim[i, ], main = paste("Estimated", nmaps[i]), col = if(i==3) colMT else grey(0:225/255)) qmap2 <- extract(qMRIQLSmoothedp1Maps, nmaps) for (i in 1:4) rimage(qmap2[[i]][, 11, ], zlim = zlim[i, ], main = paste("Smoothed", nmaps[i]), col = if(i==3) colMT else grey(0:225/255)) qmap3 <- extract(qMRIMaps2, nmaps) for (i in 1:4) rimage(qmap3[[i]][, 11, ], zlim = zlim[i, ], main = paste("Smoothed data", nmaps[i]), col = if(i==3) colMT else grey(0:225/255)) qmap0 <- extract(qMRIMaps,nmaps) mask <- extract(mpm,"mask") cat("\n", "Bias of NLR estimates\n", "R1", mean((qmap0$R1-R1)[mask]), "R2star", mean((qmap0$R2star-R2star)[mask]), "MT", mean((qmap0$MT-MT)[mask]), "PD", mean((qmap0$PD-PD)[mask]), "\n", "Bias of QL estimates\n", "R1", mean((qmap1$R1-R1)[mask]), "R2star", mean((qmap1$R2star-R2star)[mask]), "MT", mean((qmap1$MT-MT)[mask]), "PD", mean((qmap1$PD-PD)[mask]), "\n") cat("\n", "Root mean squared error of NLR estimate\n", "R1", sqrt(mean((qmap0$R1-R1)[mask]^2)), "R2star", sqrt(mean((qmap0$R2star-R2star)[mask]^2)), "MT", sqrt(mean((qmap0$MT-MT)[mask]^2)), "PD", sqrt(mean((qmap0$PD-PD)[mask]^2)), "\n", "Root mean squared error of QL estimate\n", "R1", sqrt(mean((qmap1$R1-R1)[mask]^2)), "R2star", sqrt(mean((qmap1$R2star-R2star)[mask]^2)), "MT", sqrt(mean((qmap1$MT-MT)[mask]^2)), "PD", sqrt(mean((qmap1$PD-PD)[mask]^2)),"\n", "Root mean squared error of smoothed QL estimate\n", "R1", sqrt(mean((qmap2$R1-R1)[mask]^2)), "R2star", sqrt(mean((qmap2$R2star-R2star)[mask]^2)), "MT", sqrt(mean((qmap2$MT-MT)[mask]^2)), "PD", sqrt(mean((qmap2$PD-PD)[mask]^2)),"\n", "Root mean squared error of estimate from smoothed data \n", "R1", sqrt(mean((qmap3$R1-R1)[mask]^2)), "R2star", sqrt(mean((qmap3$R2star-R2star)[mask]^2)), "MT", sqrt(mean((qmap3$MT-MT)[mask]^2)), "PD", sqrt(mean((qmap3$PD-PD)[mask]^2)),"\n") cat("Mean R1", mean(R1[mask]), "Mean R2star", mean(R2star[mask]), "Mean MT", mean(MT[mask]), "Mean PD", mean(PD[mask]),"\n")
classicalBootstrap <- function(initialSample, b = n, increases = FALSE) { if(is.vector(initialSample)) { initialSample <- matrix(initialSample,nrow=1) } n <- nrow(initialSample) parameterCheckForResampling(initialSample,b) if(increases) { initialSample <- transformFromIncreases(initialSample) } if(!all(apply(initialSample, 1, is.Fuzzy))) { stop("Some values in initial sample are not correct fuzzy numbers") } numbers <- sample(n,b, replace = TRUE) outputSample <- initialSample[numbers,] if(increases) { outputSample <- transformToIncreases(outputSample) } return(outputSample) }
library(azuremlsdk) library(optparse) library(caret) library(glmnet) options <- list( make_option(c("-d", "--data_folder")), make_option(c("-p", "--percent_train")) ) opt_parser <- OptionParser(option_list = options) opt <- parse_args(opt_parser) paste(opt$data_folder) accidents <- readRDS(file.path(opt$data_folder, "accidents.Rd")) summary(accidents) train.pct <- as.numeric(opt$percent_train) if(length(train.pct)==0 || (train.pct<0) || (train.pct>1)) train.pct <- 0.75 accident_idx <- createDataPartition(accidents$dead, p = train.pct, list = FALSE) accident_trn <- accidents[accident_idx, ] accident_tst <- accidents[-accident_idx, ] calc_acc = function(actual, predicted) { mean(actual == predicted) } accident_glmnet_mod = train( dead ~ ., data = accident_trn, method = "glmnet" ) summary(accident_glmnet_mod) log_metric_to_run("Accuracy", calc_acc(actual = accident_tst$dead, predicted = predict(accident_glmnet_mod, newdata = accident_tst)) ) log_metric_to_run("Method","GLMNET") log_metric_to_run("TrainPCT",train.pct) output_dir = "outputs" if (!dir.exists(output_dir)){ dir.create(output_dir) } saveRDS(accident_glmnet_mod, file = "./outputs/model.rds") message("Model saved")
isofind <- function(data, isoscape, calibfit = NULL, mask = NA, verbose = interactive() ) { if (verbose) { print("computing the test statistic and its variance...") } if (is.null(calibfit)) { warning( "The assignment is computed directly on the isoscape without using a calibration! This means that IsoriX considers that you directly fitted the isoscape on the same material as the material you are trying to assign. If this is not the case, rerun isofind() by providing a calibration object to the argument calibfit!") } if (!is.null(mask) && class(mask) != "SpatialPolygons" && is.na(mask)) { OceanMask <- NULL utils::data("OceanMask", envir = environment(), package = "IsoriX") mask <- OceanMask } names_layers <- gsub(" ", "_", as.character(data$sample_ID)) time <- system.time({ if (!is.null(calibfit)) { data$mean_origin <- (data$sample_value - calibfit$param["intercept"])/calibfit$param["slope"] list_stat_layers <- sapply(1:nrow(data), function(i) { data$mean_origin[i] - isoscape$isoscapes$mean } ) } else { list_stat_layers <- sapply(1:nrow(data), function(i) { data$sample_value[i] - isoscape$isoscapes$mean } ) } names(list_stat_layers) <- names_layers stat_brick <- raster::brick(list_stat_layers) rm(list_stat_layers) if (any(names_layers != names(stat_brick))) { warning("Your sample_ID could not be used to name rasters (you may have used numbers, symbols or punctuations that is messing with the package raster), so they have been slightly modified by this package.") names_layers <- names(stat_brick) } if (!is.null(calibfit)) { X <- cbind(1, data$mean_origin) fixedVar <- rowSums(X * (X %*% calibfit$fixefCov)) list_varstat_layers <- sapply(1:nrow(data), function(i) { isoscape$isoscapes$mean_predVar + calibfit$phi/calibfit$param["slope"]^2 + fixedVar[i]/calibfit$param["slope"]^2 + 0 } ) } else { list_varstat_layers <- sapply(1:nrow(data), function(i) { isoscape$isoscapes$mean_respVar } ) } names(list_varstat_layers) <- names_layers varstat_brick <- raster::brick(list_varstat_layers) rm(list_varstat_layers) if (verbose) { print("running the assignment test...") } logpv_brick <- raster::raster(varstat_brick) for (sample_ID in names_layers) { name_layer <- paste("logpv_brick$", sample_ID, sep = "") expr_to_run <- paste(name_layer, "<- .assign_test(raster::values(stat_brick[[sample_ID]]), raster::values(varstat_brick[[sample_ID]]))" ) eval(parse(text = expr_to_run)) } if (verbose) { print("combining assignments across samples...") } group_pv <- raster::calc(logpv_brick, .Fisher_method) }) time <- round(as.numeric((time)[3])) if (verbose) { print(paste("assignments for all", nrow(data), "organisms have been computed in", time, "sec.")) } if (verbose) { print("converting log p-values into p-values...") } pv_brick <- exp(logpv_brick) rm(logpv_brick) names(pv_brick) <- names_layers if (!is.null(mask)) { if (verbose) { print("applying the mask...") } raster_mask <- is.na(raster::rasterize(mask, stat_brick)) stat_brick <- stat_brick*raster_mask names(stat_brick) <- names_layers varstat_brick <- varstat_brick*raster_mask names(varstat_brick) <- names_layers pv_brick <- pv_brick*raster_mask names(pv_brick) <- names_layers group_pv <- raster::overlay(group_pv, raster_mask, fun = prod) } if (!is.null(data$lat) & !is.null(data$long)) { assigns <- .create_spatial_points(long = data$long, lat = data$lat, proj = "+proj=longlat +datum=WGS84" ) } else { assigns <- NULL } calibs <- NULL if (!is.null(calibfit)) { calibs <- calibfit$sp_points$calibs } out <- list(sample = list("stat" = stat_brick, "stat_var" = varstat_brick, "pv" = pv_brick ), group = list("pv" = group_pv), sp_points = list("sources" = isoscape$sp_points$sources, "calibs" = calibs, "assigns" = assigns ) ) class(out) <- c("ISOFIND", "list") if (verbose) { print("done!") } return(out) } .assign_test <- function(stats, vars, log_scale = TRUE) { pv <- 2*(1 - stats::pnorm(abs(stats), mean = 0, sd = sqrt(vars))) if (log_scale) { pv <- log(pv) } return(pv) } .Fisher_method <- function(logpv) { if (length(logpv) == 1) { return(exp(logpv)) } Fisher_stat <- -2*sum(logpv, na.rm = TRUE) df <- 2*length(logpv[!is.na(logpv)]) pv <- stats::pchisq(q = Fisher_stat, df = df, lower.tail = FALSE) return(pv) } print.ISOFIND <- function(x, ...) { print(summary(x)) return(invisible(NULL)) } summary.ISOFIND <- function(object, ...) { for (i in names(object)[names(object) != "sp_points"]) { cat(paste(" print(object[[i]]) cat("\n") } return(invisible(NULL)) }
e2qmol_multipliers <- function(w.length){ return(e2quantum_multipliers(w.length, molar=TRUE)) }
"glow500" "glow11m" "glow_bonemed" "glow_mis_comp" "glow_mis_wmissing" "glow_rand"
A=c(1,1.5,3,5,3.5,4.5,3.5) B=c(1,2,4,7,5,5,4.5) marks=data.frame(A,B) marks ?kmeans (c1 = kmeans(marks,centers=3)) c1$iter cbind(marks, c1$cluster) c1$centers plot(marks, pch=10,col = c1$cluster) c1$centers points(c1$centers, col = 1:3, pch = 8, cex = 3) c1$iter mcenters = marks[c(1,5),] mcenters (c2a <- kmeans(marks, centers=mcenters)) cbind(marks, c2a$cluster) matrix(c(1,1,5,7), ncol=2) ?matrix (c2b <- kmeans(marks, centers=matrix(c(1,1,5,7), ncol=2))) c2a cbind(marks,c2a$cluster) c2a$centers aggregate(marks,by=list(c2a$cluster),FUN=mean) c2a c2a$iter library(dplyr) marks marks %>% group_by(c2a$cluster) %>% summarise_all(funs(sum, mean, median, n())) x1=marks[1,]; x2=marks[2,] x1;x2 sqrt(sum((x1-x2)^2)) sqrt(1.25) dist(rbind(x1,x2)) euc.dist <- function(x1, x2) sqrt(sum((x1 - x2) ^ 2)) for (i in 1:7) print(paste(i, round(euc.dist(marks[i,], marks[1,]),2),sep='-')) ref1 = marks[1,]; ref1 ref2 = marks[4,]; ref2 (d1= apply(marks,1,function(x)sqrt(sum((x-ref1)^2)))) (d2= apply(marks,1,function(x)sqrt(sum((x-ref2)^2)))) df=cbind(marks, d1,d2) df apply(df, 1, function(x) max(which(x == min(x, na.rm = TRUE)))) df apply(df[,c(3,4)],1, min) df3 <-transform(df, mind1d2=apply(df[,c(3,4)],1, min, na.rm = TRUE)) df3 gender = c('M','F','M') gender genderF = factor(gender) genderF grades = c('A','B','C') grades gradesF = factor(grades) gradesF gradesF1 = factor(grades, ordered=T) gradesF1 gradesF2 = factor(grades, ordered=T, levels=c('C','B','A')) gradesF2 marks = rnorm(3, 50,10) df = data.frame(genderF, gradesF, marks) df str(df)
test_that("use_mit_license() works", { create_local_package() use_mit_license() expect_equal(desc::desc_get("License", proj_get())[[1]], "MIT + file LICENSE") expect_proj_file("LICENSE.md") expect_true(is_build_ignored("^LICENSE\\.md$")) expect_proj_file("LICENSE") expect_false(is_build_ignored("^LICENSE$")) }) test_that("use_proprietary_license() works", { create_local_package() use_proprietary_license("foo") expect_equal(desc::desc_get("License", proj_get())[[1]], "file LICENSE") expect_proj_file("LICENSE") }) test_that("other licenses work without error", { create_local_package() expect_error(use_agpl_license(3), NA) expect_error(use_apache_license(2), NA) expect_error(use_cc0_license(), NA) expect_error(use_ccby_license(), NA) expect_error(use_gpl_license(2), NA) expect_error(use_gpl_license(3), NA) expect_error(use_lgpl_license(2.1), NA) expect_error(use_lgpl_license(3), NA) expect_error(use_agpl3_license(), NA) expect_error(use_gpl3_license(), NA) expect_error(use_apl2_license(), NA) }) test_that("check license gives useful errors", { expect_error(check_license_version(1, 2), "must be 2") expect_error(check_license_version(1, 2:4), "must be 2, 3, or 4") }) test_that("generate correct abbreviations", { expect_equal(license_abbr("GPL", 2, TRUE), "GPL (>= 2)") expect_equal(license_abbr("GPL", 2, FALSE), "GPL-2") expect_equal(license_abbr("Apache License", 2, FALSE), "Apache License (== 2)") })
context("Bonett & Price Jr (2020) examples.") A_data <- c(21, 14, 11, 27, 19, 32, 21, 23, 18, 26, 24, 23) B_data <- c(34, 19, 26, 31, 39, 42, 27, 14, 25, 29, 33, 36) ci_median_bs <- function(alpha, y1, y2) { z <- qnorm(1 - alpha/2) n1 <- length(y1) y1 <- sort(y1) n2 <- length(y2) y2 <- sort(y2) med1 <- median(y1) med2 <- median(y2) o1 <- round(n1/2 - sqrt(n1)) if (o1 < 1) {o1 = 1} o2 <- n1 - o1 + 1 l1 <- log(y1[o1]) u1 <- log(y1[o2]) p <- pbinom(o1 - 1, size = n1, prob = .5) z0 <- qnorm(1 - p) se1 <- (u1 - l1)/(2*z0) o1 <- round(n2/2 - sqrt(n2)) if (o1 < 1) {o1 = 1} o2 <- n2 - o1 + 1 l2 <- log(y2[o1]) u2 <- log(y2[o2]) p <- pbinom(o1 - 1, size = n2, prob = .5) z0 <- qnorm(1 - p) se2 <- (u2 - l2)/(2*z0) se <- sqrt(se1^2 + se2^2) logratio <- log(med1/med2) ll <- exp(logratio - z*se) ul <- exp(logratio + z*se) out <- data.frame(median1 = med1, median2 = med2, median_ratio = exp(logratio), LL = ll, UL = ul, log_ratio = logratio, se = se) return(out) } test_that("LRM is correct.", { res_ci_median_bs <- ci_median_bs(alpha = .05, y1 = B_data, y2 = A_data) res_LRM_delta <- LRM(A_data = A_data, B_data = B_data, delta_method = TRUE) res_LRM_bar <- LRM(A_data = A_data, B_data = B_data) expect_equal(res_ci_median_bs$log_ratio, res_LRM_delta$Est) expect_error(expect_equal(res_ci_median_bs$se, res_LRM_delta$SE)) expect_equal(res_ci_median_bs$log_ratio, res_LRM_bar$Est) expect_equal(res_ci_median_bs$se, res_LRM_bar$SE) expect_equal(log(res_ci_median_bs$LL), res_LRM_bar$CI_lower) expect_equal(log(res_ci_median_bs$UL), res_LRM_bar$CI_upper) }) test_that("LRM warns for data series of length 1.", { A_data <- c(9, 5, 1) B_data <- c(2, 3) C_data <- c(3) expect_silent(LRM(A_data = A_data, B_data = B_data, delta_method = TRUE)) expect_silent(LRM(A_data = A_data, B_data = B_data)) expect_warning(LRM(A_data = A_data, B_data = C_data, delta_method = TRUE)) expect_warning(LRM(A_data = A_data, B_data = C_data)) }) test_that("LRM works when data series has zeros.", { A_data <- c(9, 5, 5, 6, 11, 4, 1, 2, 3, 6, 6) B_data <- c(0, 3, 0, 1, 4, 2, 4, 0, 3, 2, 1, 0, 0, 0) C_data <- c(0, 0, 0, 1, 0, 2, 4, 0, 3, 2, 1, 0, 0, 0) expect_silent(LRM(A_data = A_data, B_data = B_data, delta_method = TRUE)) expect_silent(LRM(A_data = A_data, B_data = B_data)) expect_silent(LRM(A_data = A_data, B_data = C_data, delta_method = TRUE)) expect_silent(LRM(A_data = A_data, B_data = C_data)) }) test_that("LRM works within calc_ES() and batch_calc_ES().", { library(dplyr) res_A <- McKissick %>% group_by(Case_pseudonym) %>% summarise( calc_ES(condition = Condition, outcome = Outcome, ES = c("LRRd","LRM"), improvement = "decrease", format = "wide") ) res_B <- batch_calc_ES( McKissick, grouping = Case_pseudonym, condition = Condition, outcome = Outcome, session_number = Session_number, ES = c("LRRd","LRM"), improvement = "decrease", format = "wide" ) res_C <- batch_calc_ES( McKissick, grouping = Case_pseudonym, condition = Condition, outcome = Outcome, session_number = Session_number, improvement = "decrease", ES = "LRM" ) %>% select(-ES) %>% rename_with(.fn = ~ paste("LRM", ., sep = "_"), .cols = -Case_pseudonym) res_D <- batch_calc_ES( McKissick, grouping = Case_pseudonym, condition = Condition, outcome = Outcome, session_number = Session_number, improvement = "decrease", ES = "all", warn = FALSE ) %>% dplyr::filter(ES == "LRM") %>% select(-ES) %>% rename_with(.fn = ~ paste("LRM", ., sep = "_"), .cols = -Case_pseudonym) res_E <- batch_calc_ES( McKissick, grouping = Case_pseudonym, condition = Condition, outcome = Outcome, session_number = Session_number, improvement = "decrease", ES = "parametric", warn = FALSE ) %>% dplyr::filter(ES == "LRM") %>% select(-ES) %>% rename_with(.fn = ~ paste("LRM", ., sep = "_"), .cols = -Case_pseudonym) expect_equal(res_A, res_B) expect_equal(res_C, select(res_B, Case_pseudonym, starts_with("LRM"))) expect_equal(res_C, res_D) expect_equal(res_C, res_E) })
context("copula") test_that("copula behaves as it should", { skip_on_cran() skip_on_travis() fun <- function(d) apply(d,2,function(x)(1:n)[rank(x)])/(1+n) n <- 200 u2 <- cbind(sample(n),sample(n)) d2 <- fun(u2) u3 <- cbind(sample(n),sample(n),sample(n)) d3 <- fun(u3) expect_equal(d2, copula(u2)$copula, label="copula:2dimensional") expect_equal(d3, copula(u3)$copula, label="copula:3dimensional") }) test_that("copula throws errors", { expect_error(copula(TRUE), label="copula:exception") expect_error(copula("text"), label="copula:exception") }) test_that("copula fails for data frames without numerics", { dat <- data.frame(x=letters, stringsAsFactors=FALSE) expect_error(copula(dat)) }) test_that("copula warns if it drops variables", { dat <- data.frame(x=letters, y=seq_along(letters), stringsAsFactors=FALSE) expect_warning(copula(dat)) })
library(hamcrest) expected <- c(0x1.0cbd62e0401d5p+5 + -0x1.a19a1cd3e1fa7p-1i, -0x1.545620f35a3e8p+4 + 0x1.921fb1fdabc2ep-1i, 0x1.af99ec211f9ap+4 + -0x1.823faf58b25ccp-1i, -0x1.a07fafb825976p+4 + 0x1.71fe17a160f0cp-1i, 0x1.911477cb4de82p+5 + -0x1.615f063b6179bp-1i, -0x1.b13aa44ba639ep+5 + 0x1.5066ae27fcfb8p-1i, 0x1.2fb690b98cadap+5 + -0x1.3f1958f6843bp-1i, -0x1.17597c20df2c3p+5 + 0x1.2d7b65af06077p-1i, 0x1.728f945ac46b8p+4 + -0x1.1b9147b798716p-1i, -0x1.402ff46335374p+5 + 0x1.095f85b47cf82p-1i, 0x1.df71d062c36c1p+5 + -0x1.edd570c6d03bp-2i, -0x1.4e2099f44455cp+5 + 0x1.c86f12e46caa8p-2i, 0x1.afd3de847cce1p+4 + -0x1.a29564a2b2fe8p-2i, -0x1.b24de47ddceaep+4 + 0x1.7c51f60495fd2p-2i, 0x1.49213cf1edc6p+5 + -0x1.55ae71c49fbc1p-2i, -0x1.7275ec4ce8a1bp+5 + 0x1.2eb49ae3b9c26p-2i, 0x1.22d869c0e94f5p+5 + -0x1.076e4a31d31b9p-2i, -0x1.a886957f22906p+5 + 0x1.bfcad7a2083bp-3i, 0x1.19a2ba051d825p+5 + -0x1.7047f967a059p-3i, -0x1.2bf437bb305a2p+5 + 0x1.2068102e51472p-3i, 0x1.71d27abb2a67bp+4 + -0x1.a07e93e34b8f8p-4i, -0x1.6ac3d7449a008p+4 + 0x1.ff879c56b56ap-5i, 0x1.b0ccc22558ffap+5 + -0x1.7b21aa498c06p-6i, -0x1.80a463e91363p+1 + -0x1.092bacdb80b6p-6i, 0x1.1e9505bc8c671p+5 + 0x1.c69b02e5ebd6p-5i, -0x1.2d47eef2c341fp+5 + -0x1.8416aa9f9c2a4p-4i, 0x1.67ea420716afep+5 + 0x1.123ee3de5414ap-3i, -0x1.338d8ad4fb357p+5 + -0x1.622d29479ea24p-3i, 0x1.d6de5aa40b439p+4 + 0x1.b1c1f3ef61a25p-3i, -0x1.185c5c32a43f3p+5 + -0x1.0074946a4054cp-2i, 0x1.c5060b0becd7fp+4 + 0x1.27c76452b3eacp-2i, -0x1.356b5f95e987ap+4 + -0x1.4ecf7a66b2a4p-2i, 0x1.ed328740899b4p+4 + 0x1.7582fa3cdeb78p-2i, -0x1.6fdd28af1ef32p+5 + -0x1.9bd81cca9aadap-2i, 0x1.0b624e879529fp+5 + 0x1.c1c532dc6861fp-2i, -0x1.71320d2088666p+4 + -0x1.e740a7884230fp-2i, 0x1.fc8388984676cp+4 + 0x1.0620814ca7e1ep-1i, -0x1.4544128161ceep+5 + -0x1.185e757a2d394p-1i, 0x1.1e9b35ebf1f2ap+5 + 0x1.2a55947a330e6p-1i, -0x1.3199bcda8eba8p+5 + -0x1.3c01545f6af4fp-1i, 0x1.8751d80713e57p+5 + 0x1.4d5d3e4742e4bp-1i, -0x1.31ff9ec4502cp+5 + -0x1.5e64ef7aa2c39p-1i, 0x1.989bf61dce0d9p+5 + 0x1.6f141a8991204p-1i, -0x1.008470167622fp+5 + -0x1.7f668861781eep-1i, 0x1.090d52e94126ap+5 + 0x1.8f58195dc36a4p-1i, -0x1.38bb60c90c9fbp+5 + -0x1.9ee4c65293533p-1i, 0x1.d8423a469dd96p+5 + 0x1.ae08a19140c64p-1i, -0x1.c5f27313708eep+3 + -0x1.bcbfd7e6710bfp-1i, 0x1.7febe7f1677ffp+4 + 0x1.cb06b19178c5ap-1i, -0x1.b0e3c9277cfa4p+5 + -0x1.d8d99334cf556p-1i, 0x1.7454a4f3bc85ep+5 + 0x1.e634febf56c2ap-1i, -0x1.57a4e45319c1fp+5 + -0x1.f315944e3c736p-1i, 0x1.1caa4212b082ep+5 + 0x1.ff78130739edep-1i, -0x1.1e604feea0193p+5 + -0x1.05acacf57f48fp+0i, 0x1.914c891f1aca1p+5 + 0x1.0b5b344fc681cp+0i, -0x1.55b295274671cp+5 + -0x1.10c630192c8ddp+0i, 0x1.52bf9590b00fcp+5 + 0x1.15ec41e8fab9p+0i, -0x1.96b2d40188607p+5 + -0x1.1acc1cbf90ce4p+0i, 0x1.89a70ba49f399p+4 + 0x1.1f64855a86258p+0i, -0x1.2d6e3b22528f3p+5 + -0x1.23b452844f635p+0i, 0x1.609ade7297a47p+5 + 0x1.27ba6d5f54c22p+0i, -0x1.9d95150621936p+5 + -0x1.2b75d1ac661dap+0i, 0x1.5005bb7f147a3p+5 + 0x1.2ee58e0c7a988p+0i, -0x1.13770964d6237p+4 + -0x1.3208c43dabaf6p+0i, 0x1.069d23abb4b79p+5 + 0x1.34dea9535bd3cp+0i, -0x1.271d64a81c745p+5 + -0x1.376685e97aebap+0i, 0x1.98c69fcf4ee9fp+4 + 0x1.399fb652db317p+0i, -0x1.5c18830a1bc29p+5 + -0x1.3b89aac28b451p+0i, 0x1.70f0d61761f6ep+5 + 0x1.3d23e7702a988p+0i, -0x1.2fd8b86cb688cp+5 + -0x1.3e6e04b72f351p+0i, 0x1.0a2894cbf2ecdp+5 + 0x1.3f67af3114f8bp+0i, -0x1.55ef001254381p+5 + -0x1.4010a7ca6f8dbp+0i, 0x1.101077cc1d4fbp+5 + 0x1.4068c3d2d9fa2p+0i, -0x1.0f7b00d7b9b5cp+5 + -0x1.406fed07bf93cp+0i, 0x1.1859ba67a497fp+5 + 0x1.40262199fba75p+0i, -0x1.3099a02d37fa8p+5 + -0x1.3f8b742e4e82ep+0i, 0x1.5ded618a2798ap+5 + 0x1.3ea00bd8a7ab6p+0i, -0x1.ebdd34e36746ap+5 + -0x1.3d6424124670ap+0i, 0x1.037c597934cd9p+5 + 0x1.3bd80caab36cdp+0i, -0x1.93f68e2c75a3bp+4 + -0x1.39fc29b396ad6p+0i, 0x1.e4cd30e2d74cep+5 + 0x1.37d0f3676f914p+0i, -0x1.62c773622be08p+5 + -0x1.3556f60b34f3dp+0i, 0x1.0e30186c470e9p+5 + 0x1.328ed1cae507ep+0i, -0x1.653a0d701b57ep+5 + -0x1.2f793a910e178p+0i, 0x1.4008de0b61adp+5 + 0x1.2c16f7d95a397p+0i, -0x1.28cfbbb9bd36ep+5 + -0x1.2868e47e297f8p+0i, 0x1.20392e06a2006p+5 + 0x1.246fee81476c2p+0i, -0x1.2f99b765ea36dp+5 + -0x1.202d16cfc98f2p+0i, 0x1.bbf0953c30f6bp+4 + 0x1.1ba17101269c2p+0i, -0x1.869258c2cd7b8p+4 + -0x1.16ce231196171p+0i, 0x1.a639ebdea6844p+5 + 0x1.11b46517ca9cdp+0i, -0x1.a68ba139b0d3cp+5 + -0x1.0c5580f619299p+0i, 0x1.3e7970e7ce6a2p+5 + 0x1.06b2d207216fp+0i, -0x1.00d9517a99561p+5 + -0x1.00cdc4c60c6c8p+0i, 0x1.b11213d30199bp+5 + 0x1.f54face4ee4cep-1i, -0x1.95eb95caa1598p+4 + -0x1.e885296041db9p-1i, 0x1.384870244425ep+4 + 0x1.db3f3a44eb502p-1i, -0x1.b501643e97469p+4 + -0x1.cd813a081a824p-1i, 0x1.cfdc68bc74a2cp+5 + 0x1.bf4ea17475b43p-1i, -0x1.7c3939a85b5aep+5 + -0x1.b0ab06c98dddcp-1i, 0x1.6b102eb10f49p+3 + 0x1.a19a1cd3e1f8dp-1i, -0x1.71d62bb871008p+4 + -0x1.921fb1fdabbd4p-1i, 0x1.1725e60ffed8fp+5 + 0x1.823faf58b2553p-1i, -0x1.55b1b55662374p+5 + -0x1.71fe17a160e5ap-1i, 0x1.7f5a866cc19c1p+4 + 0x1.615f063b61771p-1i, -0x1.7dcbdfd06b481p+5 + -0x1.5066ae27fcf15p-1i, 0x1.06925e23edbe1p+6 + 0x1.3f1958f68439p-1i, -0x1.833652c075e5p+5 + -0x1.2d7b65af05ff9p-1i, 0x1.4ec0a043381a7p+5 + 0x1.1b9147b798687p-1i, -0x1.75165f4e808a9p+4 + -0x1.095f85b47cf06p-1i, 0x1.7badac248b85bp+4 + 0x1.edd570c6d032cp-2i, -0x1.f3346dfa347ebp+4 + -0x1.c86f12e46cb0dp-2i, 0x1.52d1ece8bfed4p+5 + 0x1.a29564a2b2ec4p-2i, -0x1.2150e475cfb1bp+5 + -0x1.7c51f60495e41p-2i, 0x1.e962e16affe0fp+4 + 0x1.55ae71c49fa8bp-2i, -0x1.c4f77304e8606p+4 + -0x1.2eb49ae3b9c0bp-2i, 0x1.bfc959102d168p+3 + 0x1.076e4a31d31e8p-2i, -0x1.1d1f1ee3d33f5p+5 + -0x1.bfcad7a208232p-3i, 0x1.b015966bbb7c9p+4 + 0x1.7047f967a048cp-3i, -0x1.3b266880fd23cp+5 + -0x1.2068102e512fcp-3i, 0x1.5241779e03da4p+4 + 0x1.a07e93e34b838p-4i, -0x1.0e3fab9d16b4p+5 + -0x1.ff879c56b56p-5i, 0x1.3f2f25279b2dbp+5 + 0x1.7b21aa498b38p-6i, -0x1.7f7bbc4ff4e44p+5 + 0x1.092bacdb81bep-6i, 0x1.2246a428e6c04p+5 + -0x1.c69b02e5ec36p-5i, -0x1.996005211d4e3p+4 + 0x1.8416aa9f9c4f8p-4i, 0x1.4f8a96a826feep+5 + -0x1.123ee3de5406p-3i, -0x1.909c59c0e9a4p+3 + 0x1.622d29479ec28p-3i, 0x1.37dea14bf64dep+5 + -0x1.b1c1f3ef61c3cp-3i, -0x1.3b2edfd27d7d6p+5 + 0x1.0074946a40647p-2i, 0x1.1f378371d3501p+4 + -0x1.27c76452b3f95p-2i, -0x1.7d1ddb412124cp+5 + 0x1.4ecf7a66b2a95p-2i, 0x1.82edfd823985ap+5 + -0x1.7582fa3cdecabp-2i, -0x1.76b10fc05b69bp+5 + 0x1.9bd81cca9ab9ep-2i, 0x1.424754fcc63cfp+5 + -0x1.c1c532dc6871cp-2i, -0x1.381e9440f193p+5 + 0x1.e740a78842396p-2i, 0x1.5b055b9445c4ep+5 + -0x1.0620814ca7e46p-1i, -0x1.4fc56ddbc339ap+5 + 0x1.185e757a2d41p-1i, 0x1.039ba9624734cp+5 + -0x1.2a55947a33215p-1i, -0x1.2f26c4120506cp+5 + 0x1.3c01545f6affcp-1i, 0x1.a2d55e0f55e4p+5 + -0x1.4d5d3e4742e9bp-1i, -0x1.a7c947f2d50cap+5 + 0x1.5e64ef7aa2bcap-1i, 0x1.6359dd90333ddp+5 + -0x1.6f141a899125bp-1i, -0x1.a6ba267947e1p+5 + 0x1.7f668861782a6p-1i, 0x1.934c6e00f5628p+5 + -0x1.8f58195dc3751p-1i, -0x1.059185b398a4fp+5 + 0x1.9ee4c65293569p-1i, 0x1.17d8d915e3044p+5 + -0x1.ae08a19140ca8p-1i, -0x1.0c4227d6a32d6p+5 + 0x1.bcbfd7e67118dp-1i, 0x1.22322be6defffp+5 + -0x1.cb06b19178cedp-1i, -0x1.c96d238fc0b29p+4 + 0x1.d8d99334cf5f6p-1i, 0x1.1131417899f1fp+4 + -0x1.e634febf56c9ep-1i, -0x1.06ae417591a4cp+5 + 0x1.f315944e3c75ep-1i, 0x1.da4cfc95ee3bp+4 + -0x1.ff78130739f6ep-1i, -0x1.8f294e80036bcp+3 + 0x1.05acacf57f4e2p+0i, 0x1.3634bcdb463eep+5 + -0x1.0b5b344fc688dp+0i, -0x1.343c5ddc0276bp+5 + 0x1.10c630192c92ap+0i, 0x1.77690b2b622f4p+5 + -0x1.15ec41e8fabafp+0i, -0x1.7792526a4aeadp+5 + 0x1.1acc1cbf90d2ap+0i, 0x1.d7e8c90a95edbp+4 + -0x1.1f64855a862aap+0i, -0x1.1db27e4b69654p+5 + 0x1.23b452844f664p+0i, 0x1.939a2cabf5ef2p+4 + -0x1.27ba6d5f54c6p+0i, -0x1.802b4202faeb8p+4 + 0x1.2b75d1ac661e4p+0i, 0x1.8d3a7e57d7bfap+4 + -0x1.2ee58e0c7a9ffp+0i, -0x1.f0881af52b9b6p+4 + 0x1.3208c43dabb4dp+0i, 0x1.c33eb22100ccbp+4 + -0x1.34dea9535bd93p+0i, -0x1.1731cb1d51b6ep+4 + 0x1.376685e97aeb6p+0i, 0x1.f05fe2ef9ad2fp+4 + -0x1.399fb652db2fcp+0i, -0x1.4828ee38f4242p+5 + 0x1.3b89aac28b47p+0i, 0x1.03c96948e32ep+6 + -0x1.3d23e7702aa03p+0i, -0x1.25f9f4ad5dc68p+5 + 0x1.3e6e04b72f38dp+0i, 0x1.7ae16ec4509fp+5 + -0x1.3f67af3114f93p+0i, -0x1.dae51b3189629p+5 + 0x1.4010a7ca6f8dbp+0i, 0x1.4006428040deap+5 + -0x1.4068c3d2d9fdbp+0i, -0x1.d131608acbfc3p+5 + 0x1.406fed07bf981p+0i, 0x1.55935fd2c81e1p+5 + -0x1.40262199fba78p+0i, -0x1.97d09e974096dp+4 + 0x1.3f8b742e4e849p+0i, 0x1.c742c3ca2d0e2p+3 + -0x1.3ea00bd8a7ab4p+0i, -0x1.477624410ab8dp+5 + 0x1.3d64241246746p+0i, 0x1.3bed2833d3051p+4 + -0x1.3bd80caab371p+0i, -0x1.77e70af7bb2d7p+4 + 0x1.39fc29b396b1bp+0i, 0x1.4f5f1382bc137p+5 + -0x1.37d0f3676f944p+0i, -0x1.a759c30dad4ecp+5 + 0x1.3556f60b34f44p+0i, 0x1.f5925705540e9p+4 + -0x1.328ed1cae50acp+0i, -0x1.b80dcfd3b50f9p+4 + 0x1.2f793a910e1bcp+0i, 0x1.305806b53368fp+5 + -0x1.2c16f7d95a3dcp+0i, -0x1.813fb0ffb1ffbp+5 + 0x1.2868e47e29816p+0i, 0x1.627f52abe5671p+4 + -0x1.246fee81476c1p+0i, -0x1.106f81f213819p+5 + 0x1.202d16cfc9945p+0i, 0x1.0df79b0c2f678p+5 + -0x1.1ba1710126a14p+0i, -0x1.ad40d72de36dcp+5 + 0x1.16ce2311961a3p+0i, 0x1.a08188643e43bp+5 + -0x1.11b46517ca9dfp+0i, -0x1.dfbb15d741695p+5 + 0x1.0c5580f61927fp+0i, 0x1.ac1564fa894bdp+5 + -0x1.06b2d2072171ap+0i, -0x1.63731b3ba15cep+4 + 0x1.00cdc4c60c72ap+0i, 0x1.bc09418ec6a52p+4 + -0x1.f54face4ee562p-1i, -0x1.339c0a926192p+5 + 0x1.e885296041df9p-1i, 0x1.2a8f2cee8309ep+5 + -0x1.db3f3a44eb4c8p-1i, -0x1.370fcff9f0f86p+5 + 0x1.cd813a081a894p-1i, 0x1.29c627bfc2341p+5 + -0x1.bf4ea17475ba9p-1i, -0x1.e2287ac3fca43p+4 + 0x1.b0ab06c98de74p-1i ) assertThat(stats:::fft(inverse=TRUE,z=c(0+0i, 0.049997738617622-0.394151678231315i, -0.162286836987266-0.4118734053215i, -0.368580129901942-0.510518048590567i, 0.420008902789442+0.212862861763337i, 0.332766398569408-0.233620277751706i, 0.264617604104067+0.292429642201921i, 0.07998281429866+0.318363215613022i, 0.322801027804864+0.476018521487547i, 0.525111764313381+0.187222667758168i, -0.166216289632984-0.738516417766413i, 0.313842726893916-0.619267865544926i, -0.591380335732259+0.348470741765022i, 0.457764941987522-0.103689071543765i, -0.58127901847917+1.17369820350148i, -0.347010386142286+0.049452963925725i, 0.0342726720745041-0.0058524564797619i, 0.328929309620574-0.062004654015796i, 0.69216954754286-0.421556363726408i, 0.837634584994327-0.314945568780225i, -0.370460032941542-0.687673491975595i, -0.33590219356449-0.885007692953627i, 0.352422863074107+0.272257442277362i, -0.260820853229449-0.449822908268625i, -0.550988096133938-0.024417994482001i, 0.664090465748734+0.500704400693681i, 0.509733837416494+0.026376501483059i, 0.31426343114112-0.025067437304768i, -0.539193540429505+0.073709046614921i, -0.386286553414737-0.41157839405086i, 0.951735229985533-0.574005984494953i, -0.605062107408231+0.219497001914272i, -0.223908518458298+0.217129815457029i, 0.074527002921762+0.631151602563531i, -0.316692661677074+0.645221413953487i, 0.365617034584563+0.00629082344599i, -0.411211404538222-0.58628211392252i, -0.543890275095469+0.554916896214628i, 0.844636825495295-0.213505560713243i, 0.245775121616696+0.339164965800047i, 0.008253333909882+0.59307413825898i, -0.300433974344889-0.041472794619843i, -1.36871187464702+0.76694192682655i, 0.376843853981935-0.152864483770531i, -0.225089950052878-0.0992238412979i, 0.535130687386297-0.936967852187939i, -0.242141224096674-0.956649625182962i, 1.59191309066108+0.33962444236645i, -0.74892661566996-1.08921412722874i, -0.52166714887478-0.180028700167517i, -0.397897587822549+0.555464486808108i, 0.92656799854714+1.28731361616011i, -0.700594061094114+0.205342932257612i, 0.531095951939506+0.143386344297323i, -0.99758597584971-0.402668204591331i, 0.461350884263873+0.450185730135808i, 0.675304419379909-0.408673021250101i, 0.71758684145034+0.404792017949363i, 0.3035094616159-0.425532807458167i, 0.506055740891074+0.777705592636569i, 0.181560968229867+0.659430574391635i, 1.10397703787741-0.6886584427141i, -0.181073539200941+0.131545785616102i, 0.913193510885363+0.221545381591971i, 0.690322424306309+0.174566573804035i, -0.45483583235305-0.582192664609651i, -0.846595431910549-0.467203939952173i, -0.946638614879789-0.099906318347228i, 0.063418372506302-0.97257399962078i, -0.524368273125362+0.18065349165976i, -0.252196738751498-0.488745389511525i, -0.622922268128171+0.021777719846512i, -0.61095976261603-1.31761743291479i, -0.63929889523417+0.801397035149863i, -0.202794152643118-0.609876688135212i, -0.833718545873324+0.224598664498435i, 0.578293915403353-0.944405436783388i, 0.767240327727704-0.240964439210037i, -0.152988257623007-0.904825616277863i, 0.679457526456541-0.268837452305894i, 0.234934918030234+0.141278774406706i, -0.152584453290296-0.282538987041591i, -0.051000168322624+0.72513728803682i, -0.56129132864059+1.01415922597238i, -1.55090405662834+0.23151143485493i, 0.762710644622458-0.65694511658226i, 0.336249977456837-0.3539853252003i, 0.781513429691396+0.413028432182484i, -1.21749107714943+1.12529884453592i, -0.512666341410842+0.076197302189448i, -0.553629313503129-0.100340270793262i, -0.906476963859203-0.503695057247765i, -0.622370910791937-0.265508583764482i, 0.14689247417201-1.09298241182197i, 0.061311810343343+0.969935138015308i, -0.652955744047943+0.865942725685155i, 0.245419246727404-0.78935287914092i, 0.782962124431475-0.042779993270524i, -0.178005140682559-0.638433583284494i, -0.610509023289185+0i, 36.95629+0i, 0.339114047291116-0.815628910889233i, -0.178005140682559+0.638433583284495i, 0.782962124431475+0.042779993270524i, 0.245419246727404+0.789352879140919i, -0.652955744047944-0.865942725685155i, 0.061311810343343-0.969935138015308i, 0.14689247417201+1.09298241182197i, -0.622370910791938+0.265508583764482i, -0.906476963859203+0.503695057247765i, -0.553629313503129+0.100340270793262i, -0.512666341410842-0.076197302189448i, -1.21749107714943-1.12529884453592i, 0.781513429691396-0.413028432182484i, 0.336249977456837+0.3539853252003i, 0.762710644622458+0.65694511658226i, -1.55090405662834-0.23151143485493i, -0.56129132864059-1.01415922597238i, -0.051000168322624-0.72513728803682i, -0.152584453290296+0.282538987041591i, 0.234934918030234-0.141278774406706i, 0.679457526456541+0.268837452305894i, -0.152988257623007+0.904825616277863i, 0.767240327727704+0.240964439210037i, 0.578293915403353+0.944405436783389i, -0.833718545873324-0.224598664498436i, -0.202794152643118+0.609876688135211i, -0.63929889523417-0.801397035149863i, -0.61095976261603+1.31761743291479i, -0.622922268128171-0.021777719846512i, -0.252196738751498+0.488745389511525i, -0.524368273125362-0.18065349165976i, 0.063418372506302+0.972573999620779i, -0.946638614879789+0.099906318347228i, -0.846595431910549+0.467203939952173i, -0.45483583235305+0.582192664609651i, 0.690322424306309-0.174566573804035i, 0.913193510885363-0.221545381591971i, -0.181073539200941-0.131545785616102i, 1.10397703787741+0.6886584427141i, 0.181560968229867-0.659430574391636i, 0.506055740891074-0.777705592636569i, 0.3035094616159+0.425532807458167i, 0.71758684145034-0.404792017949363i, 0.675304419379909+0.408673021250101i, 0.461350884263874-0.450185730135808i, -0.99758597584971+0.402668204591331i, 0.531095951939506-0.143386344297323i, -0.700594061094115-0.205342932257612i, 0.92656799854714-1.28731361616011i, -0.397897587822549-0.555464486808108i, -0.521667148874779+0.180028700167517i, -0.74892661566996+1.08921412722874i, 1.59191309066108-0.33962444236645i, -0.242141224096674+0.956649625182963i, 0.535130687386297+0.936967852187939i, -0.225089950052878+0.0992238412979i, 0.376843853981935+0.152864483770531i, -1.36871187464702-0.76694192682655i, -0.300433974344889+0.041472794619843i, 0.008253333909882-0.59307413825898i, 0.245775121616696-0.339164965800046i, 0.844636825495295+0.213505560713243i, -0.543890275095469-0.554916896214628i, -0.411211404538222+0.58628211392252i, 0.365617034584563-0.00629082344599i, -0.316692661677074-0.645221413953487i, 0.074527002921762-0.631151602563532i, -0.223908518458298-0.217129815457029i, -0.605062107408231-0.219497001914272i, 0.951735229985533+0.574005984494953i, -0.386286553414736+0.41157839405086i, -0.539193540429505-0.073709046614921i, 0.31426343114112+0.025067437304768i, 0.509733837416494-0.026376501483059i, 0.664090465748735-0.500704400693681i, -0.550988096133938+0.024417994482001i, -0.260820853229449+0.449822908268625i, 0.352422863074107-0.272257442277362i, -0.33590219356449+0.885007692953627i, -0.37046003294154+0.687673491975592i, 0.837634584994327+0.314945568780225i, 0.69216954754286+0.421556363726408i, 0.328929309620574+0.062004654015796i, 0.0342726720745042+0.0058524564797619i, -0.347010386142286-0.049452963925725i, -0.58127901847917-1.17369820350148i, 0.457764941987522+0.103689071543765i, -0.591380335732259-0.348470741765022i, 0.313842726893917+0.619267865544926i, -0.166216289632984+0.738516417766413i, 0.525111764313381-0.187222667758168i, 0.322801027804864-0.476018521487546i, 0.07998281429866-0.318363215613022i, 0.264617604104067-0.292429642201921i, 0.332766398569408+0.233620277751706i, 0.420008902789442-0.212862861763337i, -0.368580129901942+0.510518048590567i, -0.162286836987266+0.411873405321501i, 0.049997738617622+0.394151678231315i )) , identicalTo( expected, tol = 1e-6 ) )
survRDah <- function(DH, freq=1, occsPerSeason, N, pStar) { if(length(occsPerSeason) > 1) stop("Different occasions per season are not supported: 'occsPerSeason' must be scalar.") K <- ncol(DH) / occsPerSeason if(length(N) != K) stop("'N' must have one value per season.") if(length(pStar) != K) stop("'pStar' must have one value per season.") seasonID <- rep(1:K, each=occsPerSeason) if(length(seasonID) != ncol(DH)) stop("The number of columns of 'DH' does not match the season data.") getDHseason <- function(dh) tapply(dh, as.factor(seasonID), max) DHseason <- t(apply(DH, 1, getDHseason)) mMat <- ch2mArray(DHseason, freq=freq) param <- rep(0, K-1) nll <- function(param) { log_phi <- plogis(param, log.p=TRUE) nll <- -sum(mMat * log_qArray(log_phi, log(pStar[-1]), log(1 - pStar[-1]))) return(min(nll, .Machine$double.xmax)) } res <- nlm(nll, param) phiHat <- plogis(res$estimate) bHat <- N[-1] / N[-K] - phiHat return(list( phiHat = phiHat, bHat = bHat, pStarHat = pStar, Nhat = N)) }
library(testthat) library(RClone) test_check("RClone", filter = "p5") print("unit tests p5 are ok !")
setMethod("sform", "character", function(object){ object = path.expand(object) stopifnot(file.exists(object)) slots = paste0("sto_xyz:", 1:3) res = sapply(slots, function(key) { fslval(object, keyword = key, verbose = FALSE) }) convmat <- function(form){ ss <- strsplit(form, " ") ss <- t(sapply(ss, function(x) x[x!=""])) class(ss) <- "numeric" return(ss) } res = convmat(res) rownames(res) = NULL return(res) })
get_random_seed <- function() { env <- globalenv() env$.Random.seed } set_random_seed <- function(seed, kind = NULL) { env <- globalenv() if (is.null(seed)) { if (!is.null(kind)) RNGkind(kind) rm(list = ".Random.seed", envir = env, inherits = FALSE) } else { env$.Random.seed <- seed } } next_random_seed <- function(seed = get_random_seed()) { sample.int(n = 1L, size = 1L, replace = FALSE) seed_next <- get_random_seed() stop_if_not(!any(seed_next != seed)) invisible(seed_next) } is_valid_random_seed <- function(seed) { oseed <- get_random_seed() on.exit(set_random_seed(oseed)) env <- globalenv() env$.Random.seed <- seed res <- tryCatch({ sample.int(n = 1L, size = 1L, replace = FALSE) }, simpleWarning = function(w) w) !inherits(res, "simpleWarning") } as_lecyer_cmrg_seed <- function(seed) { if (is.logical(seed)) { stop_if_not(length(seed) == 1L) if (!is.na(seed) && !seed) { stopf("Argument 'seed' must be TRUE if logical: %s", seed) } oseed <- get_random_seed() if (!is.na(seed) && seed) { if (is_lecyer_cmrg_seed(oseed)) return(oseed) } okind <- RNGkind("L'Ecuyer-CMRG")[1] on.exit(set_random_seed(oseed, kind = okind), add = TRUE) return(get_random_seed()) } stop_if_not(is.numeric(seed), all(is.finite(seed))) seed <- as.integer(seed) if (is_lecyer_cmrg_seed(seed)) { return(seed) } if (length(seed) == 1L) { oseed <- get_random_seed() on.exit(set_random_seed(oseed), add = TRUE) okind <- RNGkind("L'Ecuyer-CMRG")[1] on.exit(set_random_seed(oseed, kind = okind), add = TRUE) set.seed(seed) return(get_random_seed()) } stopf("Argument 'seed' must be L'Ecuyer-CMRG RNG seed as returned by parallel::nextRNGStream() or an single integer: %s", capture.output(str(seed))) } is_lecyer_cmrg_seed <- function(seed) { is.numeric(seed) && length(seed) == 7L && all(is.finite(seed)) && (seed[1] %% 10000L == 407L) } make_rng_seeds <- function(count, seed = FALSE, debug = getOption("future.debug", FALSE)) { if (is.null(seed)) return(NULL) if (is.logical(seed) && !is.na(seed) && !seed) return(NULL) stop_if_not(is.numeric(count), length(count) == 1L, !is.na(count), count >= 0L) seeds <- NULL if (debug) mdebug("Generating random seeds ...") if (is.list(seed)) { if (debug) mdebugf("Using a pre-define stream of %d random seeds ...", count) seeds <- seed nseeds <- length(seeds) if (nseeds != count) { stopf("Argument 'seed' is a list, which specifies the sequence of seeds to be used for each element iterated over, but length(seed) != number of elements: %g != %g", nseeds, count) } ns <- unique(unlist(lapply(seeds, FUN = length), use.names = FALSE)) if (length(ns) != 1L) { stopf("The elements of the list specified in argument 'seed' are not all of the same lengths (did you really pass RNG seeds?): %s", hpaste(ns)) } if (ns == 1L) { stop("Argument 'seed' is invalid. Pre-generated random seeds must be valid .Random.seed seeds, which means they should be all integers and consists of two or more elements, not just one.") } types <- unlist(lapply(seeds, FUN = typeof), use.names = FALSE) if (!all(types == "integer")) { stopf("The elements of the list specified in argument 'seed' are not all integers (did you really pass RNG seeds?): %s", hpaste(unique(types))) } if (!is_valid_random_seed(seeds[[1]])) { stopf("The list in argument 'seed' does not seem to hold elements that are valid .Random.seed values: %s", capture.output(str(seeds[[1]]))) } if (debug) { mdebugf("Using a pre-define stream of %d random seeds ... DONE", count) mdebug("Generating random seeds ... DONE") } return(seeds) } if (debug) mdebugf("Generating random seed streams for %d elements ...", count) .seed <- as_lecyer_cmrg_seed(seed) oseed <- next_random_seed() on.exit(set_random_seed(oseed)) seeds <- vector("list", length = count) for (ii in seq_len(count)) { seeds[[ii]] <- nextRNGSubStream(.seed) .seed <- nextRNGStream(.seed) } if (debug) { mdebugf("Generating random seed streams for %d elements ... DONE", count) mdebug("Generating random seeds ... DONE") } seeds }
context("lexicon fetches lexicons") test_that("unknown lexicons fail", { expect_error(lexicon("thisdoesnotexist")) }) test_that("lexicons exist", { expect_true(any(class(lexicon("aws")) == "tbl")) expect_true(any(class(lexicon("az")) == "tbl")) expect_true(any(class(lexicon("brew")) == "tbl")) expect_true(any(class(lexicon("docker")) == "tbl")) expect_true(any(class(lexicon("gcloud")) == "tbl")) expect_true(any(class(lexicon("gh")) == "tbl")) expect_true(any(class(lexicon("git")) == "tbl")) expect_true(any(class(lexicon("heroku")) == "tbl")) expect_true(any(class(lexicon("kubectl")) == "tbl")) expect_true(any(class(lexicon("sfdx")) == "tbl")) })
skip_if(utils::packageVersion('grid') < "3.6") test_that("geom_polygon draws correctly", { tbl <- data_frame( x = c( 0, 10, 10, 0, 20, 30, 30, 20, 22, 28, 28, 22 ), y = c( 0, 0, 10, 10, 20, 20, 30, 30, 22, 22, 28, 28 ), group = c(rep(1, 4), rep(2, 8)), subgroup = c(rep(1, 8), rep(2, 4)) ) p <- ggplot(tbl, aes(x, y, group = group, subgroup = subgroup)) + geom_polygon() expect_doppelganger("basic polygon plot", p) })