code
stringlengths
1
13.8M
sortedL1Prox <- function(x, lambda, method = c("stack", "pava")) { prox_method <- switch(match.arg(method), stack = 0, pava = 1) stopifnot( length(x) == length(lambda), !is.unsorted(rev(lambda)), all(lambda >= 0), all(is.finite(lambda)), all(is.finite(x)) ) res <- sortedL1ProxCpp(as.matrix(x), lambda, prox_method) as.vector(res) }
alpha.div<-function(x,index){ if(index=="simp")alpha<-Simp.index(x) if(index=="inv.simp")alpha<-Simp.index(x,inv=TRUE) if(index=="shan")alpha<-SW.index(x) alpha } Simp.index<-function(x,inv=FALSE){ if(ncol(as.matrix(x))==1){ p.i<-x/sum(x) D<-1-sum(p.i^2)} if(ncol(as.matrix(x))>1){ p.i<-apply(x,1,function(x){x/sum(x)}) if(inv==FALSE)D<-1-apply(p.i^2,2,sum) if(inv==TRUE)D<-1/apply(p.i^2,2,sum) } D } SW.index<-function(x){ if(ncol(as.matrix(x))==1){ p.i<-x/sum(x) p.i.new<-p.i[p.i!=0] h.prime<--1*sum(log(p.i.new)*p.i.new)} if(ncol(as.matrix(x))>1){ p.i<-apply(x,1,function(x){x/sum(x)}) h<-apply(p.i,1,function(x){log(x)*x}) h.prime<- -1*apply(h,1,function(x){sum(x[!is.na(x)])})} h.prime }
print.mcmcRocPrc <- function(x, ...) { auc_roc <- x$area_under_roc auc_prc <- x$area_under_prc has_curves <- !is.null(x$roc_dat) has_sims <- length(auc_roc) > 1 if (!has_sims) { roc_msg <- sprintf("%.3f", round(auc_roc, 3)) prc_msg <- sprintf("%.3f", round(auc_prc, 3)) } else { roc_msg <- sprintf("%.3f [80%%: %.3f - %.3f]", round(mean(auc_roc), 3), round(quantile(auc_roc, 0.1), 3), round(quantile(auc_roc, 0.9), 3)) prc_msg <- sprintf("%.3f [80%%: %.3f - %.3f]", round(mean(auc_prc), 3), round(quantile(auc_prc, 0.1), 3), round(quantile(auc_prc, 0.9), 3)) } cat("mcmcRocPrc object\n") cat(sprintf("curves: %s; fullsims: %s\n", has_curves, has_sims)) cat(sprintf("AUC-ROC: %s\n", roc_msg)) cat(sprintf("AUC-PR: %s\n", prc_msg)) invisible(x) } plot.mcmcRocPrc <- function(x, n = 40, alpha = .5, ...) { stopifnot( "Use mcmcRocPrc(..., curves = TRUE) to generate data for plots" = (!is.null(x$roc_dat)), "alpha must be between 0 and 1" = (alpha >= 0 & alpha <= 1), "n must be > 0" = (n > 0) ) obj<- x fullsims <- length(obj$roc_dat) > 1 if (!fullsims) { graphics::par(mfrow = c(1, 2)) plot(obj$roc_dat[[1]], type = "s", xlab = "FPR", ylab = "TPR") graphics::abline(a = 0, b = 1, lty = 3, col = "gray50") prc_dat <- obj$prc_dat[[1]] prc_dat$y[1] <- prc_dat$y[2] plot(prc_dat, type = "l", xlab = "TPR", ylab = "Precision", ylim = c(0, 1)) graphics::abline(a = attr(x, "y_pos_rate"), b = 0, lty = 3, col = "gray50") } else { graphics::par(mfrow = c(1, 2)) roc_dat <- obj$roc_dat x <- lapply(roc_dat, `[[`, 1) x <- do.call(cbind, x) colnames(x) <- paste0("sim", 1:ncol(x)) y <- lapply(roc_dat, `[[`, 2) y <- do.call(cbind, y) colnames(y) <- paste0("sim", 1:ncol(y)) xavg <- rowMeans(x) yavg <- rowMeans(y) plot(xavg, yavg, type = "n", xlab = "FPR", ylab = "TPR") samples <- sample(1:ncol(x), n) for (i in samples) { graphics::lines( x[, i], y[, i], type = "s", col = grDevices::rgb(127, 127, 127, alpha = alpha*255, maxColorValue = 255) ) } graphics::lines(xavg, yavg, type = "s") prc_dat <- obj$prc_dat x <- lapply(prc_dat, `[[`, 1) y <- lapply(prc_dat, `[[`, 2) point_cloud <- data.frame( x = unlist(x), y = unlist(y) ) point_cloud <- stats::aggregate(point_cloud[, "y", drop = FALSE], by = list(x = as.factor(point_cloud$x)), FUN = mean) point_cloud$x <- as.numeric(as.character(point_cloud$x)) xavg <- point_cloud$x yavg <- point_cloud$y plot(xavg, yavg, type = "n", xlab = "TPR", ylab = "Precision", ylim = c(0, 1)) samples <- sample(1:length(prc_dat), n) for (i in samples) { graphics::lines( x[[i]], y[[i]], col = grDevices::rgb(127, 127, 127, alpha = alpha*255, maxColorValue = 255) ) } graphics::lines(xavg, yavg) } invisible(x) } as.data.frame.mcmcRocPrc <- function(x, row.names = NULL, optional = FALSE, what = c("auc", "roc", "prc"), ...) { what <- match.arg(what) if (what=="auc") { return(as.data.frame(x[c("area_under_roc", "area_under_prc")])) } else if (what %in% c("roc", "prc")) { if (what=="roc") element <- "roc_dat" else element <- "prc_dat" if (is.null(x[[element]])) { stop("No curve data; use mcmcRocPrc(..., curves = TRUE)") } if (length(x[[element]])==1L) { return(data.frame(sim = 1L, x[[element]][[1]])) } outlist <- x[[element]] outlist <- Map(cbind, sim = (1:length(outlist)), outlist) outdf <- do.call(rbind, outlist) return(outdf) } stop("Developer error (I should not be here): please file an issue on GitHub") }
context("Splitting Pilot Set") test_dat <- read.csv("test_data.csv") test_that("split_pilot_set errors work", { expect_error( split_pilot_set(92, treat = "treated" ), "data must be a data.frame" ) expect_error( split_pilot_set(test_dat, treat = c("treated", "control") ), "treat must be a single string" ) expect_error( split_pilot_set(test_dat, treat = "zombies" ), "treat must be the name of a column in data" ) test_dat$treat_cont <- rnorm(100) test_dat$treat_char <- ifelse(test_dat$treated == 0, "a", "b") test_dat$treat_12 <- test_dat$treated + 1 expect_error( split_pilot_set(test_dat, treat = "treat_cont" ), "treatment column must be binary or logical" ) expect_error( split_pilot_set(test_dat, treat = "treat_char" ), "treatment column must be binary or logical" ) expect_error( split_pilot_set(test_dat, treat = "treat_12" ), "treatment column must be binary or logical" ) expect_error( split_pilot_set(test_dat, treat = "treated", pilot_fraction = "socks" ), "pilot_fraction must be numeric" ) expect_error( split_pilot_set(test_dat, treat = "treated", pilot_fraction = -1 ), "pilot_fraction must be between 0 and 1" ) expect_error( split_pilot_set(test_dat, treat = "treated", pilot_size = 0 ), "pilot_size must be greater than 1" ) expect_error( split_pilot_set(test_dat, treat = "treated", pilot_size = "socks" ), "pilot_size must be numeric" ) expect_error( split_pilot_set(test_dat, treat = "treated", pilot_size = 101 ), "Requested pilot size outnumbers control sample" ) expect_warning( split_pilot_set(test_dat, treat = "treated", pilot_size = 82 ), "Requested pilot size requires more than 70% of all controls" ) expect_error( split_pilot_set(test_dat, treat = "treated", group_by_covariates = "socks" ), "All covariates in group_by_covariates must be columns of the data" ) expect_error( split_pilot_set(test_dat, treat = "treated", group_by_covariates = 9 ), "group_by_covariates should be a character vector" ) }) test_that("split_pilot_set with pilot_fraction works", { mysplit <- split_pilot_set(test_dat, treat = "treated", pilot_fraction = 0.2, group_by_covariates = c("B1", "B2") ) expect_true(dim(mysplit$analysis_set)[1] > 0) expect_true(dim(mysplit$pilot_set)[1] > 0) expect_true(all(mysplit$pilot_set$treated == 0)) expect_equal(dim(mysplit$analysis_set)[1] + dim(mysplit$pilot_set)[1], 100) expect_equal(dim(mysplit$analysis_set)[2], 9) expect_equal(dim(mysplit$pilot_set)[2], 9) }) test_that("split_pilot_set with pilot_size works", { mysplit <- split_pilot_set(test_dat, treat = "treated", pilot_size = 25 ) expect_true(dim(mysplit$analysis_set)[1] > 0) expect_true(dim(mysplit$pilot_set)[1] > 0) expect_true(all(mysplit$pilot_set$treated == 0)) expect_equal(dim(mysplit$analysis_set)[1] + dim(mysplit$pilot_set)[1], 100) expect_equal(dim(mysplit$analysis_set)[2], 9) expect_equal(dim(mysplit$pilot_set)[2], 9) expect_equal(dim(mysplit$pilot_set)[1], 25) })
context("detect_if") test_that("works with any case", { dfm <- data.frame(CensusID = c(1, 2, NA)) expect_true(detect_if(dfm, "censusid", is_multiple)) expect_false(detect_if(dfm, "censusid", is_duplicated)) dfm <- data.frame(CensusID = c(1, 1)) expect_true(detect_if(dfm, "censusid", is_duplicated)) expect_false(detect_if(dfm, "censusid", is_multiple)) dfm <- data.frame(CensusID = c(1, 1, 2)) expect_true(detect_if(dfm, "censusid", is_duplicated)) expect_true(detect_if(dfm, "censusid", is_multiple)) }) test_that("rejects invalid var", { dfm <- data.frame(CensusID = c(1, 2, NA)) expect_error(detect_if(dfm, "bad", is_multiple), "invalid name") expect_error(detect_if(dfm, "bad", is_duplicated), "invalid name") }) dfm <- function(x) data.frame(Name = x, stringsAsFactors = TRUE) test_that("creates a function that detects duplicates on a specific variable", { expect_true(detect_if(dfm(c(1, 1)), "Name", is_duplicated)) expect_false(detect_if(dfm(c(1, NA)), "Name", is_duplicated)) expect_false(detect_if(dfm(c(1, 2)), "Name", is_duplicated)) }) test_that("works with upper or lowercase name", { expect_true(detect_if(dfm(c(1, 1)), "Name", is_duplicated)) expect_true(detect_if(dfm(c(1, 1)), "name", is_duplicated)) expect_false(detect_if(dfm(c(1, 2)), "Name", is_duplicated)) expect_false(detect_if(dfm(c(1, 2)), "name", is_duplicated)) }) test_that("ignores groups but groups can be handled via map(nest()$data)", { skip_if_not_installed("tidyr") skip_if_not_installed("dplyr") skip_if_not_installed("purrr") library(tidyr) library(dplyr) library(purrr) dfm <- data.frame(x = c(1, 1), g = c(1, 2), stringsAsFactors = TRUE) expect_true(detect_if(group_by(dfm, g), "x", is_duplicated)) grouped <- group_by(dfm, g) expect_false(any( map_lgl(nest(grouped)$data, ~ detect_if(.x, "x", is_duplicated)) )) })
"GetResiduals" <- function(obj) { class.obj = class(obj)[1] if (class.obj != "ar" && class.obj != "arima0" && class.obj != "Arima" && class.obj != "varest" && class.obj != "ARIMA" && class.obj != "lm" && class.obj != "glm" && class.obj != "list" ) stop("obj must be class ar, arima0, Arima, (ARIMA forecast_ARIMA Arima), varest, lm, (glm lm), or list") if (all(class.obj=="ar")){ order <- obj$order res <- ts(as.matrix(obj$resid)[-(1:order),]) } else if (all(class.obj == "arima0") || all(class.obj == "Arima")|| all (class.obj == "ARIMA")) { pdq <- obj$arma p <- pdq[1] q <- pdq[2] ps <- pdq[3] qs <- pdq[4] order <- p+q+ps+qs res <- ts(obj$residuals) } else if (all(class.obj=="varest")){ order <- obj$p res <- resid(obj) } else if (all(class.obj == "list")){ order <- obj$order if(is.null(order)) order <- 0 else order <- order res <- obj$res } if (all(class.obj=="lm") || all(class.obj == "glm")){ order <- 0 res <- obj$residuals } return(list(order = order, res = res)) }
pimeshed <- function(y, x, z, k=NULL, proj_dim=2, family = "gaussian", block_size = 30, n_samples = 1000, n_burnin = 100, n_thin = 1, n_threads = 4, verbose = 0, settings = list(adapting=TRUE, ps=TRUE, saving=FALSE), prior = list(beta=NULL, tausq=NULL, sigmasq = NULL, toplim = NULL, btmlim = NULL, set_unif_bounds=NULL), starting = list(beta=NULL, tausq=NULL, theta=NULL, lambda=NULL, v=NULL, mcmcsd=.05, mcmc_startfrom=0), debug = list(sample_beta=TRUE, sample_tausq=TRUE, sample_theta=TRUE, sample_w=TRUE, sample_lambda=TRUE, verbose=FALSE, debug=FALSE) ){ if(verbose > 0){ cat("Bayesian pi-Meshed GP regression model fit via Markov chain Monte Carlo\n") } model_tag <- "Bayesian pi-Meshed GP regression\n o --> o --> o ^ ^ ^ | | | o --> o --> o ^ ^ ^ | | | o --> o --> o\n\n" set_default <- function(x, default_val){ return(if(is.null(x)){ default_val} else { x })} if(1){ mcmc_keep <- n_samples mcmc_burn <- n_burnin mcmc_thin <- n_thin mcmc_adaptive <- settings$adapting %>% set_default(TRUE) mcmc_verbose <- debug$verbose %>% set_default(FALSE) mcmc_debug <- debug$debug %>% set_default(FALSE) saving <- settings$saving %>% set_default(FALSE) use_ps <- settings$ps %>% set_default(TRUE) which_hmc <- 4 low_mem <- FALSE if(is.null(dim(y))){ y <- matrix(y, ncol=1) orig_y_colnames <- colnames(y) <- "Y_1" } else { if(is.null(colnames(y))){ orig_y_colnames <- colnames(y) <- paste0('Y_', 1:ncol(y)) } else { orig_y_colnames <- colnames(y) colnames(y) <- paste0('Y_', 1:ncol(y)) } } if(verbose == 0){ mcmc_print_every <- 0 } else { if(verbose <= 20){ mcmc_tot <- mcmc_burn + mcmc_thin * mcmc_keep mcmc_print_every <- 1+round(mcmc_tot / verbose) } else { if(is.infinite(verbose)){ mcmc_print_every <- 1 } else { mcmc_print_every <- verbose } } } X_pca <- prcomp(x) coords <- X_pca$x[,1:proj_dim] %>% as.matrix() colnames(coords) <- paste0("Var", 1:ncol(coords)) dd <- ncol(coords) if(is.null(colnames(x))){ orig_X_colnames <- colnames(x) <- paste0('X_', 1:ncol(x)) } else { orig_X_colnames <- colnames(x) colnames(x) <- paste0('X_', 1:ncol(x)) } if(is.null(colnames(z))){ orig_Z_colnames <- colnames(z) <- paste0('Z_', 1:ncol(z)) } else { orig_Z_colnames <- colnames(z) colnames(z) <- paste0('Z_', 1:ncol(z)) } nr <- nrow(x) q <- ncol(y) k <- ifelse(is.null(k), q, k) p <- ncol(x) family <- if(length(family)==1){rep(family, q)} else {family} family_in <- data.frame(family=family) available_families <- data.frame(id=0:4, family=c("gaussian", "poisson", "binomial", "beta", "negbinomial")) family_id <- family_in %>% left_join(available_families, by=c("family"="family")) %>% pull(.data$id) latent <- "gaussian" if(!(latent %in% c("gaussian"))){ stop("Latent process not recognized. Choose 'gaussian'") } axis_partition <- rep(round((nr/block_size)^(1/dd)), dd) use_forced_grid <- FALSE use_cache <- FALSE sample_w <- debug$sample_w %>% set_default(TRUE) sample_beta <- debug$sample_beta %>% set_default(TRUE) sample_tausq <- debug$sample_tausq %>% set_default(TRUE) sample_theta <- debug$sample_theta %>% set_default(TRUE) sample_lambda <- debug$sample_lambda %>% set_default(TRUE) } if(1){ yrownas <- apply(y, 1, function(i) ifelse(sum(is.na(i))==q, NA, 1)) na_which <- ifelse(!is.na(yrownas), 1, NA) simdata <- data.frame(ix=1:nrow(coords)) %>% cbind(coords, y, na_which, x, z) %>% as.data.frame() simdata %<>% dplyr::arrange(!!!rlang::syms(paste0("Var", 1:dd))) coords <- simdata %>% dplyr::select(dplyr::contains("Var")) %>% as.matrix() sort_ix <- simdata$ix fixed_thresholds <- 1:dd %>% lapply(function(i) kthresholdscp(coords[,i], axis_partition[i])) system.time(fake_coords_blocking <- coords %>% as.matrix() %>% gen_fake_coords(fixed_thresholds, 1) ) system.time(coords_blocking <- coords %>% as.matrix() %>% tessellation_axis_parallel_fix(fixed_thresholds, 1) %>% dplyr::mutate(na_which = simdata$na_which, sort_ix=sort_ix) ) coords_blocking %<>% dplyr::rename(ix=sort_ix) blocks_prop <- coords_blocking[,paste0("L", 1:dd)] %>% unique() blocks_fake <- fake_coords_blocking[,paste0("L", 1:dd)] %>% unique() if(nrow(blocks_fake) != nrow(blocks_prop)){ suppressMessages(adding_blocks <- blocks_fake %>% dplyr::setdiff(blocks_prop) %>% dplyr::left_join(fake_coords_blocking)) coords_blocking <- dplyr::bind_rows(coords_blocking, adding_blocks) coords_blocking %<>% dplyr::arrange(!!!rlang::syms(paste0("Var", 1:dd))) } } nr_full <- nrow(coords_blocking) if(dd < 4){ suppressMessages(parents_children <- mesh_graph_build(coords_blocking %>% dplyr::select(-.data$ix), axis_partition, FALSE)) } else { suppressMessages(parents_children <- mesh_graph_build_hypercube(coords_blocking %>% dplyr::select(-.data$ix))) } parents <- parents_children[["parents"]] children <- parents_children[["children"]] block_names <- parents_children[["names"]] block_groups <- parents_children[["groups"]] suppressMessages(simdata_in <- coords_blocking %>% dplyr::select(-na_which) %>% dplyr::left_join(simdata)) simdata_in %<>% dplyr::arrange(!!!rlang::syms(paste0("Var", 1:dd))) blocking <- simdata_in$block %>% factor() %>% as.integer() indexing <- (1:nrow(simdata_in)-1) %>% split(blocking) indexing_grid <- indexing indexing_obs <- indexing_grid if(1){ matern_nu <- FALSE if(is.null(starting$nu)){ start_nu <- 0.5 matern_fix_twonu <- 1 } else { start_nu <- starting$nu if(start_nu %in% c(0.5, 1.5, 2.5)){ matern_fix_twonu <- 2 * start_nu } } if(is.null(prior$beta)){ beta_Vi <- diag(ncol(z)) * 1/100 } else { beta_Vi <- prior$beta } if(is.null(prior$tausq)){ tausq_ab <- c(2, 1) } else { tausq_ab <- prior$tausq if(length(tausq_ab) == 1){ tausq_ab <- c(tausq_ab[1], 0) } } if(is.null(prior$sigmasq)){ sigmasq_ab <- c(2, 1) } else { sigmasq_ab <- prior$sigmasq } if(is.null(starting$beta)){ start_beta <- matrix(0, nrow=ncol(z), ncol=q) } else { start_beta <- starting$beta } theta_names <- c("sigmasq", paste0("phi_", 1:p)) npar <- (p+1) set_unif_bounds <- matrix(0, nrow=npar*k, ncol=2) btmlim <- prior$btmlim %>% set_default(1e-3) toplim <- prior$toplim %>% set_default(1e3) set_unif_bounds[,1] <- btmlim set_unif_bounds[,2] <- toplim start_theta <- matrix(1, ncol=k, nrow=npar) if(!is.null(prior$set_unif_bounds)){ set_unif_bounds <- prior$set_unif_bounds } if(!is.null(starting$theta)){ start_theta <- starting$theta } if(is.null(starting$mcmcsd)){ mcmc_mh_sd <- diag(k * npar) * 0.01 } else { if(length(starting$mcmcsd) == 1){ mcmc_mh_sd <- diag(k * npar) * starting$mcmcsd } else { mcmc_mh_sd <- starting$mcmcsd } } if(is.null(starting$tausq)){ start_tausq <- family %>% sapply(function(ff) if(ff == "gaussian"){.1} else {1}) } else { start_tausq <- starting$tausq } if(is.null(starting$lambda)){ start_lambda <- matrix(0, nrow=q, ncol=k) diag(start_lambda) <- 2 } else { start_lambda <- starting$lambda } if(is.null(starting$lambda_mask)){ lambda_mask <- matrix(0, nrow=q, ncol=k) lambda_mask[lower.tri(lambda_mask)] <- 1 diag(lambda_mask) <- 1 } else { lambda_mask <- starting$lambda_mask } if(is.null(starting$mcmc_startfrom)){ mcmc_startfrom <- 0 } else { mcmc_startfrom <- starting$mcmc_startfrom } if(is.null(starting$w)){ start_v <- matrix(0, nrow = nrow(simdata_in), ncol = k) } else { start_v <- starting$v } } sort_ix <- simdata_in$ix y <- simdata_in %>% dplyr::select(dplyr::contains("Y_")) %>% as.matrix() colnames(y) <- orig_y_colnames x <- simdata_in %>% dplyr::select(dplyr::contains("X_")) %>% as.matrix() colnames(x) <- orig_X_colnames x[is.na(x)] <- 0 z <- simdata_in %>% dplyr::select(dplyr::contains("Z_")) %>% as.matrix() colnames(z) <- orig_Z_colnames if(any(is.na(z))){ stop("Cannot have NA in Z matrix") } na_which <- simdata_in$na_which coords <- simdata_in %>% dplyr::select(dplyr::contains("Var")) %>% as.matrix() coordsdata <- simdata_in %>% dplyr::select(1:dd) mcmc_run <- meshed_mcmc comp_time <- system.time({ results <- mcmc_run(y, family_id, z, x, k, parents, children, block_names, block_groups, indexing_grid, indexing_obs, set_unif_bounds, beta_Vi, sigmasq_ab, tausq_ab, matern_fix_twonu, start_v, start_lambda, lambda_mask, start_theta, start_beta, start_tausq, mcmc_mh_sd, mcmc_keep, mcmc_burn, mcmc_thin, mcmc_startfrom, n_threads, which_hmc, mcmc_adaptive, use_cache, use_forced_grid, use_ps, mcmc_verbose, mcmc_debug, mcmc_print_every, low_mem, sample_beta, sample_tausq, sample_lambda, sample_theta, sample_w) }) if(saving){ listN <- function(...){ anonList <- list(...) names(anonList) <- as.character(substitute(list(...)))[-1] anonList } saved <- listN(y, x, z, coords, k, parents, children, block_names, block_groups, indexing_grid, indexing_obs, set_unif_bounds, beta_Vi, tausq_ab, start_v, start_lambda, lambda_mask, start_theta, start_beta, start_tausq, mcmc_mh_sd, mcmc_keep, mcmc_burn, mcmc_thin, mcmc_startfrom, n_threads, mcmc_adaptive, use_forced_grid, mcmc_verbose, mcmc_debug, mcmc_print_every, sample_beta, sample_tausq, sample_lambda, sample_theta, sample_w) } else { saved <- "Model data not saved." } returning <- list(data = simdata_in, savedata = saved, block_names = block_names, block_groups = block_groups, parents = parents, children = children, coordsblocking = coords_blocking) %>% c(results) return(returning) }
tam_mml_3pl_calc_total_ll <- function( iIndex, A, B, xsi, theta, nnodes, guess, n.ik, eps, return_probs_na=FALSE, probs_na=NULL ) { AXsi <- tam_mml_compute_AXsi(A=A, xsi=xsi) maxK <- dim(A)[2] probs0 <- tam_mml_3pl_calc_prob( iIndex=iIndex, A=A, AXsi=AXsi, B=B, xsi=xsi, theta=theta, nnodes=nnodes, maxK=maxK, guess=guess )$rprobs if (is.null(probs_na)){ probs_na <- is.na(probs0) } if (sum(probs_na)>0){ probs0[ probs_na ] <- 0 } n.ik <- n.ik[ iIndex,,, drop=FALSE ] ll0 <- tam_mml_3pl_calc_ll( n.ik=n.ik, probs=probs0, eps=eps ) if (return_probs_na){ res <- list(ll0=ll0, probs_na=probs_na) } else { res <- ll0 } return(res) }
FindReplace = function(file, find, replace) { if (file.exists(file)) { cat("\n", file = file, append = TRUE) OldText <- readLines(con = file) NoLines = length(OldText) if (NoLines > 2) { if (all(OldText[c(NoLines - 1, NoLines)] == "\n")) { NoLines = NoLines - 1 } } writeLines(gsub(find, replace, OldText, fixed=TRUE)[1:NoLines], con = file) } else { warning( "The specified file does not exist.\nNo action has been taken.\n") } return(invisible(NULL)) }
"odors"
output$tabsetpanel0UI<-renderUI({ tabsetPanel(id="tabsetpanel0" ,tabPanel("1. Load example" ,tags$head(tags$style( HTML(' wpanel .tab-content {margin-left:50px;}')) ) ,value="exampleTab" ,div(class = "wpanel", uiOutput("examplepanel") ) ) ) }) output$tabsetpanel1UI<-renderUI({ tabsetPanel(id="tabsetpanel1" ,tabPanel("1. Chr. data data.frame", value="dfChrTab", uiOutput("dfchrpanel") ) ,tabPanel("2. Marks' pos. d.f.", value="dfMarkTab", uiOutput("dfmarkpanel") ) ,tabPanel("3. Marks' style d.f.", value="dfMSTab", uiOutput("dfMStylepanel") ) ,tabPanel("4. Notes' data.frames", value="notesTab", uiOutput("dfnotespanel") ) ) }) output$tabsetpanel5UI<-renderUI({ tabsetPanel(id="tabsetpanel5" ,tabPanel("Indices", value="indicesTab", uiOutput("indicespanel") ) ,tabPanel("Marks", value="marksTab", uiOutput("markspanel") ) ) }) output$tabsetpanel2UI<-renderUI({ tabsetPanel(id="tabsetpanel2", tabPanel("1. Parameters & Plot", value="paramTab" ,uiOutput("parameterPanel") ) ,tabPanel("2. Log", value="logTab", uiOutput("logpanel") ) ,tabPanel("3. code", value="codeTab", uiOutput("strpanel") ) ) }) output$tabsetpanel4UI<-renderUI({ tabsetPanel(id="tabsetpanel4", tabPanel("1. Search", value="searchTab", uiOutput("searchPanel") ) ) })
mfdb_unaggregated <- function (omitNA = FALSE, like = c(), not_like = c()) { group <- structure(list(omitNA = omitNA, like = like, not_like = not_like), class = c("mfdb_unaggregated", "mfdb_aggregate")) group } select_clause.mfdb_unaggregated <- select_clause.numeric gen_likes <- function(col, conditions, operator) { if (length(conditions) == 0) return(c()) lookup <- if (!is.null(attr(col, 'lookup'))) attr(col, 'lookup') else gsub('(.*\\.)|_id', '', col) if (lookup %in% mfdb_taxonomy_tables) { return(paste0( "(", col, " IN ", "(SELECT ", lookup, "_id FROM ", lookup, " WHERE ", paste0("name ", operator, sql_vquote(conditions), collapse = " OR "), "))")) } return(paste0("(", paste0(col, operator, sql_vquote(conditions), collapse = " OR "), ")")) } where_clause.mfdb_unaggregated <- function(mdb, x, col, outputname, group_disabled = FALSE) { lookup <- gsub('(.*\\.)|_id', '', col) c( if (x$omitNA) paste0(col, " IS NOT NULL") else c(), gen_likes(col, x$like, " LIKE "), gen_likes(col, x$not_like, " NOT LIKE "), NULL ) } agg_summary.mfdb_unaggregated <- function(mdb, x, col, outputname, data, sample_num) { if (is.null(data[[outputname]])) { if (identical(names(data), c('bssample')) || nrow(data) == 0) { return(list()) } stop("Column ", outputname, " missing from data") } vals <- unique(data[[outputname]]) as.list(structure(vals, names = vals)) }
split_chain <- function(expr, env) { rhss <- list() pipes <- list() i <- 1L while(is.call(expr) && is_pipe(get(deparse(expr[[1L]])))) { pipes[[i]] <- expr[[1L]] rhs <- expr[[3L]] if (is_parenthesized(rhs)) rhs <- eval(rhs, env, env) rhss[[i]] <- if (is_function(rhs) || is_colexpr(rhs)) prepare_function(rhs) else if (is_first(rhs)) prepare_first(rhs) else rhs if (is.call(rhss[[i]]) && identical(rhss[[i]][[1L]], quote(`function`))) stop("Anonymous functions must be parenthesized", call. = FALSE) expr <- expr[[2L]] i <- i + 1L } list(rhss = rev(rhss), pipes = rev(pipes), lhs = expr) }
dropEdge.gModel <- function(object,name.1,name.2) { form <- formula(object) listform <- readf(form[2]) new.form <- .delete.edge(listform,c(name.1,name.2)) form <- paste("~",showf(new.form)) formula(object) <- as.formula(form) if (inherits(object,"gRfit")) object <- fit(object) return(object) } addEdge.gModel <- function(object,name.1,name.2) { new.object <- object form <- formula(object) listform <- readf(form[2]) new.form <- .add.edge(listform,c(name.1,name.2)) form <- paste("~",showf(new.form)) formula(new.object) <- as.formula(form) if (inherits(new.object,"gRfit")) new.object <- fit(new.object) return(new.object) } ggm <- function(formula=~.^1, gmData, marginal){ value <- processFormula(formula,gmData, marginal,"Continuous") value$gmData <- gmData class(value) <- c("ggm","gModel") return(value) } fit.ggm <- function(object, ...){ Ydf <- observations(object$gmData) nobs <- nrow(Ydf) gc <- object$numformula Ymat <- as.matrix(Ydf) Smat <- cov(Ymat)*(nobs-1)/nobs ipsFit <- ips(gc,Smat) fit <- outfun( ipsFit$MLE, Smat,nrow(Ydf)) fit$n <- nobs fit$mean <- apply(Ymat,2,mean) fit$df <- length(which(fit$part==0))/2 fit$iterations <- ipsFit$iterations value<-object value$fit <- fit class(value) <- c("gRfit", "ggm",class(object)) return(value) } partial.corr.matrix <- function(S){ A <- solve(S) temp <- diag(1/sqrt(diag(A))) temp <- zapsmall(-temp%*%A%*%temp) diag(temp) <- 1 return(temp) } outfun <- function(Sigma, S, n){ .ell <- function(Sigma, S, n){ shdet <- function(Sigma){ prod(eigen(Sigma)[[1]]) } p <- dim(S)[1] const <- -n * p/2 * log(2 * pi) const - n/2 * log(shdet(Sigma)) - n/2 * sum(diag( solve(Sigma) %*% S )) } return(list(Sigma=round(Sigma,3), eigenvalues=eigen(Sigma)[[1]], correlation=cov2cor(Sigma), partial.correlations=partial.corr.matrix(Sigma), loglik=.ell(Sigma,S,n))) } ips <- function(cliques, S){ if(!is.matrix(S)){ return("Second argument is not a matrix!") } if(dim(S)[1]!=dim(S)[2]){ return("Second argument is not a square matrix!") } if(min(eigen(S)[[1]])<=0){ return("Second argument is not a positive definite matrix!") } start <- diag(diag(S)) p <- dim(S)[1] K <- solve(start) i <- 0 if(length(cliques)==1){ return(list(MLE=S, iterations=1)) } my.complement <- function(C) return(setdiff(1:p,C)) cliques.complements <- lapply(cliques, my.complement) repeat{ K.old <- K i <- i+1 for(j in 1:length(cliques)){ C <- cliques[[j]] notC <- cliques.complements[[j]] K[C,C] <- solve( S[C,C] ) + K[C,notC]%*%solve(K[notC,notC])%*%K[notC,C] } if(sum(abs(K.old-K)) < 1e-10) break } return(list(MLE=solve(K), iterations=i)) } globalVariables(c("rawdata", "loglm.formula")) valueLabels <- function(x) UseMethod("valueLabels") valueLabels.default <- function(x) attr(x,"dimnames") valueLabels.gmData <- function(x) attr(x,"valueLabels") varNames <- function(x)UseMethod("varNames") varNames.default <- function(x) names(attr(x,"dimnames")) varNames.gmData <- function(x)as.vector(x$varNames) nLevels <- function(x)UseMethod("nLevels") nLevels.default <- function(x) dim(x) nLevels.gmData <- function(x)structure(as.vector(x$nLevels), .Names=varNames(x)) "latent.gmData" <- function(x){attr(x,"latent")} "latent" <- function(x) UseMethod("latent") "latent<-.gmData" <- function(tmp,value){attr(tmp,"latent")<-value; return(tmp)} "latent<-" <- function(tmp,value) UseMethod("latent<-") "valueLabels<-.gmData"<- function(tmp,value){attr(tmp,"valueLabels")<-value; return(tmp)} "valueLabels<-" <- function(tmp,value) UseMethod("valueLabels<-") observations <- function(x) UseMethod("observations") obs <- function(x) UseMethod("observations") observations.gmData <- function(x) attr(x,"observations") "observations<-.gmData"<- function(tmp,value){attr(tmp,"observations")<-value; return(tmp)} "observations<-" <- function(tmp,value)UseMethod("observations<-") "description<-.gmData" <- function(tmp,value){attr(tmp,"description")<-value; return(tmp)} "description<-" <- function(tmp,value) UseMethod("description<-") "varTypes.gmData" <- function(x){structure(x$varTypes, .Names=varNames(x))} "varTypes" <- function(x) UseMethod("varTypes") "varTypes<-.gmData" <- function(tmp,value){ tmp$varTypes <-value; return(tmp)} "varTypes<-" <- function(tmp,value) UseMethod("varTypes<-") "varNames<-.gmData" <- function(tmp,value){ tmp$varNames <-value; return(tmp)} "varNames<-" <- function(tmp,value) UseMethod("varNames<-") "nLevels<-.gmData" <- function(tmp,value){ tmp$nLevels <-value; return(tmp)} "nLevels<-" <- function(tmp,value) UseMethod("nLevels<-") shortNames.gmData <- function(x)structure(as.vector(x$shortNames), .Names=varNames(x)) shortNames <- function(x)UseMethod("shortNames") "shortNames<-.gmData" <- function(tmp,value){ tmp$shortNames <-value; return(tmp)} "shortNames<-" <- function(tmp,value) UseMethod("shortNames<-") dataOrigin.gmData <- function(x) attr(x,"dataOrigin")[1] dataOrigin <- function(x)UseMethod("dataOrigin") "ordinal" <- function(tmp) UseMethod("ordinal") "ordinal<-" <- function(tmp,value) UseMethod("ordinal<-") "ordinal.gmData" <- function(tmp)attr(tmp,"ordinal") "ordinal<-.gmData" <- function(tmp,value){ varTypes(tmp)[match(value, varNames(tmp))]<-"Ordinal" return(tmp)} "nominal" <- function(tmp) UseMethod("nominal") "nominal<-" <- function(tmp,value) UseMethod("nominal<-") "nominal.gmData" <- function(tmp){ varNames(tmp)["Discrete"==varTypes(tmp)] } "nominal<-.gmData" <- function(tmp,value){ varTypes(tmp)[match(value, varNames(tmp))]<-"Discrete" return(tmp)} as.gmData <- function(from) UseMethod("as.gmData") print.gmData <- function(x, ...){ xx<-attr(x,"description") if (!is.null(xx)) cat("Description:", xx, "\n") print.data.frame(x); if (!is.null(latent(x))) cat ("Latent variables:", paste(latent(x),collapse=' '), "\n") if (!is.null(valueLabels(x))) cat("To see the values of the factors use the 'valueLabels' function\n") if (!is.null(observations(x))) cat("To see the data use the 'observations' function\n") return(invisible(x)) } summary.gmData <- function(object, ...){ print(object) mapply(function(xx,ll){ cat("Factor:", ll, "\n Levels:", paste(xx,sep=' '),"\n") }, valueLabels(object),names(valueLabels(object))) return(invisible(object)) } newgmData <- function (varNames, varTypes = rep(validVarTypes()[1], length(varNames)), nLevels = NULL, latent = NULL, valueLabels = NULL, observations = NULL, description = NULL, shortNames = NULL) { cl <- match.call() .is.subset <- function(x,y){ setequal(intersect(x,y),x) } .simpleCap <- function(x) { s <- strsplit(x, " ")[[1]] paste(toupper(substring(s, 1,1)), substring(s, 2), sep="", collapse=" ") } if (is.null(shortNames)){ nam <- varNames nama <- abbreviate(nam,1) nc <- nchar(nama) rest <- setdiff(c(letters,LETTERS), nama[nc==1]) if (length(which(nc>1)) <= length(rest)) nama[nc>1]<- rest[1:length(which(nc>1))] } else { nama <- shortNames } value <- data.frame(varNames, nama, row.names = NULL) names(value) <- c("varNames", "shortNames") varTypes <- sapply(varTypes, .simpleCap) varTypes <- sapply(varTypes, match.arg, choices=validVarTypes(), several.ok = FALSE) value$varTypes <- factor(varTypes, levels = validVarTypes()) discidx <- which("Discrete"==varTypes | "Ordinal"==varTypes) aa <- rep(NA, length(varNames)) if (!is.null(valueLabels) & !is.list(valueLabels)) valueLabels <- list(valueLabels) if (is.null(nLevels) & is.null(valueLabels)){ aa[discidx] <- 2 nLevels <- aa } if (!is.null(valueLabels)){ if (!.is.subset(varNames[discidx], names(valueLabels))){ vl <- rep(valueLabels, length(discidx)) valueLabels <- vl[1:length(discidx)] names(valueLabels) <- varNames[discidx] } uu <- valueLabels[varNames[discidx]] uu <- sapply(uu,length) aa[discidx] <- uu value$nLevels <- unlist(aa) } else { v <- nLevels[discidx] v <- v[!is.na(v)] if (length(v)==0) v <- 2 v <- rep(v, length(discidx)) v <- v[discidx] aa[discidx] <- v value$nLevels <- unlist(aa) uu <- varNames[discidx] valueLabels <- mapply(function(nn,vv){paste(nn,1:vv,sep='')},uu,v, SIMPLIFY=FALSE) } class(value) <- c("gmData", "data.frame") attr(value, "valueLabels") <- valueLabels attr(value, "latent") <- latent attr(value, "description") <- description attr(value, "observations") <- observations attr(value, "dataOrigin") <- class(observations) obsclass <- class(observations) if (is.null(obsclass)){ attr(value, "dataOrigin") <- NULL } else { if(is.element("table", obsclass)) attr(value, "dataOrigin") <- c("table",setdiff(obsclass, "table")) else{ if(is.element("data.frame", obsclass)) attr(value, "dataOrigin") <- c("data.frame", setdiff(obsclass, "data.frame")) else attr(value, "dataOrigin") <- "other" } } return(value) } validVarTypes <- function() {c("Discrete","Ordinal","Continuous")} as.gmData.data.frame <- function(from){ fact <- unlist(lapply(1:ncol(from), function(j) is.factor(from[,j]))) Types <- rep(validVarTypes()[3],length(fact)) Types[fact] <- validVarTypes()[1] levels <- unlist(lapply(1:ncol(from), function(j) { if(is.factor(from[,j])) length(levels(from[,j])) else NA} ) ) if (length(which(fact))>0){ vallabels <- list() for (j in which(fact)){ vallabels <- c(vallabels, list(levels(from[,j]))) } names(vallabels) <- names(from[which(fact)]) } else { vallabels <- list() } newgmData( varNames=names(from), varTypes=Types, nLevels=levels, valueLabels=vallabels, observations=from ) } as.gmData.table <- function(from){ counts <- as.vector(from) dn <- dimnames(from) name <- names(lapply(dn,function(x)names(x))) dim <- unlist(lapply(dn,length)) newgmData( varNames=name, varTypes=rep("Discrete",length(name)), nLevels=dim, valueLabels=dn, observations=from ) } as.gmData.array <- function(from){ res <- as.gmData(as.table(from)) observations(res) <- from res } gModel <- function(formula, gmData){ value <- list(formula=formula, gmData=gmData) class(value) <- "gModel" return(value) } "formula<-.gModel" <- function(tmp,value){tmp$formula<-value; return(tmp)} "formula<-" <- function(tmp,value) UseMethod("formula<-") "gmData.gModel" <- function(x){x$gmData} "gmData" <- function(x) UseMethod("gmData") "gmData<-.gModel" <- function(tmp,value){tmp$gmData<-value; return(tmp)} "gmData<-" <- function(tmp,value) UseMethod("gmData<-") print.gModel <- function(x, ...){ cat("Model information (gRbase)\n") cat(" Class: ", paste(class(x),collapse=' <- '),"\n") cat(" Formula: ", paste(paste(x$formula),collapse=''), "\n") } "getFit.gRfit" <- function(x){x$fit} "getFit" <- function(x) UseMethod("getFit") "getFit<-.gRfit" <- function(tmp,value){ tmp$fit <-value; return(tmp)} "getFit<-" <- function(tmp,value) UseMethod("getFit<-") print.gRfit <- function(x, ...){ print.gModel(x) cat("Fit information (gRbase)\n") cat(" logL", deviance(getFit(x)), "df", x$fit$df,"\n") } summary.gRfit <- function(object,...) summary(getFit(object)) hllm <- function(formula = ~.^1, gmData, marginal){ stop("function 'hllm' from gRbase is defunct. Please use the gRim package for hierarchical log-linear models.") } fit.hllm <- function(object,engine="loglm",...){ stop("function 'fit.hllm' from gRbase is defunct. Please use the gRim package for hierarchical log-linear models.") } stepwise.hllm <- function (object, ...) { stop("function 'stepwise.hllm' from gRbase is defunct. Please use the gRim package for hierarchical log-linear models.") } update.gModel <- function(object, addedge=NULL, dropedge=NULL, ...){ if (!is.null(addedge)) object <- addEdge.gModel(object, addedge[1], addedge[2]) if (!is.null(dropedge)) object <- dropEdge.gModel(object, dropedge[1], dropedge[2]) return(object) }
context("test-unique") test_that("uniqueness along `axis = 1` is equal to vctrs for 1D / 2D", { x <- new_array(c(1, 1, 2, 2, 3)) expect_equal(rray_unique(x, axis = 1), vec_unique(x)) expect_equal(rray_unique_loc(x, axis = 1), vec_unique_loc(x)) expect_equal(rray_unique_count(x, axis = 1), vec_unique_count(x)) x <- rray(c(1, 1, 2, 2), c(2, 2)) expect_equal(rray_unique(x, axis = 1), vec_unique(x)) expect_equal(rray_unique_loc(x, axis = 1), vec_unique_loc(x)) expect_equal(rray_unique_count(x, axis = 1), vec_unique_count(x)) }) test_that("can compute uniqueness along columns", { x <- rray(c(1, 1, 2, 2), c(1, 4)) expect_equal( rray_unique(x, axis = 2L), rray(c(1, 2), c(1, 2)) ) expect_equal( rray_unique_loc(x, 2), c(1, 3) ) expect_equal( rray_unique_loc(x, 1), 1 ) expect_equal( rray_unique_count(x, 2), 2 ) }) test_that("names are retained", { x <- rray(c(1, 1, 2, 2), c(1, 4)) x <- rray_set_row_names(x, c("r1")) x <- rray_set_col_names(x, c("c1", "c2", "c3", "c4")) expect_equal( rray_unique(x, axis = 2L), x[, c(1, 3)] ) xx <- rray_expand(x, 2) expect_equal( rray_unique(xx, 3L), xx[, , c(1, 3)] ) expect_equal( rray_unique_loc(xx, axis = 3L), c(1, 3) ) expect_equal( rray_unique_count(xx, axis = 3L), 2 ) }) test_that("`axis` is validated", { axis <- c(1, 2) expect_error(rray_unique(1, axis), "Invalid `axis`") expect_error(rray_unique_loc(1, axis), "Invalid `axis`") expect_error(rray_unique_count(1, axis), "Invalid `axis`") axis <- -1 expect_error(rray_unique(1, axis), "Invalid `axis`") expect_error(rray_unique_loc(1, axis), "Invalid `axis`") expect_error(rray_unique_count(1, axis), "Invalid `axis`") axis <- 2 expect_error(rray_unique(1, axis), "Invalid `axis`") expect_error(rray_unique_loc(1, axis), "Invalid `axis`") expect_error(rray_unique_count(1, axis), "Invalid `axis`") }) test_that("rray_unique() is correctly defined over higher dimensions", { x_dup_rows <- rray(c(1, 1, 3, 3, 2, 2, 4, 4), c(2, 2, 2)) x_dup_rows <- rray_set_row_names(x_dup_rows, c("r1", "r2")) x_dup_rows <- rray_set_col_names(x_dup_rows, c("c1", "c2")) expect_equal(rray_unique(x_dup_rows, 1), x_dup_rows[1,]) expect_equal(rray_unique(x_dup_rows, 2), x_dup_rows) x_dup_cols <- rray_transpose(x_dup_rows, c(2, 1, 3)) expect_equal(rray_unique(x_dup_cols, 1), x_dup_cols) expect_equal(rray_unique(x_dup_cols, 2), x_dup_cols[,1]) x_dup_layers <- rray_transpose(x_dup_rows, c(2, 3, 1)) expect_equal(rray_unique(x_dup_layers, 1), x_dup_layers) expect_equal(rray_unique(x_dup_layers, 3), x_dup_layers[,,1]) }) test_that("rray_unique_loc() is correctly defined over higher dimensions", { x_dup_rows <- rray(c(1, 1, 3, 3, 2, 2, 4, 4), c(2, 2, 2)) expect_identical(rray_unique_loc(x_dup_rows, 1), 1L) expect_identical(rray_unique_loc(x_dup_rows, 2), 1:2) x_dup_cols <- rray_transpose(x_dup_rows, c(2, 1, 3)) expect_identical(rray_unique_loc(x_dup_cols, 1), 1:2) expect_identical(rray_unique_loc(x_dup_cols, 2), 1L) x_dup_layers <- rray_transpose(x_dup_rows, c(2, 3, 1)) expect_identical(rray_unique_loc(x_dup_layers, 1), 1:2) expect_identical(rray_unique_loc(x_dup_layers, 3), 1L) }) test_that("rray_unique_count() is correctly defined over higher dimensions", { x_dup_rows <- rray(c(1, 1, 3, 3, 2, 2, 4, 4), c(2, 2, 2)) expect_identical(rray_unique_count(x_dup_rows, 1), 1L) expect_identical(rray_unique_count(x_dup_rows, 2), 2L) x_dup_cols <- rray_transpose(x_dup_rows, c(2, 1, 3)) expect_identical(rray_unique_count(x_dup_cols, 1), 2L) expect_identical(rray_unique_count(x_dup_cols, 2), 1L) x_dup_layers <- rray_transpose(x_dup_rows, c(2, 3, 1)) expect_identical(rray_unique_count(x_dup_layers, 1), 2L) expect_identical(rray_unique_count(x_dup_layers, 3), 1L) }) context("test-base-unique") test_that("results are the same as base R", { x <- rray(c(1, 2, 1, 2, 3, 5)) x_base <- vec_data(x) expect_equal(unique(x), as_rray(unique(x_base))) }) test_that("matrix/array results are the same as base R", { x <- rray(c(1, 2, 1, 2, 3, 5), dim = c(2, 3)) x_base <- vec_data(x) expect_equal(unique(x), as_rray(unique(x_base))) expect_equal( unique(x, MARGIN = 2), as_rray(unique(x_base, MARGIN = 2)) ) }) test_that("cannot use multiple margin", { x <- rray(c(1, 2, 1, 2, 3, 5), dim = c(2, 3)) expect_error(unique(x, MARGIN = c(1, 2))) }) test_that("cannot use margin of 0", { x <- rray(c(1, 2, 1, 2, 3, 5), dim = c(2, 3)) expect_error(unique(x, MARGIN = 0)) }) test_that("incomparables is an error from base R", { expect_error(unique(rray(1), incomparables = TRUE)) }) test_that("dim names are kept with base R rules", { x <- rray(c(1, 2, 1, 2, 3, 5), dim = c(2, 3), dim_names = list(letters[1:2], letters[3:5])) x_base <- vec_data(x) expect_equal( rray_dim_names(unique(x)), rray_dim_names(unique(x_base)) ) expect_equal( rray_dim_names(unique(x, MARGIN = 2)), rray_dim_names(unique(x_base, MARGIN = 2)) ) }) test_that("fromLast works", { x <- rray(c(1, 2, 1, 2, 3, 5), dim = c(2, 3)) x_base <- vec_data(x) expect_equal( unique(x, MARGIN = 2, fromLast = TRUE), as_rray(unique(x_base, MARGIN = 2, fromLast = TRUE)) ) })
library(rainbow) par(mfrow = c(1, 2)) plot(fts(x = 15:49, y = Australiafertility$y, xname = "Age", yname = "Fertility rate")) plot(fts(x = 15:49, y = Australiasmoothfertility$y, xname = "Age", yname = "Smoothed fertility rate"))
skip_on_cran() test_that("lock bin: bin", { skip_on_os("windows") file_post(TXT, BIN_LOCK) expect_true(bin_lock(BIN_LOCK)) expect_false(file_delete(TXT, BIN_LOCK)) expect_error(file_post(TXT, BIN_LOCK)) }) test_that("lock bin: URL", { skip_on_os("windows") url <- file.path(base_url(), bin_name_random()) expect_false(bin_lock(url)) })
library(testthat) library(synthACS) context("synth - employment") test_that("get correct results", { ca <- synthACS:::synth_data_edu(synthACS:::synth_data_mar(synthACS:::synth_data_ag( unlist(ca_dat$estimates$age_by_sex[26,])), unlist(ca_dat$estimates$marital_status[26,])), unlist(ca_dat$estimates$edu[26,])) ca_ag1 <- synthACS:::synth_data_emp(synthACS:::synth_data_edu(synthACS:::synth_data_mar( synthACS:::synth_data_ag(unlist(ca_dat$estimates$age_by_sex[1,])), unlist(ca_dat$estimates$marital_status[1,])), unlist(ca_dat$estimates$edu[1,])), unlist(ca_dat$estimates$emp_status[1,])) ca_ag2 <- synthACS:::synth_data_emp(ca, unlist(ca_dat$estimates$emp_status[26,])) ca_ag3 <- synthACS:::synth_data_emp(synthACS:::synth_data_edu(synthACS:::synth_data_mar( synthACS:::synth_data_ag(unlist(ca_dat$estimates$age_by_sex[50,])), unlist(ca_dat$estimates$marital_status[50,])), unlist(ca_dat$estimates$edu[50,])), unlist(ca_dat$estimates$emp_status[50,])) expect_true(is.data.frame(ca_ag1[[1]])) expect_true(is.data.frame(ca_ag2[[1]])) expect_true(is.data.frame(ca_ag3[[1]])) expect_true(is.list(ca_ag1)) expect_equal(length(ca_ag2), 2) expect_equal(levels(ca_ag1[[1]]$age), ca_ag2[[2]]) expect_equal(ncol(ca_ag1[[1]]), ncol(ca_ag2[[1]])) expect_equal(ncol(ca_ag1[[1]]), ncol(ca_ag3[[1]])) expect_equal(names(ca_ag1[[1]]), names(ca_ag3[[1]])) expect_equal(names(ca_ag1[[1]]), c("age", "gender", "marital_status", "edu_attain", "emp_status", "p")) expect_equal(sum(ca_ag1[[1]]$p), 1) expect_equal(sum(ca_ag2[[1]]$p), 1) expect_equal(sum(ca_ag3[[1]]$p), 1) expect_equal(tapply(ca_ag2[[1]]$p, ca_ag2[[1]]$age, sum), tapply(ca[[1]]$p, ca[[1]]$age, sum)) expect_equal(tapply(ca_ag2[[1]]$p, ca_ag2[[1]]$gender, sum), tapply(ca[[1]]$p, ca[[1]]$gender, sum)) })
nldoc_network <- function(modelfiles) { nlogocode <- nldoc_read_nlogo(modelfiles) nw <- nldoc_find_procedure_calls(nlogocode) nw.ig <- igraph::graph_from_data_frame(nw) nw.ig <- igraph::simplify(nw.ig, remove.multiple = T, remove.loops = T) return(nw.ig) }
UnimixedContCont <- function(Dataset, Surr, True, Treat, Trial.ID, Pat.ID, Model=c("Full"), Weighted=TRUE, Min.Trial.Size=2, Alpha=.05, Number.Bootstraps=500, Seed=sample(1:1000, size=1), T0T1=seq(-1, 1, by=.2), T0S1=seq(-1, 1, by=.2), T1S0=seq(-1, 1, by=.2), S0S1=seq(-1, 1, by=.2), ...){ if ((Model==c("Full") | Model==c("Reduced") | Model==c("SemiReduced"))==FALSE) {stop ("The specification of the Model=c(\"...\") argument of the call is incorrect. Use either Model=c(\"Full\"), Model=c(\"Reduced\"), or Model=c(\"SemiReduced\").")} Surr <- Dataset[,paste(substitute(Surr))] True <- Dataset[,paste(substitute(True))] Treat <- Dataset[,paste(substitute(Treat))] Trial.ID <- Dataset[,paste(substitute(Trial.ID))] Pat.ID <- Dataset[,paste(substitute(Pat.ID))] Data.Proc <- .Data.Processing(Dataset=Dataset, Surr=Surr, True=True, Treat=Treat, Trial.ID=Trial.ID, Pat.ID=Pat.ID, Min.Trial.Size=Min.Trial.Size) wide <- Data.Proc$wide dataS <- Data.Proc$dataS dataT <- Data.Proc$dataT Data.analyze <- Data.Proc$Data.analyze N.total <- Data.Proc$N.total N.trial <- Data.Proc$N.trial Obs.per.trial <- Data.Proc$Obs.per.trial S1 <- dataS$outcome[dataS$Treat==1] S0 <- dataS$outcome[dataS$Treat!=1] T1 <- dataT$outcome[dataS$Treat==1] T0 <- dataT$outcome[dataS$Treat!=1] r_T0S0 <- cor(T0,S0) r_T1S1 <- cor(T1,S1) set.seed(123); ICA <- ICA.ContCont(T0S0 = r_T0S0, T1S1 = r_T1S1, T0T0 = var(T0), T1T1 = var(T1), S0S0 = var(S0), S1S1 = var(S1), T0T1=T0T1, T0S1=T0S1, T1S0=T1S0, S0S1=S0S1) Control=list(msMaxIter=500) if (Model==c("Full")|Model==c("SemiReduced")){ Model.S <- lmer(outcome ~ Treat+(1+Treat|Trial.ID), data=dataS, ...) Model.T <- lmer(outcome ~ Treat+(1+Treat|Trial.ID), data=dataT, ...) Intercept.S <- coef(Model.S)$Trial.ID[,1] Treatment.S <- coef(Model.S)$Trial.ID[,2] Intercept.T <- coef(Model.T)$Trial.ID[,1] Treatment.T <- coef(Model.T)$Trial.ID[,2] Results.Stage.1 <- data.frame(Obs.per.trial$Trial, Obs.per.trial$Obs.per.trial, Intercept.S, Intercept.T, Treatment.S, Treatment.T, stringsAsFactors = TRUE) colnames(Results.Stage.1) <- c(NULL, "Trial", "Obs.per.trial", "Intercept.S", "Intercept.T", "Treatment.S", "Treatment.T") rownames(Results.Stage.1) <- NULL D.equiv <- var(Results.Stage.1[,3:6]) Residuals.Model.S <- residuals(Model.S, type='response') Residuals.Model.T <- residuals(Model.T, type='response') Residuals.Stage.1 <- cbind(wide$Pat.ID, data.frame(Residuals.Model.S, Residuals.Model.T, stringsAsFactors = TRUE)) colnames(Residuals.Stage.1) <- c("Pat.ID", "Residuals.Model.S", "Residuals.Model.T") rownames(Residuals.Stage.1) <- NULL Fixed.effect.pars.S <- matrix(summary(Model.S)$coef[1:2], nrow=2) Fixed.effect.pars.T <- matrix(summary(Model.T)$coef[1:2], nrow=2) rownames(Fixed.effect.pars.S) <- c("Intercept.S" , "Treatment.S") rownames(Fixed.effect.pars.T) <- c("Intercept.T" , "Treatment.T") Fixed.Effect.Pars <- data.frame(rbind(Fixed.effect.pars.S, Fixed.effect.pars.T), stringsAsFactors = TRUE) colnames(Fixed.Effect.Pars) <- c(" ") Random.effect.pars.S <- data.frame(ranef(Model.S)$Trial.ID, stringsAsFactors = TRUE) Random.effect.pars.T <- data.frame(ranef(Model.T)$Trial.ID, stringsAsFactors = TRUE) colnames(Random.effect.pars.S) <- c("Intercept.S", "Treatment.S") colnames(Random.effect.pars.T) <- c("Intercept.S", "Treatment.S") Random.Effect.Pars <- cbind(Random.effect.pars.S, Random.effect.pars.T) } if (Model==c("Reduced")){ Model.S <- lmer(outcome ~ Treat+(-1+Treat|Trial.ID), data=dataS, ...) Model.T <- lmer(outcome ~ Treat+(-1+Treat|Trial.ID), data=dataT, ...) Treatment.S <- coef(Model.S)$Trial.ID[,2] names(Treatment.S)<-"Treatment.S" Treatment.T <- coef(Model.T)$Trial.ID[,2] names(Treatment.T)<-"Treatment.T" Results.Stage.1 <- data.frame(Obs.per.trial$Trial, Obs.per.trial$Obs.per.trial, Treatment.S, Treatment.T, stringsAsFactors = TRUE) colnames(Results.Stage.1) <- c(NULL, "Trial", "Obs.per.trial", "Treatment.S", "Treatment.T") rownames(Results.Stage.1) <- NULL D.equiv <- var(Results.Stage.1[,3:4]) Residuals.Model.S <- residuals(Model.S, type='response') Residuals.Model.T <- residuals(Model.T, type='response') Residuals.Stage.1 <- cbind(wide$Pat.ID, data.frame(Surr=Residuals.Model.S, True=Residuals.Model.T, stringsAsFactors = TRUE)) colnames(Residuals.Stage.1) <- c("Pat.ID", "Residuals.Model.S", "Residuals.Model.T") rownames(Residuals.Stage.1) <- NULL Fixed.effect.pars.S <- matrix(summary(Model.S)$coef[1:2], nrow=2) rownames(Fixed.effect.pars.S)[1:2]<-c("Intercept.S", "Treatment.S") Fixed.effect.pars.T <- matrix(summary(Model.T)$coef[1:2], nrow=2) rownames(Fixed.effect.pars.T)[1:2]<-c("Intercept.T", "Treatment.T") Fixed.Effect.Pars <- data.frame(rbind(Fixed.effect.pars.S, Fixed.effect.pars.T), stringsAsFactors = TRUE) colnames(Fixed.Effect.Pars) <- c(" ") Random.effect.pars.S <- data.frame(ranef(Model.S)$Trial.ID, stringsAsFactors = TRUE) colnames(Random.effect.pars.S) <- c("Treatment.S") Random.effect.pars.T <- data.frame(ranef(Model.T)$Trial.ID, stringsAsFactors = TRUE) colnames(Random.effect.pars.T) <- c("Treatment.T") Random.Effect.Pars <- cbind(Random.effect.pars.S, Random.effect.pars.T) } if (Model==c("Full")){ if (Weighted==FALSE) {Results.Stage.2 <- lm(Results.Stage.1$Treatment.T ~ Results.Stage.1$Intercept.S + Results.Stage.1$Treatment.S)} if (Weighted==TRUE) {Results.Stage.2 <- lm(Results.Stage.1$Treatment.T ~ Results.Stage.1$Intercept.S + Results.Stage.1$Treatment.S, weights=Results.Stage.1$Obs.per.trial)} } if (Model==c("Reduced") | Model==c("SemiReduced")){ if (Weighted==FALSE) {Results.Stage.2 <- lm(Results.Stage.1$Treatment.T ~ Results.Stage.1$Treatment.S)} if (Weighted==TRUE) {Results.Stage.2 <- lm(Results.Stage.1$Treatment.T ~ Results.Stage.1$Treatment.S, weights=Results.Stage.1$Obs.per.trial)} } Trial.R2.value <- as.numeric(summary(Results.Stage.2)[c("r.squared")]) Trial.R2.sd <- sqrt((4*Trial.R2.value*(1-Trial.R2.value)^2)/(N.trial-3)) Trial.R2.lb <- max(0, Trial.R2.value + qnorm(Alpha/2) *(Trial.R2.sd)) Trial.R2.ub <- min(1, Trial.R2.value + qnorm(1-Alpha/2)*(Trial.R2.sd)) Trial.R2 <- data.frame(cbind(Trial.R2.value, Trial.R2.sd, Trial.R2.lb, Trial.R2.ub), stringsAsFactors = TRUE) colnames(Trial.R2) <- c("R2 Trial", "Standard Error", "CI lower limit", "CI upper limit") rownames(Trial.R2) <- c(" ") Trial.R.value <- sqrt(as.numeric(summary(Results.Stage.2)[c("r.squared")])) Z <- .5*log((1+Trial.R.value)/(1-Trial.R.value)) Trial.R.lb <- max(0, (exp(2*(Z-(qnorm(1-Alpha/2)*sqrt(1/(N.trial-3)))))-1)/(exp(2*(Z-(qnorm(1-Alpha/2)*sqrt(1/(N.trial-3)))))+1)) Trial.R.ub <- min(1, (exp(2*(Z+(qnorm(1-Alpha/2)*sqrt(1/(N.trial-3)))))-1)/(exp(2*(Z+(qnorm(1-Alpha/2)*sqrt(1/(N.trial-3)))))+1)) Trial.R.sd <- sqrt((1-Trial.R.value**2)/(N.trial-2)) Trial.R <- data.frame(cbind(Trial.R.value, Trial.R.sd, Trial.R.lb, Trial.R.ub), stringsAsFactors = TRUE) colnames(Trial.R) <- c("R Trial", "Standard Error", "CI lower limit", "CI upper limit") rownames(Trial.R) <- c(" ") options(warn = -1) Boot.r <- rep(0, Number.Bootstraps) for (j in 1:Number.Bootstraps){ obs <- c(1:N.total) set.seed(Seed) Indicator <- sample(obs, N.total, replace=TRUE) Seed <- Seed + 1 Sample.boot.S <- data.frame(dataS[Indicator,], stringsAsFactors = TRUE) Sample.boot.T <- data.frame(dataT[Indicator,], stringsAsFactors = TRUE) if (Model==c("Full") | Model==c("SemiReduced")){ Boot.model.S <- try(lmer(outcome ~ Treat+(1+Treat|Trial.ID), data=Sample.boot.S, ...), silent = FALSE) Boot.model.T <- try(lmer(outcome ~ Treat+(1+Treat|Trial.ID), data=Sample.boot.T, ...), silent = FALSE) } if (Model==c("Reduced")){ Boot.model.S <- try(lmer(outcome ~ Treat+(-1+Treat|Trial.ID), data=Sample.boot.S, ...), silent = FALSE) Boot.model.T <- try(lmer(outcome ~ Treat+(-1+Treat|Trial.ID), data=Sample.boot.T, ...), silent = FALSE) } Res.Boot.model.S <- residuals(Boot.model.S, type='response') Res.Boot.model.T <- residuals(Boot.model.T, type='response') Boot.r[j] <- (cor(Res.Boot.model.S,Res.Boot.model.T)) } Boot.r2 <- Boot.r**2 options(warn=0) R2ind <- (cor(Residuals.Model.T, Residuals.Model.S))**2 Var.Boot.r2 <- var(Boot.r2) Indiv.R2.lb <- max(0, R2ind + qnorm(Alpha/2)*sqrt(Var.Boot.r2)) Indiv.R2.ub <- R2ind - qnorm(Alpha/2)*sqrt(Var.Boot.r2) Indiv.R2 <- data.frame(cbind(R2ind, sqrt(Var.Boot.r2), Indiv.R2.lb, Indiv.R2.ub), stringsAsFactors = TRUE) colnames(Indiv.R2) <- c("R2 Indiv", "Standard Error", "CI lower limit", "CI upper limit") rownames(Indiv.R2) <- c(" ") Rind <- (cor(Residuals.Model.T, Residuals.Model.S)) Var.Boot.r <- var(Boot.r) Indiv.R.lb <- max(0, Rind + qnorm(Alpha/2)*sqrt(Var.Boot.r)) Indiv.R.ub <- min(1, Rind - qnorm(Alpha/2)*sqrt(Var.Boot.r)) Indiv.R <- data.frame(cbind(Rind, sqrt(Var.Boot.r), Indiv.R.lb, Indiv.R.ub), stringsAsFactors = TRUE) colnames(Indiv.R) <- c("R Indiv", "Standard Error", "CI lower limit", "CI upper limit") rownames(Indiv.R) <- c(" ") NoTreat <- wide[wide$Treat!=1,] Treat <- wide[wide$Treat==1,] T0S0 <- cor(NoTreat$Surr, NoTreat$True) T1S1 <- cor(Treat$Surr, Treat$True) Z_T0S0 <- .5*log((1+T0S0)/(1-T0S0)) rho_lb <- max(0, (exp(2*(Z_T0S0-(qnorm(1-Alpha/2)*sqrt(1/(N.total-3)))))-1)/(exp(2*(Z_T0S0-(qnorm(1-Alpha/2)*sqrt(1/(N.total-3)))))+1)) rho_ub <- min(1, (exp(2*(Z_T0S0+(qnorm(1-Alpha/2)*sqrt(1/(N.total-3)))))-1)/(exp(2*(Z_T0S0+(qnorm(1-Alpha/2)*sqrt(1/(N.total-3)))))+1)) rho_sd <- sqrt((1-T0S0**2)/(N.total-2)) rho_results_T0S0 <- data.frame(cbind(T0S0, rho_sd , rho_lb, rho_ub), stringsAsFactors = TRUE) colnames(rho_results_T0S0) <- c("Estimate", "Standard Error", "CI lower limit", "CI upper limit") rownames(rho_results_T0S0) <- c(" ") Z_T1S1 <- .5*log((1+T1S1)/(1-T1S1)) rho_lb <- max(0, (exp(2*(Z_T1S1-(qnorm(1-Alpha/2)*sqrt(1/(N.total-3)))))-1)/(exp(2*(Z_T1S1-(qnorm(1-Alpha/2)*sqrt(1/(N.total-3)))))+1)) rho_ub <- min(1, (exp(2*(Z_T1S1+(qnorm(1-Alpha/2)*sqrt(1/(N.total-3)))))-1)/(exp(2*(Z_T1S1+(qnorm(1-Alpha/2)*sqrt(1/(N.total-3)))))+1)) rho_sd <- sqrt((1-T1S1**2)/(N.total-2)) rho_results_T1S1 <- data.frame(cbind(T1S1, rho_sd , rho_lb, rho_ub), stringsAsFactors = TRUE) colnames(rho_results_T1S1) <- c("Estimate", "Standard Error", "CI lower limit", "CI upper limit") rownames(rho_results_T1S1) <- c(" ") Cor.Endpoints <- data.frame(rbind(rho_results_T0S0, rho_results_T1S1), stringsAsFactors = TRUE) rownames(Cor.Endpoints) <- c("r_T0S0", "r_T1S1") colnames(Cor.Endpoints) <- c("Estimate", "Standard Error", "CI lower limit", "CI upper limit") T0T0 = var(T0); T1T1 = var(T1); S0S0 = var(S0); S1S1 = var(S1) fit <- list(Data.Analyze=wide, Obs.Per.Trial=Obs.per.trial, Results.Stage.1=Results.Stage.1, Residuals.Stage.1=Residuals.Stage.1, Fixed.Effect.Pars=Fixed.Effect.Pars, Random.Effect.Pars=Random.Effect.Pars, Results.Stage.2=Results.Stage.2, Trial.R2=Trial.R2, Indiv.R2=Indiv.R2, Trial.R=Trial.R, Indiv.R=Indiv.R, Cor.Endpoints=Cor.Endpoints, D.Equiv=D.equiv, ICA=ICA, T0T0 = T0T0, T1T1 = T1T1, S0S0 = S0S0, S1S1 = S1S1, Call=match.call()) class(fit) <- "UnimixedContCont" fit }
fpca_gauss <- function(Y, npc = 1, Kt = 8, maxiter = 20, t_min = NULL, t_max = NULL, print.iter = FALSE, row_obj= NULL, seed = 1988, ...){ curr_iter = 1 error = rep(NA, maxiter) error[1] = 100.0 if(is.null(row_obj)){ data = data_clean(Y) Y = data$Y rows = data$Y_rows I = data$I }else{ rows = row_obj I = dim(rows)[1] } if(Kt < 3){ stop("Kt must be greater than or equal to 3.") } time = Y$index if (is.null(t_min)) {t_min = min(time)} if (is.null(t_max)) {t_max = max(time)} knots = quantile(time, probs = seq(0, 1, length = Kt - 2))[-c(1, Kt - 2)] Theta_phi = bs(c(t_min, t_max, time), knots = knots, intercept = TRUE)[-(1:2),] set.seed(seed) psi_coefs = matrix(rnorm(Kt * npc), Kt, npc) * 0.5 alpha_coefs = matrix(coef(glm(Y$value ~ 0 + Theta_phi, family = "gaussian")), Kt, 1) sigma2 = 1 temp_alpha_coefs = alpha_coefs temp_psi_coefs = psi_coefs temp_sigma2 = sigma2 phi_a = list(NA, I) phi_b = matrix(0, nrow = Kt * (npc+1), ncol = I) scores = matrix(NA, I, npc) sigma_vec = rep(NA, I) while(curr_iter < maxiter && error[curr_iter] > 0.0001){ if(print.iter){ message("current iteration: ", curr_iter) message("current error: ", error[curr_iter]) } for(i in 1:I){ subject_rows = rows$first_row[i]:rows$last_row[i] Yi = Y$value[subject_rows] Di = length(Yi) Theta_i = Theta_phi[subject_rows, ] Theta_i_quad = crossprod(Theta_i) mlist = expectedScores(Yi, temp_alpha_coefs, temp_psi_coefs, Theta_i, Theta_i_quad) Ci = solve(1/sigma2 * crossprod(psi_coefs, Theta_i_quad) %*% psi_coefs + diag(npc)) mi_inner = 1/sigma2 * (crossprod(Yi, Theta_i) - crossprod(alpha_coefs, Theta_i_quad)) %*% psi_coefs mi = tcrossprod(Ci, mi_inner) mm = Ci + tcrossprod(mi) sigma_vec[i] = -2 * t(mi) %*% t(psi_coefs) %*% t(Theta_i) %*% (Yi - Theta_i %*% alpha_coefs) + crossprod((Yi - Theta_i %*% alpha_coefs)) + sum(diag( crossprod(psi_coefs, Theta_i_quad) %*% psi_coefs %*% Ci)) + t(mi) %*% crossprod(psi_coefs, Theta_i_quad) %*% psi_coefs %*% mi si = rbind(mi, 1) ss = cbind(rbind(mm, t(mi)), si) phi_a[[i]] = kronecker(Theta_i_quad, ss) phi_b[,i] = t(Yi) %*% kronecker(Theta_i, t(si)) scores[i,] = mi } sigma2 = 1/length(Y$value) * sum(sigma_vec) phi_a_sum = Reduce("+", phi_a) phi_vec = solve(phi_a_sum) %*% rowSums(phi_b) phi_mat = matrix(phi_vec, nrow = Kt, ncol = npc + 1, byrow = TRUE) alpha_coefs = phi_mat[, npc+1] psi_coefs = phi_mat[, 1:npc] if(npc == 1){ psi_coefs = matrix(psi_coefs, ncol = 1)} curr_iter = curr_iter + 1 error[curr_iter] = sum((psi_coefs-temp_psi_coefs)^2) + sum((alpha_coefs-temp_alpha_coefs)^2) + (sigma2 - temp_sigma2)^2 temp_psi_coefs = psi_coefs temp_alpha_coefs = alpha_coefs temp_sigma2 = sigma2 } fits = rep(NA, dim(Y)[1]) subject_coef = alpha_coefs + tcrossprod(psi_coefs, scores) for(i in 1:I){ subject_rows = rows$first_row[i]:rows$last_row[i] fits[subject_rows] = Theta_phi[subject_rows, ] %*% subject_coef[,i] } fittedVals = data.frame(id = Y$id, index = Y$index, value = fits) Theta_phi_mean = bs(seq(t_min, t_max, length.out = Di), knots = knots, intercept = TRUE) psi_svd = svd(Theta_phi_mean %*% psi_coefs) efunctions = psi_svd$u evalues = ( psi_svd$d ) ^ 2 scores = scores %*% psi_svd$v ret = list( "knots" = knots, "alpha" = Theta_phi_mean %*% alpha_coefs, "mu" = Theta_phi_mean %*% alpha_coefs, "efunctions" = efunctions, "evalues" = evalues, "npc" = npc, "scores" = scores, "subject_coefs" = subject_coef, "Yhat" = fittedVals, "Y" = Y, "family" = "gaussian", "sigma2" = sigma2 ) class(ret) = "fpca" return(ret) }
library(ggplot2) load('output/result-model5-5.RData') ms <- rstan::extract(fit) qua <- apply(ms$q, 2, quantile, prob=c(0.1, 0.5, 0.9)) d_est <- data.frame(d, t(qua), check.names=FALSE) d_est$Y <- as.factor(d_est$Y) d_est$A <- as.factor(d_est$A) p <- ggplot(data=d_est, aes(x=Y, y=`50%`)) + theme_bw(base_size=18) + coord_flip() + geom_violin(trim=FALSE, size=1, color='grey80') + geom_point(aes(color=A), position=position_jitter(w=0.3, h=0), size=0.5) + scale_color_manual(values=c('grey5', 'grey50')) + labs(x='Y', y='q') ggsave(file='output/fig5-10.png', plot=p, dpi=300, w=4.5, h=3)
bonchev2 <- function(g, dist=NULL, wien=NULL){ if(class(g)[1]!="graphNEL"){ stop("'g' must be a 'graphNEL' object") } if(is.null(wien)){ wien <- wiener(g) } if(is.null(dist)){ dist <- distanceMatrix(g) } rho <- max(dist) ki <- table(dist)[2:(rho+1)] i <- as.numeric(names(ki)) In <- i*ki * log2(i) wien*log2(wien)-sum(In) }
context("lcd") skip_on_cran() lcd_cache$delete_all() test_that("lcd", { skip_on_cran() skip_if_government_down() aa <- lcd(station = "01338099999", year = 2017) expect_is(aa, "tbl_df") expect_type(aa$station, c('character')) expect_type(aa$date, 'double') expect_type(aa$latitude, 'double') expect_type(aa$longitude, 'double') expect_type(aa$elevation, 'double') expect_type(aa$hourlysealevelpressure, 'character') }) test_that("lcd fails well", { skip_on_cran() skip_if_government_down() vcr::use_cassette("lcd_not_found", { expect_error(lcd(station = "02413099999", year = "1945"), "Not Found", class = "error") }) expect_error(lcd(5), "\"year\" is missing, with no default") expect_error(lcd(5, 5), "year must be between 1901") expect_error(lcd(list(1), 5), "station must be of class") expect_error(lcd(5, list(1)), "year must be of class") expect_error(lcd(station = "01338099999", year = 2017, col_types = list(1)), "col_types must be a") }) test_that("lcd fails well when trying to read a bad file", { skip_on_cran() lcd_cache$cache_path_set(full_path = file.path(tempdir(), "foo_bar")) lcd_cache$mkdir() path <- file.path(tempdir(), "foo_bar", "2020_72517014737.csv") file.create(path) expect_error(lcd(72517014737, 2020), class = "error") unlink(path) })
library(gtable) library(grid) library(ggplot) qplot(total_bill, tip, data = tips) + facet_grid(time ~ day) -> p p ggplot_gtable(ggplot_build(p)) -> x gtable_show_layout(x) qplot(total_bill, tip, data = tips, main = "test\ntitle") + facet_grid(time ~ day) -> p p ggplot_gtable(ggplot_build(p)) -> x2 gtable_show_layout(x2) grid.draw(gtable_filter(x, "strip-top")) grid.draw(gtable_filter(x, "strip-top")[1,]) gtable_show_layout(x) gtable_show_layout(x2) str(x2, max.level=2) x2$heights[[3]]
ray2mesh <- function(mesh1, tarmesh, tol=1e12, inbound=FALSE, mindist=FALSE,...) { if (is.character(tarmesh)) tarmesh <- vcgImport(tarmesh,clean=FALSE,updateNormals=FALSE) if (inbound) mesh1$normals <- -mesh1$normals outmesh <- vcgRaySearch(mesh1,tarmesh,mindist=mindist,maxtol=tol) return(outmesh) }
createbnFromData <- function(data, seed, debug = FALSE) { columns <- colnames(data$x) factorsPerColumns <- list() for (i in 1:length(columns)) { factors <- levels(data$x[,i]) factors factorsPerColumns[[i]] <- factors } bn <- createbn(nodeNames = columns, emissionOutputPerNode = factorsPerColumns, seed = seed) bn }
getPhyloTree<-function(QmatList,indexClsVec) { memberCLS<-sort(unique(indexClsVec)) C<-length(memberCLS) N<-dim(QmatList[[2]])[1] K<-length(QmatList) minDiffAncestorMat<-matrix(K,N,N) for(k in seq(2,K)) { clusters <- apply( QmatList[[k]], 1, which.max) for( i in seq(N-1)) for (j in seq(i+1,N)) { if(clusters[i]!=clusters[j] && k<minDiffAncestorMat[i,j]) { minDiffAncestorMat[i,j]<-k minDiffAncestorMat[j,i]<-k } } } minDiffAncestorClsMat<-matrix(K,C,C) for( cl1 in seq(1,C-1 ) ) { for( cl2 in seq(cl1+1, C) ) { currMat <- minDiffAncestorMat[indexClsVec==cl1,indexClsVec==cl2] minDiffAncestorClsMat[cl1,cl2] <- median(currMat, na.rm = TRUE) minDiffAncestorClsMat[cl2,cl1] <- median(currMat, na.rm = TRUE) } } distMat<-max(c(C,minDiffAncestorClsMat))-minDiffAncestorClsMat+1 tree<-nj(distMat) return(list(minDiffAncestorClsMat=minDiffAncestorClsMat,tree=tree)) }
plotColorbarCol = function(groups, margin) { if (missing(margin)) { delta = 0.05 delta2 = 0.4 } else { delta = margin[1] delta2 = margin[2] } groups = as.numeric(groups) ugroups = unique(groups) for (i in 1:length(groups)) { coli = which(groups[i]==ugroups) a0 = c(i-1,i-1,i,i)/length(groups) b0 = c(1+0.1*delta,1+0.9*delta,1+0.9*delta,1+0.1*delta) polygon(a0,b0,col=coli,border=FALSE) } }
makeRSSSOS <- function(x, y, type, deg.is.odd, K){ force(x) force(y) force(type) force(deg.is.odd) force(K) function(par){ fit <- evalPolSOS(par, x, type, deg.is.odd, K) sum((y-fit)^2) } } makewRSSSOS <- function(x, y, w, type, deg.is.odd, K){ force(x) force(y) force(w) force(type) force(deg.is.odd) force(K) function(par){ fit <- evalPolSOS(par, x, type, deg.is.odd, K) sum(w*(y-fit)^2) } } evalPolSOS <- function(par, x, type, deg.is.odd, K){ beta <- evalCoefSOS(par, type, deg.is.odd, K) evalPol(x, beta) } evalCoefSOS <- function(par, type, deg.is.odd, K){ d <- par[1L] a <- par[2L] if(K==0){ tmp <- c(d, a*par[3L]) }else{ if(type == 0){ M <- (length(par)-2L)/2L gamma <- par[2L + 1L:M] delta <- par[M+2L + 1L:M] tmp <- convolve(gamma, rev(gamma), type="o") tmp <- tmp + convolve(delta, rev(delta), type="o") }else if(type == 1){ if(deg.is.odd){ M <- K+1 gamma <- par[2L + 1L:M] delta <- par[M+2L + 1L:K] tmp <- convolve(gamma, rev(gamma), type="o") tmp <- tmp + c(0, convolve(delta, rev(delta), type="o"), 0) }else{ gamma <- par[2L + 1L:K] delta <- par[K+2L + 1L:K] tmp <- c(convolve(gamma, rev(gamma), type="o"), 0) tmp <- tmp + c(0, convolve(delta, rev(delta), type="o")) } }else if(type == 2){ if(deg.is.odd){ M <- K+1 gamma <- par[2L + 1L:M] delta <- par[M+2L + 1L:K] tmp <- convolve(gamma, rev(gamma), type="o") tmp <- tmp + convolve(convolve(delta, rev(delta), type="o"), c(-1,1,0),type="o") }else{ gamma <- par[2L + 1L:K] delta <- par[K+2L + 1L:K] tmp <- convolve(gamma, rev(gamma), type="o") tmp <- c(tmp, 0) - c(0, tmp) tmp <- tmp + c(0, convolve(delta, rev(delta), type="o")) } }else{ stop("Why are we here.") } res <- c(d, a*tmp/(1:length(tmp))) } names(res) <- paste("beta", seq_along(res)-1, sep="") res }
Id <- "$Id: c212.interim.1a.hier2.R,v 1.6 2016/12/08 13:55:27 clb13102 Exp clb13102 $" c212.interim.1a.hier2 <- function(trial.data, sim_type = "SLICE", burnin = 10000, iter = 40000, nchains = 3, global.sim.params = data.frame(type = c("MH", "SLICE"), param = c("sigma_MH", "w"), value = c(0.2,1), control = c(0,6), stringsAsFactors = FALSE), sim.params = NULL, monitor = data.frame(variable = c("theta", "gamma", "mu.gamma", "mu.theta", "sigma2.theta", "sigma2.gamma"), monitor = c(1, 1, 1, 1, 1, 1), stringsAsFactors = FALSE), initial_values = NULL, level = 1, hyper_params = list(mu.gamma.0 = 0, tau2.gamma.0 = 10, mu.theta.0 = 0, tau2.theta.0 = 10, alpha.gamma = 3, beta.gamma = 1, alpha.theta = 3, beta.theta = 1), memory_model = "HIGH") { if (level == 0) { model_fit = c212.interim.1a.hier2.lev0(trial.data, sim_type, burnin, iter, nchains, global.sim.params, sim.params, monitor, initial_values, hyper_params, memory_model) } else if (level == 1) { model_fit = c212.interim.1a.hier2.lev1(trial.data, sim_type, burnin, iter, nchains, global.sim.params, sim.params, monitor, initial_values, hyper_params, memory_model) } else { return(NULL) } return(model_fit) }
use_rstudio_secondary_repo <- function(..., .write_json = TRUE, .backup = TRUE) { check_min_rstudio_version("1.3") if (!interactive()) { "{.code use_rstudio_secondary_repo()} must be run interactively." %>% cli::cli_alert_danger() return(invisible()) } user_passed_updated_repos <- rlang::dots_list(...) if (!rlang::is_named(user_passed_updated_repos)) { rlang::abort("Each argument must be named.") } list_current_prefs <- jsonlite::fromJSON(rstudio_config_path("rstudio-prefs.json")) if (is.null(list_current_prefs$cran_mirror)) { list_current_prefs$cran_mirror <- list("name" = "Global (CDN)", "host" = "RStudio", "url" = "https://cran.rstudio.com/", "repos" = "", "country" = "us", "secondary" = NULL) } current_repos <- repo_string_as_named_list(list_current_prefs$cran_mirror$secondary) user_passed_updated_repos <- union( current_repos[unlist(current_repos) %in% unlist(user_passed_updated_repos)] %>% names(), current_repos[names(current_repos) %in% names(user_passed_updated_repos)] %>% names() ) %>% purrr::compact() %>% {stats::setNames(rep_len(list(NULL), length.out = length(.)), .)} %>% purrr::list_modify(!!!purrr::compact(user_passed_updated_repos)) any_update <- pretty_print_updates(current_repos, user_passed_updated_repos) if (!any_update) { return(invisible(NULL)) } if (!startsWith(tolower(readline("Would you like to continue? [y/n] ")), "y")) { return(invisible(NULL)) } list_current_prefs$cran_mirror$secondary <- current_repos %>% purrr::update_list(!!!user_passed_updated_repos) %>% purrr::imap_chr(~paste0(.y, "|", .x)) %>% paste(collapse = "|") if (isTRUE(.write_json)) { write_json( list_current_prefs, path = rstudio_config_path("rstudio-prefs.json"), .backup = .backup ) return(invisible(NULL)) } else { return(list_current_prefs) } } repo_string_as_named_list <- function(x) { if (is.null(x)) return(list()) xx <- strsplit(x, "|", fixed = TRUE) %>% unlist() xx[!as.logical(seq_len(length(xx)) %% 2)] %>% stats::setNames(xx[as.logical(seq_len(length(xx)) %% 2)]) %>% as.list() }
set_vector_layout <- function(patients, height) { treatment <- sapply(unique(patients$treat), function(x) length(which(patients$treat == x))) l_trt <- treatment[-1] l_trt1 <- treatment[1] vec_lay <- c(1:l_trt1, rep(0, ifelse(l_trt1 %% height == 0, 0, height - l_trt1 %% height))) if (length(l_trt) > 0) { for (z in 1:length(l_trt)) { if (l_trt[z] %% height == 0) { diff <- 0 } else { diff <- height - l_trt[z] %% height } vec_lay_add <- c((1:l_trt[z]) + max(vec_lay), rep(0, diff)) vec_lay <- c(vec_lay, vec_lay_add) } } return(vec_lay) }
library("aroma.affymetrix") ovars <- ls(all.names=TRUE) oplan <- future::plan() message("*** GcRmaBackgroundCorrection ...") dataSet <- "GSE9890" chipType <- "HG-U133_Plus_2" csR <- AffymetrixCelSet$byName(dataSet, chipType=chipType) csR <- csR[1:6] print(csR) cdf <- getCdf(csR) acs <- getAromaCellSequenceFile(cdf) print(acs) strategies <- future:::supportedStrategies() strategies <- setdiff(strategies, "multiprocess") if (require("future.BatchJobs")) { strategies <- c(strategies, "batchjobs_local") if (any(grepl("PBS_", names(Sys.getenv())))) { strategies <- c(strategies, "batchjobs_torque") } } if (require("future.batchtools")) { strategies <- c(strategies, "batchtools_local") if (any(grepl("PBS_", names(Sys.getenv())))) { strategies <- c(strategies, "batchtools_torque") } } checksum <- NULL for (strategy in strategies) { message(sprintf("*** Using %s futures ...", sQuote(strategy))) future::plan(strategy) tags <- c("*", strategy) bg <- GcRmaBackgroundCorrection(csR, seed=0xBEEF, tags=tags) print(bg) csB <- process(bg, verbose=verbose) print(csB) csBz <- getChecksumFileSet(csB) print(csBz[[1]]) checksumT <- readChecksum(csBz[[1]]) if (is.null(checksum)) checksum <- checksumT stopifnot(identical(checksumT, checksum)) message(sprintf("*** Using %s futures ... DONE", sQuote(strategy))) } message("*** GcRmaBackgroundCorrection ... DONE") future::plan(oplan) rm(list=setdiff(ls(all.names=TRUE), ovars))
MDG <- function(level){ x <- NULL if(level==1){ x1 <- github.cssegisanddata.covid19(country = "Madagascar") x2 <- ourworldindata.org(id = "MDG") x <- full_join(x1, x2, by = "date") } return(x) }
redlist <- function (x) { n <- 0 x. <- x while (length(names(x.))==0) { x. <- do.call("c", x.) n <- n + 1 } if (n>1) { for (i in 1:(n-1)) { x <- do.call("c", x) } x } else { x } }
markowitzHull <- function (data, nFrontierPoints=50) { stopifnot(is.timeSeries(data)) Spec <- portfolioSpec() setNFrontierPoints(Spec) <- nFrontierPoints frontier <- portfolioFrontier(data, spec=Spec) Risks <- risks <- frontierPoints(frontier)[, 1] Returns <- frontierPoints(frontier)[, 2] N <- ncol(data) for (i in 1:(N - 1)) for (j in (i + 1):N) { Data <- data[, c(i, j)] ans <- portfolioFrontier(Data, spec=Spec) coord <- frontierPoints(ans) nextFrontier <- approx(coord[, 2], coord[, 1], xout = Returns)$y naIndex <- which(is.na(nextFrontier)) nextFrontier[naIndex] <- Risks[naIndex] risks <- rbind(risks, nextFrontier) } targetReturn <- Returns minTargetRisk <- Risks maxTargetRisk <- colMaxs(risks) hull <- cbind( targetReturn = Returns, minTargetRisk = Risks, maxTargetRisk = colMaxs(risks)) polygon <- cbind( c(minTargetRisk, rev(maxTargetRisk)[-1]), c(targetReturn, rev(targetReturn)[-1]) ) rownames(polygon) <- 1:nrow(polygon) colnames(polygon) <- c("targetRisk", "targetReturn") ans <- polygon attr(ans, "data") <- data attr(ans, "hull") <- hull attr(ans, "frontier") <- frontier invisible(ans) } feasibleGrid <- function(hull, trace=FALSE) { polygon <- hull data <- attr(hull, "data") hull <- attr(hull, "hull") if (trace) { plot(polygon) box(col="white") polygon(polygon, col="grey") grid() } minRisks <- as.vector(hull[, 2]) maxRisks <- as.vector(hull[, 3]) minRisk <- min(minRisks) maxRisk <- max(maxRisks) targetRisks <- seq(minRisk, maxRisk, length = length(minRisks)) targetReturns <- as.vector(hull[, 1]) N <- length(targetReturns) Grid <- matrix(NA, ncol=N, nrow=N) offset <- diff(range(targetRisks[1:2]))/2 for (i in 1:N) { targetReturn <- targetReturns[i] for (j in 1:N) { targetRisk <- targetRisks[j] + offset if (targetRisk >= minRisks[i] && targetRisk <= maxRisks[i]) { Grid[j, i] <- 1 if (trace) points(targetRisk, targetReturn, pch=19) } } } ans <- list(x=targetRisks, y=targetReturns, z=Grid) attr(ans, "data") <- data attr(ans, "polygon") <- polygon attr(ans, "hull") <- hull class(ans) <- c("feasibleGrid", "list") invisible(ans) } bestDiversification <- function(grid, FUN="var", trace=FALSE) { data <- attr(grid, "data") polygon <- attr(grid, "polygon") targetRisks <- grid$x targetReturns <- grid$y Grid <- grid$z N <- length(targetRisks) objectiveFun <- match.fun(FUN) nAssets <- ncol(data) MEAN <- colMeans(data) COV <- cov(data) if(trace) { image(grid, col="lightgrey") box(col="white") grid() } Weights <- Coord <- NULL Objective <- NA * Grid Start <- rep(1/nAssets, times = nAssets) for (i in 1:N) { targetReturn <- targetReturns[i] for (j in 1:N) { targetRisk <- targetRisks[j] if (!is.na(Grid[j,i])) { ans <- donlp2NLP( start = Start, objective <- objectiveFun, par.lower = rep(0, times = nAssets), par.upper = rep(1, times = nAssets), eqA = rbind(rep(1, times = nAssets), MEAN), eqA.bound = c(1, targetReturn), eqFun = list(function(x) sqrt(t(x) %*% COV %*% x)), eqFun.bound = targetRisk) Weights <- rbind(Weights, ans$solution) Objective[j,i] <- objectiveFun(ans$solution) Coord <- rbind(Coord, c(j,i)) if(trace) { points(targetRisk, targetReturn, pch=19, cex=0.7) } } } } ans <- list(x=targetRisks, y=targetReturns, z=Objective) attr(ans, "data") <- data attr(ans, "polygon") <- polygon attr(ans, "weights") <- cbind(Coord, Weights) class(ans) <- c("bestDiversification", "list") invisible(ans) } riskSurface <- function(diversification, FUN=NULL, ...) { data <- attr(diversification, "data") weights <- attr(diversification, "weights") polygon <- attr(diversification, "polygon") if (is.null(FUN)) FUN <- function(data, weights, ...) var(weights) fun <- match.fun(FUN) Coord <- attr(diversification, "weights")[, 1:2] Weights <- attr(diversification, "weights")[, -(1:2)] N <- nrow(Coord) x <- diversification$x y <- diversification$y z <- diversification$z Value <- NA * z for (k in 1:N) { Value[Coord[k, 1], Coord[k, 2]] <- fun(data, Weights[k, ], ...) } ans <- list(x=x, y=y, z=Value) attr(ans, "data") <- data attr(ans, "weights") <- weights attr(ans, "polygon") <- polygon class(ans) <- c("riskSurface", "list") ans } surfacePlot <- function(surface, type=c("image", "filled.contour"), nlevels=11, palette=topo.colors, addContour=TRUE, addGrid=TRUE, addHull=TRUE, addAssets=TRUE, ...) { x <- surface$x y <- surface$y z <- surface$z colors <- .scaledColors(surface, palette=palette, nlevels=nlevels) levels <- colors$levels palette <- colors$palette yOffset <- 0.025*diff(range(y)) yLim <- c(min(y)-yOffset, max(y)+yOffset) xOffset <- 0.1*diff(range(x)) xLim <- c(min(x)-xOffset/4, max(x)+xOffset) type <- match.arg(type) if (type == "image") { image(x, y, z, xlim=xLim, ylim=yLim, xlab="", ylab="", col=palette) box(col="white") } else if (type == "filled.contour") { image(x, y, z, xlim=xLim, ylim=yLim, xlab="", ylab="", col="white") graphics::.filled.contour( x = as.double(x), y = as.double(y), z = z, levels = as.double(levels), col = palette) box(col="white") } if(addContour) contour(x, y, z, add=TRUE, levels=signif(levels, 3)) if(addHull) { hull <- attr(surface, "polygon") lines(hull, lwd=2, col="darkgreen") } if(addGrid) grid() title(...) cs <- cumsum(levels) css <- ( cs - min(cs) ) / diff(range(cs)) css <- 0.95 * css + 0.025 cy <- min(y) + css * diff(range(y)) cx <- rep(xLim[2]-0.1 * xOffset, length(cy)) lines(cx, cy, lwd=3) for (i in 1:(nlevels-1)) lines(c(cx[i], cx[i+1]), c(cy[i], cy[i+1]), lwd=3, col=palette[i]) for (i in 1:nlevels) points(cx[i], cy[i], pch=16, cex=1.1, col="black") textOffset <- c(-0.0005, 0.0005, 0.0008, 0.0008, rep(0, 7)) text(cx, cy+textOffset, as.character(signif(levels, 2)), pos=2, cex=0.8) if (addAssets) { frontier <- portfolioFrontier(data) pointCex <- 2.5 textCex <- 0.5 xy <- minvariancePoints(frontier, auto=FALSE, pch=19, cex=pointCex, col = "red") text(xy[, 1], xy[, 2], "MVP", font=2, col="white", cex=textCex) xy <- tangencyPoints(frontier, auto=FALSE, pch=19, cex=pointCex, col="orange") text(xy[, 1], xy[, 2], "TGP", font=2, col="white", cex=textCex) xy <- equalWeightsPoints(frontier, auto=FALSE, pch=19, cex=pointCex, col="brown") text(xy[, 1], xy[, 2], "EWP", font=2, col="white", cex=textCex) xy <- singleAssetPoints(frontier, auto=FALSE, pch=19, cex=pointCex, col="black", lwd=2) text(xy[, 1], xy[, 2], rownames(xy), font=2, col="white", cex=textCex) } invisible(list(surface=surface, levels=levels)) } .scaledColors <- function(surface, palette=topo.colors, nlevels=11) { Z <- as.vector(surface$z) levels <- quantile(Z, probs=seq(from=0, to=1, length=nlevels), na.rm=TRUE) palette <- palette(nlevels-1) list(palette=palette, levels=levels) }
"med.regressCOP" <- function(u=seq(0.01,0.99, by=0.01), cop=NULL, para=NULL, level=NA, ...) { if(is.null(cop)) { warning("must have copula argument specified, returning NULL") return(NULL) } UV <- qua.regressCOP(f=0.5, u=u, cop=cop, para=para, ...) if(is.na(level)) return(UV) if(length(level) > 1) { warning("only the first value of 'level' is used") level <- level[1] } lo <- ifelse(level > 0.5, (1-level)/2, level/2) tmp <- UV$V; UV$V <- NULL UV$Vlwr <- qua.regressCOP(f=lo, u=u, cop=cop, para=para, ...)$V UV$V <- tmp UV$Vupr <- qua.regressCOP(f=1-lo, u=u, cop=cop, para=para, ...)$V return(UV) }
replace_emoji <- function(x, emoji_dt = lexicon::hash_emojis, ...){ gsub("\\s+", " ", .mgsub(emoji_dt[["x"]], paste0(" ", emoji_dt[["y"]], " "), to_byte(x), ...)) } replace_emoji_identifier <- function(x, emoji_dt = lexicon::hash_emojis_identifier, ...){ gsub("\\s+", " ", .mgsub(emoji_dt[["x"]], paste0(" ", emoji_dt[["y"]], " "), to_byte(x), ...)) }
cpoint <- function(a, b) { return(.Call("cpoint", a, b)) }
LassoGEE <- function(X, y, id, family = binomial("probit"), lambda, corstr = "independence", method = c("CGD", "RWL"), beta.ini = NULL, R = NULL, scale.fix = TRUE, scale.value = 1, maxiter = 50, tol = 1e-3, silent = TRUE, Mv = NULL, verbose = TRUE) { call <- match.call() method=match.arg(method) if (is.null(id)) { stop("Id variable not found!") } if (length(id) != length(y)) stop("Id and y do not have the same length!") if (!(is.double(X))) X <- as.double(X) if (!(is.double(y))) y <- as.double(y) if (!(is.double(id))) id <- as.double(id) N<-length(unique(id)) nx=ncol(X) avec <- as.integer(unlist(lapply(split(id, id), "length"))) maxclsz <- max(avec) maxcl <- maxclsz nt <- avec nobs <- sum(nt) xnames <- dimnames(X)[[2]] if (is.null(xnames)) { xnames <- paste("x", 1:dim(X)[2], sep = "") dimnames(X) <- list(NULL, xnames) } if (!(is.double(N))) N <- as.double(N) if (!(is.double(maxcl))) maxcl <- as.double(maxcl) if (!(is.double(nobs))) nobs <- as.double(nobs) if (missing(lambda)) stop("A value is not assiged for lambda!") if (missing(family)) family = gaussian(link = "identity") if (missing(corstr)) corstr = "independence" if (missing(Mv)) Mv <- NULL if (corstr == "stat_M_dep" && is.null(Mv)) stop("corstr is assumed to be 'stat_M_dep' but Mv is not specified!") if (corstr == "non_stat_M_dep" && is.null(Mv)) stop("corstr is assumed to be 'non_stat_M_dep' but Mv is not specified!") if ((corstr != "stat_M_dep" && corstr != "non_stat_M_dep") && !is.null(Mv)) stop("Mv is specified while corstr is assumed to be neither \n'stat_M_dep' nor 'non_stat_M_dep'!") if (corstr == "non_stat_M_dep" && length(unique(nt)) != 1) stop("corstr cannot be assumed to be 'non_stat_M_dep' for unbalanced data!") if (corstr == "unstructured" && length(unique(nt)) != 1) stop("corstr cannot be assumed to be 'unstructured' for unbalanced data!") if (missing(R)) R <- NULL if (corstr == "fixed" && is.null(R)) stop("corstr is assumed to be 'fixed' but R is not specified!") if (corstr != "fixed" && !is.null(R)) stop("R is specified although corstr is not assumed to be 'fixed'!") if (!is.null(R)) { Rr <- nrow(R) if (Rr != ncol(R)) stop("R is not square!") if (Rr < maxclsz) { stop("R is not big enough to accommodate some clusters!") } else if (Rr > maxclsz) { stop("R is larger than the maximum cluster!") } } if (missing(scale.fix)) scale.fix <- TRUE scale.fix <- as.integer(scale.fix) if (missing(scale.value)) scale.value = 1 scale.value <- as.integer(scale.value) if (missing(maxiter)) maxiter <- 100 maxiter <- as.integer(maxiter) if (missing(tol)) tol = 0.0001 tol = as.double(tol) if (missing(silent)) silent <- TRUE silent <- as.integer(silent) if (is.character(family)) family <- get(family) if (is.function(family)) family <- family() links <- c("identity", "log", "logit", "inverse", "probit", "cloglog") fams <- c("gaussian", "poisson", "binomial", "Gamma", "quasi") varfuns <- c("constant", "mu", "mu(1-mu)", "mu^2") corstrs <- c("independence", "fixed", "stat_M_dep", "non_stat_M_dep", "exchangeable", "AR-1", "unstructured") linkv <- as.integer(match(c(family$link), links, -1)) if (linkv < 1) stop("unknown link!") famv <- match(family$family, fams, -1) if (famv < 1) stop("unknown family") if (famv <= 4) { varfunv <- famv } else { varfunv <- match(family$varfun, varfuns, -1) } if (varfunv < 1) stop("unknown varfun!") corstrv <- as.integer(match(corstr, corstrs, -1)) if (corstrv < 1) stop("unknown corstr!") Mv <- as.integer(Mv) if (!is.null(beta.ini)) { betaest <- matrix(beta.ini, ncol = 1) if(nrow(betaest) != nx) { stop("Dimension of beta != ncol(X)!") } } else { betaest = c(rep(0,nx)) } aindex=cumsum(nt) index=c(0,aindex[-length(aindex)]) diff<-1 iter<-0 count <- c() beta_all_step <- list() while(iter < maxiter) { R.fi.hat <- PGEE::mycor_gee2( N, nt, y, X, family, beta_new = betaest, corstr = corstr, Mv = Mv, maxclsz = maxclsz, R = R, scale.fix = scale.fix, scale.value = scale.value) Rhat <- R.fi.hat$Ehat fihat <- R.fi.hat$fi eta <- drop(X%*%betaest) mu=family$linkinv(eta) mu_eta = family$mu.eta(eta) vari = family$variance(mu) S.H.E.M.val = SHM(X = X, y = y, mu = mu, mu_eta = mu_eta, vari = vari, nt = nt, index = index, Rhat = Rhat, N = N, fihat = fihat) S<-S.H.E.M.val$S v<-S.H.E.M.val$H u<- v%*%betaest + S if(method == "CGD") { inner.fit <- ac_prox_grad(u = u, v = v, lambda = rep(lambda*N, nx), tol = tol, maxiter = maxiter, silent = silent) betaest1 <- inner.fit$beta_k diff<-sum(abs(betaest-betaest1)) betaest<-betaest1 iter<-iter+1 count[iter] <- inner.fit$k beta_all_step[[iter]] <- inner.fit$beta_inner_step if (diff <= tol) { Smat <- S.H.E.M.val$Smat if(verbose) cat("iter: ",iter, "diff: ",diff,"\n") break } } else { betaest1 <- WLreglass(v = v, u = u, lambda = rep(lambda*N, nx), tol = tol) diff<-sum(abs(betaest-betaest1)) betaest<-betaest1 iter<-iter+1 if (diff <= tol) { Smat <- S.H.E.M.val$Smat if(verbose) cat("iter: ",iter, "diff: ",diff,"\n") break } } } fit <- list() attr(fit, "class") <- c("LassoGEE") fit$title <- paste("LassoGEE by", method, "Algorithm") fit$version <- "Version: 1.0" links <- c("Identity", "Logarithm", "Logit", "Reciprocal", "Probit", "Cloglog") varfuns <- c("Gaussian", "Poisson", "Binomial", "Gamma") corstrs <- c("Independent", "Fixed", "Stationary M-dependent", "Non-Stationary M-dependent", "Exchangeable", "AR-1", "Unstructured") fit$model <- list() fit$model$link <- links[linkv] fit$model$varfun <- varfuns[varfunv] fit$model$corstr <- corstrs[corstrv] if (!is.na(match(c(corstrv), c(3, 4)))) fit$model$M <- Mv fit$call <- call fit$nobs <- nobs fit$outer.iter <- iter fit$betaest <- as.vector(betaest) fit$nas <- is.na(fit$betaest) if(method == "CGD"){ fit$beta_all_step <- beta_all_step fit$inner.count <- count } names(fit$betaest) <- xnames eta <- as.vector(X %*% fit$betaest) fit$linear.predictors <- eta mu <- as.vector(family$linkinv(eta)) fit$fitted.values <- mu fit$residuals <- y - mu fit$family <- family fit$y <- as.vector(y) fit$id <- as.vector(id) fit$max.id <- maxcl fit$working.correlation <- Rhat[1:maxclsz, 1:maxclsz, which(avec == maxclsz)[1]] fit$scale <- fihat fit$S <- S fit$Smat <- Smat fit$lambda.value <- lambda fit$xnames <- xnames fit$error <- diff fit } prox_L1 = function(x, lambda){ return(sign(x) * pmax(0, abs(x) - lambda)) } ac_prox_grad <- function(u, v, lambda, tol, maxiter, silent) { L.max <- max(eigen(v)$values) L.min <- min(eigen(v)$values) L <- ifelse(L.max > 0, L.max, L.min) beta_last <-solve(v)%*%u z_last <- beta_last t_last <- 1 k <- 0 beta_inner_step <- beta_last while(k < maxiter) { need_project <- z_last-(v%*%z_last)/L + u/L beta_new <- prox_L1(need_project, lambda/abs(L)) distance <- beta_new-beta_last k <- k+1 if (silent == 0) cat(k, fill = TRUE) beta_inner_step <- cbind(beta_inner_step, beta_new) if (sqrt(sum(distance^2)) <= tol * sqrt(sum(beta_last^2))) { break } t_new <- (1 + sqrt(1 + 4 * t_last * t_last)) / 2 z_new <- beta_new + (t_last - 1) * distance / t_new beta_last <- beta_new t_last <- t_new z_last <- z_new } return(list(beta_k = beta_new, beta_inner_step = beta_inner_step, k = k)) } WLreglass<-function(v, u, lambda, tol){ p<-dim(v)[1] diff<-1 beta<-solve(v)%*%u while (diff > tol){ oldbeta<-beta z<-u-v%*%oldbeta for (j in 1:p){ beta[j]<- prox_L1((z[j]+v[j,j]*oldbeta[j]),lambda[j])/(v[j,j]) z<-z-(beta[j]-oldbeta[j])*v[,j] } diff<-max(abs(beta-oldbeta)) } return(beta) }
context("tabularize_eml()") test_that("parse summary table correctly", { eml <- system.file("extdata", "test_data", "SoilMois2012_2017__full_metadata.xml", package = "metajam") metadata <- tabularize_eml(eml) expect_equal(dim(metadata), c(16,2)) }) test_that("parse full table correctly", { eml <- system.file("extdata", "test_data", "SoilMois2012_2017__full_metadata.xml", package = "metajam") metadata <- tabularize_eml(eml, full = TRUE) expect_equal(dim(metadata), c(189,2)) }) test_that("test fails on non xml file", { eml <- system.file("extdata", "test_data", "SoilMois2012_2017.csv", package = "metajam") expect_error(tabularize_eml(eml, full = TRUE)) })
source("ESEUR_config.r") library("plyr") library("mgcv") norm_occurrences=function(df) { df$norm_occur=df$occurrences/sum(df$occurrences) return(df) } loc_acc=read.csv(paste0(ESEUR_dir, "sourcecode/local-use/acc-per-obj.csv.xz"), as.is=TRUE) loc_acc=ddply(loc_acc, .(total.access), norm_occurrences) common_loc=subset(loc_acc, total.access <= 150) around_100=subset(loc_acc, (total.access >= 95) & (total.access <= 105)) above_10=subset(loc_acc, (total.access >= 10)) locg_mod=gam(norm_occur ~ s(object.access, total.access, k=75), data=common_loc, family=Gamma) summary(locg_mod) gam.check(locg_mod) locp_mod=gam(norm_occur ~ s(object.access, k=50)+s(total.access, k=50), data=common_loc, family=Gamma) summary(locp_mod) gam.check(locp_mod) vis.gam(locg_mod, plot.type="contour") loc100_mod=gam(norm_occur ~ s(object.access, k=40), data=around_100, family=Gamma) plot(around_100$object.access, around_100$norm_occur, xlim=c(1, 60), ylim=c(0, 0.5), xlab="Accesses", ylab="Occurrences (nomalised)") lines(predict(loc100_mod, newdata=data.frame(object.access=1:100), type="response"), col="red")
medfilt1 <- function(x, n = 3, MARGIN = 2, na.omit = FALSE, ...) { mf <- function(x, n, na.omit, ...) { if (n %% 2 != 1 || n > length(x)) { stop("n must be odd and smaller than the length of x") } if (any(is.na(x))) { if (na.omit) { x <- na.omit(x) } else { spl <- stats::splinefun(seq_along(x), x) x <- spl(seq_along(x)) } } y <- stats::runmed(x, n, ...) as.vector(y) } if (is.vector(x)) { y <- mf(x, n, na.omit, ...) } else { y <- apply(x, MARGIN, mf, n, na.omit, ...) } y }
myget=function(x){ if (!is.null(x) && nzchar(x) && exists(x) && is.data.frame(get(x))) { get(x) } }
integrate_survdat <- function(dat, tau, alpha=0.05) { if ( length(which(c('time', 'status') %in% colnames(dat))) != 2) { stop('Column names must include time and status exactly.') } KMfit <- survival::survfit(Surv(time, status) ~ 1, data=dat) n <- nrow(dat) nUnique <- length(KMfit$time) KMtab <- data.frame(time = KMfit$time, surv = KMfit$surv, nRisk = KMfit$n.risk, nEvent = KMfit$n.event) %>% dplyr::filter(.data$time <= tau) %>% dplyr::add_row(time=tau, surv=KMfit$surv[nUnique]) %>% dplyr::mutate(nextTime = lead(.data$time)) %>% dplyr::mutate(diffTime = .data$nextTime - .data$time) %>% dplyr::mutate(aucChunk = .data$diffTime * .data$surv) %>% dplyr::filter(!is.na(.data$aucChunk)) %>% dplyr::mutate(cumAUC = cumsum(.data$aucChunk)) %>% dplyr::mutate(cumAUC = .data$cumAUC + .data$time[1]) %>% dplyr::mutate(intervalAUC = .data$cumAUC[length(.data$cumAUC)] - .data$cumAUC + .data$aucChunk) aucTot <- KMtab$cumAUC[nrow(KMtab)] multiplier <- ifelse(KMtab$nRisk - KMtab$nEvent == 0, 0, KMtab$nEven / (KMtab$nRisk * (KMtab$nRisk - KMtab$nEvent))) varHat <- sum( KMtab$intervalAUC^2 * multiplier ) returnDF <- data.frame(Stat = c("RMST", "RMTL"), Est = c(aucTot, tau - aucTot), se = c(sqrt(varHat), sqrt(varHat)), pval = c(1 - pchisq(aucTot^2 / varHat, df=1), 1 - pchisq((tau - aucTot)^2 / varHat, df=1)), CIlower = c(aucTot - qnorm(1 - alpha/2) * sqrt(varHat), tau - aucTot - qnorm(1 - alpha/2) * sqrt(varHat)), CIupper = c(aucTot + qnorm(1 - alpha/2) * sqrt(varHat), tau - aucTot + qnorm(1 - alpha/2) * sqrt(varHat))) return(returnDF) }
dvinecop <- function(u, vinecop, cores = 1) { assert_that(inherits(vinecop, "vinecop_dist")) u <- if_vec_to_matrix(u, dim(vinecop)[1] == 1) vinecop_pdf_cpp(u, vinecop, cores) } pvinecop <- function(u, vinecop, n_mc = 10^4, cores = 1) { assert_that( inherits(vinecop, "vinecop_dist"), is.number(n_mc), is.count(cores) ) u <- if_vec_to_matrix(u, dim(vinecop)[1] == 1) vinecop_cdf_cpp(as.matrix(u), vinecop, n_mc, cores, get_seeds()) } rvinecop <- function(n, vinecop, qrng = FALSE, cores = 1) { assert_that( is.number(n), inherits(vinecop, "vinecop_dist"), is.flag(qrng), is.number(cores) ) U <- vinecop_sim_cpp(vinecop, n, qrng, cores, get_seeds()) if (!is.null(vinecop$names)) { colnames(U) <- vinecop$names } U } print.vinecop_dist <- function(x, ...) { cat(dim(x)[1], "-dimensional vine copula model ('vinecop_dist')", sep = "") print_truncation_info(x) invisible(x) } summary.vinecop_dist <- function(object, trees = seq_len(dim(object)["trunc_lvl"]), ...) { mat <- as_rvine_matrix(get_structure(object)) d <- dim(object)[1] trees <- intersect(trees, seq_len(dim(object)["trunc_lvl"])) n_pcs <- length(unlist(object$pair_copulas[trees], recursive = FALSE)) mdf <- as.data.frame(matrix(NA, n_pcs, 10)) names(mdf) <- c( "tree", "edge", "conditioned", "conditioning", "var_types", "family", "rotation", "parameters", "df", "tau" ) k <- 1 for (t in trees) { for (e in seq_len(d - t)) { mdf$tree[k] <- t mdf$edge[k] <- e mdf$conditioned[k] <- list(c(mat[d - e + 1, e], mat[t, e])) mdf$conditioning[k] <- list(mat[rev(seq_len(t - 1)), e]) pc <- object$pair_copulas[[t]][[e]] mdf$var_types[k] <- paste(pc$var_types, collapse = ",") mdf$family[k] <- pc$family mdf$rotation[k] <- pc$rotation mdf$parameters[k] <- list(pc$parameters) if (pc$family %in% setdiff(family_set_nonparametric, "indep")) mdf$parameters[k] <- list("[30x30 grid]") mdf$df[k] <- pc$npars mdf$tau[k] <- par_to_ktau(pc) k <- k + 1 } } class(mdf) <- c("summary_df", class(mdf)) mdf } predict.vinecop <- function(object, newdata, what = "pdf", n_mc = 10^4, cores = 1, ...) { assert_that( in_set(what, c("pdf", "cdf")), is.number(n_mc), is.number(cores), cores > 0 ) newdata <- if_vec_to_matrix(newdata, dim(object)[1] == 1) switch( what, "pdf" = vinecop_pdf_cpp(newdata, object, cores), "cdf" = vinecop_cdf_cpp(newdata, object, n_mc, cores, get_seeds()) ) } fitted.vinecop <- function(object, what = "pdf", n_mc = 10^4, cores = 1, ...) { if (is.null(object$data)) { stop("data have not been stored, use keep_data = TRUE when fitting.") } assert_that( in_set(what, c("pdf", "cdf")), is.number(n_mc), is.number(cores), cores > 0 ) switch( what, "pdf" = vinecop_pdf_cpp(object$data, object, cores), "cdf" = vinecop_cdf_cpp(object$data, object, n_mc, cores, get_seeds()) ) } logLik.vinecop <- function(object, ...) { structure(object$loglik, "df" = object$npars) } mBICV <- function(object, psi0 = 0.9, newdata = NULL) { assert_that(inherits(object, "vinecop_dist"), is.number(psi0)) ll <- ifelse(is.null(newdata), object$loglik, sum(log(dvinecop(newdata, object))) ) - 2 * ll + compute_mBICV_penalty(object, psi0) } compute_mBICV_penalty <- function(object, psi0) { d <- dim(object)[1] smr <- summary(object) q_m <- tapply(smr$family, smr$tree, function(x) sum(x == "indep")) q_m <- c(q_m, rep(0, d - 1 - length(q_m))) m_seq <- seq_len(d - 1) pen <- object$npars * log(object$nobs) pen - 2 * sum( q_m * log(psi0^m_seq) + (d - seq_len(d - 1) - q_m) * log(1 - psi0^m_seq) ) } print.vinecop <- function(x, ...) { cat(dim(x)[1], "-dimensional vine copula fit ('vinecop')", sep = "") print_truncation_info(x) print_fit_info(x) invisible(x) } summary.vinecop <- function(object, trees = seq_len(dim(object)["trunc_lvl"]), ...) { trees <- intersect(trees, seq_len(dim(object)["trunc_lvl"])) mdf <- summary.vinecop_dist(object, trees) d <- dim(object)[1] k <- 1 for (t in trees) { for (e in seq_len(d - t)) { mdf$loglik[k] <- object$pair_copulas[[t]][[e]]$loglik k <- k + 1 } } mdf } dim.vinecop_dist <- function(x) { dim(x$structure) }
indexes = function(data.x,data.y, type='fixed-base'){ data.x2 = as.matrix(data.x) data.y2 = as.matrix(data.y) if(!(type %in% c('fixed-base','chained'))){ stop("'type' argument should be either 'chained' or 'fixed-base'") } nShares = ncol(data.x2) matShares = matrix(0,ncol=nShares,nrow=nrow(data.x2)) for(j in 1:ncol(matShares)){ for(i in 1:nrow(matShares)){ matShares[i,j] = (data.x2[i,j] %*% data.y2[i,j]) / (data.x2[i,] %*% data.y2[i,]) } } laspeyres = vector('list') paasche = vector('list') tornqvist = matrix(0,nrow=nrow(data.x2),ncol=ncol(data.x2)) torn= vector('list') for(i in 1:nrow(data.x2)){ laspeyres[[i]] = (data.x2[i,]%*%data.y2[1,])/(t(data.x2[1,])%*%data.y2[1,]) paasche[[i]] = (data.x2[i,]%*%data.y2[i,])/(t(data.x2[1,])%*%data.y2[i,]) } for(j in 1:ncol(matShares)){ for(i in 1:nrow(matShares)){ tornqvist[i,j] = (data.x2[i,j]/data.x2[1,j])^ (0.5*(matShares[1,j]+matShares[i,j])) } } out=data.frame(laspeyres=unlist(laspeyres), paasche = unlist(paasche)) out$fisher = sqrt(out$laspeyres * out$paasche) out$tornqvist =apply(tornqvist,1,function(x) prod(x,na.rm=T)) out$spreadPL = abs(log(out$laspeyres/out$paasche)) if(type=='chained'){out=chaining(data.x2,data.y2)} out.list = list(indexes=out,shares=matShares) return(out.list) } multicomp = function(data.x,data.y, idx='fisher',transitivity='mst', var.agg,bench,period, plotting=FALSE){ indxVars = var.agg selVars = which(!(names(data.x) %in% indxVars)) labVars = which(names(data.x) %in% indxVars) if(!is.null(period)){ rownames(data.x) = paste(data.x[,indxVars[2]], data.x[,indxVars[1]],sep='.') rownames(data.y) = paste(data.y[,indxVars[2]], data.y[,indxVars[1]],sep='.') }else{ rownames(data.x) = data.x[,var.agg] rownames(data.y) = data.y[,var.agg] } I = diag(nrow(data.x)) n = nrow(I) if(transitivity != 'mst'){ for(i in 1:n){ if(idx %in% c('fisher','tornqvist')){ I[i:n,i] = indexes(data.x[i:n,selVars], data.y[i:n,selVars])$indexes[,idx] I[i,i:n] = 1./I[i:n,i] }else{ tempQuant = rbind(data.x[i,],data.x) tempPrice = rbind(data.y[i,],data.y) I[,i] = indexes(tempQuant[,selVars], tempPrice[,selVars])$indexes[,idx][-1] } } rownames(I)=rownames(data.x) colnames(I)=rownames(I) } if(transitivity == 'eks' & !(idx %in% c('laspeyres','paasche')) ){ out = eks(I) if(!is.null(period)){benchmark = paste(bench,period,sep='.')} if(is.null(period)){benchmark=bench} out = out[,which(colnames(out)==benchmark)] out return(out) }else if(transitivity == 'mst'){ if(!idx %in% c('fisher','tornqvist')){ warning('MST should be comuted using the Fisher or Tornqvist formula') } listCheck = list() for(i in 1:n){ tempQuant = rbind(data.x[i,],data.x) tempPrice = rbind(data.y[i,],data.y) I[,i] = indexes(tempQuant[,selVars], tempPrice[,selVars])$indexes[,'spreadPL'][-1] } netwk = ape::mst(I) rownames(netwk) = rownames(data.x) colnames(netwk) = rownames(data.x) rownames(I) = rownames(data.x) colnames(I) = rownames(data.x) ig = igraph::graph.adjacency(netwk) mst0 = igraph::minimum.spanning.tree(ig) if(plotting==TRUE){ igraph::tkplot(ig,vertex.size=10, vertex.color='gold2', vertex.label.font=2, edge.arrow.width=0.6, edge.arrow.size=0.6) } degrees = list() for(u in 1:length(igraph::V(ig)$name)){ degrees[[u]] = igraph::degree(ig,igraph::V(ig)$name[u]) } outerVerts = which(unlist(degrees)==2) if(!is.null(period)){bench=paste(bench,period,sep='.')} outerVerts = outerVerts[!(names(outerVerts) %in% bench)] paths = list() for(w in 1:length(outerVerts)){ startNode = which(as.character(igraph::V(ig)$name)== bench) endNode = which(as.character(igraph::V(ig)$name) == names(outerVerts)[w]) paths[[w]] = names(igraph::shortest_paths(ig,from=startNode, to=endNode)$vpath[[1]]) } conns = list() for(j in 1:length(paths)){ conns[[j]] = list() conns[[j]][[1]] = paths[[j]] conns[[j]][[2]] = matrix(0,nrow=length(paths[[j]]), ncol=length(paths[[j]])) ghindx = 1 for(gh in paths[[j]]){ tempQuant = rbind(data.x[rownames(data.x) == gh,],data.x[match(paths[[j]],rownames(data.x)), ]) tempPrice = rbind(data.y[rownames(data.y) ==gh,],data.y[match(paths[[j]],rownames(data.y)), ]) conns[[j]][[2]][,ghindx] = indexes(tempQuant[,selVars], tempPrice[,selVars])$indexes[,idx][-1] ghindx= ghindx+1 } ghindx=1 rownames(conns[[j]][[2]]) = paths[[j]] colnames(conns[[j]][[2]]) = paths[[j]] matLinks = as.matrix(conns[[j]][[2]][,1]) for(ab in 2:nrow(conns[[j]][[2]])){ matLinks[ab,1] = conns[[j]][[2]][ab,ab-1] * matLinks[ab-1,1] } conns[[j]][[3]]=matLinks } res = conns[[1]][[3]] if(length(paths)>1){ for(g in 2:length(conns)){ resTemp = conns[[g]][[3]] resTemp = as.matrix(resTemp[which(!(rownames(resTemp) %in% rownames(res))),1]) res = rbind(res,resTemp) } } out=res return(out) }else{ warning('Returning non-transitive indexes, besides in degenerate cases') out = eks(I) rownames(out) = rownames(data.x) colnames(out) = rownames(data.x) if(!is.null(period)){benchmark = paste(bench,period,sep='.')} if(is.null(period)){benchmark=bench} out = out[,which(colnames(out)==benchmark)] out return(out) } } multicompPAR = function(data.x,data.y, idx='fisher', transitivity='mst', var.agg,bench,period, plotting=FALSE, Cores){ indxVars = var.agg selVars = which(!(names(data.x) %in% indxVars)) labVars = which(names(data.x) %in% indxVars) if(!is.null(period)){ rownames(data.x) = paste(data.x[,indxVars[2]], data.x[,indxVars[1]],sep='.') rownames(data.y) = paste(data.y[,indxVars[2]], data.y[,indxVars[1]],sep='.') }else{ rownames(data.x) = data.x[,var.agg] rownames(data.y) = data.y[,var.agg] } I = diag(nrow(data.x)) n = nrow(I) if(transitivity != 'mst'){ for(i in 1:n){ if(idx %in% c('fisher','tornqvist')){ I[i:n,i] = indexes(data.x[i:n,selVars], data.y[i:n,selVars])$indexes[,idx] I[i,i:n] = 1./I[i:n,i] }else{ tempQuant = rbind(data.x[i,],data.x) tempPrice = rbind(data.y[i,],data.y) I[,i] = indexes(tempQuant[,selVars], tempPrice[,selVars])$indexes[,idx][-1] } } rownames(I)=rownames(data.x) colnames(I)=rownames(I) } if(transitivity == 'eks' & !(idx %in% c('laspeyres','paasche')) ){ out = eks(I) if(!is.null(period)){benchmark = paste(bench,period,sep='.')} if(is.null(period)){benchmark=bench} out = out[,which(colnames(out)==benchmark)] return(out) }else if(transitivity == 'mst'){ if(!idx %in% c('fisher','tornqvist')){ warning('MST should be computed using the Fisher or Tornqvist formula') } cl=parallel::makePSOCKcluster(Cores,outfile=NULL) parallel::clusterExport(cl=cl, varlist=c('data.x', 'data.y','selVars','n','indexes','chaining'), envir=environment()) I=parallel::parSapply(cl,1:n, function(i){ tempQuant = rbind(data.x[i,],data.x) tempPrice = rbind(data.y[i,],data.y) indexes(tempQuant[,selVars], tempPrice[,selVars])$indexes[,'spreadPL'][-1] }) set.seed(123) netwk = ape::mst(I) rownames(netwk) = rownames(data.x) colnames(netwk) = rownames(data.x) rownames(I) = rownames(data.x) colnames(I) = rownames(data.x) ig = igraph::graph.adjacency(netwk) if(plotting==TRUE){ igraph::tkplot(ig,vertex.size=10, vertex.color='gold2', vertex.label.font=2, edge.arrow.width=0.6, edge.arrow.size=0.6) } degrees = list() for(u in 1:length(igraph::V(ig)$name)){ degrees[[u]] = igraph::degree(ig,igraph::V(ig)$name[u]) } outerVerts = which(unlist(degrees)==2) if(!is.null(period)){bench=paste(bench,period,sep='.')} outerVerts = outerVerts[!(names(outerVerts) %in% bench)] paths = list() for(w in 1:length(outerVerts)){ startNode = which(as.character(igraph::V(ig)$name)== bench) endNode = which(as.character(igraph::V(ig)$name) == names(outerVerts)[w]) paths[[w]] = names(igraph::shortest_paths(ig,from=startNode, to=endNode)$vpath[[1]]) } conns = list() parallel::clusterExport(cl=cl, varlist=c('paths', 'conns','idx'), envir=environment()) conns = parallel::parLapply(cl,1:length(paths),function(j){ conns[[j]] = list() conns[[j]][[1]] = paths[[j]] conns[[j]][[2]] = matrix(0,nrow=length(paths[[j]]), ncol=length(paths[[j]])) ghindx = 1 for(gh in paths[[j]]){ tempQuant = rbind(data.x[rownames(data.x) == gh,],data.x[match(paths[[j]],rownames(data.x)), ]) tempPrice = rbind(data.y[rownames(data.y) == gh,],data.y[match(paths[[j]],rownames(data.y)), ]) conns[[j]][[2]][,ghindx] = indexes(tempQuant[,selVars], tempPrice[,selVars])$indexes[,idx][-1] ghindx= ghindx+1 } ghindx=1 rownames(conns[[j]][[2]]) = paths[[j]] colnames(conns[[j]][[2]]) = paths[[j]] matLinks = as.matrix(conns[[j]][[2]][,1]) for(ab in 2:nrow(conns[[j]][[2]])){ matLinks[ab,1] = conns[[j]][[2]][ab,ab-1] * matLinks[ab-1,1] } conns[[j]][[3]]=matLinks matLinks }) res = conns[[1]] if(length(paths)>1){ for(g in 2:length(conns)){ resTemp = conns[[g]] resTemp = as.matrix(resTemp[which(!(rownames(resTemp) %in% rownames(res))),1]) res = rbind(res,resTemp) } } out=res parallel::stopCluster(cl) return(out) }else{ warning('Returning non-transitive indexes, besides in degenerate cases') out = eks(I) rownames(out) = rownames(data.x) colnames(out) = rownames(data.x) if(!is.null(period)){benchmark = paste(bench,period,sep='.')} if(is.null(period)){benchmark=bench} out = out[,which(colnames(out)==benchmark)] out return(out) } } growth = function(dataset,var.agg){ varAggs = var.agg selVars = which(!(names(dataset) %in% varAggs)) selVars0 = which(names(dataset) %in% varAggs) livelli = levels(as.factor(dataset[[var.agg[2]]])) res = dataset[1,] res = res[-1,] for(i in 1:length(livelli)){ subN = subset(dataset,dataset[[var.agg[2]]]==livelli[i]) subRowsT = 2:nrow(subN) subRows0 = 1:(nrow(subN)-1) subIndx = (subN[subRowsT,selVars]-subN[subRows0,selVars])/ subN[subRows0,selVars] subIndxC = cbind(subN[subRowsT,selVars0],subIndx) res = rbind(res,subIndxC) } res[[var.agg[2]]] = as.numeric(as.character(res[[var.agg[2]]])) return(res) } eks = function(mat){ Idx = mat for(i in 1:nrow(mat)){ for(j in 1:ncol(mat)){ idx = vector('list',length=length(nrow(mat))) for(k in 1:nrow(mat)){ idx[[k]] = (mat[i,k]*mat[k,j])^(1/nrow(mat)) } Idx[i,j] = prod(unlist(idx)) } } return(Idx) } multilateral = function( data.x, data.y, idx='fisher', transitivity='mst', var.agg, bench, period, PAR=TRUE, plotting=FALSE, Cores){ if(!(idx %in% c('paasche','laspeyres','fisher','tornqvist'))){ stop("'idx' argument should be either 'paasche','laspeyres','fisher' or 'tornqvist'") } if(!(transitivity %in% c('eks','mst'))){ stop("'transitivity' argument should be either 'eks' or 'mst'") } if(!all(var.agg %in% names(data.x))){ stop("'var.agg' arguments should be among data columns names") } if(PAR==TRUE){ out = multicompPAR(data.x,data.y, idx=idx, transitivity=transitivity, var.agg=var.agg, bench=bench,period=period, plotting=plotting, Cores=Cores) }else{ out = multicomp(data.x,data.y, idx=idx, transitivity=transitivity, var.agg=var.agg, bench=bench,period=period, plotting=plotting) } if(transitivity=='mst' & length(var.agg)==2){ name = paste(data.x[,var.agg[2]],data.x[,var.agg[1]],sep='.') out = out[match(name,rownames(out)),] }else if(transitivity=='mst' & length(var.agg)==1){ name = data.x[,var.agg] out = out[match(name,rownames(out)),] } return(out) } chaining = function(data.x,data.y){ listIndex = list() listIndex[[1]]=cbind(1,1,1) colnames(listIndex[[1]]) = c('laspeyres','paasche','tornqvist') data.x = as.matrix(data.x) data.y = as.matrix(data.y) for(i in 1:(nrow(data.x)-1)){ listIndex[[i+1]] = indexes(data.x[i:(i+1),], data.y[i:(i+1),])$indexes[2,c('laspeyres','paasche','tornqvist')] } out = do.call('rbind',listIndex) out = as.data.frame(apply(out,2,function(x) cumprod(x))) out$fisher = sqrt(out$laspeyres * out$paasche) out$spreadPL = abs(log(out$laspeyres/out$paasche)) out = out[,c('laspeyres','paasche','fisher','tornqvist','spreadPL')] return(out) }
NULL ssoadmin <- function(config = list()) { svc <- .ssoadmin$operations svc <- set_config(svc, config) return(svc) } .ssoadmin <- list() .ssoadmin$operations <- list() .ssoadmin$metadata <- list( service_name = "ssoadmin", endpoints = list("*" = list(endpoint = "sso.{region}.amazonaws.com", global = FALSE), "cn-*" = list(endpoint = "sso.{region}.amazonaws.com.cn", global = FALSE), "us-iso-*" = list(endpoint = "sso.{region}.c2s.ic.gov", global = FALSE), "us-isob-*" = list(endpoint = "sso.{region}.sc2s.sgov.gov", global = FALSE)), service_id = "SSO Admin", api_version = "2020-07-20", signing_name = "sso", json_version = "1.1", target_prefix = "SWBExternalService" ) .ssoadmin$service <- function(config = list()) { handlers <- new_handlers("jsonrpc", "v4") new_service(.ssoadmin$metadata, handlers, config) }
sampleFrom <- function ( dstn, n = 1 ) { .assertClass(dstn, c("distribution", "mvdistribution")) sampleFun <- match.fun(paste("r", dstn@RName, sep = "")) do.call(sampleFun, c(n, as.list(dstn@parameters))) } .empCDF <- function(x, ordered = FALSE) { if(!ordered) x <- sort(x, decreasing = FALSE) probs <- seq(from = 0, to = 1, along = x) approxfun(x, probs) } .empQuantile <- function(x, ordered = FALSE) { if(!ordered) x <- sort(x, decreasing = FALSE) probs <- seq(from = 0, to = 1, along = x) approxfun(probs, x) }
vcgMeshres <- function(mesh) { if (!inherits(mesh,"mesh3d")) stop("argument 'mesh' needs to be object of class 'mesh3d'") mesh <- meshintegrity(mesh,facecheck=TRUE) vb <- mesh$vb[1:3,,drop=FALSE] it <- mesh$it-1 tmp <- .Call("Rmeshres",vb,it) return(tmp) }
setConstructorS3("ChipEffectFile", function(..., probeModel=c("pm")) { probeModel <- match.arg(probeModel) this <- extend(ParameterCelFile(...), "ChipEffectFile", "cached:.firstCells" = NULL, probeModel = probeModel ) setEncodeFunction(this, function(groupData, ...) { theta <- .subset2(groupData, "theta") stdvs <- .subset2(groupData, "sdTheta") outliers <- .subset2(groupData, "thetaOutliers") pixels <- NULL if (!is.null(outliers)) pixels <- -as.integer(outliers) res <- list() if (!is.null(theta)) res$intensities <- theta if (!is.null(stdvs)) res$stdvs <- stdvs if (!is.null(pixels)) res$pixels <- pixels res }) setDecodeFunction(this, function(groupData, ...) { res <- list() if (!is.null(groupData$intensities)) res$theta <- groupData$intensities if (!is.null(groupData$stdvs)) res$sdTheta <- groupData$stdvs if (!is.null(groupData$pixels)) res$thetaOutliers <- as.logical(-groupData$pixels) res }) setAttributesByTags(this) this }) setMethodS3("as.character", "ChipEffectFile", function(x, ...) { this <- x s <- NextMethod("as.character") s <- c(s, sprintf("Parameters: %s", getParametersAsString(this))) s }, protected=TRUE) setMethodS3("getParameters", "ChipEffectFile", function(this, ...) { params <- NextMethod("getParameters") params$probeModel <- this$probeModel params }, protected=TRUE) setMethodS3("createParamCdf", "ChipEffectFile", function(static, sourceCdf, ..., verbose=FALSE) { verbose <- Arguments$getVerbose(verbose) verbose && enter(verbose, "Creating CDF for chip effects") verbose && cat(verbose, "Source chip type: ", getChipType(sourceCdf)) verbose && cat(verbose, "Source CDF: ", getPathname(sourceCdf)) for (sep in c(",", "-")) { chipType <- paste(getChipType(sourceCdf), "monocell", sep=sep) verbose && cat(verbose, "Looking for chip type: ", chipType) pathname <- AffymetrixCdfFile$findByChipType(chipType) if (!is.null(pathname)) { verbose && cat(verbose, "Found: ", pathname) break } } if (is.null(pathname)) { verbose && cat(verbose, "Pathname: Not found!") verbose && cat(verbose, "Will create CDF for the chip-effect files from the original CDF. NOTE: This will take several minutes or more!") verbose && enter(verbose, "Creating CDF") cdf <- createMonocellCdf(sourceCdf, verbose=less(verbose)) verbose && exit(verbose) } else { verbose && cat(verbose, "Pathname: ", pathname) cdf <- AffymetrixCdfFile$fromFile(pathname) } verbose && exit(verbose) cdf }, static=TRUE, private=TRUE) setMethodS3("readUnits", "ChipEffectFile", function(this, units=NULL, cdf=NULL, ..., force=FALSE, cache=FALSE, verbose=FALSE) { verbose <- Arguments$getVerbose(verbose) key <- list(method="readUnits", class=class(this)[1], pathname=getPathname(this), cdf=cdf, units=units, ...) if (getOption(aromaSettings, "devel/useCacheKeyInterface", FALSE)) { key <- getCacheKey(this, method="readUnits", pathname=getPathname(this), cdf=cdf, units=units, ...) } id <- getChecksum(key) res <- this$.readUnitsCache[[id]] if (!force && !is.null(res)) { verbose && cat(verbose, "readUnits.ChipEffectFile(): Returning cached data") return(res) } if (is.null(cdf)) { cdf <- getCellIndices(this, units=units, verbose=less(verbose)) } res <- NextMethod("readUnits", cdf=cdf, force=force, verbose=less(verbose)) if (cache) { verbose && cat(verbose, "readUnits.ChipEffectFile(): Updating cache") this$.readUnitsCache <- list() this$.readUnitsCache[[id]] <- res } res }) setMethodS3("getCellIndices", "ChipEffectFile", function(this, ..., .cache=TRUE) { cdf <- getCdf(this) getCellIndices(cdf, ...) }, protected=TRUE) setMethodS3("updateUnits", "ChipEffectFile", function(this, units=NULL, cdf=NULL, data, ...) { if (is.null(cdf)) cdf <- getCellIndices(this, units=units) NextMethod("updateUnits", cdf=cdf, data=data) }, private=TRUE) setMethodS3("findUnitsTodo", "ChipEffectFile", function(this, units=NULL, ..., force=FALSE, verbose=FALSE) { verbose <- Arguments$getVerbose(verbose) if (verbose) { pushState(verbose) on.exit(popState(verbose)) } verbose && enter(verbose, "Identifying non-fitted units in chip-effect file") verbose && cat(verbose, "Pathname: ", getPathname(this)) idxs <- NULL if (is.null(units)) { cdf <- getCdf(this) chipType <- getChipType(cdf) key <- list(method="findUnitsTodo", class=class(this)[1], chipType=chipType, params=getParameters(this)) dirs <- c("aroma.affymetrix", chipType) if (!force) { idxs <- loadCache(key, dirs=dirs) if (!is.null(idxs)) verbose && cat(verbose, "Found indices cached on file") } } if (is.null(idxs)) { verbose && enter(verbose, "Identifying CDF units") units0 <- units if (is.null(units)) { cdf <- getCdf(this) units <- seq_len(nbrOfUnits(cdf)) } nbrOfUnits <- length(units) idxs <- lapplyInChunks(units, function(unitsChunk, ...) { verbose && enter(verbose, "Reading CDF cell indices") idxsChunk <- getCellIndices(this, units=unitsChunk, force=TRUE, verbose=less(verbose)) names(idxsChunk) <- NULL verbose && exit(verbose) verbose && enter(verbose, "Extracting first CDF group for each unit") idxsChunk <- lapply(idxsChunk, FUN=function(unit) { groups <- .subset2(unit, "groups") fields <- .subset2(groups, 1) .subset2(fields, 1) }) verbose && exit(verbose) gc <- gc() idxsChunk }, chunkSize=100e3, useNames=FALSE, verbose=verbose) units <- units0 units0 <- NULL idxs <- unlist(idxs, use.names=FALSE) gc <- gc() verbose && print(verbose, gc) if (length(idxs) != nbrOfUnits) { throw("Internal error: Expected ", nbrOfUnits, " cell indices, but got ", length(idxs), ".") } if (is.null(units)) { verbose && enter(verbose, "Saving to file cache") saveCache(idxs, key=key, dirs=dirs) verbose && exit(verbose) } verbose && exit(verbose) } verbose && enter(verbose, "Reading data for these ", length(idxs), " cells") value <- .readCel(getPathname(this), indices=idxs, readIntensities=FALSE, readStdvs=TRUE, readPixels=FALSE)$stdvs verbose && exit(verbose) value <- which(value <= 0) if (!is.null(units)) value <- units[value] verbose && cat(verbose, "Looking for stdvs <= 0 indicating non-estimated units:") verbose && str(verbose, value) verbose && exit(verbose) value }) setMethodS3("getUnitGroupCellMap", "ChipEffectFile", function(this, units=NULL, force=FALSE, ..., verbose=FALSE) { if (inherits(units, "UnitGroupCellMap")) { return(units) } else if (is.null(units)) { } else if (is.list(units)) { } else { units <- Arguments$getIndices(units) } verbose <- Arguments$getVerbose(verbose) if (verbose) { pushState(verbose) on.exit(popState(verbose)) } verbose && enter(verbose, "Retrieving unit-to-cell map") if (length(units) == 0 && !is.null(units)) { map <- data.frame(unit=integer(0), group=integer(0), cell=integer(0)) class(map) <- c("UnitGroupCellMap", class(map)) verbose && exit(verbose) return(map) } cdf <- getCdf(this) useFileCache <- (is.null(units) || (!is.list(units) && length(units) > 100)) if (useFileCache) { chipType <- getChipType(cdf) key <- list(method="getUnitGroupCellMap", class=class(this)[1], chipType=chipType, params=getParameters(this), units=units) dirs <- c("aroma.affymetrix", chipType) if (!force) { map <- loadCache(key, dirs=dirs) if (!is.null(map)) { verbose && cat(verbose, "Found (unit,group,cell) map cached on file") verbose && exit(verbose) return(map) } } } if (is.list(units)) { cells <- units units <- indexOf(cdf, names=names(units)) if (any(is.na(units))) { throw("Argument 'units' is of unknown structure.") } verbose && enter(verbose, "Argument 'cells' is already a CDF cell-index structure") unitNames <- names(cells) unitSizes <- lapply(cells, FUN=function(unit) { length(.subset2(unit, "groups")) }) unitSizes <- unlist(unitSizes, use.names=FALSE) cells <- unlist(cells, use.names=FALSE) } else { verbose && enter(verbose, "Retrieving cell indices for specified units") if (is.null(units)) units <- seq_len(nbrOfUnits(cdf)) chunks <- splitInChunks(units, chunkSize=100e3) nbrOfChunks <- length(chunks) nbrOfUnits <- length(units) unitNames <- vector("character", nbrOfUnits) unitSizes <- vector("integer", nbrOfUnits) cells <- vector("list", nbrOfChunks) offset <- 0 for (kk in seq_len(nbrOfChunks)) { verbose && printf(verbose, "Chunk chunk <- chunks[[kk]] chunks[[kk]] <- NA cells0 <- getCellIndices(this, units=chunk, force=force, .cache=FALSE, verbose=less(verbose)) idxs <- offset + seq_along(chunk) offset <- offset + length(chunk) chunk <- NULL unitNames[idxs] <- names(cells0) names(cells0) <- NULL unitSizes0 <- lapply(cells0, FUN=function(unit) { length(.subset2(unit, "groups")) }) unitSizes[idxs] <- unlist(unitSizes0, use.names=FALSE) unitSizes0 <- NULL cells[[kk]] <- unlist(cells0, use.names=FALSE) cells0 <- idxs <- NULL } chunks <- NULL gc <- gc() verbose && print(verbose, gc) } cells <- unlist(cells, use.names=FALSE) gc <- gc() verbose && exit(verbose) verbose && enter(verbose, "Creating return data frame") uUnitSizes <- sort(unique(unitSizes)) verbose && cat(verbose, "Unique number of groups per unit: ", paste(uUnitSizes, collapse=",")) verbose && cat(verbose, "Number of units: ", length(unitNames)) if (is.null(units)) units <- seq_len(nbrOfUnits(cdf)) verbose && printf(verbose, "Allocating matrix of size %dx%d.\n", max(uUnitSizes), length(unitNames)) naValue <- as.integer(NA) units2 <- groups <- matrix(naValue, nrow=max(uUnitSizes), ncol=length(unitNames)) for (size in uUnitSizes) { cc <- which(unitSizes == size) seq <- seq_len(size) groups[seq,cc] <- seq units2[seq,cc] <- rep(units[cc], each=size) seq <- NULL gc <- gc() } keep <- !is.na(groups) groups <- groups[keep] units2 <- units2[keep] keep <- NULL gc <- gc() map <- data.frame(unit=units2, group=groups, cell=cells) verbose && exit(verbose) verbose && exit(verbose) class(map) <- c("UnitGroupCellMap", class(map)) if (useFileCache) { verbose && enter(verbose, "Saving to file cache") saveCache(map, key=key, dirs=dirs) verbose && exit(verbose) } map }, private=TRUE) setMethodS3("getUnitGroupCellChromosomePositionMap", "ChipEffectFile", function(this, units=NULL, chromosomes=NULL, orderByPosition=TRUE, ..., force=FALSE, verbose=FALSE) { cdf <- getCdf(this) ugcMap <- NULL if (is.null(units)) { } else if (isUnitGroupCellMap(units)) { ugcMap <- units units <- ugcMap[,"unit"] } if (!is.null(units)) { units <- Arguments$getIndices(units, range=c(1, nbrOfUnits(cdf))) } units0 <- units gi <- getGenomeInformation(cdf) if (!is.null(chromosomes)) { allChromosomes <- getChromosomes(gi) unknown <- chromosomes[!(chromosomes %in% allChromosomes)] if (length(unknown) > 0) { throw("Argument 'chromosomes' contains unknown values: ", paste(unknown, collapse=", ")) } } verbose <- Arguments$getVerbose(verbose) if (verbose) { pushState(verbose) on.exit(popState(verbose)) } verbose && enter(verbose, "Getting (unit, group, cell, chromosome, position) map") verbose && enter(verbose, "Checking cache") chipType <- getChipType(cdf) key <- list(method="getUnitGroupCellChromosomePositionMap", class=class(this)[1], chipType=chipType, units=units, ugcMap=ugcMap, chromosomes=chromosomes, orderByPosition=orderByPosition) dirs <- c("aroma.affymetrix", chipType) if (!force) { map <- loadCache(key=key, dirs=dirs) if (!is.null(map)) { verbose && cat(verbose, "Found cached results") verbose && exit(verbose) return(map) } } if (!is.null(chromosomes)) { verbose && cat(verbose, "Units:") verbose && str(verbose, units) verbose && cat(verbose, "Subset by chromosomes:") verbose && str(verbose, chromosomes) units <- getUnitsOnChromosomes(gi, chromosomes) verbose && cat(verbose, "Units:") verbose && str(verbose, units) if (!is.null(units0)) { units <- intersect(units, units0) } } verbose && cat(verbose, "Units:") verbose && str(verbose, units) if (!isUnitGroupCellMap(ugcMap)) { ugcMap <- getUnitGroupCellMap(this, units=units, force=force, verbose=less(verbose, 10)) verbose && cat(verbose, "(unit, group, cell) map:") verbose && str(verbose, ugcMap) } cpMap <- getData(gi, units=ugcMap[,"unit"], force=force, verbose=less(verbose, 10)) verbose && cat(verbose, "(chromosome, position) map:") verbose && str(verbose, cpMap) stopifnot(nrow(ugcMap) == nrow(cpMap)) map <- cbind(ugcMap, cpMap) ugcMap <- cpMap <- NULL if (orderByPosition) { o <- with(map, order(chromosome, physicalPosition)) map <- map[o,,drop=FALSE] o <- NULL verbose && cat(verbose, "Reordered by genomic position") } rownames(map) <- NULL if (object.size(map) > 50e3) { saveCache(map, key=key, dirs=dirs) verbose && cat(verbose, "Saved to file cache") } verbose && exit(verbose) map }, private=TRUE) setMethodS3("getDataFlat", "ChipEffectFile", function(this, units=NULL, fields=c("theta", "sdTheta", "outliers"), ..., verbose=FALSE) { verbose <- Arguments$getVerbose(verbose) if (verbose) { pushState(verbose) on.exit(popState(verbose)) } verbose && enter(verbose, "Retrieving data as a flat data frame") suppressWarnings({ map <- getUnitGroupCellMap(this, units=units, ..., verbose=less(verbose)) }) verbose && enter(verbose, "Reading data fields") celFields <- c(theta="intensities", sdTheta="stdvs", outliers="pixels") suppressWarnings({ data <- getData(this, indices=map[,"cell"], fields=celFields[fields]) }) rownames(data) <- seq_len(nrow(data)); names <- colnames(data) names <- gsub("intensities", "theta", names) names <- gsub("stdvs", "sdTheta", names) names <- gsub("pixels", "outliers", names) colnames(data) <- names verbose && str(verbose, data) if ("outliers" %in% names) { data[,"outliers"] <- as.logical(-data[,"outliers"]) } verbose && exit(verbose) len <- sapply(data, FUN=length) keep <- (len == nrow(map)) data <- data[keep] data <- as.data.frame(data) data <- cbind(map, data) verbose && exit(verbose) data }, private=TRUE) setMethodS3("updateDataFlat", "ChipEffectFile", function(this, data, ..., verbose=FALSE) { names <- colnames(data) namesStr <- paste(names, collapse=", ") if (!"cell" %in% names) throw("Argument 'data' must contain a column 'cell': ", namesStr) verbose <- Arguments$getVerbose(verbose) if (verbose) { pushState(verbose) on.exit(popState(verbose)) } verbose2 <- -as.integer(verbose)-2 verbose && enter(verbose, "Storing flat data to file") if ("outliers" %in% names) { data[,"outliers"] <- -as.integer(data[,"outliers"]) } names <- gsub("theta", "intensities", names) names <- gsub("sdTheta", "stdvs", names) names <- gsub("outliers", "pixels", names) colnames(data) <- names verbose && enter(verbose, "Updating file") indices <- data[,"cell"] keep <- (names %in% c("intensities", "stdvs", "pixels")) data <- data[,keep] pathname <- getPathname(this) pathname <- Arguments$getWritablePathname(pathname) .updateCel(pathname, indices=indices, data, verbose=verbose2) verbose && exit(verbose) verbose && exit(verbose) invisible(data) }, private=TRUE) setMethodS3("mergeGroups", "ChipEffectFile", function(this, fcn, fields=c("theta", "sdTheta"), ..., pathname, overwrite=FALSE, verbose=FALSE) { if (!is.function(fcn)) { throw("Argument 'fcn' is not a function: ", class(fcn)[1]) } pathname <- Arguments$getWritablePathname(pathname, mustNotExist=!overwrite) verbose <- Arguments$getVerbose(verbose) if (verbose) { pushState(verbose) on.exit(popState(verbose)) } verbose && enter(verbose, "Merging groups") verbose && enter(verbose, "Testing merge function") for (size in 1:10) { y <- matrix(1000+1:(size*4), nrow=size) yOut <- fcn(y) if (!identical(dim(yOut), dim(y))) { throw("Function 'fcn' must not change the dimension of the data: ", paste(dim(yOut), collapse="x"), " != ", paste(dim(y), collapse="x")) } } verbose && exit(verbose) map <- getUnitGroupCellMap(this, verbose=less(verbose)) verbose && str(verbose, map) uSizes <- sort(unique(data[,"group"])) verbose && cat(verbose, "Different number of groups per unit identified:") verbose && print(verbose, uSizes) data <- getDataFlat(this, units=map, ..., verbose=less(verbose)) verbose && str(verbose, data) for (size in rev(uSizes)) { verbose && enter(verbose, "Unit size ", size) idxs <- which(data[,"group"] == size) unitsS <- data[idxs, "unit"] idxs <- which(data[,"unit"] %in% unitsS) for (field in fields) { y <- data[idxs, field] y <- matrix(y, nrow=size) verbose && str(verbose, y) y <- fcn(y) verbose && str(verbose, y) data[idxs, field] <- as.vector(y) } verbose && exit(verbose) } verbose && enter(verbose, "Storing merged data") verbose && cat(verbose, "Pathname: ", pathname) verbose && enter(verbose, "Creating CEL file for results, if missing") cfN <- createFrom(this, filename=pathname, path=NULL, methods="create", clear=TRUE, verbose=less(verbose)) verbose && print(verbose, cfN) verbose && exit(verbose) verbose && enter(verbose, "Writing merged data") updateDataFlat(cfN, data=data, verbose=less(verbose)) verbose && exit(verbose) verbose && exit(verbose) verbose && exit(verbose) cfN }, protected=TRUE) setMethodS3("extractMatrix", "ChipEffectFile", function(this, ..., field=c("theta", "sdTheta")) { field <- match.arg(field) NextMethod("extractMatrix", field=field) })
.inputPrep <- function(..., spatialData, response, sigmavar, rr, longlat, nGibbs, nBurn, nThin, x, sigma2_beta, sigma2_xi, lambda, dB, gbf, Qprior, nw, knots, ffdir, localCluster, wishartScale, dMax, cage) { spatialData <- .checkSpatialData(spatialData = spatialData) nw <- .checkNW(spatialData = spatialData, nw = nw) dB <- .checkDB(dB = dB, spatialData = spatialData, cage = cage) cage <- dB$cage dB <- dB$dB response <- .verifyNumericVector(spatialData = spatialData, numVec = response, nm = 'response') x <- .verifyCovariates(spatialData = spatialData, x = x) sigmavar <- .verifyNumericVector(spatialData = spatialData, numVec = sigmavar, nm = 'sigmavar') nBurn <- as.integer(x = round(x = nBurn, digits = 0L)) if (nBurn <= 0L) { message("nBurn reset to 100") nBurn <- 100L } nThin <- as.integer(x = round(x = nThin, digits = 0L)) if (nThin <= 0L) { message("nThin reset to 1") nThin <- 1L } gibbsKeep <- tryCatch(expr = seq(from = {nBurn+1L}, to = nGibbs, by = nThin), condition = function(e){ stop(e$message) }) message("Gibbs sampler will keep ", length(x = gibbsKeep), " samples") tst <- .verifyffdir(ffdir = ffdir, nKept = length(x = gibbsKeep), nR = length(x = response)) finestOnSource <- .hMatrix(spatialData = spatialData, dB = dB) message("h matrix generated") gbfObj <- .verifyGBF(gbf = gbf, weight = rr, knots = knots, longlat = longlat, spatialData = spatialData, dB = dB) Qprior <- .verifyQPrior(qPrior = Qprior) message("Source Support") basis <- .obledCruetinBasis(spatialData = spatialData, dB = dB, gbfObj = gbfObj, nw = nw, localCluster = localCluster, verify = TRUE) gbfObj <- basis$gbfObj message("Finest Support") idB <- NA if (is.null(x = dB)) { message("\tusing source support basis") basisdB <- basis$phiOC } else if (is.integer(x = dB)) { basisdB <- .generatingBasis(spatialData = spatialData[[ dB ]], nw = nw, gbfObj = gbfObj, db = min(10000L, nw), localCluster = localCluster) basisdB <- basisdB %*% basis$OCnorm ortho <- t(x = basisdB) %*% basisdB for (i in 1L:ncol(x = basisdB)) { basisdB[,i] <- basisdB[,i] / sqrt(ortho[i,i]) } } else { basisdB <- .generatingBasis(spatialData = dB, nw = nw, gbfObj = gbfObj, db = min(10000L, nw), localCluster = localCluster) basisdB <- basisdB %*% basis$OCnorm ortho <- t(x = basisdB) %*% basisdB for (i in 1L:ncol(x = basisdB)) { basisdB[,i] <- basisdB[,i] / sqrt(ortho[i,i]) } } Qprior <- .qInv(qObj = Qprior, basisdB = basisdB, lambda = lambda, scale = wishartScale, spatialData = spatialData, dB = dB, dMax = dMax) naResponse <- is.na(x = response) | is.nan(x = response) if (sum(naResponse) > 0L) { message("excluding ", sum(naResponse), " cases from Gibbs due to incomplete response data") } notna <- !naResponse spatialOnFinest <- Matrix::Matrix(data = t(x = finestOnSource[,notna,drop=FALSE]), sparse = TRUE) isEmpty <- colSums(as.matrix(x = spatialOnFinest) > 1e-8) == 0L if (any(isEmpty)) { message("excluding ", sum(isEmpty), " elements of D_B from Gibbs step for lack of data") spatialOnFinest <- spatialOnFinest[,!isEmpty] } if (is.matrix(x = sigmavar)) { tsigmavar <- sigmavar[notna,notna,drop=FALSE] } else { tsigmavar <- sigmavar[notna] } gibbsSamples <- .gibbs(Z = response[notna], X = x[notna,,drop=FALSE], H = spatialOnFinest, psi = basis$phiOC[notna,,drop=FALSE], sigma2_eps = tsigmavar, sigma2_beta = sigma2_beta, sigma2_xi = sigma2_xi, qObj = Qprior, gibbsKeep = gibbsKeep, ffdir = ffdir) message("finished Gibbs sampling") if (any(isEmpty)) { xi <- .makeStorage(ffdir = ffdir, nrow = nrow(x = finestOnSource), ncol = ncol(x = gibbsSamples$xi)) for (i in 1L:ncol(x = gibbsSamples$xi)) { xi[!isEmpty,i] <- gibbsSamples$xi[,i] } gibbsSamples$xi <- xi } yFinest <- .yFinest(ffdir = ffdir, gibbsSamples = gibbsSamples, x = x, spatialData = spatialData, dB = dB, basisdB = basisdB, fos = finestOnSource) if (is.null(x = dB)) { finestAreas <- .getArea(spatialData = spatialData, byid = TRUE) } else if (is.numeric(x = dB)) { finestAreas <- .getArea(spatialData = spatialData[[ dB ]], byid = TRUE) } else { finestAreas <- .getArea(spatialData = dB, byid = TRUE) } ySource <- .yCageSource(ffdir = ffdir, gibbsSamples = gibbsSamples, x = x, spatialData = spatialData, cage = cage, basis = basis, H = t(x = finestOnSource)) fos <- ySource$indicator %*% t(x = finestOnSource) isEmpty <- rowSums(as.matrix(x = finestOnSource) > 1e-8) == 0L return( list("gibbs" = gibbsSamples, "yFinest" = yFinest, "finestAreas" = finestAreas, "psi" = basis, "dB" = dB, "gbfObj" = gbfObj, "nw" = nw, "ySource" = ySource$ySource, "finestOnSource" = fos, "sourceAreas" = ySource$areas, "criterion" = cage, "isEmpty" = isEmpty) ) }
setwdKTS <- function() { dirPath <- tcltk::tk_choose.dir() if (is.na(dirPath) == FALSE) { setwd(dirPath) } }
.print_bayesx <- function(x, digits = max(3L, getOption("digits") - 3L), ...) { if(!is.null(x$call)) { cat("Call:\n") print(x$call) } else { if(!is.null(x$model.fit$formula)) { cat("Formula:\n") if(is.character(x$model.fit$formula)) cat(x$model.fit$formula, "\n") else print(x$model.fit$formula) } } if(!is.null(x$model.fit)) { cat("Summary:\n") mfn <- names(x$model.fit) mfn <- mfn[mfn != "formula" & mfn != "order" & mfn != "YLevels" & mfn != "nYLevels" & mfn != "model.name"] step <- 5L for(i in 1L:length(mfn)) { txt <- x$model.fit[[mfn[i]]] if(is.numeric(txt)) txt <- round(txt, digits) txt <- deparse(txt) if(i < step) { if(!is.null(txt) && txt != "") { if(mfn[i] != "step.final.model") cat(mfn[i], "=", gsub('\"', "", txt, fixed = TRUE), " ") } } if(i == step) { if(i != length(mfn)) cat("\n") step <- step + step } } cat("\n") } return(invisible(NULL)) } .print_summary_bayesx <- function(x, digits = max(3L, getOption("digits") - 3L), signif.stars = getOption("show.signif.stars"), ...) { if(!is.null(x$model.fit)) if(!is.null(x$model.fit$model.name)) if(length(grep("_hlevel", x$model.fit$model.name))) { hlevel <- splitme(strsplit(x$model.fit$model.name, "_hlevel")[[1]][2]) go <- TRUE hl <- NULL for(i in 1:length(hlevel)) { if(hlevel[i] == "_") go <- FALSE if(go) hl <- c(hl, hlevel[i]) } hlevel <- as.integer(resplit(hl)) if(hlevel > 1) cat("Hierarchical random effects model results: stage", hlevel, "\n") else { cat("Main effects model results: stage", hlevel, "\n") cat("\n") } } if(!is.null(x$call)) { cat("Call:\n") cat(paste(deparse(x$call), sep = "\n", collapse = "\n"), "\n", sep = "") } else { if(!is.null(x$model.fit$formula)) { cat("Formula:\n") if(is.character(x$model.fit$formula)) cat(x$model.fit$formula, "\n") else print(x$model.fit$formula, showEnv = FALSE) } } liner <- "" fc <- FALSE if(!is.null(x$fixed.effects)) { fc <- TRUE if(nrow(x$fixed.effects) < 2L) { if(!any(is.na(x$fixed.effects)) && all(x$fixed.effects[1L,] == 0)) fc <- FALSE } else { if(!all(as.character(x$fixed.effects) == "NaN") && all(x$fixed.effects[1L,] == 0)) { m <- ncol(x$fixed.effects) nc <- colnames(x$fixed.effects) nr <- rownames(x$fixed.effects)[2L:nrow(x$fixed.effects)] x$fixed.effects <- matrix(x$fixed.effects[2L:nrow(x$fixed.effects),], ncol = m) colnames(x$fixed.effects) <- nc rownames(x$fixed.effects) <- nr } } x$fixed.effects <- round(x$fixed.effects, digits) } if(fc || (!is.null(x$smooth.hyp))) { cat(liner, "\n") cat("Fixed effects estimation results:\n") cat("\n") } if(fc) { cat("Parametric coefficients:\n") printCoefmat(x$fixed.effects) } if(!is.null(x$smooth.hyp)) { if(fc) cat("\n") if(x$model.fit$method == "MCMC" || x$model.fit$method == "HMCMC") cat("Smooth terms variances:\n") else cat("Smooth terms:\n") ls <- ncol(x$smooth.hyp) terms <- colnames(x$smooth.hyp) rn <- rownames(x$smooth.hyp) x$smooth.hyp <- round(x$smooth.hyp, digits) printCoefmat(x$smooth.hyp) } cat(liner, "\n") if(!is.null(x$random.hyp)) { cat("Random effects variances:\n") x$random.hyp <- round(x$random.hyp, digits) printCoefmat(x$random.hyp) cat(liner, "\n") } if(!is.null(x$model.fit)) { if(x$model.fit$method == "MCMC") { if(!is.null(x$variance)) { cat("Scale estimate:\n") x$variance <- round(x$variance, digits) printCoefmat(x$variance) cat(liner, "\n") } } else { if(!is.null(x$variance)) { cat("Scale estimate:", round(as.numeric(x$variance)[1], digits), "\n") cat(liner, "\n") } } x$model.fit <- delete.NULLs(x$model.fit) mfn <- names(x$model.fit) step <- 5L mfn <- mfn[!is.null(x$model.fit)] mfn <- mfn[mfn != "model.name"] mfn <- mfn[mfn != "formula"] mfn <- mfn[mfn != "step.final.model"] mfn <- mfn[mfn != "YLevels"] mfn <- mfn[mfn != "nYLevels"] mfn <- mfn[mfn != "order"] if(is.na(x$model.fit$N)) x$model.fit$N <- "NA" if(x$model.fit$method == "") x$model.fit$method <- "NA" for(i in 1L:length(mfn)) { if(!is.null(x$model.fit[[mfn[i]]]) && !is.na(x$model.fit[[mfn[i]]] != "")) { if(length(splitme(as.character(x$model.fit[[mfn[i]]])))) { if(i < step) cat(mfn[i], "=", x$model.fit[[mfn[i]]], " ") if(i == step) { if(i != length(mfn)) cat("\n") cat(mfn[i], "=", x$model.fit[[mfn[i]]], " ") step <- step + step } } } } cat("\n") } return(invisible(NULL)) }
subsetByRegion <- function(data, region, margin = 1/2) { UseMethod("subsetByRegion") } subsetByRegion.TopDomData <- function(data, region, margin = 1/2) { stopifnot(is.data.frame(region)) stopifnot(margin >= 0) if (margin < 1) { margin <- margin * (region$to.coord - region$from.coord) } idxs <- with(data$bins, which(chr == region$chr & from.coord >= region$from.coord - margin & to.coord <= region$to.coord + margin)) data[idxs] } subsetByRegion.TopDom <- function(data, region, margin = 1/2) { stopifnot(is.data.frame(region)) stopifnot(margin >= 0) if (margin < 1) { margin <- margin * (region$to.coord - region$from.coord) } idxs <- with(data$domain, which(chr == region$chr & from.coord >= region$from.coord - margin & to.coord <= region$to.coord + margin)) data[idxs, ] }
callBAplot = function(x, censortime, main, xlab, ylab, plot.type, smooth.graph, smooth.df, combine.graphs, alpha.level, conf.int, log.ratio){ firstgroup = substr(colnames(x)[2], 4, 4) dnames = colnames(x)[which(substr(colnames(x), 1, 1) == 'd')] numbins = length(which(unlist(strsplit(dnames, '_'))[1:length(dnames)*2] == firstgroup)) M = log(numbins)/log(2) hazgroups = unique(unlist(strsplit(dnames, '_'))[1:length(dnames)*2]) numhazards = length(hazgroups) if(plot.type == 'r'){ if(log.ratio != TRUE){ start.betas = substr(colnames(x), 1, 4) end.betas = substr(colnames(x), nchar(colnames(x))-3, nchar(colnames(x))) beta.nphindex = 1:(2^M*(numhazards-1)) + which(start.betas == 'beta' & end.betas == 'bin1')[1] - 1 x[,beta.nphindex] = exp(x[,beta.nphindex]) } dests.temp = summary.MRH(x, alpha.level = alpha.level, maxStudyTime = censortime)$beta end.betas = substr(row.names(dests.temp), nchar(row.names(dests.temp))-3, nchar(row.names(dests.temp))) beta.nph.index = 1:(2^M*(numhazards-1))+which(end.betas == 'bin1')[1]-1 dests.temp = dests.temp[beta.nph.index,] } else if(!missing(censortime)){ dests.temp = t(CalcFunction(x, function.type = plot.type, alpha.level = alpha.level, maxStudyTime = censortime)[[1]])[,c(2,1,3)] } else { dests.temp = t(CalcFunction(x, function.type = plot.type, alpha.level = alpha.level)[[1]])[,c(2,1,3)] } if(plot.type %in% c('H','S')){ dests.temp = dests.temp[-((1:numhazards-1)*(2^M+1)+1),] } if(smooth.graph == TRUE){ if(is.null(smooth.df)){ smooth.df = 2^M/2 } smooth.timepts = 1:2^M*censortime/2^M-.5*censortime/2^M dests = NULL for(ctr in 1:(numhazards-1)){ dests = rbind(dests, cbind(smooth.spline(dests.temp[1:2^M+2^M*(ctr-1),1]~smooth.timepts, df = smooth.df)$y, smooth.spline(dests.temp[1:2^M+2^M*(ctr-1),2]~smooth.timepts, df = smooth.df)$y, smooth.spline(dests.temp[1:2^M+2^M*(ctr-1),3]~smooth.timepts, df = smooth.df)$y)) } if(plot.type != 'r'){ ctr = numhazards dests = rbind(dests, cbind(smooth.spline(dests.temp[1:2^M+2^M*(ctr-1),1]~smooth.timepts, df = smooth.df)$y, smooth.spline(dests.temp[1:2^M+2^M*(ctr-1),2]~smooth.timepts, df = smooth.df)$y, smooth.spline(dests.temp[1:2^M+2^M*(ctr-1),3]~smooth.timepts, df = smooth.df)$y)) } plot.timepts = smooth.timepts max.index = 2^M } else { plot.timepts = pbfxn(2^M, censortime/2^M, rep(NA, 2^M))$x dests = NULL for(ctr in 1:(numhazards-1)){ dests = rbind(dests, cbind(pbfxn(2^M, censortime/2^M, dests.temp[1:2^M+2^M*(ctr-1),1])$y, pbfxn(2^M, censortime/2^M, dests.temp[1:2^M+2^M*(ctr-1),2])$y, pbfxn(2^M, censortime/2^M, dests.temp[1:2^M+2^M*(ctr-1),3])$y)) } if(plot.type != 'r'){ ctr = numhazards dests = rbind(dests, cbind(pbfxn(2^M, censortime/2^M, dests.temp[1:2^M+2^M*(ctr-1),1])$y, pbfxn(2^M, censortime/2^M, dests.temp[1:2^M+2^M*(ctr-1),2])$y, pbfxn(2^M, censortime/2^M, dests.temp[1:2^M+2^M*(ctr-1),3])$y)) } max.index = 2^M*2 } ylabel = 'Hazard rate' if('H' == plot.type){ ylabel = 'Cumulative hazard' } else if('S' == plot.type){ ylabel = 'Survival function' } else if('r' == plot.type){ if(log.ratio == TRUE){ ylabel = 'Log hazard ratio' } else { ylabel = 'Hazard ratio' } } timeptslabel = plot.timepts ylimit = range(dests) if(conf.int != TRUE){ ylimit = range(dests[,1]) } if(plot.type == 'S'){ ylimit[1] = 0 } if(combine.graphs != TRUE){ if('r' != plot.type){ plotnums = c(ceiling(numhazards/2), 2) numplots = numhazards mainnames = paste(hazgroups, 'group') mtextname = 'Hazard Rates by Group' } else { if(numhazards > 2){ plotnums = c(ceiling((numhazards-1)/2), 2) } else { plotnums = c(1,1) } numplots = numhazards-1 mainnames = paste('Group', hazgroups[-1]) if(log.ratio == TRUE){ mtextname = paste('Log hazard Ratios: Comparison to Group', hazgroups[1]) } else { mtextname = paste('Hazard Ratios: Comparison to Group', hazgroups[1]) } } par(mfrow = plotnums, mai = c(.35, .1, .25, 0), oma = c(0, 2, 2, 1), tck = -.02) for(hazCtr in 1:numplots){ plot(plot.timepts, dests[1:max.index+max.index*(hazCtr-1),1], type = 'l', lwd = 3, ylab = '', xlab = '', ylim = ylimit, main = mainnames[hazCtr], axes = FALSE) if(plot.type == 'r'){ if(log.ratio == TRUE){ abline(h = 0, col = 'grey') } else { abline(h = 1, col = 'grey') } } if(conf.int == TRUE){ points(plot.timepts, dests[1:max.index+max.index*(hazCtr-1),2], type = 'l', lty = 2) points(plot.timepts, dests[1:max.index+max.index*(hazCtr-1),3], type = 'l', lty = 2) } box() axis(1, at = timeptslabel, labels = round(timeptslabel, 1), cex.axis = .75, padj = -2) mtext('Time', side = 1, padj = 1.5, cex = .8) if(hazCtr %% 2 != 0){ axis(2, padj = 1.25) } } mtext(mtextname, outer = TRUE, cex = 1.4) } else { plot(plot.timepts, dests[1:max.index,1], type = 'l', lwd = 2, xlab = 'Time', ylab = ylabel, main = ylabel, ylim = ylimit) if(plot.type == 'r'){ if(log.ratio == TRUE){ abline(h = 0, col = 'grey') } else { abline(h = 1, col = 'grey') } } if(conf.int == TRUE){ points(plot.timepts, dests[1:max.index,2], type = 'l', lty = 2) points(plot.timepts, dests[1:max.index,3], type = 'l', lty = 2) } if((plot.type != 'r') | (plot.type == 'r' & numhazards > 2)){ for(hazCtr in 2:(numhazards-1)){ points(plot.timepts, dests[1:max.index+max.index*(hazCtr-1), 1], type = 'l', lwd = 2, col = hazCtr) if(conf.int == TRUE){ points(plot.timepts, dests[1:max.index+max.index*(hazCtr-1), 2], type = 'l', lty = 2, col = hazCtr) points(plot.timepts, dests[1:max.index+max.index*(hazCtr-1), 3], type = 'l', lty = 2, col = hazCtr) } } } if(plot.type != 'r'){ hazCtr = numhazards points(plot.timepts, dests[1:max.index+max.index*(hazCtr-1), 1], type = 'l', lwd = 2, col = hazCtr) if(conf.int == TRUE){ points(plot.timepts, dests[1:max.index+max.index*(hazCtr-1), 2], type = 'l', lty = 2, col = hazCtr) points(plot.timepts, dests[1:max.index+max.index*(hazCtr-1), 3], type = 'l', lty = 2, col = hazCtr) } legend(x = "topright", paste('group', hazgroups), fill = 1:numhazards, cex = 1.2) } else { legend(x = "topright", paste('group', hazgroups[-1]), fill = 2:numhazards-1, cex = 1.2) } } }
context("conditions") test_that("stop_bad_type() stores fields", { err <- catch_cnd(stop_bad_type(NA, "`NULL`", actual = "a foobaz", arg = ".foo")) expect_is(err, "purrr_error_bad_type") expect_identical(err$x, NA) expect_identical(err$expected, "`NULL`") expect_identical(err$actual, "a foobaz") expect_identical(err$arg, ".foo") }) test_that("stop_bad_type() constructs default `what`", { expect_error_cnd( stop_bad_type(NA, "`NULL`"), "Object must be `NULL`", "purrr_error_bad_type" ) expect_error_cnd( stop_bad_type(NA, "`NULL`", arg = ".foo"), "`.foo` must be `NULL`", "purrr_error_bad_type" ) expect_error_cnd( stop_bad_type(NA, "`NULL`", arg = quote(.foo)), "`arg` must be `NULL` or a string, not a symbol", "purrr_error_bad_type" ) }) test_that("stop_bad_element_type() constructs type errors", { expect_error_cnd( stop_bad_element_type(1:3, 3, "a foobaz"), "Element 3 must be a foobaz, not an integer vector", "purrr_error_bad_element_type" ) expect_error_cnd( stop_bad_element_type(1:3, 3, "a foobaz", actual = "a quux"), "Element 3 must be a foobaz, not a quux", "purrr_error_bad_element_type" ) expect_error_cnd( stop_bad_element_type(1:3, 3, "a foobaz", arg = "..arg"), "Element 3 of `..arg` must be a foobaz, not an integer vector", "purrr_error_bad_element_type" ) }) test_that("stop_bad_element_type() accepts `what`", { expect_error_cnd( stop_bad_element_type(1:3, 3, "a foobaz", what = "Result"), "Result 3 must be a foobaz, not an integer vector", "purrr_error_bad_element_type" ) }) test_that("stop_bad_length() stores fields", { err <- catch_cnd(stop_bad_length(1:3, 10, actual = 100, arg = ".foo")) expect_is(err, "purrr_error_bad_length") expect_identical(err$x, 1:3) expect_identical(err$expected_length, 10) expect_identical(err$arg, ".foo") }) test_that("stop_bad_length() constructs error message", { expect_error_cnd(stop_bad_length(1:3, 10), "Vector must have length 10, not 3", "purrr_error_bad_length") expect_error_cnd(stop_bad_length(1:3, 10, arg = ".foo"), "`.foo` must have length 10, not 3", "purrr_error_bad_length") expect_error_cnd(stop_bad_length(1:3, 10, arg = ".foo", what = "This thing"), "This thing must have length 10, not 3", "purrr_error_bad_length") expect_error_cnd(stop_bad_length(1:3, 10, arg = ".foo", what = "This thing", recycle = TRUE), "This thing must have length 1 or 10, not 3", "purrr_error_bad_length") }) test_that("stop_bad_element_length() constructs error message", { expect_error_cnd(stop_bad_element_length(1:3, 8, 10), "Element 8 must have length 10, not 3", "purrr_error_bad_element_length") expect_error_cnd(stop_bad_element_length(1:3, 8, 10, arg = ".foo"), "Element 8 of `.foo` must have length 10, not 3", "purrr_error_bad_element_length") expect_error_cnd(stop_bad_element_length(1:3, 8, 10, arg = ".foo", what = "Result"), "Result 8 of `.foo` must have length 10, not 3", "purrr_error_bad_element_length") expect_error_cnd(stop_bad_element_length(1:3, 8, 10, arg = ".foo", what = "Result", recycle = TRUE), "Result 8 of `.foo` must have length 1 or 10, not 3", "purrr_error_bad_element_length") }) test_that("stop_bad_vector() constructs error message", { expect_error_cnd(stop_bad_vector(1:3, character(), 1), "Vector must be a single string, not an integer vector of length 3", "purrr_error_bad_vector") expect_error_cnd(stop_bad_vector(factor(c("a", "b")), character(), 10), "Vector must be a character vector of length 10, not a vector of class `factor` and of length 2", "purrr_error_bad_vector") expect_error_cnd(stop_bad_vector(1:3, character(), 10, recycle = TRUE), "Vector must be a character vector of length 1 or 10, not an integer vector of length 3", "purrr_error_bad_vector") expect_error_cnd(stop_bad_vector(1:3, 1:2, 10, what = "This foobaz vector", recycle = TRUE), "This foobaz vector must be an integer vector of length 1 or 10, not an integer vector of length 3", "purrr_error_bad_vector") expect_error_cnd(stop_bad_vector(list(1, 2), logical(), 10, arg = ".quux", recycle = TRUE), "`.quux` must be a logical vector of length 1 or 10, not a list of length 2", "purrr_error_bad_vector") }) test_that("stop_bad_element_vector() constructs error message", { expect_error_cnd(stop_bad_element_vector(1:3, 3, character(), 1), "Element 3 must be a single string, not an integer vector of length 3", "purrr_error_bad_element_vector") expect_error_cnd(stop_bad_element_vector(1:3, 20, 1:2, 10, what = "Result", recycle = TRUE), "Result 20 must be an integer vector of length 1 or 10, not an integer vector of length 3", "purrr_error_bad_element_vector") expect_error_cnd(stop_bad_element_vector(list(1, 2), 1, logical(), 10, arg = ".quux", recycle = TRUE), "Element 1 of `.quux` must be a logical vector of length 1 or 10, not a list of length 2", "purrr_error_bad_element_vector") })
NULL .dbGetRowCount <- function(res, ...) { return(res@cursor$fetchedRowCount()) } setMethod('dbGetRowCount', 'PrestoResult', .dbGetRowCount)
source("ESEUR_config.r") pal_col=rainbow(2) rofpc=read.csv(paste0(ESEUR_dir, "projects/rofpc.csv.xz"), as.is=TRUE) rofpc$Function.points=as.integer(0.1+rofpc$Function.points) plot(rofpc$Function.points, rofpc$Cost.index, log="xy", col=pal_col[2], xlab="Function points", ylab="Cost\n") rof_mod=glm(log(Cost.index) ~ log(Function.points), data=rofpc) xbounds=20:2000 pred=predict(rof_mod, newdata=data.frame(Function.points=xbounds), type="response") lines(xbounds, exp(pred), col=pal_col[1])
catch_entries_commun = function(all_set, type_var, type_outcome, level_control, D, L, S, M, gamma, H, pct_rand, prop_gpe, alloc_high_prob, num_crit, step, nb_sub_cross, alpha, nsim, nsim_cv, ord.bin, M_per_covar, upper_best, seed){ if(ncol(all_set)<=2){ stop("Data base (all_set) does not contain any covariate.") } if(type_outcome != "binary" && type_outcome != "continuous" && type_outcome != "survival" && type_outcome != "count"){ stop("Outcome (type_outcome) should be either continuous, binary or survival.") } if(sum((type_var != "continuous") & (type_var != "ordinal") & (type_var != "nominal")) > 0){ stop("Covariate types (type_var) must be either continuous, ordinal, or nominal.") } if(as.integer(L) != L){ L = as.integer(L) print(paste("The maximum number of covariates to define subgroups L was transformed into integer: L=", L, sep="")) } if(L < 1){ stop("The maximum number of covariates to define subgroups L must be superior or equal to 1.") } if(as.integer(M) != M){ M = as.integer(M) print(paste("The maximum number of best promising subgroups M was transformed into integer: M=", M, sep="")) } if(M < 1){ stop("The maximum number of best promising subgroups M must be superior or equal to 1.") } if(length(gamma)==1 && is.na(gamma)){ print("Vector of relative improvment gamma was not supplied and will be chosen by cross-validation. This is time-consuming and not recommended.") } if(length(gamma) != L){ stop("Lenght of vector of relative improvment gamma should be equal to L.") } if(as.integer(H) != H){ H = as.integer(H) print(paste("The number of sets H was transformed into integer: H=", H, sep="")) } if(H < 1){ stop("The number of sets H must be superior or equal to 1.") } if(pct_rand < 0 || pct_rand > 1){ stop("Percentage of sample size allocated randomly between sets (pct_rand) must be comprised between 0 and 1.") } if(length(prop_gpe) != H){ stop("Vector of proportions in each set (prop_gpe) must be equal to the number of sets H.") } if(sum(prop_gpe<0)>0 || sum(prop_gpe> 1)>0){ stop("Proportions of sample size in each set (prop_gpe) must be comprised between 0 and 1.") } if(alloc_high_prob != TRUE && alloc_high_prob != FALSE){ alloc_high_prob = TRUE print("The allocation rule (alloc_high_prob) was misspecified and was thus reset to its default value.") } if(num_crit != 1 && num_crit != 2 && num_crit != 3){ num_crit = 1 print("The number associated to splitting criterion (num_crit) was misspecified and was thus reset to its default value.") } if(is.na(gamma) && (step < 0 || step > 1)){ stop("step for cross-validation must be comprised between 0 and 1.") } if(is.na(gamma) && as.integer(nb_sub_cross) != nb_sub_cross){ nb_sub_cross = as.integer(nb_sub_cross) print(paste("The number of folds for cross-validation (nb_sub_cross) was transformed into integer: nb_sub_cross=", nb_sub_cross, sep="")) } if(nb_sub_cross < 2){ stop("The number of folds for cross-validation (nb_sub_cross) must be superior or equal to 2.") } if(alpha < 0 || alpha > 1){ stop("Type I error rate (alpha) must be comprised between 0 and 1.") } if(as.integer(nsim) != nsim){ nsim = as.integer(nsim) print(paste("The number of permutations for resampling-based methods to adjust pvalues (nsim) was transformed into integer: nsim=", nsim, sep="")) } if(nsim < 0){ stop("The number of permutations for resampling-based methods to adjust pvalues (nsim) must be superior or equal to 0.") } if(!is.na(gamma) && as.integer(nsim_cv) != nsim_cv){ nsim_cv = as.integer(nsim_cv) print(paste("The number of permutations for resampling-based methods to adjust pvalues in the cross-validation part (nsim_cv) was transformed into integer: nsim_cv=", nsim_cv, sep="")) } if(!is.na(gamma) && nsim_cv < 0){ stop("The number of permutations for resampling-based methods to adjust pvalues in the cross-validation part (nsim_cv) must be superior or equal to 0.") } if(as.integer(ord.bin) != ord.bin){ ord.bin = as.integer(ord.bin) print(paste("The number of classes to discretize covariates (ord.bin) was transformed into integer: ord.bin=", ord.bin, sep="")) } if(ord.bin < 2){ stop("The number of classes to discretize covariates (ord.bin) must be superior or equal to 2.") } if(M_per_covar != TRUE && M_per_covar != FALSE){ M_per_covar = FALSE print("The selection rule for best promising child subgroups (M_per_covar) was misspecified and was thus reset to its default value.") } if(upper_best != TRUE && upper_best != FALSE){ upper_best = TRUE print("Boolean indicating if greater values of the outcome mean better responses (upper_best) was misspecified and was thus reset to its default value.") } if(as.integer(seed) != seed){ seed = as.integer(seed) print(paste("The seed was transformed into integer: seed=", seed, sep="")) } return(list(all_set, type_var, type_outcome, level_control, D, L, S, M, gamma, H, pct_rand, prop_gpe, alloc_high_prob, num_crit, step, nb_sub_cross, alpha, nsim, nsim_cv, ord.bin, M_per_covar, upper_best, seed)) } catch_entries1 = function(all_set, type_var, type_outcome, level_control, D, L, S, M, gamma, H, pct_rand, prop_gpe, alloc_high_prob, num_crit, step, nb_sub_cross, alpha, nsim, nsim_cv, ord.bin, M_per_covar, upper_best, seed, selec){ catch = catch_entries_commun(all_set, type_var, type_outcome, level_control, D, L, S, M, gamma, H, pct_rand, prop_gpe, alloc_high_prob, num_crit, step, nb_sub_cross, alpha, nsim, nsim_cv, ord.bin, M_per_covar, upper_best, seed) all_set = catch[[1]] type_var = catch[[2]] type_outcome = catch[[3]] level_control = catch[[4]] D = catch[[5]] L = catch[[6]] S = catch[[7]] M = catch[[8]] gamma = catch[[9]] H = catch[[10]] pct_rand = catch[[11]] prop_gpe = catch[[12]] alloc_high_prob = catch[[13]] num_crit = catch[[14]] step = catch[[15]] nb_sub_cross = catch[[16]] alpha = catch[[17]] nsim = catch[[18]] nsim_cv = catch[[19]] ord.bin = catch[[20]] M_per_covar = catch[[21]] upper_best = catch[[22]] seed = catch[[23]] if(selec != TRUE && selec != FALSE){ selec = FALSE print("Boolean indicating if the function also print subgroups selected and not necessarily validated (selec) was misspecified and was thus reset to its default value.") } return(list(all_set, type_var, type_outcome, level_control, D, L, S, M, gamma, H, pct_rand, prop_gpe, alloc_high_prob, num_crit, step, nb_sub_cross, alpha, nsim, nsim_cv, ord.bin, M_per_covar, upper_best, seed, selec)) } catch_entries2 = function(all_set, type_var, type_outcome, level_control, D, L, S, M, gamma, H, pct_rand, prop_gpe, alloc_high_prob, num_crit, step, nb_sub_cross, alpha, nsim, nsim_cv, ord.bin, M_per_covar, upper_best, seed, nrep){ catch = catch_entries_commun(all_set, type_var, type_outcome, level_control, D, L, S, M, gamma, H, pct_rand, prop_gpe, alloc_high_prob, num_crit, step, nb_sub_cross, alpha, nsim, nsim_cv, ord.bin, M_per_covar, upper_best, seed) all_set = catch[[1]] type_var = catch[[2]] type_outcome = catch[[3]] level_control = catch[[4]] D = catch[[5]] L = catch[[6]] S = catch[[7]] M = catch[[8]] gamma = catch[[9]] H = catch[[10]] pct_rand = catch[[11]] prop_gpe = catch[[12]] alloc_high_prob = catch[[13]] num_crit = catch[[14]] step = catch[[15]] nb_sub_cross = catch[[16]] alpha = catch[[17]] nsim = catch[[18]] nsim_cv = catch[[19]] ord.bin = catch[[20]] M_per_covar = catch[[21]] upper_best = catch[[22]] seed = catch[[23]] if(as.integer(nrep) != nrep){ nrep = as.integer(nrep) print(paste("The number of simulations (nrep) was transformed into integer: nrep=", nrep, sep="")) } if(nrep < 1){ stop("The number of simulations (nrep) must be superior or equal to 1.") } return(list(all_set, type_var, type_outcome, level_control, D, L, S, M, gamma, H, pct_rand, prop_gpe, alloc_high_prob, num_crit, step, nb_sub_cross, alpha, nsim, nsim_cv, ord.bin, M_per_covar, upper_best, seed, nrep)) } SIDES = function(all_set, type_var, type_outcome, level_control, D=0, L=3, S, M=5, gamma=rep(1,3), H=1, pct_rand=0.5, prop_gpe=c(1), alloc_high_prob=TRUE, num_crit=1, step=0.5, nb_sub_cross=5, alpha, nsim=500, nsim_cv=500, ord.bin=10, M_per_covar=FALSE, upper_best=TRUE, selec=FALSE, seed=42, modified=TRUE){ catch = catch_entries1(all_set, type_var, type_outcome, level_control, D, L, S, M, gamma, H, pct_rand, prop_gpe, alloc_high_prob, num_crit, step, nb_sub_cross, alpha, nsim, nsim_cv, ord.bin, M_per_covar, upper_best, seed, selec) all_set = catch[[1]] type_var = catch[[2]] type_outcome = catch[[3]] level_control = catch[[4]] D = catch[[5]] L = catch[[6]] S = catch[[7]] M = catch[[8]] gamma = catch[[9]] H = catch[[10]] pct_rand = catch[[11]] prop_gpe = catch[[12]] alloc_high_prob = catch[[13]] num_crit = catch[[14]] step = catch[[15]] nb_sub_cross = catch[[16]] alpha = catch[[17]] nsim = catch[[18]] nsim_cv = catch[[19]] ord.bin = catch[[20]] M_per_covar = catch[[21]] upper_best = catch[[22]] seed = catch[[23]] selec = catch[[24]] X_covariate = all_set[,-1] alloc_btw_sets = allocation_procedure(H, pct_rand, X_covariate, type_var, prop_gpe, alloc_high_prob, FALSE, seed) base = cbind(alloc_btw_sets, all_set) training_set = all_set[which(base[,1]==1),] if(is.na(gamma[1])==TRUE){ gamma = cross_validation(training_set, type_var, type_outcome, level_control, D, alpha, L, S, num_crit, M, step, nb_sub_cross, nsim_cv, ord.bin, upper_best, M_per_covar, seed) if(is.null(nrow(gamma))==FALSE){ gamma = as.numeric(gamma[1,]) } } res_candidates = subgroup_identification_candidates(training_set, type_var, type_outcome, level_control, D, L, S, num_crit, M, gamma, alpha, nsim, ord.bin, upper_best, M_per_covar, seed, modified) candidates = res_candidates[[1]] nb_candidates = length(candidates) if(nb_candidates==0){ print("No subgroup identified") res = list("candidates"=list(list(),c()), "confirmed"=list(list(),c())) } else{ if(nb_candidates > 1){ to_comp = combn(1:nb_candidates,2) candidates_temp = candidates pval_cand_temp = res_candidates[[3]] ind_rem = c() for(icol in 1:ncol(to_comp)){ if(identical_subgroups(candidates[[to_comp[1,icol]]], candidates[[to_comp[2,icol]]])==TRUE){ ind_rem = c(ind_rem, to_comp[2,icol]) } } ind_rem = sort(unique(ind_rem), decreasing=TRUE) for(ir in ind_rem){ candidates_temp[[ir]] = NULL } candidates = candidates_temp nb_candidates = length(candidates) if(length(ind_rem)>0){ pval_cand = pval_cand_temp[-ind_rem] } else{ pval_cand = pval_cand_temp } } else{ pval_cand = res_candidates[[3]] } if(H > 1){ confirmed = list() pval_confirmed = c() for(cand in 1:nb_candidates){ conf_all_set = TRUE i=2 while(i<=H && conf_all_set==TRUE){ set_valid_cur = all_set[which(base[,1]==i),] set_subg_cur = sub_sets_parents(set_valid_cur, candidates[[cand]])[[1]] res_analyse = analyse(set_subg_cur, type_outcome, level_control, D, alpha, upper_best) if(res_analyse[3]==FALSE){ conf_all_set = FALSE } else{ if(i == H){ confirmed[[length(confirmed)+1]] = candidates[[cand]] pval_confirmed = c(pval_confirmed,res_analyse[2]) } } i=i+1 } } if(length(pval_confirmed) > 0){ if(selec==FALSE){ res = list("candidates"=list(list(),c()), "confirmed"=list(confirmed,pval_confirmed)) } else{ res = list("candidates"=list(candidates,pval_cand),"confirmed"=list(confirmed,pval_confirmed)) } } else{ print("No subgroup confirmed") res = list("candidates"=list(list(),c()), "confirmed"=list(list(),c())) } } else{ res = list("candidates"=list(candidates,pval_cand),"confirmed"=list(list(),c())) } } res = c(res,"base"=list(all_set),"training"=list(training_set)) class(res) = "SIDES" return(res) } simulation_SIDES = function(all_set, type_var, type_outcome, level_control, D=0, L=3, S, M=5, num_crit=1, gamma=rep(1,3), alpha, nsim=500, ord.bin=10, nrep=100, seed=42, H=1, pct_rand=0.5, prop_gpe=c(1), alloc_high_prob=TRUE, step=0.5, nb_sub_cross=5, nsim_cv=500, M_per_covar=FALSE, upper_best=TRUE, nb_cores=NA, ideal=NA, modified=TRUE){ catch = catch_entries2(all_set, type_var, type_outcome, level_control, D, L, S, M, gamma, H, pct_rand, prop_gpe, alloc_high_prob, num_crit, step, nb_sub_cross, alpha, nsim, nsim_cv, ord.bin, M_per_covar, upper_best, seed, nrep) all_set = catch[[1]] type_var = catch[[2]] type_outcome = catch[[3]] level_control = catch[[4]] D = catch[[5]] L = catch[[6]] S = catch[[7]] M = catch[[8]] gamma = catch[[9]] H = catch[[10]] pct_rand = catch[[11]] prop_gpe = catch[[12]] alloc_high_prob = catch[[13]] num_crit = catch[[14]] step = catch[[15]] nb_sub_cross = catch[[16]] alpha = catch[[17]] nsim = catch[[18]] nsim_cv = catch[[19]] ord.bin = catch[[20]] M_per_covar = catch[[21]] upper_best = catch[[22]] seed = catch[[23]] nrep = catch[[24]] if(is.na(nb_cores)){ nb_cores = detectCores()-1 } if(nb_cores>1){ cl = makeCluster(nb_cores, outfile="") registerDoParallel(cl) } if(H==1){ n_rep = 1 } list_selected = list() list_top = list() pct_selected = c() pct_top = c() pct_no_subgroup = 0 pct_sous_cov_select1 = 0 pct_sous_ens_top1 = 0 pct_sous_cov_select2 = 0 pct_sous_ens_top2 = 0 pct_ideal_selected = 0 pct_ideal_top = 0 mean_size = 0 if(nb_cores>1){ res_simu = foreach(r=1:nrep, .export=ls(globalenv()), .inorder=FALSE) %dopar% { set.seed(seed+r) print(r) res_r = SIDES(all_set, type_var, type_outcome, level_control, D, L, S, M, gamma, H, pct_rand, prop_gpe, alloc_high_prob, num_crit, step, nb_sub_cross, alpha, nsim, nsim_cv, ord.bin, M_per_covar, upper_best, selec=FALSE, seed+r, modified) return(res_r) } } else{ res_simu = list() for(r in 1:nrep){ set.seed(seed+r) print(r) res_r = SIDES(all_set, type_var, type_outcome, level_control, D, L, S, M, gamma, H, pct_rand, prop_gpe, alloc_high_prob, num_crit, step, nb_sub_cross, alpha, nsim, nsim_cv, ord.bin, M_per_covar, upper_best, selec=FALSE, seed+r, modified) res_simu = c(res_simu, list(res_r)) } } for(r in 1:nrep){ res_r = res_simu[[r]] if( (H==1 && length(res_r$candidates[[2]]) > 0) || (H>1 && length(res_r$confirmed[[2]]) > 0) ){ if(H > 1){ select_cur = res_r$confirmed[[1]] pval_cur = res_r$confirmed[[2]] } else{ select_cur = res_r$candidates[[1]] pval_cur = res_r$candidates[[2]] } find_sous_cov1 = FALSE find_sous_ens1 = FALSE find_sous_cov2 = FALSE find_sous_ens2 = FALSE if(length(list_selected)==0){ list_selected = c(list_selected, select_cur) pct_selected = c(pct_selected, rep(1, length(select_cur))) for(sg in 1:length(select_cur)){ cand_sg = select_cur[[sg]] mean_size = mean_size + nrow(sub_sets_parents(res_r$training, cand_sg)[[1]])/length(select_cur) if(identical_subgroups(ideal, cand_sg)==TRUE){ pct_ideal_selected = pct_ideal_selected+1 if(pval_cur[sg]==min(pval_cur)){ pct_ideal_top = pct_ideal_top+1 } } if(find_sous_cov1 == FALSE && included_subgroups(cand_sg, ideal)==TRUE){ find_sous_cov1 = TRUE pct_sous_cov_select1 = pct_sous_cov_select1+1 } if(find_sous_ens1 == FALSE && included_subgroups(ideal, cand_sg)==TRUE){ find_sous_ens1 = TRUE pct_sous_ens_top1 = pct_sous_ens_top1+1 } if(find_sous_cov2 == FALSE && included_subgroups(cand_sg, ideal)==TRUE && identical_subgroups(cand_sg, ideal)==FALSE){ find_sous_cov2 = TRUE pct_sous_cov_select2 = pct_sous_cov_select2+1 } if(find_sous_ens2 == FALSE && included_subgroups(ideal, cand_sg)==TRUE && identical_subgroups(cand_sg, ideal)==FALSE){ find_sous_ens2 = TRUE pct_sous_ens_top2 = pct_sous_ens_top2+1 } } } else{ if(length(select_cur)>0){ for(s in 1:length(select_cur)){ cand_s = select_cur[[s]] different = TRUE i=1 while(different==TRUE && i <= length(list_selected)){ if(identical_subgroups(cand_s, list_selected[[i]])==TRUE){ different=FALSE pct_selected[i] = pct_selected[i]+1 } i = i+1 } if(different == TRUE){ list_selected = c(list_selected, list(cand_s)) pct_selected = c(pct_selected, 1) } mean_size = mean_size + nrow(sub_sets_parents(res_r$training, cand_s)[[1]])/length(select_cur) if(identical_subgroups(ideal, cand_s)==TRUE){ pct_ideal_selected = pct_ideal_selected+1 if(pval_cur[s]==min(pval_cur)){ pct_ideal_top = pct_ideal_top+1 } } if(find_sous_cov1 == FALSE && included_subgroups(cand_s, ideal)==TRUE){ find_sous_cov1 = TRUE pct_sous_cov_select1 = pct_sous_cov_select1+1 } if(find_sous_ens1 == FALSE && included_subgroups(ideal, cand_s)==TRUE){ find_sous_ens1 = TRUE pct_sous_ens_top1 = pct_sous_ens_top1+1 } if(find_sous_cov2 == FALSE && included_subgroups(cand_s, ideal)==TRUE && identical_subgroups(cand_s, ideal)==FALSE){ find_sous_cov2 = TRUE pct_sous_cov_select2 = pct_sous_cov_select2+1 } if(find_sous_ens2 == FALSE && included_subgroups(ideal, cand_s)==TRUE && identical_subgroups(cand_s, ideal)==FALSE){ find_sous_ens2 = TRUE pct_sous_ens_top2 = pct_sous_ens_top2+1 } } } } } else{ pct_no_subgroup = pct_no_subgroup+1 } } mean_size = mean_size/(nrep-pct_no_subgroup) pct_selected = pct_selected/nrep*100 pct_no_subgroup = pct_no_subgroup/nrep*100 or_pct_selected = order(pct_selected, decreasing=TRUE) pct_ideal_selected = pct_ideal_selected/nrep*100 pct_ideal_top = pct_ideal_top/nrep*100 pct_sous_cov_select1 = pct_sous_cov_select1/nrep*100 pct_sous_ens_top1 = pct_sous_ens_top1/nrep*100 pct_sous_cov_select2 = pct_sous_cov_select2/nrep*100 pct_sous_ens_top2 = pct_sous_ens_top2/nrep*100 if(nb_cores>1){ stopCluster(cl) } res = list( "pct_no_subgroup"=pct_no_subgroup, "mean_size"=mean_size, "pct_ideal_selected"=pct_ideal_selected, "pct_ideal_top"=pct_ideal_top, "pct_sous_cov_select1"=pct_sous_cov_select1, "pct_sous_ens_top1"=pct_sous_ens_top1, "pct_sous_cov_select2"=pct_sous_cov_select2, "pct_sous_ens_top2"=pct_sous_ens_top2, "subgroups"=list_selected[or_pct_selected], "pct_selection"=pct_selected[or_pct_selected], "ideal"=ideal ) res = c(res,"base"=list(all_set)) class(res) = "simulation_SIDES" return(res) } identical_subgroups = function(g1, g2){ res = FALSE if(sum(!is.element(g1[[1]], g2[[1]])) == 0 && sum(!is.element(g2[[1]], g1[[1]])) == 0){ for(j in 1:length(g1[[1]])){ ind_j = which(g1[[1]][j]==g2[[1]]) if(sum(!is.element(g1[[2]][[j]], g2[[2]][[ind_j]])) == 0 && sum(!is.element(g2[[2]][[ind_j]], g1[[2]][[j]])) == 0){ res = TRUE } } } return(res) } included_subgroups = function(g1, g2){ res = FALSE if(sum(!is.element(g1[[1]], g2[[1]])) == 0){ for(j in 1:length(g1[[1]])){ ind_j = which(g1[[1]][j]==g2[[1]]) if(sum(!is.element(g1[[2]][[j]], g2[[2]][[ind_j]])) == 0){ res = TRUE } } } return(res) } print_gpe = function(subgroup, pval=NA, x, pct=NA){ icov = subgroup[[1]] nb_cov = length(icov) type_var = subgroup[[3]] levels_icov = subgroup[[2]] txt_sgpe = c() for(i in 1:nb_cov){ levels_theo = sort(unique(x$base[,icov[i]])) levels_sgpe = c() if(type_var[i]=="ordinal"){ val_cut = as.numeric(substr(levels_icov[[i]],1,nchar(levels_icov[[i]])-1)) signe = substr(levels_icov[[i]],nchar(levels_icov[[i]]),nchar(levels_icov[[i]])) levels_sgpe = "" if(signe == "-"){ levels_sgpe = levels_theo[which(levels_theo<=val_cut)] } else{ levels_sgpe = levels_theo[which(levels_theo>val_cut)] } tlevels_sgpe = paste(levels_sgpe, collapse=",") txt_sgpe = c(txt_sgpe, paste(names(x$base)[icov[i]], " = {", tlevels_sgpe,"}",sep="")) } else if(type_var[i]=="nominal"){ levels_sgpe = levels_icov[[i]] tlevels_sgpe = paste(levels_sgpe, collapse=",") txt_sgpe = c(txt_sgpe, paste(names(x$base)[icov[i]], " = {", tlevels_sgpe,"}",sep="")) } else if(type_var[i]=="continuous"){ val_cut = as.numeric(substr(levels_icov[[i]],1,nchar(levels_icov[[i]])-1)) signe = substr(levels_icov[[i]],nchar(levels_icov[[i]]),nchar(levels_icov[[i]])) levels_sgpe = "" if(signe == "-"){ signe = "<=" } else{ signe = ">" } txt_sgpe = c(txt_sgpe, paste(names(x$base)[icov[i]], " ", signe, " ", val_cut, sep="")) } if(i < nb_cov){ txt_sgpe = c(txt_sgpe, " AND ") } else{ txt_sgpe = c(txt_sgpe, "\n") } } cat(txt_sgpe) if(!is.na(pval)){ cat("pvalue = ", pval, "\n") } if(!is.na(pct)){ cat("Percentage of selection = ", pct, "% \n") } } print.SIDES = function(x, ...){ nb_cand = length(x$candidates[[2]]) nb_conf = length(x$confirmed[[2]]) if(nb_cand>0){ cat("Identified candidate subgroups before confirmation phase:\n") for(i in 1:nb_cand){ print_gpe(subgroup=x$candidates[[1]][[i]], pval=x$candidates[[2]][i], x=x) } } else{ cat("No candidate subgroups identified before confirmation phase:\n") } if(nb_conf>0){ cat("Confirmed candidate subgroups:\n") for(i in 1:nb_conf){ print_gpe(subgroup=x$confirmed[[1]][[i]], pval=x$confirmed[[2]][i], x=x) } } else{ cat("No candidate subgroups confirmed:\n") } } print.simulation_SIDES = function(x, ...){ nb_ssgpe = length(x$pct_selection) others = FALSE cat("No subgroup selected in ", x$pct_no_subgroup, "% \n") cat("Average size of the confirmed subgroups in the training data set in ", x$mean_size, "\n") if(length(x$ideal) > 1 || (length(x$ideal) == 1 && is.na(x$ideal)==FALSE)){ cat("Percentage of simulations where the ideal subgroup is confirmed: ", x$pct_ideal_selected, "% \n") cat("Percentage of simulations where the ideal subgroup is the top confirmed subgroup: ", x$pct_ideal_top, "% \n") cat("Percentage of simulations where a subgroup containing a subset of the covariates used to define the ideal subgroup is selected (including the ideal): ", x$pct_sous_cov_select1, "% \n") cat("Percentage of simulations where a subgroup containing a subset of the covariates used to define the ideal subgroup is selected (excluding the ideal): ", x$pct_sous_cov_select2, "% \n") cat("Percentage of simulations where a subset of the ideal subgroup is selected (including the ideal): ", x$pct_sous_ens_top1, "% \n") cat("Percentage of simulations where a subset of the ideal subgroup is selected (exluding the ideal): ", x$pct_sous_ens_top2, "% \n") } if(nb_ssgpe>0){ cat("Confirmed candidate subgroups:\n") for(i in 1:nb_ssgpe){ if(x$pct_selection[i] >= 10){ print_gpe(subgroup=x$subgroups[[i]], x=x, pct=x$pct_selection[i]) } else{ others = TRUE } } if(others == TRUE){ cat("Others subgroups in less than 10% \n") } } }
.onLoad<- function(libname, pkgname) { assign("pkg.globals", new.env(), envir=parent.env(environment())) assign("pkg.basedir", NA, pkg.globals) assign("pkg.modeldir", NA, pkg.globals) assign("pkg.scenariodir", NA, pkg.globals) assign("pkg.modellibdir", NA, pkg.globals) assign("pkg.id", NA, pkg.globals) assign("pkg.cwd", NA, pkg.globals) assign("pkg.parameters", data.frame(), pkg.globals) assign("pkg.results", data.frame(), pkg.globals) assign("pkg.progressbar", NULL, pkg.globals) assign("pkg.progressbar.enabled", FALSE, pkg.globals) assign("pkg.stats.calls", 0, pkg.globals) assign("pkg.parallelize", FALSE, pkg.globals) assign("pkg.runcluster", NULL, pkg.globals) assign("pkg.maxcores", getpkgdefaultcores(), pkg.globals) assign("pkg.outputdir",paste0(Sys.getenv("TMP"),"/rrepast-deployment/"), pkg.globals) assign("pkg.repastlibdir", "/repast.simphony/", pkg.globals) assign("pkg.java.parameters","-server -Xms512m -Xmx1024m", pkg.globals) assign("pkg.randomSeed","randomSeed", pkg.globals) set.seed(exp(1)*10^6) compatibility() } Model<- function(modeldir="",maxtime=300,dataset="none", load=FALSE) { if(dir.exists(modeldir)) { configModelDirs(modeldir) jvm.init() e<- Engine() Engine.endAt(e,maxtime) Engine.SetAggregateDataSet(e,dataset) if(load == TRUE) { Load(e) } return(e) } else { stop(paste0("The model directory does not exist: ", modeldir)) } } Load<- function(e) { Engine.LoadModel(e,getScenarioDir()) setId(Engine.getId(e)) } Run<- function(e,r=1,seed=c()) { if(length(seed) == 0) { seed= runif(r,-10^8,10^8) } else if(length(seed) != r) { stop("The provided set of random numbers doesn't match replications!") } p<- GetSimulationParameters(e) ClearResults() SetResultsParameters(p) PB.init(1, r) results<- c() for(i in 1:r) { if(r > 1) { Engine.setParameter(e,getKeyRandom(),as.integer(seed[i])) } Engine.RunModel(e) data<- GetOutput(e) data$run<- i AddResults(data) results<- rbind(results,data) PB.update(i) } PB.close() return(results) } RunExperiment<- function(e, r=1, design, FUN) { paramset<- c() output<- c() dataset<- c() psets<- nrow(design) PB.init(psets, r) for(i in 1:psets) { d<- design[i,] SetSimulationParameters(e, d) PB.pset(i) results<- Run(e,r) calibration<- FUN(d,results) if(is.null(calibration)) { stop("Invalid user provided calibration function!") } pset<- i paramset<- rbind(paramset,cbind(pset,d)) output<- rbind(output,cbind(pset,calibration)) dataset<- rbind(dataset,cbind(pset,results)) } PB.close() return(list(paramset=paramset, output=output, dataset=dataset)) } getExperimentParamSet<- function(e) { v<- e$paramset return(v) } getExperimentOutput<- function(e) { v<- e$output return(v) } getExperimentDataset<- function(e) { v<- e$dataset return(v) } GetOutput<- function(e) { c<- textConnection(Engine.GetModelOutput(e)) read.csv(c) } GetSimulationParameterType<- function(e, k) { Engine.getParameterType(e, k) } UpdateDefaultParameters<- function(e, p) { if(is.null(e)) { stop("Engine object is null!") } parameters<- GetSimulationParameters(e) for(key in names(p)) { if(key %in% names(parameters)) { value<- sprintf("%s",p[key]) SetSimulationParameter(e, key, value) } else { print(sprintf("The model does not have a paramter with name [ %s ]",key)) } } } SetSimulationParameters<- function(e, p) { if(is.null(e)) { stop("Engine object is null!") } for(key in names(p)) { value<- p[1,key] if(is.factor(value)) { value<- levels(value) } SetSimulationParameter(e, key, value) } } SetSimulationParameter<- function(e, key, value) { if(is.null(e)) { stop("Engine object is null!") } keys<- names(GetSimulationParameters(e)) if(key %in% keys) { switch(typeof(value), double = { value<- as.double(value) }, integer = { value<- as.integer(value) }, character = { value<- as.character(value) }) Engine.setParameter(e,key,value) } } GetSimulationParameters<- function(e) { keys<- "" values<- "" names<- Engine.getParameterNames(e) for(n in names) { v<- Engine.getParameterAsString(e,n) if(nchar(keys) == 0){ keys<- n values<- v } else { keys<- paste0(keys,",",n) values<- paste0(values,",",v) } } b<- rbind(keys,values) c<- textConnection(b) read.csv(c) } ClearResults<- function() { assign("pkg.results", data.frame(), pkg.globals) assign("pkg.parameters", data.frame(), pkg.globals) } GetResults<- function() { return(get("pkg.results", pkg.globals)) } SetResults<- function(d) { assign("pkg.results", d, pkg.globals) } AddResults<- function(d) { r<- GetResults() SetResults(rbind(r,d)) } GetResultsParameters<- function() { return(get("pkg.parameters", pkg.globals)) } SetResultsParameters<- function(d) { assign("pkg.parameters", d, pkg.globals) } SaveSimulationData<- function(as="csv", experiment=NULL) { createOutputDir() filename<- getId() if(is.na(filename)) { stop("Model was not initialized correctly!") } paramset<- NULL output<- NULL dataset<- NULL if(!is.null(experiment)) { paramset<- getExperimentParamSet(experiment) output<- getExperimentOutput(experiment) dataset<- getExperimentDataset(experiment) } else { paramset<- GetResultsParameters() dataset<- GetResults() } hash <- digest(Sys.time(), algo="crc32") f0<- paste0(getOutputDir(),tolower(filename),"-paramset-",hash) f1<- paste0(getOutputDir(),tolower(filename),"-output-",hash) f2<- paste0(getOutputDir(),tolower(filename),"-dataset-",hash) switch(as, csv = { f0<- paste0(f0,".csv") f1<- paste0(f1,".csv") f2<- paste0(f2,".csv") write.csv(paramset, f0, row.names=FALSE) if(!is.null(output)) { write.csv(output, f1, row.names=FALSE) } write.csv(dataset, f2, row.names=FALSE) }, xls = { f0<- paste0(f0,".xlsx") f1<- paste0(f1,".xlsx") f2<- paste0(f2,".xlsx") xlsx::write.xlsx(paramset, f0) if(!is.null(output)) { xlsx::write.xlsx(output, f1) } xlsx::write.xlsx(dataset, f0) }) return(hash) } AddFactor<- function(factors=c(), lambda="qunif",name, min, max, int=FALSE) { if(max < min) { stop("Invalid factor range!") } rrow<- c(lambda=lambda,name=name,min=min,max=max, int=int) rownames(rrow)<- NULL if(length(factors) > 0 && any(factors[,"name"] == name)) { i<- which(factors[,"name"] == name) factors[i,]<- c(rrow) } else { factors<- rbind(factors,c(rrow)) } return(factors) } AddFactor0<- function(factors=c(), ...) { argv<- list(...) v.lambda<- ifelse(is.null(lget(argv,"lambda")), "qunif", lget(argv,"lambda")) v.int<- ifelse(is.null(lget(argv,"int")), FALSE, lget(argv,"int")) is.range<- function(v) { (lcontains(v,"name") && lcontains(v,"min") && lcontains(v,"max") && (!lcontains(v,"levels"))) } is.levels<- function(v) { (lcontains(v,"name") && lcontains(v,"levels") && !(lcontains(v,"min") || lcontains(v,"max"))) } if(is.range(argv)) { name<- lget(argv,"name") v.min<- lget(argv,"min") v.max<- lget(argv,"max") if(v.max < v.min) { stop("Invalid factor range!") } rrow<- c(lambda=v.lambda,name=name,min=v.min,max=v.max, int=v.int) } else { if (is.levels(argv)) { name<- lget(argv,"name") v.levels<- lget(argv,"levels") rrow<- c(lambda=v.lambda,name=name,levels=as.list(v.levels)) } else { stop("Invalid parameter combination!") } } rownames(rrow)<- NULL if(length(factors) > 0 && any(factors[,"name"] == name)) { i<- which(factors[,"name"] == name) factors[i,]<- c(rrow) } else { factors<- rbind(factors,c(rrow)) } factors } GetFactorLevels<- function(factors, name) { mylevels<- c() if(length(factors) > 0 && any(factors[,"name"] == name)) { i<- which(factors[,"name"] == name) n<- ncol(factors) for(j in (which(colnames(factors) == "levels1")):n) { mylevels<- c(mylevels, factors[[i, j]]) } } mylevels } GetFactorsSize<- function(factors) { n<- nrow(factors) if(is.null(n)) n<- 0 return(n) } ApplyFactorRange<- function(design, factors) { trunciftrue<- function(v, f) { if(f) { v<- trunc(v) } v } k<- GetFactorsSize(factors) d<- sapply(1:k, function(p) {trunciftrue(match.fun( factors[p,"lambda"])(design[,p],as.numeric(factors[p,"min"]),as.numeric(factors[p,"max"])), factors[p,"int"])}) if(is.null(nrow(d))) { d<- as.data.frame(t(d)) } else { d<- as.data.frame(d) } names(d)<- factors[,"name"] return(d) } BuildParameterSet<- function(design, parameters) { v<- as.data.frame(design) tmp.p<- parameters for(n in names(v)) { tmp.p[n]<- NULL } for(i in 1:length(names(tmp.p))) { v<- cbind(tmp.p[i],v) } return(v) }
nd.moments <- function(A, k=3, metric=c("euclidean","maximum","manhattan","canberra","binary","minkowski"), out.dist=TRUE){ if ((!is.list(A))||(length(A)<=1)){ stop("* nd.moments : input 'A' should be a list of length larger than 1.") } listA = list_transform(A, NIflag="not") N = length(listA) myk = round(k) if (missing(metric)){ mymetric = "euclidean" } else { mymetric = match.arg(metric) } myreturn = as.logical(out.dist) features = array(0,c(N,myk)) for (n in 1:N){ features[n,] = (moment_single2(as.matrix(listA[[n]]), myk)) } dmat = stats::dist(features, method=mymetric) if (!myreturn){ dmat = as.matrix(dmat) } result = list() result$D= dmat return(result) } moment_single1 <- function(Amat, k){ n = nrow(Amat) temp = Amat mult = Amat output = rep(0,k) for (i in 1:k){ output[i] = (base::sum(base::diag(temp)))/(exp(1+(i/2.0)*log(n))) if (i < k){ temp = temp%*%mult } } return(log(output)) } moment_single2 <- function(Amat, k){ n = nrow(Amat) temp = Amat/n mult = Amat/n output = rep(0,k) for (i in 1:k){ output[i] = base::sum(base::diag(temp)) temp = temp%*%mult } return(log(output)) }
download_rba <- function(urls, path = tempdir()) { check_rba_connection() filenames <- basename(urls) filenames_with_path <- file.path(path, filenames) safely_download_files <- purrr::safely(do_download_files) download_result <- safely_download_files( urls = urls, filenames_with_path = filenames_with_path ) if (!is.null(download_result$error)) { Sys.sleep(5) download_result <- safely_download_files( urls = urls, filenames_with_path = filenames_with_path ) } if (!is.null(download_result$error)) { stop("Could not download ", urls) } invisible(filenames_with_path) } do_download_files <- function(urls, filenames_with_path) { user_timeout <- getOption("timeout") options(timeout = 120) purrr::walk2( .x = urls, .y = filenames_with_path, .f = utils::download.file, quiet = FALSE, mode = "wb", headers = readrba_header ) options(timeout = user_timeout) }
require(geometa, quietly = TRUE) require(testthat) context("ISOImageryMetadata") test_that("encoding/decoding",{ testthat::skip_on_cran() md = ISOImageryMetadata$new() md$setFileIdentifier("my-metadata-identifier") md$setParentIdentifier("my-parent-metadata-identifier") md$setCharacterSet("utf8") md$setLanguage("eng") md$setDateStamp(ISOdate(2015, 1, 1, 1)) md$setMetadataStandardName("ISO 19115:2003/19139") md$setMetadataStandardVersion("1.0") md$setDataSetURI("my-dataset-identifier") for(i in 1:3){ rp <- ISOResponsibleParty$new() rp$setIndividualName(paste0("Firstname",i," Lastname",i)) rp$setOrganisationName("somewhere") rp$setPositionName(paste0("someposition",i)) rp$setRole("pointOfContact") contact <- ISOContact$new() phone <- ISOTelephone$new() phone$setVoice(paste0("myphonenumber",i)) phone$setFacsimile(paste0("myfacsimile",i)) contact$setPhone(phone) address <- ISOAddress$new() address$setDeliveryPoint("theaddress") address$setCity("thecity") address$setPostalCode("111") address$setCountry("France") address$setEmail("[email protected]") contact$setAddress(address) res <- ISOOnlineResource$new() res$setLinkage("http://somelink") res$setName("someresourcename") contact$setOnlineResource(res) rp$setContactInfo(contact) expect_true(md$addContact(rp)) } expect_equal(length(md$contact), 3L) expect_true(md$delContact(rp)) expect_equal(length(md$contact), 2L) vsr <- ISOVectorSpatialRepresentation$new() vsr$setTopologyLevel("geometryOnly") geomObject <- ISOGeometricObjects$new() geomObject$setGeometricObjectType("surface") geomObject$setGeometricObjectCount(5L) vsr$setGeometricObjects(geomObject) expect_true(md$addSpatialRepresentationInfo(vsr)) expect_false(md$addSpatialRepresentationInfo(vsr)) geomObject$setGeometricObjectCount(6L) expect_true(md$delSpatialRepresentationInfo(vsr)) rs <- ISOReferenceSystem$new() rsId <- ISOReferenceIdentifier$new(code = "4326", codeSpace = "EPSG") rs$setReferenceSystemIdentifier(rsId) md$setReferenceSystemInfo(rs) ident <- ISODataIdentification$new() ident$setAbstract("abstract") ident$setPurpose("purpose") expect_true(ident$addCredit("credit1")) expect_false(ident$addCredit("credit1")) expect_true(ident$addCredit("credit2")) expect_true(ident$addCredit("credit3")) expect_equal(length(ident$credit), 3L) expect_true(ident$delCredit("credit3")) expect_equal(length(ident$credit), 2L) expect_true(ident$addStatus("completed")) expect_false(ident$addStatus("completed")) expect_true(ident$addStatus("valid")) expect_true(ident$addStatus("final")) expect_equal(length(ident$status), 3L) expect_true(ident$delStatus("final")) expect_equal(length(ident$status), 2L) ident$setLanguage("eng") ident$setCharacterSet("utf8") ident$addTopicCategory("biota") ident$addTopicCategory("oceans") rp <- ISOResponsibleParty$new() rp$setIndividualName("John Who") rp$setOrganisationName("somewhere") rp$setPositionName("someposition") rp$setRole("pointOfContact") contact <- ISOContact$new() phone <- ISOTelephone$new() phone$setVoice("myphonenumber") phone$setFacsimile("myfacsimile") contact$setPhone(phone) address <- ISOAddress$new() address$setDeliveryPoint("theaddress") address$setCity("thecity") address$setPostalCode("111") address$setCountry("France") address$setEmail("[email protected]") contact$setAddress(address) res <- ISOOnlineResource$new() res$setLinkage("http://somelink") res$setName("somename") contact$setOnlineResource(res) rp$setContactInfo(contact) ident$addPointOfContact(rp) ct <- ISOCitation$new() ct$setTitle("sometitle") d1 <- ISODate$new() d1$setDate(ISOdate(2015, 1, 1, 1)) d1$setDateType("creation") ct$addDate(d1) d2 <- ISODate$new() d2$setDate(ISOdate(2015, 3, 31, 1)) d2$setDateType("publication") ct$addDate(d2) ct$setEdition("1.0") ct$setEditionDate(as.Date(ISOdate(2015, 1, 1, 1))) ct$addIdentifier(ISOMetaIdentifier$new(code = "identifier")) ct$addPresentationForm("mapDigital") ct$addCitedResponsibleParty(rp) ident$setCitation(ct) go1 <- ISOBrowseGraphic$new( fileName = "http://wwww.somefile.org/png1", fileDescription = "Map Overview 1", fileType = "image/png" ) go2 <- ISOBrowseGraphic$new( fileName = "http://www.somefile.org/png2", fileDescription = "Map Overview 2", fileType = "image/png" ) expect_true(ident$addGraphicOverview(go1)) expect_false(ident$addGraphicOverview(go1)) expect_true(ident$addGraphicOverview(go2)) expect_equal(length(ident$graphicOverview), 2L) expect_true(ident$delGraphicOverview(go2)) expect_equal(length(ident$graphicOverview), 1L) mi <- ISOMaintenanceInformation$new() mi$setMaintenanceFrequency("daily") ident$setResourceMaintenance(mi) lc <- ISOLegalConstraints$new() lc$addUseLimitation("limitation1") lc$addUseLimitation("limitation2") lc$addUseLimitation("limitation3") lc$addAccessConstraint("copyright") lc$addAccessConstraint("license") lc$addUseConstraint("copyright") lc$addUseConstraint("license") expect_equal(length(lc$useLimitation), 3L) expect_equal(length(lc$accessConstraints), 2L) expect_equal(length(lc$useConstraints), 2L) ident$addResourceConstraints(lc) sc <- ISOSecurityConstraints$new() sc$setClassification("secret") sc$setUserNote("ultra secret") sc$setClassificationSystem("no classification in particular") sc$setHandlingDescription("description") ident$addResourceConstraints(sc) expect_equal(length(ident$resourceConstraints), 2L) expect_true(ident$delResourceConstraints(sc)) expect_equal(length(ident$resourceConstraints), 1L) extent <- ISOExtent$new() bbox <- ISOGeographicBoundingBox$new(minx = -180, miny = -90, maxx = 180, maxy = 90) extent$setGeographicElement(bbox) vert <- ISOVerticalExtent$new() vert$setMinimumValue(0) vert$setMaximumValue(500) extent$setVerticalElement(vert) te <- ISOTemporalExtent$new() start <- ISOdate(2000, 1, 12, 12, 59, 45) end <- ISOdate(2010, 8, 22, 13, 12, 43) tp <- GMLTimePeriod$new(beginPosition = start, endPosition = end) te$setTimePeriod(tp) extent$setTemporalElement(te) ident$setExtent(extent) kwds1 <- ISOKeywords$new() kwds1$addKeyword("keyword1") kwds1$addKeyword("keyword2") kwds1$setKeywordType("theme") th1 <- ISOCitation$new() th1$setTitle("General1") th1$addDate(d1) kwds1$setThesaurusName(th1) ident$addKeywords(kwds1) kwds2 <- ISOKeywords$new() kwds2$addKeyword("keyword1") kwds2$addKeyword("keyword2") kwds2$setKeywordType("theme") th2 <- ISOCitation$new() th2$setTitle("General2") th2$addDate(d1) kwds2$setThesaurusName(th2) ident$addKeywords(kwds2) kwds3 <- ISOKeywords$new() kwds3$addKeyword("Dinophysis sp") kwds3$addKeyword("Prorocentrum lima") kwds3$addKeyword("Gambierdiscus toxicus") kwds3$setKeywordType("theme") th3 <- ISOCitation$new() th3$setTitle("Taxonomy") th3$addDate(d1) kwds3$setThesaurusName(th3) ident$addKeywords(kwds3) ident$setSupplementalInformation("some additional information") expect_true(ident$addSpatialRepresentationType("vector")) expect_false(ident$addSpatialRepresentationType("vector")) expect_true(ident$addSpatialRepresentationType("grid")) expect_equal(length(ident$spatialRepresentationType), 2L) expect_true(ident$delSpatialRepresentationType("grid")) expect_equal(length(ident$spatialRepresentationType), 1L) md$setIdentificationInfo(ident) distrib <- ISODistribution$new() dto <- ISODigitalTransferOptions$new() for(i in 1:3){ or <- ISOOnlineResource$new() or$setLinkage(paste0("http://somelink",i)) or$setName(paste0("name",i)) or$setDescription(paste0("description",i)) or$setProtocol("WWW:LINK-1.0-http--link") dto$addOnlineResource(or) } distrib$setDigitalTransferOptions(dto) md$setDistributionInfo(distrib) dq <- ISODataQuality$new() scope <- ISOScope$new() scope$setLevel("dataset") dq$setScope(scope) dc <- ISODomainConsistency$new() result <- ISOConformanceResult$new() spec <- ISOCitation$new() spec$setTitle("specification title") spec$addAlternateTitle("specification alternate title") d <- ISODate$new() d$setDate(ISOdate(2015, 1, 1, 1)) d$setDateType("publication") spec$addDate(d1) result$setSpecification(spec) result$setExplanation("some explanation about the conformance") result$setPass(TRUE) dc$addResult(result) dq$addReport(dc) lineage <- ISOLineage$new() lineage$setStatement("statement") dq$setLineage(lineage) md$setDataQualityInfo(dq) md = ISOImageryMetadata$new() md$setFileIdentifier("my-metadata-identifier") md$setParentIdentifier("my-parent-metadata-identifier") md$setCharacterSet("utf8") md$setLanguage("eng") md$setDateStamp(ISOdate(2015, 1, 1, 1)) md$setMetadataStandardName("ISO 19115:2003/19139") md$setMetadataStandardVersion("1.0") md$setDataSetURI("my-dataset-identifier") for(i in 1:3){ rp <- ISOResponsibleParty$new() rp$setIndividualName(paste0("Firstname",i," Lastname",i)) rp$setOrganisationName("somewhere") rp$setPositionName(paste0("someposition",i)) rp$setRole("pointOfContact") contact <- ISOContact$new() phone <- ISOTelephone$new() phone$setVoice(paste0("myphonenumber",i)) phone$setFacsimile(paste0("myfacsimile",i)) contact$setPhone(phone) address <- ISOAddress$new() address$setDeliveryPoint("theaddress") address$setCity("thecity") address$setPostalCode("111") address$setCountry("France") address$setEmail("[email protected]") contact$setAddress(address) res <- ISOOnlineResource$new() res$setLinkage("http://somelink") res$setName("someresourcename") contact$setOnlineResource(res) rp$setContactInfo(contact) expect_true(md$addContact(rp)) } expect_equal(length(md$contact), 3L) expect_true(md$delContact(rp)) expect_equal(length(md$contact), 2L) vsr <- ISOVectorSpatialRepresentation$new() vsr$setTopologyLevel("geometryOnly") geomObject <- ISOGeometricObjects$new() geomObject$setGeometricObjectType("surface") geomObject$setGeometricObjectCount(5L) vsr$setGeometricObjects(geomObject) expect_true(md$addSpatialRepresentationInfo(vsr)) expect_false(md$addSpatialRepresentationInfo(vsr)) geomObject$setGeometricObjectCount(6L) expect_true(md$delSpatialRepresentationInfo(vsr)) rs <- ISOReferenceSystem$new() rsId <- ISOReferenceIdentifier$new(code = "4326", codeSpace = "EPSG") rs$setReferenceSystemIdentifier(rsId) md$setReferenceSystemInfo(rs) ident <- ISODataIdentification$new() ident$setAbstract("abstract") ident$setPurpose("purpose") expect_true(ident$addCredit("credit1")) expect_false(ident$addCredit("credit1")) expect_true(ident$addCredit("credit2")) expect_true(ident$addCredit("credit3")) expect_equal(length(ident$credit), 3L) expect_true(ident$delCredit("credit3")) expect_equal(length(ident$credit), 2L) expect_true(ident$addStatus("completed")) expect_false(ident$addStatus("completed")) expect_true(ident$addStatus("valid")) expect_true(ident$addStatus("final")) expect_equal(length(ident$status), 3L) expect_true(ident$delStatus("final")) expect_equal(length(ident$status), 2L) ident$setLanguage("eng") ident$setCharacterSet("utf8") ident$addTopicCategory("biota") ident$addTopicCategory("oceans") rp <- ISOResponsibleParty$new() rp$setIndividualName("John Who") rp$setOrganisationName("somewhere") rp$setPositionName("someposition") rp$setRole("pointOfContact") contact <- ISOContact$new() phone <- ISOTelephone$new() phone$setVoice("myphonenumber") phone$setFacsimile("myfacsimile") contact$setPhone(phone) address <- ISOAddress$new() address$setDeliveryPoint("theaddress") address$setCity("thecity") address$setPostalCode("111") address$setCountry("France") address$setEmail("[email protected]") contact$setAddress(address) res <- ISOOnlineResource$new() res$setLinkage("http://somelink") res$setName("somename") contact$setOnlineResource(res) rp$setContactInfo(contact) ident$addPointOfContact(rp) ct <- ISOCitation$new() ct$setTitle("sometitle") d1 <- ISODate$new() d1$setDate(ISOdate(2015, 1, 1, 1)) d1$setDateType("creation") ct$addDate(d1) d2 <- ISODate$new() d2$setDate(ISOdate(2015, 3, 31, 1)) d2$setDateType("publication") ct$addDate(d2) ct$setEdition("1.0") ct$setEditionDate(as.Date(ISOdate(2015, 1, 1, 1))) ct$addIdentifier(ISOMetaIdentifier$new(code = "identifier")) ct$addPresentationForm("mapDigital") ct$addCitedResponsibleParty(rp) ident$setCitation(ct) go1 <- ISOBrowseGraphic$new( fileName = "http://wwww.somefile.org/png1", fileDescription = "Map Overview 1", fileType = "image/png" ) go2 <- ISOBrowseGraphic$new( fileName = "http://www.somefile.org/png2", fileDescription = "Map Overview 2", fileType = "image/png" ) expect_true(ident$addGraphicOverview(go1)) expect_false(ident$addGraphicOverview(go1)) expect_true(ident$addGraphicOverview(go2)) expect_equal(length(ident$graphicOverview), 2L) expect_true(ident$delGraphicOverview(go2)) expect_equal(length(ident$graphicOverview), 1L) mi <- ISOMaintenanceInformation$new() mi$setMaintenanceFrequency("daily") ident$setResourceMaintenance(mi) lc <- ISOLegalConstraints$new() lc$addUseLimitation("limitation1") lc$addUseLimitation("limitation2") lc$addUseLimitation("limitation3") lc$addAccessConstraint("copyright") lc$addAccessConstraint("license") lc$addUseConstraint("copyright") lc$addUseConstraint("license") expect_equal(length(lc$useLimitation), 3L) expect_equal(length(lc$accessConstraints), 2L) expect_equal(length(lc$useConstraints), 2L) ident$addResourceConstraints(lc) sc <- ISOSecurityConstraints$new() sc$setClassification("secret") sc$setUserNote("ultra secret") sc$setClassificationSystem("no classification in particular") sc$setHandlingDescription("description") ident$addResourceConstraints(sc) expect_equal(length(ident$resourceConstraints), 2L) expect_true(ident$delResourceConstraints(sc)) expect_equal(length(ident$resourceConstraints), 1L) extent <- ISOExtent$new() bbox <- ISOGeographicBoundingBox$new(minx = -180, miny = -90, maxx = 180, maxy = 90) extent$setGeographicElement(bbox) vert <- ISOVerticalExtent$new() vert$setMinimumValue(0) vert$setMaximumValue(500) extent$setVerticalElement(vert) te <- ISOTemporalExtent$new() start <- ISOdate(2000, 1, 12, 12, 59, 45) end <- ISOdate(2010, 8, 22, 13, 12, 43) tp <- GMLTimePeriod$new(beginPosition = start, endPosition = end) te$setTimePeriod(tp) extent$setTemporalElement(te) ident$setExtent(extent) kwds1 <- ISOKeywords$new() kwds1$addKeyword("keyword1") kwds1$addKeyword("keyword2") kwds1$setKeywordType("theme") th1 <- ISOCitation$new() th1$setTitle("General1") th1$addDate(d1) kwds1$setThesaurusName(th1) ident$addKeywords(kwds1) kwds2 <- ISOKeywords$new() kwds2$addKeyword("keyword1") kwds2$addKeyword("keyword2") kwds2$setKeywordType("theme") th2 <- ISOCitation$new() th2$setTitle("General2") th2$addDate(d1) kwds2$setThesaurusName(th2) ident$addKeywords(kwds2) kwds3 <- ISOKeywords$new() kwds3$addKeyword("Dinophysis sp") kwds3$addKeyword("Prorocentrum lima") kwds3$addKeyword("Gambierdiscus toxicus") kwds3$setKeywordType("theme") th3 <- ISOCitation$new() th3$setTitle("Taxonomy") th3$addDate(d1) kwds3$setThesaurusName(th3) ident$addKeywords(kwds3) ident$setSupplementalInformation("some additional information") expect_true(ident$addSpatialRepresentationType("vector")) expect_false(ident$addSpatialRepresentationType("vector")) expect_true(ident$addSpatialRepresentationType("grid")) expect_equal(length(ident$spatialRepresentationType), 2L) expect_true(ident$delSpatialRepresentationType("grid")) expect_equal(length(ident$spatialRepresentationType), 1L) md$setIdentificationInfo(ident) distrib <- ISODistribution$new() dto <- ISODigitalTransferOptions$new() for(i in 1:3){ or <- ISOOnlineResource$new() or$setLinkage(paste0("http://somelink",i)) or$setName(paste0("name",i)) or$setDescription(paste0("description",i)) or$setProtocol("WWW:LINK-1.0-http--link") dto$addOnlineResource(or) } distrib$setDigitalTransferOptions(dto) md$setDistributionInfo(distrib) dq <- ISODataQuality$new() scope <- ISOScope$new() scope$setLevel("dataset") dq$setScope(scope) dc <- ISODomainConsistency$new() result <- ISOConformanceResult$new() spec <- ISOCitation$new() spec$setTitle("specification title") spec$addAlternateTitle("specification alternate title") d <- ISODate$new() d$setDate(ISOdate(2015, 1, 1, 1)) d$setDateType("publication") spec$addDate(d1) result$setSpecification(spec) result$setExplanation("some explanation about the conformance") result$setPass(TRUE) dc$addResult(result) dq$addReport(dc) lineage <- ISOLineage$new() lineage$setStatement("statement") dq$setLineage(lineage) md$setDataQualityInfo(dq) xml <- md$encode() expect_is(xml, "XMLInternalNode") md2 <- ISOImageryMetadata$new(xml = xml) xml2 <- md2$encode() expect_true(ISOAbstractObject$compare(md, md2)) xml <- md$encode() expect_is(xml, "XMLInternalNode") md2 <- ISOImageryMetadata$new(xml = xml) xml2 <- md2$encode() expect_true(ISOAbstractObject$compare(md, md2)) }) test_that("encoding/decoding - i18n",{ testthat::skip_on_cran() md = ISOImageryMetadata$new() md$setFileIdentifier("my-metadata-identifier") md$setParentIdentifier("my-parent-metadata-identifier") md$setCharacterSet("utf8") md$setLanguage("eng") md$setDateStamp(ISOdate(2015, 1, 1, 1)) md$setMetadataStandardName("ISO 19115:2003/19139") md$setMetadataStandardVersion("1.0") md$setDataSetURI("my-dataset-identifier") eng <- ISOLocale$new() eng$setId("EN") eng$setLanguage("EN") eng$setCharacterSet("utf8") md$addLocale(eng) fr <- ISOLocale$new() fr$setId("FR") fr$setLanguage("FR") fr$setCharacterSet("utf8") md$addLocale(fr) esp <- ISOLocale$new() esp$setLanguage("ES") esp$setCharacterSet("utf8") md$addLocale(esp) chi <- ISOLocale$new() chi$setLanguage("ZH") chi$setCharacterSet("utf8") md$addLocale(chi) ru <- ISOLocale$new() ru$setLanguage("RU") ru$setCharacterSet("utf8") md$addLocale(ru) ar <- ISOLocale$new() ar$setLanguage("AR") ar$setCharacterSet("utf8") md$addLocale(ar) for(i in 1:3){ rp <- ISOResponsibleParty$new() rp$setIndividualName( "someone", locales = list( EN = paste("name in english",i), FR = paste("nom en français",i), ES = paste("Nombre en español",i), AR = paste("الاسم باللغة العربية",i), RU = paste("имя на русском",i), ZH = paste("中文名",i) )) rp$setOrganisationName( "organization", locales = list( EN = "organization", FR = "organisation", ES = "organización", AR = "منظمة", RU = "организация", ZH = "组织" )) rp$setPositionName( "someposition", locales = list( EN = paste("my position",i), FR = paste("mon poste",i), ES = paste("mi posición",i), AR = paste("موقعي",i), RU = paste("моя позиция",i), ZH = paste("我的位置",i) ) ) rp$setRole("pointOfContact") contact <- ISOContact$new() phone <- ISOTelephone$new() phone$setVoice( "myphonenumber", locales = list( EN = "myphonenumber in UK", FR = "mon numéro en France", ES = "mi número en España", AR = "رقم هاتفي في المملكة العربية السعودية", RU = "мой номер телефона в России", ZH = "我在中国的电话号码" ) ) phone$setFacsimile( "myfacsimile", locales = list( EN = "mi facsimile in UK", FR = "mon cax en France", ES = "mi fax en España", AR = "فاكس بلدي في المملكة العربية السعودية", RU = "мой факс в россии", ZH = "我在中国的传真" ) ) contact$setPhone(phone) address <- ISOAddress$new() address$setDeliveryPoint( "theaddress", locales = list( EN = "address in UK", FR = "adresse en France", ES = "dirección en España", AR = "العنوان في المملكة العربية السعودية", RU = "адрес в россии", ZH = "在中国的地址" )) address$setCity( "thecity", locales = list( EN = "thecity", FR="ville", ES="Ciudad", AR="مدينة", RU="город", ZH="城市" )) address$setPostalCode( "111", locales=list( EN="111_UK",FR="111_FR",ES="111_ES",AR="111_AR",RU="111_RU",ZH="111_ZH" ) ) address$setCountry( "United Kingdom", locales=list( EN="United Kingdom", FR="France", ES="España", AR="العربية السعودية", RU="Россия", ZH = "网站名称" ) ) address$setEmail( "[email protected]", locales = list( EN=paste0("someoneinuk",i,"@theorg.org"), FR=paste0("someoneinfrance",i,"@theorg.org"), ES=paste0("someoneinspain",i,"@theorg.org"), AR=paste0("someoneinsaudiarabia",i,"@theorg.org"), RU=paste0("someoneinrussia",i,"@theorg.org"), ZH=paste0("someoneinchina",i,"@theorg.org") ) ) contact$setAddress(address) res <- ISOOnlineResource$new() res$setLinkage("http://www.somewhereovertheweb.org") res$setName( "name", locales=list( EN="name of the website", FR="nom du site internet", ES="nombre del sitio web", AR="اسم الموقع", RU="название сайта", ZH="网站名称" )) res$setDescription( "description", locales = list( EN="description_EN", FR="description_FR", ES="description_ES", AR="description_AR", RU="description_RU", ZH="description_ZH" )) res$setProtocol( "protocol", locales=list( EN="protocol_EN", FR="protocol_FR", ES="protocol_ES", AR="protocol_AR", RU="protocol_RU", ZH="protocol_ZH" )) contact$setOnlineResource(res) rp$setContactInfo(contact) expect_true(md$addContact(rp)) } expect_equal(length(md$contact), 3L) expect_true(md$delContact(rp)) expect_equal(length(md$contact), 2L) vsr <- ISOVectorSpatialRepresentation$new() vsr$setTopologyLevel("geometryOnly") geomObject <- ISOGeometricObjects$new() geomObject$setGeometricObjectType("surface") geomObject$setGeometricObjectCount(5L) vsr$setGeometricObjects(geomObject) expect_true(md$addSpatialRepresentationInfo(vsr)) expect_false(md$addSpatialRepresentationInfo(vsr)) geomObject$setGeometricObjectCount(6L) expect_true(md$delSpatialRepresentationInfo(vsr)) rs <- ISOReferenceSystem$new() rsId <- ISOReferenceIdentifier$new(code = "4326", codeSpace = "EPSG") rs$setReferenceSystemIdentifier(rsId) md$setReferenceSystemInfo(rs) ident <- ISODataIdentification$new() ident$setAbstract( "abstract", locales = list( EN = "abstract", FR = "résumé", ES = "resumen", AR = "ملخص", RU = "резюме", ZH = "摘要" )) ident$setPurpose( "purpose", locales = list( EN = "purpose", FR = "objectif", ES = "objetivo", AR = "غرض", RU = "цель", ZH = "目的" )) ident$setLanguage("eng") ident$setCharacterSet("utf8") ident$addTopicCategory("biota") ident$addTopicCategory("oceans") rp <- ISOResponsibleParty$new() rp$setIndividualName( "someone", locales = list( EN = "name in english", FR = "nom en français", ES = "Nombre en español", AR = "الاسم باللغة العربية", RU = "имя на русском", ZH = "中文名" )) rp$setOrganisationName( "organization", locales = list( EN = "organization", FR = "organisation", ES = "organización", AR = "منظمة", RU = "организация", ZH = "组织" )) rp$setPositionName( "someposition", locales = list( EN = "my position", FR = "mon poste", ES = "mi posición", AR = "موقعي", RU = "моя позиция", ZH = "我的位置" ) ) rp$setRole("pointOfContact") contact <- ISOContact$new() phone <- ISOTelephone$new() phone$setVoice( "myphonenumber", locales = list( EN = "myphonenumber in UK", FR = "mon numéro en France", ES = "mi número en España", AR = "رقم هاتفي في المملكة العربية السعودية", RU = "мой номер телефона в России", ZH = "我在中国的电话号码" ) ) phone$setFacsimile( "myfacsimile", locales = list( EN = "mi facsimile in UK", FR = "mon cax en France", ES = "mi fax en España", AR = "فاكس بلدي في المملكة العربية السعودية", RU = "мой факс в россии", ZH = "我在中国的传真" ) ) contact$setPhone(phone) address <- ISOAddress$new() address$setDeliveryPoint( "theaddress", locales = list( EN = "address in UK", FR = "adresse en France", ES = "dirección en España", AR = "العنوان في المملكة العربية السعودية", RU = "адрес в россии", ZH = "在中国的地址" )) address$setCity( "thecity", locales = list( EN = "thecity", FR="ville", ES="Ciudad", AR="مدينة", RU="город", ZH="城市" )) address$setPostalCode( "111", locales=list( EN="111_UK",FR="111_FR",ES="111_ES",AR="111_AR",RU="111_RU",ZH="111_ZH" ) ) address$setCountry( "United Kingdom", locales=list( EN="United Kingdom", FR="France", ES="España", AR="العربية السعودية", RU="Россия", ZH = "网站名称" ) ) address$setEmail( "[email protected]", locales = list( EN="[email protected]", FR="[email protected]", ES="[email protected]", AR="[email protected]", RU="[email protected]", ZH="[email protected]" ) ) contact$setAddress(address) res <- ISOOnlineResource$new() res$setLinkage("http://www.somewhereovertheweb.org") res$setName( "name", locales=list( EN="name of the website", FR="nom du site internet", ES="nombre del sitio web", AR="اسم الموقع", RU="название сайта", ZH="网站名称" )) res$setDescription( "description", locales = list( EN="description_EN", FR="description_FR", ES="description_ES", AR="description_AR", RU="description_RU", ZH="description_ZH" )) res$setProtocol( "protocol", locales=list( EN="protocol_EN", FR="protocol_FR", ES="protocol_ES", AR="protocol_AR", RU="protocol_RU", ZH="protocol_ZH" )) contact$setOnlineResource(res) rp$setContactInfo(contact) ident$addPointOfContact(rp) ct <- ISOCitation$new() ct$setTitle( "sometitle", locales = list( EN = "title", FR = "titre", ES = "título", AR = "لقبان", RU = "название", ZH = "标题" ) ) d <- ISODate$new() d$setDate(ISOdate(2015, 1, 1, 1)) d$setDateType("publication") ct$addDate(d) ct$setEdition("1.0") ct$setEditionDate(ISOdate(2015,1,1)) ct$addIdentifier(ISOMetaIdentifier$new(code = "identifier")) ct$addPresentationForm("mapDigital") ct$addCitedResponsibleParty(rp) ident$setCitation(ct) go <- ISOBrowseGraphic$new() go$setFileName("http://wwww.somefile.org/png") go$setFileDescription( "Map overview", locales = list( EN = "Map overview", FR = "Aperçu de carte", ES = "Vista general del mapa", AR = "نظرة عامة على الخريطة", RU = "Обзор карты", ZH = "地图概述" ) ) ident$setGraphicOverview(go) mi <- ISOMaintenanceInformation$new() mi$setMaintenanceFrequency("daily") ident$setResourceMaintenance(mi) lc <- ISOLegalConstraints$new() lc$addUseLimitation( "use limitation 1", locales= list( EN = "use limitation 1", FR = "limitation d'utilisation 1", ES = "limitación de uso 1", AR = "الحد من الاستخدام 1", RU = "предел использования 1", ZH = "使用限制1" )) lc$addUseLimitation( "use limitation 2", locales= list( EN = "use limitation 2", FR = "limitation d'utilisation 2", ES = "limitación de uso 2", AR = "2 الحد من الاستخدام ", RU = "предел использования 2", ZH = "使用限制2" )) lc$addAccessConstraint("copyright") lc$addAccessConstraint("license") lc$addUseConstraint("copyright") lc$addUseConstraint("license") expect_equal(length(lc$useLimitation), 2L) expect_equal(length(lc$accessConstraints), 2L) expect_equal(length(lc$useConstraints), 2L) ident$setResourceConstraints(lc) extent <- ISOExtent$new() bbox <- ISOGeographicBoundingBox$new(minx = -180, miny = -90, maxx = 180, maxy = 90) extent$setGeographicElement(bbox) ident$setExtent(extent) kwds <- ISOKeywords$new() kwds$addKeyword( "keyword1", locales = list( EN = "keyword 1", FR = "mot-clé 1", ES = "palabra clave 1", AR = "1 الكلمة", RU = "ключевое слово 1", ZH = "关键词 1" )) kwds$addKeyword( "keyword1", locales = list( EN = "keyword 2", FR = "mot-clé 2", ES = "palabra clave 2", AR = "2 الكلمة", RU = "ключевое слово 2", ZH = "关键词 2" )) kwds$setKeywordType("theme") th <- ISOCitation$new() th$setTitle( "General", locales =list( EN = "General", FR = "Général", ES = "General", AR = "جنرال لواء", RU = "генеральный", ZH = "一般" )) th$addDate(d) kwds$setThesaurusName(th) ident$addKeywords(kwds) ident$setSupplementalInformation( "additional information", locales = list( EN = "additional information", FR = "information additionnelle", ES = "información adicional", AR = "معلومة اضافية", RU = "Дополнительная информация", ZH = "附加信息" )) md$setIdentificationInfo(ident) distrib <- ISODistribution$new() dto <- ISODigitalTransferOptions$new() or <- ISOOnlineResource$new() or$setLinkage("http://somelink") or$setName( "name", locales=list( EN="name of the website", FR="nom du site internet", ES="nombre del sitio web", AR="اسم الموقع", RU="название сайта", ZH="网站名称" )) or$setDescription( "description", locales = list( EN="description_EN", FR="description_FR", ES="description_ES", AR="description_AR", RU="description_RU", ZH="description_ZH" )) or$setProtocol( "protocol", locales=list( EN="protocol_EN", FR="protocol_FR", ES="protocol_ES", AR="protocol_AR", RU="protocol_RU", ZH="protocol_ZH" )) dto$addOnlineResource(or) distrib$setDigitalTransferOptions(dto) format <- ISOFormat$new() format$setName( "someone", locales = list( EN = "name in english", FR = "nom en français", ES = "Nombre en español", AR = "الاسم باللغة العربية", RU = "имя на русском", ZH = "中文名" )) format$setVersion("1.0") format$setAmendmentNumber("2") format$setSpecification( "specification title", locales = list( EN="specification title", FR="Titre de la spécification", ES="Título de la especificación", AR="عنوان المواصفات", RU="название спецификации", ZH="规范的标题" )) distrib$addFormat(format) md$setDistributionInfo(distrib) dq <- ISODataQuality$new() scope <- ISOScope$new() scope$setLevel("dataset") dq$setScope(scope) dc <- ISODomainConsistency$new() result <- ISOConformanceResult$new() spec <- ISOCitation$new() spec$setTitle( "specification title", locales = list( EN="specification title", FR="Titre de la spécification", ES="Título de la especificación", AR="عنوان المواصفات", RU="название спецификации", ZH="规范的标题" )) spec$addAlternateTitle( "specification alternate title", locales = list( EN="specification alternate title", FR="Titre alternatif de la spécification", ES="Título alternativo de la especificación", AR="عنوان بديل للمواصفات", RU="альтернативное название спецификации", ZH="规范的替代标题" )) d <- ISODate$new() d$setDate(ISOdate(2015, 1, 1, 1)) d$setDateType("publication") spec$addDate(d) result$setSpecification(spec) result$setExplanation( "explanation about the conformance", locales = list( EN = "explanation about the conformance", FR = "explication à propos de la conformité", ES = "explicación sobre la conformidad", AR = "شرح حول التوافق", RU = "объяснение о соответствии", ZH = "关于一致性的解释" )) result$setPass(TRUE) dc$addResult(result) dq$addReport(dc) lineage <- ISOLineage$new() lineage$setStatement( "statement", locales = list( EN = "statement", FR = "déclaration", ES = "declaración", AR = "بيان", RU = "заявление", ZH = "声明" )) dq$setLineage(lineage) md$setDataQualityInfo(dq) xml <- md$encode() expect_is(xml, "XMLInternalNode") md2 <- ISOImageryMetadata$new(xml = xml) xml2 <- md2$encode() expect_true(ISOAbstractObject$compare(md, md2)) md$save("test.xml") md3 <- readISO19139("test.xml") expect_true(ISOAbstractObject$compare(md, md3)) })
setClass("Stream", representation(url = "character", requestedStarttime = "POSIXct", requestedEndtime = "POSIXct", act_flags = "integer", io_flags = "integer", dq_flags = "integer", timing_qual = "numeric", traces = "list"), prototype(url = "", requestedStarttime = as.POSIXct("1900-01-01T00:00:00",format="%Y-%m-%dT%H:%M:%OS6", tz="GMT"), requestedEndtime = as.POSIXct("1900-01-01T00:00:00",format="%Y-%m-%dT%H:%M:%OS6", tz="GMT"), act_flags = rep(as.integer(0),8), io_flags = rep(as.integer(0),8), dq_flags = rep(as.integer(0),8), timing_qual = as.numeric(NA), traces = list(new("Trace"))) ) if (!isGeneric("uniqueIds")) { setGeneric("uniqueIds", function(x) { standardGeneric("uniqueIds") }) } uniqueIds.Stream <- function(x, na.rm=FALSE) { ids <- unlist(lapply(x@traces, slot, "id")) return( unique(ids) ) } setMethod("uniqueIds", signature(x="Stream"), function(x) uniqueIds.Stream(x)) if (!isGeneric("parallelLength")) { setGeneric("parallelLength", function(x) { standardGeneric("parallelLength") }) } parallelLength.Stream <- function(x, na.rm=FALSE) { return( unlist(lapply(x@traces, function(element) length(element))) ) } setMethod("parallelLength", signature(x="Stream"), function(x) parallelLength.Stream(x)) if (!isGeneric("parallelMax")) { setGeneric("parallelMax", function(x, na.rm) { standardGeneric("parallelMax") }) } parallelMax.Stream <- function(x, na.rm) { return( unlist(lapply(x@traces, function(element) max(element, na.rm=na.rm))) ) } setMethod("parallelMax", signature(x="Stream", na.rm="logical"), function(x, na.rm) parallelMax.Stream(x, na.rm=na.rm)) setMethod("parallelMax", signature(x="Stream", na.rm="missing"), function(x, na.rm) parallelMax.Stream(x, na.rm=FALSE)) if (!isGeneric("parallelMean")) { setGeneric("parallelMean", function(x, na.rm) { standardGeneric("parallelMean") }) } parallelMean.Stream <- function(x, na.rm) { return( unlist(lapply(x@traces, function(element) mean(element, na.rm=na.rm))) ) } setMethod("parallelMean", signature(x="Stream", na.rm="logical"), function(x, na.rm) parallelMean.Stream(x, na.rm=na.rm)) setMethod("parallelMean", signature(x="Stream", na.rm="missing"), function(x, na.rm) parallelMean.Stream(x, na.rm=FALSE)) if (!isGeneric("parallelMin")) { setGeneric("parallelMin", function(x, na.rm) { standardGeneric("parallelMin") }) } parallelMin.Stream <- function(x, na.rm) { return( unlist(lapply(x@traces, function(element) min(element, na.rm=na.rm))) ) } setMethod("parallelMin", signature(x="Stream", na.rm="logical"), function(x, na.rm) parallelMin.Stream(x, na.rm=na.rm)) setMethod("parallelMin", signature(x="Stream", na.rm="missing"), function(x, na.rm) parallelMin.Stream(x, na.rm=FALSE)) if (!isGeneric("parallelMedian")) { setGeneric("parallelMedian", function(x, na.rm) { standardGeneric("parallelMedian") }) } parallelMedian.Stream <- function(x, na.rm) { return( unlist(lapply(x@traces, function(element) median(element, na.rm=na.rm))) ) } setMethod("parallelMedian", signature(x="Stream", na.rm="logical"), function(x, na.rm) parallelMedian.Stream(x, na.rm=na.rm)) setMethod("parallelMedian", signature(x="Stream", na.rm="missing"), function(x, na.rm) parallelMedian.Stream(x, na.rm=FALSE)) if (!isGeneric("parallelSd")) { setGeneric("parallelSd", function(x, na.rm) { standardGeneric("parallelSd") }) } parallelSd.Stream <- function(x, na.rm) { return( unlist(lapply(x@traces, function(element) sd(element, na.rm=na.rm))) ) } setMethod("parallelSd", signature(x="Stream", na.rm="logical"), function(x, na.rm) parallelSd.Stream(x, na.rm=na.rm)) setMethod("parallelSd", signature(x="Stream", na.rm="missing"), function(x, na.rm) parallelSd.Stream(x, na.rm=FALSE)) if (!isGeneric("parallelRms")) { setGeneric("parallelRms", function(x, na.rm) { standardGeneric("parallelRms") }) } parallelRms.Stream <- function(x, na.rm) { return( unlist(lapply(x@traces, function(element) rms(element, na.rm=na.rm))) ) } setMethod("parallelRms", signature(x="Stream", na.rm="logical"), function(x, na.rm) parallelRms.Stream(x, na.rm=na.rm)) setMethod("parallelRms", signature(x="Stream", na.rm="missing"), function(x, na.rm) parallelRms.Stream(x, na.rm=FALSE)) if (!isGeneric("parallelRmsVariance")) { setGeneric("parallelRmsVariance", function(x, na.rm) { standardGeneric("parallelRmsVariance") }) } parallelRmsVariance.Stream <- function(x, na.rm) { return( unlist(lapply(x@traces, function(element) rmsVariance(element, na.rm=na.rm))) ) } setMethod("parallelRmsVariance", signature(x="Stream", na.rm="logical"), function(x, na.rm) parallelRmsVariance.Stream(x, na.rm=na.rm)) setMethod("parallelRmsVariance", signature(x="Stream", na.rm="missing"), function(x, na.rm) parallelRmsVariance.Stream(x, na.rm=FALSE)) length.Stream <- function(x) { return( sum(parallelLength(x)) ) } setMethod("length", signature(x="Stream"), function(x) length.Stream(x)) max.Stream <- function(x, ..., na.rm=FALSE) { return( max(parallelMax(x, na.rm=na.rm)) ) } setMethod("max", signature(x="Stream"), function(x, ...) max.Stream(x, ...)) mean.Stream <- function(x, ...) { data <- unlist(lapply(x@traces, slot, "data")) return( mean(data, ...) ) } setMethod("mean", signature(x="Stream"), function(x, ...) mean.Stream(x, ...)) min.Stream <- function(x, ..., na.rm=FALSE) { return( min(parallelMin(x, na.rm=na.rm)) ) } setMethod("min", signature(x="Stream"), function(x, ...) min.Stream(x, ...)) median.Stream <- function(x, na.rm) { data <- unlist(lapply(x@traces, slot, "data")) return( median(data, na.rm=na.rm) ) } setMethod("median", signature(x="Stream", na.rm="logical"), function(x, na.rm) median.Stream(x, na.rm=na.rm)) setMethod("median", signature(x="Stream", na.rm="missing"), function(x, na.rm) median.Stream(x, na.rm=FALSE)) sd.Stream <- function(x, na.rm) { data <- unlist(lapply(x@traces, slot, "data")) return( sd(data, na.rm=na.rm) ) } setMethod("sd", signature(x="Stream", na.rm="logical"), function(x, na.rm) sd.Stream(x, na.rm=na.rm)) setMethod("sd", signature(x="Stream", na.rm="missing"), function(x, na.rm) sd.Stream(x, na.rm=FALSE)) if (!isGeneric("rms")) { setGeneric("rms", function(x, na.rm) { standardGeneric("rms") }) } rms.Stream <- function(x, na.rm) { data <- unlist(lapply(x@traces, slot, "data")) return( sqrt( mean((data)^2, na.rm=na.rm) ) ) } setMethod("rms", signature("Stream", na.rm="logical"), function(x, na.rm) rms.Stream(x, na.rm=na.rm)) setMethod("rms", signature("Stream", na.rm="missing"), function(x, na.rm) rms.Stream(x, na.rm=FALSE)) if (!isGeneric("rmsVariance")) { setGeneric("rmsVariance", function(x, na.rm) { standardGeneric("rmsVariance") }) } rmsVariance.Stream <- function(x, na.rm) { data <- unlist(lapply(x@traces, slot, "data")) mean <- mean(data, na.rm=na.rm) if (na.rm) { n <- length(data)-length(which(is.na(data))) } else { n <- length(data) } return( sqrt( sum((data-mean)^2,na.rm=na.rm) / n ) ) } setMethod("rmsVariance", signature("Stream", na.rm="logical"), function(x, na.rm) rmsVariance.Stream(x, na.rm=na.rm)) setMethod("rmsVariance", signature("Stream", na.rm="missing"), function(x, na.rm) rmsVariance.Stream(x, na.rm=FALSE)) if (!isGeneric("multiplyBy")) { setGeneric("multiplyBy", function(x, y) { standardGeneric("multiplyBy") }) } multiplyBy.Stream <- function(x, y) { traces <- lapply(x@traces, function(element) multiplyBy(element, y=y)) return( new("Stream", url=x@url, requestedStarttime=x@requestedStarttime, requestedEndtime=x@requestedEndtime, act_flags=x@act_flags, io_flags=x@io_flags, dq_flags=x@dq_flags, timing_qual=x@timing_qual, traces=traces) ) } setMethod("multiplyBy", signature("Stream", y="numeric"), function(x, y) multiplyBy.Stream(x, y=y)) if (!isGeneric("getGaps")) { setGeneric("getGaps", function(x, min_gap) { standardGeneric("getGaps") }) } getGaps.Stream <- function(x, min_gap) { num_ids <- length(uniqueIds(x)) if (num_ids > 1) { stop(paste("getGaps.Stream:",num_ids,"unique ids encountered in Stream.")) } headers <- lapply(x@traces, slot, "stats") num_headers <- length(headers) sampling_rates <- sapply(headers, slot, "sampling_rate") if (any(sampling_rates < 0 )) { stop(paste("getGaps.Stream: encountered sampling rate < 0")) } gaps <- numeric(num_headers+1) nsamples <- integer(num_headers+1) for ( i in seq(from=1, to=num_headers)) { if (i == 1) { sampling_rate <- sampling_rates[1] min_gap_new <- ifelse(is.null(min_gap), 1/sampling_rate, min_gap) min_gap_new <- max(min_gap_new, 1/sampling_rate) delta <- as.numeric(difftime(headers[[1]]@starttime, x@requestedStarttime, units="secs")) - 1/sampling_rate if (delta > min_gap_new - 0.5/sampling_rate) { gaps[1] <- delta + 1/sampling_rate nsamples[1] <- as.integer(round(gaps[1] * sampling_rate)) } else { gaps[1] <- 0 nsamples[1] <- 0 } } else { sampling_rate <- sampling_rates[[i-1]] min_gap_new <- ifelse(is.null(min_gap), 1/sampling_rate, min_gap) min_gap_new <- max(min_gap_new, 1/sampling_rate) h1 <- headers[[i-1]] h2 <- headers[[i]] delta <- difftime(h2@starttime, h1@endtime, units="secs") - 1/sampling_rate if (abs(delta) > min_gap_new - 0.5/sampling_rate) { gaps[i] <- delta nsamples[i] <- as.integer(round(abs(delta) * sampling_rate)) } else { gaps[i] <- 0 nsamples[i] <- 0 } } if (i == num_headers) { sampling_rate <- sampling_rates[[i]] min_gap_new <- ifelse(is.null(min_gap), 1/sampling_rate, min_gap) min_gap_new <- max(min_gap_new, 1/sampling_rate) delta <- as.numeric(difftime(x@requestedEndtime, headers[[num_headers]]@endtime, units="secs")) - 1/sampling_rate if (delta > min_gap_new - 0.5/sampling_rate) { gaps[num_headers+1] <- delta nsamples[num_headers+1] <- as.integer(round(delta * sampling_rate)) } else { gaps[num_headers+1] <- 0 nsamples[num_headers+1] <- 0 } } } gap_list <- list(gaps=gaps, nsamples=nsamples) return(gap_list) } setMethod("getGaps", signature(x="Stream", min_gap="numeric"), function(x, min_gap) getGaps.Stream(x, min_gap)) setMethod("getGaps", signature(x="Stream", min_gap="missing"), function(x, min_gap) getGaps.Stream(x, NULL)) if (!isGeneric("getUpDownTimes")) { setGeneric("getUpDownTimes", function(x, min_signal, min_gap) { standardGeneric("getUpDownTimes") }) } getUpDownTimes.Stream <- function(x, min_signal, min_gap) { num_ids <- length(uniqueIds(x)) if (num_ids > 1) { stop(paste("getUpDownTimes.Stream:",num_ids,"unique ids encountered in Stream.")) } headerList <- lapply(x@traces, slot, "stats") starttimeList <- lapply(headerList, slot, "starttime") endtimeList <- lapply(headerList, slot, "endtime") starttimes <- as.POSIXct(unlist(lapply(starttimeList, strftime, format="%Y-%m-%dT%H:%M:%OS", tz="GMT")), format="%Y-%m-%dT%H:%M:%OS", tz="GMT") endtimes <- as.POSIXct(unlist(lapply(endtimeList, strftime, format="%Y-%m-%dT%H:%M:%OS", tz="GMT")), format="%Y-%m-%dT%H:%M:%OS", tz="GMT") signal_durations <- difftime(endtimes, starttimes, units="sec") good_traces_flag <- signal_durations >= min_signal headerList <- headerList[good_traces_flag] starttimes <- starttimes[good_traces_flag] endtimes <- endtimes[good_traces_flag] num_headers <- length(headerList) if (num_headers == 1) { up_down_times <- c(starttimes[1], endtimes[1]) return(up_down_times) } up_down_times <- c(starttimes,endtimes) for (i in seq(num_headers-1)) { delta <- difftime(starttimes[i+1], endtimes[i], units="secs") if (delta < 0 || delta < min_gap) { up_down_times[(2*i)] <- NA up_down_times[(2*i)+1] <- NA } else { up_down_times[(2*i)] <- endtimes[i] up_down_times[(2*i)+1] <- starttimes[i+1] } } return(stats::na.omit(up_down_times)) } setMethod("getUpDownTimes", signature(x="Stream", min_signal="numeric", min_gap="numeric"), function(x, min_signal, min_gap) getUpDownTimes.Stream(x, min_signal, min_gap)) setMethod("getUpDownTimes", signature(x="Stream", min_signal="missing", min_gap="missing"), function(x, min_signal, min_gap) getUpDownTimes.Stream(x, min_signal=30, min_gap=60)) if (!isGeneric("slice")) { setGeneric("slice", function(x, starttime, endtime) { standardGeneric("slice") }) } slice.Stream <- function(x, starttime, endtime) { num_traces <- length(x@traces) stream_start <- x@traces[[1]]@stats@starttime stream_end <- x@traces[[num_traces]]@stats@endtime if (starttime >= endtime) { stop(paste("slice.Stream: requested starttime \"", starttime, "\" >= requested endtime \"", endtime, "\"")) } if (starttime >= stream_end) { stop(paste("slice.Stream: requested starttime \"", starttime, "\" >= Stream endtime \"", stream_end, "\"")) } if (endtime <= stream_start) { stop(paste("slice.Stream: requested endtime \"", endtime, "\" <= Stream starttime \"", stream_start, "\"")) } traces <- list() for (i in seq(num_traces)) { tr <- x@traces[[i]] if (starttime >= tr@stats@endtime || endtime <= tr@stats@starttime) { } else if (starttime <= tr@stats@starttime && endtime >= tr@stats@endtime) { traces <- append(traces,tr) } else { sliced_trace <- slice(tr, starttime, endtime) traces <- append(traces, sliced_trace) } } return( new("Stream", url=x@url, requestedStarttime=starttime, requestedEndtime=endtime, act_flags=x@act_flags, io_flags=x@io_flags, dq_flags=x@dq_flags, timing_qual=x@timing_qual, traces=traces) ) } setMethod("slice", signature(x="Stream", starttime="POSIXct", endtime="POSIXct"), function(x, starttime, endtime) slice.Stream(x, starttime=starttime, endtime=endtime)) if (!isGeneric("mergeTraces")) { setGeneric("mergeTraces", function(x, fillMethod) { standardGeneric("mergeTraces") }) } mergeTraces.Stream <- function(x, fillMethod) { num_traces <- length(x@traces) if (sum(getGaps(x)$nsamples) == 0 && num_traces == 1) { return(x) } gapInfo <- getGaps(x) num_gaps <- length(gapInfo$nsamples) if (num_gaps != num_traces+1) { stop(paste("mergeTraces.Stream: num_gaps (",num_gaps,") should be one more than num_traces (",num_traces,")", sep="")) } headers <- lapply(x@traces, slot, "stats") sampling_rates <- sapply(headers, slot, "sampling_rate") num_rates <- length(unique(round(sampling_rates,digits=4))) if ( ! all(stats::dist(unique(sampling_rates)) < 0.0002 )) { stop(paste("mergeTraces.Stream:",num_rates,"unique sampling rates encountered in Stream.")) } if (gapInfo$nsamples[1] == 0) { totalStart <- x@traces[[1]]@stats@starttime } else { totalStart <- x@requestedStarttime } if (gapInfo$nsamples[length(gapInfo$nsamples)] == 0) { totalEnd <- x@traces[[length(x@traces)]]@stats@endtime } else { totalEnd <- x@requestedEndtime } totalSecs <- as.numeric(difftime(totalEnd, totalStart, units="secs")) totalPoints <- as.integer(round(totalSecs) * x@traces[[1]]@stats@sampling_rate) num_vectors <- num_gaps + num_traces dataList <- vector('list',num_vectors) if (fillMethod == "fillNA") { for (i in seq(num_traces)) { dataList[[2*i-1]] <- rep(NA,gapInfo$nsamples[i]) dataList[[2*i]] <- x@traces[[i]]@data } dataList[[num_vectors]] <- rep(NA,gapInfo$nsamples[[num_gaps]]) } else if (fillMethod == "fillZero") { for (i in seq(num_traces)) { dataList[[2*i-1]] <- rep(0,gapInfo$nsamples[i]) dataList[[2*i]] <- x@traces[[i]]@data } dataList[[num_vectors]] <- rep(0,gapInfo$nsamples[[num_gaps]]) } else { stop(paste("mergeTraces.Stream: unknown fillMethod '", fillMethod, "'",sep="")) } data <- unlist(dataList) missing_points <- totalPoints - length(data) if ( missing_points > ceiling(2 * x@traces[[1]]@stats@sampling_rate) ) { stop(paste("mergeTraces.Stream:", missing_points, "unaccounted for points after merge")) } else if ( missing_points < ceiling(-2 * x@traces[[1]]@stats@sampling_rate) ) { stop(paste("mergeTraces.Stream:", abs(missing_points), "extra points after merge")) } if (missing_points > 0) { data <- c(data,rep(NA,missing_points)) } stats <- x@traces[[1]]@stats stats@npts <- as.integer(totalPoints) if (gapInfo$nsamples[1] == 0) { stats@starttime <- x@traces[[1]]@stats@starttime } else { stats@starttime <- x@requestedStarttime } if (gapInfo$nsamples[length(gapInfo$nsamples)] == 0) { stats@endtime <- x@traces[[length(x@traces)]]@stats@endtime } else { stats@endtime <- x@requestedEndtime } stats@processing <- append(stats@processing,paste(num_traces," traces merged into a single trace using method '",fillMethod,"'",sep="")) id <- x@traces[[1]]@id Sensor <- x@traces[[1]]@Sensor InstrumentSensitivity <- x@traces[[1]]@InstrumentSensitivity SensitivityFrequency <- x@traces[[1]]@SensitivityFrequency InputUnits <- x@traces[[1]]@InputUnits traces <- list( new("Trace", id, stats, Sensor, InstrumentSensitivity, SensitivityFrequency, InputUnits, data=data[1:totalPoints]) ) return( new("Stream", url=x@url, requestedStarttime=x@requestedStarttime, requestedEndtime=x@requestedEndtime, act_flags=x@act_flags, io_flags=x@io_flags, dq_flags=x@dq_flags, timing_qual=x@timing_qual, traces=traces) ) } setMethod("mergeTraces", signature(x="Stream", fillMethod="character"), function(x, fillMethod) mergeTraces.Stream(x, fillMethod=fillMethod)) setMethod("mergeTraces", signature(x="Stream", fillMethod="missing"), function(x, fillMethod) mergeTraces.Stream(x, fillMethod="fillNA")) if (!isGeneric("plotUpDownTimes")) { setGeneric("plotUpDownTimes", function(x, min_signal, min_gap, ...) { standardGeneric("plotUpDownTimes") }) } plotUpDownTimes.Stream <- function(x, min_signal=30, min_gap=60, ...) { upDownTimes <- getUpDownTimes(x, min_signal=min_signal, min_gap=min_gap) GMTTimes <- as.POSIXct(upDownTimes, "%Y-%m-%dT%H:%M:%OS", tz="GMT") onOffs <- seq(length(GMTTimes)) %% 2 allTimes <- c(x@requestedStarttime, GMTTimes, x@requestedEndtime) allOnOffs <- c(0,onOffs,0) plot(allTimes, allOnOffs, type="s", xlab="GMT", ylab="", yaxt="n", ...) graphics::axis(2, at=c(0,1), labels=c("Off","On"), las=1, tick=TRUE) graphics::abline(v=x@requestedEndtime, lwd=3, col='white') graphics::box() id <- stringr::str_sub(x@traces[[1]]@id, 1, stringr::str_length(x@traces[[1]]@id)-2) main <- paste("On/Off transitions for ",id) sensorText <- paste("(", x@traces[[1]]@Sensor, ")") graphics::title(main) graphics::mtext(sensorText, line=0.2) } plotUpDownTimes.POSIXct <- function(x, min_signal=30, min_gap=60, ...) { upDownTimes <- x GMTTimes <- as.POSIXct(upDownTimes, "%Y-%m-%dT%H:%M:%OS", tz="GMT") onOff <- seq(length(GMTTimes)) %% 2 plot(GMTTimes, onOff, type="s", xlab="GMT", ylab="", yaxt="n", ...) graphics::axis(2, at=c(0,1), labels=c("Off","On"), las=1, tick=TRUE) graphics::abline(v=upDownTimes[length(upDownTimes)], lwd=2, col='white') graphics::box() } setMethod("plotUpDownTimes", signature(x="Stream", min_signal="numeric", min_gap="numeric"), function(x, min_signal, min_gap, ...) plotUpDownTimes.Stream(x, min_signal, min_gap=min_gap, ...)) setMethod("plotUpDownTimes", signature(x="Stream", min_signal="numeric", min_gap="missing"), function(x, min_signal, min_gap, ...) plotUpDownTimes.Stream(x, min_signal, min_gap=60, ...)) setMethod("plotUpDownTimes", signature(x="Stream", min_signal="missing", min_gap="numeric"), function(x, min_signal, min_gap, ...) plotUpDownTimes.Stream(x, min_signal=30, min_gap, ...)) setMethod("plotUpDownTimes", signature(x="Stream", min_signal="missing", min_gap="missing"), function(x, min_signal, min_gap, ...) plotUpDownTimes.Stream(x, min_signal=30, min_gap=60, ...)) setMethod("plotUpDownTimes", signature(x="POSIXct", min_signal="numeric", min_gap="numeric"), function(x, min_signal, min_gap, ...) plotUpDownTimes.POSIXct(x, min_signal, min_gap, ...)) setMethod("plotUpDownTimes", signature(x="POSIXct", min_signal="numeric", min_gap="missing"), function(x, min_signal, min_gap, ...) plotUpDownTimes.POSIXct(x, min_signal=30, min_gap, ...)) setMethod("plotUpDownTimes", signature(x="POSIXct", min_signal="missing", min_gap="numeric"), function(x, min_signal, min_gap, ...) plotUpDownTimes.POSIXct(x, min_signal, min_gap=60, ...)) setMethod("plotUpDownTimes", signature(x="POSIXct", min_signal="missing", min_gap="missing"), function(x, min_signal, min_gap, ...) plotUpDownTimes.POSIXct(x, min_signal=30, min_gap=60, ...)) if (!isGeneric("mergeUpDownTimes")) { setGeneric("mergeUpDownTimes", function(udt1,udt2,bothOn) { standardGeneric("mergeUpDownTimes") }) } mergeUpDownTimes.POSIXct <- function(udt1,udt2,bothOn) { if (is.null(udt1)) { return(udt2) } if (is.null(udt2)) { return(udt1) } unsorted_times <- c(udt1,udt2) sort_indices <- order(unsorted_times) times <- unsorted_times[sort_indices] onOff1 <- (seq(length(udt1)) %% 2 - 0.5) * 2 onOff2 <- (seq(length(udt2)) %% 2 - 0.5) * 2 unsorted_onOff <- c(onOff1,onOff2) onOff <- unsorted_onOff[sort_indices] cumOnOff <- cumsum(onOff) if (bothOn) { both_up_indices <- which(cumOnOff == 2) any_down_indices <- both_up_indices + 1 both_upDownTimes <- sort(times[c(both_up_indices,any_down_indices)]) return(both_upDownTimes) } else { both_down_indices <- which(cumOnOff == 0) either_up_indices <- c(1, both_down_indices[-length(both_down_indices)] + 1) either_upDownTimes <- sort(times[c(either_up_indices,both_down_indices)]) return(either_upDownTimes) } } setMethod("mergeUpDownTimes", signature(udt1="POSIXct", udt2="POSIXct", bothOn="logical"), function(udt1,udt2,bothOn) mergeUpDownTimes.POSIXct(udt1,udt2,bothOn)) setMethod("mergeUpDownTimes", signature(udt1="POSIXct", udt2="POSIXct", bothOn="missing"), function(udt1,udt2,bothOn) mergeUpDownTimes.POSIXct(udt1,udt2,bothOn=FALSE)) setMethod("mergeUpDownTimes", signature(udt1="NULL", udt2="POSIXct", bothOn="logical"), function(udt1,udt2,bothOn) mergeUpDownTimes.POSIXct(udt1,udt2,bothOn)) setMethod("mergeUpDownTimes", signature(udt1="NULL", udt2="POSIXct", bothOn="missing"), function(udt1,udt2,bothOn) mergeUpDownTimes.POSIXct(udt1,udt2,bothOn=FALSE)) setMethod("mergeUpDownTimes", signature(udt1="POSIXct", udt2="NULL", bothOn="logical"), function(udt1,udt2,bothOn) mergeUpDownTimes.POSIXct(udt1,udt2,bothOn)) setMethod("mergeUpDownTimes", signature(udt1="POSIXct", udt2="NULL", bothOn="missing"), function(udt1,udt2,bothOn) mergeUpDownTimes.POSIXct(udt1,udt2,bothOn=FALSE)) plot.Stream <- function(x, ...) { tr <- mergeTraces(x)@traces[[1]] plot(tr, ...) if (length(x@traces) == 1) { graphics::mtext(paste(length(x@traces),"trace"), side=3, line=0.2, adj=0.95) } else { graphics::mtext(paste(length(x@traces),"traces"), side=3, line=0.2, adj=0.95) } } setMethod("plot", signature(x="Stream"), function(x, ...) plot.Stream(x, ...))
rmarkdown::render('batch_correction.Rmd') rmarkdown::render('correcting.Rmd') rmarkdown::render('differential_expression.Rmd') rmarkdown::render('seurat.Rmd') rmarkdown::render('variance_stabilizing_transformation.Rmd') rmarkdown::render('theta_regularization.Rmd') rmarkdown::render('method_comparison.Rmd')
tag <- function(thing, tag="") { tryCatch( withCallingHandlers(eval.parent(thing), warning=function(w) { w$tag <- tag warning(w) invokeRestart("muffleWarning") }), error=function(e) { e$tag <- tag stop(e) } ) invisible(NULL) } maybe <- function(f) { function(...) { returnValue <- NULL warningValue <- NULL warningTag <- NULL errorValue <- NULL errorTag <- NULL returnValue <- tryCatch( withCallingHandlers(f(...), warning=function(w) { warningValue <<- append(warningValue, w$message) wtag <- if(is.null(w$tag)) "" else w$tag warningTag <<- append(warningTag, wtag) invokeRestart("muffleWarning") }), error=function(e) { errorValue <<- e$message errorTag <<- if(is.null(e$tag)) "" else e$tag return(NULL) } ) rval <- list() class(rval) <- "Maybe" rval["value"] <- list(returnValue) rval["warning"] <- list(warningValue) rval["warningtag"] <- list(warningTag) rval["error"] <- list(errorValue) rval["errortag"] <- list(errorTag) return(rval) } } list2maybe <- function(x) { rval <- list() rval $ value <- as.list(x) rval $ warnings <- maybeFrame() rval $ errors <- maybeFrame() class(rval) <- "maybeList" return(rval) } maybeFrame <- function() { data.frame(stage=character(), index=integer(), message=character(), stringsAsFactors=FALSE) } maybe_llply <- function(.data, .fun, .text="", ..., .progress=progress_simr(.text), .extract=FALSE) { if(!is(.data, "maybeList")) { .data <- list2maybe(.data) } maybenot <- seq_along(.data$value) %in% .data$errors$index z <- list() z[maybenot] <- llply(.data$errormessage[maybenot], function(e) maybe(stop(e))()) z[!maybenot] <- llply(.data$value[!maybenot], maybe(.fun), ..., .progress=.progress) rval <- list() rval $ value <- llply(z, `[[`, "value") extractWarnings <- if(.extract) do.call(rbind, llply(rval$value, `[[`, "warnings")) else maybeFrame() extractErrors <- if(.extract) do.call(rbind, llply(rval$value, `[[`, "errors")) else maybeFrame() warnings <- llply(z, `[[`, "warning") wtags <- llply(z, `[[`, "warningtag") index <- rep(seq_along(warnings), laply(warnings, length)) message <- unlist(warnings) stage <- unlist(wtags) rval $ warnings <- rbind( .data$warnings, extractWarnings, data.frame(stage, index, message, stringsAsFactors=FALSE) ) errors <- llply(z, `[[`, "error") etags <- llply(z, `[[`, "errortag") index <- which(!laply(errors, is.null)) message <- unlist(errors) stage <- unlist(etags) rval $ errors <- rbind( .data$errors, extractErrors, data.frame(stage, index, message, stringsAsFactors=FALSE) ) class(rval) <- "maybeList" return(rval) } list_to_atomic <- function(x) { if(any(laply(x, length) > 1)) stop("vectors longer than one found") if(any(laply(x, is.recursive))) stop("recursive elements found") unlist(ifelse(laply(x, is.null), NA, x)) } maybe_laply <- function(...) { rval <- maybe_llply(...) rval $ value <- list_to_atomic(rval $ value) return(rval) } maybe_raply <- function(.N, .thing, ...) { maybe_laply(seq_len(.N), eval.parent(substitute(function(.) .thing)), ...) } maybe_rlply <- function(.N, .thing, ...) { maybe_llply(seq_len(.N), eval.parent(substitute(function(.) .thing)), ...) } sometimes <- function(x, p=0.01, emsg="x8x", pw=NA, wmsg="boo!", lambda=NA) { if(!is.na(pw)) { if(runif(1) < pw) { nmsg <- if(is.na(lambda)) 1 else rpois(1, lambda) for(i in seq_len(nmsg)) { warning(sample(wmsg, 1)) } } } if(runif(1) < p) test_error(emsg) x } test_error <- function(e) stop(e)
rvn_annual_quantiles <- function(hgdata, prd=NULL, Qlower=0.1, Qupper=0.9, water_year=TRUE, mm=9) { prd <- rvn_get_prd(hgdata, prd) hgdata <- hgdata[prd] maxyear <- year(end(hgdata)) monthday <- as.Date(paste0(toString(maxyear), "-", month(hgdata), "-", day(hgdata))) if (water_year) { monthday[month(monthday) > mm] = monthday[month(monthday) > mm] - years(1) } qdat <- xts(aggregate(hgdata, by=monthday, quantile, probs=c(Qlower, .5, Qupper), na.rm=TRUE)) return(qdat) }
library("testthat") context("test-multitypePoisson.R") test_that("Small multi-type Poisson dense regression", { dobson1 <- data.frame( counts = c(18,17,15,20,10,20,25,13,12), outcome = gl(3,1,9), treatment = gl(3,3) ) dobson <- rbind(dobson1, dobson1) dobson$type = as.factor(c(rep("A",9),rep("B",9))) tolerance <- 1E-4 goldFit <- glm(counts ~ outcome + treatment, data = dobson1, family = poisson()) glmFit <- glm(counts ~ outcome + treatment, data = dobson, contrasts = dobson$type, family = poisson()) dataPtrD <- createCyclopsData(counts ~ outcome + treatment, data = dobson, type = dobson$type, modelType = "pr", method = "debug") cyclopsFitD <- fitCyclopsModel(dataPtrD, prior = createPrior("none"), control = createControl(noiseLevel = "silent")) dataPtrE <- createCyclopsData(Multitype(counts, type) ~ outcome + treatment, data = dobson, modelType = "pr", method = "debug") cyclopsFitE <- fitCyclopsModel(dataPtrE, prior = createPrior("none"), control = createControl(noiseLevel = "silent")) expect_equal(coef(cyclopsFitD), coef(cyclopsFitE)) dataPtrI <- createCyclopsData(Multitype(counts, type) ~ 1, indicatorFormula = ~ outcome + treatment, data = dobson, modelType = "pr", method = "debug") cyclopsFitI <- fitCyclopsModel(dataPtrI, prior = createPrior("none"), control = createControl(noiseLevel = "silent")) expect_equal(coef(cyclopsFitI), coef(cyclopsFitD)) dataPtrS <- createCyclopsData(Multitype(counts, type) ~ 1, sparseFormula = ~ outcome + treatment, data = dobson, modelType = "pr", method = "debug") cyclopsFitS <- fitCyclopsModel(dataPtrS, prior = createPrior("none"), control = createControl(noiseLevel = "silent")) expect_equal(coef(cyclopsFitS), coef(cyclopsFitD)) }) test_that("coef throws error when not converged", { dobson1 <- data.frame( counts = c(18,17,15,20,10,20,25,13,12), outcome = gl(3,1,9), treatment = gl(3,3) ) dobson2 <- data.frame( counts = c(18,17,15,20,10,20,25,13,12)-10, outcome = gl(3,1,9), treatment = gl(3,3) ) dobson <- rbind(dobson1, dobson2) dobson$type = as.factor(c(rep("A",9),rep("B",9))) tolerance <- 1E-4 dataPtrD <- createCyclopsData(Multitype(counts, type) ~ outcome + treatment, data = dobson, modelType = "pr") cyclopsFitD <- fitCyclopsModel(dataPtrD, prior = createPrior(c("normal","normal"), c(0.0001,10), graph = "type"), control = createControl(noiseLevel = "silent")) expect_error(coef(cyclopsFitD), "did not converge") }) test_that("confirm dimension check", { dobson1 <- data.frame( counts = c(18,17,15,20,10,20,25,13,12), outcome = gl(3,1,9), treatment = gl(3,3) ) dobson2 <- data.frame( counts = c(18,17,15,20,10,20,25,13,12)-10, outcome = gl(3,1,9), treatment = gl(3,3) ) dobson <- rbind(dobson1, dobson2) dobson$type = as.factor(c(rep("A",9),rep("B",9))) tolerance <- 1E-4 dataPtrD <- createCyclopsData(Multitype(counts, type) ~ outcome + treatment, data = dobson, modelType = "pr") expect_error(fitCyclopsModel(dataPtrD, prior = createPrior(c("normal"), c(0.0001,10), graph = "type"), control = createControl(noiseLevel = "silent")), "dimensionality mismatch") expect_error(fitCyclopsModel(dataPtrD, prior = createPrior(c("normal", "normal"), c(0.0001), graph = "type"), control = createControl(noiseLevel = "silent")), "dimensionality mismatch") }) test_that("Small multi-type Poisson with hierarchical prior", { dobson1 <- data.frame( counts = c(18,17,15,20,10,20,25,13,12), outcome = gl(3,1,9), treatment = gl(3,3) ) dobson2 <- data.frame( counts = c(18,17,15,20,10,20,25,13,12)-10, outcome = gl(3,1,9), treatment = gl(3,3) ) dobson <- rbind(dobson1, dobson2) dobson$type = as.factor(c(rep("A",9),rep("B",9))) tolerance <- 1E-4 glmFit <- glm(counts ~ outcome + treatment, data = dobson, contrasts = dobson$type, family = poisson()) dataPtrD <- createCyclopsData(Multitype(counts, type) ~ outcome + treatment, data = dobson, modelType = "pr") cyclopsFitD <- fitCyclopsModel(dataPtrD, prior = createPrior(c("normal","normal"), c(0.0001,10), graph = "type"), control = createControl(noiseLevel = "silent", maxIterations = 2000)) cyclopsFitE <- fitCyclopsModel(dataPtrD, prior = createPrior(c("normal","normal"), c(0.0001,0.0001), graph = "type"), control = createControl(noiseLevel = "silent")) }) test_that("Check multitype SCCS", { })
epi.nomogram <- function(se, sp, lr, pre.pos, verbose = FALSE){ if(is.na(se) & is.na(sp) & !is.na(lr[1])& !is.na(lr[2])){ lr.pos <- lr[1] lr.neg <- lr[2] } if(!is.na(se) & !is.na(sp) & is.na(lr[1]) & is.na(lr[2])){ lr.pos <- se / (1 - sp) lr.neg <- (1 - se) / sp } pre.odds <- pre.pos / (1 - pre.pos) post.odds.pos <- pre.odds * lr.pos post.odds.neg <- pre.odds * lr.neg post.opos.tpos <- post.odds.pos / (1 + post.odds.pos) post.opos.tneg <- post.odds.neg / (1 + post.odds.neg) lr <- data.frame(pos = lr.pos, neg = lr.neg) prior <- data.frame(opos = pre.pos) post <- data.frame(opos.tpos = post.opos.tpos, opos.tneg = post.opos.tneg) rval <- list(lr = lr, prior = prior, post = post) if(verbose == TRUE){ return(rval) } if(verbose == FALSE){ post.opos.tpos <- ifelse(post.opos.tpos < 0.01, round(post.opos.tpos, digits = 4), round(post.opos.tpos, digits = 2)) post.opos.tneg <- ifelse(post.opos.tneg < 0.01, round(post.opos.tneg, digits = 4), round(post.opos.tneg, digits = 2)) cat("Given a positive test result, the post-test probability of being outcome positive is", post.opos.tpos, "\n") cat("Given a negative test result, the post-test probability of being outcome positive is", post.opos.tneg, "\n") } }
NULL NULL NULL NULL 'single quotes with embedded and \n not embedded line breaks' x <- ' 2' x <- '\001' '\x01' "\001" '\001' NULL NULL
library("ggplot2") agg.top.Spain.evol <- read.csv("aggregated-top-Spain-evol.csv",sep=';') ggplot(agg.top.Spain.evol,aes(x=users,y=followers))+geom_line()+geom_point() ggsave('users-vs-followers.png') ggplot(agg.top.Spain.evol,aes(x=users,y=contributions))+geom_line()+geom_point() ggsave('users-vs-contributions.png')
context("LoremProvider works") test_that("LoremProvider works", { aa <- LoremProvider$new() expect_is(aa, "LoremProvider") expect_is(aa, "R6") expect_is(aa$word, "function") expect_is(aa$word(), "character") expect_equal(length(aa$word()), 1) expect_is(aa$words, "function") expect_is(aa$words(), "character") expect_equal(length(aa$words()), 3) expect_is(aa$sentence, "function") expect_is(aa$sentence(), "character") expect_equal(length(aa$sentence()), 1) expect_is(aa$sentences, "function") expect_is(aa$sentences(), "character") expect_equal(length(aa$sentences()), 3) expect_is(aa$paragraph, "function") expect_is(aa$paragraph(), "character") expect_equal(length(aa$paragraph()), 1) expect_is(aa$paragraphs, "function") expect_is(aa$paragraphs(), "character") expect_equal(length(aa$paragraphs()), 3) expect_is(aa$text, "function") expect_is(aa$text(), "character") expect_equal(length(aa$text()), 1) }) test_that("LoremProvider fails well", { expect_error(LoremProvider$new(locale = "foobar"), "foobar not in set of available locales") expect_error(LoremProvider$new(sentence_punctuation = 5), "sentence_punctuation must be of class character") expect_error(LoremProvider$new(word_connector = 5), "word_connector must be of class character") aa <- LoremProvider$new() expect_error(aa$word(ext_words = 5), "ext_words must be of class character") expect_error(aa$words(nb = "foobar"), "nb must be of class numeric, integer") expect_error(aa$words(ext_words = 5), "ext_words must be of class character") expect_error(aa$sentence(nb_words = "adf"), "nb_words must be of class numeric, integer") expect_error(aa$sentence(ext_words = 5), "ext_words must be of class character") expect_error(aa$sentence(variable_nb_words = 5), "variable_nb_words must be of class logical") expect_error(aa$sentences(nb = "adf"), "nb must be of class numeric, integer") expect_error(aa$sentences(ext_words = 5), "ext_words must be of class character") expect_error(aa$paragraph(nb_sentences = "foobar"), "nb_sentences must be of class numeric, integer") expect_error(aa$paragraph(variable_nb_sentences = 4), "variable_nb_sentences must be of class logical") expect_error(aa$paragraph(ext_words = 5), "ext_words must be of class character") expect_error(aa$paragraphs(nb = "adf"), "nb must be of class numeric, integer") expect_error(aa$paragraphs(ext_words = 5), "ext_words must be of class character") expect_error(aa$text(max_nb_chars = "adf"), "max_nb_chars must be of class numeric, integer") expect_error(aa$text(ext_words = 5), "ext_words must be of class character") })
loadGMT = function(target) { fc = file(target) aList = strsplit(readLines(fc), "\t") close(fc) nms = sapply(aList,function(x){return(x[1])}) out = sapply(aList,function(x){return(x[3:length(x)])}) names(out) = nms return(out) } loadGCT = function(target) { dat = utils::read.table(file=target, skip=2,header=TRUE,sep="\t") rownames(dat) = dat[,1] dat = dat[,3:dim(dat)[2]] return(t(as.matrix(dat))) } loadCLS = function(target, sampleNames) { fc = file(target) l = readLines(fc) close(fc) out = c() if(l[1] == " out = sapply(strsplit(l[3]," |\t")[[1]],as.numeric) } else { nms = strsplit(l[2]," ")[[1]] cls = strsplit(l[3]," |\t")[[1]] nminds = sapply((0:length(nms)-2),as.character) out = c() for(i in cls) { if(i %in% nminds){ out = c(out,nms[as.integer(i)+2]) } else { out = c(out,i) } } } names(out) = sampleNames return(out) }
siInner <- function(indPair, pVec, compMatch, object, indexMat, parmMat, varMat, level, reference, type, sifct, interval, degfree, logBase) { jInd <- indPair[1] kInd <- indPair[2] parmInd1 <- indexMat[, jInd] parmInd2 <- indexMat[, kInd] parmChosen1 <- parmMat[, jInd] parmChosen2 <- parmMat[, kInd] SIeval <- sifct(parmChosen1, parmChosen2, pVec, jInd, kInd, reference, type) SIval <- SIeval$"val" dSIval <- SIeval$"der" oriMatRow <- c(SIval, sqrt(t(dSIval) %*% varMat %*% dSIval)) siMatRow <- matrix(NA, 1, 4) siMatRow[1, 1] <- SIval if (identical(object$"type", "continuous")) { qFct <- function(x) {qt(x, degfree)} pFct <- function(x) {pt(x, degfree)} } else { qFct <- qnorm pFct <- pnorm } if (identical(interval, "none")) { siMatRow[2] <- oriMatRow[2] tempStat <- (siMatRow[1] - 1)/siMatRow[2] siMatRow[3] <- tempStat siMatRow[4] <- pFct(-abs(tempStat)) + (1 - pFct(abs(tempStat))) } if ( (identical(interval, "delta")) || (identical(interval, "fls")) ) { stErr <- oriMatRow[2] tquan <- qFct(1 - (1 - level)/2) siMatRow[2] <- siMatRow[1] - tquan * stErr siMatRow[3] <- siMatRow[1] + tquan * stErr ciLabel <- "Delta method" } if (identical(interval, "tfls")) { lsVal <- log(oriMatRow[1]) lsdVal <- oriMatRow[2] / oriMatRow[1] tquan <- qFct(1 - (1 - level)/2) siMatRow[2] <- exp(lsVal - tquan * lsdVal) siMatRow[3] <- exp(lsVal + tquan * lsdVal) ciLabel <- "To and from log scale" } if ((!is.null(logBase)) && (identical(interval, "fls"))) { siMatRow[1] <- logBase^(siMatRow[1]) siMatRow[2] <- logBase^(siMatRow[2]) siMatRow[3] <- logBase^(siMatRow[3]) ciLabel <- "From log scale" } if (identical(interval, "fieller")) { vcMat <- matrix(NA, 2, 2) vcMat[1, 1] <- SIeval$"der1" %*% varMat %*% SIeval$"der1" vcMat[2, 2] <- SIeval$"der2" %*% varMat %*% SIeval$"der2" vcMat[1, 2] <- SIeval$"der1" %*% varMat %*% SIeval$"der2" vcMat[2, 1] <- vcMat[1, 2] muVec <- c(SIeval$"valnum", SIeval$"valden") siMatRow[2:3] <- fieller(muVec, degfree, vcMat, level = level) ciLabel <- "Fieller" } c(siMatRow, dSIval) }
read.tree.to.data.matrix <- function(data.file1, data.file2) { G1 <- read.tree(data.file1) G2 <- read.tree(data.file2) n <- length(G1[[1]]$tip.label) to <- G1[[1]]$tip.label N1 <- length(G1) N2 <- length(G2) distVec_all1 <- as.matrix(G1, to) distVec_all2 <- as.matrix(G2, to) rownames(distVec_all1) <- NULL rownames(distVec_all2) <- NULL class <- as.factor(c(rep(1, N1), rep(2, N2))) D <- data.frame(class, rbind(distVec_all1, distVec_all2)) return(D) }
spatial_clip <- function( data, quantile, replace = NA, normalise = TRUE ) { if(missing(quantile) == TRUE) { quantile <- 1 } data@data@values[ data@data@values < quantile(data@data@values, quantile, na.rm = TRUE)] <- replace if(normalise == TRUE) { data@data@values <- ( data@data@values - min(data@data@values, na.rm = TRUE)) / (max(data@data@values, na.rm = TRUE) - min(data@data@values, na.rm = TRUE)) } return(data) }
bindDist <- function(margins = NULL, ..., p = NULL, keepScale = TRUE, reverse = FALSE, copula = NULL, skewness = NULL, kurtosis = NULL) { List <- list(...) if(length(List) > 0) { if(!is.null(skewness)) stop("CONFLICT: skewness and list of distributions cannot be both specified.") if(!is.null(kurtosis)) stop("CONFLICT: kurtosis and list of distributions cannot be both specified.") skewness <- rep(NA, length(List)) kurtosis <- rep(NA, length(List)) } else { if(!is.null(skewness)) { if(!is.null(kurtosis)) { if(length(skewness) != length(kurtosis)) stop("CONFLICT: The length of skewness and kurtosis must be equal.") } else { kurtosis <- rep(0, length(skewness)) } } else { if(!is.null(kurtosis)) { skewness <- rep(0, length(kurtosis)) } else { stop("CONFLICT: Either the list of distributions and the skewness (or kurtosis) argument must be specified.") } } List <- rep(list(NA), length(skewness)) } if (is.null(p)) { if(length(List) > 0) { p <- length(List) } else { p <- length(skewness) } } if (!is.null(margins)) { if(length(margins) == 1) margins <- rep(margins, p) } else { margins <- rep("NA", p) } if (length(reverse) == 1) reverse <- rep(reverse, p) if (length(reverse) != p) stop("Please specify the reverse option as TRUE or FALSE or the vector of TRUE/FALSE with the length of the number of the marginal distributions.") if (length(margins) != p) stop("Please specify the type of marginal distribution so that the length of the number of the marginal distributions is equal to the number of desired variables.") if (length(keepScale) == 1) keepScale <- rep(keepScale, p) if (length(keepScale) != p) stop("Please specify the keepScale option as TRUE or FALSE or the vector of TRUE/FALSE with the length of the number of the marginal distributions.") if (length(List) != p) List <- rep(List, length.out = p) if (length(skewness) != p) skewness <- rep(skewness, length.out = p) if (length(kurtosis) != p) kurtosis <- rep(kurtosis, length.out = p) if (!is.null(copula)) { if(!is(copula, "copula")) stop("The 'copula' argument is not a multivariate copula") copula@dimension <- as.integer(p) } else { copula <- new("NullCopula") } return(new("SimDataDist", margins = margins, paramMargins = List, p = p, keepScale = keepScale, reverse = reverse, copula = copula, skewness = skewness, kurtosis = kurtosis)) }
crssigtest <- function(model = NULL, index = NULL, boot.num = 399, boot.type = c("residual","reorder"), random.seed = 42, boot = TRUE) { if(exists(".Random.seed", .GlobalEnv)) { save.seed <- get(".Random.seed", .GlobalEnv) exists.seed <- TRUE } else { exists.seed <- FALSE } set.seed(random.seed) if(is.null(model)) stop(" you must provide a crs model") if(is.null(index)) index <- 1:NCOL(model$xz) if(index < 1 || index > NCOL(model$xz)) stop(" you must provide a valid index") boot.type <- match.arg(boot.type) df1.vec <- numeric(length(index)) df2.vec <- numeric(length(index)) uss.vec <- numeric(length(index)) rss.vec <- numeric(length(index)) F.vec <- numeric(length(index)) P.vec.boot <- numeric(length(index)) P.vec.asy <- numeric(length(index)) F.boot <- numeric(length=boot.num) F.boot.mat <- matrix(NA,nrow=boot.num,ncol=length(index)) for(ii in 1:length(index)) { model.degree <- model$degree model.lambda <- model$lambda model.segments <- model$segments model.basis <- model$basis model.knots <- model$knots degree.restricted <- model.degree lambda.restricted <- model.lambda segments.restricted <- model.segments xz.numeric <- FALSE if(is.numeric(model$xz[,index[ii]])) xz.numeric <- TRUE if(xz.numeric) { degree.index <- 0 for(jj in 1:index[ii]) if(is.numeric(model$xz[,jj])) degree.index <- degree.index + 1 model.degree[degree.index] <- ifelse(model$degree[degree.index]==0,1,model$degree[degree.index]) model.segments[degree.index] <- ifelse(model$degree[degree.index]==0,1,model$segments[degree.index]) degree.restricted[degree.index] <- 0 segments.restricted[degree.index] <- 1 } else { lambda.index <- 0 for(jj in 1:index[ii]) if(!is.numeric(model$xz[,jj])) lambda.index <- lambda.index + 1 model.lambda[lambda.index] <- ifelse(isTRUE(all.equal(model$lambda[lambda.index],1)),.Machine$double.eps,model$lambda[lambda.index]) lambda.restricted[lambda.index] <- 1 } model.unrestricted <- crs(xz=model$xz, y=model$y, cv="none", degree=model.degree, lambda=model.lambda, segments=model.segments, basis=model.basis, knots=model.knots) model.restricted <- crs(xz=model$xz, y=model$y, cv="none", degree=degree.restricted, lambda=lambda.restricted, segments=segments.restricted, basis=model.basis, knots=model.knots) uss.vec[ii] <- sum(residuals(model.unrestricted)^2) rss.vec[ii] <- sum(residuals(model.restricted)^2) df1.vec[ii] <- max(1,round(sum(model.unrestricted$hatvalues))-round(sum(model.restricted$hatvalues))) df2.vec[ii] <- model$nobs-round(sum(model.unrestricted$hatvalues)) F.df <- df2.vec[ii]/df1.vec[ii] F.pseudo <- F.df*(rss.vec[ii]-uss.vec[ii])/uss.vec[ii] F.vec[ii] <- F.pseudo if(boot) { if(boot.type=="reorder") xz.boot <- model$xz for(bb in 1:boot.num) { if(boot.type=="reorder") { xz.boot[,index[ii]] <- sample(model$xz[,index[ii]],replace=T) model.unrestricted.boot <- crs(xz=xz.boot, y=model$y, cv="none", degree=model.degree, lambda=model.lambda, segments=model.segments, basis=model.basis, knots=model.knots) model.restricted.boot <- crs(xz=xz.boot, y=model$y, cv="none", degree=degree.restricted, lambda=lambda.restricted, segments=segments.restricted, basis=model.basis, knots=model.knots) } else { y.boot <- fitted(model.restricted) + as.numeric(scale(sample(residuals(model),replace=T),center=TRUE,scale=FALSE)) model.unrestricted.boot <- crs(xz=model$xz, y=y.boot, cv="none", degree=model.degree, lambda=model.lambda, segments=model.segments, basis=model.basis, knots=model.knots) model.restricted.boot <- crs(xz=model$xz, y=y.boot, cv="none", degree=degree.restricted, lambda=lambda.restricted, segments=segments.restricted, basis=model.basis, knots=model.knots) } uss.boot <- sum(residuals(model.unrestricted.boot)^2) rss.boot <- sum(residuals(model.restricted.boot)^2) F.boot[bb] <- F.df*(rss.boot-uss.boot)/uss.boot } F.boot.mat[,ii] <- F.boot P.vec.boot[ii] <- mean(ifelse(F.boot > F.pseudo, 1, 0)) } P.vec.asy[ii] <- pf(F.pseudo,df1=df1.vec[ii],df2=df2.vec[ii],lower.tail=FALSE) } if(exists.seed) assign(".Random.seed", save.seed, .GlobalEnv) return(sigtest.crs(index=index, P=P.vec.boot, P.asy=P.vec.asy, F=F.vec, F.boot=F.boot.mat, df1=df1.vec, df2=df2.vec, rss=rss.vec, uss=uss.vec, boot.num=boot.num, boot.type=boot.type, xnames=names(model$xz))) } sigtest.crs <- function(index, P, P.asy, F, F.boot, df1, df2, rss, uss, boot.num, boot.type, xnames){ tsig <- list(index=index, P=P, P.asy=P.asy, F=F, F.boot=F.boot, df1=df1, df2=df2, rss=rss, uss=uss, boot.num=boot.num, boot.type=switch(boot.type, "residual" = "Residual", "reorder" = "Reorder"), xnames=xnames) tsig$reject <- rep('', length(F)) tsig$rejectNum <- rep(NA, length(F)) tsig$reject[a <- (P < 0.1)] <- '.' tsig$rejectNum[a] <- 10 tsig$reject[a <- (P < 0.05)] <- '*' tsig$rejectNum[a] <- 5 tsig$reject[a <- (P < 0.01)] <- '**' tsig$rejectNum[a] <- 1 tsig$reject[a <- (P < 0.001)] <- '***' tsig$rejectNum[a] <- 0.1 class(tsig) = "sigtest.crs" return(tsig) } print.sigtest.crs <- function(x, ...){ cat("\nRegression Spline Significance Test", "\nTest Type: ", x$boot.type," (",x$boot.num, " replications)", "\nPredictors tested for significance:\n", paste(paste(x$xnames[x$index]," (",x$index,")", sep=""), collapse=", "),"\n\n", sep="") maxNameLen <- max(nc <- nchar(nm <- x$xnames[x$index])) cat("\nSignificance Test Summary\n") cat("P Value:", paste("\n", nm, ' ', blank(maxNameLen-nc), format.pval(x$P), " ", formatC(x$reject,width=-4,format="s"), "(F = ", formatC(x$F,digits=4,format="fg"), ", df1 = ", x$df1, ", df2 = ", x$df2, ", rss = ", formatC(x$rss,digits=6,format="fg"), ", uss = ", formatC(x$uss,digits=6,format="fg"),")",sep='')) cat("\n---\nSignif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1\n\n") } summary.sigtest.crs <- function(object, ...) { print(object) }
rscontract_update <- function(host = "", type = "", hint = "") { observer <- getOption("connectionObserver") if (is.null(observer)) { return(invisible(NULL)) } observer$connectionUpdated(type = type, host = host, hint = hint) }
context("variable_label() replacement methods") test_that( "variable_label<-.default" , { object <- 1:4 variable_label(object) <- "Label 1" expect_identical( object = object , expected = structure( 1:4 , label = "Label 1" , class = c("tiny_labelled", "integer") ) ) expect_error( variable_label(object) <- NULL , regexp = "Variable labels must not be NULL. To entirely remove variable labels, use unlabel()." ) expect_error( variable_label(object) <- 1:2 , regexp = "Trying to set a variable label of length greater than one: '1', '2'" ) variable_label(object) <- list(b = list("a")) expect_identical( variable_label(object) , "a" ) } ) test_that( "variable_label<-.data.frame" , { object <- data.frame(a = 1:4, b = 5:8) object$c <- list(1:2, 3:4, 5:6, 7:8) expect_error( variable_label(object) <- c("not_in_data" = "test") , "While trying to set variable labels, some requested columns could not be found in data.frame:\n'not_in_data'" , fixed = TRUE ) expect_error( variable_label(object) <- "a" , "The assigned variable label(s) must be passed as a named vector or a named list." , fixed = TRUE ) variable_label(object) <- c("a" = "A beautiful test label.", c = "Deal with list columns") expect_identical( object = object , expected = structure( list( a = structure( 1:4 , label = "A beautiful test label." , class = c("tiny_labelled", "integer") ) , b = 5:8 , c = structure( list(1:2, 3:4, 5:6, 7:8) , label = "Deal with list columns" , class = c("tiny_labelled", "list") ) ) , row.names = c(NA, -4L) , class = "data.frame" ) ) object <- label_variables( object , a = "A different, but equally beautiful, test label." , b = "A mediocre reinterpretation of the a's label." ) expect_identical( object = object , expected = structure( list( a = structure( 1:4 , label = "A different, but equally beautiful, test label." , class = c("tiny_labelled", "integer") ) , b = structure( 5:8 , label = "A mediocre reinterpretation of the a's label." , class = c("tiny_labelled", "integer") ) , c = structure( list(1:2, 3:4, 5:6, 7:8) , label = "Deal with list columns" , class = c("tiny_labelled", "list") ) ) , row.names = c(NA, -4L) , class = "data.frame" ) ) object <- npk variable_label(object) <- c( N = "Nitrogen" , P = NULL ) } ) test_that( "variable_label.data.frame() for duplicate column names" , { object <- data.frame(x = 1, x = 2, check.names = F) variable_label(object) <- c(x = "Test duplicate columns") expect_identical( variable_label(object) , list(x = "Test duplicate columns", x = "Test duplicate columns") ) } ) test_that( "variable_label.data.frame() -- only modify columns if value is not NULL" , { object <- data.frame( x = 1 , y = 2 ) variable_labels(object) <- list( x = "A nice label" , y = NULL ) expect_identical( variable_labels(object) , list(x = "A nice label", y = NULL) ) } ) context("variable_label() extraction methods") test_that( "variable_label.tiny_labelled-method" , { object <- 1:10 class(object) <- c("tiny_labelled", "integer") attr(object, "label") <- "label1" expect_identical( object = variable_label(object) , expected = "label1" ) } ) test_that( "variable_label.data.frame-method" , { x <- npk variable_label(x) <- list(N = "Nitrogen", P = "Phosphate", K = expression(italic(K))) expect_identical( variable_label(x) , list( block = NULL , N = "Nitrogen" , P = "Phosphate" , K = expression(italic(K)) , yield = NULL ) ) } )
context("opt_dead_expr") test_that("dead expr empty code", { code <- paste( "", sep = "\n" ) opt_code <- opt_dead_expr(list(code))$codes[[1]] expect_equal(opt_code, paste( "", sep = "\n" )) }) test_that("dont eliminate DE in parent env", { code <- paste( "8 + 8 + 1918", sep = "\n" ) opt_code <- opt_dead_expr(list(code))$codes[[1]] expect_equal(opt_code, paste( "8 + 8 + 1918", sep = "\n" )) }) test_that("eliminate DE in fun", { code <- paste( "8 + 8 + 1918", "foo <- function() 8818", "bar <- function() {", " 8818", " 8818", "}", sep = "\n" ) opt_code <- opt_dead_expr(list(code))$codes[[1]] expect_equal(opt_code, paste( "8 + 8 + 1918", "foo <- function() 8818", "bar <- function() {", " 8818", "}", sep = "\n" )) }) test_that("eliminate DE in fun", { code <- paste( "8 + 8 + 1918", "foo <- function() 8818", "bar <- function(x) {", " x + 8818", " 8818", "}", sep = "\n" ) opt_code <- opt_dead_expr(list(code))$codes[[1]] expect_equal(opt_code, paste( "8 + 8 + 1918", "foo <- function() 8818", "bar <- function(x) {", " 8818", "}", sep = "\n" )) }) test_that("eliminate DE in fun with ';", { code <- paste( "bar <- function(x) { 8818; 8818; 8818; 8818 }", sep = "\n" ) opt_code <- opt_dead_expr(list(code))$codes[[1]] expect_equal(opt_code, paste( "bar <- function(x) { ; ; ; 8818 }", sep = "\n" )) }) test_that("eliminate DE in loop", { code <- paste( "bar <- function(x) {", " while (TRUE) {", " x + 8818", " }", " while (TRUE) x + 8818", " for (i in 1:10) {", " x + 8818", " }", " for (i in 1:10) x + 8818", " repeat {", " x + 8818", " }", " repeat x + 8818", "}", sep = "\n" ) opt_code <- opt_dead_expr(list(code))$codes[[1]] expect_equal(opt_code, paste( "bar <- function(x) {", " while (TRUE) {", " }", " while (TRUE) {}", " for (i in 1:10) {", " }", " for (i in 1:10) {}", " repeat {", " }", " repeat {}", "}", sep = "\n" )) }) test_that("dont eliminate DE in if/else", { code <- paste( "bar <- function(x) {", " if (x == 0) {", " x + 8818", " } else if (x == 1) {", " x + 8818", " } else {", " x + 8818", " }", "}", sep = "\n" ) opt_code <- opt_dead_expr(list(code))$codes[[1]] expect_equal(opt_code, code) }) test_that("eliminate DE in if/else", { code <- paste( "bar <- function(x) {", " if (x == 0) {", " x + 8818", " } else if (x == 1) {", " x + 8818", " } else {", " x + 8818", " }", " x + 8818", "}", sep = "\n" ) opt_code <- opt_dead_expr(list(code))$codes[[1]] expect_equal(opt_code, paste( "bar <- function(x) {", " if (x == 0) {", " } else if (x == 1) {", " } else {", " }", " x + 8818", "}", sep = "\n" )) }) test_that("dont eliminate assigns", { code <- paste( "bar <- function(x) {", " x <- 3", " x <- x + 3", " if (x == 0) {", " x <- 3", " x + 8818", " } else if (x == 1) {", " x <- 3", " x + 8818", " } else {", " x <- 3", " x + 8818", " }", " x <- 3", " x + 8818", "}", sep = "\n" ) opt_code <- opt_dead_expr(list(code))$codes[[1]] expect_equal(opt_code, paste( "bar <- function(x) {", " x <- 3", " x <- x + 3", " if (x == 0) {", " x <- 3", " } else if (x == 1) {", " x <- 3", " } else {", " x <- 3", " }", " x <- 3", " x + 8818", "}", sep = "\n" )) }) test_that("dont eliminate part of exprs", { code <- paste( "bar <- function(x) {", " tp <- ip[startsWith(ip, token)]", " completions <- lapply(tp, function(package) NULL)", " x + 8818", "}", sep = "\n" ) opt_code <- opt_dead_expr(list(code))$codes[[1]] expect_equal(opt_code, code) }) test_that("dont eliminate empty `if` or loop", { code <- paste( "foo <- function() {", " if (cond) NULL", " if (cond) NULL else NULL", " while (cond) NULL", " for (i in cond) NULL", " 8818", "}", sep = "\n" ) opt_code <- opt_dead_expr(list(code))$codes[[1]] expect_equal(opt_code, code) }) test_that("eliminate empty in one side of `ifelse`", { code <- paste( "foo <- function() {", " if (cond) x else NULL", " if (cond) NULL else x", " 8818", "}", sep = "\n" ) opt_code <- opt_dead_expr(list(code))$codes[[1]] expect_equal(opt_code, paste( "foo <- function() {", " if (cond) {} else NULL", " if (cond) NULL else {}", " 8818", "}", sep = "\n" )) })
NumCat <- function(ColDes,DataMat,NADes){ ColDes=ColDes[[1]] DataVec=DataMat[,ColDes] CatNum=length(unique(DataVec[which((DataVec)!=NADes)])) return(CatNum)}
library(RSwissMaps) library(tidyverse) library(RMariaDB) library(RMySQL)
print.gofOutlier <- function (x, ...) { coll.string <- paste("\n", space(33), sep = "") cat("\nResults of Outlier Test\n") cat("-------------------------\n\n") cat("Test Method:", space(21), x$method, "\n\n", sep = "") cat("Hypothesized Distribution:", space(7), x$distribution, "\n\n", sep = "") if (!is.null(x$n.param.est) && x$n.param.est > 0) { cat("Estimated Parameter(s):", space(10), paste(paste(format(names(x$distribution.parameters), justify = "left"), format(x$distribution.parameters, nsmall = 0, ...), sep = " = "), collapse = coll.string), "\n\n", sep = "") cat("Estimation Method:", space(15), x$estimation.method, "\n\n", sep = "") } if (is.null(names(x$data.name))) cat("Data:", space(28), x$data.name, "\n\n", sep = "") else cat("Data:", space(28), paste(paste(format(names(x$data.name), justify = "left"), format(x$data.name, ...), sep = " = "), collapse = coll.string), "\n\n", sep = "") if (!is.null(x$subset.expression)) cat("Subset With:", space(21), x$subset.expression, "\n\n", sep = "") if (!is.null(x$parent.of.data)) cat("Data Source:", space(21), x$parent.of.data, "\n\n", sep = "") if (!is.null(x$bad.obs) && any(x$bad.obs > 0)) { if (length(x$bad.obs) == 1) cat("Number NA/NaN/Inf's Removed:", space(5), x$bad.obs, "\n\n", sep = "") else { cat("Number NA/NaN/Inf's Removed:", space(5), paste(paste(format(names(x$bad.obs), justify = "left"), format(x$bad.obs, nsmall = 0, ...), sep = " = "), collapse = coll.string), "\n\n", sep = "") } } if (length(x$sample.size) > 1) { cat("Sample Sizes:", space(20), paste(paste(format(names(x$sample.size), justify = "left"), format(x$sample.size, nsmall = 0, ...), sep = " = "), collapse = coll.string), "\n\n", sep = "") } else { cat("Sample Size:", space(21), x$sample.size, "\n\n", sep = "") } string <- ifelse(length(x$statistic) == 1, paste("Test Statistic:", space(18), sep = ""), paste("Test Statistics:", space(17), sep = "")) cat(string, paste(paste(format(names(x$statistic), justify = "left"), format(x$statistic, nsmall = 0, ...), sep = " = "), collapse = coll.string), "\n\n", sep = "") n.params <- length(x$parameters) if (n.params > 0) { string <- ifelse(n.params > 1, paste("Test Statistic Parameters:", space(7), sep = ""), paste("Test Statistic Parameter:", space(8), sep = "")) cat(string, paste(paste(format(names(x$parameters), justify = "left"), format(x$parameters, nsmall = 0, ...), sep = " = "), collapse = coll.string), "\n\n", sep = "") } if (!is.null(x$p.value)) { if (length(x$p.value) == 1) cat("P-value:", space(25), format(x$p.value, ...), "\n\n", sep = "") else { if (!is.null(names(x$p.value))) cat("P-values:", space(24), paste(paste(format(names(x$p.value), justify = "left"), format(x$p.value, ...), sep = " = "), collapse = coll.string), "\n\n", sep = "") else cat("P-values:", space(24), paste(format(x$p.value, ...), collapse = coll.string), "\n\n", sep = "") } } cat("Alternative Hypothesis:", space(10), x$alternative, "\n\n", sep = "") if (!is.null(x$alpha)) cat("Type I Error:", space(20), paste(100 * x$alpha, "%", sep = ""), "\n\n", sep = "") if (!is.null(x$n.outliers)) cat("Number of Outliers Detected:", space(5), x$n.outliers, "\n\n", sep = "") if (!is.null(x$all.stats)) { print(x$all.stats) cat("\n\n") } invisible(x) }
test_that("oc_get returns a response object", { skip_if_oc_offline() withr::local_envvar(c("OPENCAGE_KEY" = key_200)) expect_s3_class( oc_get( oc_build_url( query_par = list( placename = "irrelevant", key = Sys.getenv("OPENCAGE_KEY") ), endpoint = "json" ) ), "HttpResponse" ) }) test_that("oc_get returns a response object for Namibia NA countrycode", { skip_if_no_key() skip_if_oc_offline() expect_s3_class( oc_get( oc_build_url( query_par = list( placename = "Windhoek", key = Sys.getenv("OPENCAGE_KEY"), countrycode = "NA" ), endpoint = "json" ) ), "HttpResponse" ) }) test_that("oc_get returns a response object for vector countrycode", { skip_if_no_key() skip_if_oc_offline() expect_s3_class( oc_get( oc_build_url( query_par = list( placename = "Paris", key = Sys.getenv("OPENCAGE_KEY"), countrycode = c("FR", "US") ), endpoint = "json" ) ), "HttpResponse" ) }) test_that("oc_get_limited is rate limited", { skip_on_cran() skip_if_offline("httpbin.org") tm <- system.time({ replicate(2, oc_get_limited("https://httpbin.org/get")) }) rate <- ratelimitr::get_rates(oc_get_limited) expect_gte(tm[["elapsed"]], rate[[1]][["period"]] / rate[[1]][["n"]]) }) test_that("oc_get_memoise memoises", { skip_on_cran() skip_if_offline("httpbin.org") oc_get_memoise("https://httpbin.org/get") tm <- system.time({ oc_get_memoise("https://httpbin.org/get") }) expect_lt(tm["elapsed"], 0.5) })
evaluate_candidates_glmnet <- function(Y,X,Q,lambdas, ctmletype, family,Qbounds, g.dataset, ab, candidates, like_type, gbound, training_set=1:length(Y), best_k = NULL) { Qstar_best <- 0 bestlambdas<-candidates$lambdas test_set <- !training_set | all(training_set) ncandidates <- length(lambdas) j<-1 nextbestlambdas<-bestlambdas[j] est <- likelihood <- varIC <- varDstar <-rep(Inf, ncandidates) if(ctmletype==1){ epsilon<-matrix(rep(Inf,ncandidates*2),ncol=2) } if(ctmletype==2){ epsilon<-matrix(rep(Inf,ncandidates*4),ncol=4) } for (i in 1:ncandidates){ f1 <- eval(paste("A ~ ", paste(paste(names(X[,-1]), sep=''), collapse=" + "))) f2 <- as.formula(f1) lassox<- model.matrix(f2, X)[,-1] lassoy<-as.factor(X[,1]) gbw <- glmnet(x=lassox,y=lassoy,family="binomial") g <- predict(gbw,newx=lassox,s=lambdas[i],type="response") g1W.total <- bound(g, c(gbound, 1-gbound)) g0W.total <- 1 - bound(g, c(gbound, 1-gbound)) H1W <- X[,1]/g1W.total H0W <- (1 - X[,1])/g0W.total if(ctmletype==1){ suppressWarnings(epsilon[i,]<- coef(glm(Y ~ -1 + offset(Q[, "QAW"]) + H0W+ H1W, family = family))) Qstar <- Q + c((epsilon[i,1] * H0W + epsilon[i,2] * H1W), epsilon[i,1]/g0W.total, epsilon[i,2]/g1W.total) } if(ctmletype==2){ if(i==1){ g1<-predict(gbw,newx=lassox,s=(lambdas[i]+0.005),type="response") }else{ g1<-predict(gbw,newx=lassox,s=(lambdas[i-1]),type="response") } g1W.total1 <- bound(g1, c(gbound, 1-gbound)) g0W.total1 <- 1 - bound(g1, c(gbound, 1-gbound)) ddg1<--(g1W.total-g1W.total1) ddg1[which(ddg1==0)]<-1e-10 ddg0<--(g0W.total-g0W.total1) ddg0[which(ddg0==0)]<-1e-10 ddH1W <- (X[,1]/(g1W.total^2))*ddg1 ddH0W <- ((1 - X[,1])/(g0W.total^2))*ddg0 suppressWarnings(epsilon[i,]<- coef(glm(Y ~ -1 +offset(Q[, "QAW"])+ H0W+H1W+ ddH0W + ddH1W, family = family))) Qstar <- Q + cbind((epsilon[i,1] * H0W+ epsilon[i,2] * H1W), epsilon[i,1]/g0W.total, epsilon[i,2]/g1W.total)+ cbind((epsilon[i,3] * ddH0W+ epsilon[i,4] * ddH1W), (epsilon[i,3]/(g0W.total^2))*ddg0, (epsilon[i,4]/(g1W.total^2))*ddg1) } if(family=="binomial"){ Qstar <- plogis(Qstar) } est[i] <- (mean(Qstar[training_set,"Q1W"]) - mean(Qstar[training_set,"Q0W"]))*diff(ab) if(!is.null(best_k)){ if(i == best_k){ Qstar_best <- Qstar } } if(like_type=="RSS"){ likelihood[i] <- sum((Y[test_set]-Qstar[test_set,"QAW"])^2) }else{ likelihood[i] <- -sum(Y[test_set]*log(Qstar[test_set,"QAW"]) + (1-Y[test_set])*log(1-Qstar[test_set,"QAW"])) } temp <- calc_varIC(Y[test_set], Q=Qstar[test_set,], A=X[test_set,1], W=X[test_set, 2], g1W=g1W.total[test_set], ICg=TRUE) varDstar[i] <- temp[1] varIC[i] <- temp[2] if(is.nan(est[i])|is.infinite(est[i])){est[i] <- NA} if(is.nan(likelihood[i])|is.infinite(likelihood[i])){likelihood[i] <- NA} if(is.nan(varIC[i])|is.infinite(varIC[i])){varIC[i] <- NA} if(is.nan(varDstar[i])|is.infinite(varDstar[i])){varDstar[i] <- NA} if(lambdas[i]==nextbestlambdas){ if(ctmletype==1){ Q <- Q + c((epsilon[i,1] * H0W + epsilon[i,2] * H1W), epsilon[i,1]/g0W.total, epsilon[i,2]/g1W.total) } if(ctmletype==2){ Q <- Q + cbind((epsilon[i,1] * H0W+ epsilon[i,2] * H1W), epsilon[i,1]/g0W.total, epsilon[i,2]/g1W.total)+ cbind((epsilon[i,3] * ddH0W+ epsilon[i,4] * ddH1W), (epsilon[i,3]/(g0W.total^2))*ddg0, (epsilon[i,4]/(g1W.total^2))*ddg1) } Q <- qlogis(bound(plogis(Q), Qbounds)) j <- j+1 if(length(bestlambdas)>=j){ nextbestlambdas<-bestlambdas[j] }else{ nextbestlambdas<-0 } } } return(list(est=est, likelihood=likelihood, varDstar=varDstar, varIC=varIC, Qstar_best = Qstar_best)) } construct_candidates_glmnet <- function(Y, X, Q, lambdas, ctmletype, family,Qbounds,training_set, gbound, like_type, verbose, stopFactor){ g.dataset <- X Epsilon <- scorelambdas<-NULL bestlambdas<-NULL minScore <- Inf lambdas_remaining<-lambdas ncandidates<-length(lambdas) i <- 0 DONE <- ncandidates<= 0 while(!DONE) { i <- i+1 if(verbose) {cat("\tBeginning construction of clever covariate", i,"\n")} nlambdas<-length(lambdas_remaining) epsilon <- NULL score <- rep(NA, nlambdas) if(ctmletype==1){ eps_try <- matrix(ncol=2,nrow=nlambdas) } if(ctmletype==2){ eps_try <- matrix(ncol=4,nrow=nlambdas) } if(verbose){ cat("\n\t Selecting best bandwidth to add to model...\n") } for (j in 1:nlambdas){ if(verbose) { cat("\t\tTrying", lambdas_remaining[j],"\n") } f1<-eval(paste("A ~ ", paste(paste(names(X[,-1]), sep=''), collapse=" + "))) f2<-as.formula(f1) lassox<- model.matrix(f2, X[training_set,])[,-1] lassoy<-as.factor(X[training_set,1]) gbw<-glmnet(x=lassox,y=lassoy,family="binomial") g<-predict(gbw,newx=lassox,s=lambdas_remaining[j],type="response") g1W.total <- bound(g, c(gbound, 1-gbound)) g0W.total <- 1 - bound(g, c(gbound, 1-gbound)) H1W <- X[training_set,1]/g1W.total H0W <- (1 - X[training_set,1])/g0W.total if(ctmletype==1){ suppressWarnings(eps_try[j,]<- coef(glm(Y[training_set] ~ -1 + offset(Q[training_set, "QAW"]) + H0W + H1W, family = family))) Qstar <- Q[training_set,] + c((eps_try[j,1] * H0W + eps_try[j,2] * H1W), eps_try[j,1]/g0W.total, eps_try[j,2]/g1W.total) } if(ctmletype==2){ if(j==1){ g1<-predict(gbw,newx=lassox,s=(lambdas_remaining[j]+0.005),type="response") }else{ g1<-predict(gbw,newx=lassox,s=(lambdas_remaining[j-1]),type="response") } g1W.total1 <- bound(g1, c(gbound, 1-gbound)) g0W.total1 <- 1 - bound(g1, c(gbound, 1-gbound)) ddg1<--(g1W.total-g1W.total1) ddg1[which(ddg1==0)]<-1e-10 ddg0<--(g0W.total-g0W.total1) ddg0[which(ddg0==0)]<-1e-10 ddH1W <- (X[training_set,1]/(g1W.total^2))*ddg1 ddH0W <- ((1 - X[training_set,1])/(g0W.total^2))*ddg0 suppressWarnings(eps_try[j,]<- coef(glm(Y[training_set] ~ -1 + offset(Q[training_set, "QAW"])+ H0W+H1W+ ddH0W + ddH1W, family = family))) Qstar <- Q[training_set,] + cbind((eps_try[j,1] * H0W+ eps_try[j,2] * H1W), eps_try[j,1]/g0W.total, eps_try[j,2]/g1W.total)+ cbind((eps_try[j,3] * ddH0W+ eps_try[j,4] * ddH1W), (eps_try[j,3]/(g0W.total^2))*ddg0, (eps_try[j,4]/(g1W.total^2))*ddg1) } if(family=="binomial"){ Qstar <- plogis(Qstar)} varIC <- calc_varIC(Y[training_set], Qstar, A=X[training_set,1],g1W=g1W.total)[1] * sum(training_set)/length(training_set) if(like_type == "RSS"){ score[j] <- sum((Y[training_set] - Qstar[,"QAW"])^2) + varIC[1] }else { score[j] <- -sum(Y[training_set]*log(Qstar[,"QAW"]) + (1-Y[training_set])*log(1-Qstar[,"QAW"])) + varIC[1] } } if(verbose) { cat("\t\t",paste("penalized", like_type,":"), round(score,5), "\n") } score[is.nan(score)] <- Inf best <- which.min(abs(score)) if(verbose) { cat("\t\tbest choice:", lambdas_remaining[best], "\n") } bestScore <- score[best] epsilon <- rbind(epsilon, eps_try[best,]) if(verbose) { cat("\t\tbest score:", bestScore, "\n") } earlyStop <- minScore*stopFactor < bestScore if(earlyStop & verbose){ cat("Stopping early because loss function of current candidate >", stopFactor, "times the best candidate seen so far\n") cat("The ratio of best to current (",i,"), is ", round(bestScore/minScore, 2), "\n") } minScore <- ifelse(minScore<bestScore, minScore, bestScore) if(bestScore==minScore){ Epsilon <- rbind(Epsilon, epsilon) bestlambdas <- c(bestlambdas, lambdas_remaining[best]) f1<-eval(paste("A ~ ", paste(paste(names(X[,-1]), sep=''), collapse=" + "))) f2<-as.formula(f1) lassox<- model.matrix(f2, X)[,-1] lassoy<-as.factor(X[,1]) gbw<-glmnet(x=lassox,y=lassoy,family="binomial") g<-predict(gbw,newx=lassox,s=lambdas_remaining[best],type="response") g1W.total <- bound(g, c(gbound, 1-gbound)) g0W.total <- 1 - bound(g, c(gbound, 1-gbound)) H1W <- X[,1]/g1W.total H0W <- (1 - X[,1])/g0W.total if(ctmletype==1){ Q[training_set,] <- Q[training_set,] + c(( Epsilon[dim(Epsilon)[1],1] * H0W[training_set] + Epsilon[dim(Epsilon)[1],2] * H1W[training_set]), Epsilon[dim(Epsilon)[1],1]/g0W.total[training_set], Epsilon[dim(Epsilon)[1],2]/g1W.total[training_set]) Q[training_set,]<-qlogis(bound(plogis(Q[training_set,]), Qbounds)) } if(ctmletype==2){ if(best==1){ g1<-predict(gbw,newx=lassox,s=(lambdas_remaining[best]+0.005), type="response") }else{ g1<-predict(gbw,newx=lassox,s=(lambdas_remaining[best-1]), type="response") } g1W.total1 <- bound(g1, c(gbound, 1-gbound)) g0W.total1 <- 1 - bound(g1, c(gbound, 1-gbound)) ddg1<--(g1W.total-g1W.total1) ddg1[which(ddg1==0)]<-1e-10 ddg0<--(g0W.total-g0W.total1) ddg0[which(ddg0==0)]<-1e-10 ddH1W <- (X[,1]/(g1W.total^2))*ddg1 ddH0W <- ((1 - X[,1])/(g0W.total^2))*ddg0 Q[training_set,] <- Q[training_set,] + cbind(( Epsilon[dim(Epsilon)[1],1] * H0W[training_set] + Epsilon[dim(Epsilon)[1],2] * H1W[training_set]), Epsilon[dim(Epsilon)[1],1]/g0W.total[training_set], Epsilon[dim(Epsilon)[1],2]/g1W.total[training_set])+ cbind(( Epsilon[dim(Epsilon)[1],3] * ddH0W[training_set] + Epsilon[dim(Epsilon)[1],4] * ddH1W[training_set]), ((Epsilon[dim(Epsilon)[1],3]/(g0W.total^2))*ddg0)[training_set], ((Epsilon[dim(Epsilon)[1],4]/(g1W.total^2))*ddg1)[training_set]) Q[training_set,]<-qlogis(bound(plogis(Q[training_set,]), Qbounds)) } lambdas_remaining <- lambdas_remaining[which(lambdas_remaining<lambdas_remaining[best])] ncandidates<-length(lambdas_remaining) }else{ ncandidates<-0 } DONE <- ncandidates <= 0 | earlyStop if(verbose){ if(bestScore==minScore){ cat("\tThe model for clever covariate", i, "is complete.\n") cat("\t\t...Calculating h(A,W) based on candidate g-estimator", i,"\n") cat("\t\t...Running a logistic regression to fit epsilon\n") cat("\t\t...Updating estimate of Q(A,W) = Q(A,W) + epsilon * h(A,W)\n") } if(DONE){ cat("\tAll candidate TMLE estimators have been constructed\n\n") } else { cat("\n\tReady to use the updated estimate of Q(A,W) to construct the next clever covariate.\n") } } } return(list(lambdas=bestlambdas, epsilon=Epsilon, earlyStop=earlyStop)) } stage2_glmnet <- function(Y, X, Q, lambdas, ctmletype, family, Qbounds, ab,training_set=rep(T,length(Y)), like_type, gbound,verbose, stopFactor=10^6, best_k = NULL) { if(verbose) { cat ("\n\t\t-----Stage 2: Constructing candidate TMLE estimators-----\n\n") } candidates <- construct_candidates_glmnet(Y, X, Q,lambdas,ctmletype, family=family[1] , Qbounds,training_set=training_set, gbound=gbound, like_type=like_type, verbose=verbose,stopFactor=stopFactor) results.all <- evaluate_candidates_glmnet(Y, X, Q,lambdas,ctmletype, family[1],Qbounds, g.dataset=X, candidates, ab=ab, like_type=like_type, gbound=gbound, training_set=training_set, best_k = best_k) return(list(candidates=candidates, results.all=results.all)) } cv_glmnet <- function(Y,X, est.all, Q, lambdas,ctmletype, family, Qbounds, ab, like_type, gbound, verbose=FALSE, PEN, V=5, folds = NULL) { n <- length(Y) nconstructed <- length(est.all) if(is.null(folds)){ folds <- by(sample(1:n,n), rep(1:V, length=n), list) }else{ if(length(folds) != V){ stop("The number of user-specified folds information does not match V") }else if(mean(sort(unlist(folds)) - 1:n)!= 0){ stop("Error in the indices of the user-specified folds") } } likelihood <- varDstar <- bias <- c(rep(0,nconstructed)) est <- matrix(data=NA, nrow=nconstructed, ncol=V) if(verbose) {cat("\tfold: ")} for (v in 1:V){ if(verbose) {cat(v," ")} test_set <- folds[[v]] training_set <- rep(TRUE, n) training_set[folds[[v]]] <- FALSE candidates <- stage2_glmnet(Y,X, Q,lambdas,ctmletype, family=family, Qbounds = Qbounds, ab=ab, training_set=training_set, like_type=like_type, gbound=gbound, verbose=FALSE) est[,v] <- candidates$results.all$est likelihood <- c(likelihood+candidates$results.all$likelihood) varDstar <- c(varDstar+candidates$results.all$varDstar) bias <- c(bias+(candidates$results.all$est-est.all)) } bias <- bias pen <- varDstar*(diff(ab))^2/V + n*(bias/V)^2 if(identical(family[1], gaussian) | identical(family[1], "gaussian")){ pen <- pen * log(n) } if(PEN){ score <- likelihood*(diff(ab)^2) + pen } else { score <- likelihood*(diff(ab)^2) } score[is.infinite(score)|is.nan(score)] <- Inf best_k <- which.min(abs(score)) if(verbose){ cat("\n\n") cat("\t terms: ", candidates$candidates$terms, "\n") cat("\t all estimates: ", est.all, "\n") cat("\t all RSS: ", score, "\n") cat("\t best_k: ", best_k, "\n\n") } return(list(best_k=best_k, est=est, likelihood=likelihood, like_type=like_type, penlikelihood=score, varIC=varDstar/V, bias=bias/V, pen=pen)) }
print.summary.HDBRR<- function(x, ...){ if(!inherits(x, "summary.HDBRR")) stop("This function only works for objects of class 'HDBRR'\n"); model <- x$call summary <- x$summary lambda <- x$lambda edf <- x$edf cat("\nCall:\n", paste(deparse(model), sep = "\n", collapse = "\n"), "\n\n", sep = "") cat("\nCoefficients:\n") print(summary) cat("-----\n") cat("Signif. codes: 10 '***' 6 '**' 2 '*' 0 ' ' \n\n") cat("\nRidge parameter:", lambda) cat("\nEffective degrees of freedom:", edf) }
test_that("summary and print.summary work", { summary(data_corpus_inaugural[1:2]) summ <- summary(data_corpus_inaugural[1:2]) expect_is(summ, "data.frame") expect_equal( names(summ), c("Text", "Types", "Tokens", "Sentences", "Year", "President", "FirstName", "Party") ) expect_output( print(summ), "Corpus consisting of 2 documents, showing 2 documents: Text Types Tokens Sentences Year President FirstName Party 1789-Washington 625 1537 23 1789 Washington George none 1793-Washington 96 147 4 1793 Washington George none" ) })
robcor <- function(x, y = NULL, method = c("ssd", "quadrant", "mcd"), partial = FALSE, post = "psdcor", scaler = "s_FastQn", regress = "lmrob") { method <- match.arg(method) scaler <- match.fun(scaler) if (!is.null(post)) post <- match.fun(post) if (is.data.frame(y)) y <- as.matrix(y) if (is.data.frame(x)) x <- as.matrix(x) if (!is.matrix(x) && is.null(y)) stop("supply both 'x' and 'y' or a matrix-like 'x'") if (!(is.numeric(x) || is.logical(x))) stop("'x' must be numeric") stopifnot(is.atomic(x)) if (!is.null(y)) { if (!(is.numeric(y) || is.logical(y))) stop("'y' must be numeric") stopifnot(is.atomic(y)) if (method == "mcd") stop(paste("'y' must be NULL for", method)) if (partial) stop("'y' must be NULL for partial correlations") } if (partial && any(method == c("mcd"))) stop(paste("partial correlations unavailable for", method)) if (method == "mcd") { ret <- covMcd(x, cor = TRUE)$cor } else { ret <- .PairwiseCorrelation(x, y, method, partial, post, scaler, regress) } ret } .PairwiseCorrelation <- function(x, y, method, partial, post, scaler, regress) { if (method == "ssd") { .Standardize <- function(x) { musigma <- apply(x, 2, function(x) scaler(na.omit(x), mu.too=TRUE)) scale(x, musigma[1,], musigma[2,]) } .PairCorrelation <- function(nx, ny) { s2u <- scaler(nx + ny)^2 s2v <- scaler(nx - ny)^2 (s2u - s2v) / (s2u + s2v) } } else if (method == "quadrant") { .Standardize <- function(x) { center <- apply(x, 2, median, na.rm = TRUE) sign(sweep(x, 2, center)) } .PairCorrelation <- function(nx, ny) { n <- nx * ny sin(sum(n) / sum(abs(n)) * pi / 2) } } else { stop("unimplemented method") } if (is.null(y)) { ncy <- ncx <- ncol(x) if (ncx == 0) stop("'x' is empty") if (!is.null(.Standardize)) x <- .Standardize(x) if (partial) { if (regress == "lmrob") { require(robustbase) } regress <- match.fun(regress) r <- .PartialToCorrelation(.BuildPartial(x, .Standardize, .PairCorrelation, regress)) } else { r <- diag(ncx) for (i in seq_len(ncx - 1)) { for (j in i + seq_len(ncx - i)) { x2 <- x[, i] y2 <- x[, j] ok <- complete.cases(x2, y2) x2 <- x2[ok] y2 <- y2[ok] r[i, j] <- r[j, i] <- if (any(ok)) { .PairCorrelation(x2, y2) } else { NA } } } } if (is.function(post)) r <- post(r) rownames(r) <- colnames(x) colnames(r) <- colnames(x) } else { if (length(x) == 0L || length(y) == 0L) stop("both 'x' and 'y' must be non-empty") matrixResult <- is.matrix(x) || is.matrix(y) if (!is.matrix(x)) x <- matrix(x, ncol = 1L) if (!is.matrix(y)) y <- matrix(y, ncol = 1L) if (!is.null(.Standardize)) { x <- .Standardize(x) y <- .Standardize(y) } ncx <- ncol(x) ncy <- ncol(y) r <- matrix(0, nrow = ncx, ncol = ncy) for (i in seq_len(ncx)) { for (j in seq_len(ncy)) { x2 <- x[, i] y2 <- y[, j] ok <- complete.cases(x2, y2) x2 <- x2[ok] y2 <- y2[ok] r[i, j] <- if (any(ok)) { .PairCorrelation(x2, y2) } else { NA } } } if (is.function(post)) r <- post(r) rownames(r) <- colnames(x) colnames(r) <- colnames(y) if (!matrixResult) r <- drop(r) } r } .BuildPartial <- function(data, fStandardize, fCorrelate, fRegression) { stopifnot(is.matrix(data)) p <- ncol(data) result <- diag(p) data <- as.data.frame(data) colnames(data) <- paste0("x", seq_len(p)) for (i in seq_len(p - 1)) { if (i == 1) { for (j in i + seq_len(p - i)) { result[i, j] <- result[j, i] <- fCorrelate(data[,i], data[,j]) } } else { vars <- paste0("x", seq_len(i - 1)) f.i <- as.formula(paste(paste0("x", i), "~", vars)) res.i <- residuals(fRegression(f.i, data)) res.i <- as.vector(fStandardize(as.matrix(res.i))) for (j in i + seq_len(p - i)) { f.j <- as.formula(paste(paste0("x", j), "~", vars)) res.j <- residuals(fRegression(f.j, data)) res.j <- as.vector(fStandardize(as.matrix(res.j))) result[i, j] <- result[j, i] <- fCorrelate(res.i, res.j) } } } return(result) } .PartialToCorrelation <- function(mtx) { stopifnot(nrow(mtx) == ncol(mtx)) stopifnot(isSymmetric(mtx)) p <- ncol(mtx) result <- diag(p) for (i in seq_len(p - 1)) { for (j in i + seq_len(p - i)) { r <- mtx[i, j] for (n in seq_len(i - 1)) { a <- mtx[i, i - n] b <- mtx[i - n, j] r <- a * b + r * sqrt(1 - a^2) * sqrt(1 - b^2) } result[i, j] <- result[j, i] <- r } } result }
meanvarTall = function(lower=rep(-Inf,length(mu)),upper=rep(Inf,length(mu)),mu,Sigma,nu,omega = FALSE){ p = length(mu) if(p == 1){ if(nu >= 3){ return(meanvarT16(a = lower,b = upper,mu = mu,Sigma = Sigma,nu=nu,omega)) }else{ if(omega){ return(RcppMCT.lin(n = 5000,a = lower,b = upper,mu = mu,S = as.matrix(Sigma),nu = nu,omega = omega)) }else{ return(dtmvtmuvar(a = lower,b = upper,mu = mu,S = Sigma,nu=nu)) } } } bool1 = is.infinite(lower) bool2 = is.infinite(upper) if(sum(bool1*bool2) > 0){ if(sum(bool1*bool2) == p){ if(nu > 2){ varcov = nu/(nu-2)*Sigma EYY = varcov + mu%*%t(mu) return(list(mean = mu,EYY = EYY,varcov = varcov)) }else{ return(list(mean = mu,EYY = matrix(NaN,p,p),varcov = matrix(NaN,p,p))) } }else{ return(withinfsT(lower,upper,mu,Sigma,nu)) } } if(nu > 4){ if(sum(bool1) + sum(bool2) == 0){ return(meanvarT.Lin.IC(a = lower,b = upper,mu = mu,S = Sigma,nu=nu,omega)) }else{ if(sum(bool1) == p){ if(sum(bool2) == p){ varcov = nu/(nu-2)*Sigma return(list(mean = mu,EYY = varcov + mu%*%t(mu),varcov = varcov)) }else{ return(meanvarT.Lin.RC(b = upper,mu = mu,S = Sigma,nu=nu,omega)) } }else{ if(sum(bool2) == p){ return(meanvarT.Lin.LC(a = lower,mu = mu,S = Sigma,nu=nu,omega)) }else{ return(meanvarT.Lin.LRIC(a = lower,b = upper,mu = mu,S = Sigma,nu=nu,omega)) } } } } if(nu >= 3){ if(sum(bool1) + sum(bool2) == 0){ return(meanvarT16_finite(a = lower,b = upper,mu = mu,Sigma = Sigma,nu=nu,omega)) }else{ if(sum(bool1) == p){ if(sum(bool2) == p){ varcov = nu/(nu-2)*Sigma return(list(mean = mu,EYY = varcov + mu%*%t(mu),varcov = varcov)) }else{ return(meanvarT16_upper(b = upper,mu = mu,Sigma = Sigma,nu=nu,omega)) } }else{ if(sum(bool2) == p){ return(meanvarT16_lower(a = lower,mu = mu,Sigma = Sigma,nu=nu,omega)) }else{ return(meanvarT16(a = lower,b = upper,mu = mu,Sigma = Sigma,nu=nu,omega)) } } } } if(omega){ return(RcppMCT.lin(n = 5000,a = lower,b = upper,mu = mu,S = as.matrix(Sigma),nu = nu,omega = omega)) }else{ if(sum(bool1) + sum(bool2) == 0){ return(ftmvtmuvar(a = lower,b = upper,mu = mu,S = Sigma,nu=nu)) }else{ if(sum(bool1) == p){ if(sum(bool2) == p){ varcov = nu/(nu-2)*Sigma return(list(mean = mu,EYY = varcov + mu%*%t(mu),varcov = varcov)) }else{ return(utmvtmuvar(b = upper,mu = mu,S = Sigma,nu=nu)) } }else{ if(sum(bool2) == p){ return(ltmvtmuvar(a = lower,mu = mu,S = Sigma,nu=nu)) }else{ return(dtmvtmuvar(a = lower,b = upper,mu = mu,S = Sigma,nu=nu)) } } } } }
dat <- dat[,c("{user_parms}")] names(dat) <- c("case","session","phase","outcome") dat <- preprocess_SCD(case = case, phase = phase, session = session, outcome = outcome, design = "{user_design}", center = {user_model_center}, data = dat)
NULL assembleShadowTest <- function( j, position, o, eligible_flag, exclude_index, stimulus_record, info, config, constants, constraints ) { administered_stimulus_index <- na.omit(unique(o@administered_stimulus_index)) xdata <- getXdataOfAdministered(constants, position, o, stimulus_record, constraints) xdata_exclude <- getXdataOfExcludedEntry(constants, exclude_index[[j]]) xdata <- combineXdata(xdata, xdata_exclude) if (constants$use_eligibility_control) { current_segment <- o@theta_segment_index[position] eligible_flag_in_current_theta_segment <- getEligibleFlagInSegment(eligible_flag, current_segment, constants) eligible_flag_in_current_theta_segment <- flagAdministeredAsEligible(eligible_flag_in_current_theta_segment, o, position, constants) } if (constants$use_eligibility_control && constants$exposure_control_method %in% c("ELIGIBILITY")) { xdata_elg <- applyEligibilityConstraintsToXdata(xdata, eligible_flag_in_current_theta_segment, constants, constraints) shadowtest <- runAssembly(config, constraints, xdata = xdata_elg, objective = info) is_optimal <- isShadowtestOptimal(shadowtest) if (is_optimal) { shadowtest$feasible <- TRUE return(shadowtest) } shadowtest <- runAssembly(config, constraints, xdata = xdata, objective = info) shadowtest$feasible <- FALSE return(shadowtest) } if (constants$use_eligibility_control && constants$exposure_control_method %in% c("BIGM", "BIGM-BAYESIAN")) { info <- applyEligibilityConstraintsToInfo( info, eligible_flag_in_current_theta_segment, config, constants ) shadowtest <- runAssembly(config, constraints, xdata = xdata, objective = info) shadowtest$feasible <- TRUE return(shadowtest) } if (!constants$use_eligibility_control) { shadowtest <- runAssembly(config, constraints, xdata = xdata, objective = info) shadowtest$feasible <- TRUE return(shadowtest) } } isShadowtestOptimal <- function(shadowtest) { return(isOptimal(shadowtest$status, shadowtest$solver)) }
test_that("Potential numerical issues",{ expect_equal( range( sapply(subtracks( diffinv(matrix(rep(sqrt(2),200),ncol=4,byrow=T)), 2 ), overallAngle ) ), c(0,0) ) })
key.control <- function(plot = TRUE, lab = NULL, title = NULL, between = 0) { return(list(plot = plot, x = NULL, lab = lab, title = title, between = between)) }
SkewBoot <- function(data,replicates,units,type){ MaxSkew<-NULL Scalar<-NULL MardiaSkewness<-NULL rm("MardiaSkewness") fine<-replicates+1 if(type!="Directional"&&type!="Partial"&&type!="Mardia"){ print("ERROR: type must be either Directional, Partial or Mardia") } else{ xxx<-matrix(c(0),ncol=1,nrow=fine) uno<-matrix(c(1),nrow=units,ncol=1) AA<-matrix(ncol=1, nrow=fine) Y<-matrix(nrow=fine,ncol=1) for (b in 1:fine){ xB<-matrix(sample(data,size=ncol(data)*units,replace=TRUE),nrow=units) if (type=="Directional"){ proj<-MaxSkew(xB,5,2,FALSE) xxx[b,1]<-FisherSkew(proj)[2,1] } if(type=="Partial"){ Scalar<-PartialSkew(xB) xxx[b,1]<-Scalar } if(type=="Mardia"){ SkewMardia(xB) Mardiaprova<-MardiaSkewness xxx[b,1]<-Mardiaprova } xxx.mean<-mean(xxx) m<-xxx-xxx.mean xxx.sd<-sd(xxx) Y[,1]<-m/xxx.sd z<-Y[,1] AA[b,1]<-round(mean(z^3),digits=4) } if(type=="Directional"){ hist(AA[2:fine,1],freq=FALSE,main="Histogram of bootstrapped Directional skewness",xlab="Skewness") } if(type=="Partial"){ hist(AA[2:fine,1],freq=FALSE,main="Histogram of bootstrapped Partial skewness",xlab="Skewness") } if(type=="Mardia"){ hist(AA[2:fine,1],freq=FALSE,main="Histogram of bootstrapped Mardia skewness",xlab="Skewness") } print("Vector") print(AA[2:fine,1]) count<-0 for(i in 2:fine){ if(AA[i,1]>= FisherSkew(data)[2,1]) count<-count+1 } pvalue.Skew<-(count+1)/fine print("Pvalue") print(pvalue.Skew) } }
TestIndLS <- function(posx, posy, posz=NULL,T, alpha=0.05, nTrans=100,PA=FALSE,cores=1, fixed.seed=NULL) { NumProcess<-2+(is.null(posz)==F) n<-length(posx) distObs<-DistObs(posx=posx,posy=posy,posz=posz, info='F', PA=PA) cl<-makeCluster(cores) clusterExport(cl, objects(, envir = .GlobalEnv)) if (is.null(fixed.seed)==F) set.seed(fixed.seed) shi1<-round(runif(nTrans,1,(T-1))) if(NumProcess==3) { if (is.null(fixed.seed)==F) set.seed((fixed.seed+1)) shi2<-round(runif(nTrans,1,(T-1))) } else {shi2<-NULL} matdist<- parSapply(cl, c(1:nTrans), FUN=fn2B, posx=posx, posy=posy, posz=posz,NumProcess=NumProcess, PA=PA, shi1=shi1, shi2=shi2, T=T) matdistT<-cbind(distObs,matdist) matperT<-parSapply(cl, c(1:length(distObs)), FUN=mirank,mat=matdistT)/(nTrans+1) KSest<-parSapply(cl, c(1:(nTrans+1)), FUN=miKS,mat=matperT) stopCluster(cl) KSpv<-1-rank(KSest)[1]/(nTrans+1) reject<-as.numeric(KSpv<alpha) return(list(pv=KSpv, reject=reject, est=KSest)) }
polygon_metrics = function(las, func, geometry, ...) { UseMethod("polygon_metrics", las) } polygon_metrics.LAS = function(las, func, geometry, ...) { stopifnot(is(geometry, "sf") | is(geometry, "sfc")) geometry <- sf::st_geometry(geometry) stopifnot(is(geometry, "sfc_POLYGON") | is(geometry, "sfc_MULTIPOLYGON")) M <- template_metrics(las, func, geometry, ...) M <- sf::st_set_geometry(M, geometry) return(M) }
"bpy.colors" <- function (n = 100, cutoff.tails = 0.1, alpha = 1) { n <- as.integer(n[1]) if (n <= 0) return(character(0)) if (cutoff.tails >= 1 || cutoff.tails < 0) stop("cutoff.tails should be in [0, 1]") i = seq(0.5 * cutoff.tails, 1 - 0.5 * cutoff.tails, length.out = n) r = ifelse(i < .25, 0, ifelse(i < .57, i / .32 - .78125, 1)) g = ifelse(i < .42, 0, ifelse(i < .92, 2 * i - .84, 1)) b = ifelse(i < .25, 4 * i, ifelse(i < .42, 1, ifelse(i < .92, -2 * i + 1.84, i / .08 - 11.5))) rgb(r, g, b, alpha) }