code
stringlengths
1
13.8M
binder_builder <- function(path = ".", hub = "mybinder.org", urlpath = "rstudio") { path <- sanitize_path(path) if (!has_a_git_remote()) { stop( "Cannot build without the project having a Git remote. Please connec this to a public repository on GitHub" ) } user <- gh_tree_remote(path)$username repo <- gh_tree_remote(path)$repo binder_runtime <- glue::glue("https://{hub}/build/gh/{user}/{repo}/master") res <- httr::GET(binder_runtime) url <- glue("https://{hub}/v2/gh/{user}/{repo}/master?urlpath={urlpath}") return(url) } build_binder <- function(path = ".", hub = "mybinder.org", urlpath = "rstudio") { proceed <- TRUE if (!is_clean(path)) { if (interactive()) { proceed <- usethis::ui_yeah( "There are uncommitted files in your repo. Until committed and pushed to GitHub, Binder cannot build from these files. Do you still wish to continue?" ) } else { warning("There are uncommitted files in your repo. Until committed and pushed to GitHub, Binder cannot build from these files.") } } if (proceed) { cliapp::cli_alert_info( glue::glue( "Your Binder is being built in the background. Once built, your browser will automatically launch. You can also click the binder badge on your README at any time." ) ) `%...>%` <- promises::`%...>%` multisession <- "future" %:::% "multisession" future::plan(multisession, workers = 2) future::future({ binder_builder(path, hub, urlpath) }) %...>% utils::browseURL } }
RWMH<- function(data,propob=NULL,posterior=NULL,iter=1500,burn=500,vscale=1.5, start=NULL,prior="Normal",mu=0,sig=10){ if(is.null(posterior)){ logpost<- function(start,data) posterior(start,data,Log=TRUE,mu=mu,sig=sig,prior=prior) } if(is.null(propob)){ propob = lapl_aprx(data[,1],data[,-1]) } varprop = vscale*propob$var npar = length(propob$mode) Mat = array(0, c(iter, npar)) if(is.null(start)){ start = MASS::mvrnorm(n=1,propob$mode,varprop) } e = 0.000001 Mat[1,] = start; AccptRate<-0 for(i in 2:iter){ start= Mat[i-1,] prop = MASS::mvrnorm(n=1,start,varprop) + stats::runif(1,-e,e) lpa = logpost(prop,data); lpb = logpost(start,data) accprob = exp(lpa-lpb) if(stats::runif(1)< accprob){ Mat[i,]=prop AccptRate<- AccptRate +1 }else{ Mat[i,]=start } } AcceptanceRate = AccptRate/iter val = list(Matpram=Mat[-c(1:burn),],AcceptanceRate=AcceptanceRate) cat("Random Walk MH algorithm successful. Acceptance ratio = ", AcceptanceRate," \n") return(val) } IndepMH<- function(data,propob=NULL,posterior=NULL,iter=1500,burn=500,vscale=1.5, start=NULL,prior="Uniform",mu=0,sig=10){ if(is.null(posterior)){ logpost<- function(start,data) posterior(start,data,Log=T,mu=mu,sig=sig,prior=prior) } if(is.null(propob)){ propob = lapl_aprx(data[,1],data[,-1]) } varprop = vscale*propob$var npar = length(propob$mode) Mat = array(0, c(iter, npar)) if(is.null(start)){ start = MASS::mvrnorm(n=1,propob$mode,varprop) } Mat[1,] = start; AccptRate<-0 for(i in 2:iter){ start= Mat[i-1,] prop = MASS::mvrnorm(n=1,propob$mode,varprop) lpa = logpost(prop,data); lpb = logpost(start,data) accprob = exp(lpa-lpb) if(stats::runif(1)< accprob){ Mat[i,]=prop AccptRate<- AccptRate +1 }else{ Mat[i,]=start } } Accept_Rate = AccptRate/iter val = list(Matpram=Mat[-c(1:burn),],Accept_Rate = AccptRate/iter) cat("IndepMH algorithm successful. Acceptance ratio = ", Accept_Rate," \n") return(val) }
svc <- paws::kinesisvideo() test_that("describe_signaling_channel", { expect_error(svc$describe_signaling_channel(), NA) }) test_that("describe_stream", { expect_error(svc$describe_stream(), NA) }) test_that("list_signaling_channels", { expect_error(svc$list_signaling_channels(), NA) }) test_that("list_signaling_channels", { expect_error(svc$list_signaling_channels(MaxResults = 20), NA) }) test_that("list_streams", { expect_error(svc$list_streams(), NA) }) test_that("list_streams", { expect_error(svc$list_streams(MaxResults = 20), NA) }) test_that("list_tags_for_stream", { expect_error(svc$list_tags_for_stream(), NA) })
uniprot <- function(accid) { oops <- requireNamespace("XML", quietly = TRUE) if(!oops) stop("Please install the XML package from CRAN") url <- paste('http://www.uniprot.org/uniprot/', accid, '.xml', sep="") tmpfile <- tempfile() download.file(url, tmpfile) xml <- XML::xmlRoot(XML::xmlParse(tmpfile)) node.names <- XML::xmlSApply(xml[[1]], XML::xmlName) inds <- which(node.names=="accession") accession <- NULL for(i in 1:length(inds)) accession <- c(accession, XML::xmlValue(xml[[1]][[inds[i]]])) inds <- which(node.names=="name") name <- NULL for(i in 1:length(inds)) name <- c(name, XML::xmlValue(xml[[1]][[inds[i]]])) inds <- which(node.names=="sequence") sequence <- gsub("\n", "", XML::xmlValue(xml[[1]][[inds]])) inds <- which(node.names=="organism") node <- xml[[1]][[inds]] organism <- NULL tmpl <- unlist(XML::xmlApply(node, XML::xmlAttrs)) if("scientific" %in% tmpl) organism <- XML::xmlValue(node[[which(tmpl %in% "scientific")]]) if("common" %in% tmpl) organism <- c(organism, XML::xmlValue(node[[which(tmpl %in% "common")]])) inds <- which(node.names=="organism") node <- xml[[1]][[inds]] taxon <- NULL for ( i in 1:XML::xmlSize(node[['lineage']]) ) { taxon <- c(taxon, XML::xmlValue(node[['lineage']][[i]])) } node <- xml[[1]][['protein']] fullName <- XML::xmlValue(node[['recommendedName']][['fullName']]) shortName <- XML::xmlValue(node[['recommendedName']][['shortName']]) node <- xml[[1]][['gene']] gene <- XML::xmlValue(node[[1]]) inds <- which(node.names=="dbReference") dbref <- list() for(i in 1:length(inds)) { node <- xml[[1]][[inds[i]]] dbref[[i]] <- XML::xmlAttrs(node) } dbref <- unlist(dbref) type.inds <- names((dbref)) == "type" id.inds <- names((dbref)) == "id" dbref <- data.frame(type=dbref[type.inds], id=dbref[id.inds], stringsAsFactors=FALSE) out <- list(accession = accession, name = name, fullName = fullName, shortName = shortName, sequence = sequence, gene = gene, organism = organism, taxon = taxon, dbref=dbref) return(out) }
model.binary.het.eqcor <- function(prior.type = "unif", rank.prob = TRUE){ if(prior.type == "unif" & rank.prob){ modelstring<-" model{ for(i in 1:len){ p[i] <- phi(mu[t[i]] + vi[s[i], t[i]]) r[i] ~ dbin(p[i], totaln[i]) } for(j in 1:nstudy){ vi[j, 1:ntrt] ~ dmnorm(zeros[1:ntrt], T[1:ntrt, 1:ntrt]) } for(j in 1:ntrt){ AR[j] <- phi(mu[j]/sqrt(1 + pow(sigma[j], 2))) mu[j] ~ dnorm(0, 0.001) sigma[j] ~ dunif(0.0001, c) } for(j in 1:ntrt){ for(k in 1:ntrt){ T[j,k] <- 1/sigma[j]*1/sigma[k]*ifelse(j == k, diag, offdiag) } } diag <- (1 + (ntrt - 2)*rho)/(1 + (ntrt - 2)*rho - (ntrt - 1)*rho^2) offdiag <- (-rho/(1 + (ntrt - 2)*rho - (ntrt - 1)*rho^2)) rho ~ dunif(-1/(ntrt - 1), 0.9999) for(j in 1:ntrt){ for(k in 1:ntrt){ LRR[j,k] <- log(RR[j,k]) LOR[j,k] <- log(OR[j,k]) RR[j,k] <- AR[j]/AR[k] RD[j,k] <- AR[j]-AR[k] OR[j,k] <- AR[j]/(1 - AR[j])/AR[k]*(1 - AR[k]) } } rk[1:ntrt] <- (ntrt + 1 - rank(AR[]))*ifelse(higher.better, 1, 0) + (rank(AR[]))*ifelse(higher.better, 0, 1) for(i in 1:ntrt){ rank.prob[1:ntrt, i] <- equals(rk[], i) } } " } if(prior.type == "unif" & !rank.prob){ modelstring<-" model{ for(i in 1:len){ p[i] <- phi(mu[t[i]] + vi[s[i], t[i]]) r[i] ~ dbin(p[i], totaln[i]) } for(j in 1:nstudy){ vi[j, 1:ntrt] ~ dmnorm(zeros[1:ntrt], T[1:ntrt, 1:ntrt]) } for(j in 1:ntrt){ AR[j] <- phi(mu[j]/sqrt(1 + pow(sigma[j], 2))) mu[j] ~ dnorm(0, 0.001) sigma[j] ~ dunif(0.0001, c) } for(j in 1:ntrt){ for(k in 1:ntrt){ T[j,k] <- 1/sigma[j]*1/sigma[k]*ifelse(j == k, diag, offdiag) } } diag <- (1 + (ntrt - 2)*rho)/(1 + (ntrt - 2)*rho - (ntrt - 1)*rho^2) offdiag <- (-rho/(1 + (ntrt - 2)*rho - (ntrt - 1)*rho^2)) rho ~ dunif(-1/(ntrt - 1), 0.9999) for(j in 1:ntrt){ for(k in 1:ntrt){ LRR[j,k] <- log(RR[j,k]) LOR[j,k] <- log(OR[j,k]) RR[j,k] <- AR[j]/AR[k] RD[j,k] <- AR[j] - AR[k] OR[j,k] <- AR[j]/(1 - AR[j])/AR[k]*(1 - AR[k]) } } } " } if(prior.type == "invgamma" & rank.prob){ modelstring<-" model{ for(i in 1:len){ p[i] <- phi(mu[t[i]] + vi[s[i], t[i]]) r[i] ~ dbin(p[i], totaln[i]) } for(j in 1:nstudy){ vi[j, 1:ntrt] ~ dmnorm(zeros[1:ntrt], T[1:ntrt, 1:ntrt]) } for(j in 1:ntrt){ AR[j] <- phi(mu[j]/sqrt(1 + pow(sigma[j], 2))) mu[j] ~ dnorm(0, 0.001) sigma[j] <- 1/sqrt(inv.sig.sq[j]) inv.sig.sq[j] ~ dgamma(a, b) } for(j in 1:ntrt){ for(k in 1:ntrt){ T[j,k] <- 1/sigma[j]*1/sigma[k]*ifelse(j == k, diag, offdiag) } } diag <- (1 + (ntrt - 2)*rho)/(1 + (ntrt - 2)*rho - (ntrt - 1)*rho^2) offdiag <- (-rho/(1 + (ntrt - 2)*rho - (ntrt - 1)*rho^2)) rho ~ dunif(-1/(ntrt - 1), 0.9999) for(j in 1:ntrt){ for(k in 1:ntrt){ LRR[j,k] <- log(RR[j,k]) LOR[j,k] <- log(OR[j,k]) RR[j,k] <- AR[j]/AR[k] RD[j,k] <- AR[j] - AR[k] OR[j,k] <- AR[j]/(1 - AR[j])/AR[k]*(1 - AR[k]) } } rk[1:ntrt] <- (ntrt + 1 - rank(AR[]))*ifelse(higher.better, 1, 0) + (rank(AR[]))*ifelse(higher.better, 0, 1) for(i in 1:ntrt){ rank.prob[1:ntrt, i] <- equals(rk[], i) } } " } if(prior.type == "invgamma" & !rank.prob){ modelstring<-" model{ for(i in 1:len){ p[i] <- phi(mu[t[i]] + vi[s[i], t[i]]) r[i] ~ dbin(p[i], totaln[i]) } for(j in 1:nstudy){ vi[j, 1:ntrt] ~ dmnorm(zeros[1:ntrt], T[1:ntrt, 1:ntrt]) } for(j in 1:ntrt){ AR[j] <- phi(mu[j]/sqrt(1 + pow(sigma[j], 2))) mu[j] ~ dnorm(0, 0.001) sigma[j] <- 1/sqrt(inv.sig.sq[j]) inv.sig.sq[j] ~ dgamma(a, b) } for(j in 1:ntrt){ for(k in 1:ntrt){ T[j,k] <- 1/sigma[j]*1/sigma[k]*ifelse(j == k, diag, offdiag) } } diag <- (1 + (ntrt - 2)*rho)/(1 + (ntrt - 2)*rho - (ntrt - 1)*rho^2) offdiag <- (-rho/(1 + (ntrt - 2)*rho - (ntrt - 1)*rho^2)) rho ~ dunif(-1/(ntrt - 1), 0.9999) for(j in 1:ntrt){ for(k in 1:ntrt){ LRR[j,k] <- log(RR[j,k]) LOR[j,k] <- log(OR[j,k]) RR[j,k] <- AR[j]/AR[k] RD[j,k] <- AR[j] - AR[k] OR[j,k] <- AR[j]/(1 - AR[j])/AR[k]*(1 - AR[k]) } } } " } if(!is.element(prior.type, c("unif", "invgamma"))){ stop("specified prior type is wrong.") } return(modelstring) }
summary.snowprofileSet <- function(object, ...) { Summaries <- lapply(object, summary) Summaries <- data.table::rbindlist(Summaries, fill = TRUE) Summaries <- as.data.frame(Summaries) return(Summaries) }
AVERAGE <- function(number1,number2 = NA,number3 = NA,number4 = NA,number5 = NA,number6 = NA,number7 = NA,number8 = NA,number9 = NA,number10 = NA,number11 = NA,number12 = NA,number13 = NA,number14 = NA,number15 = NA,number16 = NA,number17 = NA,number18 = NA,number19 = NA,number20 = NA,number21 = NA,number22 = NA,number23 = NA,number24 = NA){ mean(c(number1,number2,number3,number4,number5,number6,number7, number8,number9,number10,number11,number12,number13,number14,number15, number16,number17,number18,number19,number20,number21,number22,number23,number24),na.rm = TRUE) }
NA utils::globalVariables(c("stat", "value", "response_var_")) rhs_or_expr <- function(x) { e <- enexpr(x) if (rlang::is_formula(e)) { return(rlang::f_rhs(e)) } return(e) } cond2sum <- function(formula) { e <- environment(formula) res <- as.formula(sub("\\|", "+", format(formula))) environment(res) <- e res } df_stats <- function(formula, data, ..., drop = TRUE, fargs = list(), sep = "_", format = c("wide", "long"), groups = NULL, long_names = FALSE, nice_names = FALSE, na.action = "na.warn") { qdots <- rlang::enquos(...) format <- match.arg(format) if (length(qdots) < 1) { qdots <- list(dplyr::quo(df_favstats)) names(qdots) <- "" na.action = "na.pass" } if (inherits(formula, "data.frame") && inherits(data, "formula")) { tmp <- data data <- formula formula <- tmp } if ( ! inherits(formula, "formula")) stop("first arg must be a formula") if ( ! inherits(data, "data.frame")) stop("second arg must be a data.frame") formula <- cond2sum(mosaic_formula_q(reop_formula(formula), groups = !!rlang::enexpr(groups))) if (length(formula) == 2L) { formula <- substitute(x ~ 1, list(x = formula[[2]])) } left <- rlang::f_lhs(formula) if (left == "." || (length(left) > 1 && left[[1]] == "+")) { if (left == ".") { lefts <- setdiff( names(data), sapply(parse_call(rlang::f_rhs(formula)), deparse) ) lefts <- lapply(lefts, as.name) } else { lefts <- parse_call(left) } long_names <- FALSE formulas <- lapply( lefts, function(x) { my_form <- substitute(L ~ R, list(L = x, R = rlang::f_rhs(formula))) class(my_form) <- "formula" my_form } ) res <- lapply( formulas, function(f) { df_stats(f, data, ..., drop = drop, fargs = fargs, sep = sep, format = format, nice_names = nice_names, na.action = na.action) } ) return(bind_rows(res)) } if (identical(na.action, "na.warn")) na.action <- na.warn MF <- model.frame(formula, data, na.action = na.action) one_group <- FALSE if (ncol(MF) == 1) { one_group <- TRUE if ("group" %in% names(MF)) { MF[, "..group.."] <- 1 } else { MF[, "group"] <- 1 } } res <- lapply( qdots, function(f) { if (inherits(rlang::f_rhs(f), "call")) { df_aggregate(MF[, 1], by = MF[, -1, drop = FALSE], FUN = function(x) eval(substitute(x %>% foo, list(foo = rlang::f_rhs(f)))), drop = drop) } else { df_aggregate(MF[, 1], by = MF[, -1, drop = FALSE], FUN = function(x) do.call(rlang::eval_tidy(f), c(list(x), fargs)), drop = drop) } } ) arg_names <- names(res) num_grouping_vars <- ncol(MF) - 1 groups <- res[[1]][, 1:num_grouping_vars, drop = FALSE] res0 <- res res1 <- lapply(res, function(x) make_df(x[[dim(x)[2]]])) res <- res1 res_names <- lapply(res1, names) res_names <- lapply(res_names, function(x) if(all(x == ".")) NULL else x) ncols <- sapply(res, ncol) fun_names <- sapply( qdots, function(x) { if (rlang::is_character(rlang::f_rhs(x))) rlang::f_rhs(x) else deparse(rlang::f_rhs(x)) } ) fun_names <- ifelse(sapply(res_names, is.null), fun_names, "") part1 <- rep(ifelse(arg_names == "", fun_names, arg_names), ncols) part1 <- gsub("df_favstats", "", part1) part2 <- rep(ifelse(arg_names == "" & long_names & ! fun_names == "df_favstats", deparse(formula[[2]]), ""), ncols) part2 <- ifelse(part1 == "", "", part2) res_names <- ifelse(sapply(res_names, is.null), "", res_names) alt_res_names <- lapply(ncols, function(nc) if (nc > 1) format(1:nc) else "") part3 <- ifelse(res_names == "", alt_res_names, res_names) part3 <- unlist(part3) final_names <- paste(part1, part2, part3, sep = sep) final_names <- gsub(paste0(sep, sep), sep, final_names) final_names <- gsub(paste0(sep, "$"), "", final_names) final_names <- gsub(paste0("^", sep), "", final_names) res <- do.call(cbind, c(list(groups), res)) names(res) <- c(names(res)[1:num_grouping_vars], unlist(final_names)) if (nice_names) names(res) <- base::make.names(names(res), unique = TRUE) if (one_group) { res <- res[, -1, drop = FALSE] } row.names(res) <- NULL res <- res %>% dplyr::mutate(response_var_ = deparse(rlang::f_lhs(formula))) %>% dplyr::select(response_var_, names(res)) if (! "response" %in% names(res)) { res <- dplyr::rename(res, response = response_var_) } if (format == "long") { res %>% tidyr::pivot_longer(names_to = "stat", values_to = "value", !! -(1:(1 + num_grouping_vars))) } else { res } } df_favstats <- function (x, ..., na.rm = TRUE, type = 7) { if (!is.null(dim(x)) && min(dim(x)) != 1) warning("Not respecting matrix dimensions. Hope that's OK.") if (! is.numeric(x)) { warning("Auto-converting ", class(x), " to numeric.") x <- as.numeric(x) if (!is.numeric(x)) stop("Auto-conversion to numeric failed.") } qq <- if (na.rm) stats::quantile(x, na.rm = na.rm, type = type) else rep(NA, 5) val <- data.frame( min=qq[1], Q1 = qq[2], median = qq[3], Q3 = qq[4], max = qq[5], mean = base::mean(x, na.rm = na.rm), sd = stats::sd(x, na.rm = na.rm), n = base::sum(! is.na(x)), missing = base::sum( is.na(x) ) ) rownames(val) <- "" return(val) } na.warn <- function(object, ...) { res <- stats::na.exclude(object, ...) n_excluded <- nrow(object) - nrow(res) if (n_excluded > 0L) { warning(paste0("Excluding ", n_excluded, " rows due to missing data [df_stats()]."), call. = FALSE) } res }
addMetaInformation <- function(series,map_list, meta_env = NULL, overwrite_objects = F, overwrite_elements = T){ stopifnot(is.list(map_list)) class(map_list) <- c('miro','list') map_list[map_list == ''] <- NULL if(length(map_list) == 0) map_list <- NULL if(is.null(meta_env)){ meta_env <- new.env() if(!is.null(map_list)){ meta_env[[series]] <- map_list } } else { if(overwrite_objects){ if(!is.null(map_list)){ meta_env[[series]] <- map_list } } else { if(!is.null(meta_env[[series]])){ elements_in_old <- (names(map_list) %in% names(meta_env[[series]])) new_elements <- map_list[!elements_in_old] meta_env[[series]] <- c(meta_env[[series]],new_elements) if(overwrite_elements & length(map_list[elements_in_old]) != 0){ meta_env[[series]][names(map_list[elements_in_old])] <- map_list[elements_in_old] } } else { meta_env[[series]] <- map_list } } } class(meta_env) <- c('meta_env','environment') meta_env }
test_that("posterior_interval pi has the correct form", { ds_pi_interval <- posterior_interval(ds_fit, pars = "pi") expect_equal(dim(ds_pi_interval), c(4, 2)) expect_equal(colnames(ds_pi_interval), c("5%", "95%")) ccds_pi_interval <- posterior_interval(ccds_fit, pars = "pi") expect_equal(dim(ccds_pi_interval), c(4, 2)) expect_equal(colnames(ccds_pi_interval), c("5%", "95%")) hds_pi_interval <- posterior_interval(hds_fit, pars = "pi") expect_equal(dim(hds_pi_interval), c(4, 2)) expect_equal(colnames(hds_pi_interval), c("5%", "95%")) }) test_that("Can change interval probability", { default <- posterior_interval(ds_fit, pars = "pi") smaller <- posterior_interval(ds_fit, pars = "pi", prob = 0.5) expect_lte(default[1, 1], smaller[1, 1]) expect_gte(default[1, 2], smaller[1, 2]) larger <- posterior_interval(ds_fit, pars = "pi", prob = 0.99) expect_gte(default[1, 1], larger[1, 1]) expect_lte(default[1, 2], larger[1, 2]) }) test_that("posterior_interval for theta has the correct form", { J <- 5 K <- 4 ds_theta_interval <- posterior_interval(ds_fit, pars = "theta") expect_equal(dim(ds_theta_interval), c(J * K * K , 2)) expect_equal(colnames(ds_theta_interval), c("5%", "95%")) ccds_theta_interval <- posterior_interval(ds_fit, pars = "theta") expect_equal(dim(ccds_theta_interval), c(J * K * K , 2)) expect_equal(colnames(ccds_theta_interval), c("5%", "95%")) }) test_that("DS and CCDS posterior_interval for theta have the same rownames", { ds_theta_interval <- posterior_interval(ds_fit, pars = "theta") ccds_theta_interval <- posterior_interval(ds_fit, pars = "theta") expect_equal(rownames(ds_theta_interval), rownames(ccds_theta_interval)) }) test_that("posterior_interval errors correctly", { expect_error( posterior_interval(ds_fit_optim, pars = "z"), "Can't calculate posterior intervals for a model fit using optimisation." ) expect_error( posterior_interval(ds_fit, pars = "z"), "Cannot calculate quantiles for z" ) }) test_that("posterior_interval errors informatively with the HDS", { expect_snapshot(posterior_interval(hds_fit), error = TRUE) }) test_that("posterior_interval orders parameters correctly", { correct_rownames <- sprintf("theta[1, 1, %s]", 1:K) expect_equal(rownames(posterior_interval(ds_fit, pars = "theta"))[1:K], correct_rownames) })
source(system.file(file.path('tests', 'testthat', 'test_utils.R'), package = 'nimble')) RwarnLevel <- options('warn')$warn options(warn = 1) nimbleVerboseSetting <- nimbleOptions('verbose') nimbleOptions(verbose = FALSE) nimbleProgressBarSetting <- nimbleOptions('MCMCprogressBar') nimbleOptions(MCMCprogressBar = FALSE) context('Testing of BNP functionality') getSamplesDPmeasure_old <- function(MCMC, epsilon = 1e-4) { if(exists('model',MCMC, inherits = FALSE)) compiled <- FALSE else compiled <- TRUE if(compiled) { if(!exists('Robject', MCMC, inherits = FALSE) || !exists('model', MCMC$Robject, inherits = FALSE)) stop("getSamplesDPmeasure: problem with finding model object in compiled MCMC") model <- MCMC$Robject$model mvSamples <- MCMC$Robject$mvSamples } else { model <- MCMC$model mvSamples <- MCMC$mvSamples } rsampler <- sampleDPmeasure_old(model, mvSamples, epsilon) if(compiled) { csampler <- compileNimble(rsampler, project = model) csampler$run() samplesMeasure <- csampler$samples } else { rsampler$run() samplesMeasure <- rsampler$samples } dcrpVar <- rsampler$dcrpVar clusterVarInfo <- nimble:::findClusterNodes(model, dcrpVar) namesVars <- rsampler$tildeVars p <- length(namesVars) truncG <- ncol(samplesMeasure) / (rsampler$tildeVarsColsSum[p+1]+1) namesW <- sapply(seq_len(truncG), function(i) paste0("weight[", i, "]")) namesAtoms <- nimble:::getSamplesDPmeasureNames(clusterVarInfo, model, truncG, p) colnames(samplesMeasure) <- c(namesW, namesAtoms) output <- list(samples = samplesMeasure, trunc = truncG) return(output) } sampleDPmeasure_old <- nimbleFunction( name = 'sampleDPmeasure_old', setup=function(model, mvSaved, epsilon){ mvSavedVars <- mvSaved$varNames stochNodes <- model$getNodeNames(stochOnly = TRUE) distributions <- model$getDistribution(stochNodes) dcrpIndex <- which(distributions == 'dCRP') if(length(dcrpIndex) == 1) { dcrpNode <- stochNodes[dcrpIndex] dcrpVar <- model$getVarNames(nodes = dcrpNode) } else { if(length(dcrpIndex) == 0 ){ stop('sampleDPmeasure: One node with a dCRP distribution is required.\n') } stop('sampleDPmeasure: Currently only models with one node with a dCRP distribution are allowed.\n') } if(sum(dcrpVar == mvSavedVars) == 0) stop('sampleDPmeasure: The node having the dCRP distribution has to be monitored in the MCMC (and therefore stored in the modelValues object).\n') dcrpElements <- model$expandNodeNames(dcrpNode, returnScalarComponents = TRUE) clusterVarInfo <- nimble:::findClusterNodes(model, dcrpVar) tildeVars <- clusterVarInfo$clusterVars if( is.null(tildeVars) ) stop('sampleDPmeasure: The model should have at least one cluster variable.\n') isIID <- TRUE for(i in seq_along(clusterVarInfo$clusterNodes)) { clusterNodes <- clusterVarInfo$clusterNodes[[i]] clusterIDs <- clusterVarInfo$clusterIDs[[i]] splitNodes <- split(clusterNodes, clusterIDs) valueExprs <- lapply(splitNodes, function(x) { out <- sapply(x, model$getValueExpr) names(out) <- NULL out }) if(length(unique(valueExprs)) != 1) isIID <- FALSE } if(!isIID && length(tildeVars) == 2 && nimble:::checkNormalInvGammaConjugacy(model, clusterVarInfo, length(dcrpElements), 'dinvgamma')) isIID <- TRUE if(!isIID && length(tildeVars) == 2 && nimble:::checkNormalInvGammaConjugacy(model, clusterVarInfo, length(dcrpElements), 'dgamma')) isIID <- TRUE if(!isIID && length(tildeVars) == 2 && nimble:::checkNormalInvWishartConjugacy(model, clusterVarInfo, length(dcrpElements), 'dinvwish')) isIID <- TRUE if(!isIID && length(tildeVars) == 2 && nimble:::checkNormalInvWishartConjugacy(model, clusterVarInfo, length(dcrpElements), 'dwish')) isIID <- TRUE if(!isIID) stop('sampleDPmeasure: cluster parameters have to be independent and identically distributed. \n') counts <- tildeVars %in% mvSavedVars if( sum(counts) != length(tildeVars) ) stop('sampleDPmeasure: The node(s) representing the cluster variables must be monitored in the MCMC (and therefore stored in the modelValues object).\n') parentNodesTildeVars <- NULL candidateParentNodes <- model$getNodeNames(includeData = FALSE, stochOnly = TRUE) candidateParentNodes <- candidateParentNodes[!candidateParentNodes %in% unlist(clusterVarInfo$clusterNodes)] for(i in seq_along(candidateParentNodes)) { aux <- model$getDependencies(candidateParentNodes[i], self = FALSE) for(j in seq_along(tildeVars)) { if(sum(aux == clusterVarInfo$clusterNodes[[j]][1])) parentNodesTildeVars <- c(parentNodesTildeVars, candidateParentNodes[i]) } } if(length(parentNodesTildeVars)) { parentNodesTildeVarsDeps <- model$getDependencies(parentNodesTildeVars, self = FALSE) } else parentNodesTildeVarsDeps <- NULL parentNodesTildeVarsDeps <- model$topologicallySortNodes(c(parentNodesTildeVarsDeps, unlist(clusterVarInfo$clusterNodes))) if(!all(model$getVarNames(nodes = parentNodesTildeVars) %in% mvSavedVars)) stop('sampleDPmeasure: The stochastic parent nodes of the cluster variables have to be monitored in the MCMC (and therefore stored in the modelValues object).\n') if(is.null(parentNodesTildeVars)) parentNodesTildeVars <- tildeVars parentNodesXi <- NULL candidateParentNodes <- model$getNodeNames(includeData = FALSE, stochOnly = TRUE) candidateParentNodes <- candidateParentNodes[!candidateParentNodes == dcrpNode] for(i in seq_along(candidateParentNodes)) { aux <- model$getDependencies(candidateParentNodes[i], self = FALSE) if(sum(aux == dcrpNode)) { parentNodesXi <- c(parentNodesXi, candidateParentNodes[i]) } } if(!all(model$getVarNames(nodes = parentNodesXi) %in% mvSavedVars)) stop('sampleDPmeasure: The stochastic parent nodes of the membership variables have to be monitored in the MCMC (and therefore stored in the modelValues object).\n') if(is.null(parentNodesXi)) parentNodesXi <- dcrpNode fixedConc <- TRUE if(length(parentNodesXi)) { fixedConc <- FALSE parentNodesXiDeps <- model$getDependencies(parentNodesXi, self = FALSE) parentNodesXiDeps <- parentNodesXiDeps[!parentNodesXiDeps == dcrpNode] } else { parentNodesXiDeps <- dcrpNode } dataNodes <- model$getDependencies(dcrpNode, stochOnly = TRUE, self = FALSE) N <- length(model$expandNodeNames(dcrpNode, returnScalarComponents = TRUE)) p <- length(tildeVars) lengthData <- length(model$expandNodeNames(dataNodes[1], returnScalarComponents = TRUE)) dimTildeVarsNim <- numeric(p+1) dimTildeVars <- numeric(p+1) for(i in 1:p) { dimTildeVarsNim[i] <- model$getDimension(clusterVarInfo$clusterNodes[[i]][1]) dimTildeVars[i] <- lengthData^(dimTildeVarsNim[i]) } nTildeVarsPerCluster <- clusterVarInfo$numNodesPerCluster nTilde <- numeric(p+1) nTilde[1:p] <- clusterVarInfo$nTilde / nTildeVarsPerCluster if(any(nTilde[1:p] != nTilde[1])){ stop('sampleDPmeasure: All cluster parameters must have the same number of parameters.\n') } tildeVarsCols <- c(dimTildeVars[1:p]*nTildeVarsPerCluster, 0) tildeVarsColsSum <- c(0, cumsum(tildeVarsCols)) mvIndexes <- matrix(0, nrow=nTilde[1], ncol=(sum(dimTildeVars[1:p]*nTildeVarsPerCluster))) for(j in 1:p) { tildeNodesModel <- model$expandNodeNames(clusterVarInfo$clusterVars[j], returnScalarComponents=TRUE) allIndexes <- 1:length(tildeNodesModel) for(l in 1:nTilde[1]) { clusterID <- l tildeNodesPerClusterID <- model$expandNodeNames(clusterVarInfo$clusterNodes[[j]][clusterVarInfo$clusterIDs[[j]] == clusterID], returnScalarComponents=TRUE) aux <- match(tildeNodesModel, tildeNodesPerClusterID, nomatch = 0) mvIndexes[l,(tildeVarsColsSum[j]+1):tildeVarsColsSum[j+1] ] <- which(aux != 0) } } samples <- matrix(0, nrow = 1, ncol = 1) truncG <- 0 niter <- 0 setupOutputs(lengthData, dcrpVar) }, run=function(){ niter <<- getsize(mvSaved) if( fixedConc ) { concSamples <- nimNumeric(length = niter, value = model$getParam(dcrpNode, 'conc')) } else { concSamples <- numeric(niter) for( iiter in 1:niter ) { nimCopy(from = mvSaved, to = model, nodes = parentNodesXi, row=iiter) model$calculate(parentNodesXiDeps) concSamples[iiter] <- model$getParam(dcrpNode, 'conc') } } dcrpAux <- mean(concSamples) + N truncG <<- log(epsilon) / log(dcrpAux / (dcrpAux+1)) truncG <<- ceiling(truncG) samples <<- matrix(0, nrow = niter, ncol = truncG*(tildeVarsColsSum[p+1]+1)) for(iiter in 1:niter){ checkInterrupt() vaux <- rbeta(1, 1, concSamples[iiter] + N) v1prod <- 1 samples[iiter, 1] <<- vaux for(l1 in 2:truncG) { v1prod <- v1prod * (1-vaux) vaux <- rbeta(1, 1, concSamples[iiter] + N) samples[iiter, l1] <<- vaux * v1prod } samples[iiter, 1:truncG] <<- samples[iiter, 1:truncG] / (1 - v1prod * (1-vaux)) probs <- nimNumeric(N) uniqueValues <- matrix(0, nrow = N, ncol = tildeVarsColsSum[p+1]) xiiter <- mvSaved[dcrpVar, iiter] range <- min(xiiter):max(xiiter) index <- 1 for(i in seq_along(range)){ cond <- sum(xiiter == range[i]) if(cond > 0){ probs[index] <- cond nimCopy(mvSaved, model, tildeVars, row = iiter) for(j in 1:p){ jcols <- (tildeVarsColsSum[j]+1):tildeVarsColsSum[j+1] uniqueValues[index, jcols] <- values(model, tildeVars[j])[mvIndexes[range[i], jcols]] } index <- index+1 } } probs[index] <- concSamples[iiter] newValueIndex <- index nimCopy(mvSaved, model, parentNodesTildeVars, row = iiter) sumCol <- truncG for(l1 in 1:truncG) { index <- rcat(prob = probs[1:newValueIndex]) if(index == newValueIndex){ model$simulate(parentNodesTildeVarsDeps) for(j in 1:p){ jcols <- (sumCol + 1):(sumCol + tildeVarsCols[j]) samples[iiter, jcols] <<- values(model, tildeVars[j])[mvIndexes[1, (tildeVarsColsSum[j]+1):tildeVarsColsSum[j+1]]] sumCol <- sumCol + tildeVarsCols[j] } } else { for(j in 1:p){ jcols <- (sumCol +1):(sumCol + tildeVarsCols[j]) samples[iiter, jcols] <<- uniqueValues[index, (tildeVarsColsSum[j]+1):tildeVarsColsSum[j+1]] sumCol <- sumCol + tildeVarsCols[j] } } } } }, methods = list( reset = function () {} ) ) test_that("Test computations (prior predictive and posterior) and sampler assignment for conjugate CRP samplers", { set.seed(0) code <- nimbleCode({ for(i in 1:5) { for(j in 1:2) { y[i,j] ~ dnorm( mu[xi[i], j] , var = j/2) mu[i, j] ~ dnorm(0.2*j, var=j) } } xi[1:5] ~ dCRP(1, size=5) }) inits <- list(xi = 1:5, mu = matrix(rnorm(5*2, 0), nrow=5, ncol=2)) y <- matrix(rnorm(5*2, 10, 1), ncol=2, nrow=5) y[4:5, ] <- rnorm(2*2, -10, 1) data <- list(y=y) model <- nimbleModel(code, data=data, inits=inits, dimensions=list(mu=c(5,2)), calculate=TRUE) mConf <- configureMCMC(model, monitors = c('xi','mu')) mcmc <- buildMCMC(mConf) crpIndex <- which(sapply(mConf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_conjugate_dnorm_dnorm") pYgivenT <- sum(c(model$getLogProb('y[1, 1]'), model$getLogProb('y[1, 2]'))) pT <- sum(c(model$getLogProb('mu[1, 1]'), model$getLogProb('mu[1, 2]'))) dataVar <- c(model$getParam('y[1,1]', 'var') , model$getParam('y[1,2]', 'var') ) priorVar <- c(model$getParam('mu[1, 1]', 'var'), model$getParam('mu[1, 2]', 'var')) priorMean <- c(model$getParam('mu[1, 1]', 'mean') , model$getParam('mu[1, 2]', 'mean')) postVar <- 1 / (1 / dataVar + 1 / priorVar) postMean <- postVar * (c(data$y[1, 1], data$y[1, 2]) / dataVar + priorMean / priorVar) pTgivenY <- dnorm(model$mu[1, 1] , postMean[1], sqrt(postVar[1]), log = TRUE) + dnorm(model$mu[1, 2] , postMean[2], sqrt(postVar[2]), log = TRUE) mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$storeParams() pY <- mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$calculate_prior_predictive(1) expect_equal(pY, pT + pYgivenT - pTgivenY) set.seed(1) mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$sample(1, 1) set.seed(1) smp <- rnorm(2 , postMean, sqrt(postVar)) expect_identical(smp, c(model$mu[1, 1], model$mu[1, 2])) code=nimbleCode( { for(i in 1:5){ for(j in 1:2) { mu[i, 1:2, j] ~ dmnorm(mu0[1:2, j], cov=Cov0[1:2, 1:2, j]) y[i, 1:2, j] ~ dmnorm(mu[xi[i], 1:2, j], cov=Sigma0[1:2, 1:2, j]) } } xi[1:5] ~ dCRP(conc=1, size=5) } ) mu <- array(0, c(5, 2, 2)) for(j in 1:2) { mu[ , ,j] <- matrix(rnorm(5*2, 0, sqrt(0.01)), nrow=5, ncol=2) } y <- array(0, c(5, 2, 5)) for(i in 1:5) { for(j in 1:2) { y[i, ,j] <- rnorm(2, 5, sqrt(0.01)) } } mu0 <- matrix(rnorm(2*2), ncol=2, nrow=2) Cov0 <- array(0, c(2, 2, 2)) Sigma0 <- array(0, c(2, 2, 2)) for(j in 1:2) { Cov0[, , j] <- rinvwish_chol(1, chol(matrix(c(10, .7, .7, 10), 2)), 2) Sigma0[, , j] <- rinvwish_chol(1, chol(matrix(c(1, .5, .5, 1), 2)), 2) } model = nimbleModel(code, data = list(y = y), inits = list(xi = 1:5, mu=mu), constants=list(mu0 =mu0, Cov0 = Cov0, Sigma0 = Sigma0)) conf <- configureMCMC(model, monitors=c('xi', 'mu')) mcmc <- buildMCMC(conf) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_conjugate_dmnorm_dmnorm") pYgivenT <- sum(c(model$getLogProb('y[1, 1:2, 1]'), model$getLogProb('y[1, 1:2, 2]'))) pT <- sum(c(model$getLogProb('mu[1, 1:2, 1]'), model$getLogProb('mu[1, 1:2, 2]'))) dataCov <- list(model$getParam('y[1, 1:2, 1]', 'cov') , model$getParam('y[1, 1:2, 2]', 'cov') ) priorCov <- list(model$getParam('mu[1, 1:2, 1]', 'cov'), model$getParam('mu[1, 1:2, 2]', 'cov')) priorMean <- list(model$getParam('mu[1, 1:2, 1]', 'mean') , model$getParam('mu[1, 1:2, 2]', 'mean')) dataPrec <- list(inverse(dataCov[[1]]), inverse(dataCov[[2]])) priorPrec <- list(inverse(priorCov[[1]]), inverse(priorCov[[2]])) postPrecChol <- list(chol(dataPrec[[1]] + priorPrec[[1]]), chol(dataPrec[[2]] + priorPrec[[2]])) postMean <- list(backsolve(postPrecChol[[1]], forwardsolve(t(postPrecChol[[1]]), (dataPrec[[1]] %*% y[1, 1:2, 1] + priorPrec[[1]] %*% priorMean[[1]])[,1])), backsolve(postPrecChol[[2]], forwardsolve(t(postPrecChol[[2]]), (dataPrec[[2]] %*% y[1, 1:2, 2] + priorPrec[[2]] %*% priorMean[[2]])[,1]))) pTgivenY <- dmnorm_chol(model$mu[1, 1:2, 1], postMean[[1]], postPrecChol[[1]], prec_param = TRUE, log = TRUE) + dmnorm_chol(model$mu[1, 1:2, 2], postMean[[2]], postPrecChol[[2]], prec_param = TRUE, log = TRUE) mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$storeParams() pY <- mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$calculate_prior_predictive(1) expect_equal(pY, pT + pYgivenT - pTgivenY) set.seed(1) mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$sample(1, 1) set.seed(1) smp1 <- rmnorm_chol(1, postMean[[1]], postPrecChol[[1]], prec_param = TRUE) smp2 <- rmnorm_chol(1, postMean[[2]], postPrecChol[[2]], prec_param = TRUE) expect_identical(smp1, model$mu[1, 1:2, 1]) expect_identical(smp2, model$mu[1, 1:2, 2]) code <- nimbleCode({ for(i in 1:5) { for(j in 1:2) { y[i,j] ~ dnorm( mu[i, j] , var = s2[xi[i], j]) s2[i, j] ~ dinvgamma(shape = 2*j, scale = 0.1*j) } } xi[1:5] ~ dCRP(1, size=5) }) inits <- list(xi = 1:5, mu = matrix(rnorm(5*2, 0), nrow=5, ncol=2), s2 = matrix(rinvgamma(5*2, 2, 0.1), nrow=5, ncol=2)) y <- matrix(rnorm(5*2, 10, 1), ncol=2, nrow=5) y[4:5, ] <- rnorm(2*2, -10, 1) data <- list(y=y) model <- nimbleModel(code, data=data, inits=inits, dimensions=list(mu=c(5,2)), calculate=TRUE) mConf <- configureMCMC(model, monitors = c('xi','s2')) mcmc <- buildMCMC(mConf) crpIndex <- which(sapply(mConf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_conjugate_dinvgamma_dnorm") pYgivenT <- sum(c(model$getLogProb('y[1, 1]'), model$getLogProb('y[1, 2]'))) pT <- sum(c(model$getLogProb('s2[1, 1]'), model$getLogProb('s2[1, 2]'))) dataMean <- c(model$getParam('y[1,1]', 'mean') , model$getParam('y[1,2]', 'mean') ) priorShape <- c(model$getParam('s2[1, 1]', 'shape'), model$getParam('s2[1, 2]', 'shape')) priorScale <- c(model$getParam('s2[1, 1]', 'scale') , model$getParam('s2[1, 2]', 'scale')) postShape <- priorShape + 0.5 postScale <- priorScale + 0.5 * (c(data$y[1, 1], data$y[1, 2]) - dataMean)^2 pTgivenY <- dinvgamma(model$s2[1, 1] , shape = postShape[1], scale = postScale[1], log = TRUE) + dinvgamma(model$s2[1, 2] , shape = postShape[2], scale = postScale[2], log = TRUE) mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$storeParams() pY <- mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$calculate_prior_predictive(1) expect_equal(pY, pT + pYgivenT - pTgivenY) set.seed(1) mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$sample(1, 1) set.seed(1) smp <- rinvgamma(2 , shape = postShape, scale = postScale) expect_identical(smp, c(model$s2[1, 1], model$s2[1, 2])) code <- nimbleCode({ xi[1:5] ~ dCRP(conc = 1, size = 5) for(i in 1:5){ for(j in 1:2) { Sigma[1:2, 1:2, i, j] ~ dinvwish(S = R0[1:2, 1:2, j], df = v0[j]) y[i, 1:2, j] ~ dmnorm(mu[i, 1:2, j], cov = Sigma[1:2, 1:2, xi[i], j] ) } } }) R0 <- array(0, c(2, 2, 2)) for(j in 1:2) { R0[, , j] <- rinvwish_chol(1, chol(matrix(c(10, .7, .7, 10), 2)), 2) } Sigma <- array(0, c(2,2,5, 2)) for(i in 1:5){ for(j in 1:2) { Sigma[, , i, j] <- rinvwish_chol(1, chol(matrix(c(1, .5, .5, 1), 2)), 2) } } mu <- array(0, c(5, 2, 2)) for(j in 1:2) { mu[ , ,j] <- matrix(rnorm(5*2, 0, sqrt(0.01)), nrow=5, ncol=2) } y <- array(0, c(5, 2, 2)) for(i in 1:5) { for(j in 1:2) { y[i, ,j] <- rnorm(2, 0, sqrt(0.01)) } } data = list(y = y) inits = list(xi = 1:5, mu = mu, Sigma = Sigma) Consts <- list(v0 = rpois(2, 5), R0 = R0) model = nimbleModel(code, data=data, inits=inits, constants = Consts) mConf = configureMCMC(model, monitors = c('xi', 'Sigma')) mcmc = buildMCMC(mConf) crpIndex <- which(sapply(mConf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_conjugate_dinvwish_dmnorm") dataMean <- list(model$getParam('y[1, 1:2, 1]', 'mean'), model$getParam('y[1, 1:2, 2]', 'mean')) pYgivenT <- sum(model$getLogProb('y[1, 1:2, 1]'), model$getLogProb('y[1, 1:2, 2]')) pT <- sum(model$getLogProb('Sigma[1:2, 1:2, 1, 1]'), model$getLogProb('Sigma[1:2, 1:2, 1, 2]')) df0 <- c(model$getParam('Sigma[1:2, 1:2, 1, 1]', 'df'), model$getParam('Sigma[1:2, 1:2, 1, 2]', 'df')) priorScale <- list(model$getParam('Sigma[1:2, 1:2, 1, 1]', 'S'), model$getParam('Sigma[1:2, 1:2, 1, 2]', 'S')) pTgivenY <- dinvwish_chol(model$Sigma[1:2, 1:2, 1, 1], chol(priorScale[[1]] + (data$y[1, 1:2, 1]-dataMean[[1]])%*%t(data$y[1, 1:2, 1]-dataMean[[1]])), df = (df0[1]+1), scale_param=TRUE, log = TRUE) + dinvwish_chol(model$Sigma[1:2, 1:2, 1, 2], chol(priorScale[[2]] + (data$y[1, 1:2, 2]-dataMean[[2]])%*%t(data$y[1, 1:2, 2]-dataMean[[2]])), df = (df0[2]+1), scale_param=TRUE, log = TRUE) mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$storeParams() pY <- mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$calculate_prior_predictive(1)[1] expect_equal(pY, pT + pYgivenT - pTgivenY) set.seed(1) mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$sample(1, 1) set.seed(1) smp1 <- list() smp2 <- list() smp1[[1]] <- rinvwish_chol(1, chol(priorScale[[1]] + (data$y[1, 1:2, 1]-dataMean[[1]])%*%t(data$y[1, 1:2, 1]-dataMean[[1]])), df = (df0[1]+1), scale_param=TRUE ) smp1[[2]] <- rinvwish_chol(1, chol(priorScale[[2]] + (data$y[1, 1:2, 2]-dataMean[[2]])%*%t(data$y[1, 1:2, 2]-dataMean[[2]])), df = (df0[2]+1), scale_param=TRUE ) expect_identical(smp1[[1]], model$Sigma[1:2, 1:2, 1, 1]) expect_identical(smp1[[2]], model$Sigma[1:2, 1:2, 1, 2]) code <- nimbleCode({ xi[1:5] ~ dCRP(conc = 1, size = 5) for(i in 1:5){ for(j in 1:2) { Sigma[1:2, 1:2, i, j] ~ dwish(R = R0[1:2, 1:2, j], df = v0[j]) y[i, 1:2, j] ~ dmnorm(mu[i, 1:2, j], prec = Sigma[1:2, 1:2, xi[i], j] ) } } }) R0 <- array(0, c(2, 2, 2)) for(j in 1:2) { R0[, , j] <- rwish_chol(1, chol(matrix(c(10, .7, .7, 10), 2)), 2) } Sigma <- array(0, c(2,2,5, 2)) for(i in 1:5){ for(j in 1:2) { Sigma[, , i, j] <- rwish_chol(1, chol(matrix(c(1, .5, .5, 1), 2)), 2) } } mu <- array(0, c(5, 2, 2)) for(j in 1:2) { mu[ , ,j] <- matrix(rnorm(5*2, 0, sqrt(0.01)), nrow=5, ncol=2) } y <- array(0, c(5, 2, 2)) for(i in 1:5) { for(j in 1:2) { y[i, ,j] <- rnorm(2, 0, sqrt(0.01)) } } data = list(y = y) inits = list(xi = 1:5, mu = mu, Sigma = Sigma) Consts <- list(v0 = rpois(2, 5), R0 = R0) model = nimbleModel(code, data=data, inits=inits, constants = Consts) mConf = configureMCMC(model, monitors = c('xi', 'Sigma')) mcmc = buildMCMC(mConf) crpIndex <- which(sapply(mConf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_conjugate_dwish_dmnorm") dataMean <- list(model$getParam('y[1, 1:2, 1]', 'mean'), model$getParam('y[1, 1:2, 2]', 'mean')) pYgivenT <- sum(model$getLogProb('y[1, 1:2, 1]'), model$getLogProb('y[1, 1:2, 2]')) pT <- sum(model$getLogProb('Sigma[1:2, 1:2, 1, 1]'), model$getLogProb('Sigma[1:2, 1:2, 1, 2]')) df0 <- c(model$getParam('Sigma[1:2, 1:2, 1, 1]', 'df'), model$getParam('Sigma[1:2, 1:2, 1, 2]', 'df')) priorScale <- list(model$getParam('Sigma[1:2, 1:2, 1, 1]', 'R'), model$getParam('Sigma[1:2, 1:2, 1, 2]', 'R')) pTgivenY <- dwish_chol(model$Sigma[1:2, 1:2, 1, 1], chol(priorScale[[1]] + (data$y[1, 1:2, 1]-dataMean[[1]])%*%t(data$y[1, 1:2, 1]-dataMean[[1]])), df = (df0[1]+1), scale_param=FALSE, log = TRUE) + dwish_chol(model$Sigma[1:2, 1:2, 1, 2], chol(priorScale[[2]] + (data$y[1, 1:2, 2]-dataMean[[2]])%*%t(data$y[1, 1:2, 2]-dataMean[[2]])), df = (df0[2]+1), scale_param=FALSE, log = TRUE) mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$storeParams() pY <- mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$calculate_prior_predictive(1)[1] expect_equal(pY, pT + pYgivenT - pTgivenY) set.seed(1) mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$sample(1, 1) set.seed(1) smp1 <- list() smp2 <- list() smp1[[1]] <- rwish_chol(1, chol(priorScale[[1]] + (data$y[1, 1:2, 1]-dataMean[[1]])%*%t(data$y[1, 1:2, 1]-dataMean[[1]])), df = (df0[1]+1), scale_param=FALSE ) smp1[[2]] <- rwish_chol(1, chol(priorScale[[2]] + (data$y[1, 1:2, 2]-dataMean[[2]])%*%t(data$y[1, 1:2, 2]-dataMean[[2]])), df = (df0[2]+1), scale_param=FALSE ) expect_identical(smp1[[1]], model$Sigma[1:2, 1:2, 1, 1]) expect_identical(smp1[[2]], model$Sigma[1:2, 1:2, 1, 2]) code = nimbleCode({ xi[1:5] ~ dCRP(conc=1, size=5) for(i in 1:5) { for(j in 1:2) { mu[i, j] ~ dnorm(j, var = s2[i, j]/kappa[j]) s2[i, j] ~ dinvgamma(shape=j+1, scale=j) y[i, j] ~ dnorm(mu[xi[i], j], var=s2[xi[i], j]) } } for(j in 1:2) { kappa[j] <- 2+j } }) y <- matrix(rnorm(5*2, 10, 1), ncol=2, nrow=5) y[4:5, ] <- rnorm(2*2, -10, 1) data = list(y = y) inits = list(xi = 1:5, mu=matrix(rnorm(5*2), ncol=2, nrow=5), s2=matrix(rinvgamma(5*2, 2, 1), ncol=2, nrow=5)) model = nimbleModel(code, data=data, inits=inits) mConf = configureMCMC(model, monitors = c('xi','mu', 's2')) mcmc = buildMCMC(mConf) crpIndex <- which(sapply(mConf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_conjugate_dnorm_invgamma_dnorm") pYgivenT <- sum(model$getLogProb('y[1, 1]'), model$getLogProb('y[1, 2]')) pT1 <- sum(model$getLogProb('mu[1,1]'), model$getLogProb('mu[1, 2]')) pT2 <- sum(model$getLogProb('s2[1, 1]'), model$getLogProb('s2[1, 2]')) priorMean <- c(model$getParam('mu[1, 1]', 'mean'), model$getParam('mu[1, 2]', 'mean')) kappa <- c(values(model, 's2[1, 1]')[1]/model$getParam('mu[1, 1]', 'var'), values(model, 's2[1, 2]')[1]/model$getParam('mu[1, 2]', 'var')) priorShape <- c(model$getParam('s2[1, 1]', 'shape'), model$getParam('s2[1, 2]', 'shape')) priorScale <- c(model$getParam('s2[1, 1]', 'scale'), model$getParam('s2[1, 2]', 'scale')) pTgivenY2 <- dinvgamma(model$s2[1, 1], shape = priorShape[1] + 1/2, scale = priorScale[1] + kappa[1] * (data$y[1,1] - priorMean[1])^2 / (2*(1+kappa[1])), log=TRUE) + dinvgamma(model$s2[1, 2], shape = priorShape[2] + 1/2, scale = priorScale[2] + kappa[2] * (data$y[1,2] - priorMean[2])^2 / (2*(1+kappa[2])), log=TRUE) pTgivenY1 <- dnorm(model$mu[1, 1], mean = (kappa[1] * priorMean[1] + data$y[1, 1])/(1 + kappa[1]), sd = sqrt(model$s2[1, 1] / (1+kappa[1])), log=TRUE) + dnorm(model$mu[1, 2], mean = (kappa[2] * priorMean[2] + data$y[1, 2])/(1 + kappa[2]), sd = sqrt(model$s2[1, 2] / (1+kappa[2])), log=TRUE) mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$storeParams() pY <- mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$calculate_prior_predictive(1) expect_equal(pY, pT1 + pT2 + pYgivenT - pTgivenY1 - pTgivenY2) set.seed(1) mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$sample(1, 1) set.seed(1) smp1 <- rep(0,2) smp2 <- rep(0,2) smp1[1] <- rinvgamma(1, shape = priorShape[1] + 1/2, scale = priorScale[1] + kappa[1] * (data$y[1,1] - priorMean[1])^2 / (2*(1+kappa[1]))) smp2[1] <- rnorm(1, mean = (kappa[1] * priorMean[1] + data$y[1,1])/(1 + kappa[1]), sd = sqrt(smp1[1] / (1+kappa[1]))) smp1[2] <- rinvgamma(1, shape = priorShape[2] + 1/2, scale = priorScale[2] + kappa[2] * (data$y[1,2] - priorMean[2])^2 / (2*(1+kappa[2])) ) smp2[2] <- rnorm(1, mean = (kappa[2] * priorMean[2] + data$y[1, 2])/(1 + kappa[2]), sd = sqrt(smp1[2] / (1+kappa[2]))) expect_identical(smp1, c(model$s2[1, 1], model$s2[1, 2])) expect_identical(smp2, c(model$mu[1, 1], model$mu[1, 2]) ) code = nimbleCode({ xi[1:5] ~ dCRP(conc=1, size=5) for(i in 1:5) { for(j in 1:2) { mu[i, j] ~ dnorm(j, tau = s2[i, j]*kappa[j]) s2[i, j] ~ dgamma(shape=j+1, rate=j) y[i, j] ~ dnorm(mu[xi[i], j], tau=s2[xi[i], j]) } } for(j in 1:2) { kappa[j] <- 2+j } }) y <- matrix(rnorm(5*2, 10, 1), ncol=2, nrow=5) y[4:5, ] <- rnorm(2*2, -10, 1) data = list(y = y) inits = list(xi = 1:5, mu=matrix(rnorm(5*2), ncol=2, nrow=5), s2=matrix(rgamma(5*2, 1, 2), ncol=2, nrow=5)) model = nimbleModel(code, data=data, inits=inits) mConf = configureMCMC(model, monitors = c('xi','mu', 's2')) mcmc = buildMCMC(mConf) crpIndex <- which(sapply(mConf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_conjugate_dnorm_gamma_dnorm") pYgivenT <- sum(model$getLogProb('y[1, 1]'), model$getLogProb('y[1, 2]')) pT1 <- sum(model$getLogProb('mu[1,1]'), model$getLogProb('mu[1, 2]')) pT2 <- sum(model$getLogProb('s2[1, 1]'), model$getLogProb('s2[1, 2]')) priorMean <- c(model$getParam('mu[1, 1]', 'mean'), model$getParam('mu[1, 2]', 'mean')) kappa <- c(model$getParam('mu[1, 1]', 'tau') / values(model, 's2[1, 1]')[1], model$getParam('mu[1, 2]', 'tau') / values(model, 's2[1, 2]')[1]) priorShape <- c(model$getParam('s2[1, 1]', 'shape'), model$getParam('s2[1, 2]', 'shape')) priorRate <- c(model$getParam('s2[1, 1]', 'rate'), model$getParam('s2[1, 2]', 'rate')) pTgivenY2 <- dgamma(model$s2[1, 1], shape = priorShape[1] + 1/2, rate = priorRate[1] + kappa[1] * (data$y[1,1] - priorMean[1])^2 / (2*(1+kappa[1])), log=TRUE) + dgamma(model$s2[1, 2], shape = priorShape[2] + 1/2, rate = priorRate[2] + kappa[2] * (data$y[1,2] - priorMean[2])^2 / (2*(1+kappa[2])), log=TRUE) pTgivenY1 <- dnorm(model$mu[1, 1], mean = (kappa[1] * priorMean[1] + data$y[1, 1])/(1 + kappa[1]), sd = sqrt(1/(model$s2[1, 1] *(1+kappa[1]))), log=TRUE) + dnorm(model$mu[1, 2], mean = (kappa[2] * priorMean[2] + data$y[1, 2])/(1 + kappa[2]), sd = sqrt(1/(model$s2[1, 2] *(1+kappa[2]))), log=TRUE) mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$storeParams() pY <- mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$calculate_prior_predictive(1) expect_equal(pY, pT1 + pT2 + pYgivenT - pTgivenY1 - pTgivenY2) set.seed(1) mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$sample(1, 1) set.seed(1) smp1 <- rep(0,2) smp2 <- rep(0,2) smp1[1] <- rgamma(1, shape = priorShape[1] + 1/2, rate = priorRate[1] + kappa[1] * (data$y[1,1] - priorMean[1])^2 / (2*(1+kappa[1]))) smp2[1] <- rnorm(1, mean = (kappa[1] * priorMean[1] + data$y[1,1])/(1 + kappa[1]), sd = sqrt(1 / (smp1[1]*(1+kappa[1])))) smp1[2] <- rgamma(1, shape = priorShape[2] + 1/2, rate = priorRate[2] + kappa[2] * (data$y[1,2] - priorMean[2])^2 / (2*(1+kappa[2])) ) smp2[2] <- rnorm(1, mean = (kappa[2] * priorMean[2] + data$y[1, 2])/(1 + kappa[2]), sd = sqrt(1 / (smp1[2]*(1+kappa[2])))) expect_identical(smp1, c(model$s2[1, 1], model$s2[1, 2])) expect_identical(smp2, c(model$mu[1, 1], model$mu[1, 2]) ) code <- nimbleCode({ xi[1:5] ~ dCRP(conc = 1, size = 5) for(i in 1:5){ for(j in 1:2) { Sigma[1:2, 1:2, i, j] ~ dinvwish(S = R0[1:2, 1:2, j], df = v0[j]) SigmaAux[1:2, 1:2, i, j] <- Sigma[1:2, 1:2, i, j] / k0[j] mu[i, 1:2, j] ~ dmnorm(mu0[1:2, j], cov = SigmaAux[1:2, 1:2, i, j] ) y[i, 1:2, j] ~ dmnorm(mu[xi[i], 1:2, j], cov = Sigma[1:2, 1:2, xi[i], j] ) } } }) R0 <- array(0, c(2, 2, 2)) for(j in 1:2) { R0[, , j] <- rinvwish_chol(1, chol(matrix(c(10, .7, .7, 10), 2)), 2) } Sigma <- array(0, c(2,2,5, 2)) for(i in 1:5){ for(j in 1:2) { Sigma[, , i, j] <- rinvwish_chol(1, chol(matrix(c(1, .5, .5, 1), 2)), 2) } } mu <- array(0, c(5, 2, 2)) for(j in 1:2) { mu[ , ,j] <- matrix(rnorm(5*2, 0, sqrt(0.01)), nrow=5, ncol=2) } y <- array(0, c(5, 2, 2)) for(i in 1:5) { for(j in 1:2) { y[i, ,j] <- rnorm(2, 0, sqrt(0.01)) } } data = list(y = y) inits = list(xi = 1:5, mu = mu, Sigma = Sigma) Consts <- list(mu0 = matrix(rnorm(4), ncol=2, nrow=2), v0 = rpois(2, 5), k0 = rgamma(2, 1, 1), R0 = R0) model = nimbleModel(code, data=data, inits=inits, constants = Consts) mConf = configureMCMC(model, monitors = c('xi','mu', 'Sigma')) mcmc = buildMCMC(mConf) crpIndex <- which(sapply(mConf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_conjugate_dmnorm_invwish_dmnorm") pYgivenT <- sum(model$getLogProb('y[1, 1:2, 1]'), model$getLogProb('y[1, 1:2, 2]')) pT1 <- sum(model$getLogProb('mu[1,1:2, 1]'), model$getLogProb('mu[1, 1:2, 2]')) pT2 <- sum(model$getLogProb('Sigma[1:2, 1:2, 1, 1]'), model$getLogProb('Sigma[1:2, 1:2, 1, 2]')) priorMean <- list(model$getParam('mu[1, 1:2, 1]', 'mean'), model$getParam('mu[1, 1:2, 2]', 'mean')) kappa <- c(values(model, 'Sigma[1:2, 1:2, 1, 1]')[1]/model$getParam('mu[1, 1:2, 1]', 'cov')[1, 1], values(model, 'Sigma[1:2, 1:2, 1, 2]')[1]/model$getParam('mu[1, 1:2, 2]', 'cov')[1, 1]) df0 <- c(model$getParam('Sigma[1:2, 1:2, 1, 1]', 'df'), model$getParam('Sigma[1:2, 1:2, 1, 2]', 'df')) priorScale <- list(model$getParam('Sigma[1:2, 1:2, 1, 1]', 'S'), model$getParam('Sigma[1:2, 1:2, 1, 2]', 'S')) pTgivenY2 <- dinvwish_chol(model$Sigma[1:2, 1:2, 1, 1], chol(priorScale[[1]] + (kappa[1]/(kappa[1]+1)) * (data$y[1, 1:2, 1]-priorMean[[1]])%*%t(data$y[1, 1:2, 1]-priorMean[[1]])), df = (df0[1]+1), scale_param=TRUE, log = TRUE) + dinvwish_chol(model$Sigma[1:2, 1:2, 1, 2], chol(priorScale[[2]] + (kappa[2]/(kappa[2]+1)) * (data$y[1, 1:2, 2]-priorMean[[2]])%*%t(data$y[1, 1:2, 2]-priorMean[[2]])), df = (df0[2]+1), scale_param=TRUE, log = TRUE) pTgivenY1 <- dmnorm_chol(model$mu[1, 1:2, 1], mean = (kappa[1] * priorMean[[1]] + data$y[1, 1:2, 1])/(1 + kappa[1]), chol( model$Sigma[1:2, 1:2, 1, 1] / (1+kappa[1]) ), prec_param = FALSE, log = TRUE) + dmnorm_chol(model$mu[1, 1:2, 2], mean = (kappa[2] * priorMean[[2]] + data$y[1, 1:2, 2])/(1 + kappa[2]), chol( model$Sigma[1:2, 1:2, 1, 2] / (1+kappa[2]) ), prec_param = FALSE, log = TRUE) mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$storeParams() pY <- mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$calculate_prior_predictive(1)[1] expect_equal(pY, pT1 + pT2 + pYgivenT - pTgivenY1 - pTgivenY2) set.seed(1) mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$sample(1, 1) set.seed(1) smp1 <- list() smp2 <- list() smp1[[1]] <- rinvwish_chol(1, chol(priorScale[[1]] + (kappa[1]/(kappa[1]+1)) * (data$y[1, 1:2, 1]-priorMean[[1]])%*%t(data$y[1, 1:2, 1]-priorMean[[1]])), df = (df0[1]+1), scale_param=TRUE ) smp2[[1]] <- rmnorm_chol(1, mean = (kappa[1] * priorMean[[1]] + data$y[1, 1:2, 1])/(1 + kappa[1]), chol( smp1[[1]] / (1+kappa[1]) ), prec_param = FALSE) smp1[[2]] <- rinvwish_chol(1, chol(priorScale[[2]] + (kappa[2]/(kappa[2]+1)) * (data$y[1, 1:2, 2]-priorMean[[2]])%*%t(data$y[1, 1:2, 2]-priorMean[[2]])), df = (df0[2]+1), scale_param=TRUE ) smp2[[2]] <- rmnorm_chol(1, mean = (kappa[2] * priorMean[[2]] + data$y[1, 1:2, 2])/(1 + kappa[2]), chol( smp1[[2]] / (1+kappa[2]) ), prec_param = FALSE) expect_identical(smp1[[1]], model$Sigma[1:2, 1:2, 1, 1]) expect_identical(smp1[[2]], model$Sigma[1:2, 1:2, 1, 2]) expect_identical(smp2[[1]], model$mu[1, 1:2, 1]) expect_identical(smp2[[2]], model$mu[1, 1:2, 2]) code <- nimbleCode({ xi[1:5] ~ dCRP(conc = 1, size = 5) for(i in 1:5){ for(j in 1:2) { Sigma[1:2, 1:2, i, j] ~ dwish(R = R0[1:2, 1:2, j], df = v0[j]) SigmaAux[1:2, 1:2, i, j] <- Sigma[1:2, 1:2, i, j] * k0[j] mu[i, 1:2, j] ~ dmnorm(mu0[1:2, j], prec = SigmaAux[1:2, 1:2, i, j] ) y[i, 1:2, j] ~ dmnorm(mu[xi[i], 1:2, j], prec = Sigma[1:2, 1:2, xi[i], j] ) } } }) R0 <- array(0, c(2, 2, 2)) for(j in 1:2) { R0[, , j] <- rwish_chol(1, chol(matrix(c(10, .7, .7, 10), 2)), 2) } Sigma <- array(0, c(2,2,5, 2)) for(i in 1:5){ for(j in 1:2) { Sigma[, , i, j] <- rwish_chol(1, chol(matrix(c(1, .5, .5, 1), 2)), 2) } } mu <- array(0, c(5, 2, 2)) for(j in 1:2) { mu[ , ,j] <- matrix(rnorm(5*2, 0, sqrt(0.01)), nrow=5, ncol=2) } y <- array(0, c(5, 2, 2)) for(i in 1:5) { for(j in 1:2) { y[i, ,j] <- rnorm(2, 0, sqrt(0.01)) } } data = list(y = y) inits = list(xi = 1:5, mu = mu, Sigma = Sigma) Consts <- list(mu0 = matrix(rnorm(4), ncol=2, nrow=2), v0 = rpois(2, 5), k0 = rgamma(2, 1, 1), R0 = R0) model = nimbleModel(code, data=data, inits=inits, constants = Consts) mConf = configureMCMC(model, monitors = c('xi','mu', 'Sigma')) mcmc = buildMCMC(mConf) crpIndex <- which(sapply(mConf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_conjugate_dmnorm_wish_dmnorm") pYgivenT <- sum(model$getLogProb('y[1, 1:2, 1]'), model$getLogProb('y[1, 1:2, 2]')) pT1 <- sum(model$getLogProb('mu[1,1:2, 1]'), model$getLogProb('mu[1, 1:2, 2]')) pT2 <- sum(model$getLogProb('Sigma[1:2, 1:2, 1, 1]'), model$getLogProb('Sigma[1:2, 1:2, 1, 2]')) priorMean <- list(model$getParam('mu[1, 1:2, 1]', 'mean'), model$getParam('mu[1, 1:2, 2]', 'mean')) kappa <- c(model$getParam('mu[1, 1:2, 1]', 'prec')[1, 1]/values(model, 'Sigma[1:2, 1:2, 1, 1]')[1], model$getParam('mu[1, 1:2, 2]', 'prec')[1, 1]/values(model, 'Sigma[1:2, 1:2, 1, 2]')[1]) df0 <- c(model$getParam('Sigma[1:2, 1:2, 1, 1]', 'df'), model$getParam('Sigma[1:2, 1:2, 1, 2]', 'df')) priorRate <- list(model$getParam('Sigma[1:2, 1:2, 1, 1]', 'R'), model$getParam('Sigma[1:2, 1:2, 1, 2]', 'R')) pTgivenY2 <- dwish_chol(model$Sigma[1:2, 1:2, 1, 1], chol(priorRate[[1]] + (kappa[1]/(kappa[1]+1)) * (data$y[1, 1:2, 1]-priorMean[[1]])%*%t(data$y[1, 1:2, 1]-priorMean[[1]])), df = (df0[1]+1), scale_param=FALSE, log = TRUE) + dwish_chol(model$Sigma[1:2, 1:2, 1, 2], chol(priorRate[[2]] + (kappa[2]/(kappa[2]+1)) * (data$y[1, 1:2, 2]-priorMean[[2]])%*%t(data$y[1, 1:2, 2]-priorMean[[2]])), df = (df0[2]+1), scale_param=FALSE, log = TRUE) pTgivenY1 <- dmnorm_chol(model$mu[1, 1:2, 1], mean = (kappa[1] * priorMean[[1]] + data$y[1, 1:2, 1])/(1 + kappa[1]), chol( model$Sigma[1:2, 1:2, 1, 1] * (1+kappa[1]) ), prec_param = TRUE, log = TRUE) + dmnorm_chol(model$mu[1, 1:2, 2], mean = (kappa[2] * priorMean[[2]] + data$y[1, 1:2, 2])/(1 + kappa[2]), chol( model$Sigma[1:2, 1:2, 1, 2] * (1+kappa[2]) ), prec_param = TRUE, log = TRUE) mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$storeParams() pY <- mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$calculate_prior_predictive(1)[1] expect_equal(pY, pT1 + pT2 + pYgivenT - pTgivenY1 - pTgivenY2) set.seed(1) mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$sample(1, 1) set.seed(1) smp1 <- list() smp2 <- list() smp1[[1]] <- rwish_chol(1, chol(priorRate[[1]] + (kappa[1]/(kappa[1]+1)) * (data$y[1, 1:2, 1]-priorMean[[1]])%*%t(data$y[1, 1:2, 1]-priorMean[[1]])), df = (df0[1]+1), scale_param=FALSE ) smp2[[1]] <- rmnorm_chol(1, mean = (kappa[1] * priorMean[[1]] + data$y[1, 1:2, 1])/(1 + kappa[1]), chol( smp1[[1]] * (1+kappa[1]) ), prec_param = TRUE) smp1[[2]] <- rwish_chol(1, chol(priorRate[[2]] + (kappa[2]/(kappa[2]+1)) * (data$y[1, 1:2, 2]-priorMean[[2]])%*%t(data$y[1, 1:2, 2]-priorMean[[2]])), df = (df0[2]+1), scale_param=FALSE ) smp2[[2]] <- rmnorm_chol(1, mean = (kappa[2] * priorMean[[2]] + data$y[1, 1:2, 2])/(1 + kappa[2]), chol( smp1[[2]] * (1+kappa[2]) ), prec_param = TRUE) expect_identical(smp1[[1]], model$Sigma[1:2, 1:2, 1, 1]) expect_identical(smp1[[2]], model$Sigma[1:2, 1:2, 1, 2]) expect_identical(smp2[[1]], model$mu[1, 1:2, 1]) expect_identical(smp2[[2]], model$mu[1, 1:2, 2]) code <- nimbleCode({ for(i in 1:5) { for(j in 1:2) { y[i,j] ~ dnorm( mu[i, j] , tau = s2[xi[i], j]) s2[i, j] ~ dgamma(shape = j, rate = j+1) } } xi[1:5] ~ dCRP(1, size=5) }) inits <- list(xi = 1:5, mu = matrix(rnorm(5*2, 0), nrow=5, ncol=2), s2 = matrix(rgamma(5*2, 0.1, rate=1), nrow=5, ncol=2)) y <- matrix(rnorm(5*2, 10, 1), ncol=2, nrow=5) data <- list(y=y) model <- nimbleModel(code, data=data, inits=inits, dimensions=list(mu=c(5,2)), calculate=TRUE) mConf <- configureMCMC(model, monitors = c('xi','s2')) mcmc <- buildMCMC(mConf) crpIndex <- which(sapply(mConf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_conjugate_dgamma_dnorm") pYgivenT <- sum(c(model$getLogProb('y[1, 1]'), model$getLogProb('y[1, 2]'))) pT <- sum(c(model$getLogProb('s2[1, 1]'), model$getLogProb('s2[1, 2]'))) dataMean <- c(model$getParam('y[1,1]', 'mean') , model$getParam('y[1,2]', 'mean') ) priorShape <- c(model$getParam('s2[1, 1]', 'shape'), model$getParam('s2[1, 2]', 'shape')) priorRate <- c(model$getParam('s2[1, 1]', 'rate') , model$getParam('s2[1, 2]', 'rate')) postShape <- priorShape + 0.5 postRate <- priorRate + 0.5 * (c(data$y[1, 1], data$y[1, 2]) - dataMean)^2 pTgivenY <- dgamma(model$s2[1, 1] , shape = postShape[1], rate = postRate[1], log = TRUE) + dgamma(model$s2[1, 2] , shape = postShape[2], rate = postRate[2], log = TRUE) mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$storeParams() pY <- mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$calculate_prior_predictive(1) expect_equal(pY, pT + pYgivenT - pTgivenY) set.seed(1) mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$sample(1, 1) set.seed(1) smp <- rgamma(2 , shape = postShape, rate = postRate) expect_identical(smp, c(model$s2[1, 1], model$s2[1, 2])) code = nimbleCode({ for(i in 1:5) { for(j in 1:2) { mu[i, j] ~ dbeta(1+j,j) y[i, j] ~ dbern(mu[xi[i], j]) } } xi[1:5] ~ dCRP(conc=1, size=5) }) y = matrix(rbinom(10, size=1, prob=0.1), ncol=2, nrow=5) y[4:5, ] <- rbinom(4, size=1, prob=0.9) data = list(y=y) inits = list(xi = 1:5, mu=matrix(rbeta(10, 1, 1), ncol=2, nrow=5)) m = nimbleModel(code, data=data, inits = inits) mConf = configureMCMC(m, monitors = c('xi','mu')) mcmc = buildMCMC(mConf) crpIndex <- which(sapply(mConf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_conjugate_dbeta_dbern") pYgivenT <- sum(m$getLogProb('y[1, 1]'), m$getLogProb('y[1, 2]')) pT <- sum(m$getLogProb('mu[1, 1]'), m$getLogProb('mu[1, 2]')) priorShape1 <- c(m$getParam('mu[1, 1]', 'shape1'), m$getParam('mu[1, 2]', 'shape1')) priorShape2 <- c(m$getParam('mu[1, 1]', 'shape2'), m$getParam('mu[1, 2]', 'shape2')) pTgivenY <- dbeta(m$mu[1, 1], shape1=priorShape1[1]+data$y[1, 1], shape2=priorShape2[1]+1-data$y[1, 1], log=TRUE) + dbeta(m$mu[1, 2], shape1=priorShape1[2]+data$y[1, 2], shape2=priorShape2[2]+1-data$y[1, 2], log=TRUE) mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$storeParams() pY <- mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$calculate_prior_predictive(1) expect_equal(pY, pT + pYgivenT - pTgivenY) set.seed(1) mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$sample(1, 1) set.seed(1) smp <- c(rbeta(1 , shape1=priorShape1[1]+data$y[1, 1], shape2=priorShape2[1]+1-data$y[1, 1]), rbeta(1 , shape1=priorShape1[2]+data$y[1, 2], shape2=priorShape2[2]+1-data$y[1, 2]) ) expect_identical(smp, c(m$mu[1, 1], m$mu[1, 2])) code = nimbleCode({ for(i in 1:5) { for(j in 1:2) { mu[i, j] ~ dbeta(j,5+j) y[i, j] ~ dbinom(size=10, prob=mu[xi[i], j]) } } xi[1:5] ~ dCRP(conc=1, size=5) }) y = matrix(rbinom(10, size=10, prob=0.1), ncol=2, nrow=5) data = list(y=y) inits = list(xi = 1:5, mu=matrix(rbeta(10, 1, 1), ncol=2, nrow=5)) m = nimbleModel(code, data=data, inits = inits) mConf = configureMCMC(m, monitors = c('xi','mu')) mcmc = buildMCMC(mConf) crpIndex <- which(sapply(mConf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_conjugate_dbeta_dbin") pYgivenT <- sum(m$getLogProb('y[1, 1]'), m$getLogProb('y[1, 2]')) pT <- sum(m$getLogProb('mu[1, 1]'), m$getLogProb('mu[1, 2]')) priorShape1 <- c(m$getParam('mu[1, 1]', 'shape1'), m$getParam('mu[1, 2]', 'shape1')) priorShape2 <- c(m$getParam('mu[1, 1]', 'shape2'), m$getParam('mu[1, 2]', 'shape2')) dataSize <- c(m$getParam('y[1, 1]', 'size'), m$getParam('y[1, 2]', 'size')) pTgivenY <- dbeta(m$mu[1, 1], shape1=priorShape1[1]+data$y[1, 1], shape2=priorShape2[1]+dataSize[1]-data$y[1, 1], log=TRUE)+ dbeta(m$mu[1, 2], shape1=priorShape1[2]+data$y[1, 2], shape2=priorShape2[2]+dataSize[2]-data$y[1, 2], log=TRUE) mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$storeParams() pY <- mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$calculate_prior_predictive(1) expect_equal(pY, pT + pYgivenT - pTgivenY) set.seed(1) mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$sample(1, 1) set.seed(1) smp <- c(rbeta(1 , shape1=priorShape1[1]+data$y[1, 1], shape2=priorShape2[1]+dataSize[1]-data$y[1, 1]), rbeta(1 , shape1=priorShape1[2]+data$y[1, 2], shape2=priorShape2[2]+dataSize[2]-data$y[1, 2]) ) expect_identical(smp, c(m$mu[1, 1], m$mu[1, 2])) code = nimbleCode({ for(i in 1:5) { for(j in 1:2) { mu[i, j] ~ dbeta(j,j+1) y[i, j] ~ dnegbin(size=10, prob=mu[xi[i], j]) } } xi[1:5] ~ dCRP(conc=1, size=5) }) y = matrix(rnbinom(10, size=10, prob=0.1), ncol=2, nrow=5) data = list(y=y) inits = list(xi = 1:5, mu=matrix(rbeta(10, 1, 1), ncol=2, nrow=5)) m = nimbleModel(code, data=data, inits= inits) mConf = configureMCMC(m, monitors = c('xi','mu')) mcmc = buildMCMC(mConf) crpIndex <- which(sapply(mConf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_conjugate_dbeta_dnegbin") pYgivenT <- sum(m$getLogProb('y[1, 1]'), m$getLogProb('y[1, 2]')) pT <- sum(m$getLogProb('mu[1, 1]'), m$getLogProb('mu[1, 2]')) priorShape1 <- c(m$getParam('mu[1, 1]', 'shape1'), m$getParam('mu[1, 2]', 'shape1')) priorShape2 <- c(m$getParam('mu[1, 1]', 'shape2'), m$getParam('mu[1, 2]', 'shape2')) dataSize <- c(m$getParam('y[1, 1]', 'size'), m$getParam('y[1, 2]', 'size')) pTgivenY <- dbeta(m$mu[1, 1], shape1=priorShape1[1]+dataSize[1], shape2=priorShape2[1]+data$y[1, 1], log=TRUE) + dbeta(m$mu[1, 2], shape1=priorShape1[2]+dataSize[2], shape2=priorShape2[2]+data$y[1, 2], log=TRUE) mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$storeParams() pY <- mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$calculate_prior_predictive(1) expect_equal(pY, pT + pYgivenT - pTgivenY) set.seed(1) mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$sample(1, 1) set.seed(1) smp <- c(rbeta(1 , shape1=priorShape1[1]+dataSize[1], shape2=priorShape2[1]+data$y[1, 1]), rbeta(1 , shape1=priorShape1[2]+dataSize[2], shape2=priorShape2[2]+data$y[1, 2])) expect_identical(smp, c(m$mu[1, 1], m$mu[1, 2]) ) code = nimbleCode({ for(i in 1:5) { for(j in 1:2) { mu[i, j] ~ dgamma(j,j+1) y[i, j] ~ dpois(mu[xi[i], j]) } } xi[1:5] ~ dCRP(conc=1, size=5) }) y = matrix(rpois(10, 1), ncol=2, nrow=5) data = list(y=y) inits = list(xi = 1:5, mu=matrix(rgamma(10, 1, 5), ncol=2, nrow=5)) m = nimbleModel(code, data=data, inits= inits) cm<-compileNimble(m) mConf = configureMCMC(m, monitors=c('mu', 'xi')) mcmc = buildMCMC(mConf) crpIndex <- which(sapply(mConf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_conjugate_dgamma_dpois") pYgivenT <- sum(m$getLogProb('y[1, 1]'), m$getLogProb('y[1, 2]')) pT <- sum(m$getLogProb('mu[1, 1]'), m$getLogProb('mu[1, 2]')) priorShape <- c(m$getParam('mu[1, 1]', 'shape'), m$getParam('mu[1, 2]', 'shape')) priorRate <- c(m$getParam('mu[1, 1]', 'rate'), m$getParam('mu[1, 2]', 'rate')) pTgivenY <- dgamma(m$mu[1, 1], shape = priorShape[1] + data$y[1, 1], rate = priorRate[1] + 1, log=TRUE) + dgamma(m$mu[1, 2], shape = priorShape[2] + data$y[1, 2], rate = priorRate[2] + 1, log=TRUE) mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$storeParams() pY <- mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$calculate_prior_predictive(1) expect_equal(pY, pT + pYgivenT - pTgivenY) set.seed(1) mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$sample(1, 1) set.seed(1) smp <- c(rgamma(1 , shape = priorShape[1] + data$y[1, 1], rate = priorRate[1] + 1), rgamma(1 , shape = priorShape[2] + data$y[1, 2], rate = priorRate[2] + 1)) expect_identical(smp, c(m$mu[1, 1], m$mu[1, 2])) code = nimbleCode({ for(i in 1:5) { for(j in 1:2) { mu[i, j] ~ dgamma(j,j+1) y[i, j] ~ dexp(mu[xi[i], j]) } } xi[1:5] ~ dCRP(conc=1, size=5) }) y = matrix(rexp(10, 1), ncol=2, nrow=5) data = list(y=y) inits = list(xi = 1:5, mu=matrix(rgamma(10, 1, 1), ncol=2, nrow=5)) m = nimbleModel(code, data=data, inits= inits) mConf = configureMCMC(m, monitors = c('xi','mu')) mcmc = buildMCMC(mConf) crpIndex <- which(sapply(mConf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_conjugate_dgamma_dexp") pYgivenT <- sum(m$getLogProb('y[1, 1]'),m$getLogProb('y[1, 2]')) pT <- sum(m$getLogProb('mu[1, 1]'), m$getLogProb('mu[1, 2]')) priorShape <- c(m$getParam('mu[1, 1]', 'shape'), m$getParam('mu[1, 2]', 'shape')) priorRate <- c(m$getParam('mu[1, 1]', 'rate'), m$getParam('mu[1, 2]', 'rate')) pTgivenY <- dgamma(m$mu[1,1], shape=priorShape[1]+1, rate=priorRate[1]+data$y[1, 1], log=TRUE)+ dgamma(m$mu[1, 2], shape=priorShape[2]+1, rate=priorRate[2]+data$y[1, 2], log=TRUE) mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$storeParams() pY <- mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$calculate_prior_predictive(1) expect_equal(pY, pT + pYgivenT - pTgivenY) set.seed(1) mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$sample(1, 1) set.seed(1) smp <- c(rgamma(1, shape=priorShape[1]+1, rate=priorRate[1]+data$y[1, 1]), rgamma(1, shape=priorShape[2]+1, rate=priorRate[2]+data$y[1, 2])) expect_identical(smp, c(m$mu[1, 1], m$mu[1, 2])) code = nimbleCode({ for(i in 1:5) { for(j in 1:2) { mu[i, j] ~ dgamma(j, rate = j+1) y[i, j] ~ dgamma(4, rate = mu[xi[i], j]) } } xi[1:5] ~ dCRP(conc=1, size=5) }) y = matrix(rgamma(10, 4, 4), ncol=2, nrow=5) data = list(y = y) inits = list(xi = 1:5, mu=matrix(rgamma(10, 1, 5), ncol=2, nrow=5)) m = nimbleModel(code, data=data, inits= inits) mConf = configureMCMC(m, monitors = c('xi','mu')) mcmc = buildMCMC(mConf) crpIndex <- which(sapply(mConf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_conjugate_dgamma_dgamma") pYgivenT <- sum(m$getLogProb('y[1, 1]'), m$getLogProb('y[1, 2]')) pT <- sum(m$getLogProb('mu[1, 1]'), m$getLogProb('mu[1, 2]')) priorShape <- c(m$getParam('mu[1, 1]', 'shape'), m$getParam('mu[1, 2]', 'shape')) priorRate <- c(m$getParam('mu[1, 1]', 'rate'), m$getParam('mu[1, 2]', 'rate')) dataShape <- c(m$getParam('y[1, 1]', 'shape'), m$getParam('y[1, 2]', 'shape')) pTgivenY <- dgamma(m$mu[1, 1], shape=dataShape[1]+priorShape[1], rate=priorRate[1]+data$y[1, 1], log=TRUE) + dgamma(m$mu[1, 2], shape=dataShape[2]+priorShape[2], rate=priorRate[2]+data$y[1, 2], log=TRUE) mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$storeParams() pY <- mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$calculate_prior_predictive(1) expect_equal(pY, pT + pYgivenT - pTgivenY) set.seed(1) mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$sample(1, 1) set.seed(1) smp <- c(rgamma(1, shape=dataShape[1]+priorShape[1], rate=priorRate[1]+data$y[1, 1]), rgamma(1, shape=dataShape[2]+priorShape[2], rate=priorRate[2]+data$y[1, 2])) expect_identical(smp, c(m$mu[1, 1], m$mu[1, 2])) code = nimbleCode({ for(i in 1:5) { for(j in 1:2) { mu[i, j] ~ dgamma(j, 5+j) y[i, j] ~ dweib(shape=4*j, lambda = mu[xi[i], j]) } } xi[1:5] ~ dCRP(conc=1, size=5) }) y <- matrix(rweibull(10, 4, 4), ncol=2, nrow=5) data = list(y = y) inits = list(xi = 1:5, mu=matrix(rgamma(10, 1, 5), ncol=2, nrow=5)) m = nimbleModel(code, data=data, inits= inits) mConf = configureMCMC(m, monitors=list('xi', 'mu')) mcmc = buildMCMC(mConf) crpIndex <- which(sapply(mConf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_conjugate_dgamma_dweib") pYgivenT <- sum(m$getLogProb('y[1, 1]'), m$getLogProb('y[1, 2]')) pT <- sum(m$getLogProb('mu[1, 1]'), m$getLogProb('mu[1, 2]')) priorShape <- c(m$getParam('mu[1, 1]', 'shape'), m$getParam('mu[1, 2]', 'shape')) priorRate <- c(m$getParam('mu[1, 1]', 'rate'), m$getParam('mu[1, 2]', 'rate')) dataShape <- c(m$getParam('y[1, 1]', 'shape'), m$getParam('y[1, 2]', 'shape')) pTgivenY <- dgamma(m$mu[1, 1], shape=1+priorShape[1], rate=priorRate[1]+data$y[1,1]^dataShape[1], log=TRUE) + dgamma(m$mu[1, 2], shape=1+priorShape[2], rate=priorRate[2]+data$y[1, 2]^dataShape[2], log=TRUE) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$storeParams() pY <- mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$calculate_prior_predictive(1) expect_equal(pY, pT + pYgivenT - pTgivenY) set.seed(1) mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$sample(1, 1) set.seed(1) smp <- c(rgamma(1, shape=1+priorShape[1], rate=priorRate[1]+data$y[1, 1]^dataShape[1]), rgamma(1, shape=1+priorShape[2], rate=priorRate[2]+data$y[1, 2]^dataShape[2])) expect_identical(smp, c(m$mu[1, 1], m$mu[1, 2])) code = nimbleCode({ for(i in 1:5) { for(j in 1:2) { mu[i, j] ~ dgamma(j, rate=5+j) y[i, j] ~ dinvgamma(shape=4*j, scale = mu[xi[i], j]) } } xi[1:5] ~ dCRP(conc=1, size=5) }) y <- matrix(rinvgamma(10, 4, 3), ncol=2, nrow=5) data = list(y = y) inits = list(xi = 1:5, mu=matrix(rgamma(10, 1, 5), ncol=2, nrow=5)) m = nimbleModel(code, data=data, inits= inits) mConf = configureMCMC(m, monitors = list('xi', 'mu')) mcmc = buildMCMC(mConf) crpIndex <- which(sapply(mConf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_conjugate_dgamma_dinvgamma") pYgivenT <- sum(m$getLogProb('y[1, 1]'), m$getLogProb('y[1, 2]')) pT <- sum(m$getLogProb('mu[1, 1]'), m$getLogProb('mu[1, 2]')) priorShape <- c(m$getParam('mu[1, 1]', 'shape'), m$getParam('mu[1, 2]', 'shape')) priorRate <- c(m$getParam('mu[1, 1]', 'rate'), m$getParam('mu[1, 2]', 'rate')) dataShape <- c(m$getParam('y[1, 1]', 'shape'), m$getParam('y[1, 2]', 'shape')) pTgivenY <- dgamma(m$mu[1, 1], shape=dataShape[1]+priorShape[1], rate=priorRate[1]+1/data$y[1, 1], log=TRUE)+ dgamma(m$mu[1, 2], shape=dataShape[2]+priorShape[2], rate=priorRate[2]+1/data$y[1, 2], log=TRUE) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$storeParams() pY <- mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$calculate_prior_predictive(1) expect_equal(pY, pT + pYgivenT - pTgivenY) set.seed(1) mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$sample(1, 1) set.seed(1) smp <- c(rgamma(1, shape=dataShape[1]+priorShape[1], rate=priorRate[1]+1/data$y[1, 1]), rgamma(1, shape=dataShape[2]+priorShape[2], rate=priorRate[2]+1/data$y[1, 2])) expect_identical(smp, c(m$mu[1, 1], m$mu[1, 2])) code=nimbleCode( { for(i in 1:5){ for(j in 1:2) { p[i, 1:3, j] ~ ddirch(alpha=alpha0[1:3, j]) y[i, 1:3, j] ~ dmulti(prob=p[xi[i], 1:3, j], size=3) } } xi[1:5] ~ dCRP(conc=1, size=5) } ) alpha0 <- matrix(rgamma(3*2, 1, 1), ncol=2, nrow=3) p <- array(0, c(5, 3, 2)) for(i in 1:5) { for(j in 1:2) { p[i, , j] <- rdirch(1, c(1, 1, 1)) } } y <- array(0, c(5, 3, 2)) for(i in 1:5){ for(j in 1:2) { y[i, , j] = rmulti(1, prob=c(0.01,0.01,0.98), size=3) } } data = list(y = y) m = nimbleModel(code, data = data, inits = list(xi = 1:5, p=p), constants=list(alpha0 = alpha0)) mConf = configureMCMC(m, monitors = list('xi', 'p')) mcmc = buildMCMC(mConf) crpIndex <- which(sapply(mConf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_conjugate_ddirch_dmulti") pYgivenT <- sum(m$getLogProb('y[1, 1:3, 1]'), m$getLogProb('y[1, 1:3, 2]')) pT <- sum(m$getLogProb('p[1, 1:3, 1]'), m$getLogProb('p[1, 1:3, 2]')) priorAlpha <- list(m$getParam('p[1, 1:3, 1]', 'alpha'), m$getParam('p[1, 1:3, 2]', 'alpha')) pTgivenY <- ddirch(m$p[1,1:3, 1], alpha = priorAlpha[[1]]+data$y[1, 1:3, 1], log=TRUE) + ddirch(m$p[1,1:3, 2], alpha = priorAlpha[[2]]+data$y[1, 1:3, 2], log=TRUE) mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$storeParams() pY <- mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$calculate_prior_predictive(1) expect_equal(pY, pT + pYgivenT - pTgivenY) set.seed(1) mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]]$sample(1, 1) set.seed(1) smp <- list(rdirch(1, alpha = priorAlpha[[1]]+data$y[1, 1:3, 1]), rdirch(1, alpha = priorAlpha[[2]]+data$y[1, 1:3, 2])) expect_identical(smp[[1]], m$p[1, 1:3, 1]) expect_identical(smp[[2]], m$p[1, 1:3, 2]) } ) test_that("sampleDPmeasure: testing that required variables in MCMC modelValues are monitored", { set.seed(1) code <- nimbleCode({ xi[1:6] ~ dCRP(conc0, 6) conc0 ~ dgamma(1, 1) for(i in 1:6){ mu[i] ~ dnorm(0, 1) y[i] ~ dnorm(mu[xi[i]], 1) } }) Inits <- list(xi = c(1,1,2,1,1,2), mu = 1:6, conc0 = 1) Data <- list( y = rnorm(6)) m <- nimbleModel(code, data=Data, inits=Inits) mConf <- configureMCMC(m) mMCMC <- buildMCMC(mConf) expect_error(getSamplesDPmeasure(mMCMC), 'sampleDPmeasure: The node having the dCRP distribution') mConf <- configureMCMC(m, monitors = c('xi', 'conc0', 'mu')) mMCMC <- buildMCMC(mConf) expect_message(output <- runMCMC(mMCMC, niter=1)) expect_silent(output <- getSamplesDPmeasure(mMCMC)) code <- nimbleCode({ xi[1:6] ~ dCRP(1, 6) mu0 ~ dnorm(0, 1) s20 ~ dgamma(1, 1) for(i in 1:6){ mu[i] ~ dnorm(mu0, s20) y[i] ~ dnorm(mu[xi[i]], 1) } }) Inits <- list(xi = c(1,1,2,1,1,2), mu = 1:6, mu0 = 0, s20 = 1) Data <- list( y = rnorm(6)) m <- nimbleModel(code, data=Data, inits=Inits) mConf <- configureMCMC(m) mMCMC <- buildMCMC(mConf) expect_error(getSamplesDPmeasure(mMCMC), 'sampleDPmeasure: The node\\(s\\) representing the cluster variables') mConf <- configureMCMC(m, monitors = c('mu', 'xi')) mMCMC <- buildMCMC(mConf) expect_error(getSamplesDPmeasure(mMCMC), 'sampleDPmeasure: The stochastic parent nodes') mConf <- configureMCMC(m, monitors = c('mu', 'xi', 'mu0', 's20')) mMCMC <- buildMCMC(mConf) expect_message(output <- runMCMC(mMCMC, niter=1)) expect_silent(output <- getSamplesDPmeasure(mMCMC)) code <- nimbleCode({ xi[1:6] ~ dCRP(conc0, 6) conc0 ~ dgamma(a, rate=b) a ~ dgamma(1, rate=1) b ~ dgamma(1, rate=0.1) for(i in 1:6){ mu[i] ~ dnorm(0, 1) y[i] ~ dnorm(mu[xi[i]], 1) } }) Inits <- list(xi = c(1,1,2,1,1,2), mu = 1:6, conc0 = 1, a = 1, b = 1) Data <- list( y = rnorm(6)) m <- nimbleModel(code, data=Data, inits=Inits) mConf <- configureMCMC(m, monitors = c('xi', 'mu')) mMCMC <- buildMCMC(mConf) expect_error(getSamplesDPmeasure(mMCMC), 'sampleDPmeasure: The stochastic parent nodes of the membership') mConf <- configureMCMC(m, monitors = c('xi', 'mu', 'conc0')) mMCMC <- buildMCMC(mConf) expect_message(output <- runMCMC(mMCMC, niter=1)) outputG <- getSamplesDPmeasure(mMCMC) code <- nimbleCode({ xi[1:6] ~ dCRP(conc0, 6) conc0 <- a + b a ~ dgamma(1, rate=1) b <- d + 1 d ~ dgamma(1, 1) for(i in 1:6){ mu[i] ~ dnorm(0, 1) y[i] ~ dnorm(mu[xi[i]], 1) } }) Inits <- list(xi = c(1,1,2,1,1,2), mu = 1:6, a = 1,d=1, conc0=1) Data <- list( y = rnorm(6)) m <- nimbleModel(code, data=Data, inits=Inits) mConf <- configureMCMC(m, monitors = c('xi', 'mu')) mMCMC <- buildMCMC(mConf) expect_error(getSamplesDPmeasure(mMCMC), 'sampleDPmeasure: The stochastic parent nodes of the membership') mConf <- configureMCMC(m, monitors = c('xi', 'mu', 'conc0')) mMCMC <- buildMCMC(mConf) expect_error(getSamplesDPmeasure(mMCMC), 'sampleDPmeasure: The stochastic parent nodes of the membership') mConf <- configureMCMC(m, monitors = c('xi', 'mu', 'a', 'b')) mMCMC <- buildMCMC(mConf) expect_error(getSamplesDPmeasure(mMCMC), 'sampleDPmeasure: The stochastic parent nodes of the membership') mConf <- configureMCMC(m, monitors = c('xi', 'mu', 'a', 'b', 'd')) mMCMC <- buildMCMC(mConf) expect_message(output <- runMCMC(mMCMC, niter=1)) expect_silent(outputG <- getSamplesDPmeasure(mMCMC)) mConf <- configureMCMC(m, monitors = c('xi', 'mu', 'a', 'd')) mMCMC <- buildMCMC(mConf) expect_message(output <- runMCMC(mMCMC, niter=1)) expect_silent(outputG <- getSamplesDPmeasure(mMCMC)) }) test_that("check iid assumption in sampleDPmeasure", { set.seed(1) code <- nimbleCode({ for(i in 1:10){ muTilde[i] ~ dnorm(i, 1) y[i] ~ dnorm(muTilde[xi[i]], 1) } xi[1:10] ~ dCRP(conc = 1, size=10) }) Inits <- list( xi = sample(1:2, size=10, replace=TRUE), muTilde = rep(1, 10)) Data <- list(y = c(rnorm(10, 0,1))) m <- nimbleModel(code, data=Data, inits=Inits) cm <- compileNimble(m) mConf <- configureMCMC(m, monitors = c('muTilde','xi')) mMCMC <- buildMCMC(mConf) cMCMC <- compileNimble(mMCMC, project = m, showCompilerOutput = FALSE) output <- runMCMC(cMCMC, niter=1, nburnin = 0, thin=1) expect_error(samplesG <- getSamplesDPmeasure(cMCMC), 'sampleDPmeasure: cluster parameters have to be independent and identically') if(.Platform$OS.type != "windows") { nimble:::clearCompiled(m) } code=nimbleCode({ xi[1:3] ~ dCRP(1, size = 3) thetatilde[1] ~ dnorm(0, 1) thetatilde[2] ~ dt(0, 1, 1) thetatilde[3] ~ dt(0, 1, 1) s2tilde[1] ~ dinvgamma(2, 1) s2tilde[2] ~ dgamma(1, 1) s2tilde[3] ~ dgamma(1, 1) for(i in 1:3){ y[i] ~ dnorm(thetatilde[xi[i]], var=s2tilde[xi[i]]) } } ) Inits <- list(xi = rep(1, 3), thetatilde=rep(0,3), s2tilde=rep(1,3)) Data <- list(y = rnorm(3,-5, 1)) m <- nimbleModel(code, data=Data, inits=Inits) cm <- compileNimble(m) mConf <- configureMCMC(m, monitors = c('thetatilde', 's2tilde', 'xi')) expect_silent(mMCMC <- buildMCMC(mConf)) cMCMC <- compileNimble(mMCMC, project = m) output <- cMCMC$run(1) expect_error(getSamplesDPmeasure(cMCMC), 'sampleDPmeasure: cluster parameters have to be independent and identically') if(.Platform$OS.type != "windows") { nimble:::clearCompiled(m) } code=nimbleCode( { xi[1:10] ~ dCRP(1 , size=10) thetatilde[1] ~ dnorm(0, 1) thetatilde[2] ~ dt(0, 1, 1) thetatilde[3] ~ dt(0, 1, 1) for(i in 1:10){ y[i] ~ dnorm(thetatilde[xi[i]], var=1) } } ) Inits=list(xi=rep(1, 10), thetatilde=rep(0,3)) Data=list(y=rnorm(10, 0,1)) m <- nimbleModel(code, data=Data, inits=Inits) cm <- compileNimble(m) mConf <- configureMCMC(m, monitors = c('thetatilde', 'xi')) expect_warning(mMCMC <- buildMCMC(mConf)) cMCMC <- compileNimble(mMCMC, project = m) cMCMC$run(1) expect_error(getSamplesDPmeasure(cMCMC), 'sampleDPmeasure: cluster parameters have to be independent and identically') if(.Platform$OS.type != "windows") { nimble:::clearCompiled(m) } code=nimbleCode( { xi[1:10] ~ dCRP(1 , size=10) thetatilde[1] ~ dnorm(0, 1) thetatilde[2] ~ dt(0, 1, 1) thetatilde[3] ~ dt(0, 1, 1) s2tilde[1] ~ dinvgamma(2, 1) s2tilde[2] ~ dgamma(1, 1) s2tilde[3] ~ dgamma(1, 1) for(i in 1:10){ y[i] ~ dnorm(thetatilde[xi[i]], var=s2tilde[xi[i]]) } } ) Inits=list(xi=rep(1, 10), thetatilde=rep(0,3), s2tilde=rep(1,3)) Data=list(y=rnorm(10, 0,1)) m <- nimbleModel(code, data=Data, inits=Inits) cm <- compileNimble(m) mConf <- configureMCMC(m, monitors = c('thetatilde', 's2tilde', 'xi')) expect_warning(mMCMC <- buildMCMC(mConf)) cMCMC <- compileNimble(mMCMC, project = m) cMCMC$run(1, reset=FALSE) expect_error(getSamplesDPmeasure(cMCMC), 'sampleDPmeasure: cluster parameters have to be independent and identically') if(.Platform$OS.type != "windows") { nimble:::clearCompiled(m) } code=nimbleCode( { for(j in 1:3) { for(i in 1:4){ muj[j, 1:2, i] <- (i+j)*mu0[1:2] muTilde[j, 1:2, i] ~ dmnorm(muj[j, 1:2, i], cov=Cov0[1:2, 1:2]) y[j, 1:2, i] ~ dmnorm(muTilde[j, 1:2, xi[i]], cov=Sigma0[1:2, 1:2]) } } xi[1:4] ~ dCRP(conc=1, size=4) } ) muTilde <- array(0, c(3, 2, 4)) for(j in 1:3) { muTilde[ j, ,] <- matrix(0, nrow=4, ncol=2) } y <- array(0, c(3, 2, 4)) for(i in 1:2) { for(j in 1:2) { y[j, ,i] <- rnorm(2, 5, sqrt(0.01)) } y[3, ,i] <- rnorm(2,10, sqrt(0.01)) } for(i in 3:4) { for(j in 1:2) { y[j, ,i] <- rnorm(2, -5, sqrt(0.01)) } y[3, ,i] <- rnorm(2, -10, sqrt(0.01)) } m = nimbleModel(code, data = list(y = y), inits = list(xi = 1:4, muTilde=muTilde), constants=list(mu0 = rep(0,2), Cov0 = diag(10, 2), Sigma0 = diag(1, 2))) cmodel <- compileNimble(m) conf <- configureMCMC(m, monitors=c('xi', 'muTilde')) mcmc <- buildMCMC(conf) cMCMC <- compileNimble(mcmc, project = m) cMCMC$run(1) expect_error(getSamplesDPmeasure(cMCMC), 'sampleDPmeasure: cluster parameters have to be independent and identically') if(.Platform$OS.type != "windows") { nimble:::clearCompiled(m) } }) test_that("check use of epsilon parameter in getSamplesDPmeasure", { set.seed(1) code <- nimbleCode({ for(i in 1:n) { y[i] ~ dnorm(mu[i], 1) mu[i] <- muTilde[xi[i]] } for(i in 1:n) { muTilde[i] ~ dnorm(mu0, sd = sd0) } xi[1:n] ~ dCRP(alpha, size = n) sd0 ~ dgamma(1, 1) alpha ~ dgamma(1, 1) mu0 ~ dnorm(0, var=10) }) n <- 30 constants <- list(n = n) data <- list(y = rnorm(n, 0, 1)) inits <- list(alpha = 1, mu0 = 0, sd0 = 5, xi = 1:n, muTilde = rep(0,n)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) cmodel <- compileNimble(model) conf <- configureMCMC(model, monitors = c('xi', 'muTilde', 'sd0', 'alpha', 'mu0')) mcmc <- buildMCMC(conf) cmcmc <- compileNimble(mcmc, project = model) output <- runMCMC(cmcmc, niter=1, nburnin=0, thin=1 , inits=inits, setSeed=FALSE) outputG <- getSamplesDPmeasure(cmcmc, setSeed = 1) tr1 <- nrow(outputG[[1]]) outputG <- getSamplesDPmeasure(cmcmc, epsilon = 0.1, setSeed = 1) tr2 <- nrow(outputG[[1]]) outputG <- getSamplesDPmeasure(cmcmc, epsilon = 0.00001, setSeed = 1) tr3 <- nrow(outputG[[1]]) expect_true(tr1 > tr2, info='getSamplesDPmeasure: truncation level for larger epsilon incorrectly computed') expect_true(tr1 < tr3, info='getSamplesDPmeasure: truncation level for smaller epsilon incorrectly computed') if(.Platform$OS.type != "windows") { nimble:::clearCompiled(model) } }) test_that("Test opening of new clusters in CRP sampler ", { code <- nimbleCode({ for(i in 1:n) { y[i] ~ dnorm(mu[i], 1) mu[i] <- muTilde[xi[i]] } for(i in 1:n) { muTilde[i] ~ dnorm(mu0, sd = sd0) } xi[1:n] ~ dCRP(alpha, size = n) }) n <- 20 constants <- list(n = n) data <- list(y = c(50, rep(0, n-1))) inits <- list(alpha = 1, mu0 = 0, sd0 = 5, xi = rep(1, n), muTilde = c(0, -50, rep(0, n-2))) model <- nimbleModel(code, data = data, constants = constants, inits = inits) cmodel <- compileNimble(model) conf <- configureMCMC(model, monitors = c('xi', 'muTilde', 'sd0', 'alpha', 'mu0')) conf$removeSamplers('muTilde') mcmc <- buildMCMC(conf) cmcmc <- compileNimble(mcmc, project = model) set.seed(1) output <- runMCMC(cmcmc, niter=1, nburnin=0, thin=1 , inits=inits, setSeed=FALSE) expect_lt(abs(output[1, 'muTilde[2]'] - 50), 3, label = 'incorrect update of parameter for second cluster') expect_identical(output[1, 'xi[1]'], c('xi[1]'=2), 'incorrect cluster for first obs') expect_identical(output[1, 'muTilde[1]'], c('muTilde[1]'=0), 'incorrect update of parameter for first cluster') if(.Platform$OS.type != "windows") { nimble:::clearCompiled(model) } code <- nimbleCode({ for(i in 1:n) { y[i] ~ T(dnorm(mu[i], 1), -500, 500) mu[i] <- muTilde[xi[i]] } for(i in 1:n) { muTilde[i] ~ dnorm(mu0, sd = sd0) } xi[1:n] ~ dCRP(alpha, size = n) }) n <- 20 constants <- list(n = n) data <- list(y = c(50, rep(0, n-1))) inits <- list(alpha = 1, mu0 = 50, sd0 = 5, xi = rep(1, n), muTilde = c(0, -50, rep(0, n-2))) model <- nimbleModel(code, data = data, constants = constants, inits = inits) cmodel <- compileNimble(model) conf <- configureMCMC(model, monitors = c('xi', 'muTilde', 'sd0', 'alpha', 'mu0')) conf$removeSamplers('muTilde') mcmc <- buildMCMC(conf) cmcmc <- compileNimble(mcmc, project = model) set.seed(1) output <- runMCMC(cmcmc, niter=1, nburnin=0, thin=1 , inits=inits, setSeed=FALSE) expect_true(output[1, 'muTilde[2]'] != -50, 'incorrect update of parameter for second cluster') expect_identical(output[1, 'xi[1]'], c('xi[1]'=2), 'incorrect cluster for first obs') if(.Platform$OS.type != "windows") { nimble:::clearCompiled(model) } code <- nimbleCode({ for(i in 1:n) { y[i] ~ T(dnorm(mu[i], 1), -500, 500) mu[i] <- muTilde[xi[i]] } for(i in 1:n) { muTilde[i] ~ dnorm(mu0, sd = sd0) } xi[1:n] ~ dCRP(alpha, size = n) }) n <- 20 constants <- list(n = n) data <- list(y = c(50, rep(0, n-1))) inits <- list(alpha = 1, mu0 = -50, sd0 = 5, xi = rep(1, n), muTilde = c(0, 50, rep(0, n-2))) model <- nimbleModel(code, data = data, constants = constants, inits = inits) cmodel <- compileNimble(model) conf <- configureMCMC(model, monitors = c('xi', 'muTilde', 'sd0', 'alpha', 'mu0')) conf$removeSamplers('muTilde') mcmc <- buildMCMC(conf) cmcmc <- compileNimble(mcmc, project = model) set.seed(1) output <- runMCMC(cmcmc, niter=1, nburnin=0, thin=1 , inits=inits, setSeed=FALSE) expect_true(output[1, 'muTilde[2]'] == 50, 'incorrect update of parameter for second cluster') expect_identical(output[1, 'xi[1]'], c('xi[1]'=1), 'incorrect cluster for first obs') if(.Platform$OS.type != "windows") { nimble:::clearCompiled(model) } code <- nimbleCode({ for(i in 1:n) { y[i] ~ T(dnorm(mu[i], 1), -500, 500) mu[i] <- muTilde[xi[i]] } for(i in 1:n) { muTilde[i] ~ dnorm(mu0, sd = sd0) } xi[1:n] ~ dCRP(alpha, size = n) }) n <- 20 constants <- list(n = n) data <- list(y = c(50, rep(0, n-1))) inits <- list(alpha = 1, mu0 = -50, sd0 = 5, xi = rep(1, n), muTilde = c(0, -50, rep(0, n-2))) inits$xi[1] <- 2 model <- nimbleModel(code, data = data, constants = constants, inits = inits) cmodel <- compileNimble(model) conf <- configureMCMC(model, monitors = c('xi', 'muTilde', 'sd0', 'alpha', 'mu0')) conf$removeSamplers('muTilde') mcmc <- buildMCMC(conf) cmcmc <- compileNimble(mcmc, project = model) set.seed(1) output <- runMCMC(cmcmc, niter=1, nburnin=0, thin=1 , inits=inits, setSeed=FALSE) expect_true(output[1, 'muTilde[2]'] == -50, 'incorrect update of parameter for second cluster') expect_identical(output[1, 'xi[1]'], c('xi[1]'=1), 'incorrect cluster for first obs') if(.Platform$OS.type != "windows") { nimble:::clearCompiled(model) } code <- nimbleCode({ for(i in 1:n) { y[i] ~ T(dnorm(mu[i], 1), -500, 500) mu[i] <- muTilde[xi[i]] } for(i in 1:n) { muTilde[i] ~ dnorm(mu0, sd = sd0) } xi[1:n] ~ dCRP(alpha, size = n) }) n <- 20 constants <- list(n = n) data <- list(y = c(50, rep(0, n-1))) inits <- list(alpha = 1, mu0 = 50, sd0 = 5, xi = rep(1, n), muTilde = c(0, -50, rep(0, n-2))) inits$xi[1] <- 2 model <- nimbleModel(code, data = data, constants = constants, inits = inits) cmodel <- compileNimble(model) conf <- configureMCMC(model, monitors = c('xi', 'muTilde', 'sd0', 'alpha', 'mu0')) conf$removeSamplers('muTilde') mcmc <- buildMCMC(conf) cmcmc <- compileNimble(mcmc, project = model) set.seed(1) output <- runMCMC(cmcmc, niter=1, nburnin=0, thin=1 , inits=inits, setSeed=FALSE) expect_lt(abs(output[1, 'muTilde[2]'] - 50), 5, label = 'incorrect update of parameter for second cluster') expect_identical(output[1, 'xi[1]'], c('xi[1]'=2), 'incorrect cluster for first obs') if(.Platform$OS.type != "windows") { nimble:::clearCompiled(model) } }) test_that("Test reset frunction in CRP sampler ", { set.seed(1) code=nimbleCode( { xi[1:10] ~ dCRP(1 , size=10) for(i in 1:2) thetatilde[i] ~ dnorm(0, 1) for(i in 1:10){ y[i] ~ dnorm(thetatilde[xi[i]], var=1) } } ) Inits=list(xi=rep(1, 10), thetatilde=rep(0,2)) Data=list(y=c(rnorm(3,-5, 1), rnorm(3,5, 1), rnorm(4, 0,1))) m <- nimbleModel(code, data=Data, inits=Inits) cm <- compileNimble(m) mConf <- configureMCMC(m, monitors = c('thetatilde', 'xi')) expect_warning(mMCMC <- buildMCMC(mConf)) cMCMC <- compileNimble(mMCMC, project = m) expect_output(cMCMC$run(1), info='CRP_sampler: This MCMC is for a parametric model') cMCMC$run(1, reset=FALSE) if(.Platform$OS.type != "windows") { nimble:::clearCompiled(m) } }) test_that("Test that not nonparametric MCMC message in CRP sampler is printed", { set.seed(1) code=nimbleCode( { xi[1:10] ~ dCRP(1 , size=10) for(i in 1:2) thetatilde[i] ~ dnorm(mean=0, var=10) for(i in 1:10){ y[i] ~ dnorm(thetatilde[xi[i]], var=1) } } ) Inits=list(xi=rep(1, 10), thetatilde=c(0,0)) Data=list(y=c(rnorm(3,-5, 1), rnorm(4, 0, 1), rnorm(3,5,1))) m <- nimbleModel(code, data=Data, inits=Inits) cm <- compileNimble(m) mConf <- configureMCMC(m, monitors = c('thetatilde', 'xi')) expect_warning(mMCMC <- buildMCMC(mConf)) cMCMC <- compileNimble(mMCMC, project = m) expect_output(out <- runMCMC(mcmc=cMCMC, niter=1, nburnin = 0, thin=1), 'CRP_sampler: This MCMC is for a parametric model.') code=nimbleCode( { xi[1:10] ~ dCRP(conc0 , size=10) conc0 ~ dgamma(1, 1) for(i in 1:2) thetatilde[i] ~ dnorm(mean=0, var=10) for(i in 1:10){ y[i] ~ dnorm(thetatilde[xi[i]], var=1) } } ) Inits=list(xi=rep(1, 10), thetatilde=c(0,0), conc0=1) Data=list(y=c(rnorm(3,-5, 1), rnorm(4, 0, 1), rnorm(3,5,1))) m <- nimbleModel(code, data=Data, inits=Inits) cm <- compileNimble(m) mConf <- configureMCMC(m) expect_warning(mMCMC <- buildMCMC(mConf)) cMCMC <- compileNimble(mMCMC, project = m) expect_output(out <- runMCMC(mcmc=cMCMC, niter=1, nburnin = 0, thin=1), 'CRP_sampler: This MCMC is not for a proper model.') code=nimbleCode( { xi[1:10] ~ dCRP(1 , size=10) for(i in 1:5) thetatilde[i] ~ dnorm(mean=0, var=10) for(i in 1:10){ y[i] ~ dnorm(thetatilde[xi[i]], var=1) } } ) Inits=list(xi=rep(1:5, 2), thetatilde=rep(0,5)) Data=list(y=c(rnorm(3,-5, 1), rnorm(4, 0, 1), rnorm(3,5,1))) m <- nimbleModel(code, data=Data, inits=Inits) cm <- compileNimble(m) mConf <- configureMCMC(m, monitors = c('thetatilde', 'xi')) expect_warning(mMCMC <- buildMCMC(mConf)) cMCMC <- compileNimble(mMCMC, project = m) expect_output(out <- runMCMC(cMCMC, niter=1, nburnin = 0, thin=1), 'CRP_sampler: This MCMC is for a parametric model.') code=nimbleCode( { xi[1:10] ~ dCRP(1 , size=10) for(i in 1:5) thetatilde[i] ~ dt(0,1,1) for(i in 1:10){ y[i] ~ dnorm(thetatilde[xi[i]], var=1) } } ) Inits=list(xi=rep(1:5, 2), thetatilde=rep(0,5)) Data=list(y=c(rnorm(3,-5, 1), rnorm(4, 0, 1), rnorm(3,5,1))) m <- nimbleModel(code, data=Data, inits=Inits) cm <- compileNimble(m) mConf <- configureMCMC(m, monitors = c('thetatilde', 'xi')) expect_warning(mMCMC <- buildMCMC(mConf)) cMCMC <- compileNimble(mMCMC, project = m) expect_output(out <- runMCMC(cMCMC, niter=1, nburnin = 0, thin=1), 'CRP_sampler: This MCMC is for a parametric model.') code=nimbleCode( { xi[1:10] ~ dCRP(1 , size=10) for(i in 1:10){ thetatilde[i] ~ dnorm(mean=0, var=10) y[i] ~ dnorm(thetatilde[xi[i]], var=1) } } ) Inits=list(xi=1:10, thetatilde=rep(0,10)) Data=list(y=c(rnorm(3,-5, 1), rnorm(4, 0, 1), rnorm(3,5,1))) m <- nimbleModel(code, data=Data, inits=Inits) cm <- compileNimble(m) mConf <- configureMCMC(m, monitors = c('thetatilde', 'xi')) mMCMC <- buildMCMC(mConf) cMCMC <- compileNimble(mMCMC, project = m) expect_silent(out <- runMCMC(cMCMC, niter=1, nburnin = 0, thin=1)) code=nimbleCode( { for(i in 1:4){ p[i,1:3] ~ ddirch(alpha=alpha0[1:3]) y[i,1:3] ~ dmulti(prob=p[xi[i],1:3], size=3) } xi[1:4] ~ dCRP(conc=1, size=4) } ) p0 <- matrix(0, ncol=3, nrow=4) y0 <- matrix(0, ncol=3, nrow=4) for(i in 1:4){ p0[i,]=rdirch(1, c(1, 1, 1)) y0[i,] = rmulti(1, prob=c(0.3,0.3,0.4), size=3) } m = nimbleModel(code, data = list(y = y0), inits = list(xi = 1:4, p=p0), constants=list(alpha0 = c(1,1,1))) conf <- configureMCMC(m, monitors=c('p', 'xi')) mcmc <- buildMCMC(conf) cm = compileNimble(m) cmcmc=compileNimble(mcmc,project=m) expect_silent(cmcmc$run(100)) }) test_that("Check error given when model has no cluster variables", { set.seed(1) code <- nimbleCode({ xi[1:6] ~ dCRP(conc0, 6) conc0 ~ dgamma(1, 1) for(i in 1:6){ y[i] ~ dnorm(xi[i], 1) } }) Inits <- list(xi = c(1,1,2,1,1,2), conc0 = 1) Data <- list( y = rnorm(6)) m <- nimbleModel(code, data=Data, inits=Inits) mConf <- configureMCMC(m) expect_error(buildMCMC(mConf) , 'sampler_CRP: Detected that the CRP variable is used in some way not as an index') }) test_that("dCRP nimble function calculates density correctly",{ x <- c(1,1,2,1,1,2) conc <- 1 truth <- (conc/(conc+1-1))*(1/(conc+2-1))*(conc/(conc+3-1))* (2/(conc+4-1))*(3/(conc+5-1))*(1/(conc+6-1)) ltruth <- log(truth) expect_equal(dCRP(x, conc, size=length(x), log=FALSE), truth, info = paste0("incorrect dCRP nimble function calculation")) expect_equal(dCRP(x, conc, size=length(x), log=TRUE), ltruth, info = paste0("incorrect dCRP nimble function calculation in log scale")) cdCRP <- compileNimble(dCRP) expect_equal(cdCRP(x, conc, size=length(x)), (truth), info = paste0("incorrect dCRP value in compiled nimble function")) expect_equal(cdCRP(x, conc, size=length(x), log=TRUE), (ltruth), info = paste0("incorrect dCRP value in compiled nimble function in log scale")) expect_equal(dCRP(x, conc=-1, size=length(x), log=FALSE), NaN, info = paste0("incorrect parameters space allowed")) expect_error(dCRP(x, conc=1, size=3, log=FALSE), "length of 'x' has to be equal to 'size'") expect_error(dCRP(x, conc=1, size=10, log=FALSE), "length of 'x' has to be equal to 'size'") }) test_that("CRP model calculation and dimensions are correct:", { x <- c(1,1,2,1,1,2) conc <- 1 truth <- (conc/(conc+1-1))*(1/(conc+2-1))*(conc/(conc+3-1))* (2/(conc+4-1))*(3/(conc+5-1))*(1/(conc+6-1)) ltruth <- log(truth) CRP_code <- nimbleCode({ x[1:6] ~ dCRP(conc, size=6) }) Consts <- list(conc = 1) Inits <- list(x = c(1,1,2,1,1,2)) CRP_model <- nimbleModel(CRP_code, data=Inits, constants=Consts) CRP_model$x <- x expect_equal(exp(CRP_model$calculate()), truth, info = paste0("incorrect likelihood value for dCRP")) c_CRP_model <- compileNimble(CRP_model) c_CRP_model$x expect_equal(exp(c_CRP_model$calculate()), truth, info = paste0("incorrect likelihood value for compiled dCRP")) CRP_code2 <- nimbleCode({ x[1:6] ~ dCRP(1, size=10) }) Inits <- list(x = c(1,1,2,1,1,2)) CRP_model2 <- nimbleModel(CRP_code2, data=Inits) expect_error(CRP_model2$calculate(), "length of 'x' has to be equal to 'size'") CRP_code3 <- nimbleCode({ x[1:6] ~ dCRP(1, size=3) }) Inits <- list(x = c(1,1,2,1,1,2)) CRP_model3 <- nimbleModel(CRP_code3, data=Inits) expect_error(CRP_model3$calculate(), "length of 'x' has to be equal to 'size'") }) test_that("random sampling from CRP in model with additional levels", { conc <- 1 set.seed(0) size <- 6 r_samps <- t(replicate(10000, rCRP(n = 1, conc, size = size))) true_EK <- sum(conc/(conc+1:size-1)) expect_lt(abs(mean(apply(r_samps, 1, function(x)length(unique(x)))) - true_EK), 0.01, label = "Difference in expected mean of K exceeds tolerance") set.seed(1) CRP_code <- nimbleCode({ x[1:6] ~ dCRP(conc=1, size=6) for(i in 1:6){ mu[i] ~ dnorm(0,1) y[i] ~ dnorm(mu[x[i]], 1) } }) Inits <- list(x = c(1,1,2,1,1,2), mu = 1:6) Data <- list( y = rnorm(6)) CRP_model <- nimbleModel(CRP_code, data=Data, inits=Inits) c_CRP_model <- compileNimble(CRP_model) simul_samp <- function(model) { model$simulate() return(model$x) } simul_samps <- t(replicate(10000, simul_samp(c_CRP_model))) expect_lt(abs(mean(apply(simul_samps, 1, function(x)length(unique(x)))) - true_EK), 0.01, label = "Difference in expected mean of K, from compiled model, exceeds tolerance") }) test_that("Testing conjugacy detection with models using CRP", { code = nimbleCode({ for(i in 1:4) y[i] ~ dnorm(mu[xi[i]], sd = 1) for(i in 1:2){ mu[i] ~ dnorm(0,1)} xi[1:4] ~ dCRP(conc=1, size=4) }) m = nimbleModel(code, data = list(y = rnorm(4)), inits = list(xi = rep(1,4), mu=rnorm(4))) conf <- configureMCMC(m) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_warning(mcmc <- buildMCMC(conf), "sampler_CRP: The number of clusters based on the cluster parameters is less") expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_conjugate_dnorm_dnorm") code = nimbleCode({ for(i in 1:4) { mu[i] ~ dnorm(beta,1) y[i] ~ dnorm(mu[xi[i]], sd = 1) } xi[1:4] ~ dCRP(conc=1, size=4) beta ~ dnorm(0,1) }) m = nimbleModel(code, data = list(y = rnorm(4)), inits = list(xi = rep(1,4), mu=rnorm(4), beta =1)) conf <- configureMCMC(m) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') mcmc=buildMCMC(conf) expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_conjugate_dnorm_dnorm") code = nimbleCode({ for(i in 1:4) { mu[i] ~ dnorm(0,1) mui[i] <- mu[xi[i]] y[i] ~ dnorm(mui[i], sd = 1) } xi[1:4] ~ dCRP(conc=1, size=4) }) m = nimbleModel(code, data = list(y = rnorm(4)), inits = list(xi = rep(1,4), mu=rnorm(4))) conf <- configureMCMC(m) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') mcmc=buildMCMC(conf) expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_conjugate_dnorm_dnorm") code = nimbleCode({ for(i in 1:4) { mui[i] <- mu[xi[i]] y[i] ~ dnorm(mui[i], sd = 1) } for(i in 1:2){ mu[i] ~ dnorm(0,1)} xi[1:4] ~ dCRP(conc=1, size=4) }) m = nimbleModel(code, data = list(y = rnorm(4)), inits = list(xi = rep(1,4), mu=rnorm(4))) conf <- configureMCMC(m) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') mcmc=buildMCMC(conf) expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_conjugate_dnorm_dnorm") code = nimbleCode({ for(i in 1:4) { mu[i, 2] ~ dnorm(0,1) y[i] ~ dnorm(mu[xi[i], 2], sd = 1) } xi[1:4] ~ dCRP(conc=1, size=4) }) m = nimbleModel(code, data = list(y = rnorm(4)), inits = list(xi = rep(1,4), mu=cbind(rnorm(4),rnorm(4)))) conf <- configureMCMC(m) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') mcmc=buildMCMC(conf) expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_conjugate_dnorm_dnorm") code = nimbleCode({ for(i in 1:4) { mu[2, i] ~ dnorm(0,1) y[i] ~ dnorm(mu[2, xi[i]], sd = 1) } xi[1:4] ~ dCRP(conc=1, size=4) }) m = nimbleModel(code, data = list(y = rnorm(4)), inits = list(xi = rep(1,4), mu=t(cbind(rnorm(4),rnorm(4))))) conf <- configureMCMC(m) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') mcmc=buildMCMC(conf) expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_conjugate_dnorm_dnorm") code = nimbleCode({ for(i in 1:4) { mu[i] ~ dpois(10) y[i] ~ dnorm(mu[xi[i]], sd = 1) } xi[1:4] ~ dCRP(conc=1, size=4) }) m = nimbleModel(code, data = list(y = rnorm(4)), inits = list(xi = rep(1,4), mu=rpois(4, 10))) conf <- configureMCMC(m) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') mcmc=buildMCMC(conf) expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_nonconjugate") code = nimbleCode({ for(i in 1:4) { s2tilde[i] ~ dinvgamma(a,b) s2[i] <- lambda * s2tilde[xi[i]] y[i] ~ dnorm(0, var = s2[i]) } xi[1:4] ~ dCRP(conc=1, size=4) lambda ~ dgamma(1, 1) a ~ dgamma(1, 1) b ~ dgamma(1, 1) }) m = nimbleModel(code, data = list(y = rnorm(4)), inits = list(xi = rep(1,4), s2=rinvgamma(4, 1,1), a=1, b=1, lambda=2)) conf <- configureMCMC(m) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') mcmc=buildMCMC(conf) expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_nonconjugate") code <- nimbleCode({ for(i in 1:5) { for(j in 1:2) { y[i,j] ~ dnorm( mu[xi[i], j] , var = 1) mu[i, j] ~ dnorm(i+j, var=100) } } xi[1:5] ~ dCRP(1, size=5) }) inits <- list(xi = rep(1, 5), mu = matrix(rnorm(5*2, 0), nrow=5, ncol=2)) y <- matrix(rnorm(5*2, 10, 1), ncol=2, nrow=5) y[4:5, ] <- rnorm(2*2, -10, 1) data <- list(y=y) model <- nimbleModel(code, data=data, inits=inits, dimensions=list(mu=c(5,2)), calculate=TRUE) mConf <- configureMCMC(model, monitors = c('xi','mu')) mcmc <- buildMCMC(mConf) crpIndex <- which(sapply(mConf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_nonconjugate") code <- nimbleCode({ for(i in 1:5) { for(j in 1:2) { y[i,j] ~ dnorm( mu[xi[i], j] , var = sigma2[xi[i], j]) mu[i, j] ~ dnorm(0, var=100) sigma2[i, j] ~ dinvgamma(2, 1) } } xi[1:5] ~ dCRP(1, size=5) }) inits <- list(xi = rep(1, 5), mu = matrix(rnorm(5*2), nrow=5, ncol=2), sigma2 = matrix(rinvgamma(5*2, 2, 1), nrow=5, ncol=2)) y <- matrix(rnorm(5*2, 10, 1), ncol=2, nrow=5) y[4:5, ] <- rnorm(2*2, -10, 1) data <- list(y=y) model <- nimbleModel(code, data=data, inits=inits, dimensions=list(mu=c(5,2), sigma2=c(5,2)), calculate=TRUE) cmodel<-compileNimble(model) mConf <- configureMCMC(model, monitors = c('xi','mu', 'sigma2')) mcmc <- buildMCMC(mConf) crpIndex <- which(sapply(mConf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_nonconjugate") code=nimbleCode( { for(i in 1:4){ p[1:3, i] ~ ddirch(alpha=alpha0[1:3]) y[i,1:3] ~ dmulti(prob=p[1:3, xi[i]], size=3) } xi[1:4] ~ dCRP(conc=1, size=4) } ) set.seed(1) p0 <- matrix(0, ncol=3, nrow=4) y0 <- matrix(0, ncol=3, nrow=4) for(i in 1:4){ p0[i,]=rdirch(1, c(1, 1, 1)) y0[i,] = rmulti(1, prob=c(0.3,0.3,0.4), size=3) } m = nimbleModel(code, data = list(y = y0), inits = list(xi = rep(1,4), p=t(p0)), constants=list(alpha0 = c(1,1,1))) conf <- configureMCMC(m) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') mcmc <- buildMCMC(conf) expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_conjugate_ddirch_dmulti") code=nimbleCode( { for(i in 1:4){ p[i, 2:4] ~ ddirch(alpha=alpha0[1:3]) y[i,1:3] ~ dmulti(prob=p[xi[i], 2:4], size=3) } xi[1:4] ~ dCRP(conc=1, size=4) } ) set.seed(1) p0 <- matrix(0, ncol=3, nrow=4) y0 <- matrix(0, ncol=3, nrow=4) for(i in 1:4){ p0[i,]=rdirch(1, c(1, 1, 1)) y0[i,] = rmulti(1, prob=c(0.3,0.3,0.4), size=3) } p0 <- cbind(rep(0, 4), p0) m = nimbleModel(code, data = list(y = y0), inits = list(xi = rep(1,4), p=p0), constants=list(alpha0 = c(1,1,1))) conf <- configureMCMC(m) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') mcmc <- buildMCMC(conf) expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_conjugate_ddirch_dmulti") code = nimbleCode({ for(i in 1:4) { s2[i] ~ dinvgamma(1, 1) mu[i] ~ dnorm(0,1) y[i] ~ dnorm(mu[xi[i]], var = s2[xi[i]]) } xi[1:4] ~ dCRP(conc=1, size=4) }) m = nimbleModel(code, data = list(y = rnorm(4)), inits = list(xi = rep(1,4), mu=rnorm(4), s2=rinvgamma(4, 1,1))) conf <- configureMCMC(m) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') mcmc=buildMCMC(conf) expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_nonconjugate") code = nimbleCode({ for(i in 1:4) { sigma[i] ~ dinvgamma(1, 1) mu[i] ~ dnorm(0,1) y[i] ~ dnorm(mu[xi[i]], sd = sigma[xi[i]]) } xi[1:4] ~ dCRP(conc=1, size=4) }) m = nimbleModel(code, data = list(y = rnorm(4)), inits = list(xi = rep(1,4), mu = rnorm(4), sigma = rinvgamma(4, 1,1))) conf <- configureMCMC(m) mcmc=buildMCMC(conf) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_nonconjugate") code = nimbleCode({ for(i in 1:4) { s2[i] ~ dinvgamma(a,b) mu[i] ~ dnorm(0, var = s2[i]/kappa) y[i] ~ dnorm(mu[xi[i]], var = s2[xi[i]]) } xi[1:4] ~ dCRP(conc=1, size=4) kappa ~ dgamma(1, 1) a ~ dgamma(1, 1) b ~ dgamma(1, 1) }) m = nimbleModel(code, data = list(y = rnorm(4)), inits = list(xi = rep(1,4), mu=rnorm(4), s2=rinvgamma(4, 1,1), a=1, b=1, kappa=2)) conf <- configureMCMC(m) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') mcmc=buildMCMC(conf) expect_equal(nimble:::checkCRPconjugacy(m, 'xi[1:4]'), "conjugate_dnorm_invgamma_dnorm") expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_conjugate_dnorm_invgamma_dnorm") code = nimbleCode({ for(i in 1:4) { s2Tilde[i] ~ dinvgamma(a,b) s2[i] <- s2Tilde[xi[i]] muTilde[i] ~ dnorm(0, var = s2Tilde[i]/kappa) mu[i] <- muTilde[xi[i]] y[i] ~ dnorm(mu[i], var = s2[i]) } xi[1:4] ~ dCRP(conc=1, size=4) kappa ~ dgamma(1, 1) a ~ dgamma(1, 1) b ~ dgamma(1, 1) }) m = nimbleModel(code, data = list(y = rnorm(4)), inits = list(xi = rep(1,4), muTilde=rnorm(4), s2Tilde=rinvgamma(4, 1,1), a=1, b=1, kappa=2)) conf <- configureMCMC(m) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') mcmc=buildMCMC(conf) expect_equal(nimble:::checkCRPconjugacy(m, 'xi[1:4]'), "conjugate_dnorm_invgamma_dnorm") expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_conjugate_dnorm_invgamma_dnorm") code = nimbleCode({ for(i in 1:4) { mu[i] ~ dgamma(1,1) mui[i] <- mu[xi[i]] y[i] ~ dexp(mui[i]) } xi[1:4] ~ dCRP(conc=1, size=4) }) m = nimbleModel(code, data = list(y = rexp(4, 4)), inits = list(xi = rep(1,4), mu=rgamma(4, 1, 1))) conf <- configureMCMC(m) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') mcmc=buildMCMC(conf) expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_conjugate_dgamma_dexp") code = nimbleCode({ for(i in 1:4) { mu[i] ~ dgamma(1,1) mui[i] <- mu[xi[i]] y[i] ~ dexp(mui[i]+3) } xi[1:4] ~ dCRP(conc=1, size=4) }) m = nimbleModel(code, data = list(y = rexp(4, 4)), inits = list(xi = rep(1,4), mu=rgamma(4, 1, 1))) conf <- configureMCMC(m) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') mcmc=buildMCMC(conf) expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_nonconjugate") code = nimbleCode({ for(i in 1:4) { mu[i] ~ dgamma(1,1) mui[i] <- mu[xi[i]] y[i] ~ dexp(3*mui[i]) } xi[1:4] ~ dCRP(conc=1, size=4) }) m = nimbleModel(code, data = list(y = rexp(4, 4)), inits = list(xi = rep(1,4), mu=rgamma(4, 1, 1))) conf <- configureMCMC(m) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') mcmc=buildMCMC(conf) expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_nonconjugate") code = nimbleCode({ for(i in 1:4){ mu[i] <- muTilde[xi[i]] y[i] ~ dnorm(mu[i], sd = 1) muTilde[i] ~ dnorm(mu0[i], sd = s0) mu0[i] ~ dnorm(0,1) } xi[1:4] ~ dCRP(1, 4) s0 ~ dhalfflat() }) m = nimbleModel(code, data = list(y = rnorm(4)), inits = list(xi = rep(1,4))) conf <- configureMCMC(m) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') mcmc=buildMCMC(conf) expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_nonconjugate") }) test_that("Testing handling (including error detection) with non-standard CRP model specification",{ n <- 20 const <- list(n = n) inits <- list(xi = rep(1,n), muTilde = rnorm(n), conc = 1) data <- list(y = rnorm(n)) tildeNames <- paste0("muTilde[", 1:n, "]") target <- paste0("xi[1:", n, "]") code <- nimbleCode({ xi[1:n] ~ dCRP(conc, n) for(i in 1:n) { y[i] ~ dnorm(mu[i], var = 1) mu[i] <- muTilde[xi[i]] } for(i in 1:n){ muTilde[i] ~ dnorm(0,1) } }) m <- nimbleModel(code, data = data, constants = const, inits = inits) conf <- configureMCMC(m) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_conjugate_dnorm_dnorm") clusterNodeInfo <- nimble:::findClusterNodes(m, target) expect_equal(TRUE, clusterNodeInfo$targetIsIndex) expect_equal(FALSE, clusterNodeInfo$targetIndexedByFunction) expect_equal(1, clusterNodeInfo$numIndexes) expect_equal(1, clusterNodeInfo$indexPosition) expect_equal(n, clusterNodeInfo$nTilde) code <- nimbleCode({ xi[1:n] ~ dCRP(conc, n) for(i in 1:n) { y[i] ~ dnorm(mu[i], var = 1) mu[i] <- muTilde[xi[i], 2] } for(i in 1:n){muTilde[i, 2] ~ dnorm(0,1)} }) inits2 <- inits inits2$muTilde <- matrix(rnorm(n*2), n) m <- nimbleModel(code, data = data, constants = const, inits = inits2) conf <- configureMCMC(m) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_conjugate_dnorm_dnorm") clusterNodeInfo <- nimble:::findClusterNodes(m, target) expect_equal(clusterNodeInfo$clusterNodes[[1]], paste0("muTilde[", 1:n, ", 2]")) expect_equal(TRUE, clusterNodeInfo$targetIsIndex) expect_equal(FALSE, clusterNodeInfo$targetIndexedByFunction) expect_equal(2, clusterNodeInfo$numIndexes) expect_equal(1, clusterNodeInfo$indexPosition) expect_equal(n, clusterNodeInfo$nTilde) code <- nimbleCode({ xi[1:n] ~ dCRP(conc, n) for(i in 1:n) { y[i] ~ dnorm(mu[i], var = 1) mu[i] <- muTilde[xi[i]] } for(i in 1:(n-2)){muTilde[i] ~ dnorm(0,1)} }) m <- nimbleModel(code, data = data, constants = const, inits = inits) conf <- configureMCMC(m) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_warning(mcmc <- buildMCMC(conf), "less than the number of potential clusters") expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_conjugate_dnorm_dnorm") clusterNodeInfo <- nimble:::findClusterNodes(m, target) expect_equal(TRUE, clusterNodeInfo$targetIsIndex) expect_equal(FALSE, clusterNodeInfo$targetIndexedByFunction) expect_equal(1, clusterNodeInfo$numIndexes) expect_equal(1, clusterNodeInfo$indexPosition) expect_equal(n-2, clusterNodeInfo$nTilde) code <- nimbleCode({ xi[1:n] ~ dCRP(conc, n) for(i in 1:n) { y[i] ~ dnorm(mu[i], var = 1) mu[i] <- muTilde[b[i]] } for(j in 1:n) b[j] <- xi[j] for(i in 1:n) muTilde[i] ~ dnorm(0,1) }) m <- nimbleModel(code, data = data, constants = const, inits = inits) conf <- configureMCMC(m) expect_error(mcmc <- buildMCMC(conf), "Detected that the CRP variable is used in some way not as an index") code <- nimbleCode({ xi[1:n] ~ dCRP(conc, n) for(i in 1:n) { y[i] ~ dnorm(muTilde[2, xi[i]], var = 1) } for(i in 1:n) {muTilde[2, i] ~ dnorm(0,1)} }) inits2 <- inits inits2$muTilde <- rbind(rnorm(n), rnorm(n)) m <- nimbleModel(code, data = data, constants = const, inits = inits2) conf <- configureMCMC(m) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_conjugate_dnorm_dnorm") clusterNodeInfo <- nimble:::findClusterNodes(m, target) expect_equal(clusterNodeInfo$clusterNodes[[1]], paste0("muTilde[2, ", 1:n, "]")) expect_equal(2, clusterNodeInfo$numIndexes) expect_equal(2, clusterNodeInfo$indexPosition) expect_equal(TRUE, clusterNodeInfo$targetIsIndex) expect_equal(FALSE, clusterNodeInfo$targetIndexedByFunction) code <- nimbleCode({ xi[1:n] ~ dCRP(conc, n) for(i in 1:n) { y[i] ~ dnorm(muTilde[2, xi[i]], var = 1) } for(j in 1:2) for(i in 1:n) {muTilde[j, i] ~ dnorm(0,1)} }) m <- nimbleModel(code, data = data, constants = const, inits = inits2) conf <- configureMCMC(m) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_conjugate_dnorm_dnorm") clusterNodeInfo <- nimble:::findClusterNodes(m, target) expect_equal(clusterNodeInfo$clusterNodes[[1]], paste0("muTilde[2, ", 1:n, "]")) expect_equal(2, clusterNodeInfo$numIndexes) expect_equal(2, clusterNodeInfo$indexPosition) expect_equal(TRUE, clusterNodeInfo$targetIsIndex) expect_equal(FALSE, clusterNodeInfo$targetIndexedByFunction) code <- nimbleCode({ xi[1:n] ~ dCRP(conc, n) for(i in 1:n) { y[i] ~ dnorm(mu[i], var = 1) mu[i] <- muTilde[xi[i]+1] } for(i in 1:(n+1)) {muTilde[i] ~ dnorm(0,1)} }) inits2$muTilde <- rnorm(n+1) m <- nimbleModel(code, data = data, constants = const, inits = inits2) conf <- configureMCMC(m) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_conjugate_dnorm_dnorm") clusterNodeInfo <- nimble:::findClusterNodes(m, target) expect_equal(clusterNodeInfo$clusterNodes[[1]], paste0("muTilde[", 2:(n+1), "]")) expect_equal(1, clusterNodeInfo$numIndexes) expect_equal(1, clusterNodeInfo$indexPosition) expect_equal(FALSE, clusterNodeInfo$targetIsIndex) expect_equal(FALSE, clusterNodeInfo$targetIndexedByFunction) expect_equal(n, clusterNodeInfo$nTilde) code <- nimbleCode({ xi[1:n] ~ dCRP(conc, n) for(i in 1:n) { y[i] ~ dnorm(mu[i], var = 1) mu[i] <- muTilde[xi[i]+1] } for(i in 2:(n+1)) {muTilde[i] ~ dnorm(0,1)} }) m <- nimbleModel(code, data = data, constants = const, inits = inits2) conf <- configureMCMC(m) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_conjugate_dnorm_dnorm") clusterNodeInfo <- nimble:::findClusterNodes(m, target) expect_equal(clusterNodeInfo$clusterNodes[[1]], paste0("muTilde[", 2:(n+1), "]")) expect_equal(1, clusterNodeInfo$numIndexes) expect_equal(1, clusterNodeInfo$indexPosition) expect_equal(FALSE, clusterNodeInfo$targetIsIndex) expect_equal(FALSE, clusterNodeInfo$targetIndexedByFunction) expect_equal(n, clusterNodeInfo$nTilde) code <- nimbleCode({ xi[1:n] ~ dCRP(conc, n) for(i in 1:n) { y[i] ~ dnorm(mu[i], var = 1) mu[i] <- muTilde[n-xi[i]+1] } for(i in 1:n) {muTilde[i] ~ dnorm(0,1)} }) m <- nimbleModel(code, data = data, constants = const, inits = inits) conf <- configureMCMC(m) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_conjugate_dnorm_dnorm") clusterNodeInfo <- nimble:::findClusterNodes(m, target) expect_equal(clusterNodeInfo$clusterNodes[[1]], paste0("muTilde[", n:1, "]")) expect_equal(1, clusterNodeInfo$numIndexes) expect_equal(1, clusterNodeInfo$indexPosition) expect_equal(FALSE, clusterNodeInfo$targetIsIndex) expect_equal(FALSE, clusterNodeInfo$targetIndexedByFunction) expect_equal(n, clusterNodeInfo$nTilde) code <- nimbleCode({ xi[1:n] ~ dCRP(conc, n) for(i in 1:n) { y[i] ~ dnorm(mu[i], var = 1) mu[i] <- muTilde[xi[n-i+1]] } for(i in 1:n) {muTilde[i] ~ dnorm(0,1)} }) m <- nimbleModel(code, data = data, constants = const, inits = inits) expect_error(conf <- configureMCMC(m), "findClusterNodes: Detected that a cluster parameter is indexed by a function") code <- nimbleCode({ xi[1:n] ~ dCRP(conc, n) for(i in 1:n) { y[i] ~ dnorm(mu[i], var = 1) mu[i] <- muTilde[xi[i]+2] } for(i in 3:(n+2)) {muTilde[i] ~ dnorm(0,1)} }) inits2$muTilde <- rnorm(n+2) m <- nimbleModel(code, data = data, constants = const, inits = inits2) conf <- configureMCMC(m) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_conjugate_dnorm_dnorm") clusterNodeInfo <- nimble:::findClusterNodes(m, target) expect_equal(clusterNodeInfo$clusterNodes[[1]], paste0("muTilde[", 3:(n+2), "]")) expect_equal(1, clusterNodeInfo$numIndexes) expect_equal(1, clusterNodeInfo$indexPosition) expect_equal(FALSE, clusterNodeInfo$targetIsIndex) expect_equal(FALSE, clusterNodeInfo$targetIndexedByFunction) expect_equal(n, clusterNodeInfo$nTilde) code <- nimbleCode({ xi[1:n] ~ dCRP(conc, n) for(i in 1:n) { y[i] ~ dnorm(mu[i], var = 1) mu[i] <- muTilde[xi[i]] } for(i in 1:(2*n)) {muTilde[i] ~ dnorm(0,1)} }) inits2$muTilde <- rnorm(2*n) m <- nimbleModel(code, data = data, constants = const, inits = inits2) conf <- configureMCMC(m) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_conjugate_dnorm_dnorm") clusterNodeInfo <- nimble:::findClusterNodes(m, target) expect_equal(clusterNodeInfo$clusterNodes[[1]], paste0("muTilde[", 1:n, "]")) expect_equal(1, clusterNodeInfo$numIndexes) expect_equal(1, clusterNodeInfo$indexPosition) expect_equal(TRUE, clusterNodeInfo$targetIsIndex) expect_equal(FALSE, clusterNodeInfo$targetIndexedByFunction) expect_equal(n, clusterNodeInfo$nTilde) code <- nimbleCode({ xi[1:n] ~ dCRP(conc, n) for(i in 1:n) { y[i] ~ dnorm(mu[i], var = 1) mu[i] <- muTilde[xi[i]] } for(i in 2:(n-2)) muTilde[i] ~ dnorm(0,1) }) m <- nimbleModel(code, data = data, constants = const, inits = inits) conf <- configureMCMC(m) expect_warning(mcmc <- buildMCMC(conf), "sampler_CRP: The number of clusters based on the cluster parameters is less") clusterNodeInfo <- nimble:::findClusterNodes(m, target) expect_equal(clusterNodeInfo$clusterNodes[[1]], paste0("muTilde[", 2:(n-2), "]")) expect_equal(1, clusterNodeInfo$numIndexes) expect_equal(1, clusterNodeInfo$indexPosition) expect_equal(TRUE, clusterNodeInfo$targetIsIndex) expect_equal(FALSE, clusterNodeInfo$targetIndexedByFunction) expect_equal(n-3, clusterNodeInfo$nTilde) code <- nimbleCode({ xi[1:n] ~ dCRP(conc, n) for(i in 1:n) { y[i] ~ dnorm(mu[i], var = 1) mu[i] <- muTilde[xi[i]+1] } for(i in 2:(n-2)) {muTilde[i] ~ dnorm(0,1)} }) m <- nimbleModel(code, data = data, constants = const, inits = inits) conf <- configureMCMC(m) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_warning(mcmc <- buildMCMC(conf), "sampler_CRP: The number of clusters based on the cluster parameters is less") expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_conjugate_dnorm_dnorm") clusterNodeInfo <- nimble:::findClusterNodes(m, target) expect_equal(clusterNodeInfo$clusterNodes[[1]], paste0("muTilde[", 2:(n-2), "]")) expect_equal(1, clusterNodeInfo$numIndexes) expect_equal(1, clusterNodeInfo$indexPosition) expect_equal(FALSE, clusterNodeInfo$targetIsIndex) expect_equal(FALSE, clusterNodeInfo$targetIndexedByFunction) expect_equal(n-3, clusterNodeInfo$nTilde) code <- nimbleCode({ xi[1:n] ~ dCRP(conc, n) for(i in 1:n) { y[i] ~ dnorm(mu[i], var = 1) mu[i] <- muTilde[xi[i]] } for(i in 1:n) {muTilde[i] ~ dnorm(0, 1)} z ~ dnorm(muTilde[1], 1) }) m <- nimbleModel(code, data = data, constants = const, inits = inits) conf <- configureMCMC(m) expect_error(mcmc <- buildMCMC(conf), "Only the variables being clustered") code=nimbleCode({ for(i in 1:10) { muTilde[i] ~ dnorm(log(xi[1]), 1) mu[i] <- muTilde[xi[i]] y[i] ~ dnorm(mu[i], 1) } xi[1:10] ~ dCRP(1 , size=10) }) Inits=list(xi=rep(1, 10), muTilde=rep(0,10)) Data=list(y=rnorm(10,0, 1)) m <- nimbleModel(code, data=Data, inits=Inits) mConf <- configureMCMC(m) expect_error(mcmc <- buildMCMC(mConf), 'sampler_CRP: Detected that the CRP variable is used in some way not as an index') code=nimbleCode({ for(i in 1:10) { muTilde[i] ~ dnorm(0, 1) mu[i] <- muTilde[xi[i]] y[i] ~ dnorm(mu[i], 1) } xi[1:10] ~ dCRP(1 , size=10) tau ~ dnorm(muTilde[xi[1]], 1) }) Inits=list(xi=rep(1, 10), muTilde=rep(0,10), tau=1) Data=list(y=rnorm(10,0, 1)) m <- nimbleModel(code, data=Data, inits=Inits) mConf <- configureMCMC(m) expect_error(mcmc <- buildMCMC(mConf), 'sampler_CRP: Detected unusual indexing') code <- nimbleCode({ xi[1:n] ~ dCRP(alpha, n) for(i in 1:n){ mu[i] ~ dnorm(0, var = s2[i]/lambda) s2[i] ~ dinvgamma(2, 1) y[i] ~ dnorm(mu[xi[i]], var = s2[xi[i]]) x[i] ~ dnorm(mu[xi[i]], 1) } lambda ~ dgamma(1, 1) alpha ~ dgamma(1, 1) }) m <- nimbleModel(code, data=c(data, list(x = rnorm(n))), inits=inits, constants = const) mConf <- configureMCMC(m) mMCMC <- buildMCMC(mConf) code <- nimbleCode({ xi[1:n] ~ dCRP(alpha, n) for(i in 1:n){ mu[i] ~ dnorm(0, var = s2[i]/lambda) s2[i] ~ dinvgamma(2, 1) y[i] ~ dnorm(mu[xi[i]], var = s2[xi[i]]) } for(i in 1:5) x[i] ~ dnorm(mu[xi[i]], 1) lambda ~ dgamma(1, 1) alpha ~ dgamma(1, 1) }) m <- nimbleModel(code, data=c(data, list(x = rnorm(5))), inits=inits, constants = const) mConf <- configureMCMC(m) expect_error(mMCMC <- buildMCMC(mConf), "sampler_CRP: Inconsistent indexing") code <- nimbleCode({ xi[1:n] ~ dCRP(conc, n) for(i in 1:n) { y[i] ~ dnorm(mu[i], var = 1) mu[i] <- muTilde[xi[i]] } for(i in 1:n) muTilde[i] ~ dnorm(0,1) z ~ dnorm(muTilde[n+1], 1) }) inits2$muTilde <- rnorm(n+1) m <- nimbleModel(code, data = data, constants = const, inits = inits2) conf <- configureMCMC(m) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_conjugate_dnorm_dnorm") clusterNodeInfo <- nimble:::findClusterNodes(m, target) expect_equal(clusterNodeInfo$clusterNodes[[1]], paste0("muTilde[", 1:n, "]")) expect_equal(1, clusterNodeInfo$numIndexes) expect_equal(1, clusterNodeInfo$indexPosition) expect_equal(TRUE, clusterNodeInfo$targetIsIndex) expect_equal(FALSE, clusterNodeInfo$targetIndexedByFunction) expect_equal(n, clusterNodeInfo$nTilde) code <- nimbleCode({ xi[1:n] ~ dCRP(conc, n) for(i in 1:n) y[i] ~ dnorm(mu[i], var = 1) for(i in 1:(n-2)) mu[i] <- muTilde[xi[i]] for(j in (n-1):n) mu[j] <- exp(muTilde[xi[j]]) for(i in 1:n) muTilde[i] ~ dnorm(0, 1) }) constSave <- const const$n <- 4 m <- nimbleModel(code, data = data, constants = const, inits = inits) conf <- configureMCMC(m) expect_error(mcmc <- buildMCMC(conf), "differing number of clusters indicated by") const <- constSave code <- nimbleCode({ xi[1:n] ~ dCRP(conc, n) for(i in 1:n) { y[i] ~ dnorm(mu[i], var = s2[i]) mu[i] <- muTilde[xi[i]] s2[i] ~ dgamma(1,1) } for(i in 1:n) {muTilde[i] ~ dnorm(0,1)} }) m <- nimbleModel(code, data = data, constants = const, inits = inits) conf <- configureMCMC(m) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_conjugate_dnorm_dnorm") clusterNodeInfo <- nimble:::findClusterNodes(m, target) expect_equal(clusterNodeInfo$clusterNodes[[1]], paste0("muTilde[", 1:n, "]")) expect_equal(TRUE, clusterNodeInfo$targetIsIndex) expect_equal(FALSE, clusterNodeInfo$targetIndexedByFunction) expect_equal(1, clusterNodeInfo$numIndexes) expect_equal(1, clusterNodeInfo$indexPosition) expect_equal(n, clusterNodeInfo$nTilde) code <- nimbleCode({ xi[1:n] ~ dCRP(conc, n) for(i in 1:(n/2)) { y[i] ~ dnorm(mu[i], var = 1) } for(i in ((n/2)+1):n) {y[i] ~ dnorm(mu[i], var = 1)} for(i in 1:n) {mu[i] <- muTilde[xi[i]]} for(i in 1:n) {muTilde[i] ~ dnorm(0,1)} }) m <- nimbleModel(code, data = data, constants = const, inits = inits) conf <- configureMCMC(m) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_nonconjugate") clusterNodeInfo <- nimble:::findClusterNodes(m, target) expect_equal(clusterNodeInfo$clusterNodes[[1]], paste0("muTilde[", 1:n, "]")) expect_equal(TRUE, clusterNodeInfo$targetIsIndex) expect_equal(FALSE, clusterNodeInfo$targetIndexedByFunction) expect_equal(1, clusterNodeInfo$numIndexes) expect_equal(1, clusterNodeInfo$indexPosition) expect_equal(n, clusterNodeInfo$nTilde) code <- nimbleCode({ xi[1:n] ~ dCRP(conc, n) y[1] ~ dnorm(mu[1], var = s2[1]) for(i in 2:n) y[i] ~ dnorm(mu[i]+y[i-1], var = s2[i]) for(i in 1:n) { mu[i] <- muTilde[xi[i]] s2[i] ~ dgamma(1,1) } for(i in 1:n) {muTilde[i] ~ dnorm(0,1)} }) m <- nimbleModel(code, data = data, constants = const, inits = inits) conf <- configureMCMC(m) expect_error(mcmc <- buildMCMC(conf), "Variables being clustered must be conditionally independent.") code <- nimbleCode({ xi[1:n] ~ dCRP(conc, n) for(i in 1:n) { y[i] ~ dnorm(mu[i], var = 1) mu[i] <- muTilde[xi[i]] } muTilde[1] ~ dnorm(0, 1) for(i in 2:n) {muTilde[i] ~ dnorm(muTilde[i-1],1)} }) m <- nimbleModel(code, data = data, constants = const, inits = inits) conf <- configureMCMC(m) expect_error(mcmc <- buildMCMC(conf), "sampler_CRP: cluster parameters must be independent across clusters") code <- nimbleCode({ xi[1:n] ~ dCRP(conc, n) for(i in 1:n) { y[i] ~ dnorm(mu[i], var = 1) mu[i] <- muTilde[xi[i]] } for(i in 1:(n-1) ) {muTilde[i] ~ dnorm(mu0[i],1)} muTilde[n] ~ dgamma(1,1) }) m <- nimbleModel(code, data = data, constants = const, inits = inits) conf <- configureMCMC(m) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_nonconjugate") clusterNodeInfo <- nimble:::findClusterNodes(m, target) expect_equal(clusterNodeInfo$clusterNodes[[1]], paste0("muTilde[", 1:n, "]")) expect_equal(TRUE, clusterNodeInfo$targetIsIndex) expect_equal(FALSE, clusterNodeInfo$targetIndexedByFunction) expect_equal(1, clusterNodeInfo$numIndexes) expect_equal(1, clusterNodeInfo$indexPosition) expect_equal(n, clusterNodeInfo$nTilde) code <- nimbleCode({ xi[1:n] ~ dCRP(conc + muTilde[1], n) for(i in 1:n) { y[i] ~ dnorm(mu[i], var = 1) mu[i] <- muTilde[xi[i]] } for(i in 1:n) {muTilde[i] ~ dnorm(0,1)} }) m <- nimbleModel(code, data = data, constants = const, inits = inits) conf <- configureMCMC(m) expect_error(mcmc <- buildMCMC(conf), "Only the variables being clustered can depend") code <- nimbleCode({ xi[1:n] ~ dCRP(conc, n) for(i in 1:n) { y[i] ~ dnorm(mu[i], var = 1) mu[i] <- muTilde[xi[i]] tmp[i] ~ dnorm(0,1) } for(i in 1:n) muTilde[i] ~ dnorm(tmp[xi[i]],1) }) m <- nimbleModel(code, data = data, constants = const, inits = inits) conf <- configureMCMC(m) expect_error(mcmc <- buildMCMC(conf), "Only the variables being clustered can depend") inits$s2Tilde <- rep(1, n) code <- nimbleCode({ xi[1:n] ~ dCRP(conc, n) for(i in 1:n) { y[i] ~ dnorm(mu[i], var = s2Tilde[xi[i]]) mu[i] <- muTilde[xi[i]] } for(i in 1:n) { muTilde[i] ~ dnorm(0, var = s2Tilde[i]) s2Tilde[i] ~ dinvgamma(1,1) } }) m <- nimbleModel(code, data = data, constants = const, inits = inits) conf <- configureMCMC(m) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_conjugate_dnorm_invgamma_dnorm") clusterNodeInfo <- nimble:::findClusterNodes(m, target) expect_equal(clusterNodeInfo$clusterNodes[[2]], paste0("muTilde[", 1:n, "]")) expect_equal(clusterNodeInfo$clusterNodes[[1]], paste0("s2Tilde[", 1:n, "]")) expect_equal(c(1,1), clusterNodeInfo$numIndexes) expect_equal(c(1,1), clusterNodeInfo$indexPosition) expect_equal(rep(TRUE, 2), clusterNodeInfo$targetIsIndex) expect_equal(rep(FALSE, 2), clusterNodeInfo$targetIndexedByFunction) expect_equal(rep(n,2), clusterNodeInfo$nTilde) code <- nimbleCode({ xi[1:n] ~ dCRP(conc, n) for(i in 1:n) { y[i] ~ dnorm(mu[i], var = s2Tilde[xi[i]]) mu[i] <- muTilde[xi[i]] } kappa ~ dgamma(1,1) for(i in 1:n) muTilde[i] ~ dnorm(0, var = s2Tilde[i]/kappa) for(i in 1:(n-1)) s2Tilde[i] ~ dinvgamma(1,1) }) m <- nimbleModel(code, data = data, constants = const, inits = inits) conf <- configureMCMC(m) expect_error(mcmc <- buildMCMC(conf), "sampler_CRP: In a model with multiple cluster parameters, the number") code <- nimbleCode({ xi[1:n] ~ dCRP(conc, n) for(i in 1:n) { y[i] ~ dnorm(mu[i], var = s2Tilde[xi[i]]) mu[i] <- muTilde[xi[i]] } kappa ~ dgamma(1,1) for(i in 1:(n-1)) { muTilde[i] ~ dnorm(0,var = s2Tilde[i]/kappa) s2Tilde[i] ~ dinvgamma(1,1) } }) m <- nimbleModel(code, data = data, constants = const, inits = inits) conf <- configureMCMC(m) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_warning(mcmc <- buildMCMC(conf), "less than the number of potential clusters") expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_conjugate_dnorm_invgamma_dnorm") clusterNodeInfo <- nimble:::findClusterNodes(m, target) expect_equal(clusterNodeInfo$clusterNodes[[2]], paste0("muTilde[", 1:(n-1), "]")) expect_equal(clusterNodeInfo$clusterNodes[[1]], paste0("s2Tilde[", 1:(n-1), "]")) expect_equal(c(1,1), clusterNodeInfo$numIndexes) expect_equal(c(1,1), clusterNodeInfo$indexPosition) expect_equal(rep(TRUE, 2), clusterNodeInfo$targetIsIndex) expect_equal(rep(FALSE, 2), clusterNodeInfo$targetIndexedByFunction) expect_equal(c(n-1, n-1), clusterNodeInfo$nTilde) code <- nimbleCode({ xi[1:n] ~ dCRP(conc, n) for(i in 1:n) { y[i] ~ dnorm(mu[i], var = s2Tilde[xi[i]]) mu[i] <- muTilde[xi[i],xi[i]] } for(i in 1:n) { for(j in 1:n) {muTilde[i,j] ~ dnorm(0,var=s2Tilde[i]/3)} s2Tilde[i] ~ dinvgamma(1,1) } }) inits2 <- inits inits2$muTilde <- matrix(rnorm(n^2),n) m <- nimbleModel(code, data = data, constants = const, inits = inits2) expect_error(conf <- configureMCMC(m), "CRP variable used multiple times") code <- nimbleCode({ xi[1:n] ~ dCRP(conc, n) for(i in 1:n) { y[i] ~ dnorm(mu[i], var = s2Tilde[n-xi[i]+1]) mu[i] <- muTilde[xi[i]] } for(i in 1:n) { muTilde[i] ~ dnorm(0,var=s2Tilde[n-i+1]/3) s2Tilde[i] ~ dinvgamma(1,1) } }) m <- nimbleModel(code, data = data, constants = const, inits = inits) conf <- configureMCMC(m) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_conjugate_dnorm_invgamma_dnorm") clusterNodeInfo <- nimble:::findClusterNodes(m, target) expect_equal(clusterNodeInfo$clusterNodes[[2]], paste0("muTilde[", 1:n, "]")) expect_equal(clusterNodeInfo$clusterNodes[[1]], paste0("s2Tilde[", n:1, "]")) expect_equal(c(1,1), clusterNodeInfo$numIndexes) expect_equal(c(1,1), clusterNodeInfo$indexPosition) expect_equal(c(FALSE, TRUE), clusterNodeInfo$targetIsIndex) expect_equal(rep(FALSE, 2), clusterNodeInfo$targetIndexedByFunction) expect_equal(rep(n,2), clusterNodeInfo$nTilde) code <- nimbleCode({ xi[1:n] ~ dCRP(conc, n) for(i in 1:n) { y[i] ~ dnorm(mu[i], var = s2Tilde[n-xi[i]+1]) mu[i] <- muTilde[xi[i]] } for(i in 1:n) { muTilde[i] ~ dnorm(0,var=s2Tilde[i]/3) s2Tilde[i] ~ dinvgamma(1,1) } }) m <- nimbleModel(code, data = data, constants = const, inits = inits) conf <- configureMCMC(m) expect_error(mcmc <- buildMCMC(conf), "sampler_CRP: cluster parameters must be independent across clusters") code <- nimbleCode({ xi[1:n] ~ dCRP(conc, n) for(i in 1:n) { y[i] ~ dnorm(muTilde[xi[i]], var = exp(s2Tilde[xi[i]])) } for(i in 1:n) { muTilde[i] ~ dnorm(0,1) s2Tilde[i] ~ dgamma(1,1) } }) m <- nimbleModel(code, data = data, constants = const, inits = inits) conf <- configureMCMC(m) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_nonconjugate") clusterNodeInfo <- nimble:::findClusterNodes(m, target) expect_equal(clusterNodeInfo$clusterNodes[[2]], paste0("muTilde[", 1:n, "]")) expect_equal(clusterNodeInfo$clusterNodes[[1]], paste0("s2Tilde[", 1:n, "]")) expect_equal(c(1,1), clusterNodeInfo$numIndexes) expect_equal(c(1,1), clusterNodeInfo$indexPosition) expect_equal(rep(TRUE, 2), clusterNodeInfo$targetIsIndex) expect_equal(rep(FALSE, 2), clusterNodeInfo$targetIndexedByFunction) expect_equal(rep(n,2), clusterNodeInfo$nTilde) data$y <- matrix(rnorm(n^2), n) code <- nimbleCode({ xi[1:n] ~ dCRP(conc, n) for(i in 1:n) { for(j in 1:n) y[i,j] ~ dnorm(muTilde[xi[i]], var = s2Tilde[xi[j]]) } for(i in 1:n) { muTilde[i] ~ dnorm(0,1) s2Tilde[i] ~ dinvgamma(1,1) } }) m <- nimbleModel(code, data = data, constants = const, inits = inits) expect_error(conf <- configureMCMC(m), "findClusterNodes: found cluster membership parameters that use different indexing variables") inits$muTilde <- matrix(rnorm(n^2), n) code <- nimbleCode({ xi[1:n] ~ dCRP(conc, n) for(i in 1:n) { for(j in 1:n) {y[i,j] ~ dnorm(muTilde[xi[i],xi[j]], var = s2Tilde[xi[i]])} } for(i in 1:n) { for(j in 1:n) {muTilde[i,j] ~ dnorm(0,1)} s2Tilde[i] ~ dinvgamma(1,1) } }) m <- nimbleModel(code, data = data, constants = const, inits = inits) expect_error(conf <- configureMCMC(m), "CRP variable used multiple times in") code <- nimbleCode({ for(i in 1:n) { for(j in 1:J) { y[i, j] ~ dnorm(thetaTilde[xi[i], j], 1) thetaTilde[i, j] ~ dnorm(0, 1) }} xi[1:n] ~ dCRP(alpha, size = n) }) n <- 5 J <- 3 constants <- list(n = n, J = J) data <- list(y = matrix(rnorm(n*J),n,J)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = matrix(rnorm(J*n), n, J)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') expect_identical(cn$clusterNodes[[1]], c(matrix(model$expandNodeNames('thetaTilde'), J, n, byrow = TRUE))) expect_identical(cn$numNodesPerCluster, as.integer(J)) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_conjugate_dnorm_dnorm") expect_identical(crpSampler$nObsPerClusID, J) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(0)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- conf$getSamplers('thetaTilde') expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n*J)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), rep(1:n, each = J)) code <- nimbleCode({ for(i in 1:n) { for(j in 1:J) { y[i, j] ~ dnorm(thetaTilde[xi[i], j], 1) }} for(i in 1:n2) { for(j in 1:J) { thetaTilde[i, j] ~ dnorm(0, 1) }} xi[1:n] ~ dCRP(alpha, size = n) }) n <- 5 n2 <- 4 J <- 3 constants <- list(n = n, n2 = n2, J = J) data <- list(y = matrix(rnorm(n*J),n,J)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = matrix(rnorm(J*n2), n2, J)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') expect_identical(cn$clusterNodes[[1]], c(matrix(model$expandNodeNames('thetaTilde'), J, n2, byrow = TRUE))) expect_identical(cn$numNodesPerCluster, as.integer(J)) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_warning(mcmc <- buildMCMC(conf), "is less than the number of potential") crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_conjugate_dnorm_dnorm") expect_identical(crpSampler$nObsPerClusID, J) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(0)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- conf$getSamplers('thetaTilde') expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n2*J)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), rep(1:n2, each = J)) code <- nimbleCode({ for(i in 1:n) { for(j in 1:J) { y[i, j] ~ dnorm(theta[i, j], 1) theta[i, j] <- thetaTilde[xi[i], j] }} for(i in 1:n2) for(j in 1:J) thetaTilde[i, j] ~ dnorm(0, 1) xi[1:n] ~ dCRP(alpha, size = n) }) n <- 5 n2 <- 4 J <- 3 constants <- list(n = n, n2 = n2, J = J) data <- list(y = matrix(rnorm(n*J),n,J)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = matrix(rnorm(J*n), n, J)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') nodes <- model$expandNodeNames('thetaTilde') nodes <- nodes[nodes %in% model$getNodeNames()] expect_identical(cn$clusterNodes[[1]], c(matrix(nodes, J, n2, byrow = TRUE))) expect_identical(cn$numNodesPerCluster, as.integer(J)) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_warning(mcmc <- buildMCMC(conf), "is less than the number of potential") crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_conjugate_dnorm_dnorm") expect_identical(crpSampler$nObsPerClusID, J) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(J)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- conf$getSamplers('thetaTilde') expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n2*J)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), rep(1:n2, each = J)) code <- nimbleCode({ for(i in 1:n) { for(j in 1:J) { y[j, i] ~ dnorm(thetaTilde[j, xi[i]], 1) thetaTilde[j, i] ~ dnorm(0, 1) }} xi[1:n] ~ dCRP(alpha, size = n) }) n <- 5 J <- 3 constants <- list(n = n, J = J) data <- list(y = matrix(rnorm(n*J),J,n)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = matrix(rnorm(J*n), J, n)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') expect_identical(cn$clusterNodes[[1]], model$expandNodeNames('thetaTilde')) expect_identical(cn$numNodesPerCluster, as.integer(J)) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_conjugate_dnorm_dnorm") expect_identical(crpSampler$nObsPerClusID, J) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(0)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- conf$getSamplers('thetaTilde') expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n*J)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), rep(1:n, each = J)) code <- nimbleCode({ for(j in 1:J) { for(i in 1:n) { y[j, i] ~ dnorm(thetaTilde[j, xi[i]], 1) thetaTilde[j, i] ~ dnorm(0, 1) }} xi[1:n] ~ dCRP(alpha, size = n) }) n <- 5 J <- 3 constants <- list(n = n, J = J) data <- list(y = matrix(rnorm(n*J),J,n)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = matrix(rnorm(J*n), J, n)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') expect_identical(cn$clusterNodes[[1]], model$expandNodeNames('thetaTilde')) expect_identical(cn$numNodesPerCluster, as.integer(J)) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_conjugate_dnorm_dnorm") expect_identical(crpSampler$nObsPerClusID, J) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(0)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- conf$getSamplers('thetaTilde') expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n*J)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), rep(1:n, J)) code <- nimbleCode({ for(i in 1:n) { for(j in 1:J) { y[j, i] ~ dnorm(theta[j, i], 1) theta[j, i] <- thetaTilde[xi[i], j] thetaTilde[i, j] ~ dnorm(0, 1) }} xi[1:n] ~ dCRP(alpha, size = n) }) n <- 5 J <- 3 constants <- list(n = n, J = J) data <- list(y = matrix(rnorm(n*J),J,n)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = matrix(rnorm(J*n), n, J)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') nodes <- model$expandNodeNames('thetaTilde') expect_identical(cn$clusterNodes[[1]], c(matrix(nodes, J, n, byrow = TRUE))) expect_identical(cn$numNodesPerCluster, as.integer(J)) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_conjugate_dnorm_dnorm") expect_identical(crpSampler$nObsPerClusID, J) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(J)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- conf$getSamplers('thetaTilde') expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n*J)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), rep(1:n, each = J)) code <- nimbleCode({ for(i in 1:n) { for(j in 1:J) { y[i, j] ~ dnorm(thetaTilde[xi[i]+1, j], 1) }} for(i in 2:(n+1)) { for(j in 1:J) { thetaTilde[i, j] ~ dnorm(0, 1) }} xi[1:n] ~ dCRP(alpha, size = n) }) n <- 5 J <- 3 constants <- list(n = n, J = J) data <- list(y = matrix(rnorm(n*J),n,J)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = matrix(rnorm(J*(n+1)), n+1, J)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') nodes <- model$expandNodeNames('thetaTilde') expect_identical(cn$clusterNodes[[1]], c(matrix(nodes, J, n+1, byrow = TRUE)[,-1])) expect_identical(cn$numNodesPerCluster, as.integer(J)) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_conjugate_dnorm_dnorm") expect_identical(crpSampler$nObsPerClusID, J) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(0)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- conf$getSamplers('thetaTilde') expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n*J)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), rep(1:n, each = J)) code <- nimbleCode({ for(i in 1:n) { for(j in 1:J) { y[i, j] ~ dnorm(theta[i, j], 1) theta[i,j] <- thetaTilde[xi[i]+1, j] }} for(i in 2:(n+1)) { for(j in 1:J) { thetaTilde[i, j] ~ dnorm(0, 1) }} xi[1:n] ~ dCRP(alpha, size = n) }) n <- 5 J <- 3 constants <- list(n = n, J = J) data <- list(y = matrix(rnorm(n*J),n,J)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = matrix(rnorm(J*(n+1)), n+1, J)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') nodes <- model$expandNodeNames('thetaTilde') expect_identical(cn$clusterNodes[[1]], c(matrix(nodes, J, n+1, byrow = TRUE)[,-1])) expect_identical(cn$numNodesPerCluster, as.integer(J)) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_conjugate_dnorm_dnorm") expect_identical(crpSampler$nObsPerClusID, J) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(J)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- conf$getSamplers('thetaTilde') expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n*J)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), rep(1:n, each = J)) code <- nimbleCode({ for(i in 1:n) { for(j in 1:J) { y[i, j] ~ dnorm(thetaTilde[xi[i]], 1) } thetaTilde[i] ~ dnorm(0, 1) } xi[1:n] ~ dCRP(alpha, size = n) }) n <- 5 J <- 3 constants <- list(n = n, J = J) data <- list(y = matrix(rnorm(n*J),n,J)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = rnorm(n)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') expect_identical(cn$clusterNodes[[1]], model$expandNodeNames('thetaTilde')) expect_identical(cn$numNodesPerCluster, 1L) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_nonconjugate") expect_identical(crpSampler$nObsPerClusID, J) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(0)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- conf$getSamplers('thetaTilde') expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), 1:n) code <- nimbleCode({ for(i in 1:n) { y[i] ~ dnorm(thetaTilde[xi[i]], s2tilde[xi[i]]) s2tilde[i] ~ dunif(0, 10) } for(i in 1:n2) thetaTilde[i] ~ dnorm(0, 1) xi[1:n] ~ dCRP(alpha, size = n) }) n <- 5 n2 <- 4 J <- 3 constants <- list(n = n, n2 = n2, J = J) data <- list(y = rnorm(n)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = rnorm(n2), s2tilde = runif(n)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) expect_silent(conf <- configureMCMC(model, print = FALSE)) expect_error(mcmc <- buildMCMC(conf), "sampler_CRP: In a model with multiple cluster parameters") code <- nimbleCode({ for(i in 1:n) { y[i] ~ dnorm(thetaTilde[xi[i]], s2tilde[xi[i]+1]) s2tilde[i] ~ dunif(0, 10) thetaTilde[i] ~ dnorm(0, 1) } xi[1:n] ~ dCRP(alpha, size = n) }) n <- 5 J <- 3 constants <- list(n = n, J = J) data <- list(y = rnorm(n)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = rnorm(n), s2tilde = runif(n)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) expect_silent(conf <- configureMCMC(model, print = FALSE)) expect_error(mcmc <- buildMCMC(conf), "sampler_CRP: In a model with multiple cluster parameters") code <- nimbleCode({ for(i in 1:n) { y[i] ~ dnorm(theta[i], sd = sigma[i]) theta[i] <- thetaTilde[xi[i]] sigma[i] <- sigmaTilde[xi[i]] sigmaTilde[i] <- 1 / tauTilde[i] thetaTilde[i] ~ dnorm(mu, var = sigmaTilde[i]) tauTilde[i] ~ dgamma(a, b) } xi[1:n] ~ dCRP(alpha, size = n) }) n <- 5 J <- 2 constants <- list(n = n) data <- list(y = rnorm(n)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = rnorm(n), tauTilde = rgamma(n, 1, 1)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) expect_silent(conf <- configureMCMC(model, print = FALSE)) expect_error(mcmc <- buildMCMC(conf), "findClusterNodes: detected that deterministic nodes are being clustered") code <- nimbleCode({ for(i in 1:n) { for(j in 1:J) y[i,j] ~ dnorm(thetaTilde[xi[i],j], 1) thetaTilde[i, 1:J] ~ dmnorm(mn[1:J], iden[1:J,1:J]) } mn[1:J] <- mu*ones[1:J] xi[1:n] ~ dCRP(alpha, size = n) }) n <- 5 J <- 3 constants <- list(n = n, J = J) data <- list(y = matrix(rnorm(n*J),n,J)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = matrix(rnorm(J*n), n, J), iden = diag(3), mu = 0) model <- nimbleModel(code, data = data, constants = constants, inits = inits) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') nodes <- model$expandNodeNames('thetaTilde') expect_identical(cn$clusterNodes[[1]], nodes) expect_identical(cn$numNodesPerCluster, 1L) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_nonconjugate") expect_identical(crpSampler$nObsPerClusID, J) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(0)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- conf$getSamplers('thetaTilde') expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), 1:n) code <- nimbleCode({ for(i in 1:n) { for(j in 1:2) { y[i, j] ~ dnorm(thetaTilde[xi[i], j], 1) } thetaTilde[i, 1] ~ dnorm(0, 1) thetaTilde[i, 2] ~ dnorm(0, 1) } xi[1:n] ~ dCRP(alpha, size = n) }) n <- 5 J <- 2 constants <- list(n = n, J=J) data <- list(y = matrix(rnorm(n*J),n,J)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = matrix(rnorm(J*n), n, J)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') nodes <- model$expandNodeNames('thetaTilde') expect_identical(cn$clusterNodes[[1]], c(matrix(nodes, J, n, byrow = TRUE))) expect_identical(cn$numNodesPerCluster, as.integer(J)) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_conjugate_dnorm_dnorm") expect_identical(crpSampler$nObsPerClusID, J) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(0)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- conf$getSamplers('thetaTilde') expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n*J)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), rep(1:n, J)) code <- nimbleCode({ for(i in 1:n) { y[i, 1:J] ~ dmnorm(thetaTilde[xi[i],1:J], iden[1:J,1:J]) thetaTilde[i, 1:J] ~ dmnorm(mn[1:J], iden[1:J,1:J]) } mn[1:J] <- mu*ones[1:J] xi[1:n] ~ dCRP(alpha, size = n) }) n <- 5 J <- 3 constants <- list(n = n, J = J) data <- list(y = matrix(rnorm(n*J),n,J)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = matrix(rnorm(J*n), n, J), iden = diag(3), mu = 0) model <- nimbleModel(code, data = data, constants = constants, inits = inits) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') nodes <- model$expandNodeNames('thetaTilde') expect_identical(cn$clusterNodes[[1]], nodes) expect_identical(cn$numNodesPerCluster, 1L) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_conjugate_dmnorm_dmnorm") expect_identical(crpSampler$nObsPerClusID, 1) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(0)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- conf$getSamplers('thetaTilde') expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), 1:n) code <- nimbleCode({ for(i in 1:n) { y[i, 1:J] ~ dmnorm(thetaTilde[xi[i],1:J], iden[1:J,1:J]) for(j in 1:J) thetaTilde[i, j] ~ dnorm(0,1) } xi[1:n] ~ dCRP(alpha, size = n) }) n <- 5 J <- 3 constants <- list(n = n, J = J) data <- list(y = matrix(rnorm(n*J),n,J)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = matrix(rnorm(J*n), n, J), iden = diag(J)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') nodes <- model$expandNodeNames('thetaTilde') expect_identical(cn$clusterNodes[[1]], c(matrix(nodes, J, n, byrow = TRUE))) expect_identical(cn$numNodesPerCluster, as.integer(J)) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_nonconjugate") expect_identical(crpSampler$nObsPerClusID, 1) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(0)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- conf$getSamplers('thetaTilde') expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n*J)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), rep(1:n, each = J)) code <- nimbleCode({ for(i in 1:n) { y[i, 1:2] ~ dmnorm(thetaTilde[xi[i],1:2], iden[1:2,1:2]) thetaTilde[i, 1] ~ dnorm(0,1) thetaTilde[i, 2] ~ dnorm(0,1) } xi[1:n] ~ dCRP(alpha, size = n) }) n <- 5 J <- 2 constants <- list(n = n) data <- list(y = matrix(rnorm(n*J),n,J)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = matrix(rnorm(J*n), n, J), iden = diag(J)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') nodes <- model$expandNodeNames('thetaTilde') expect_identical(cn$clusterNodes[[1]], c(matrix(nodes, J, n, byrow = TRUE))) expect_identical(cn$numNodesPerCluster, as.integer(J)) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_nonconjugate") expect_identical(crpSampler$nObsPerClusID, 1) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(0)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- conf$getSamplers('thetaTilde') expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n*J)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), rep(1:n, J)) code <- nimbleCode({ for(i in 1:n) { y1[i] ~ dnorm(thetaTilde1[xi[i]], 1) y2[i] ~ dnorm(thetaTilde2[xi[i]], 1) thetaTilde1[i] ~ dnorm(mu, sigma) thetaTilde2[i] ~ dnorm(mu, sigma) } xi[1:n] ~ dCRP(alpha, size = n) }) n <- 5 constants <- list(n = n) data <- list(y1 = rnorm(n), y2 = rnorm(n)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde1 = rnorm(n), thetaTilde2 = rnorm(n)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') nodes <- model$expandNodeNames('thetaTilde1') expect_identical(cn$clusterNodes[[1]], nodes) expect_identical(cn$numNodesPerCluster, rep(1L, 2)) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_nonconjugate") expect_identical(crpSampler$nObsPerClusID, J) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(0)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- conf$getSamplers('thetaTilde1') expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), 1:n) code <- nimbleCode({ for(i in 1:n) { y[i] ~ dnorm(thetaTilde[xi[i]], 1) } thetaTilde[1] ~ dnorm(mu, sigma) for(i in 2:n) thetaTilde[i] ~ dgamma(1,1) xi[1:n] ~ dCRP(alpha, size = n) }) n <- 5 constants <- list(n = n) data <- list(y = rnorm(n)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = rnorm(n)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') nodes <- model$expandNodeNames('thetaTilde') expect_identical(cn$clusterNodes[[1]], nodes) expect_identical(cn$numNodesPerCluster, 1L) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_nonconjugate") expect_identical(crpSampler$nObsPerClusID, 1) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(0)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- conf$getSamplers('thetaTilde') expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), as.integer(c(2:n, 1))) code <- nimbleCode({ for(i in 3:n) { y[i] ~ dt(thetaTilde[xi[i]], 1, 1) } for(i in 1:2) y[i] ~ dnorm(thetaTilde[xi[i]], 1) for(i in 1:n) thetaTilde[i] ~ dnorm(0,1) xi[1:n] ~ dCRP(alpha, size = n) }) n <- 5 constants <- list(n = n) data <- list(y = rnorm(n)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = rnorm(n)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) expect_silent(conf <- configureMCMC(model, print = FALSE)) expect_error(mcmc <- buildMCMC(conf), "sampler_CRP: In a model with multiple cluster parameters") code <- nimbleCode({ for(i in 2:n) { y[i] ~ dt(thetaTilde[xi[i]], 1, 1) } y[1] ~ dnorm(thetaTilde[xi[1]], 1) for(i in 1:n) thetaTilde[i] ~ dnorm(0,1) xi[1:n] ~ dCRP(alpha, size = n) }) n <- 5 constants <- list(n = n) data <- list(y = rnorm(n)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = rnorm(n)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) expect_silent(conf <- configureMCMC(model, print = FALSE)) expect_error(mcmc <- buildMCMC(conf), "sampler_CRP: Detected unusual indexing") code <- nimbleCode({ for(i in 1:(n-1)) { for(j in 1:J) { y[i, j] ~ dnorm(thetaTilde[xi[i], j], 1) thetaTilde[i, j] ~ dnorm(0, 1) }} for(j in 1:J) { y[n, j] ~ dt(thetaTilde[xi[n], j], 1 ,1) thetaTilde[n, j] ~ dnorm(0, 1) } xi[1:n] ~ dCRP(alpha, size = n) }) n <- 5 J <- 3 constants <- list(n = n, J = J) data <- list(y = matrix(rnorm(n*J),n,J)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = matrix(rnorm(J*n), n, J)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) expect_silent(conf <- configureMCMC(model, print = FALSE)) expect_error(mcmc <- buildMCMC(conf), "sampler_CRP: Detected unusual indexing") code <- nimbleCode({ for(i in 1:n) { y1[i] ~ dnorm(thetaTilde[xi[i], 1], 1) y2[i] ~ dnorm(thetaTilde[xi[i], 2], 1) for(j in 1:2) thetaTilde[i, j] ~ dnorm(0, 1) } xi[1:n] ~ dCRP(alpha, size = n) }) n <- 5 J <- 2 constants <- list(n = n) data <- list(y1 = rnorm(n), y2 = rnorm(n)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = matrix(rnorm(n*J),n,J)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') nodes <- model$expandNodeNames('thetaTilde') expect_identical(cn$clusterNodes[[1]], nodes[1:n]) expect_identical(cn$numNodesPerCluster, rep(1L, 2)) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_nonconjugate") expect_identical(crpSampler$nObsPerClusID, J) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(0)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- conf$getSamplers('thetaTilde') expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n*J)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), rep(1:n, J)) code <- nimbleCode({ for(i in 1:n) { y1[i] ~ dnorm(thetaTilde[xi[i], 1], 1) y2[i] ~ dnorm(thetaTilde[xi[i], 2], 1) thetaTilde[i, 1] ~ dnorm(0, 1) thetaTilde[i, 2] ~ dnorm(0, 1) } xi[1:n] ~ dCRP(alpha, size = n) }) n <- 5 J <- 2 constants <- list(n = n) data <- list(y1 = rnorm(n), y2 = rnorm(n)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = matrix(rnorm(n*J),n,J)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') nodes <- model$expandNodeNames('thetaTilde') expect_identical(cn$clusterNodes[[1]], nodes[1:n]) expect_identical(cn$numNodesPerCluster, rep(1L, 2)) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_nonconjugate") expect_identical(crpSampler$nObsPerClusID, J) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(0)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- conf$getSamplers('thetaTilde') expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n*J)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), rep(1:n, J)) code <- nimbleCode({ for(i in 1:n) { y1[i] ~ dnorm(thetaTilde[xi[i], 1], 1) y2[i] ~ dnorm(thetaTilde[xi[i], 2], 1) thetaTilde[i, 1:2] ~ dmnorm(mn[1:2], iden[1:2,1:2]) } mn[1:2] <- mu*ones[1:2] xi[1:n] ~ dCRP(alpha, size = n) }) n <- 5 J <- 2 constants <- list(n = n) data <- list(y1 = rnorm(n), y2 = rnorm(n)) inits <- list(alpha = 1, xi = rep(1, n), iden = diag(1, 2), thetaTilde = matrix(rnorm(n*J), n, J), ones = rep(1,2)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') nodes <- model$expandNodeNames('thetaTilde') expect_identical(cn$clusterNodes[[1]], nodes) expect_identical(cn$numNodesPerCluster, rep(1L, 2)) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_nonconjugate") expect_identical(crpSampler$nObsPerClusID, J) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(0)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- conf$getSamplers('thetaTilde') expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), 1:n) code <- nimbleCode({ for(i in 1:n) { for(j in 1:J) { y[i,j] ~ dnorm(theta[i], sd = sigma[i,j]) sigma[i,j] <- sigmaTilde[xi[i], j] sigmaTilde[i,j] ~ dinvgamma(a, b) } theta[i] <- thetaTilde[xi[i]] thetaTilde[i] ~ dnorm(mu, phi) } xi[1:n] ~ dCRP(alpha, size = n) }) n <- 5 J <- 2 constants <- list(n = n, J = J) data <- list(y = matrix(rnorm(n*J), n, J)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = rnorm(n), sigmaTilde = matrix(rgamma(n*J, 1, 1), n, J)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') nodes <- model$expandNodeNames('thetaTilde') expect_identical(cn$clusterNodes[[2]], nodes) nodes <- model$expandNodeNames('sigmaTilde') expect_identical(cn$clusterNodes[[1]], c(matrix(nodes, J, n, byrow = TRUE))) expect_identical(cn$numNodesPerCluster, c(2L, 1L)) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_nonconjugate") expect_identical(crpSampler$nObsPerClusID, J) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(J+1)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- c(conf$getSamplers('thetaTilde'), conf$getSamplers('sigmaTilde')) expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n*(J+1))) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), c(1:n, rep(1:n, each = J))) code <- nimbleCode({ for(i in 1:n) { y[i] ~ dnorm(theta[i], sd = sigma[i]) theta[i] <- thetaTilde[xi[i]] sigma[i] <- 1 / tau[i] tau[i] <- tauTilde[xi[i]] thetaTilde[i] ~ dnorm(mu, var = sigmaTilde[i]) sigmaTilde[i] <- 1 / tauTilde[i] tauTilde[i] ~ dgamma(a, b) } xi[1:n] ~ dCRP(alpha, size = n) }) n <- 5 J <- 2 constants <- list(n = n) data <- list(y = rnorm(n)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = rnorm(n), tauTilde = rgamma(n, 1, 1)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') nodes <- model$expandNodeNames('thetaTilde') expect_identical(cn$clusterNodes[[2]], nodes) nodes <- model$expandNodeNames('tauTilde') expect_identical(cn$clusterNodes[[1]], nodes) expect_identical(cn$numNodesPerCluster, rep(1L, 2)) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_nonconjugate") expect_identical(crpSampler$nObsPerClusID, 1) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(3)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- c(conf$getSamplers('thetaTilde'), conf$getSamplers('tauTilde')) expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n*J)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), rep(1:n, J)) code <- nimbleCode({ for(i in 1:n) { for(j in 1:J) { y[i,j] ~ dnorm(thetaTilde[xi[i], 2, j] , var = 1) } } for(i in 1:n) { for(j in 1:J) { for(k in 1:2) { thetaTilde[i, k, j] ~ dnorm(0,1) } } } xi[1:n] ~ dCRP(1, size=n) }) n <- 5 J <- 3 constants <- list(n = n, J = J) inits <- list(xi = rep(1, n), thetaTilde = array(0, c(n,2,J))) y <- matrix(0, nrow = n , ncol= J) data <- list(y = y) model <- nimbleModel(code, data = data, inits = inits, constants = constants) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') nodes <- model$expandNodeNames('thetaTilde') expect_identical(cn$clusterNodes[[1]], c(t(array(nodes, c(n, 2, J))[,2,]))) expect_identical(cn$numNodesPerCluster, as.integer(J)) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_conjugate_dnorm_dnorm") expect_identical(crpSampler$nObsPerClusID, J) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(0)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- conf$getSamplers('thetaTilde')[16:30] expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n*J)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), rep(1:n, each = J)) code <- nimbleCode({ for(i in 1:n) { for(k in 1:2) { for(j in 1:J) { y[k,i,j] ~ dnorm(thetaTilde[k, xi[i], j] , var = 1) } } } for(i in 1:n) { for(j in 1:J) { for(k in 1:2) { thetaTilde[k, i, j] ~ dnorm(0,1) } } } xi[1:n] ~ dCRP(1, size=n) }) n <- 5 J <- 3 constants <- list(n = n, J = J) inits <- list(xi = rep(1, n), thetaTilde = array(0, c(2, n, J))) y <- array(0, c(2, n, J)) data <- list(y = y) model <- nimbleModel(code, data = data, inits = inits, constants = constants) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') nodes <- c(matrix(model$expandNodeNames('thetaTilde[1:2, 1, 1:3]'), J, 2, byrow = TRUE), matrix(model$expandNodeNames('thetaTilde[1:2, 2, 1:3]'), J, 2, byrow = TRUE), matrix(model$expandNodeNames('thetaTilde[1:2, 3, 1:3]'), J, 2, byrow = TRUE), matrix(model$expandNodeNames('thetaTilde[1:2, 4, 1:3]'), J, 2, byrow = TRUE), matrix(model$expandNodeNames('thetaTilde[1:2, 5, 1:3]'), J, 2, byrow = TRUE)) expect_identical(cn$clusterNodes[[1]], nodes) expect_identical(cn$numNodesPerCluster, 6L) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_conjugate_dnorm_dnorm") expect_identical(crpSampler$nObsPerClusID, 2*J) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(0)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- conf$getSamplers('thetaTilde') expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n*J*2)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), rep(1:n, each = J*2)) code <- nimbleCode({ for(i in 1:3) { for(j in 1:4) { y[i,j] ~ dnorm(thetaTilde[xi[3-i+1], j] , var = 1) thetaTilde[i, j] ~ dnorm(0,1) } } xi[1:3] ~ dCRP(1, size=3) }) inits <- list(xi = c(1, 1, 1), thetaTilde = matrix(0, nrow=3, ncol=4)) y <- matrix(5, nrow=3, ncol=4) data <- list(y = y) model <- nimbleModel(code, data = data, inits = inits) expect_error(conf <- configureMCMC(model, print = FALSE), "findClusterNodes: Detected that a cluster parameter is indexed by a function") code <- nimbleCode({ for(i in 1:3) { for(j in 1:4) { y[i,j] ~ dnorm(thetaTilde[xi[i+j], j] , var = 1) thetaTilde[i, j] ~ dnorm(0,1) } } xi[1:7] ~ dCRP(1, size=7) }) inits <- list(xi = rep(1,7), thetaTilde = matrix(0, nrow=3, ncol=4)) y <- matrix(5, nrow=3, ncol=4) data <- list(y = y) model <- nimbleModel(code, data = data, inits = inits) expect_error(conf <- configureMCMC(model, print = FALSE), "findClusterNodes: Detected that a cluster parameter is indexed by a function") code <- nimbleCode({ for(i in 1:3) { for(j in 1:4) { y[i,j] ~ dnorm(thetaTilde[xi[i], xi[j]] , var = 1) thetaTilde[i, j] ~ dnorm(0,1) } } xi[1:4] ~ dCRP(1, size=4) }) inits <- list(xi = rep(1,7), thetaTilde = matrix(0, nrow=3, ncol=4)) y <- matrix(5, nrow=3, ncol=4) data <- list(y = y) model <- nimbleModel(code, data = data, inits = inits) expect_error(conf <- configureMCMC(model, print = FALSE), "findClusterNodes: CRP variable used multiple times") code <- nimbleCode({ for(i in 1:4) { for(j in 1:4) { y[i,j] ~ dnorm(thetaTilde[xi[i], xi[i]] , var = 1) thetaTilde[i, j] ~ dnorm(0,1) } } xi[1:4] ~ dCRP(1, size=4) }) inits <- list(xi = rep(1,7), thetaTilde = matrix(0, nrow=4, ncol=4)) y <- matrix(5, nrow=4, ncol=4) data <- list(y = y) model <- nimbleModel(code, data = data, inits = inits) expect_error(conf <- configureMCMC(model, print = FALSE), "findClusterNodes: CRP variable used multiple times") code <- nimbleCode({ for(i in 1:4) { for(j in 1:4) { y[i,j] ~ dnorm(thetaTilde[xi[i]], var = s2Tilde[xi[j]]) } } for(i in 1:4) thetaTilde[i] ~ dnorm(0,1) for(i in 1:4) s2Tilde[i] ~ dnorm(0,1) xi[1:4] ~ dCRP(1, size=4) }) inits <- list(xi = rep(1,4)) y <- matrix(5, nrow=4, ncol=4) data <- list(y = y) model <- nimbleModel(code, data = data, inits = inits) expect_error(conf <- configureMCMC(model, print = FALSE), "findClusterNodes: found cluster membership parameters that use different indexing variables") code <- nimbleCode({ for(i in 1:n) { y[i] ~ dnorm(b0[xi[i]] + b1[xi[i]]*x[i], var = 1) } for(i in 1:n) { b0[i] ~ dnorm(0,1) b1[i] ~ dnorm(0,1) } xi[1:n] ~ dCRP(1, size=n) }) n <- 5 constants <- list(n = n) data = list(y = rnorm(n)) inits = list(x = rnorm(n), xi = rep(1,n)) model <- nimbleModel(code, data = data, inits = inits, constants = constants) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') nodes <- model$expandNodeNames('b0') expect_identical(cn$clusterNodes[[1]], nodes) nodes <- model$expandNodeNames('b1') expect_identical(cn$clusterNodes[[2]], nodes) expect_identical(cn$numNodesPerCluster, rep(1L, 2)) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_nonconjugate") expect_identical(crpSampler$nObsPerClusID, 1) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(1)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- c(conf$getSamplers('b0'), conf$getSamplers('b1')) expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n*2)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), rep(1:n, 2)) code <- nimbleCode({ for(i in 1:n) { y[i] ~ dnorm(beta[xi[i], 1] + beta[xi[i], 2]*x[i], var = 1) } for(i in 1:n) { beta[i,1] ~ dnorm(0,1) beta[i,2] ~ dnorm(0,1) } xi[1:n] ~ dCRP(1, size = n) }) n <- 5 constants <- list(n = n) data = list(y = rnorm(n)) inits = list(x = rnorm(n), xi = rep(1,n)) model <- nimbleModel(code, data = data, inits = inits, constants = constants) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') nodes <- model$expandNodeNames('beta') expect_identical(cn$clusterNodes[[1]], nodes[1:n]) expect_identical(cn$clusterNodes[[2]], nodes[(n+1):(2*n)]) expect_identical(cn$numNodesPerCluster, rep(1L, 2)) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_nonconjugate") expect_identical(crpSampler$nObsPerClusID, 1) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(1)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- conf$getSamplers('beta') expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n*2)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), rep(1:n, 2)) code <- nimbleCode({ for(i in 1:n) { y[i] ~ dnorm(beta[xi[i], 1] + beta[xi[i], 2]*x[i], var = 1) } for(i in 1:n) for(j in 1:2) beta[i,j] ~ dnorm(0,1) xi[1:n] ~ dCRP(1, size=n) }) n <- 5 constants <- list(n = n) data = list(y = rnorm(n)) inits = list(x = rnorm(n), xi = rep(1,n)) model <- nimbleModel(code, data = data, inits = inits, constants = constants) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') nodes <- model$expandNodeNames('beta') expect_identical(cn$clusterNodes[[1]], nodes[1:n]) expect_identical(cn$clusterNodes[[2]], nodes[(n+1):(2*n)]) expect_identical(cn$numNodesPerCluster, rep(1L, 2)) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_nonconjugate") expect_identical(crpSampler$nObsPerClusID, 1) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(1)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- conf$getSamplers('beta') expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n*2)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), rep(1:n, 2)) code <- nimbleCode({ for(i in 1:n) { y[i] ~ dnorm(inprod(beta[1:J, xi[i]], x[i,1:J]), var = 1) } for(i in 1:n) for(j in 1:J) beta[j, i] ~ dnorm(0,1) xi[1:n] ~ dCRP(1, size = n) }) n <- 5 J <- 2 constants <- list(n = n, J = J) data = list(y = rnorm(n)) inits = list(x = matrix(rnorm(n*J),n,J), xi = rep(1,n)) model <- nimbleModel(code, data = data, inits = inits, constants = constants) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') nodes <- model$expandNodeNames('beta') expect_identical(cn$clusterNodes[[1]], nodes) expect_identical(cn$numNodesPerCluster, as.integer(J)) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_nonconjugate") expect_identical(crpSampler$nObsPerClusID, 1) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(0)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- conf$getSamplers('beta') expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n*2)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), rep(1:n, each = J)) code <- nimbleCode({ for(i in 1:n) { y[i] ~ dnorm(inprod(beta[1:J, xi[i]], x[i,1:J]), var = 1) } for(i in 1:n) beta[1:J, i] ~ dmnorm(z[1:J], pr[1:J,1:J]) xi[1:n] ~ dCRP(1, size=n) }) n <- 5 J <- 2 constants <- list(n = n, J = J) data = list(y = rnorm(n)) inits = list(x = matrix(rnorm(n*J),n,J), xi = rep(1,n), pr = diag(J)) model <- nimbleModel(code, data = data, inits = inits, constants = constants) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') nodes <- model$expandNodeNames('beta') expect_identical(cn$clusterNodes[[1]], nodes) expect_identical(cn$numNodesPerCluster, as.integer(1)) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_nonconjugate") expect_identical(crpSampler$nObsPerClusID, 1) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(0)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- conf$getSamplers('beta') expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), 1:n) code <- nimbleCode({ for(i in 1:4) { for(j in 2:3) { y[i,j] ~ dnorm(mu[xi[i]] + y[i,j-1], 1) } } for(i in 1:4) { mu[i] ~ dnorm(0,1) } xi[1:4] ~ dCRP(1, size=4) }) data = list(y =matrix( rnorm(4*3), 4 ,3)) inits = list(xi = rep(1,4)) model <- nimbleModel(code, data = data, inits = inits) expect_silent(conf <- configureMCMC(model, print = FALSE)) expect_error(mcmc <- buildMCMC(conf), "sampler_CRP: Variables being clustered must be conditionally independent") code <- nimbleCode({ for(i in 1:4) { for(j in 2:3) { y[i,j] ~ dnorm(mu[xi[i]], exp(y[i,j-1])) } } for(i in 1:4) { mu[i] ~ dnorm(0,1) } xi[1:4] ~ dCRP(1, size=4) }) data = list(y =matrix( rnorm(4*3), 4 ,3)) inits = list(xi = rep(1,4)) model <- nimbleModel(code, data = data, inits = inits) expect_silent(conf <- configureMCMC(model, print = FALSE)) expect_error(mcmc <- buildMCMC(conf), "sampler_CRP: Variables being clustered must be conditionally independent") code <- nimbleCode({ for(i in 2:4) { for(j in 1:3) { y[i,j] ~ dnorm(mu[xi[i]] + y[i-1,j], 1) } } for(i in 1:4) { mu[i] ~ dnorm(0,1) } xi[1:4] ~ dCRP(1, size=4) }) data = list(y =matrix( rnorm(4*3), 4 ,3)) inits = list(xi = rep(1,4)) model <- nimbleModel(code, data = data, inits = inits) expect_silent(conf <- configureMCMC(model, print = FALSE)) expect_error(mcmc <- buildMCMC(conf), "sampler_CRP: Variables being clustered must be conditionally independent") code <- nimbleCode({ for(i in 1:3) { for(j in 1:3) { y[i,j] ~ dnorm(mu[xi[i]] + y[i+1,j], 1) } } for(i in 1:4) { mu[i] ~ dnorm(0,1) } xi[1:4] ~ dCRP(1, size=4) }) data = list(y =matrix( rnorm(4*3), 4 ,3)) inits = list(xi = rep(1,4)) model <- nimbleModel(code, data = data, inits = inits) expect_silent(conf <- configureMCMC(model, print = FALSE)) expect_error(mcmc <- buildMCMC(conf), "sampler_CRP: Variables being clustered must be conditionally independent") code <- nimbleCode({ for(i in 1:4) { y[i,1] ~ dnorm(mu[xi[i]], 1) for(j in 2:3) { y[i,j] ~ dnorm(mu[xi[i]] + y[i,j-1], 1) } } for(i in 1:4) { mu[i] ~ dnorm(0,1) } xi[1:4] ~ dCRP(1, size=4) }) data = list(y =matrix( rnorm(4*3), 4 ,3)) inits = list(xi = rep(1,4)) model <- nimbleModel(code, data = data, inits = inits) expect_silent(conf <- configureMCMC(model, print = FALSE)) expect_error(mcmc <- buildMCMC(conf), "sampler_CRP: Variables being clustered must be conditionally independent") code <- nimbleCode({ for(i in 1:n) { y[i,1:2] ~ dmnorm(mu[xi[i], 1:2], cov = sigma[xi[i],1:2,1:2]) mu[i, 1:2] ~ dmnorm(mu0[1:2], iden[1:2,1:2]) sigma[i,1:2,1:2] ~ dinvwish(S[1:2,1:2], nu) } xi[1:n] ~ dCRP(1, size=n) }) n <- 5 data = list(y =matrix( rnorm(n*2), n ,2)) sigma <- array(0, c(n, 2, 2)) for(i in 1:n) sigma[i, 1:2, 1:2] <- diag(2) inits = list(xi = rep(1,n), iden = diag(2), sigma = sigma, S = diag(2)) model <- nimbleModel(code, constants = list(n = n), data = data, inits = inits) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') nodes <- model$expandNodeNames('mu') expect_identical(cn$clusterNodes[[2]], nodes) nodes <- model$expandNodeNames('sigma') expect_identical(cn$clusterNodes[[1]], nodes) expect_identical(cn$numNodesPerCluster, rep(1L, 2)) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_nonconjugate") expect_identical(crpSampler$nObsPerClusID, 1) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(1)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- c(conf$getSamplers('mu'), conf$getSamplers('sigma')) expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n*2)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), rep(1:n, 2)) sigma <- array(0, c(n, 2, 2)) for(i in 1:n) sigma[i, 1:2, 1:2] <- diag(2) code <- nimbleCode({ for(i in 1:n) { y[i,1:2] ~ dmnorm(mu[xi[i], 1:2], cov = sigma[xi[i],1:2,1:2]) mu[i, 1:2] ~ dmnorm(mu0[1:2], cov = sigmaAux[i,1:2,1:2]) sigmaAux[i,1:2,1:2] <- sigma[i,1:2,1:2]/kappa sigma[i,1:2,1:2] ~ dinvwish(S[1:2,1:2], nu) } xi[1:n] ~ dCRP(1, size=n) }) n <- 5 data = list(y =matrix( rnorm(n*2), n ,2)) inits = list(xi = rep(1,n), S = diag(2), sigma = sigma, kappa = 1) model <- nimbleModel(code, constants = list(n = n), data = data, inits = inits) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') nodes <- model$expandNodeNames('mu') expect_identical(cn$clusterNodes[[2]], nodes) nodes <- model$expandNodeNames('sigma') expect_identical(cn$clusterNodes[[1]], nodes) expect_identical(cn$numNodesPerCluster, rep(1L, 2)) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_conjugate_dmnorm_invwish_dmnorm") expect_identical(crpSampler$nObsPerClusID, 1) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(1)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- c(conf$getSamplers('mu'), conf$getSamplers('sigma')) expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n*2)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), rep(1:n, 2)) code <- nimbleCode({ for(i in 1:n) { for(j in 1:2) { y[i, j,1:2] ~ dmnorm(mu[xi[i], j, 1:2], cov = sigma[xi[i], j, 1:2,1:2]) mu[i, j, 1:2] ~ dmnorm(mu0[1:2], cov = sigmaAux[i, j, 1:2,1:2]) sigmaAux[i, j, 1:2,1:2] <- sigma[i, j, 1:2,1:2]/kappa sigma[i, j, 1:2,1:2] ~ dinvwish(S[1:2,1:2], nu) }} xi[1:n] ~ dCRP(1, size=n) }) n <- 5 sigma <- array(0, c(n, 2, 2, 2)) for(i in 1:n) for(j in 1:2) sigma[i, j, 1:2, 1:2] <- diag(2) data = list(y =array(rnorm(n*2*2), c(n, 2, 2))) inits = list(xi = rep(1,n), kappa = 1, sigma = sigma, S = diag(2)) model <- nimbleModel(code, constants = list(n=n), data = data, inits = inits) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') nodes <- model$expandNodeNames('mu') expect_identical(cn$clusterNodes[[2]], c(matrix(nodes, 2, n, byrow = TRUE))) nodes <- model$expandNodeNames('sigma') expect_identical(cn$clusterNodes[[1]], c(matrix(nodes, 2, n, byrow = TRUE))) expect_identical(cn$numNodesPerCluster, rep(2L, 2)) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_conjugate_dmnorm_invwish_dmnorm") expect_identical(crpSampler$nObsPerClusID, 2) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(2)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- c(conf$getSamplers('mu'), conf$getSamplers('sigma')) expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n*2*2)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), rep(rep(1:n, each = 2), 2)) code <- nimbleCode({ for(i in 1:n) { for(j in 1:2) { y[i, j,1:2] ~ dmnorm(mu[xi[i], j, 1:2], cov = sigma[xi[i], j, 1:2,1:2]) mu[i, j, 1:2] ~ dmnorm(mu0[i, 1:2], cov = sigmaAux[i, j, 1:2,1:2]) sigmaAux[i, j, 1:2,1:2] <- sigma[i, j, 1:2,1:2]/kappa sigma[i, j, 1:2,1:2] ~ dinvwish(S[1:2,1:2], nu) }} xi[1:n] ~ dCRP(1, size=n) }) n <- 5 data = list(y =array(rnorm(n*2*2), c(n, 2, 2))) inits = list(xi = rep(1,n), kappa = 1, S = diag(2), sigma = sigma) model <- nimbleModel(code, data = data, inits = inits, constants = list(n = n)) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') nodes <- model$expandNodeNames('mu') expect_identical(cn$clusterNodes[[2]], c(matrix(nodes, 2, n, byrow = TRUE))) nodes <- model$expandNodeNames('sigma') expect_identical(cn$clusterNodes[[1]], c(matrix(nodes, 2, n, byrow = TRUE))) expect_identical(cn$numNodesPerCluster, rep(2L, 2)) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_nonconjugate") expect_identical(crpSampler$nObsPerClusID, 2) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(2)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- c(conf$getSamplers('mu'), conf$getSamplers('sigma')) expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n*2*2)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), rep(rep(1:n, each = 2), 2)) code <- nimbleCode({ for(i in 1:n) { for(j in 1:2) { y[i, j,1:2] ~ dmnorm(mu[xi[i], j, 1:2], cov = sigma[xi[i], j, 1:2,1:2]) mu[i, j, 1:2] ~ dmnorm(mu0[j, 1:2], cov = sigmaAux[i, j, 1:2,1:2]) sigmaAux[i, j, 1:2,1:2] <- sigma[i, j, 1:2,1:2]/kappa sigma[i, j, 1:2,1:2] ~ dinvwish(S[1:2,1:2], nu) }} xi[1:n] ~ dCRP(1, size=n) }) n <- 5 data = list(y =array(rnorm(n*2*2), c(n, 2, 2))) inits = list(xi = rep(1,n), kappa = 1, sigma = sigma, S = diag(2)) model <- nimbleModel(code, data = data, inits = inits, constants = list(n=n)) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') nodes <- model$expandNodeNames('mu') expect_identical(cn$clusterNodes[[2]], c(matrix(nodes, 2, n, byrow = TRUE))) nodes <- model$expandNodeNames('sigma') expect_identical(cn$clusterNodes[[1]], c(matrix(nodes, 2, n, byrow = TRUE))) expect_identical(cn$numNodesPerCluster, rep(2L, 2)) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_conjugate_dmnorm_invwish_dmnorm") expect_identical(crpSampler$nObsPerClusID, 2) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(2)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- c(conf$getSamplers('mu'), conf$getSamplers('sigma')) expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n*2*2)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), rep(rep(1:n, each = 2), 2)) code <- nimbleCode({ for(i in 1:n) { for(j in 1:2) { y[i, j,1:2] ~ dmnorm(mu[xi[i], j, 1:2], cov = sigma[xi[i], j, 1:2,1:2]) mu[i, j, 1:2] ~ dmnorm(mu0[1:2], cov = pr[1:2,1:2]) sigma[i, j, 1:2,1:2] ~ dinvwish(S[1:2,1:2], nu) }} xi[1:n] ~ dCRP(1, size=n) }) n <- 5 data = list(y =array(rnorm(n*2*2), c(n, 2, 2))) inits = list(xi = rep(1,n), sigma = sigma, pr = diag(2), S = diag(2)) model <- nimbleModel(code, data = data, inits = inits, constants = list(n=n)) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') nodes <- model$expandNodeNames('mu') expect_identical(cn$clusterNodes[[2]], c(matrix(nodes, 2, n, byrow = TRUE))) nodes <- model$expandNodeNames('sigma') expect_identical(cn$clusterNodes[[1]], c(matrix(nodes, 2, n, byrow = TRUE))) expect_identical(cn$numNodesPerCluster, rep(2L, 2)) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_nonconjugate") expect_identical(crpSampler$nObsPerClusID, 2) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(2)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- c(conf$getSamplers('mu'), conf$getSamplers('sigma')) expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n*2*2)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), rep(rep(1:n, each = 2), 2)) code <- nimbleCode({ for(i in 1:n) { for(j in 1:2) { y[i, j, 1:2] ~ dmnorm(mu[xi[i], j, 1:2], cov = sigma[xi[i], 1:2,1:2]) mu[i, j, 1:2] ~ dmnorm(mu0[1:2], cov = sigmaAux[i, 1:2,1:2]) } sigmaAux[i, 1:2,1:2] <- sigma[i, 1:2,1:2]/kappa sigma[i, 1:2,1:2] ~ dinvwish(S[1:2,1:2], nu) } xi[1:n] ~ dCRP(1, size=n) }) sigma <- array(0, c(n, 2, 2)) for(i in 1:n) sigma[i, 1:2, 1:2] <- diag(2) n <- 5 data = list(y =array(rnorm(n*2*2), c(n, 2, 2))) inits = list(xi = rep(1,n), sigma = sigma, S = diag(2), kappa = 1) model <- nimbleModel(code, data = data, inits = inits, constants = list(n = n)) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') nodes <- model$expandNodeNames('mu') expect_identical(cn$clusterNodes[[2]], c(matrix(nodes, 2, n, byrow = TRUE))) nodes <- model$expandNodeNames('sigma') expect_identical(cn$clusterNodes[[1]], nodes) expect_identical(cn$numNodesPerCluster, c(1L, 2L)) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_nonconjugate") expect_identical(crpSampler$nObsPerClusID, 2) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(1)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- c(conf$getSamplers('mu'), conf$getSamplers('sigma')) expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n*3)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), c(rep(1:n, each = 2), 1:n)) code <- nimbleCode({ for(i in 1:n) { for(j in 1:2) y[i, j,1:2] ~ dmnorm(mu[xi[i], 1:2], cov = sigma[xi[i], 1:2,1:2]) mu[i, 1:2] ~ dmnorm(mu0[1:2], cov = sigmaAux[i, 1:2,1:2]) sigmaAux[i, 1:2,1:2] <- sigma[i, 1:2,1:2]/kappa sigma[i, 1:2,1:2] ~ dinvwish(S[1:2,1:2], nu) } xi[1:n] ~ dCRP(1, size=n) }) n <- 5 data = list(y =array(rnorm(n*2*2), c(5, 2, 2))) inits = list(xi = rep(1,n), kappa = 1, S = diag(2), sigma = sigma) model <- nimbleModel(code, data = data, inits = inits, constants = list(n=n)) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') nodes <- model$expandNodeNames('mu') expect_identical(cn$clusterNodes[[2]], nodes) nodes <- model$expandNodeNames('sigma') expect_identical(cn$clusterNodes[[1]], nodes) expect_identical(cn$numNodesPerCluster, rep(1L, 2)) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_nonconjugate") expect_identical(crpSampler$nObsPerClusID, 2) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(1)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- c(conf$getSamplers('mu'), conf$getSamplers('sigma')) expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n*2)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), rep(1:n, 2)) code <- nimbleCode({ for(i in 1:n) { y[i,1:2] ~ dmnorm(mu[xi[i], 1:2], cov = sigma[1:2,1:2]) mu[i, 1:2] ~ dmnorm(mu0[1:2], iden[1:2,1:2]) } xi[1:n] ~ dCRP(1, size=n) }) n <- 5 data = list(y =matrix( rnorm(n*2), n ,2)) inits = list(xi = rep(1,n), iden = diag(2), sigma = diag(2)) model <- nimbleModel(code, data = data, inits = inits, constants = list(n=n)) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') nodes <- model$expandNodeNames('mu') expect_identical(cn$clusterNodes[[1]], nodes) expect_identical(cn$numNodesPerCluster, 1L) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_conjugate_dmnorm_dmnorm") expect_identical(crpSampler$nObsPerClusID, 1) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(0)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- conf$getSamplers('mu') expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), 1:n) code <- nimbleCode({ for(i in 1:4) y[i] ~ dnorm(thetaTilde[xi[i]], 1) thetaTilde[1] ~ dnorm(a,1) for(i in 2:4) thetaTilde[i] ~ dnorm(thetaTilde[i-1], 1) xi[1:4] ~ dCRP(1, size=4) a ~ dunif(0,1) }) data = list(y = rnorm(4)) inits = list(xi = rep(1,4)) model <- nimbleModel(code, data = data, inits = inits) expect_silent(conf <- configureMCMC(model, print = FALSE)) expect_error(mcmc <- buildMCMC(conf), "sampler_CRP: cluster parameters must be independent across clusters") code <- nimbleCode({ for(i in 1:4) y[i] ~ dnorm(thetaTilde[xi[i]], 1) thetaTilde[4] ~ dnorm(0,1) for(i in 1:3) thetaTilde[i] ~ dnorm(thetaTilde[i+1], 1) xi[1:4] ~ dCRP(1, size=4) }) data = list(y = rnorm(4)) inits = list(xi = rep(1,4)) model <- nimbleModel(code, data = data, inits = inits) expect_silent(conf <- configureMCMC(model, print = FALSE)) expect_error(mcmc <- buildMCMC(conf), "sampler_CRP: cluster parameters must be independent across clusters") code <- nimbleCode({ for(i in 1:4) y[i] ~ dnorm(thetaTilde[xi[i]], 1) thetaTilde[1:4] ~ dmnorm(z[1:4], iden[1:4,1:4]) xi[1:4] ~ dCRP(1, size=4) }) data = list(y = rnorm(4)) inits = list(xi = rep(1,4), iden = diag(4)) model <- nimbleModel(code, data = data, inits = inits) expect_error(conf <- configureMCMC(model, print = FALSE), "Cannot determine wrapped sampler for cluster parameter") code <- nimbleCode({ for(i in 1:4) { y[i] ~ dnorm(thetaTilde[xi[i]], 1) thetaTilde[i] ~ dnorm(i, 1) } xi[1:4] ~ dCRP(1, size=4) }) n <- 4 data = list(y = rnorm(4)) inits = list(xi = rep(1,4)) model <- nimbleModel(code, data = data, inits = inits) cn <- nimble:::findClusterNodes(model, 'xi[1:4]') nodes <- model$expandNodeNames('thetaTilde') expect_identical(cn$clusterNodes[[1]], nodes) expect_identical(cn$numNodesPerCluster, 1L) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_nonconjugate") expect_identical(crpSampler$nObsPerClusID, 1) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(0)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- conf$getSamplers('thetaTilde') expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), 1:n) code <- nimbleCode({ for(i in 1:4) y[i] ~ dnorm(thetaTilde[xi[i]], 1) for(i in 1:3) thetaTilde[i] ~ dnorm(0, 1) thetaTilde[4] ~ dnorm(5, 2) xi[1:4] ~ dCRP(1, size=4) }) n <- 4 data = list(y = rnorm(4)) inits = list(xi = rep(1,4)) model <- nimbleModel(code, data = data, inits = inits) cn <- nimble:::findClusterNodes(model, 'xi[1:4]') nodes <- model$expandNodeNames('thetaTilde') expect_identical(cn$clusterNodes[[1]], nodes) expect_identical(cn$numNodesPerCluster, 1L) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_nonconjugate") expect_identical(crpSampler$nObsPerClusID, 1) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(0)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- conf$getSamplers('thetaTilde') expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), 1:n) code <- nimbleCode({ for(i in 1:3) { y[i] ~ dnorm(thetaTilde[xi[i]], 1) } thetaTilde[1] ~ dnorm(0, 1) thetaTilde[2] ~ dgamma(1, 1) thetaTilde[3] ~ dnorm(5, 1) xi[1:3] ~ dCRP(alpha, size = 3) }) n <- 3 constants <- list(n = n) data <- list(y = rnorm(n)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = rnorm(n)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) cn <- nimble:::findClusterNodes(model, 'xi[1:4]') nodes <- model$expandNodeNames('thetaTilde') expect_identical(cn$clusterNodes[[1]], nodes) expect_identical(cn$numNodesPerCluster, 1L) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_nonconjugate") expect_identical(crpSampler$nObsPerClusID, 1) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(0)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- conf$getSamplers('thetaTilde') expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), 1:n) code <- nimbleCode({ for(i in 1:3) { y[i] ~ dnorm(theta[i], 1) theta[i] <- thetaTilde[xi[i]] } thetaTilde[1] ~ dnorm(0, 1) thetaTilde[2] ~ dgamma(1, 1) thetaTilde[3] ~ dnorm(5, 1) xi[1:3] ~ dCRP(alpha, size = 3) }) n <- 3 constants <- list(n = n) data <- list(y = rnorm(n)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = rnorm(n)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) cn <- nimble:::findClusterNodes(model, 'xi[1:4]') nodes <- model$expandNodeNames('thetaTilde') expect_identical(cn$clusterNodes[[1]], nodes) expect_identical(cn$numNodesPerCluster, 1L) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_nonconjugate") expect_identical(crpSampler$nObsPerClusID, 1) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(1)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- conf$getSamplers('thetaTilde') expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), 1:n) code <- nimbleCode({ for(i in 1:3) { y[i] ~ dnorm(theta[i], 1) thetaTilde[i] ~ dnorm(0,1) } theta[1] <- thetaTilde[xi[1]] theta[2] <- exp(thetaTilde[xi[2]]) theta[3] <- thetaTilde[xi[3]] xi[1:3] ~ dCRP(alpha, size = 3) }) n <- 3 constants <- list(n = n) data <- list(y = rnorm(n)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = rnorm(n)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) expect_silent(conf <- configureMCMC(model, print = FALSE)) expect_error(mcmc <- buildMCMC(conf), "sampler_CRP: Detected unusual indexing") code <- nimbleCode({ for(i in 1:4) { y[i] ~ dnorm(theta[i], 1) thetaTilde[i] ~ dnorm(0,1) } for(i in 1:2) theta[i] <- thetaTilde[xi[i]] for(j in 3:4) theta[j] <- exp(thetaTilde[xi[j]]) xi[1:4] ~ dCRP(alpha, size = 4) }) n <- 4 constants <- list(n = n) data <- list(y = rnorm(n)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = rnorm(n)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) expect_silent(conf <- configureMCMC(model, print = FALSE)) expect_error(mcmc <- buildMCMC(conf), "sampler_CRP: differing number of clusters") code <- nimbleCode({ for(i in 1:n) { for(j in 1:J) { y[i, j] ~ dnorm(thetaTilde[xi[i], j], 1) thetaTilde[i, j] ~ dnorm(i, 1) }} xi[1:n] ~ dCRP(alpha, size = n) }) n <- 5 J <- 3 constants <- list(n = n, J = J) data <- list(y = matrix(rnorm(n*J),n,J)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = matrix(rnorm(J*n), n, J)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') nodes <- model$expandNodeNames('thetaTilde') expect_identical(cn$clusterNodes[[1]], c(matrix(nodes, J, n, byrow = TRUE))) expect_identical(cn$numNodesPerCluster, as.integer(J)) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_nonconjugate") expect_identical(crpSampler$nObsPerClusID, J) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(0)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- conf$getSamplers('thetaTilde') expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n*J)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), rep(1:n, each = J)) code <- nimbleCode({ for(i in 1:n) { for(j in 1:J) { y[i, j] ~ dnorm(thetaTilde[xi[i], j], 1) thetaTilde[i, j] ~ dnorm(j, 1) }} xi[1:n] ~ dCRP(alpha, size = n) }) n <- 5 J <- 3 constants <- list(n = n, J = J) data <- list(y = matrix(rnorm(n*J),n,J)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = matrix(rnorm(J*n), n, J)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') nodes <- model$expandNodeNames('thetaTilde') expect_identical(cn$clusterNodes[[1]], c(matrix(nodes, J, n, byrow = TRUE))) expect_identical(cn$numNodesPerCluster, as.integer(J)) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_conjugate_dnorm_dnorm") expect_identical(crpSampler$nObsPerClusID, J) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(0)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- conf$getSamplers('thetaTilde') expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n*J)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), rep(1:n, each = J)) code <- nimbleCode({ for(i in 1:n) { y[i, 1] ~ dnorm(thetaTilde[xi[i], 1], 1) y[i, 2] ~ dgamma(thetaTilde[xi[i], 2], 1) thetaTilde[i, 1] ~ dnorm(0, 1) thetaTilde[i, 2] ~ dgamma(1, 1) } xi[1:n] ~ dCRP(alpha, size = n) }) n <- 5 J <- 2 constants <- list(n = n, J = J) data <- list(y = matrix(rnorm(n*J),n,J)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = cbind(rnorm(n), rgamma(n,1,1))) model <- nimbleModel(code, data = data, constants = constants, inits = inits) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') nodes <- model$expandNodeNames('thetaTilde') expect_identical(cn$clusterNodes[[1]], nodes[1:n]) expect_identical(cn$clusterNodes[[2]], nodes[(n+1):(2*n)]) expect_identical(cn$numNodesPerCluster, rep(1L, 2)) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_nonconjugate") expect_identical(crpSampler$nObsPerClusID, J) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(0)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- conf$getSamplers('thetaTilde') expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n*J)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), rep(1:n, J)) code <- nimbleCode({ for(i in 1:n) { for(j in 1:J) { y[i, j] ~ dnorm(thetaTilde[xi[i], j], 1) } thetaTilde[i, 1] ~ dnorm(0, 1) thetaTilde[i, 2] ~ dgamma(3, 1) thetaTilde[i, 3] ~ dnorm(5, 1) } xi[1:n] ~ dCRP(alpha, size = n) }) n <- 5 J <- 3 constants <- list(n = n, J = J) data <- list(y = matrix(rnorm(n*J),n,J)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = matrix(rnorm(J*n), n, J)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') nodes <- model$expandNodeNames('thetaTilde') expect_identical(cn$clusterNodes[[1]], c(matrix(nodes, J, n, byrow = TRUE))) expect_identical(cn$numNodesPerCluster, as.integer(J)) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_nonconjugate") expect_identical(crpSampler$nObsPerClusID, J) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(0)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- conf$getSamplers('thetaTilde') expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n*J)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), rep(1:n, J)) code <- nimbleCode({ for(i in 1:n) { for(j in 1:J) { y[i, j] ~ dnorm(thetaTilde[xi[i], j], 1) } thetaTilde[i, 1] ~ dnorm(0,1) thetaTilde[i, 2] ~ dnorm(thetaTilde[i,1], 1) thetaTilde[i, 3] ~ dnorm(thetaTilde[i,2], 1) } xi[1:n] ~ dCRP(alpha, size = n) }) n <- 5 J <- 3 constants <- list(n = n, J = J) data <- list(y = matrix(rnorm(n*J),n,J)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = matrix(rnorm(J*n), n, J)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') nodes <- model$expandNodeNames('thetaTilde') expect_identical(cn$clusterNodes[[1]], c(matrix(nodes, J, n, byrow = TRUE))) expect_identical(cn$numNodesPerCluster, as.integer(J)) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_nonconjugate") expect_identical(crpSampler$nObsPerClusID, J) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(0)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- conf$getSamplers('thetaTilde') expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n*J)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), rep(1:n, J)) code <- nimbleCode({ for(i in 1:n) { for(j in 1:J) { y[i, j] ~ dnorm(thetaTilde[xi[i], j], var = s2tilde[xi[i]]) thetaTilde[i, j] ~ dnorm(0, 1) } s2tilde[i] ~ dinvgamma(1,1) } xi[1:n] ~ dCRP(alpha, size = n) }) n <- 5 J <- 3 constants <- list(n = n, J = J) data <- list(y = matrix(rnorm(n*J),n,J)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = matrix(rnorm(J*n), n, J), s2tilde = rgamma(n, 1, 1)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') nodes <- model$expandNodeNames('s2tilde') expect_identical(cn$clusterNodes[[1]], nodes) nodes <- model$expandNodeNames('thetaTilde') expect_identical(cn$clusterNodes[[2]], c(matrix(nodes, J, n, byrow = TRUE))) expect_identical(cn$numNodesPerCluster, c(1L, 3L)) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_nonconjugate") expect_identical(crpSampler$nObsPerClusID, J) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(1)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- conf$getSamplers(c('thetaTilde', 's2tilde')) expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n*(J+1))) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), c(1:n, rep(1:n, each = J))) code <- nimbleCode({ for(i in 1:n) { for(j in 1:J) { y[i, j] ~ dnorm(thetaTilde[xi[i]], var = s2tilde[xi[i]]) } thetaTilde[i] ~ dnorm(0, 1) s2tilde[i] ~ dinvgamma(1,1) } xi[1:n] ~ dCRP(alpha, size = n) }) n <- 5 J <- 3 constants <- list(n = n, J = J) data <- list(y = matrix(rnorm(n*J),n,J)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = rnorm(n), s2tilde = rgamma(n, 1, 1)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') nodes <- model$expandNodeNames('s2tilde') expect_identical(cn$clusterNodes[[1]], nodes) nodes <- model$expandNodeNames('thetaTilde') expect_identical(cn$clusterNodes[[2]], nodes) expect_identical(cn$numNodesPerCluster, c(1L, 1L)) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_nonconjugate") expect_identical(crpSampler$nObsPerClusID, J) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(1)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- conf$getSamplers(c('thetaTilde', 's2tilde')) expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n*2)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), rep(1:n, 2)) code <- nimbleCode({ for(i in 1:n) { for(j in 1:J) { y[i, j] ~ dnorm(thetaTilde[xi[i], j], var = s2tilde[xi[i], j]) thetaTilde[i, j] ~ dnorm(theta0, var = s2tilde[i, j]/kappa) s2tilde[i, j] ~ dinvgamma(1,1) } } xi[1:n] ~ dCRP(alpha, size = n) }) n <- 5 J <- 3 constants <- list(n = n, J = J) data <- list(y = matrix(rnorm(n*J),n,J)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = matrix(rnorm(J*n), n, J), s2tilde = matrix(rgamma(J*n, 1, 1),n,J)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') nodes <- model$expandNodeNames('s2tilde') expect_identical(cn$clusterNodes[[1]], c(matrix(nodes, J, n, byrow = TRUE))) nodes <- model$expandNodeNames('thetaTilde') expect_identical(cn$clusterNodes[[2]], c(matrix(nodes, J, n, byrow = TRUE))) expect_identical(cn$numNodesPerCluster, rep(as.integer(J), 2)) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_conjugate_dnorm_invgamma_dnorm") expect_identical(crpSampler$nObsPerClusID, J) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(J)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- conf$getSamplers(c('thetaTilde', 's2tilde')) expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n*J*2)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), rep(rep(1:n, each = J), 2)) code <- nimbleCode({ for(i in 1:n) { for(j in 1:J) { y[i, j] ~ dnorm(thetaTilde[xi[i], j], var = s2tilde[xi[i]+1, j]) thetaTilde[i, j] ~ dnorm(theta0, var = s2tilde[i+1, j]/kappa) } } for(i in 1:(n+1)) { for(j in 1:J) { s2tilde[i, j] ~ dinvgamma(1,1) } } xi[1:n] ~ dCRP(alpha, size = n) }) n <- 5 J <- 3 constants <- list(n = n, J = J) data <- list(y = matrix(rnorm(n*J),n,J)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = matrix(rnorm(J*n), n, J), s2tilde = matrix(rgamma(J*(n+1), 1, 1),n+1,J)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') nodes <- model$expandNodeNames('s2tilde') expect_identical(cn$clusterNodes[[1]], c(matrix(nodes, J, n+1, byrow = TRUE)[,-1])) nodes <- model$expandNodeNames('thetaTilde') expect_identical(cn$clusterNodes[[2]], c(matrix(nodes, J, n, byrow = TRUE))) expect_identical(cn$numNodesPerCluster, rep(as.integer(J), 2)) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_conjugate_dnorm_invgamma_dnorm") expect_identical(crpSampler$nObsPerClusID, J) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(J)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- conf$getSamplers(c('thetaTilde', 's2tilde'))[-(1:J)] expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n*J*2)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), rep(rep(1:n, each = J), 2)) code <- nimbleCode({ for(i in 1:n) { for(j in 1:J) { y[i, j] ~ dnorm(thetaTilde[xi[i], j], var = s2tilde[xi[i], j]) thetaTilde[i, j] ~ dnorm(j, var = s2tilde[i, j]/kappa) s2tilde[i, j] ~ dinvgamma(1,1) } } xi[1:n] ~ dCRP(alpha, size = n) }) n <- 5 J <- 3 constants <- list(n = n, J = J) data <- list(y = matrix(rnorm(n*J),n,J)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = matrix(rnorm(J*n), n, J), s2tilde = matrix(rgamma(J*n, 1, 1),n,J)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') nodes <- model$expandNodeNames('s2tilde') expect_identical(cn$clusterNodes[[1]], c(matrix(nodes, J, n, byrow = TRUE))) nodes <- model$expandNodeNames('thetaTilde') expect_identical(cn$clusterNodes[[2]], c(matrix(nodes, J, n, byrow = TRUE))) expect_identical(cn$numNodesPerCluster, rep(as.integer(J), 2)) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_conjugate_dnorm_invgamma_dnorm") expect_identical(crpSampler$nObsPerClusID, J) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(J)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- conf$getSamplers(c('thetaTilde', 's2tilde')) expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n*J*2)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), rep(rep(1:n, each = J), 2)) code <- nimbleCode({ for(i in 1:n) { for(j in 1:J) { y[i, j] ~ dnorm(thetaTilde[xi[i], j], var = s2tilde[xi[i], j]) thetaTilde[i, j] ~ dnorm(i, var = s2tilde[i, j]/kappa) s2tilde[i, j] ~ dinvgamma(1,1) } } xi[1:n] ~ dCRP(alpha, size = n) }) n <- 5 J <- 3 constants <- list(n = n, J = J) data <- list(y = matrix(rnorm(n*J),n,J)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = matrix(rnorm(J*n), n, J), s2tilde = matrix(rgamma(J*n, 1, 1),n,J)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') nodes <- model$expandNodeNames('s2tilde') expect_identical(cn$clusterNodes[[1]], c(matrix(nodes, J, n, byrow = TRUE))) nodes <- model$expandNodeNames('thetaTilde') expect_identical(cn$clusterNodes[[2]], c(matrix(nodes, J, n, byrow = TRUE))) expect_identical(cn$numNodesPerCluster, rep(as.integer(J), 2)) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_nonconjugate") expect_identical(crpSampler$nObsPerClusID, J) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(J)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- conf$getSamplers(c('thetaTilde', 's2tilde')) expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n*J*2)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), rep(rep(1:n, each = J), 2)) code <- nimbleCode({ for(i in 1:n) { for(j in 1:J) { y[i, j] ~ dnorm(thetaTilde[xi[i]], var = s2tilde[xi[i]]) } thetaTilde[i] ~ dnorm(theta0, var = s2tilde[i]/kappa) s2tilde[i] ~ dinvgamma(1,1) } xi[1:n] ~ dCRP(alpha, size = n) }) n <- 5 J <- 3 constants <- list(n = n, J = J) data <- list(y = matrix(rnorm(n*J),n,J)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = rnorm(n), s2tilde = rgamma(n, 1, 1)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') nodes <- model$expandNodeNames('s2tilde') expect_identical(cn$clusterNodes[[1]], nodes) nodes <- model$expandNodeNames('thetaTilde') expect_identical(cn$clusterNodes[[2]], nodes) expect_identical(cn$numNodesPerCluster, rep(as.integer(1), 2)) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_nonconjugate") expect_identical(crpSampler$nObsPerClusID, J) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(1)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- conf$getSamplers(c('thetaTilde', 's2tilde')) expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n*2)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), rep(1:n, 2)) code <- nimbleCode({ for(i in 1:n) { for(j in 1:J) { y[i, j] ~ dnorm(thetaTilde[xi[i], j], var = s2tilde[xi[i]]) thetaTilde[i,j] ~ dnorm(theta0, var = s2tilde[i]/kappa) } s2tilde[i] ~ dinvgamma(1,1) } xi[1:n] ~ dCRP(alpha, size = n) }) n <- 5 J <- 3 constants <- list(n = n, J = J) data <- list(y = matrix(rnorm(n*J),n,J)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = matrix(rnorm(J*n), n, J), s2tilde = rgamma(n, 1, 1)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') nodes <- model$expandNodeNames('s2tilde') expect_identical(cn$clusterNodes[[1]], nodes) nodes <- model$expandNodeNames('thetaTilde') expect_identical(cn$clusterNodes[[2]], c(matrix(nodes, J, n, byrow = TRUE))) expect_identical(cn$numNodesPerCluster, c(1L, 3L)) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_nonconjugate") expect_identical(crpSampler$nObsPerClusID, J) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(1)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- conf$getSamplers(c('thetaTilde', 's2tilde')) expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n*(J+1))) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), c(1:n, rep(1:n, each = J))) code <- nimbleCode({ for(i in 1:n) { y[i] ~ dnorm(thetaTilde[xi[n-i+1]], 1) } for(i in 1:n) { thetaTilde[i] ~ dnorm(0, 1) } xi[1:n] ~ dCRP(alpha, size = n) }) n <- 5 constants <- list(n = n) data <- list(y = rnorm(n)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = rnorm(n)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) expect_error(conf <- configureMCMC(model, print = FALSE), "findClusterNodes: Detected that a cluster parameter is indexed by a function") code <- nimbleCode({ for(i in 1:n) { y[i] ~ dnorm(thetaTilde[xi[exp(i)]], 1) } for(i in 1:n) { thetaTilde[i] ~ dnorm(0, 1) } xi[1:n] ~ dCRP(alpha, size = n) }) n <- 5 constants <- list(n = n) data <- list(y = rnorm(n)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = rnorm(n)) expect_error(model <- nimbleModel(code, data = data, constants = constants, inits = inits), "dimensions specified are smaller than") code <- nimbleCode({ for(i in 1:n) { y[i] ~ dnorm(thetaTilde[xi[i]], s2tilde[xi[n-i+1]]) } for(i in 1:n) { thetaTilde[i] ~ dnorm(0, 1) } for(i in 1:n) s2tilde[i] ~ dunif(0, 10) xi[1:n] ~ dCRP(alpha, size = n) }) n <- 5 constants <- list(n = n) data <- list(y = rnorm(n)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = rnorm(n), s2tilde = runif(n+1)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) expect_error(conf <- configureMCMC(model, print = FALSE), "findClusterNodes: Detected that a cluster parameter is indexed by a function") code <- nimbleCode({ for(i in 1:n) { y[i] ~ dnorm(thetaTilde[xi[i]], exp(thetaTilde[xi[i]])) } for(i in 1:n) { thetaTilde[i] ~ dnorm(0, 1) } xi[1:n] ~ dCRP(alpha, size = n) }) n <- 5 constants <- list(n = n) data <- list(y = rnorm(n)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = rnorm(n)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') nodes <- model$expandNodeNames('thetaTilde') expect_identical(cn$clusterNodes[[1]], nodes) expect_identical(cn$numNodesPerCluster, rep(1L, 2)) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_nonconjugate") expect_identical(crpSampler$nObsPerClusID, 1) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(1)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- conf$getSamplers('thetaTilde') expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), 1:n) code <- nimbleCode({ for(i in 1:n) { y[i] ~ dnorm(theta[i], exp(thetaTilde[xi[i]])) } for(i in 1:n) { thetaTilde[i] ~ dnorm(0, 1) theta[i] <- thetaTilde[xi[i]] } xi[1:n] ~ dCRP(alpha, size = n) }) n <- 5 constants <- list(n = n) data <- list(y = rnorm(n)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = rnorm(n)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') nodes <- model$expandNodeNames('thetaTilde') expect_identical(cn$clusterNodes[[1]], nodes) expect_identical(cn$numNodesPerCluster, rep(1L, 2)) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_nonconjugate") expect_identical(crpSampler$nObsPerClusID, 1) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(2)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- conf$getSamplers('thetaTilde') expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), 1:n) code <- nimbleCode({ for(i in 1:n) { y[i] ~ dnorm(thetaTilde[xi[i]+1], exp(thetaTilde[xi[i]])) } for(i in 1:(n+1)) { thetaTilde[i] ~ dnorm(0, 1) } xi[1:n] ~ dCRP(alpha, size = n) }) n <- 5 constants <- list(n = n) data <- list(y = rnorm(n)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = rnorm(n+1)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) expect_silent(conf <- configureMCMC(model, print = FALSE)) expect_error(mcmc <- buildMCMC(conf), "sampler_CRP: Inconsistent indexing") code <- nimbleCode({ for(i in 1:n) { y1[i] ~ dnorm(thetaTilde[xi[i]], 1) y2[i] ~ dnorm(thetaTilde[xi[i]], 1) thetaTilde[i] ~ dnorm(mu, sigma) } xi[1:n] ~ dCRP(alpha, size = n) }) n <- 5 constants <- list(n = n) data <- list(y1 = rnorm(n), y2 = rnorm(n)) inits <- list(alpha = 1, xi = rep(1, n), thetaTilde = rnorm(n)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) cn <- nimble:::findClusterNodes(model, 'xi[1:5]') nodes <- model$expandNodeNames('thetaTilde') expect_identical(cn$clusterNodes[[1]], nodes) expect_identical(cn$numNodesPerCluster, rep(1L, 2)) expect_silent(conf <- configureMCMC(model, print = FALSE)) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_silent(mcmc <- buildMCMC(conf)) crpSampler <- mcmc$samplerFunctions[[crpIndex]] expect_equal(crpSampler$sampler, "CRP_nonconjugate") expect_identical(crpSampler$nObsPerClusID, 2) expect_identical(crpSampler$nIntermClusNodesPerClusID, as.integer(0)) expect_identical(crpSampler$n, as.integer(n)) paramSamplers <- conf$getSamplers('thetaTilde') expect_identical(sapply(paramSamplers, function(x) x$name), rep('CRP_cluster_wrapper', n)) ids <- sapply(paramSamplers, function(x) x$control$clusterID) expect_identical(as.integer(ids), 1:n) code <- nimbleCode({ for(i in 1:n) { y[i] ~ dnorm(thetaTilde[xi[i]], 1) z[i] ~ dnorm(thetaTilde[eta[i]], 1) thetaTilde[i] ~ dnorm(0, 1) } xi[1:n] ~ dCRP(alpha, size = n) eta[1:n] ~ dCRP(alpha, size = n) }) n <- 5 constants <- list(n = n) data <- list(y = rnorm(n), z = rnorm(n)) inits <- list(alpha = 1, xi = rep(1, n), eta = rep(1,n), thetaTilde = rnorm(n)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) expect_silent(conf <- configureMCMC(model, print = FALSE)) expect_error(mcmc <- buildMCMC(conf), "sampler_CRP: Only the variables being clustered") code <- nimbleCode({ for(i in 1:n) { for(j in 1:J) { y[i, j] ~ dnorm(thetaTilde[xi[i], j], 1) }} for(i in 1:n) { for(j in 1:J) { thetaTilde[i, j] ~ dnorm(0, 1) }} xi[1:(n+1)] ~ dCRP(alpha, size = n+1) }) n <- 5 n2 <- 4 J <- 3 constants <- list(n = n, n2 = n2, J = J) data <- list(y = matrix(rnorm(n*J),n,J)) inits <- list(alpha = 1, xi = rep(1, n+1), thetaTilde = matrix(rnorm(J*n), n, J)) model <- nimbleModel(code, data = data, constants = constants, inits = inits) expect_silent(conf <- configureMCMC(model, print = FALSE)) expect_error(mcmc <- buildMCMC(conf), "The number of nodes that are jointly clustered must be the same") code <- nimbleCode({ for(i in 1:n) { for(j in 1:J) { y[i, j] ~ dnorm(thetaTilde[xi[i], j], 1) }} for(i in 1:n) { for(j in 1:J) { thetaTilde[i, j] ~ dnorm(0, 1) }} xi[1:(n-1)] ~ dCRP(alpha, size = n-1) }) n <- 5 n2 <- 4 J <- 3 constants <- list(n = n, n2 = n2, J = J) data <- list(y = matrix(rnorm(n*J),n,J)) inits <- list(alpha = 1, xi = rep(1, n-1), thetaTilde = matrix(rnorm(J*n), n, J)) expect_error(model <- nimbleModel(code, data = data, constants = constants, inits = inits), "dimensions specified are smaller than model specification") code <- nimbleCode({ for(i in 1:3) { for(j in 1:4) { y[i,j] ~ dnorm( thetaTilde[xi[i], eta[j]] , var = 1) thetaTilde[i, j] ~ dnorm(0, 1) } } xi[1:3] ~ dCRP(1, size=3) eta[1:4] ~ dCRP(1, size=4) }) inits <- list(xi = rep(1,3), eta = rep(1,4), thetaTilde = matrix(0, nrow=3, ncol=4)) y <- matrix(5, nrow=3, ncol=4) data <- list(y = y) model <- nimbleModel(code, data = data, inits = inits) expect_silent(conf <- configureMCMC(model, print = FALSE)) expect_error(mcmc <- buildMCMC(conf), "sampler_CRP: Detected use of multiple stochastic indexes of a variable") code <- nimbleCode({ for(i in 1:3) { for(j in 1:4) { y[i,j] ~ dnorm( thetaTilde[xi[i], eta[j]] , var = 1) }} for(i in 1:2) { for(j in 1:3) { thetaTilde[i, j] ~ dnorm(0, 1) } } xi[1:3] ~ dCRP(1, size=3) eta[1:4] ~ dCRP(1, size=4) }) inits <- list(xi = rep(1,3), eta = rep(1,4), thetaTilde = matrix(0, nrow=3, ncol=4)) y <- matrix(5, nrow=3, ncol=4) data <- list(y = y) model <- nimbleModel(code, data = data, inits = inits) expect_silent(conf <- configureMCMC(model, print = FALSE)) expect_error(mcmc <- buildMCMC(conf), "sampler_CRP: Detected use of multiple stochastic indexes of a variable") }) model <- function() { for(i in 1:4) { mu[i] ~ dnorm(0,1) y[i] ~ dnorm(mu[xi[i]], sd = 1) } xi[1:4] ~ dCRP(conc=1, size=4) } inits = list(xi = 1:4, mu=rnorm(4)) data = list(y = rnorm(4)) testBUGSmodel(example = 'test1', dir = "", model = model, data = data, inits = inits, useInits = TRUE) model <- function() { for(i in 1:4) { mu[i] ~ dgamma(1,1) y[i] ~ dpois(mu[xi[i]]) } xi[1:4] ~ dCRP(conc=1, size=4) } inits = list(xi = 1:4, mu=rgamma(4, 1, 1)) data = list(y = rpois(4, 4)) testBUGSmodel(example = 'test2', dir = "", model = model, data = data, inits = inits, useInits = TRUE) model <- function() { for(i in 1:4) { mu[i] ~ dgamma(1,1) y[i] ~ dexp(mu[xi[i]]) } xi[1:4] ~ dCRP(conc=1, size=4) } inits = list(xi = 1:4, mu=rgamma(4, 1, 1)) data = list(y = rexp(4, 4)) testBUGSmodel(example = 'test3', dir = "", model = model, data = data, inits = inits, useInits = TRUE) model <- function() { for(i in 1:4) { mu[i] ~ dgamma(1,1) y[i] ~ dgamma(4, mu[xi[i]]) } xi[1:4] ~ dCRP(conc=1, size=4) } inits = list(xi = 1:4, mu=rgamma(4, 1, 1)) data = list(y = rgamma(4, 4, 4)) testBUGSmodel(example = 'test4', dir = "", model = model, data = data, inits = inits, useInits = TRUE) model <- function() { for(i in 1:4) { mu[i] ~ dbeta(1,1) y[i] ~ dbern(mu[xi[i]]) } xi[1:4] ~ dCRP(conc=1, size=4) } inits = list(xi = 1:4, mu=rbeta(4, 1, 1)) data = list(y = rbinom(4, size=1, prob=0.5)) testBUGSmodel(example = 'test5', dir = "", model = model, data = data, inits = inits, useInits = TRUE) model <- function() { for(i in 1:4){ p[i,1:3] ~ ddirch(alpha=alpha0[1:3]) y[i,1:3] ~ dmulti(prob=p[xi[i],1:3], size=3) } xi[1:4] ~ dCRP(conc=1, size=4) } set.seed(1) p0 <- matrix(0, ncol=3, nrow=4) y0 <- matrix(0, ncol=3, nrow=4) for(i in 1:4){ p0[i,]=rdirch(1, c(1, 1, 1)) y0[i,] = rmulti(1, prob=c(0.3,0.3,0.4), size=3) } inits = list(xi = 1:4, p=p0) data = list(y = y0) alpha0 = c(1,1,1) testBUGSmodel(example = 'test6', dir = "", model = model, data = data, inits = inits, useInits = TRUE) model <- function() { for(i in 1:4) { s2[i] ~ dinvgamma(1, 1) mu[i] ~ dnorm(0,1) y[i] ~ dnorm(mu[xi[i]], var = s2[xi[i]]) } xi[1:4] ~ dCRP(conc=1, size=4) } inits = list(xi = 1:4, mu=rnorm(4), s2=rinvgamma(4, 1,1)) data = list(y = rnorm(4)) testBUGSmodel(example = 'test7', dir = "", model = model, data = data, inits = inits, useInits = TRUE) model <- function() { for(i in 1:4) { mu[i] ~ dgamma(1, rate=1) y[i] ~ dinvgamma(shape=4, scale = mu[xi[i]]) } xi[1:4] ~ dCRP(conc=1, size=4) } inits = list(xi = rep(1,4), mu=rgamma(4, 1, 1)) data = list(y = rinvgamma(4, 4, 4)) testBUGSmodel(example = 'test8', dir = "", model = model, data = data, inits = inits, useInits = TRUE) model <- function() { for(i in 1:4) { mu[i] ~ dgamma(1,1) y[i] ~ dweib(shape=4, lambda = mu[xi[i]]) } xi[1:4] ~ dCRP(conc=1, size=4) } inits = list(xi = rep(1,4), mu=rgamma(4, 1, 1)) data = list(y = rweibull(4, 4, 4)) testBUGSmodel(example = 'test9', dir = "", model = model, data = data, inits = inits, useInits = TRUE) model <- function() { for(i in 1:4) { mu[i] ~ dgamma(1,1) y[i] ~ dnorm(4, tau = mu[xi[i]]) } xi[1:4] ~ dCRP(conc=1, size=4) } inits = list(xi = rep(1,4), mu=rgamma(4, 1, 1)) data = list(y = rnorm(4, 4, 4)) testBUGSmodel(example = 'test10', dir = "", model = model, data = data, inits = inits, useInits = TRUE) model <- function() { for(i in 1:4) { mu[i] ~ dbeta(1,1) y[i] ~ dbinom(size=10, prob=mu[xi[i]]) } xi[1:4] ~ dCRP(conc=1, size=4) } inits = list(xi = rep(1,4), mu=rbeta(4, 1, 1)) data = list(y = rbinom(4, size=10, prob=0.5)) testBUGSmodel(example = 'test11', dir = "", model = model, data = data, inits = inits, useInits = TRUE) model <- function() { for(i in 1:4) { mu[i] ~ dbeta(1,1) y[i] ~ dnegbin(size=10, prob=mu[xi[i]]) } xi[1:4] ~ dCRP(conc=1, size=4) } inits = list(xi = rep(1,4), mu=rbeta(4, 1, 1)) data = list(y = rnbinom(4, size=10, prob=0.5)) testBUGSmodel(example = 'test12', dir = "", model = model, data = data, inits = inits, useInits = TRUE) model <- function() { for(i in 1:4){ mu[i,1:4] ~ dmnorm(mu0[1:4], cov=Cov0[1:4, 1:4]) y[i,1:4] ~ dmnorm(mu[xi[i],1:4], cov=Sigma0[1:4, 1:4]) } xi[1:4] ~ dCRP(conc=1, size=4) } inits = list(xi = 1:4, mu=matrix(rnorm(16), 4, 4)) data = list(y = matrix(rnorm(16), 4, 4)) constants = list(mu0 = rep(0,4), Cov0 = diag(10, 4), Sigma0 = diag(1, 4)) testBUGSmodel(example = 'test13', dir = "", model = model, data = data, inits = c(inits, constants), useInits = TRUE) test_that("Testing of misspecification of dimension when using CRP", { code = nimbleCode({ for(i in 1:4) { mu[i] ~ dnorm(0,1) y[i] ~ dnorm(mu[xi[i]], sd = 1) } xi[1:10] ~ dCRP(conc=1, size=10) }) m = nimbleModel(code, data = list(y = rnorm(4)), inits = list(xi = rep(1,10), mu=rnorm(4))) conf <- configureMCMC(m) expect_error(buildMCMC(conf), "sampler_CRP: At least one variable has to be clustered") code = nimbleCode({ for(i in 1:10) { mu[i] ~ dnorm(0,1) y[i] ~ dnorm(mu[xi[i]], sd = 1) } xi[1:4] ~ dCRP(conc=1, size=4) }) expect_error(nimbleModel(code, data = list(y = rnorm(10)), inits = list(xi = rep(1,4), mu=rnorm(10))), "dimensions specified are smaller") code = nimbleCode({ mu[1] ~ dnorm(0,1) mu[2] ~ dnorm(0,1) y[1] ~ dnorm(mu[xi[1]], 1) y[2] ~ dnorm(mu[xi[1]], 1) xi[1:2] ~ dCRP(conc=1, size=2) }) m <- nimbleModel(code, data = list(y = rnorm(2)), inits = list(xi = rep(1,2), mu=rnorm(2))) conf <- configureMCMC(m) expect_error(buildMCMC(conf), "sampler_CRP: Detected unusual indexing") code = nimbleCode({ mu[1] ~ dnorm(0,1) mu[2] ~ dnorm(0,1) y[1] ~ dnorm(mu[xi[1]], 1) y[1] ~ dnorm(mu[xi[2]], 1) xi[1:2] ~ dCRP(conc=1, size=2) }) expect_error(nimbleModel(code, data = list(y = rnorm(2)), inits = list(xi = rep(1,2), mu=rnorm(2))), "There are multiple definitions") code = nimbleCode({ for(i in 1:50){ mu[i] ~ dnorm(0,1) } for(i in 1:100){ y[i] ~ dnorm(mu[xi[i]], var=1) } xi[1:100] ~ dCRP(conc=1, size=100) }) m <- nimbleModel(code, data = list(y = rnorm(100)), inits = list(xi = rep(1,100), mu=rnorm(50))) conf <- configureMCMC(m) expect_warning(buildMCMC(conf), "sampler_CRP: The number of clusters based on the cluster parameters is less than the number of potential clusters") code = nimbleCode({ for(i in 1:50){ mu[i] ~ dnorm(0,1) s2[i] ~ dinvgamma(1,1) } for(i in 1:100){ y[i] ~ dnorm(mu[xi[i]], var=s2[xi[i]]) } xi[1:100] ~ dCRP(conc=1, size=100) }) m <- nimbleModel(code, data = list(y = rnorm(100)), inits = list(xi = rep(1,100), mu=rnorm(50), s2=rinvgamma(50,1,1))) conf <- configureMCMC(m) expect_warning(buildMCMC(conf), "sampler_CRP: The number of clusters based on the cluster parameters is less than the number of potential clusters") code = nimbleCode({ for(i in 1:50){ mu[i] ~ dnorm(0,1) s2[i] ~ dinvgamma(1,1) } for(i in 1:100){ y[i] ~ dnorm(mu[xi[i]], var=s2[xi[1]]) } xi[1:100] ~ dCRP(conc=1, size=100) }) m <- nimbleModel(code, data = list(y = rnorm(100)), inits = list(xi = rep(1,100), mu=rnorm(50), s2=rinvgamma(1,1,1))) expect_error(conf <- configureMCMC(m), "findClusterNodes: found cluster membership parameters that use different indexing") code = nimbleCode({ for(i in 1:50){ mu[i] ~ dnorm(0,1) } for(i in 1:99){ y[i] ~ dnorm(mu[xi[i]]+mu[xi[i+1]], var=1) } y[100] ~ dnorm(mu[xi[100]], 1) xi[1:100] ~ dCRP(conc=1, size=100) }) m <- nimbleModel(code, data = list(y = rnorm(100)), inits = list(xi = rep(1,100), mu=rnorm(50))) expect_error(conf <- configureMCMC(m), "findClusterNodes: Detected that a cluster parameter is indexed by a function") code = nimbleCode({ for(i in 1:3){ mu[i] ~ dnorm(0,1) } for(i in 1:100){ y[i] ~ dnorm(mu[xi[i]], var=1) } xi[1:100] ~ dCRP(conc=1, size=100) }) m <- nimbleModel(code, data = list(y = c(rnorm(20, -5) , rnorm(20, 0), rnorm(20, 5), rnorm(20, 10), rnorm(20, 20))), inits = list(xi = rep(1,100), mu=rnorm(3))) cm <- compileNimble(m) conf <- configureMCMC(m) expect_warning(mMCMC <- buildMCMC(conf)) cmMCMC=compileNimble(mMCMC, project=m, resetFunctions=TRUE) set.seed(1) expect_output(cmMCMC$run(1), "CRP_sampler: This MCMC is for a parametric model") }) test_that("Testing more BNP models based on CRP", { codeBNP <- nimbleCode({ for(i in 1:nStudies) { y[i] ~ dbin(size = nStudies, prob = q[i]) x[i] ~ dbin(size = nStudies, prob = p[i]) q[i] <- expit(theta + gamma[i]) p[i] <- expit(gamma[i]) gamma[i] ~ dnorm(mu[i], var = tau[i]) mu[i] <- muTilde[xi[i]] tau[i] <- tauTilde[xi[i]] } for(i in 1:nStudies) { muTilde[i] ~ dnorm(mu0, sd = sd0) tauTilde[i] ~ dinvgamma(a0, b0) } xi[1:nStudies] ~ dCRP(conc, size = nStudies) conc ~ dgamma(1, 1) mu0 ~ dflat() sd0 ~ dunif(0, 100) a0 ~ dunif(0, 100) b0 ~ dunif(0, 100) theta ~ dflat() }) Consts=list(nStudies=10) set.seed(1) Inits=list(gamma=rep(1,10), muTilde=rep(1,10), tauTilde=rep(1,10), xi=rep(1,10), conc =1, mu0 = 0, sd0 = 1, a0 = 1, b0 = 1, theta = 0) Data=list(y=rbinom(10, 10, 0.5), x=rbinom(10, 10, 0.5)) model<-nimbleModel(codeBNP, data=Data, inits=Inits, constants=Consts, calculate=TRUE) cmodel<-compileNimble(model) mConf <- configureMCMC(model) crpIndex <- which(sapply(mConf$getSamplers(), function(x) x[['name']]) == 'CRP') mMCMC <- buildMCMC(mConf) expect_equal(mConf$getSamplers()[[1]]$name, "CRP_concentration") expect_equal(class(mMCMC$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_nonconjugate") model <- function() { for(i in 1:10) { y[i] ~ dbin(size = 10, prob = q[i]) x[i] ~ dbin(size = 10, prob = p[i]) q[i] <- expit(theta + gamma[i]) p[i] <- expit(gamma[i]) gamma[i] ~ dnorm(mu[i], var = tau[i]) mu[i] <- muTilde[xi[i]] tau[i] <- tauTilde[xi[i]] } for(i in 1:10) { muTilde[i] ~ dnorm(mu0, sd = sd0) tauTilde[i] ~ dinvgamma(a0, b0) } xi[1:10] ~ dCRP(conc, size = 10) conc ~ dgamma(1, 1) mu0 ~ dflat() sd0 ~ dunif(0, 100) a0 ~ dunif(0, 100) b0 ~ dunif(0, 100) theta ~ dflat() } testBUGSmodel(example = 'test8', dir = "", model = model, data = Data, inits = Inits, useInits = TRUE) time <- c(1.25,1.25,2,2,2,3,5,5,6,6,6,6,7,7,7,9,11,11,11,11,11,13,14,15,16,16,17,17,18,19,19,24,25,26,32,35,37,41,41,51,52,54,58,66,67,88,89,92,4,4,7,7,8,12,11,12,13,16,19,19,28,41,53,57,77) vstatus <- c(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0) logBUN <- c(2.2175,1.9395,1.5185,1.7482,1.301,1.5441,2.2355,1.6812,1.3617,2.1139,1.1139,1.415,1.9777,1.0414,1.1761,1.7243,1.1139,1.2304,1.301,1.5682,1.0792,0.7782,1.3979,1.6021,1.3424,1.3222,1.2304,1.5911,1.4472,1.0792,1.2553,1.301,1,1.2304,1.3222,1.1139,1.6021,1,1.1461,1.5682,1,1.2553,1.2041,1.4472,1.3222,1.1761,1.3222,1.4314,1.9542,1.9243,1.1139,1.5315,1.0792,1.1461,1.6128,1.3979,1.6628,1.1461,1.3222,1.3222,1.2304,1.7559,1.1139,1.2553,1.0792) HGB <- c(9.4,12,9.8,11.3,5.1,6.7,10.1,6.5,9,10.2,9.7,10.4,9.5,5.1,11.4,8.2,14,12,13.2,7.5,9.6,5.5,14.6,10.6,9,8.8,10,11.2,7.5,14.4,7.5,14.6,12.4,11.2,10.6,7,11,10.2,5,7.7,10.1,9,12.1,6.6,12.8,10.6,14,11,10.2,10,12.4,10.2,9.9,11.6,14,8.8,4.9,13,13,10.8,7.3,12.8,12,12.5,14) n <- length(time) alive <- vstatus == 0 cens_time <- rep(NA, n) cens_time[alive] <- time[alive] cens_time[!alive] <- Inf time[alive] <- NA logBUN <- (logBUN - mean(logBUN)) / sd(logBUN) HGB <- (HGB - mean(HGB)) / sd(HGB) codeAFT <- nimbleCode({ for(i in 1:n) { x[i] ~ dweib(alpha, exp(lambda[i])) is_cens[i] ~ dinterval(x[i], c[i]) lambda[i] <- inprod(Z[i, 1:p], delta[1:p]) + eta[i] eta[i] <- etaTilde[xi[i]] } xi[1:n] ~ dCRP(conc, size = n) conc ~ dgamma(1, 1) for(i in 1:n){ etaTilde[i] ~ dunif(b0, B0) } alpha ~ dunif(a0, A0) for(j in 1:p){ delta[j] ~ dflat() } }) constants = list(b0 = -10, B0 = 10, a0 = 0.1, A0 = 10, p = 2, n = n, c = cens_time, Z = cbind(logBUN, HGB)) data = list(is_cens = as.numeric(alive), x = time) xInit <- rep(NA, n) xInit[alive] <- cens_time[alive] + 10 inits = list(alpha = 1, delta = c(0, 0), conc = 1, etaTilde = runif(n,constants$b0, constants$B0), xi = sample(1:3, n, replace = TRUE), x = xInit) model <- nimbleModel(codeAFT, constants = constants, data = data, inits = inits) conf = configureMCMC(model) mcmc = buildMCMC(conf) expect_equal(conf$getSamplers()[[1]]$name, "CRP_concentration") crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_identical(length(crpIndex), 1L) expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_nonconjugate") model <- function() { for(i in 1:n) { x[i] ~ dweib(alpha, 1+exp(lambda[i])) is_cens[i] ~ dinterval(x[i], c[i]) lambda[i] <- inprod(Z[i, 1:p], delta[1:p]) + eta[i] eta[i] <- etaTilde[xi[i]] } xi[1:n] ~ dCRP(conc, size = n) conc ~ dgamma(1, 1) for(i in 1:n){ etaTilde[i] ~ dunif(b0, B0) } alpha ~ dunif(a0, A0) for(j in 1:p){ delta[j] ~ dflat() } } Data = list(is_cens = as.numeric(alive), x = time, b0 = -10, B0 = 10, a0 = 0.1, A0 = 10, p = 2, n = n, c = cens_time, Z = cbind(logBUN, HGB)) xInit <- rep(NA, n) xInit[alive] <- cens_time[alive] + 10 Inits = list(alpha = 1, delta = c(0, 0), conc = 1, etaTilde = runif(n,Data$b0, Data$B0), xi = sample(1:3, n, replace = TRUE), x = xInit) testBUGSmodel(example = 'test9', dir = "", model = model, data = Data, inits = Inits, useInits = TRUE) }) test_that("stick_breaking nimble function calculation and use is correct", { set.seed(0) x <- rbeta(5, 1, 1) truth <- c(x[1], x[2:5]*cumprod(1-x[1:4]), prod(1-x[1:5])) ltruth <- log(truth) expect_equal(stick_breaking(x, log=FALSE), truth, info = paste0("incorrect stick_breaking nimble function calculation")) expect_equal(stick_breaking(x, log=TRUE), ltruth, info = paste0("incorrect stick_breaking nimble function log calculation")) cSB <- compileNimble(stick_breaking) expect_equal(cSB(x, log=FALSE), truth, info = paste0("incorrect compiled stick_breaking nimble function calculation")) expect_equal(cSB(x, log=TRUE), ltruth, info = paste0("incorrect compiled stick_breaking nimble function log calculation")) x <- c(0.1, 0.4, -0.1, 0.3) expect_output(aux <- stick_breaking(x, log=FALSE), "values in 'z' have to be in", info = "stick_breaking not warning of negative component") expect_equal(aux, rep(NaN, length(x)+1), info = "stick_breaking not correctly handling negative component") x <- c(0.1, 5, 0.4, 0.3) expect_output(aux <- stick_breaking(x, log=FALSE), "values in 'z' have to be in") expect_equal(aux, rep(NaN, length(x)+1), info = "stick_breaking incorrectly handling larger than 1 component") x <- c(0.1, 0.2, 0, 0.3, 0.8) truth <- c(x[1], x[2:5]*cumprod(1-x[1:4]), prod(1-x[1:5])) expect_equal(stick_breaking(x, log=FALSE), truth, info = paste0("incorrect stick_breaking nimble function calculation with one 0 component")) x <- c(0.1, 0.2, 1, 0.3, 0.8) truth <- c(x[1], x[2:5]*cumprod(1-x[1:4]), prod(1-x[1:5])) expect_equal(stick_breaking(x, log=FALSE), truth, info = paste0("incorrect stick_breaking nimble function calculation with one 1 component")) }) test_that("Stick breaking model calculation is correct", { set.seed(0) x <- rbeta(5, 1, 1) truth <- c(x[1], x[2:5]*cumprod(1-x[1:4]), prod(1-x[1:5])) SB_code <- nimbleCode({ for(i in 1:5) z[i] ~ dbeta(1, 1) w[1:6] <- stick_breaking(z[1:5]) }) set.seed(1) Inits <- list(z = rbeta(5, 1, 1)) SB_model <- nimbleModel(SB_code, data=Inits) SB_model$z <- x SB_model$calculate() expect_equal(c(SB_model$w), truth, info = paste0("incorrect stick breaking weights in model")) c_SB_model <- compileNimble(SB_model) c_SB_model$z <- x c_SB_model$calculate() c_SB_model$w expect_equal(c(c_SB_model$w), truth, info = paste0("incorrect stick breaking weights in compiled model")) }) model <- function() { for(j in 1:5) z[j] ~ dbeta(1, 1) w[1:6] <- stick_breaking(z[1:5]) for(i in 1:10){ xi[i] ~ dcat(w[1:6]) } } Inits <- list(z = rep(0.5,5)) Data <- list(xi = 1:10) testBUGSmodel(example = 'test1', dir = "", model = model, data = Data, inits = Inits, useInits = TRUE) model <- function(){ for(i in 1:10){ xi[i] ~ dcat(w[1:10]) y[i] ~ dnorm( thetatilde[xi[i]], var=1) } for(i in 1:10){ thetatilde[i] ~ dnorm(0, var=20) } for(i in 1:9){ z[i] ~ dbeta(1,1) } w[1:10] <- stick_breaking(z[1:9]) } Inits=list(thetatilde=rep(0,10), z=rep(0.5, 9), xi=1:10) Data=list(y=rnorm(10)) testBUGSmodel(example = 'test2', dir = "", model = model, data = Data, inits = Inits, useInits = TRUE) model <- function(){ for(i in 1:10){ xi[i] ~ dcat(w[1:10]) theta[i] <- thetatilde[xi[i]] y[i] ~ dnorm( theta[i], var=1) } for(i in 1:10){ thetatilde[i] ~ dnorm(0, var=20) } for(i in 1:9){ z[i] ~ dbeta(1,1) } w[1:10] <- stick_breaking(z[1:9]) } Inits=list(thetatilde=rep(0,10), z=rep(0.5, 9), xi=1:10) Data=list(y=rnorm(10)) testBUGSmodel(example = 'test3', dir = "", model = model, data = Data, inits = Inits, useInits = TRUE) model <- function(){ for(i in 1:10){ xi[i] ~ dcat(w[1:10]) theta[i] <- thetatilde[xi[i]] y[i] ~ dnorm( theta[i], var=s2tilde[xi[i]]) } for(i in 1:10){ thetatilde[i] ~ dnorm(0, var=20) s2tilde[i] ~ dinvgamma(1, 1) } for(i in 1:9){ z[i] ~ dbeta(1,1) } w[1:10] <- stick_breaking(z[1:9]) } Inits=list(thetatilde=rep(0,10), z=rep(0.5, 9), xi=1:10, s2tilde=rep(1,10)) Data=list(y=rnorm(10)) testBUGSmodel(example = 'test4', dir = "", model = model, data = Data, inits = Inits, useInits = TRUE) test_that("Testing conjugacy detection with bnp stick breaking models", { code=nimbleCode( { for(i in 1:5){ thetatilde[i] ~ dnorm(mean=0, var=10) } for(i in 1:4){ z[i] ~ dbeta(1, 1) } w[1:5] <- stick_breaking(z[1:4]) for(i in 1:5){ xi[i] ~ dcat(w[1:5]) y[i] ~ dnorm(thetatilde[xi[i]], var=1) } } ) m = nimbleModel(code, data = list(y = rnorm(5)), inits = list(xi = rep(1,5), thetatilde=rep(0,5), z=rep(0.5,4))) conf <- configureMCMC(m) expect_match(conf$getSamplers()[[6]]$name, "conjugate_dbeta_dcat", info = "failed to detect categorical-beta conjugacy") code=nimbleCode( { for(i in 1:5){ thetatilde[i] ~ dnorm(mean=0, var=10) } for(i in 1:4){ z[i] ~ dunif(0,1) } w[1:5] <- stick_breaking(z[1:4]) for(i in 1:5){ xi[i] ~ dcat(w[1:5]) y[i] ~ dnorm(thetatilde[xi[i]], var=1) } } ) m = nimbleModel(code, data = list(y = rnorm(5)), inits = list(xi = rep(1,5), thetatilde=rep(0,5), z=rep(0.5,4))) conf <- configureMCMC(m) expect_failure(expect_match(conf$getSamplers()[[6]]$name, "conjugate_dbeta_dcat", info = "failed to detect categorical-beta conjugacy")) code=nimbleCode( { for(i in 1:5){ thetatilde[i] ~ dnorm(mean=0, var=10) } for(i in 1:4){ z[i] ~ dbeta(1, conc) } conc ~ dgamma(1,1) w[1:5] <- stick_breaking(z[1:4]) for(i in 1:5){ xi[i] ~ dcat(w[1:5]) y[i] ~ dnorm(thetatilde[xi[i]], var=1) } } ) m = nimbleModel(code, data = list(y = rnorm(5)), inits = list(xi = rep(1,5), thetatilde=rep(0,5), z=rep(0.5,4), conc=1)) conf <- configureMCMC(m) expect_match(conf$getSamplers()[[7]]$name, "conjugate_dbeta_dcat", info = "failed to detect categorical-beta conjugacy") }) test_that("Testing BNP model using stick breaking representation", { Code=nimbleCode( { for(i in 1:Trunc) { thetatilde[i] ~ dnorm(mean=0, var=40) s2tilde[i] ~ dinvgamma(shape=1, scale=0.5) } for(i in 1:(Trunc-1)) { z[i] ~ dbeta(1, 1) } w[1:Trunc] <- stick_breaking(z[1:(Trunc-1)]) for(i in 1:N) { xi[i] ~ dcat(w[1:Trunc]) theta[i] <- thetatilde[xi[i]] s2[i] <- s2tilde[xi[i]] y[i] ~ dnorm(theta[i], var=s2[i]) } } ) Consts <- list(N=50, Trunc=25) set.seed(1) Inits <- list(thetatilde = rnorm(Consts$Trunc, 0, sqrt(40)), s2tilde = rinvgamma(Consts$Trunc, shape=1, scale=0.5), z = rbeta(Consts$Trunc-1, 1, 1), xi = sample(1:10, size=Consts$N, replace=TRUE)) Data = list(y = c(rnorm(Consts$N/2,5,sqrt(4)), rnorm(Consts$N/2,-5,sqrt(4)))) model = nimbleModel(Code, data=Data, inits=Inits, constants=Consts, calculate=TRUE) cmodel = compileNimble(model) modelConf = configureMCMC(model, thin=100) expect_match(modelConf$getSamplers()[[51]]$name, "conjugate_dbeta_dcat", info = "failed to detect categorical-beta conjugacy in BNP model") modelMCMC = buildMCMC(modelConf) CmodelMCMC = compileNimble(modelMCMC, project=model, resetFunctions=TRUE) CmodelMCMC$run(10000) samples = as.matrix(CmodelMCMC$mvSamples) s2Sam = samples[, 1:25] thetaSam = samples[, 26:50] zSam = samples[, 51:74] Tr = 25 Wpost = t(apply(zSam, 1, function(x)c(x[1], x[2:(Tr-1)]*cumprod(1-x[1:(Tr-2)]), cumprod(1-x[1:(Tr-1)])[N=Tr-1]))) ngrid = 302 grid = seq(-10, 25,len=ngrid) nsave = 100 predSB = matrix(0, ncol=ngrid, nrow=nsave) for(i in 1:nsave) { predSB[i, ] = sapply(1:ngrid, function(j)sum(Wpost[i, ]*dnorm(grid[j], thetaSam[i,],sqrt(s2Sam[i,])))) } f0 <- function(x) 0.5*dnorm(x,5,sqrt(4)) + 0.5*dnorm(x,-5,sqrt(4)) fhat <- apply(predSB, 2, mean) f0grid <- sapply(grid, f0) L1dist <- mean(abs(f0grid - fhat)) expect_lt(abs(L1dist - 0.01), 0.01, label = "wrong estimation of density in DPM of normal distrbutions") }) test_that("random sampling from model works fine", { set.seed(0) x <- rbeta(5, 1, 1) truth <- c(x[1], x[2:5]*cumprod(1-x[1:4]), prod(1-x[1:5])) SB_code2 <- nimbleCode({ for(i in 1:5) z[i] ~ dbeta(1, 1) w[1:6] <- stick_breaking(z[1:5]) for(i in 1:10){ xi[i] ~ dcat(w[1:6]) } }) set.seed(1) Inits <- list(z = rbeta(5, 1, 1)) data <- list(xi = rep(1,10)) SB_model2 <- nimbleModel(SB_code2, data=data, inits=Inits) c_SB_model2 <- compileNimble(SB_model2) c_SB_model2$z <- x c_SB_model2$calculate() expect_equal(c_SB_model2$w, truth, info = paste0("incorrect stick breaking weights in SB_model2")) set.seed(0) simul_samp <- function(model) { model$simulate() return(model$w) } simul_samps <- t(replicate(10000, simul_samp(c_SB_model2))) trueE <- c(0.5^(1:5) ) expect_lt(max(abs(apply(simul_samps, 2, mean)[1:5] - trueE)), 0.01, label = paste0("incorrect weights (w) sampling in SB_model2")) SB_code3 <- nimbleCode({ for(i in 1:5) z[i] ~ dgamma(10, 10) w[1:6] <- stick_breaking(z[1:5]) for(i in 1:10){ xi[i] ~ dcat(w[1:6]) } }) set.seed(1) Inits <- list(z = rgamma(5, 10, 10)) data <- list(xi = 1:10) expect_output(m <- nimbleModel(SB_code3, data=data, inits=Inits), "values in 'z' have to be in \\(0,1\\)") set.seed(1) Inits <- list(z = rbeta(5, 1, 1)) data <- list(xi = rep(1,10)) SB_model3 <- nimbleModel(SB_code3, data=data, inits=Inits) expect_output(m <- SB_model3$simulate(), "values in 'z' have to be in \\(0,1\\)") SB_code4 <- nimbleCode({ for(i in 1:4) z[i] ~ dbeta(1,1) w[1:6] <- stick_breaking(z[1:4]) for(i in 1:10){ xi[i] ~ dcat(w[1:6]) } }) set.seed(1) Inits <- list(z = rbeta(4, 10, 10)) data <- list(xi = rep(1,10)) expect_warning(m <- nimbleModel(SB_code4, data=data, inits=Inits), "number of items to replace") SB_code5 <- nimbleCode({ for(i in 1:2) z[i] ~ dbeta(1,1) w[1:6] <- stick_breaking(z[1:2]) for(i in 1:10){ xi[i] ~ dcat(w[1:6]) } }) set.seed(1) Inits <- list(z = rbeta(2, 10, 10)) data <- list(xi = rep(1,10)) expect_failure(expect_error(SB_model5 <- nimbleModel(SB_code5, data=data, inits=Inits))) cSB_model5 <- compileNimble(SB_model5) expect_output(cSB_model5$calculate('w'), "Error in mapCopy") SB_code6 <- nimbleCode({ for(i in 1:10) z[i] ~ dbeta(1,1) w[1:6] <- stick_breaking(z[1:10]) for(i in 1:10){ xi[i] ~ dcat(w[1:6]) } }) set.seed(1) Inits <- list(z = rbeta(10, 10, 10)) data <- list(xi = rep(1,10)) expect_warning(SB_model6 <- nimbleModel(SB_code6, data=data, inits=Inits), "number of items to replace") cSB_model6 <- compileNimble(SB_model6) expect_output(cSB_model6$calculate('w'), "Error in mapCopy") }) test_that("Testing sampler assignment and misspecification of priors for conc parameter", { code = nimbleCode({ for(i in 1:4) { mu[i] ~ dnorm(0,1) y[i] ~ dnorm(mu[xi[i]], sd = 1) } xi[1:4] ~ dCRP(alpha, size=4) alpha ~ dgamma(1, 1) }) m = nimbleModel(code, data = list(y = rnorm(4)), inits = list(xi = rep(1,4), mu = rnorm(4), alpha = 1)) conf <- configureMCMC(m) expect_equal(conf$getSamplers('alpha')[[1]]$name, "CRP_concentration") code = nimbleCode({ for(i in 1:4) { mu[i] ~ dnorm(0,1) y[i] ~ dnorm(mu[xi[i]], sd = 1) } xi[1:4] ~ dCRP(alpha, size=4) alpha ~ dexp(1) }) m = nimbleModel(code, data = list(y = rnorm(4)), inits = list(xi = rep(1,4), mu = rnorm(4), alpha = 1)) conf <- configureMCMC(m) expect_equal(conf$getSamplers('alpha')[[1]]$name, "RW") code = nimbleCode({ for(i in 1:4) { mu[i] ~ dnorm(0,1) y[i] ~ dnorm(mu[xi[i]], sd = 1) } xi[1:4] ~ dCRP(alpha, size=4) alpha ~ dunif(0,1) }) m = nimbleModel(code, data = list(y = rnorm(4)), inits = list(xi = rep(1,4), mu = rnorm(4), alpha = 1)) conf <- configureMCMC(m) expect_equal(conf$getSamplers('alpha')[[1]]$name, "RW") code = nimbleCode({ for(i in 1:4) { mu[i] ~ dnorm(0,1) y[i] ~ dnorm(mu[xi[i]], sd = 1) } xi[1:4] ~ dCRP(alpha, size=4) alpha ~ dnorm(-10,1) }) m = nimbleModel(code, data = list(y = rnorm(4)), inits = list(xi = rep(1,4), mu = rnorm(4), alpha = 1)) expect_failure(expect_output(m$simulate(), "value of concentration parameter")) expect_output(out <- m$calculate(), "Dynamic index out of bounds") code = nimbleCode({ for(i in 1:4) { mu[i] ~ dnorm(0,1) y[i] ~ dnorm(mu[xi[i]], sd = 1) } xi[1:4] ~ dCRP(0, size=4) }) m = nimbleModel(code, data = list(y = rnorm(4)), inits = list(xi = rep(1,4), mu = rnorm(4))) expect_failure(expect_output(m$simulate(), "value of concentration parameter has to be larger than zero")) expect_output(out <- m$calculate(), "Dynamic index out of bounds") }) test_that("Testing dnorm_dnorm non-identity conjugacy setting, regression setting", { set.seed(1) code = nimbleCode({ for(i in 1:n) { for(j in 1:J) { b1[i,j] ~ dnorm(beta, 0.25) y[i,j] ~ dnorm(b0 + b1[xi[i],j]*x[i], sd = 0.7) } } xi[1:n] ~ dCRP(conc=1, size=n) beta ~ dnorm(0,1) b0 ~ dnorm(0,1) }) n <- 4 J <- 2 constants <- list(n = n, J = J) data <- list(y = matrix(rnorm(n*J),n,J), x = rnorm(n)) m = nimbleModel(code, data = data, constants = constants, inits = list(xi = c(4,3,2,1), b1 = matrix(rnorm(n*J),n,J), beta = rnorm(1), b0 = rnorm(1))) conf <- configureMCMC(m) mcmc <- buildMCMC(conf) crpIndex <- which(sapply(conf$getSamplers(), function(x) x[['name']]) == 'CRP') expect_equal(class(mcmc$samplerFunctions[[crpIndex]]$helperFunctions$contentsList[[1]])[1], "CRP_conjugate_dnorm_dnorm_nonidentity", info = 'dnorm_dnorm_nonidentity conjugacy not detected') mcmc$samplerFunctions[[1]]$helperFunctions[[1]]$calculate_offset_coeff(1,4) expect_identical(mcmc$samplerFunctions[[1]]$helperFunctions[[1]]$offset[1:J], rep(m$b0, J), info = 'calculation of offset in dnorm_dnorm_nonidentity incorrect') expect_lt(max(abs(mcmc$samplerFunctions[[crpIndex]]$helperFunctions[[1]]$coeff[1:J] - rep(m$x[1], J))), 1e-15, label = 'calculation of offset in dnorm_dnorm_nonidentity incorrect') mcmc$samplerFunctions[[1]]$helperFunctions[[1]]$calculate_offset_coeff(2,3) expect_identical(mcmc$samplerFunctions[[1]]$helperFunctions[[1]]$offset[1:J], rep(m$b0, J), info = 'calculation of offset in dnorm_dnorm_nonidentity incorrect') expect_lt(max(abs(mcmc$samplerFunctions[[crpIndex]]$helperFunctions[[1]]$coeff[1:J] - rep(m$x[2], J))), 1e-15, label = 'calculation of offset in dnorm_dnorm_nonidentity incorrect') tmp <- m$calculate() pYgivenT <- m$getLogProb('y[1, 1:2]') pT <- m$getLogProb('b1[4, 1:2]') dataVar <- c(m$getParam('y[1, 1]', 'var'), m$getParam('y[1, 2]', 'var')) priorVar <- c(m$getParam('b1[4, 1]', 'var'), m$getParam('b1[4, 2]', 'var')) priorMean <- c(m$getParam('b1[4, 1]', 'mean'), m$getParam('b1[4, 2]', 'mean')) postVar <- 1 / (m$x[1]^2 / dataVar + 1 / priorVar) postMean <- postVar * (m$x[1]*(data$y[1, 1:2]-m$b0) / dataVar + priorMean / priorVar) pTgivenY <- dnorm(m$b1[4, 1] , postMean[1], sqrt(postVar[1]), log = TRUE) + dnorm(m$b1[4, 2] , postMean[2], sqrt(postVar[2]), log = TRUE) mcmc$samplerFunctions[[1]]$helperFunctions$contentsList[[1]]$storeParams() mcmc$samplerFunctions[[1]]$helperFunctions$contentsList[[1]]$calculate_offset_coeff(1, 4) pY <- mcmc$samplerFunctions[[1]]$helperFunctions$contentsList[[1]]$calculate_prior_predictive(1) expect_equal(pY, pT + pYgivenT - pTgivenY, info = "problem with predictive distribution for dnorm_dnorm_nonidentity") set.seed(1) mcmc$samplerFunctions[[1]]$helperFunctions$contentsList[[crpIndex]]$sample(1, 4) set.seed(1) smp <- rnorm(2, postMean, sqrt(postVar)) expect_lt(max(abs(smp - m$b1[4, 1:2])), 1e-15, label = "problem with predictive sample for dnorm_dnorm_nonidentity") set.seed(1) n <- 100 data <- list(y = matrix(rnorm(n*J),n,J), x = rnorm(n)) constants <- list(n = n, J = J) inits <- list(xi = rep(1, n), b1 = matrix(4,n,J), beta = 1) set.seed(1) code = nimbleCode({ for(i in 1:n) { for(j in 1:J) { b1[i,j] ~ dnorm(beta, 1) y[i,j] ~ dnorm(b0 + b1[xi[i],j]*x[i], sd = 1) } } xi[1:n] ~ dCRP(conc=1, size=n) beta ~ dnorm(0,1) }) m = nimbleModel(code, data = data, constants = constants, inits = c(inits, list(b0 = 0))) conf <- configureMCMC(m, monitors = c('b1','beta','xi')) mcmc <- buildMCMC(conf) cm <- compileNimble(m) cmcmc <- compileNimble(mcmc, project = m) smp1 <- runMCMC(cmcmc, 1000, setSeed = 1) set.seed(1) code = nimbleCode({ for(i in 1:n) { for(j in 1:J) { b1[i,j] ~ dnorm(beta, 1) y[i,j] ~ dnorm(b1[xi[i],j]*x[i], sd = 1) } } xi[1:n] ~ dCRP(conc=1, size=n) beta ~ dnorm(0,1) }) m = nimbleModel(code, data = data, constants = constants, inits = inits) conf <- configureMCMC(m, monitors = c('b1','beta','xi')) mcmc<-buildMCMC(conf) cm <- compileNimble(m) cmcmc <- compileNimble(mcmc, project = m) smp2 <- runMCMC(cmcmc, 1000, setSeed = 1) expect_identical(smp1, smp2, "sampling for identity and special case of non-identity not identical") }) test_that("Testing that cluster parameters are appropriately updated and mvSaved in good state", { set.seed(1) code <- nimbleCode({ xi[1:n] ~ dCRP(conc=1, size=n) for(i in 1:n) { mu[i] ~ T(dnorm(50, 1), -200, 200) y[i] ~ dnorm(mu[xi[i]], sd = 1) } }) n <- 15 data <- list(y = rnorm(n)) inits <- list(xi = rep(1,n), mu = rep(0, n)) m <- nimbleModel(code, data=data, inits= inits, constants = list(n=n)) conf <- configureMCMC(m, nodes = 'xi') cm <- compileNimble(m) mcmc <- buildMCMC(conf) cmcmc <- compileNimble(mcmc, project=m) cmcmc$run(1) expect_identical(cm$mu[2], 0, info = 'mu[2] is changed') expect_identical(cm$mu[3], 0, info = 'mu[3] is changed') expect_identical(cmcmc$mvSaved[['mu']], cm$mu) expect_identical(cmcmc$mvSaved[['logProb_mu']], cm$logProb_mu) expect_identical(sum(cm$logProb_mu), cm$calculate('mu')) expect_identical(cmcmc$mvSaved[['xi']], cm$xi) expect_identical(cmcmc$mvSaved[['logProb_xi']], cm$logProb_xi) expect_identical(sum(cm$logProb_xi), cm$calculate('xi')) expect_equal(sum(cmcmc$mvSaved[['logProb_mu']]) + sum(cmcmc$mvSaved[['logProb_xi']]) + sum(cmcmc$mvSaved[['logProb_y']]), cm$calculate()) set.seed(1) code <- nimbleCode({ xi[1:n] ~ dCRP(conc=1, size=n) for(i in 1:n) { mu[i] ~ T(dnorm(0, 1), -200, 200) y[i] ~ dnorm(mu[xi[i]], sd = 1) } }) n <- 15 data <- list(y = c(0, rnorm(n-1, 50, 1))) inits <- list(xi = rep(1,n), mu = rep(50, n)) m <- nimbleModel(code, data=data, inits= inits, constants = list(n=n)) conf <- configureMCMC(m, nodes = 'xi') cm <- compileNimble(m) mcmc <- buildMCMC(conf) cmcmc <- compileNimble(mcmc, project=m) cmcmc$run(1) expect_lt(abs(cm$mu[2]), 3, label = 'mu[2] is not changed') expect_identical(cm$mu[3], 50, info = 'mu[3] is changed') expect_identical(cm$mu[4], 50, info = 'mu[4] is changed') expect_identical(cmcmc$mvSaved[['mu']], cm$mu) expect_identical(cmcmc$mvSaved[['logProb_mu']], cm$logProb_mu) expect_identical(sum(cm$logProb_mu), cm$calculate('mu')) expect_identical(cmcmc$mvSaved[['xi']], cm$xi) expect_identical(cmcmc$mvSaved[['logProb_xi']], cm$logProb_xi) expect_identical(sum(cm$logProb_xi), cm$calculate('xi')) expect_equal(sum(cmcmc$mvSaved[['logProb_mu']]) + sum(cmcmc$mvSaved[['logProb_xi']]) + sum(cmcmc$mvSaved[['logProb_y']]), cm$calculate()) set.seed(1) code <- nimbleCode({ xi[1:n] ~ dCRP(conc=1, size=n) for(i in 1:n) { mu[i] ~ dnorm(50, 1) y[i] ~ dnorm(mu[xi[i]], sd = 1) } }) n <- 15 data <- list(y = rnorm(n)) inits <- list(xi = rep(1,n), mu = rep(0, n)) m <- nimbleModel(code, data=data, inits= inits, constants = list(n=n)) conf <- configureMCMC(m, nodes = 'xi') cm <- compileNimble(m) mcmc <- buildMCMC(conf) cmcmc <- compileNimble(mcmc, project=m) cmcmc$run(1) expect_identical(cm$mu[2], 0, info = 'mu[2] is changed') expect_identical(cm$mu[3], 0, info = 'mu[3] is changed') expect_identical(cmcmc$mvSaved[['mu']], cm$mu) expect_identical(cmcmc$mvSaved[['logProb_mu']], cm$logProb_mu) expect_identical(sum(cm$logProb_mu), cm$calculate('mu')) expect_identical(cmcmc$mvSaved[['xi']], cm$xi) expect_identical(cmcmc$mvSaved[['logProb_xi']], cm$logProb_xi) expect_identical(sum(cm$logProb_xi), cm$calculate('xi')) expect_equal(sum(cmcmc$mvSaved[['logProb_mu']]) + sum(cmcmc$mvSaved[['logProb_xi']]) + sum(cmcmc$mvSaved[['logProb_y']]), cm$calculate()) set.seed(1) code <- nimbleCode({ xi[1:n] ~ dCRP(conc=1, size=n) for(i in 1:n) { mu[i] ~ dnorm(0, 1) y[i] ~ dnorm(mu[xi[i]], sd = 1) } }) n <- 15 data <- list(y = c(0, rnorm(n-1, 50, 1))) inits <- list(xi = rep(1,n), mu = rep(50, n)) m <- nimbleModel(code, data=data, inits= inits, constants = list(n=n)) conf <- configureMCMC(m, nodes = 'xi') cm <- compileNimble(m) mcmc <- buildMCMC(conf) cmcmc <- compileNimble(mcmc, project=m) cmcmc$run(1) expect_lt(abs(cm$mu[2]), 3, label = 'mu[2] is not changed') expect_identical(cm$mu[3], 50, info = 'mu[3] is changed') expect_identical(cmcmc$mvSaved[['mu']], cm$mu) expect_identical(cmcmc$mvSaved[['logProb_mu']], cm$logProb_mu) expect_identical(sum(cm$logProb_mu), cm$calculate('mu')) expect_identical(cmcmc$mvSaved[['xi']], cm$xi) expect_identical(cmcmc$mvSaved[['logProb_xi']], cm$logProb_xi) expect_identical(sum(cm$logProb_xi), cm$calculate('xi')) expect_equal(sum(cmcmc$mvSaved[['logProb_mu']]) + sum(cmcmc$mvSaved[['logProb_xi']]) + sum(cmcmc$mvSaved[['logProb_y']]), cm$calculate()) set.seed(1) code <- nimbleCode({ xi[1:n] ~ dCRP(conc=1, size=n) for(i in 1:n) { muTilde[i] ~ T(dnorm(0, 1), -200, 200) sigmaTilde[i] ~ dinvgamma(a,b) mu[i] <- muTilde[xi[i]] y[i] ~ dnorm(mu[i], sd = sigmaTilde[xi[i]]) } a ~ dgamma(1,1) b ~ dgamma(1,1) }) n <- 15 data <- list(y = rnorm(n)) inits <- list(xi = rep(1,n), muTilde = rnorm(n), sigmaTilde = rinvgamma(n, 1, 1)) m <- nimbleModel(code, data=data, inits= inits, constants = list(n=n)) conf <- configureMCMC(m, nodes = 'xi') cm <- compileNimble(m) mcmc <- buildMCMC(conf) cmcmc <- compileNimble(mcmc, project=m) cmcmc$run(10) expect_identical(cmcmc$mvSaved[['muTilde']], cm$muTilde) expect_identical(cmcmc$mvSaved[['logProb_muTilde']], cm$logProb_muTilde) expect_identical(cmcmc$mvSaved[['sigmaTilde']], cm$sigmaTilde) expect_identical(cmcmc$mvSaved[['logProb_sigmaTilde']], cm$logProb_sigmaTilde) expect_identical(cmcmc$mvSaved[['mu']], cm$mu) expect_identical(cmcmc$mvSaved[['xi']], cm$xi) expect_identical(cmcmc$mvSaved[['logProb_xi']], cm$logProb_xi) expect_identical(cmcmc$mvSaved[['y']], cm$y) expect_identical(cmcmc$mvSaved[['logProb_y']], cm$logProb_y) expect_identical(cmcmc$mvSaved[['a']], cm$a) expect_identical(cmcmc$mvSaved[['logProb_a']], cm$logProb_a) expect_identical(cmcmc$mvSaved[['b']], cm$b) expect_identical(cmcmc$mvSaved[['logProb_b']], cm$logProb_b) }) test_that("Testing wrapper sampler that avoids sampling empty clusters", { set.seed(1) code = nimbleCode({ xi[1:n] ~ dCRP(conc=1, size=n) for(i in 1:n) { mu[i] ~ dnorm(0,1) y[i] ~ dnorm(mu[xi[i]], sd = 1) } }) n <- 15 data <- list(y = rnorm(n)) inits <- list(xi = rep(1,n), mu=rnorm(n)) m <- nimbleModel(code, data=data, inits= inits, constants = list(n=n)) conf <- configureMCMC(m) samplers <- conf$getSamplers() expect_identical(samplers[[2]]$name, 'CRP_cluster_wrapper', info = "cluster wrapper sampler not set") expect_identical(samplers[[2]]$control$wrapped_type, 'conjugate_dnorm_dnorm_identity_dynamicDeps', info = "cluster wrapper sampler not conjugate") cm <- compileNimble(m) mcmc <- buildMCMC(conf) cmcmc <- compileNimble(mcmc, project=m) out <- runMCMC(cmcmc, 500) expect_identical(1L, length(unique(out[ , paste0('mu[', n, ']')])), info = "last cluster is sampled") focalCluster <- max(out[ , (n+1):(2*n)])-1 focalClusterName <- paste0('mu[', focalCluster, ']') focalClusterPresent <- apply(out[ , (n+1):(2*n)], 1, function(x) focalCluster %in% x) focalClusterNew <- which(diff(focalClusterPresent) == 1)+1 focalClusterAbsent <- which(!focalClusterPresent[-1])+1 smp <- out[ , focalClusterName] expect_false(any(smp[focalClusterNew]- smp[focalClusterNew - 1] == 0), info = 'no new cluster parameter value when new cluster opened') expect_true(all(smp[focalClusterAbsent] - smp[focalClusterAbsent - 1] == 0), info = 'new cluster parameter value despite cluster being closed') set.seed(1) code <- nimbleCode({ xi[1:n] ~ dCRP(conc=1, size=n) for(i in 1:n) { mu[i] ~ dgamma(1,1) y[i] ~ dnorm(mu[xi[i]], sd = 1) } }) n <- 15 data <- list(y = rnorm(n)) inits <- list(xi = rep(1,n), mu=rgamma(n,1,1)) m <- nimbleModel(code, data=data, inits= inits, constants = list(n=n)) conf <- configureMCMC(m) samplers <- conf$getSamplers() expect_identical(samplers[[2]]$name, 'CRP_cluster_wrapper', info = "cluster wrapper sampler not set") expect_identical(samplers[[2]]$control$wrapped_type, 'RW', info = "cluster wrapper sampler conjugate") cm <- compileNimble(m) mcmc <- buildMCMC(conf) cmcmc <- compileNimble(mcmc, project=m) out <- runMCMC(cmcmc, 500) expect_identical(1L, length(unique(out[ , paste0('mu[', n, ']')])), info = "last cluster is sampled") focalCluster <- max(out[ , (n+1):(2*n)])-1 focalClusterName <- paste0('mu[', focalCluster, ']') focalClusterPresent <- apply(out[ , (n+1):(2*n)], 1, function(x) focalCluster %in% x) focalClusterNew <- which(diff(focalClusterPresent) == 1)+1 focalClusterAbsent <- which(!focalClusterPresent[-1])+1 smp <- out[ , focalClusterName] expect_false(any(smp[focalClusterNew]- smp[focalClusterNew - 1] == 0), info = 'no new cluster parameter value when new cluster opened') expect_true(all(smp[focalClusterAbsent] - smp[focalClusterAbsent - 1] == 0), info = 'new cluster parameter value despite cluster being closed') set.seed(1) code = nimbleCode({ xi[1:n] ~ dCRP(conc=1, size=n) for(i in 1:n) { mu[i] ~ dnorm(0,1) y[i] ~ dnorm(mu[xi[i]], sd = 1) } }) n <- 15 data <- list(y = rnorm(n)) inits <- list(xi = rep(1,n), mu=rnorm(n)) m <- nimbleModel(code, data=data, inits= inits, constants = list(n=n)) conf <- configureMCMC(m) conf$removeSamplers('mu') cm <- compileNimble(m) mcmc <- buildMCMC(conf) cmcmc <- compileNimble(mcmc, project=m) out <- runMCMC(cmcmc, 500) expect_identical(1L, length(unique(out[ , paste0('mu[', n, ']')])), info = "last cluster is sampled") focalCluster <- max(out[ , (n+1):(2*n)])-1 focalClusterName <- paste0('mu[', focalCluster, ']') focalClusterPresent <- apply(out[ , (n+1):(2*n)], 1, function(x) focalCluster %in% x) focalClusterNew <- which(diff(focalClusterPresent) == 1)+1 focalClusterAbsent <- which(!focalClusterPresent[-1])+1 smp <- out[ , focalClusterName] expect_false(any(smp[focalClusterNew]- smp[focalClusterNew - 1] == 0), info = 'no new cluster parameter value when new cluster opened') expect_true(all(smp[focalClusterAbsent] - smp[focalClusterAbsent - 1] == 0), info = 'new cluster parameter value despite cluster being closed') set.seed(1) code <- nimbleCode({ xi[1:n] ~ dCRP(conc=1, size=n) for(i in 1:n) { mu[i] ~ dgamma(1,1) y[i] ~ dnorm(mu[xi[i]], sd = 1) } }) n <- 15 data <- list(y = rnorm(n)) inits <- list(xi = rep(1,n), mu=rgamma(n,1,1)) m <- nimbleModel(code, data=data, inits= inits, constants = list(n=n)) conf <- configureMCMC(m) conf$removeSamplers('mu') cm <- compileNimble(m) mcmc <- buildMCMC(conf) cmcmc <- compileNimble(mcmc, project=m) out <- runMCMC(cmcmc, 500) expect_identical(1L, length(unique(out[ , paste0('mu[', n, ']')])), info = "last cluster is sampled") focalCluster <- max(out[ , (n+1):(2*n)])-1 focalClusterName <- paste0('mu[', focalCluster, ']') focalClusterPresent <- apply(out[ , (n+1):(2*n)], 1, function(x) focalCluster %in% x) focalClusterNew <- which(diff(focalClusterPresent) == 1)+1 focalClusterAbsent <- which(!focalClusterPresent[-1])+1 smp <- out[ , focalClusterName] expect_false(any(smp[focalClusterNew]- smp[focalClusterNew - 1] == 0), info = 'no new cluster parameter value when new cluster opened') expect_true(all(smp[focalClusterAbsent] - smp[focalClusterAbsent - 1] == 0), info = 'new cluster parameter value despite cluster being closed') set.seed(1) code <- nimbleCode({ xi[1:n] ~ dCRP(conc=1, size=n) for(i in 1:n) { mu[i] ~ dnorm(0,1) sigma[i] ~ dinvgamma(1,1) y[i] ~ dnorm(mu[xi[i]], var = sigma[xi[i]]) } }) n <- 15 data <- list(y = rnorm(n)) inits <- list(xi = rep(1,n), mu = rnorm(n), sigma = rinvgamma(n, 1, 1)) m <- nimbleModel(code, data=data, inits= inits, constants = list(n=n)) conf <- configureMCMC(m) samplers <- conf$getSamplers() expect_identical(samplers[[2]]$name, 'CRP_cluster_wrapper', info = "cluster wrapper sampler not set") expect_identical(samplers[[17]]$name, 'CRP_cluster_wrapper', info = "cluster wrapper sampler not set") cm <- compileNimble(m) mcmc <- buildMCMC(conf) cmcmc <- compileNimble(mcmc, project=m) out <- runMCMC(cmcmc, 500) expect_identical(1L, length(unique(out[ , paste0('mu[', n, ']')])), info = "last cluster is sampled") focalCluster <- max(out[ , (2*n+1):(3*n)])-1 focalClusterPresent <- apply(out[ , (2*n+1):(3*n)], 1, function(x) focalCluster %in% x) focalClusterNew <- which(diff(focalClusterPresent) == 1)+1 focalClusterAbsent <- which(!focalClusterPresent[-1])+1 focalClusterName <- paste0('mu[', focalCluster, ']') smp <- out[ , focalClusterName] expect_false(any(smp[focalClusterNew]- smp[focalClusterNew - 1] == 0), info = 'no new cluster parameter value when new cluster opened') expect_true(all(smp[focalClusterAbsent] - smp[focalClusterAbsent - 1] == 0), info = 'new cluster parameter value despite cluster being closed') focalClusterName <- paste0('sigma[', focalCluster, ']') smp <- out[ , focalClusterName] expect_false(any(smp[focalClusterNew]- smp[focalClusterNew - 1] == 0), info = 'no new cluster parameter value when new cluster opened') expect_true(all(smp[focalClusterAbsent] - smp[focalClusterAbsent - 1] == 0), info = 'new cluster parameter value despite cluster being closed') set.seed(1) code = nimbleCode({ xi[1:n] ~ dCRP(conc=1, size=n) for(i in 1:n) { mu[i, 1:3] ~ dmnorm(z[1:3], pr[1:3,1:3]) tmp[i, 1:3] <- exp(mu[xi[i],1:3]) y[i,1:3] ~ dmnorm(tmp[i,1:3], pr[1:3,1:3]) } }) n <- 15 data <- list(y = matrix(rnorm(n*3, 1, 1),n)) inits <- list(xi = rep(1,n), mu = matrix(rnorm(n*3), n), pr = diag(3), z = rep(0,3)) m <- nimbleModel(code, data=data, inits= inits, constants = list(n=n)) conf <- configureMCMC(m) samplers <- conf$getSamplers() expect_identical(samplers[[2]]$name, 'CRP_cluster_wrapper', info = "cluster wrapper sampler not set") expect_identical(samplers[[2]]$control$wrapped_type, 'RW_block', info = "cluster wrapper sampler conjugate") cm <- compileNimble(m) mcmc <- buildMCMC(conf) cmcmc <- compileNimble(mcmc, project=m) out <- runMCMC(cmcmc, 500) expect_identical(1L, length(unique(out[ , paste0('mu[', n, ', 3]')])), info = "last cluster is sampled") focalCluster <- max(out[ , (3*n+1):(4*n)])-1 focalClusterName <- paste0('mu[', focalCluster, ', 3]') focalClusterPresent <- apply(out[ , (3*n+1):(4*n)], 1, function(x) focalCluster %in% x) focalClusterNew <- which(diff(focalClusterPresent) == 1)+1 focalClusterAbsent <- which(!focalClusterPresent[-1])+1 smp <- out[ , focalClusterName] expect_false(any(smp[focalClusterNew]- smp[focalClusterNew - 1] == 0), info = 'no new cluster parameter value when new cluster opened') expect_true(all(smp[focalClusterAbsent] - smp[focalClusterAbsent - 1] == 0), info = 'new cluster parameter value despite cluster being closed') code <- nimbleCode({ xi[1:n] ~ dCRP(conc=1, size=n) for(i in 1:n) { mu[i] ~ dgamma(1,1) y[i] ~ dnorm(mu[xi[i]], sd = 1) } xi2[1:n] ~ dCRP(conc=1, size=n) for(i in 1:n) { mu2[i] ~ dnorm(0,1) y2[i] ~ dnorm(mu2[xi2[i]], sd = 1) } }) n <- 15 data <- list(y = rnorm(n), y2 = rnorm(n)) inits <- list(xi = rep(1,n), mu=rgamma(n,1,1), xi2 = rep(1,n), mu2 = rnorm(n)) m <- nimbleModel(code, data=data, inits= inits, constants = list(n=n)) conf <- configureMCMC(m) mcmc <- buildMCMC(conf) cm <- compileNimble(m) cmcmc <- compileNimble(mcmc,project=m) out <- runMCMC(cmcmc, 10) }) test_that("offset and coeff set up in conjugacy for BNP so that non-dependencies are screened out", { code <- nimbleCode({ for(i in 1:2) { y[i] ~ dnorm(mu[xi[i]], 1) mu[i] ~ dnorm(0,1) } xi[1:2] ~ dCRP(1, 2) }) m <- nimbleModel(code, data = list (y = rnorm(2)), inits = list(mu = rnorm(2), xi = rep(1,2))) conf <- configureMCMC(m) mcmc <- buildMCMC(conf) expect_identical(mcmc$samplerFunctions[[2]]$regular_sampler[[1]]$N_dep_dnorm_identity, 2L) expect_identical(c('dep_dnorm_identity_offset', 'dep_dnorm_identity_coeff') %in% ls(mcmc$samplerFunctions[[2]]$regular_sampler[[1]]), rep(TRUE, 2)) code <- nimbleCode({ for(i in 1:2) { y[i, 1:3] ~ dmnorm(mu[xi[i], 1:3], pr[1:3,1:3]) mu[i, 1:3] ~ dmnorm(z[1:3], pr[1:3,1:3]) } xi[1:2] ~ dCRP(1, 2) }) m <- nimbleModel(code, data = list (y = matrix(rnorm(6), 2)), inits = list(mu = matrix(rnorm(6),2), xi = rep(1,2), pr = diag(3))) conf <- configureMCMC(m) mcmc <- buildMCMC(conf) expect_identical(mcmc$samplerFunctions[[2]]$regular_sampler[[1]]$N_dep_dmnorm_identity, 2L) expect_identical(c('dep_dmnorm_identity_offset', 'dep_dmnorm_identity_coeff') %in% ls(mcmc$samplerFunctions[[2]]$regular_sampler[[1]]), rep(TRUE, 2)) code <- nimbleCode({ for(i in 1:2) { mn[i, 1:3] <- A[1:3,1:3]%*%mu[xi[i], 1:3] y[i, 1:3] ~ dmnorm(mn[i, 1:3], pr[1:3,1:3]) mu[i, 1:3] ~ dmnorm(z[1:3], pr[1:3,1:3]) } xi[1:2] ~ dCRP(1, 2) }) m <- nimbleModel(code, data = list (y = matrix(rnorm(6), 2)), inits = list(A = diag(3), mu = matrix(rnorm(6),2), xi = rep(1,2), pr = diag(3))) conf <- configureMCMC(m) mcmc <- buildMCMC(conf) expect_identical(mcmc$samplerFunctions[[2]]$regular_sampler[[1]]$N_dep_dmnorm_multiplicative, 2L) expect_identical(c('dep_dmnorm_multiplicative_offset', 'dep_dmnorm_multiplicative_coeff') %in% ls(mcmc$samplerFunctions[[2]]$regular_sampler[[1]]), rep(TRUE, 2)) code <- nimbleCode({ for(i in 1:2) { y[i, 1:3] ~ dmnorm(mu[1:3], pr[xi[i], 1:3,1:3]) pr[i, 1:3,1:3] ~ dwish(R[1:3,1:3], 8) } xi[1:2] ~ dCRP(1, 2) }) pr <- array(0, c(2, 3, 3)); pr[1,,] <- pr[2,,] <- diag(3) m <- nimbleModel(code, data = list(y = matrix(rnorm(6),2)), inits = list(xi = rep(1,2), pr = pr, R = diag(3))) conf <- configureMCMC(m) mcmc <- buildMCMC(conf) expect_identical(mcmc$samplerFunctions[[2]]$regular_sampler[[1]]$N_dep_dmnorm_identity, 2L) expect_identical(c('dep_dmnorm_identity_offset', 'dep_dmnorm_identity_coeff') %in% ls(mcmc$samplerFunctions[[2]]$regular_sampler[[1]]), c(FALSE, TRUE)) code <- nimbleCode({ for(i in 1:2) { y[i, 1:3] ~ dmnorm(mu[1:3], pr0[i, 1:3, 1:3]) pr0[i, 1:3,1:3] <- theta * pr[xi[i], 1:3,1:3] pr[i, 1:3,1:3] ~ dwish(R[1:3,1:3], 8) } xi[1:2] ~ dCRP(1, 2) }) pr <- array(0, c(2, 3, 3)); pr[1,,] <- pr[2,,] <- diag(3) m <- nimbleModel(code, data = list(y = matrix(rnorm(6),2)), inits = list(xi = rep(1,2), pr = pr, R = diag(3))) conf <- configureMCMC(m) mcmc <- buildMCMC(conf) expect_identical(mcmc$samplerFunctions[[2]]$regular_sampler[[1]]$N_dep_dmnorm_multiplicativeScalar, 2L) expect_identical(c('dep_dmnorm_multiplicativeScalar_offset', 'dep_dmnorm_multiplicativeScalar_coeff') %in% ls(mcmc$samplerFunctions[[2]]$regular_sampler[[1]]), c(FALSE, TRUE)) }) options(warn = RwarnLevel) nimbleOptions(verbose = nimbleVerboseSetting) nimbleOptions(MCMCprogressBar = nimbleProgressBarSetting)
plsRglm <- function(x, ...) UseMethod("plsRglmmodel") plsRglmmodel <- plsRglm
ARM2.order <- function(x,y,pmax) { aicmat=matrix(NA,nrow=pmax); bicmat=matrix(NA,nrow=pmax); for (i in 1:pmax) { M = ARM2(x,y,p=i) aicmat[i,]=M$aic;bicmat[i,]=M$bic; } p.aic=which.min(aicmat) p.bic=which.min(bicmat) return(list(p.aic=p.aic,p.bic=p.bic)) }
context("Final tests") test_that("tmp_load does not exist", { expect_false(any(grepl("tmp_load", list.files(".", recursive = TRUE)))) }) test_that("~/R/sdmpredictors was not created", { if(dir.exists("~/R/sdmpredictors")) { skip_on_cran() skip_on_ci() creation_time <- file.info("~/R/sdmpredictors")[1,"ctime"] modified_time <- file.info("~/R/sdmpredictors")[1,"mtime"] expect_gt(as.double(difftime(Sys.time(), creation_time, units = "mins")), 20) expect_gt(as.double(difftime(Sys.time(), modified_time, units = "mins")), 10) } else { expect_false(dir.exists("~/R/sdmpredictors")) } })
document_waves <- function( survey_list ) { validate_survey_list(survey_list) n_survey <- length(survey_list) tmp <- tibble( id = vapply ( survey_list, function(x) attr(x, "id"), character(1)), filename = vapply ( survey_list, function(x) attr(x, "filename"), character(1)), ncol = vapply (survey_list, ncol, integer(1)), nrow = vapply ( survey_list, nrow, integer(1)), object_size = vapply ( survey_list, object.size, double(1)) ) attr(tmp, "original_list") <- deparse(substitute(survey_list)) tmp }
select_seasons = function(x, max.season = 4, lrt = FALSE, print = TRUE) { listOfFits = list() n.seasons = 0 while (n.seasons <= max.season) { message(paste("Fitting model with", n.seasons, "seasons...\n")) listOfFits[[n.seasons+1]] = fit_cyclomort(x, n.seasons = n.seasons) names(listOfFits)[n.seasons + 1] = paste0("fit",n.seasons) n.seasons = n.seasons + 1 } lof.summary <- summarize_listOfFits(listOfFits, lrt = lrt, print = print) class(listOfFits) = "cmfitlist" return(list(fits = listOfFits, summary = lof.summary)) } summarize_listOfFits <- function(listOfFits, lrt = lrt, print = print){ AIC.table <- ldply(listOfFits, summarize, n.seasons = n.seasons, logLik = logLik, d.f. = ifelse(n.seasons == 0, 1, n.seasons * 3), AIC = AIC) %>% mutate(dAIC = AIC - min(AIC), .id = NULL) n.seasons <- length(listOfFits) - 1 if(print){ cat("\nDelta AIC table of fitted models:\n") print(AIC.table, row.names = FALSE) } if(lrt){ fits.ll <- AIC.table$logLik %>% as.numeric ks <- AIC.table$d.f. chisq.vals <- (outer(fits.ll, fits.ll, `-`) %>% abs) * 2 dfs <- outer(ks, ks, `-`) %>% abs p.vals <- 1-pchisq(chisq.vals, ks) mat.names <- outer(0:n.seasons, 0:n.seasons, paste, sep = "-") ut <- upper.tri(mat.names) LRT.table <- data.frame( comparison = mat.names[ut], ChiSq = chisq.vals[ut] %>% round(2), d.f. = dfs[ut], p.value = p.vals[ut] %>% signif(3)) %>% arrange(comparison) %>% mutate(signif = cut(p.value, c(-1,0.001, 0.01, 0.05, 0.1, 1), labels = c("***", "**", "*", "-", ""))) if(print){ cat("\nNested likelihood-ratio tests:\n") print(LRT.table, row.names = FALSE) } } else LRT.table <- NULL return(list(AIC.table = AIC.table, LRT.table = LRT.table)) }
context("test-create_importance_data") test_that("create importance data works", { model_final <- lm(mpg ~ cyl + wt + hp + gear + carb, data=mtcars) model_null <- lm(mpg ~ 1, data=mtcars) tab_summary <- .create_tab_summary(model_final, model_null, dict=NA, isDeviance=FALSE) expect_equal("data.frame", class(tab_summary)) expect_equal(1, tab_summary$cum_contr[nrow(tab_summary)]) dat2 <- .create_common_importance_data(tab_summary) expect_equal(class(dat2), "data.frame") })
requiet("betareg") requiet("margins") requiet("emmeans") requiet("broom") test_that("marginaleffects: vs. margins vs. emmeans", { set.seed(1024) data("GasolineYield", package = "betareg") tmp <- GasolineYield tmp$batch <- factor(tmp$batch) mod <- betareg::betareg(yield ~ batch + temp, data = tmp) suppressWarnings({ res <- marginaleffects(mod, variables = "temp") mar <- data.frame(margins::margins(mod, unit_ses = TRUE)) }) expect_true(test_against_margins(res, mar, tolerance = 0.1)) mfx <- marginaleffects(mod, newdata = datagrid(batch = 1), variables = "temp") em <- suppressWarnings( emtrends(mod, ~temp, "temp", at = list("batch" = GasolineYield$batch[1]))) em <- tidy(em) expect_equal(mfx$dydx, em$temp.trend, tolerance = .001) expect_equal(mfx$std.error, em$std.error, tolerance = .001) }) test_that("marginaleffects: vs. Stata", { stata <- readRDS(test_path("stata/stata.rds"))[["betareg_betareg_01"]] dat <- read.csv(test_path("stata/databases/betareg_betareg_01.csv")) mod <- betareg::betareg(yield ~ factor(batch) + temp, data = dat) mfx <- merge(tidy(marginaleffects(mod)), stata) expect_equal(mfx$estimate, mfx$dydxstata, tolerance = .0001) expect_equal(mfx$std.error, mfx$std.errorstata, tolerance = .0001) }) test_that("predictions: no validity", { set.seed(1024) data("GasolineYield", package = "betareg") mod <- betareg::betareg(yield ~ batch + temp, data = GasolineYield) pred <- predictions(mod) expect_predictions(pred, n_row = nrow(GasolineYield)) pred <- predictions(mod, newdata = datagrid(batch = 1:3, temp = c(300, 350))) expect_predictions(pred, n_row = 6) }) test_that("marginalmeans: vs. emmeans", { set.seed(1024) data("GasolineYield", package = "betareg") mod <- betareg::betareg(yield ~ batch + temp, data = GasolineYield) mm <- marginalmeans(mod) expect_marginalmeans(mm, n_row = 10) mm <- tidy(mm) em <- broom::tidy(emmeans::emmeans(mod, "batch")) expect_equal(mm$estimate, em$estimate) expect_equal(mm$std.error, em$std.error, tolerance = .01) })
sink(stdout(), type = "message") overwrite <- TRUE verbose <- TRUE args <- commandArgs(trailingOnly = TRUE) usage <- function(msg) { print(msg) print(paste0("Usage: ", args[0], " cf-nc_Input_File outputfile [tempfolder]")) print(paste0("Example1: ", args[0], " US-Dk3.pecan.nc US-Dk3.clim [/tmp/watever]")) print(paste0("Example2: ", args[0], " US-Dk3.pecan.zip US-Dk3.clim [/tmp/watever]")) stop() } if (length(args) < 2) { usage("Not enough arguments") } if (length(args) > 2) { tempDir <- args[3] } else { tempDir <- "temp" } inputFile <- args[1] outputFile <- args[2] cffolder <- file.path(tempDir, "cf") dir.create(cffolder, showWarnings = FALSE, recursive = TRUE) outfolder <- file.path(tempDir, "clim") dir.create(outfolder, showWarnings = FALSE, recursive = TRUE) if (grepl("pecan.zip$", args[1])) { system2(Sys.which("unzip"), c("-o", "-d", cffolder, inputFile)) site <- NA startYear <- NA endYear <- NA for (file in list.files(path = cffolder, pattern = "*.nc$")) { pieces <- strsplit(file, ".", fixed = TRUE)[[1]] if (length(pieces) != 3) { usage(paste0("invalid file ", file, " should be <site>.<year>.nc")) } if (is.na(site)) { site <- pieces[1] } else if (site != pieces[1]) { usage(paste0("inconsistent sites ", file, " should be ", site, ".<year>.nc")) } if (is.na(startYear) || pieces[2] < startYear) { startYear <- pieces[2] } if (is.na(endYear) || pieces[2] > endYear) { endYear <- pieces[2] } startDate <- as.POSIXlt(paste0(startYear, "-01-01 00:00:00"), tz = "UTC") endDate <- as.POSIXlt(paste0(endYear, "-12-31 23:59:59"), tz = "UTC") } } else if (grepl("pecan.nc$", inputFile)) { pieces <- strsplit(inputFile, ".", fixed = TRUE)[[1]] if (length(piecesx) != 4) { usage("Input file name should be of format <site>.<year>.pecan.nc") } site <- pieces[1] year <- pieces[2] file.copy(inputFile, file.path(cffolder, paste(site, year, "nc", sep = "."))) startDate <- as.POSIXlt(paste0(year, "-01-01 00:00:00"), tz = "UTC") endDate <- as.POSIXlt(paste0(year, "-12-31 23:59:59"), tz = "UTC") } else { usage("Did not recognize type of file") } library(PEcAn.SIPNET) result <- met2model.SIPNET(cffolder, site, outfolder, start_date = startDate, end_date = endDate, overwrite = overwrite) file.rename(result$file, outputFile)
"cpmexample1"
A1 <- matrix(c(1,0,0,0,0, 0,0,1,0,0, 0,0,0,1,0, 0,0,0,0,1), nrow=5, ncol=4) A2 <- matrix(c(1,0,0,0,0, 0,1,0,0,0, 0,0,1,0,0, 0,0,0,1,0), nrow=5, ncol=4) H41 <- summary(alrtest(z = H1, A = A1, r = 2)) H42 <- summary(alrtest(z = H1, A = A2, r = 2))
require(BB) dgaussmix <- function (p) { prop <- p[1:nmix] mu <- p[(nmix+1):(2*nmix)] sigma <- p[(2*nmix+1)] sapply(y, function(y)sum(prop*dnorm(y,mean=mu,sd=sqrt(sigma)))) } rgaussmix <- function (n, prop, mu, sigma) { nmix <- length(mu) imix <- sample(1:nmix, size=n, prob=prop, rep=TRUE) y <- rnorm(n, mean = mu[imix], sd = sqrt(sigma)) return(y) } gaussmix.mloglik <- function(p){ - sum(log(dgaussmix(p))) } gaussmix.grad <- function(p){ g <- rep(NA, length(p)) f <- dgaussmix(p) pj <- p[1:nmix] mu <- p[(nmix+1): (2*nmix)] sigma <- p[2*nmix + 1] phi <- outer(y, mu, function(y, mu) dnorm(y,mean=mu,sd=sqrt(sigma))) g[1:nmix] <- - colSums(phi/f) phi2 <- outer(y, mu, function(y, mu) (y - mu)/sigma) fimuj <- t(t(phi * phi2) * pj) g[(nmix+1): (2*nmix)] <- - colSums(fimuj/f) phi3 <- outer(y, mu, function(y, mu) (y - mu)^2/sigma) fisig <- apply(t(t(phi * ( 1 - phi3) ) * pj), 1, sum) g[2*nmix+1] <- sum(fisig / f) / (2 * sigma) g } heq <- function(x) { x[1] + x[2] + x[3] + x[4] - 1 } hin <- function(x) { h <- rep(NA, 9) h[1] <- x[1] h[2] <- x[2] h[3] <- x[3] h[4] <- x[4] h[5] <- 1 - x[1] h[6] <- 1 - x[2] h[7] <- 1 - x[3] h[8] <- 1 - x[4] h[9] <- x[9] h } Amat <- matrix(0, 10, 9) Amat[1, 1:4] <- 1 Amat[2,1] <- Amat[3,2] <- Amat[4,3] <- Amat[5,4] <- Amat[10,9] <- 1 Amat[6, 1] <- Amat[7, 2] <- Amat[8, 3] <- Amat[9, 4] <- -1 b <- c(1,0,0,0,0,-1,-1,-1,-1, 0) meq <- 1 p <- c(0.2,0.4,0.2,0.2) nmix <- length(p) mu <- c(0,3,7,11) sigma <- 2 npts <- 500 set.seed(12345) y <- rgaussmix(npts, p, mu, sigma) ymean <- mean(y) ysd <- sd(y) p0 <- rep(1/nmix, nmix) ymean0 <- ymean + ysd * runif(nmix, -1.2, 1.2) ysd0 <- ysd par0 <- c(p0,ymean0, ysd0^2) ans <- spg(par=par0, fn=gaussmix.mloglik, gr=gaussmix.grad, project="projectLinear", projectArgs=list(A=Amat, b=b, meq=meq)) if (0 != ans$convergence) stop("test did not converge!") fuzz <- 5e-5 if(fuzz < max(abs(ans$par - c( 0.2103359277577284137, 0.2191738028962620377, 0.2174358494266191433, 0.3530544199193904609, 7.0060291485783237064, 11.2527073428970716407, -0.0166017473519236673, 2.9360474287487265954, 2.0609328632879644339)))){ print(ans$par, digits=18) cat("difference:\n") print(ans$par - c( 0.2103359277577284137, 0.2191738028962620377, 0.2174358494266191433, 0.3530544199193904609, 7.0060291485783237064, 11.2527073428970716407, -0.0166017473519236673, 2.9360474287487265954, 2.0609328632879644339), digits=18) stop("converged to different parameter values!") } if(fuzz < max(abs(ans$value - 1388.64728677794915))){ print(ans$value, digits=18) stop("converged to different function value!") } ans Amat <- matrix(0, 1, 9) Amat[1, 1:4] <- 1 b <- 1 meq <- 1 ans2 <- spg(par=par0, fn=gaussmix.mloglik, gr=gaussmix.grad, lower=c(rep(0,4), rep(-Inf, 4), 0), upper=c(rep(1,4), rep(Inf, 4), Inf), project="projectLinear", projectArgs=list(A=Amat, b=b, meq=meq)) if(fuzz < max(abs(ans$par - ans2$par))){ print(ans2$par, digits=18) cat("difference:\n") print(ans$par - ans2$par, digits=18) stop("converged to different parameter values with lower and upper!") } if(fuzz < max(abs(ans$value - ans2$value))){ print(ans2$value, digits=18) stop("converged to different function value with lower and upper!") } ans2
fitted.mix <- function(object, digits = NULL, ...) { mixobj<-object pmat <- grpintprob(mixobj$mixdata, mixobj$parameters, mixobj$distribution, mixobj$constraint) n <- sum(mixobj$mixdata[, 2]) joint <- n * sweep(pmat, 2, mixobj$parameters[, 1], "*") mixed <- apply(joint, 1, sum) conditprob <- sweep(joint, 1, mixed, "/") if (mixobj$usecondit) { conditional <- sweep(conditprob, 1, apply(mixobj$mixdata[, -(1:2)], 1, sum), "*") outlist <- list(mixed = mixed, joint = joint, conditional = conditional, conditprob = conditprob) } else outlist <- list(mixed = mixed, joint = joint, conditprob = conditprob) if (is.null(digits)) outlist else sapply(outlist, round, digits) }
if(requireNamespace("numDeriv", quietly = TRUE)){ q <- c(rep(1, 2), rep(0, 20)) xnames <- c("W", "H", paste("x", 1:5, sep = ""), paste("y", 1:5, sep = ""), paste("w", 1:5, sep = ""), paste("h", 1:5, sep = "") ) gamma <- 5.0 rho <- 1.0 Amin <- 100 G <- matrix(0.0, nrow = 26, ncol = 22) h <- matrix(0.0, nrow = 26, ncol = 1) G[1, 3] <- -1.0 G[2, 4] <- -1.0 G[3, 6] <- -1.0 G[4, c(3, 5, 13)] <- c(1.0, -1.0, 1.0) h[4, 1] <- -rho G[5, c(4, 5, 14)] <- c(1.0, -1.0, 1.0) h[5, 1] <- -rho G[6, c(5, 7, 15)] <- c(1.0, -1.0, 1.0) h[6, 1] <- -rho G[7, c(6, 7, 16)] <- c(1.0, -1.0, 1.0) h[7, 1] <- -rho G[8, c(1, 7, 17)] <- c(-1.0, 1.0, 1.0) G[9, 9] <- -1.0 G[10, 10] <- -1.0 G[11, 12] <- -1.0 G[12, c(8, 9, 19)] <- c(-1.0, 1.0, 1.0) h[12, 1] <- -rho G[13, c(8, 11, 18)] <- c(1.0, -1.0, 1.0) h[13, 1] <- -rho G[14, c(10, 11, 20)] <- c(1.0, -1.0, 1.0) h[14, 1] <- -rho G[15, c(2, 11, 21)] <- c(-1.0, 1.0, 1.0) G[16, c(2, 12, 22)] <- c(-1.0, 1.0, 1.0) G[17, c(13, 18)] <- c(-1.0, 1.0 / gamma) G[18, c(13, 18)] <- c(1.0, -gamma) G[19, c(14, 19)] <- c(-1.0, 1.0 / gamma) G[20, c(14, 19)] <- c(1.0, -gamma) G[21, c(15, 19)] <- c(-1.0, 1.0 / gamma) G[22, c(15, 20)] <- c(1.0, -gamma) G[23, c(16, 20)] <- c(-1.0, 1.0 / gamma) G[24, c(16, 21)] <- c(1.0, -gamma) G[25, c(16, 21)] <- c(-1.0, 1.0 / gamma) G[26, c(17, 22)] <- c(1.0, -gamma) nno1 <- nnoc(G = G, h = h) f1 <- function(x) -x[13] + Amin / x[18] f2 <- function(x) -x[14] + Amin / x[19] f3 <- function(x) -x[15] + Amin / x[20] f4 <- function(x) -x[16] + Amin / x[21] f5 <- function(x) -x[17] + Amin / x[22] g1 <- function(x, func = f1) numDeriv::grad(func = func, x = x) g2 <- function(x, func = f2) numDeriv::grad(func = func, x = x) g3 <- function(x, func = f3) numDeriv::grad(func = func, x = x) g4 <- function(x, func = f4) numDeriv::grad(func = func, x = x) g5 <- function(x, func = f5) numDeriv::grad(func = func, x = x) h1 <- function(x, func = f1) numDeriv::hessian(func = func, x = x) h2 <- function(x, func = f2) numDeriv::hessian(func = func, x = x) h3 <- function(x, func = f3) numDeriv::hessian(func = func, x = x) h4 <- function(x, func = f4) numDeriv::hessian(func = func, x = x) h5 <- function(x, func = f5) numDeriv::hessian(func = func, x = x) x0 <- rep(1, 22) ans <- cccp(q = q, cList = list(nno1), x0 = x0, nlfList = list(f1, f2, f3, f4, f5), nlgList = list(g1, g2, g3, g4, g5), nlhList = list(h1, h2, h3, h4, h5)) xsol <- getx(ans) names(xsol) <- xnames xsol plot(c(0, xsol["W"]), c(0, xsol["H"]), type = "n", xlab = "", ylab = "", main = "Floor Planning") for(i in 1:5){ rect(xleft = xsol[i + 2], ybottom = xsol[i + 7], xright = xsol[i + 2] + xsol[i + 12], ytop = xsol[i + 7] + + xsol[i + 17], col = "gray", border = "black", lty = 1, lwd = 1) text(x = c(xsol[i + 2] + xsol[i + 12] / 2), y = c(xsol[i + 7] + + xsol[i + 17] / 2), labels = i) } }
NULL getExamplePkModel <- function( ) { dataParametersFile <- system.file("extData", "examplePkParameters.csv" , package = "microsamplingDesign") exampleParameters <- read.csv( dataParametersFile , stringsAsFactors = FALSE , na.strings = NULL ) nParam <- nrow( exampleParameters ) parameterNames <- exampleParameters$parameter correlationMatrix <- diag( rep( 1 , nParam ) ) colnames( correlationMatrix ) <- parameterNames rownames( correlationMatrix ) <- parameterNames pkModel <- new( "PkModel" , modelFunction = get2ComptModelCurve , parameters = exampleParameters , correlationMatrix = correlationMatrix , coeffVariationError = 0.1 , dosingInfo = data.frame( time = c( 0 , 2 ) , dose = c( 20 , 30 ) , stringsAsFactors = TRUE ) ) return( pkModel ) } construct2CompModel <- function( parameters , dosingInfo , correlationMatrix = NULL , coeffVariationError = 0 ) { nParameters <- nrow( parameters ) parameterNames <- parameters$parameter if( is.null( correlationMatrix ) ) { correlationMatrix <- diag( 1 , nParameters ) colnames( correlationMatrix ) <- parameterNames rownames( correlationMatrix ) <- parameterNames } pkModel <- new( "PkModel" , modelFunction = get2ComptModelCurve , parameters = parameters , dosingInfo = dosingInfo , correlationMatrix = correlationMatrix, coeffVariationError = coeffVariationError ) return( pkModel ) } if( 0 == 1 ) { model <- getExampleModel object <- model setParameters(object) <- data.frame(zever = 1) object <- getExamplePkModel() validatePkModel( object ) object@correlationMatrix <- rbind(cbind(object@correlationMatrix , 1 ) , 1 ) validatePkModel( object ) } validatePkModel <- function( object ) { errors <- character( ) parameterSlot <- object@parameters nParameters <- nrow( parameterSlot ) parameterSlotNamesMin <- c( "parameter" , "value" , "coeffVariation" ) paramSlotNames <- colnames( parameterSlot ) checkParamNames <- all( parameterSlotNamesMin %in% paramSlotNames ) if( ! checkParamNames ) { msg <- paste0( "column names of slot parameters should be: ( " , paste0( parameterSlotNamesMin , collapse = ", " ) ,")" , "\n" ) errors <- c( errors , msg ) } CVResidual <- object@coeffVariationError checkOneValue <- length( CVResidual ) == 1 checkNumeric <- is.numeric( CVResidual ) if( ! ( checkOneValue && checkNumeric ) ) { msg <- paste0( "coeffVariationError should be one numeric value" , "\n") errors <- c( errors , msg ) } if ( length( errors) == 0 ) { return( TRUE ) } else { cat( errors ) return( FALSE ) } } setClass("PkModel", contains = c( "PkModelParent" ) ) setValidity( "PkModel" , validatePkModel ) plotPkModel <- function( object , times , nCurves = 12 , nSamplesIntegration = 1000 , seed = 134 , sampleCurvesOnly = FALSE , indSamplingPoints = FALSE ) { set.seed( seed ) nTimes <- length( times ) set.seed( seed ) exampleCurves <- getPkData( pkModel = object, timePoints = times , nSubjectsPerScheme = 1 , nSamples = nCurves ) plotObject( object = exampleCurves , nCurves = NULL , nSamplesIntegration = nSamplesIntegration , sampleCurvesOnly = sampleCurvesOnly , seed = seed , indSamplingPoints = indSamplingPoints ) } setMethod( f = "plotObject" , signature = "PkModel" , definition = plotPkModel ) checkPkData <- function( object ) { errors <- character( ) dimData <- dim( [email protected] ) nDimensions <- length( dimData ) if( !nDimensions == 3 ) { msg <- paste0( "Dimensions of data array should be 3, not: ", nDimensions, "\n" ) errors <- c ( errors, msg ) } timeDimension <- dimData[ 2 ] if( !timeDimension == length( object@timePoints ) ) { msg <- paste0( "time dimension in data does not correspond to number of timePoints", "\n" ) errors <- c( errors, msg ) } if( ! is.numeric( [email protected] ) ) { msg <- paste("Data values should be numeric" , "\n" ) errors <- c( errors, msg ) } if ( length(errors) == 0 ) { TRUE } else { cat( errors ) FALSE } } setClass("PkData", contains = "PkModel", slots = c( .Data = "array", timePoints = "vector" ) , validity = checkPkData ) setMethod( f = "getPkModel" , signature = "PkData" , definition = function( object ) { model <- object@modelFunction parameters <- object@parameters dosingInfo <- object@dosingInfo corrMat <- object@correlationMatrix addError <- object@coeffVariationError pkModel <- new( "PkModel" , modelFunction = model , parameters = parameters , correlationMatrix = corrMat , coeffVariationError = addError , dosingInfo = dosingInfo ) return( pkModel ) } ) getExampleData <- function( ) { timePoints <- c( 0.5 , 1 , 2 , 10 ) pkModel <- getExamplePkModel() dataExample <- getPkData( pkModel , timePoints , nSubjectsPerScheme = 2 , nSamples = 7 ) return( dataExample ) } setMethod( "getTimePoints", "PkData", function( object ) { return( object@timePoints ) } ) setMethod( "getData", "PkData", function( object ) { return( [email protected] ) } ) if( 0 == 1 ) { object <- getExampleData() timePointsSelect <- c( 0.5 , 1 ) .PkDataClass.timePointSubset( object, timePointsSelect ) subsetOnTimePoints.PkData( object, c( 1 , 3 , 20 ) ) subsetOnTimePoints.PkData( object, "blablabla" ) subsetOnTimePoints.PkData( object, "blablabla" ) } subsetOnTimePoints.PkData <- function( object, timePointsSelect ) { timePoints <- getTimePoints(object) flagSubset <- timePointsSelect %in% timePoints if( !all( flagSubset ) ) { stop( "timePointsSelect is not a subset of the objects' timePoints" ) } flagTimeSelect <- timePoints %in% timePointsSelect dataNew <- getData( object )[ , flagTimeSelect , ] timePointsNew <- getTimePoints( object ) [ flagTimeSelect ] flagGoodTimePointsSelect <- identical( timePointsNew , timePointsSelect) if( !flagGoodTimePointsSelect ) { stop( "incorrect timePoint selection" ) } output <- object output@timePoints <- timePointsNew [email protected] <- dataNew validObject( output ) return( output ) } setMethod( f = subsetOnTimePoints , signature = "PkModel", definition = subsetOnTimePoints.PkData ) rm( subsetOnTimePoints.PkData ) if( 0 == 1 ) { object <- getPkData( getExamplePkModel() , 1:10 , 5 , 10 ) nCurves <- 3 plotObject( object = exampleCurves , nCurves = NULL , nSamplesIntegration = nSamplesIntegration , sampleCurvesOnly = sampleCurvesOnly , seed = seed , indSamplingPoints = indSamplingPoints ) } plotPkData <- function( object , nCurves = NULL , nSamplesIntegration = 1000 , sampleCurvesOnly = TRUE , seed = NULL , indSamplingPoints = TRUE , addZeroIsZero = FALSE ) { pkDataFlat <- flattenPkData( object ) times <- getTimePoints( object ) if( addZeroIsZero ){ pkDataFlat <- cbind( 0 , pkDataFlat ) times <- c( 0 , times ) } nSubjects <- nrow( pkDataFlat ) if( ( is.null( nCurves ) ) ) { dataSelect <- pkDataFlat } else if ( nCurves >= nSubjects ) { dataSelect <- pkDataFlat } else { dataSelect <- pkDataFlat[ seq_len( nCurves ) , , drop = FALSE ] } nCurvesSelect <- nrow( dataSelect ) nTimes <- length( times ) exampleCurvesVector <- as.vector( t( dataSelect ) ) curveDataPlot <- data.frame( subject = rep( 1 : nCurvesSelect , rep( nTimes , nCurvesSelect ) ) , time = rep( times , nCurvesSelect) , concentration = exampleCurvesVector , curve = "sample curve" , stringsAsFactors = TRUE ) if( !is.null(seed) ) { set.seed( seed ) } if( ! sampleCurvesOnly ) { popAveragedcurve <- getPopAveragedCurve( timePoints = times , pkModel = object , nSamples = nSamplesIntegration ) avCurve <- data.frame( subject = NA , time = times , concentration = as.vector( popAveragedcurve ) , curve = " averaged curve" , stringsAsFactors = TRUE ) plotData <- rbind( curveDataPlot , avCurve ) lineWidth <- c( 1.75 , 3 ) } else { plotData <- curveDataPlot lineWidth <- 2.5 } with( data = plotData , { plot <- ggplot(data = plotData , aes( x = time , y = concentration , group = subject , size = curve , color = curve ) ) + geom_path() + ylab("\n Concentration in plasma \n") + xlab("\n Time in hours ") + theme( axis.title = element_text(size = rel(1.2)), axis.text = element_text(size = rel(1.2)) ) + scale_colour_grey( start = 0.8 , end = 0.2 ) + scale_size_manual( values = lineWidth ) if( indSamplingPoints ) { plot = plot + geom_point( colour = "dodgerblue3" ) } plot } ) } setMethod( f = "plotObject" , signature = "PkData" , definition = plotPkData )
library(httr) oauth_endpoints("google") myapp <- oauth_app("google", key = "16795585089.apps.googleusercontent.com", secret = "hlJNgK73GjUXILBQvyvOyurl" ) google_token <- oauth2.0_token(oauth_endpoints("google"), myapp, scope = "https://www.googleapis.com/auth/userinfo.profile" ) req <- GET( "https://www.googleapis.com/oauth2/v1/userinfo", config(token = google_token) ) stop_for_status(req) content(req)
setGeneric("overlap", function(venn, slice = "all") { standardGeneric("overlap") } ) setMethod("overlap", c(venn = "Venn", slice = "ANY"), function(venn, slice = "all") { if (slice[1] != "all") { venn2 = venn@sets[slice] inter = purrr::reduce(venn2, function(x, y) intersect(x, y)) } else { inter = purrr::reduce(venn@sets, function(x, y) intersect(x, y)) } inter } ) setGeneric("unite", function(venn, slice = "all") { standardGeneric("unite") } ) setMethod("unite", c(venn = "Venn", slice = "ANY"), function(venn, slice = "all") { if (slice[1] != "all") { venn2 = venn@sets[slice] uni = purrr::reduce(venn2, function(x, y) union(x, y)) } else { uni = purrr::reduce(venn@sets, function(x, y) union(x, y)) } uni } ) setGeneric("discern", function(venn, slice1, slice2 = "all") { standardGeneric("discern") } ) setMethod("discern", c(venn = "Venn", slice1 = "ANY", slice2 = "ANY"), function(venn, slice1, slice2 = "all") { if (is.numeric(slice1)) { slice1 = names(venn@sets)[slice1] } if (is.numeric(slice2)) { slice2 = names(venn@sets)[slice2] } if (slice2[1] == "all") { slice2 = setdiff(names(venn@sets), slice1) set1 = venn@sets[slice1] %>% purrr::reduce(function(x, y) union(x, y)) set2 = venn@sets[slice2] %>% purrr::reduce(function(x, y) union(x, y)) differ = setdiff(set1, set2) } else { set1 = venn@sets[slice1] %>% purrr::reduce(function(x, y) union(x, y)) set2 = venn@sets[slice2] %>% purrr::reduce(function(x, y) union(x, y)) differ = setdiff(set1, set2) } differ } )
options(digits=12) if(!require("optimx"))stop("this test requires package optimx.") if(!require("setRNG"))stop("this test requires setRNG.") test.rng <- list(kind="Wichmann-Hill", normal.kind="Box-Muller", seed=c(979,1479,1542)) old.seed <- setRNG(test.rng) cat("optimx test brown-x.f ...\n") brown.f <- function(x) { p <- x n <- length(p) odd <- seq(1,n,by=2) even <- seq(2,n,by=2) sum((p[odd]^2)^(p[even]^2 + 1) + (p[even]^2)^(p[odd]^2 + 1)) } npar<-50 p0 <- rnorm(npar,sd=2) system.time(ans.optx <- optimx(par=p0, fn=brown.f, control=list(all.methods=TRUE, save.failures=TRUE, maxit=2500)))[1] print(ans.optx)
fSolI <- function(solD, sample='hour', BTi, EoT=TRUE, keep.night=TRUE, method='michalsky'){ Bo <- 1367 lat <- d2r(attr(solD, 'lat')) signLat <- ifelse(sign(lat)==0, 1, sign(lat)) if (missing(BTi)){ sampleDiff <- char2diff(sample) start.sol <- start(solD) end.sol <- end(solD) seqby <- seq(start.sol, end.sol+86400-1, by = sampleDiff) } else { seqby <- BTi sampleDiff <- median(diff(BTi)) } seqby.day<-truncDay(seqby) solD.day<-index(solD) mtch<-match(seqby.day, solD.day, nomatch = 0) mtch.in <- which(mtch>0) mtch <- mtch[mtch>0] sol.rep<-data.frame(solD)[mtch,] seqby.match<-seqby[mtch.in] decl<-sol.rep$decl ws<-sol.rep$ws Bo0d<-sol.rep$Bo0d eo<-sol.rep$eo if (EoT) {EoT <- sol.rep$EoT} else {EoT <- 0} jd <- as.numeric(julian(seqby.match, origin='2000-01-01 12:00:00 UTC')) TO <- hms(seqby.match) methods <- c('cooper', 'spencer', 'michalsky', 'strous') method <- match.arg(method, methods) w=switch(method, cooper = h2r(TO-12)+EoT, spencer = h2r(TO-12)+EoT, michalsky = { meanLong <- (280.460+0.9856474*jd)%%360 meanAnomaly <- (357.528+0.9856003*jd)%%360 eclipLong <- (meanLong +1.915*sin(d2r(meanAnomaly))+0.02*sin(d2r(2*meanAnomaly)))%%360 excen <- 23.439-0.0000004*jd sinEclip <- sin(d2r(eclipLong)) cosEclip <- cos(d2r(eclipLong)) cosExcen <- cos(d2r(excen)) ascension <- r2d(atan2(sinEclip*cosExcen, cosEclip))%%360 lmst <- (h2d(6.697375 + 0.0657098242*jd + TO))%%360 w <- (lmst-ascension) w <- d2r(w + 360*(w < -180) - 360*(w > 180)) }, strous = { meanAnomaly <- (357.5291 + 0.98560028*jd)%%360 coefC <- c(1.9148, 0.02, 0.0003) sinC <- sin(outer(1:3, d2r(meanAnomaly), '*')) C <- colSums(coefC*sinC) trueAnomaly <- (meanAnomaly + C)%%360 eclipLong <- (trueAnomaly + 282.9372)%%360 excen <- 23.435 sinEclip <- sin(d2r(eclipLong)) cosEclip <- cos(d2r(eclipLong)) cosExcen <- cos(d2r(excen)) ascension <- r2d(atan2(sinEclip*cosExcen, cosEclip))%%360 lmst <- (280.1600+360.9856235*jd)%%360 w <- (lmst-ascension) w <- d2r(w + 360*(w< -180) - 360*(w>180)) } ) aman<-abs(w)<=abs(ws) cosThzS<-sin(decl)*sin(lat)+cos(decl)*cos(w)*cos(lat) cosThzS[cosThzS>1]<-1 AlS <- asin(cosThzS) cosAzS <- signLat*(cos(decl)*cos(w)*sin(lat)-cos(lat)*sin(decl))/cos(AlS) cosAzS[cosAzS > 1] <- 1 cosAzS[cosAzS < -1] <- -1 AzS <- sign(w)*acos(cosAzS) Bo0<-Bo*eo*cosThzS Bo0[!aman] <- 0 a <- 0.409-0.5016*sin(ws+pi/3) b <- 0.6609+0.4767*sin(ws+pi/3) rd<-Bo0/Bo0d rg<-rd*(a+b*cos(w)) resultDF<-data.frame(w, aman, cosThzS, AlS, AzS, Bo0, rd, rg) if (!keep.night){ resultDF <- resultDF[aman==TRUE,] seqby.match <- seqby.match[aman==TRUE] mtch <- mtch[aman==TRUE] } else {} result <- zoo(resultDF, order.by=seqby.match) attr(result, 'match') <- mtch attr(result, 'lat') <- r2d(lat) attr(result, 'sample') <- sampleDiff result }
cur_vars_env <- new.env() current_vars <- function() cur_vars_env$selected select_helpers <- list(starts_with = function(...) starts_with(vars, ...), ends_with = function(...) ends_with(vars, ...), contains = function(...) contains(vars, ...), matches = function(...) matches(vars, ...), num_range = function(...) num_range(vars, ...), one_of = function(...) one_of(vars, ...), everything = function(...) everything(vars, ...)) starts_with <- function(match, ignore.case = TRUE, vars = current_vars()) { stopifnot(assertthat::is.string(match), !is.na(match), nchar(match) > 0) if (ignore.case) match <- tolower(match) n <- nchar(match) if (ignore.case) vars <- tolower(vars) which_vars(match, substr(vars, 1, n)) } ends_with <- function(match, ignore.case = TRUE, vars = current_vars()) { stopifnot(assertthat::is.string(match), !is.na(match), nchar(match) > 0) if (ignore.case) match <- tolower(match) n <- nchar(match) if (ignore.case) vars <- tolower(vars) length <- nchar(vars) which_vars(match, substr(vars, pmax(1, length - n + 1), length)) } contains <- function(match, ignore.case = TRUE, vars = current_vars()) { stopifnot(assertthat::is.string(match), nchar(match) > 0) if (ignore.case) { vars <- tolower(vars) match <- tolower(match) } grep_vars(match, vars, fixed = TRUE) } matches <- function(match, ignore.case = TRUE, vars = current_vars()) { stopifnot(assertthat::is.string(match), nchar(match) > 0) grep_vars(match, vars, ignore.case = ignore.case) } num_range <- function(prefix, range, width = NULL, vars = current_vars()) { if (!is.null(width)) { range <- sprintf(paste0("%0", width, "d"), range) } match_vars(paste0(prefix, range), vars) } one_of <- function(..., vars = current_vars()) { keep <- c(...) if (!is.character(keep)) { stop("`c(...)` must be a character vector", call. = FALSE) } if (!all(keep %in% vars)) { bad <- setdiff(keep, vars) warning("Unknown variables: ", paste0("`", bad, "`", collapse = ", ")) } match_vars(keep, vars) } everything <- function(vars = current_vars()) { seq_along(vars) } match_vars <- function(needle, haystack) { x <- match(needle, haystack) x <- x[!is.na(x)] fill_out(x, haystack) } grep_vars <- function(needle, haystack, ...) { fill_out(grep(needle, haystack, ...), haystack) } which_vars <- function(needle, haystack) { fill_out(which(needle == haystack), haystack) } fill_out <- function(x, haystack) { if (length(x) > 0) return(x) -seq_along(haystack) }
context("Testing class definitions") test_that("funData class constructor", { expect_error(funData(argvals = "Test", X = matrix(2, nrow = 1)), "unable to find an inherited method") expect_error(funData(argvals = list(1,"Test"), X = array(1:2, dim = c(1,1,1))), "All argvals elements must be numeric") expect_error(funData(argvals = list(1:5), X = list(cbind(1:5,6:10))), "unable to find an inherited method") expect_error(funData(argvals = list(1:5), X = array(1:25, dim = c(1,5,5))), "argvals and X element have different support dimensions! X-Dimensions must be of the form N x M1 x ... x Md") expect_error(funData(argvals = list(1:5, 1:4), X = array(1:25, dim = c(1,5,5))), "argvals and X have different number of sampling points! X-Dimensions must be of the form N x M1 x ... x Md") expect_is(funData(argvals = c(1:5), X = matrix(c(1:19, NA), nrow = 4)), "funData") expect_equal(funData(argvals = 1:5, X = matrix(1:20, nrow = 4)), funData(argvals = list(1:5), X = matrix(1:20, nrow = 4))) }) test_that("multiFunData class constructor", { f1 <- funData(argvals = 1:5, X = matrix(1:20, nrow = 4)) expect_error(multiFunData(list(5, 5)), "Elements of multiFunData must be of class funData!") expect_error(multiFunData(list(f1, funData(argvals = list(1:5, 6:10), X = array(1:125, c(5,5,5))))), "All elements must have the same number of observations!") expect_is(as(f1, "multiFunData"), "multiFunData") expect_equal(multiFunData(f1,f1), multiFunData(list(f1,f1))) }) test_that("irregfunData class constructor", { expect_error(irregFunData(argvals = "Test", X = list(5)), "unable to find an inherited method") expect_error(irregFunData(argvals = list("Test"), X = list(5)), "argvals must be supplied as list of numerics") expect_error(irregFunData(argvals = list(5), X = "Test"), "unable to find an inherited method") expect_error(irregFunData(argvals = list(5), X = list("Test")), "X must be supplied as list of numerics") expect_error(irregFunData(argvals = list(1:5), X = list(1:5, 2:4)), "Different number of observations for argvals and X") expect_error(irregFunData(argvals = list(1:5, 1:4), X = list(1:5, 2:4)), "Different numbers of observation points in argvals and X") }) test_that("coerce methods", { x <- seq(0,1,0.01) f <- funData(argvals = x, X = 1:5 %o% x) i1 <- irregFunData(argvals = list(1:5, 3:6), X = list(2:6, 4:7)) expect_error(as.irregFunData(tensorProduct(f,f)), "The funData object must be defined on a one-dimensional domain.") expect_equal(f, as.multiFunData(f)[[1]]) expect_equal(as.funData(i1), {f1 <- funData(1:6, rbind(c(2:6, NA), c(NA,NA,4:7)))}) expect_equal(unique(unlist(i1@argvals)), f1@argvals[[1]]) expect_equal(i1@X, apply(f1@X, 1, na.omit), check.attributes = FALSE) expect_equal(i1, as.irregFunData(f1)) fName <- f; names(fName) <- letters[1:nObs(fName)] expect_equal(head(as.data.frame(f), nObsPoints(f)), data.frame(obs = "1", argvals1 = x, X = f@X[1,]), check.attributes = FALSE) expect_equal(tail(as.data.frame(f), nObsPoints(f)), data.frame(obs = "5", argvals1 = x, X = f@X[5,]), check.attributes = FALSE) expect_equal(tail(as.data.frame(fName), nObsPoints(fName)), data.frame(obs = "e", argvals1 = x, X = f@X[5,]), check.attributes = FALSE) expect_equal(as.data.frame(as.multiFunData(f)), list(as.data.frame(f))) expect_equal(as.data.frame(i1), data.frame(obs = rep(c("1","2"), times = c(5,4)), argvals = unlist(argvals(i1)), X = unlist(X(i1)))) if(!(requireNamespace("fda", quietly = TRUE))) { expect_warning(funData2fd(f), "Please install the fda package to use the funData2fd function for funData objects.") expect_warning(fd2funData(NULL), "Please install the fda package to use the fd2funData function for funData objects.") } else { library("fda") daybasis <- create.fourier.basis(c(0, 365), nbasis=65) tempfd <- Data2fd(argvals = day.5, y = CanadianWeather$dailyAv[,,"Temperature.C"], daybasis) expect_error(funData2fd("fun", daybasis), "Argument is not of class 'funData'.") expect_error(funData2fd(funData(argvals = list(1:5, 1:4), X = 3:1 %o% 1:5 %o% 1:4)), "funData2fd is only defined for functions on one-dimensional domains.") expect_error(fd2funData(tempfd, letters[1:5]), "Parameter 'argvals' must be either a vector of argument values or a list containing such a vector.") tempFun <- fd2funData(tempfd, argvals = day.5) tempFun2 <- fd2funData(tempfd, argvals = list(day.5)) expect_equal(nObs(tempFun), 35) expect_equal(nObsPoints(tempFun), 365) expect_equal(mean(norm(tempFun)), 60906.17, tol = 1e-5) expect_equal(norm(tempFun)[1], 27068, tol = 1e-5) expect_equal(tempFun, tempFun2) reTempfd <- funData2fd(tempFun, daybasis) reTempfd$fdnames$time <- tempfd$fdnames$time expect_equal(tempfd, reTempfd) } })
context("get_ids") test_that("get_ids returns the correct values and classses", { skip_on_cran() tt <- get_ids("Chironomus riparius", db = "ncbi", messages = FALSE, suppress = TRUE) expect_equal(tt[[1]][[1]], "315576") expect_is(tt, "ids") expect_is(tt[[1]], "uid") expect_is(tt[[1]][[1]], "character") }) test_that("get_ids accepts ask and verbose arguments", { skip_on_cran() expect_message(get_ids("Pinus contorta", db = "ncbi", suppress = TRUE)) expect_message(get_ids("Pinus contorta", db = "ncbi", messages = FALSE, suppress = TRUE), NA) }) nn <- c('Imperata brasiliensis','Hylebates cordatus','Apocopis intermedius', 'Paspalum subciliatum','Bromus nottowayanus','Chimonobambusa marmorea', 'Panicum adenophorum','Otatea glauca','Himalayacalamus falconeri', 'Briza lamarckiana','Trisetum turcicum','Brachiaria subulifolia', 'Boissiera squarrosa','Arthrostylidium pubescens','Neyraudia reynaudiana' ,'Bromus gunckelii','Poa sudicola','Pentameris thuarii', 'Calamagrostis inexpansa','Willkommia texana','Helictotrichon cantabricum', 'Muhlenbergia tenuifolia','Sporobolus ioclados','Bambusa cerosissima', 'Axonopus flabelliformis','Glyceria lithuanica','Pentaschistis malouinensis', 'Perrierbambus madagascariensis','Hierochloe alpina','Hemarthria compressa', 'Zizania latifolia','Festuca altaica','Gigantochloa wrayi','Festuca alpina', 'Aegilops caudata','Elymus cognatus','Agrostis gracililaxa', 'Gymnopogon foliosus') test_that("works on a variety of names", { skip_on_cran() skip_on_ci() expect_is(sw(get_ids(nn[13], db = c("ncbi", "itis", "tropicos"), suppress = TRUE, ask = FALSE, messages = FALSE)), "ids") expect_is(sw(get_ids(nn[14], db = c("ncbi", "tropicos"), suppress = TRUE, ask = FALSE, messages = FALSE)), "ids") expect_is(sw(get_ids(nn[15], db = c("ncbi", "itis", "tropicos"), suppress = TRUE, ask = FALSE, messages = FALSE)), "ids") })
context("test-na-warn") test_that("na.warn warns when dropping", { df <- data.frame(x = 1:5, y = c(1, NA, 3, NA, 5)) expect_warning(mod <- lm(y ~ x, data = df, na.action = na.warn), "Dropping 2") pred <- unname(predict(mod)) expect_equal(is.na(pred), is.na(df$y)) })
library(lattice) library(latticeExtra) library(microplot) options(latexcmd='pdflatex') options(dviExtension='pdf') if (nchar(Sys.which("open"))) { options(xdvicmd="open") } else { options(xdvicmd="xdg-open") } irisBW <- bwplot( ~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width | Species, data=iris, outer=TRUE, as.table=TRUE, scales=list(alternating=FALSE), xlab=NULL, par.strip.text=list(cex=1.5)) names(dimnames(irisBW))[[2]] <- "Measurement" pdf("irisBW.pdf", width=7, height=7) useOuterStrips(irisBW) suppress <- dev.off() irisBW.update <- update(irisBW, xlab=NULL, par.settings=list( layout.heights=layoutHeightsCollapse(), layout.widths=layoutWidthsCollapse(), axis.line=list(col="transparent")), layout=c(1,1) ) irisBW.axis <- update(irisBW.update[1,1], scales=list(cex=.6), par.settings=list(layout.heights=list(axis.bottom=1, panel=0), axis.line=list(col="black"))) pdf("irisBW%03d.pdf", onefile=FALSE, height=.4, width=1.6) irisBW.update suppress <- dev.off() pdf("irisBW013.pdf", height=.4, width=1.6) irisBW.axis suppress <- dev.off() graphnames <- paste0("irisBW", sprintf("%03i", 1:13), ".pdf") graphicsnames <- t(matrix(as.includegraphics(graphnames[1:12], height="2em", raise="-1.3ex"), nrow=3, ncol=4, dimnames=dimnames(irisBW))) BWMS.latex <- Hmisc::latex(graphicsnames, caption="\\Large Measurement by Species", where="!htbp", label="BWMS", title="Measurement", file="BWMS.tex", size="Large") BWMS.latex$style <- "graphicx" graphicsnamesA <- rbind(graphicsnames, as.includegraphics(graphnames[13], height="2em", raise="-1.3ex")) BWMSA.latex <- Hmisc::latex(graphicsnamesA, caption="\\Large Measurement by Species, with $x$-scale", where="!htbp", n.rgroup=c(4, 1), rgroup=c("\\vspace*{-1em}", "\\vspace*{-1.25em}"), label="BWMSA", title="Measurement", file="BWMSA.tex", size="Large") BWMSA.latex$style <- "graphicx" BWSM.latex <- Hmisc::latex(t(graphicsnames), caption="\\Large Species by Measurement", where="!htbp", label="BWSM", title="Species", file="BWSM.tex", size="large") BWSM.latex$style <- "graphicx" iris.fivenum <- sapply(levels(iris$Species), function(i) { tmp <- sapply(iris[iris$Species==i, 1:4], fivenum) dimnames(tmp)[[1]] <- c("min", "Q1", "med", "Q3", "max") tmp }, simplify=FALSE) BW5num <- rbind( data.frame(t(iris.fivenum[[1]]), "Box Plots"=graphicsnames[,1], check.names=FALSE), data.frame(t(iris.fivenum[[2]]), "Box Plots"=graphicsnames[,2], check.names=FALSE), data.frame(t(iris.fivenum[[3]]), "Box Plots"=graphicsnames[,3], check.names=FALSE)) BW5num$Measurement=names(iris)[1:4] BW5num <- BW5num[, c(7,1:6)] BW5num.latex <- Hmisc::latex(BW5num, rowname=" ", rowlabel="Species", rgroup=levels(iris$Species), n.rgroup=c(4,4,4), cgroup=c("", "Five Number Summary", ""), n.cgroup=c(1, 5, 1), caption="\\Large Five Number Summary and Boxplots for each Species and Measurement", label="irisBW5num", where="!htbp") BW5num.latex$style <- "graphicx"
context("add_dummy_variables") test_that("Function create the correct columns", { cols_expected <- c("mpg","disp","hp","drat","wt","qsec","vs","am","gear","carb","cyl_6","cyl_8") expect_equal( colnames(add_dummy_variables(mtcars, cyl, c(4,6,8))), cols_expected ) expect_equal( colnames(add_dummy_variables(mtcars, cyl, auto_values = TRUE)), cols_expected ) }) test_that("Function fails when no values are passed and auto_values is FALSE",{ expect_error(add_dummy_variables(mtcars, cyl)) expect_error(add_dummy_variables(mtcars, cyl, auto_values = FALSE)) }) test_that("Has error when variable is missing",{ expect_error(add_dummy_variables(mtcars, error)) })
tess.plot.singlechain.diagnostics = function(output, parameters=c("speciation rates", "speciation shift times", "extinction rates", "extinction shift times", "net-diversification rates", "relative-extinction rates", "mass extinction times"), diagnostics=c("ESS","geweke"), ess.crit=c(100,200), geweke.crit=0.05, correction="bonferroni", xlab="million years ago", col=NULL, xaxt="n", yaxt="s", pch=19, ...){ validFigTypes <- c("speciation rates", "speciation shift times", "extinction rates", "extinction shift times", "net-diversification rates", "relative-extinction rates", "mass extinction times") invalidFigTypes <- parameters[!parameters %in% validFigTypes] if ( length( invalidFigTypes ) > 0 ) { stop("\nThe following figure types are invalid: ",paste(invalidFigTypes,collapse=", "),".", "\nValid options are: ",paste(validFigTypes,collapse=", "),".") } validDiagnostics <- c("ESS","geweke") invalidDiagnostics <- diagnostics[!diagnostics %in% validDiagnostics] if ( length( invalidFigTypes ) > 0 ) { stop("\nThe following diagnostics are invalid: ",paste(invalidDiagnostics,collapse=", "),".", "\nValid options are: ",paste(validDiagnostics,collapse=", "),".") } if ( is.null(col) ) { col <- c(" } else if ( length(col) != 3 ){ stop("\nYou must supply 3 input colors.") } treeAge <- max(branching.times(output$tree)) numIntervals <- length(output$intervals)-1 plotAt <- 0:numIntervals intervalSize <- treeAge/numIntervals labels <- pretty(c(0,treeAge)) labelsAt <- numIntervals - (labels / intervalSize) for ( type in parameters ) { for ( diag in diagnostics ) { if ( diag == "ESS" ) { thisOutput <- output[[type]] thisESS <- effectiveSize(thisOutput) thisCol <- col[findInterval(thisESS,ess.crit)+1] ylim <- range(pretty(c(0,max(thisESS)))) thisCol[thisESS == 0] <- 'grey90' thisESS[thisESS == 0] <- max(ylim) barplot(thisESS,space=0,xaxt=xaxt,col=thisCol,border=NA,main=type,ylab="effective sample size",xlab=xlab,ylim=ylim,...) abline(h=ess.crit,lty=2,...) axis(1,at=labelsAt,labels=labels) box() } else if ( diag == "geweke" ) { thisOutput <- output[[type]] thisGeweke <- geweke.diag(thisOutput)$z if ( !is.null(correction) ) { if ( correction == "bonferroni" ) { crit <- geweke.crit / numIntervals } if ( correction == "sidak" ) { crit <- 1 - (1 - geweke.crit)^(1/numIntervals) } } else { crit <- geweke.crit } thisPvalue <- pnorm(thisGeweke) thisPvalue[is.na(thisPvalue)] <- 0 failed <- thisPvalue < crit | thisPvalue > 1 - (crit) thisCol <- ifelse(failed,col[1],col[3]) criticalGewekeValues <- qnorm(c(crit,1-crit)) ylim <- range(pretty(c(thisGeweke,criticalGewekeValues)),finite=TRUE) plot(thisGeweke,col=thisCol,type="p",xaxt=xaxt,ylab="Geweke statistic",main=type,xlab=xlab,ylim=ylim,xlim=range(plotAt),pch=pch,...) abline(h=criticalGewekeValues,lty=2,...) axis(1,at=labelsAt,labels=labels) } } } }
options(width = 120) options(warn = 1) options(bitmapType = "cairo") suppressPackageStartupMessages({ library(tidyverse) library(minfi) library(RColorBrewer) library(ggsci) }) plot_colors = c(brewer.pal(5, "Set1"), brewer.pal(8, "Dark2"), pal_igv("default")(51)) load_data = function(sample_sheet) { if (!file.exists(sample_sheet)) stop("sample sheet ", sample_sheet, " does not exist") samples_tbl = read_csv(sample_sheet) if (!("Basename" %in% colnames(samples_tbl))) stop("sample sheet must contain \"Basename\" column") if (!("Sentrix_ID" %in% colnames(samples_tbl))) stop("sample sheet must contain \"Sentrix_ID\" column") if (!("Sample" %in% colnames(samples_tbl))) stop("sample sheet must contain \"Sample\" column") if (!("Condition" %in% colnames(samples_tbl))) stop("sample sheet must contain \"Condition\" column") samples_tbl$Array = gsub(".*/([0-9]*)_R[0-9][0-9]C[0-9][0-9]", "\\1", samples_tbl$Basename) message("\n\n ===== minfi::read.metharray.exp() ===== \n\n") raw_set = read.metharray.exp(targets = samples_tbl, recursive = TRUE, verbose = FALSE) if (!(identical(sampleNames(raw_set), sub(".*/", "", pData(raw_set)$Basename)))) stop("sample names not identical") sampleNames(raw_set) = pData(raw_set)$Sample message("array: ", annotation(raw_set)[["array"]]) message("annotation: ", annotation(raw_set)[["annotation"]]) message("samples per condition: ") raw_set$Condition %>% table(useNA = "ifany") %>% print() message("\n\n ===== minfi::read.qcReport() ===== \n\n") qcReport(raw_set, sampGroups=pData(raw_set)$Condition, pdf="plot.qcreport.pdf") png("plot.density.raw.condition.png", width = 8, height = 5, units = "in", res = 300) densityPlot(raw_set, sampGroups = pData(raw_set)$Condition, pal = plot_colors) dev.off() png("plot.density.raw.array.png", width = 8, height = 5, units = "in", res = 300) densityPlot(raw_set, sampGroups = pData(raw_set)$Array, pal = plot_colors) dev.off() if (file.exists("Rplots.pdf")) file.remove("Rplots.pdf") message("\n\n ===== minfi::detectionP() ===== \n\n") det_p = detectionP(raw_set) det_p_summary = tibble( sample = colnames(det_p), detected_positions = colSums(det_p < 0.01), failed_positions = colSums(det_p >= 0.01), failed_positions_pct = round(colMeans(det_p > 0.01), digits = 3) ) %>% arrange(-failed_positions) %>% mutate(failed_positions_pct = failed_positions_pct * 100) write_csv(det_p_summary, "summary.detection.csv") return(raw_set) } normalize_data = function(raw_channel_set) { message("\n\n ===== minfi::preprocessRaw() ===== \n\n") mset = preprocessRaw(raw_channel_set) qc = getQC(mset) mset = addQC(mset, qc = qc) png("plot.medianintensity.png", width = 8, height = 8, units = "in", res = 300) plotQC(qc) dev.off() message("\n\n ===== minfi::preprocessFunnorm() ===== \n\n") norm_set = preprocessFunnorm(raw_set, bgCorr = TRUE, dyeCorr = TRUE) write(paste0("total probes: ", nrow(norm_set)), file = "norm.log", append = TRUE) det_p = detectionP(raw_set) det_p = det_p[intersect(rownames(det_p), rownames(norm_set)), ] norm_set = norm_set[rowSums(det_p < 0.01) == ncol(det_p), ] write(paste0("detected probes: ", nrow(norm_set)), file = "norm.log", append = TRUE) norm_set = addSnpInfo(norm_set) norm_set = dropLociWithSnps(norm_set, snps = c("SBE","CpG"), maf = 0) write(paste0("non-SNP probes: ", nrow(norm_set)), file = "norm.log", append = TRUE) png("plot.sex.png", width = 8, height = 8, units = "in", res = 300) plotSex(getSex(norm_set), id = sampleNames(norm_set)) dev.off() annot = getAnnotation(norm_set) annot_tbl = annot %>% as_tibble(rownames = "probe") %>% arrange(probe) remove_cols = c( "AddressA", "AddressB", "ProbeSeqA", "ProbeSeqB", "NextBase", "Color", "Forward_Sequence", "SourceSeq", "Probe_rs", "CpG_rs", "SBE_rs","Probe_maf", "CpG_maf", "SBE_maf", "Islands_Name", "UCSC_RefGene_Accession", "GencodeBasicV12_NAME", "GencodeBasicV12_Accession", "GencodeBasicV12_Group", "GencodeCompV12_Accession", "DNase_Hypersensitivity_NAME", "OpenChromatin_NAME", "Methyl27_Loci", "Methyl450_Loci", "Random_Loci") annot_tbl = annot_tbl %>% dplyr::select(!any_of(remove_cols)) write_csv(head(annot_tbl, 100), "annot.head100.csv") write_csv(annot_tbl, "annot.csv.gz") sex_probes = annot$Name[annot$chr %in% c("chrX", "chrY")] norm_set = norm_set[!(rownames(norm_set) %in% sex_probes), ] write(paste0("non-sex probes: ", nrow(norm_set)), file = "norm.log", append = TRUE) beta = getBeta(norm_set) png("plot.density.norm.fnorm.png", width = 8, height = 5, units = "in", res = 300) densityPlot(beta, sampGroups = pData(norm_set)$Condition, pal = plot_colors) dev.off() png("plot.mds.raw.condition.png", width = 8, height = 8, units = "in", res = 300) mdsPlot(raw_set, numPositions = 10000, sampNames = sampleNames(raw_set), sampGroups = pData(raw_set)$Condition, legendPos = "topright", legendNCol = 1, pal = plot_colors) dev.off() png("plot.mds.norm.fnorm.condition.png", width = 8, height = 8, units = "in", res = 300) mdsPlot(beta, numPositions = 10000, sampNames = sampleNames(norm_set), sampGroups = pData(norm_set)$Condition, legendPos = "topright", legendNCol = 1, pal = plot_colors) dev.off() png("plot.mds.norm.fnorm.array.png", width = 8, height = 8, units = "in", res = 300) mdsPlot(beta, numPositions = 10000, sampNames = sampleNames(norm_set), sampGroups = pData(norm_set)$Array, legendPos = "topright", legendNCol = 1, pal = plot_colors) dev.off() beta = getBeta(norm_set) beta_tbl = beta %>% round(3) %>% as_tibble(rownames = "probe") %>% arrange(probe) write_csv(head(beta_tbl, 100), "beta.head100.csv") write_csv(beta_tbl, "beta.csv.gz") return(norm_set) }
byclade <- function (x, remperc, groups) { ngroups<-length(unique(groups)) if(class(x)=="matrix"){ remove.dat <- function(specimen, removes) { ndat <- length(specimen) rems <- sample(ndat, removes, replace = FALSE) for (k in 1:removes) { m <- rems[k] specimen[m] <- NA } return(specimen) } newx1 <- as.matrix(x) grouping <- as.factor(groups) newx2 <- as.matrix(x) totaldata <- nrow(x) * ncol(x) n <- round(totaldata * remperc) ndat <- 1:totaldata remove <- sample(ndat, n, replace = FALSE) for (k in 1:n) { i <- remove[k] newx1[i] <- NA } binary <- ifelse(is.na(newx1), 1, 0) numberper <- apply(binary, 1, sum) rows <- 1:nrow(x) numbersp <- ifelse(numberper == 0, 0, 1) * rows nsp <- length(numbersp) sorted <- sort(numberper, decreasing = TRUE) splitgroups <- split(as.data.frame(x), grouping) npergroup <- sapply(splitgroups, nrow, simplify = TRUE) counts <- 1:nsp for (i in 1:nsp) { m <- groups[i] a <- npergroup[m] counts[i] <- a } counts <- counts sums <- sum(npergroup) ratio <- sums/counts probs <- ratio/sum(ratio) orders <- sample(1:nsp, nsp, replace = FALSE, prob = probs) for (k in 1:nsp) { removes <- sorted[k] spnumber <- orders[k] specimen <- newx2[spnumber, ] newsp <- remove.dat(specimen, removes) newx2[spnumber, ] <- newsp } return(newx2)} if(class(x)=="array"){ remove.dat <- function(specimen, removes) { ndat <- nrow(specimen) rems <- sample(ndat, removes, replace = FALSE) for (k in 1:removes) { specimen[rems[k],] <- rep(NA,dim(specimen)[[2]]) } return(specimen) } newx1 <- x grouping <- as.factor(groups) totaldata <- nrow(x) * dim(x)[[3]] n <- round(totaldata * remperc) all.spl<-cbind(rep(1:dim(x)[3],each=nrow(x)),rep(1:nrow(x),dim(x)[[3]])) remove <- all.spl[sample(1:totaldata, n, replace = FALSE),] outs <- table(remove[,1]) remove<-rep(0,dim(x)[[3]]) remove[as.numeric(names(outs))]<-outs sorted <- sort(remove, decreasing = TRUE) npergroup <- table(groups) counts <- rep(0,dim(x)[[3]]) for (i in 1:length(remove)) { m <- groups[i] a <- npergroup[m] counts[i] <- a } counts <- counts sums <- sum(npergroup) ratio <- sums/counts probs <- ratio/sum(ratio) orders <- sample(1:dim(x)[[3]], dim(x)[[3]], replace = FALSE, prob = probs) for (k in 1:length(sorted)){ removes <- sorted[k] spnumber <- orders[k] specimen <- newx1[,,spnumber] if(removes==0){newsp<-specimen } else { newsp <- remove.dat(specimen, removes)} newx1[,,spnumber] <- newsp } dimnames(newx1)[[3]]<-dimnames(x)[[3]] return(newx1)} }
knitr::opts_chunk$set( collapse = TRUE, comment = " ) rm(list=ls()) library(ModelMatrixModel) set.seed(10) traindf= data.frame(x1 = sample(LETTERS[1:5], replace = T, 20), x2 = rnorm(20, 100, 5), x3 = factor(sample(c("U","L","P"), replace = T, 20)), y = rnorm(20, 10, 2)) set.seed(20) newdf=data.frame(x1 = sample(LETTERS[1:5], replace = T, 3), x2 = rnorm(3, 100, 5), x3 = sample(c("U","L","P"), replace = T, 3)) head(traindf) sapply(traindf,class) f1=formula("~x1+x2") head(model.matrix(f1, traindf),2) head(model.matrix(f1, newdf),2) f2=formula("~ 1+x1+x2") mm=ModelMatrixModel( f2,traindf,remove_1st_dummy =T,sparse = F) class(mm) head(mm$x,2) mm_pred=predict(mm,newdf) head(mm_pred$x,2) mm=ModelMatrixModel(~x1+x2+x3,traindf,remove_1st_dummy = F) data.frame(as.matrix(head(mm$x,2))) mm_pred=predict(mm,newdf) data.frame(as.matrix(head(mm_pred$x,2))) mm=ModelMatrixModel(~x2+x3+x2:x3,traindf) data.frame(as.matrix(head(mm$x,2))) mm_pred=predict(mm,newdf) data.frame(as.matrix(head(mm_pred$x,2))) mm=ModelMatrixModel(~x2*x3,traindf,remove_1st_dummy = T) data.frame(as.matrix(head(mm$x,2))) mm_pred=predict(mm,newdf) data.frame(as.matrix(head(mm_pred$x,2))) mm=ModelMatrixModel(~x2+x3,traindf) data.frame(as.matrix(head(mm$x,2))) newdf2=newdf newdf2[1,'x3']='z' mm_pred=predict(mm,newdf2,handleInvalid = "keep") data.frame(as.matrix(head(mm_pred$x,2))) mm=ModelMatrixModel(~poly(x2,3)+x3,traindf) data.frame(as.matrix(head(mm$x,2))) mm_pred=predict(mm,newdf) data.frame(as.matrix(head(mm_pred$x,2))) mm=ModelMatrixModel(~poly(x2,3,raw=T)+x3, traindf) data.frame(as.matrix(head(mm$x,2))) mm_pred=predict(mm,newdf) data.frame(as.matrix(head(mm_pred$x,2))) mm=ModelMatrixModel(~x2+x3,traindf,scale = T,center = T) data.frame(as.matrix(head(mm$x,2))) mm_pred=predict(mm,newdf) data.frame(as.matrix(head(mm_pred$x,2)))
canvas_function <- function(colors, background = " polar = TRUE, formula = NULL) { .checkUserInput(background = background) if (is.null(formula)) { painting_formulas <- list() painting_formulas[[1]] <- list( x = quote(runif(1, -10, 10) * x_i^sample(c(0.5, 1:6), 1) - sin(y_i^sample(c(0.5, 1:6), 1)) * runif(1, -100, 100)), y = quote(runif(1, -10, 10) * y_i^sample(c(0.5, 1:6), 1) - cos(x_i^sample(c(0.5, 1:6), 1)) * y_i^sample(1:6, 1) + runif(1, -100, 100)) ) painting_formulas[[2]] <- list( x = quote(runif(1, -1, 10) * x_i^sample(c(0.5, 1:6), 1) - sin(y_i^sample(c(0.5, 1:6), 1))), y = quote(runif(1, -1, 10) * y_i^sample(c(0.5, 1:6), 1) - cos(x_i^sample(c(0.5, 1:6), 1)) * y_i^sample(c(0.5, 1:6), 1)) ) painting_formulas[[3]] <- list( x = quote(runif(1, -5, 5) * x_i^sample(1:5, 1) - sin(y_i^sample(1:5, 1))), y = quote(runif(1, -5, 5) * y_i^sample(1:5, 1) - cos(x_i^sample(1:5, 1))) ) painting_formula <- painting_formulas[[sample(1:length(painting_formulas), 1)]] } else { if (!is.list(formula) || !("x" %in% names(formula)) || !("y" %in% names(formula))) { stop("'formula' must be a named list containing 'x' and 'y'") } painting_formula <- list(x = formula[["x"]], y = formula[["y"]]) } grid <- expand.grid(x_i = seq(from = -pi, to = pi, by = by), y_i = seq(from = -pi, to = pi, by = by)) x_i <- grid$x_i y_i <- grid$y_i full_canvas <- data.frame(x = eval(painting_formula$x), y = eval(painting_formula$y)) z <- y_i[stats::complete.cases(full_canvas)] full_canvas <- full_canvas[stats::complete.cases(full_canvas), ] artwork <- ggplot2::ggplot(data = full_canvas, ggplot2::aes(x = x, y = y, color = z)) + ggplot2::geom_point(alpha = 0.1, size = 0, shape = 20) + ggplot2::scale_color_gradientn(colors = colors) if (polar) { artwork <- artwork + ggplot2::coord_polar() } artwork <- theme_canvas(artwork, background) return(artwork) }
mb_bet_cancel <- function(session_data,bet_id=NULL,event_id=NULL,market_id=NULL,runner_id=NULL,cancel_all=FALSE) { content <- list(status_code=0) if(is.null(session_data)|!is.list(session_data)){ print(paste("You have not provided data about your session in the session_data parameter. Please execute mb_login('my_user_name','verysafepassword') and save the resulting object in a variable e.g. my_session <- mb_login(username,pwd); and pass session_data=my_session as a parameter in this function."));return(content) } if(sum(bet_id%%1)>0) {print(paste("The bet_id values must be in integer format. Please amend and try again."));return(content)} if(sum(event_id%%1)>0) {print(paste("The event_id values must be in integer format. Please amend and try again."));return(content)} if(sum(market_id%%1)>0) {print(paste("The market_id values must be in integer format. Please amend and try again."));return(content)} if(sum(runner_id%%1)>0) {print(paste("The runner_id values must be in integer format. Please amend and try again."));return(content)} if(sum(!is.null(bet_id))==0&sum(!is.null(event_id))==0&sum(!is.null(market_id))==0&sum(!is.null(runner_id))==0&cancel_all==FALSE){ print(paste("No bets have been specified for cancellation, please try again."));return(content) } offer_action <- "";event_action <- "";market_action <- "";runner_action <- ""; if(sum(!is.null(bet_id))>0){ offer_action <- paste(',offer-ids'=paste(bet_id,collapse=","),sep="") } if(sum(!is.null(event_id))>0){ event_action <- paste(',event-ids'=paste(event_id,collapse=","),sep="") } if(sum(!is.null(market_id))>0){ market_action <- paste(',market-ids'=paste(market_id,collapse=","),sep="") } if(sum(!is.null(runner_id))>0){ runner_action <- paste(',runner-ids'=paste(runner_id,collapse=","),sep="") } body_data <- paste("{'exchange-type':'back-lay','currency':'",session_data$currency,"','odds-type':'",session_data$odds_type,"' ",offer_action,event_action,market_action,runner_action,"}",sep="") cancel_bet_resp <- httr::DELETE(paste("https://www.matchbook.com/edge/rest/offers",sep=""),body=body_data,httr::set_cookies('session-token'=session_data$session_token),httr::content_type_json(),httr::accept_json(),httr::add_headers('User-Agent'='rlibnf')) status_code <- cancel_bet_resp$status_code if(status_code==200) { content <- jsonlite::fromJSON(content(cancel_bet_resp, "text", "application/json")) content$status_code <- status_code } else if(status_code==401){ print(paste("Please login as your session may have expired ...",sep="")) content <- jsonlite::fromJSON(content(cancel_bet_resp, "text", "application/json")) content$status_code <- status_code } else{ print(paste("Warning/Error in communicating with cancel bet at https://www.matchbook.com/edge/rest/offers",sep="")) content <- jsonlite::fromJSON(content(cancel_bet_resp, "text", "application/json")) content$status_code <- status_code } return(content) }
context("sprinkle_discrete") x <- dust(mtcars) test_that( "Correctly reassigns `bg`", { expect_equal( sprinkle_discrete( x, cols = "gear", discrete = "bg", discrete_color = c("red", "blue", "green"))[["body"]][["bg"]][289:320], c("red", "blue", "green")[match(mtcars$gear, c(3, 4, 5))] ) } ) test_that( "Correctly reassigns `font_color`", { expect_equal( sprinkle_discrete( x, cols = "gear", discrete = "font", discrete_color = c("red", "blue", "green"))[["body"]][["font_color"]][289:320], c("red", "blue", "green")[match(mtcars$gear, c(3, 4, 5))] ) } ) test_that( "Correctly reassigns `font_color`", { expect_equal( sprinkle_discrete( x, cols = "gear", discrete = "font_color", discrete_color = c("red", "blue", "green"))[["body"]][["font_color"]][289:320], c("red", "blue", "green")[match(mtcars$gear, c(3, 4, 5))] ) } ) test_that( "Selects default colors when discrete_color is NULL", { expect_silent( sprinkle_discrete(x, cols = "gear", discrete = "bg") ) } ) test_that( "Correctly reassigns `border`", { expect_equal( sprinkle_discrete( x, cols = "gear", discrete = "border", discrete_color = c("red", "blue", "green"))[["body"]][["left_border"]][289:320], sprintf("1px solid %s", c("red", "blue", "green")[match(mtcars$gear, c(3, 4, 5))]) ) } ) test_that( "Correctly reassigns `border`", { expect_equal( sprinkle_discrete( x, cols = "gear", discrete = "right_border", discrete_color = c("red", "blue", "green"))[["body"]][["right_border"]][289:320], sprintf("1px solid %s", c("red", "blue", "green")[match(mtcars$gear, c(3, 4, 5))]) ) } ) test_that( "Function succeeds when called on a dust_list object", { expect_silent( dplyr::group_by(mtcars, am, vs) %>% dust(ungroup = FALSE) %>% sprinkle_discrete(cols = "gear", discrete = "bg", discrete_color = c("red", "blue", "green")) ) } ) test_that( "Cast an error if x is not a dust object", { expect_error(sprinkle_discrete(x = mtcars, cols = "gear", discrete = "bg")) } ) test_that( "Cast an error if discrete is not a subset of bg, border, font, ...", { expect_error(sprinkle_discrete(x = x, cols = "gear", discrete = "font_height")) } ) test_that( "Cast an error if discrete_color is not character", { expect_error(sprinkle_discrete(x = x, cols = "gear", discrete_colors = 1:3)) } ) test_that( "Cast an error if discrete_color is not a recognized color", { expect_error(sprinkle_discrete(x = x, cols = "gear", discrete_colors = c("my own red", "my own blue", "my own green"))) } ) test_that( "Cast an error if discrete_color has too few values", { expect_error(sprinkle_discrete(x = x, cols = "gear", discrete_colors = c('red', 'blue'))) } ) test_that( "Cast an error if part is not one of body, head, foot, interfoot", { expect_error( sprinkle_discrete(x = x, cols = "gear", part = "not a part") ) } ) test_that( "Cast an error if fixed is not logical(1)", expect_error( sprinkle_discrete(x = x, cols = "gear", fixed = "FALSE") ) ) test_that( "Cast an error if fixed is not logical(1)", expect_error( sprinkle_discrete(x = x, cols = "gear", fixed = c(TRUE, FALSE)) ) ) test_that( "Cast an error if recycle is not one of none, rows, cols", { expect_error( sprinkle_discrete(x = x, cols = "gear", recycle = "not a value") ) } )
lgpa <- function(x, sub.id = 1:(dim(x)[1]), scale=TRUE, reflect=FALSE){ if ((!is.array(x))||(length(dim(x))!=3)){ stop("* lgpa : input 'x' should be a 3d array.") } dimsx = dim(x) k = dimsx[1] m = dimsx[2] n = dimsx[3] sub.id = round(sub.id) sub.id = base::intersect(sub.id, 1:k) if ((max(sub.id) > k)||(!is.vector(sub.id))){ stop("* lgpa : an input 'sub.id' should be a vector containing indices in [1,nrow(x)].") } par.scale = scale par.reflect = reflect nsubid = length(sub.id) xsub = x[sub.id,,] meanvecs = list() for (i in 1:n){ meanvecs[[i]] = colMeans(xsub[,,i]) } for (i in 1:n){ xsub[,,i] = xsub[,,i] - matrix(rep(meanvecs[[i]],nsubid), ncol=m, byrow = TRUE) } xout = shapes::procGPA(xsub, scale=par.scale, reflect = par.reflect)$rotated rotmats = list() for (i in 1:n){ tgt1 = xsub[,,i] tgt2 = xout[,,i] rotmats[[i]] = aux_pinv((t(tgt1)%*%tgt1))%*%(t(tgt1)%*%tgt2) } output = array(0,dim(x)) for (i in 1:n){ tgtx = x[,,i] output[,,i] = (tgtx - matrix(rep(meanvecs[[i]],k), ncol=m, byrow = TRUE))%*%(rotmats[[i]]) } return(output) }
sockettest = function() { expect_error(parallelStartSocket(cpus = 2, socket.hosts = "localhost"), "You cannot set both") parallelStop() parallelStartSocket(2) partest1() parallelStop() parallelStartSocket(2, load.balancing = TRUE) partest1() parallelStop() parallelStartSocket(socket.hosts = c("localhost", "localhost")) partest1() parallelStop() parallelStartSocket(2, logging = TRUE, storagedir = tempdir()) partest2(tempdir()) parallelStop() parallelStartSocket(2) partest3() parallelStop() parallelStartSocket(2) partest4(slave.error.test = TRUE) parallelStop() parallelStartSocket(2) partest5() parallelStop() parallelStartSocket(2) partest6(slave.error.test = TRUE) parallelStop() }
FeatureImp <- R6::R6Class("FeatureImp", inherit = InterpretationMethod, public = list( initialize = function(predictor, loss, compare = "ratio", n.repetitions = 5) { assert_choice(compare, c("ratio", "difference")) assert_number(n.repetitions) self$compare <- compare if (!inherits(loss, "function")) { allowedLosses <- c( "ce", "f1", "logLoss", "mae", "mse", "rmse", "mape", "mdae", "msle", "percent_bias", "rae", "rmse", "rmsle", "rse", "rrse", "smape" ) checkmate::assert_choice(loss, allowedLosses) private$loss_string <- loss loss <- getFromNamespace(loss, "Metrics") } else { private$loss_string <- head(loss) } if (is.null(predictor$data$y)) { stop("Please call Predictor$new() with the y target vector.") } super$initialize(predictor = predictor) self$loss <- private$set_loss(loss) private$getData <- private$sampler$get.xy self$n.repetitions <- n.repetitions actual <- private$sampler$y[[1]] predicted <- private$run.prediction(private$sampler$X)[[1]] self$original.error <- loss(actual, predicted) if (self$original.error == 0 & self$compare == "ratio") { warning("Model error is 0, switching from compare='ratio' to compare='difference'") self$compare <- "difference" } suppressPackageStartupMessages(private$run(self$predictor$batch.size)) }, loss = NULL, original.error = NULL, n.repetitions = NULL, compare = NULL ), private = list( loss_string = NULL, q = function(pred) probs.to.labels(pred), combine.aggregations = function(agg, dat) { if (is.null(agg)) { return(dat) } }, run = function(n) { private$dataSample <- private$getData() result <- NULL estimate_feature_imp <- function(feature, data.sample, y, n.repetitions, y.names, pred, loss) { cnames <- setdiff(colnames(data.sample), y.names) qResults <- data.table::data.table() y.vec <- data.table::data.table() for (repi in 1:n.repetitions) { mg <- MarginalGenerator$new(data.sample, data.sample, features = feature, n.sample.dist = 1, y = y, cartesian = FALSE, id.dist = TRUE ) while (!mg$finished) { data.design <- mg$next.batch(n, y = TRUE) y.vec <- rbind(y.vec, data.design[, y.names, with = FALSE]) qResults <- rbind( qResults, pred(data.design[, cnames, with = FALSE]) ) } } results <- data.table::data.table( feature = feature, actual = y.vec[[1]], predicted = qResults[[1]], num_rep = rep(1:n.repetitions, each = nrow(data.sample)) ) results <- results[, list("permutation_error" = loss(actual, predicted)), by = list(feature, num_rep) ] results } n.repetitions <- self$n.repetitions data.sample <- private$dataSample y <- private$sampler$y y.names <- private$sampler$y.names pred <- private$run.prediction loss <- self$loss result <- rbindlist(unname( future.apply::future_lapply(private$sampler$feature.names, function(x) { estimate_feature_imp(x, data.sample = data.sample, y = y, n.repetitions = n.repetitions, y.names = y.names, pred = pred, loss = loss ) }, future.seed = TRUE, future.globals = FALSE, future.packages = loadedNamespaces() ) ), use.names = TRUE) if (self$compare == "ratio") { result[, importance_raw := permutation_error / self$original.error] } else { result[, importance_raw := permutation_error - self$original.error] } result <- result[, list( "importance" = median(importance_raw), "permutation.error" = median(permutation_error), "importance.05" = quantile(importance_raw, probs = 0.05), "importance.95" = quantile(importance_raw, probs = 0.95) ), by = list(feature)] result <- result[order(result$importance, decreasing = TRUE), ] result <- result[, list( feature, importance.05, importance, importance.95, permutation.error )] private$finished <- TRUE self$results <- data.frame(result) }, generatePlot = function(sort = TRUE, ...) { requireNamespace("ggplot2", quietly = TRUE) res <- self$results if (sort) { res$feature <- factor(res$feature, levels = res$feature[order(res$importance)] ) } xstart <- ifelse(self$compare == "ratio", 1, 0) ggplot(res, aes(y = feature, x = importance)) + geom_segment(aes(y = feature, yend = feature, x = importance.05, xend = importance.95), size = 1.5, color = "darkslategrey") + geom_point(size = 3) + scale_x_continuous(sprintf("Feature Importance (loss: %s)", private$loss_string)) + scale_y_discrete("") }, set_loss = function(loss) { self$loss <- loss }, printParameters = function() { cat("error function:", private$loss_string) } ) ) plot.FeatureImp <- function(x, sort = TRUE, ...) { x$plot(sort = sort, ...) }
context("trim") s <- createMassSpectrum(mass=1:10, intensity=11:20) test_that("trim throws errors", { expect_error(trim(s, range=1:10), "has to be a vector of length 2") expect_error(trim(s, range=1), "has to be a vector of length 2") expect_error(trim(c(s, createMassSpectrum(mass=21:30, intensity=1:10))), "No overlap") }) test_that("trim throws warnings", { expect_warning(trim(s, range=c(20, 30)), "No data points left") }) test_that("trim", { expect_equal(trim(s, c(2, 9)), createMassSpectrum(mass=2:9, intensity=12:19)) }) test_that("trim,list throws errors", { expect_error(trim(list(x=1, y=2)), "no list of MALDIquant::AbstractMassObject objects") }) test_that("trim works with list of AbstractMassObject objects", { r <- createMassSpectrum(mass=2:9, intensity=12:19) expect_equal(trim(list(s, s), c(2, 9)), list(r, r)) expect_equal(trim(list(s, r)), list(r, r)) })
plot.inequality <- function(x, title = NULL, ...) { if (!is.inequality(x)) { stop("Not an object of class 'inequality'") } Q <- Qmax <- NULL if (is.null(title)) { title <- "Lorenz curve" } lor <- x[["Lorenz"]] gini <- x[["Gini"]] lor <- 100*lor lor$Qmax <- c(rep(0,nrow(lor)-1), max(lor$Q)) p <- ggplot(data = lor, aes(F, Q)) + theme(panel.background = element_rect(fill = "transparent"), plot.title = element_text(size = 12)) + geom_ribbon(aes(x = F, ymax = F, ymin = Q), fill = "dodgerblue4", alpha = 1) + geom_line(aes(y = Q), col = "dodgerblue", lwd = 1.2) + geom_line(aes(y = Qmax), col = "dodgerblue", lwd = 1.2) + geom_line(aes(y = F), col = "dodgerblue", lwd = 1.2) + annotate("text", x = 25, y = 80, label = paste("Gini index = ", gini, "%", sep = ""), size = 5) + labs(title=title, x="", y="") return(p) }
cognito_ui <- function(id){ ns <- NS(id) jscode <- "Shiny.addCustomMessageHandler('redirect', function(url) { window.location = url;});" addResourcePath('cognitor', system.file('', package='cognitoR')) fluidRow( shinyjs::useShinyjs(), HTML('<div id="cognitor_loader"></div>'), tags$link(rel = "stylesheet", type = "text/css", href = "cognitor/css/loader.css"), tags$head(tags$script(jscode)), cookie_ui(ns("cookiemod")) ) }
NBR <- function (NIR, SWIR2) { if (missing(NIR)) { stop("Required data missing. Please, select the reflectance values for the Near Infrared band") } if (missing(SWIR2)) { stop("Required data missing. Please, enter the reflectance values for the Short Wave Infrared 2 band") } NBR <- (NIR-SWIR2)/(NIR+SWIR2) }
app <- ShinyDriver$new("../../") app$snapshotInit("offsets", screenshot = FALSE) app$setInputs(advOpts_cores = 2, wait_ = FALSE, values_ = FALSE) app$setInputs(navbar_ID = "Data", ex_da_sel = "epilepsy") app$setInputs(navbar_ID = "Likelihood", outc_sel = "count", dist_sel = "negbinomial") app$setInputs(likelihood_navlist_ID = "Predictors", pred_mainCP_sel = c("Trt", "zAge"), pred_mainPP_sel = c("patient", "visit")) app$setInputs(pred_int_build = c("Trt", "zAge"), pred_int_add = "click") app$setInputs(pred_int_build = c("Trt", "visit"), pred_int_add = "click") app$setInputs(offs_sel = c("zBase", "Base")) app$setInputs(likelihood_navlist_ID = "Formula preview") app$setInputs(navbar_ID = "Prior") app$snapshot() app$setInputs(navbar_ID = "Data", ex_da_sel = "") app$setInputs(navbar_ID = "Likelihood") app$setInputs(likelihood_navlist_ID = "Predictors") app$setInputs(likelihood_navlist_ID = "Outcome") app$setInputs(navbar_ID = "Prior") app$snapshot()
NULL complementarityIndex <- function(g1,g2, seed.set1, seed.set2, threshold = 0, p = FALSE, nperm = 1000){ normalize_complementarity <- function(complement.cpd, seed.set1) { if (length(complement.cpd)) { norm.seed <- lapply(seed.set1, function(x)match(complement.cpd,x, nomatch = 0)) %>% sapply(sum) %>% is_greater_than(0) %>% sum complementary.index <- norm.seed / length(seed.set1) } else complementary.index <- 0 } perm_complementary <- function(seed.set1, seed.set2, g1, nonseed2){ seed1.len <- lengths(seed.set1) sample.seed1 <- sample(V(g1)$name,sum(seed1.len)) %>% split(rep(1:length(seed.set1), seed1.len)) complement.cpd <- setdiff(unlist(sample.seed1),unlist(seed.set2)) %>% intersect(., nonseed2) perm.complementary <- normalize_complementarity(complement.cpd, sample.seed1) return(perm.complementary) } if (!is.igraph(g1) || !is.igraph(g2)) stop("Both g1 and g2 must be igraph object") nonseed2 <- setdiff(V(g2)$name, unlist(seed.set2)) complement.cpd <- setdiff(unlist(seed.set1),unlist(seed.set2)) %>% intersect(., nonseed2) complementary.index <- normalize_complementarity(complement.cpd, seed.set1) if (p){ perm.complementary <- replicate(nperm, perm_complementary(seed.set1, seed.set2, g1, nonseed2)) p.value <- sum(perm.complementary < complementary.index, 1)/(nperm + 1) p.value <- round(p.value, digits = 5) return(list(complementary.index = complementary.index, p.value = p.value)) }else return(complementary.index) } competitionIndex <- function(g1,g2, seed.set1, seed.set2, threshold=0, p = FALSE, nperm = 1000){ normalize_competition <- function(intersect.seed, seed.set1){ if(length(intersect.seed)){ norm.seed <- lapply(seed.set1, function(x)match(intersect.seed, x, nomatch = 0)) %>% sapply(sum) %>% is_greater_than(0) %>% sum competition.index <- norm.seed/length(seed.set1) }else{ competition.index <- 0 } } perm_competition <- function(seed.set1, seed.set2, g1){ seed1.len <- lengths(seed.set1) sample.seed1 <- sample(V(g1)$name,sum(seed1.len)) %>% split(rep(1:length(seed.set1), seed1.len)) intersect.seed <- intersect(unlist(sample.seed1),unlist(seed.set2)) return(normalize_competition(intersect.seed, sample.seed1)) } if (!is.igraph(g1) || !is.igraph(g2)) stop("Both g1 and g2 must be igraph object") intersect.seed <- intersect(unlist(seed.set1),unlist(seed.set2)) if(length(intersect.seed)){ norm.seed <- lapply(intersect.seed,function(x)lapply(seed.set1, function(y)match(x,y,nomatch=0))) %>% lapply(.,function(x)which(x>0)) %>% unique %>% length competition.index <- norm.seed/length(seed.set1) }else{ competition.index <- 0 } if (p){ perm.competition <- replicate(nperm, perm_competition(seed.set1, seed.set2, g1)) p.value <- sum(perm.competition > competition.index, 1)/(nperm + 1) p.value <- round(p.value, digits = 5) return(list(competition.index = competition.index, p.value = p.value)) }else return(competition.index) } calculateCooperationIndex <- function(g, ...,threshold=0, p = FALSE, nperm = 1000){ if (is.igraph(g)){ g <- c(list(g), list(...)) }else{ g <- c(g, list(...)) } l <- length(g) if (l < 2) stop("At least two species to compare") seed.set <- lapply(g, getSeedSets) %>% lapply(function(x)x@seeds) competition.index <- matrix(1,l,l) complementarity.index <- matrix(0,l,l) index <- permutations(l,2) %>% t %>% as.data.frame perm.seed.set <- lapply(index,function(x)seed.set[x]) perm.g <- lapply(index, function(x)g[x]) competition.v <- map2(perm.g,perm.seed.set, function(x,y)competitionIndex(x[[1]],x[[2]],y[[1]],y[[2]], threshold, p, nperm)) complementarity.v <- map2(perm.g, perm.seed.set, function(x,y)complementarityIndex(x[[1]],x[[2]],y[[1]],y[[2]], threshold, p, nperm)) for(i in 1:length(index)){ competition.index[index[1,i],index[2,i]] = unlist(competition.v[i])[1] complementarity.index[index[1,i],index[2,i]] = unlist(complementarity.v[i])[1] } row.names(competition.index) <- names(g) colnames(competition.index) <- names(g) row.names(complementarity.index) = colnames(complementarity.index) <- names(g) if (p){ competition.index.p <- matrix(0,l,l) row.names(competition.index.p) = colnames(competition.index.p) <- names(g) complementarity.index.p <- matrix(0,l,l) row.names(complementarity.index.p) = colnames(complementarity.index.p) <- names(g) for(i in 1:length(index)){ competition.index.p[index[1,i],index[2,i]] = unlist(competition.v[i])[2] complementarity.index.p[index[1,i],index[2,i]] = unlist(complementarity.v[i])[2] } return(list(competition.index = competition.index, competition.index.p = competition.index.p, complementarity.index = complementarity.index, complementarity.index.p = complementarity.index.p)) } else return(list(competition.index = competition.index, complementarity.index = complementarity.index)) }
`PathList` <- function(C,D){ L <- nrow(C) for(i in D:1) { L <- c(C[L[1],i],L) } return(L) }
plot(child ~ parent, galton)
fun.lm.theo.gld <- function (L1, L2, L3, L4, param) { if (length(L1) > 1) { L4 <- L1[4] L3 <- L1[3] L2 <- L1[2] L1 <- L1[1] } result <- rep(NA, 4) if(fun.check.gld(L1,L2,L3,L4,param)==FALSE){ return(result)} if (tolower(param) == "rs") { result[1] <- L1 + 1/L2 * ((L3 + 1)^-1 - (L4 + 1)^-1) result[2] <- fun.Lm.gt.2.rs(L3, L4, 2)/L2 result[3] <- fun.Lm.gt.2.rs(L3, L4, 3)/L2 result[4] <- fun.Lm.gt.2.rs(L3, L4, 4)/L2 } if (tolower(param) == "fmkl" | tolower(param)=="fkml") { if (L3 != 0 & L4 != 0) { result[1] <- L1 - 1/L2 * ((L3 + 1)^-1 - (L4 + 1)^-1) } if (L3 == 0 & L4 == 0) { result[1] <- fun.fmkl0(1)/L2 + L1 } if (L3 != 0 & L4 == 0) { result[1] <- fun.fmkl.L40(1, L3)/L2 + L1 } if (L3 == 0 & L4 != 0) { result[1] <- fun.fmkl.L30(1, L4)/L2 + L1 } result[2] <- fun.Lm.gt.2.fmkl(L3, L4, 2)/L2 result[3] <- fun.Lm.gt.2.fmkl(L3, L4, 3)/L2 result[4] <- fun.Lm.gt.2.fmkl(L3, L4, 4)/L2 } return(result) }
my_test_progress <- function(format = "[:bar] :percent ") { test_progress(format) } my_is_option_enabled <- function() { test_is_option_enabled() }
project_to <- function(sample_file, to_fy, fy.year.of.sample.file = NULL, ...) { if (is.null(fy.year.of.sample.file)) { fy.year.of.sample.file <- match(nrow(sample_file), c(254318L, 258774L, 263339L, 269639L, 277202L)) if (is.na(fy.year.of.sample.file)) { stop("`fy.year.of.sample.file` was not provided, yet its value could not be ", "inferred from nrow(sample_file) = ", nrow(sample_file), ". Either use ", "a 2% sample file of the years 2012-13, 2013-14, 2014-15, 2015-16, 2016-17, or ", "supply `fy.year.of.sample.file` manually.") } fy.year.of.sample.file <- c("2012-13", "2013-14", "2014-15", "2015-16", "2016-17")[fy.year.of.sample.file] } h <- as.integer(fy2yr(to_fy) - fy2yr(fy.year.of.sample.file)) project(sample_file = sample_file, h = h, fy.year.of.sample.file = fy.year.of.sample.file, ...) }
create_beast2_screenlog_folder <- function(beast2_options) { testthat::expect_true(file.exists(beast2_options$input_filename)) screenlog_filename <- beastier::extract_screenlog_filename_from_beast2_input_file( input_filename = beast2_options$input_filename ) if (is.na(screenlog_filename)) { return(invisible(beast2_options)) } dir.create( dirname(screenlog_filename), showWarnings = FALSE, recursive = TRUE ) testthat::expect_true( dir.exists(dirname(screenlog_filename)) ) invisible(beast2_options) }
.onUnload <- function(libpath) library.dynam.unload("survival", libpath)
context("canvasXpress Web Charts - Sunburst") test_that("cXsunburst1", { check_ui_test(cXsunburst1()) }) test_that("cXsunburst2", { check_ui_test(cXsunburst2()) }) test_that("cXsunburst3", { check_ui_test(cXsunburst3()) }) test_that("cXsunburst4", { check_ui_test(cXsunburst4()) })
setClass(Class = "clv.pnbd", contains = "clv.fitted.transactions", slots = c( cbs = "data.table"), prototype = list( cbs = data.table())) clv.pnbd <- function(cl, clv.data){ dt.cbs.pnbd <- pnbd_cbs(clv.data = clv.data) clv.model <- clv.model.pnbd.no.cov() return(new("clv.pnbd", clv.fitted.transactions(cl=cl, clv.model=clv.model, clv.data=clv.data), cbs = dt.cbs.pnbd)) } pnbd_cbs <- function(clv.data){ Date <- Price <- x <- date.first.actual.trans <- date.last.transaction <- NULL trans.dt <- clv.data.get.transactions.in.estimation.period(clv.data = clv.data) cbs <- trans.dt[ , list(x =.N, date.first.actual.trans = min(Date), date.last.transaction = max(Date)), by="Id"] cbs[, x := x - 1] cbs[, ':='(t.x = clv.time.interval.in.number.tu([email protected], interv=interval(start = date.first.actual.trans, end = date.last.transaction)), T.cal = clv.time.interval.in.number.tu([email protected], interv=interval(start = date.first.actual.trans, end = [email protected]@timepoint.estimation.end)))] cbs[, date.last.transaction := NULL] setkeyv(cbs, c("Id", "date.first.actual.trans")) setcolorder(cbs, c("Id","x","t.x","T.cal", "date.first.actual.trans")) return(cbs) }
"weir3a5.broadcrest" <- function(h, ht=NULL, b=NULL, B=NULL, P=NULL, L=NULL, R=0, r=0, A=NULL, alpha=1, slopeus="vertical", slopeds="vertical", kc=NULL, kr=NULL, ks=NULL, C=NULL, low.head.class=c("paved", "gravel"), contractratio=NULL, extended=TRUE, header="", flowdigits=2, coedigits=3, verbose=FALSE, eps=0.001, maxit=20) { low.head.class <- match.arg(low.head.class); if(slopeus != "vertical") { if(as.logical(length(grep(":",slopeus)))) { slopeus <- as.numeric(unlist(strsplit(slopeus,":"))); slopeus <- slopeus[1]/slopeus[2]; } else { stop("slopeus does not contain a colon (:)"); } } else { slopeus <- 0; } if(slopeds != "vertical") { if(as.logical(length(grep(":",slopeds)))) { slopeds <- as.numeric(unlist(strsplit(slopeds,":"))); slopeds <- slopeds[1]/slopeds[2]; } else { stop("slopeds does not contain a colon (:)"); } } else { slopeds <- 0; } if(slopeus < 0) stop("upstream slope can not be negative"); if(slopeds < 0) stop("downstream slope can not be negative"); if(is.null(h)) { stop("head is NULL"); } if(is.null(ht)) ht <- rep(0, length(h)); if(length(h) != length(ht)) { stop("length of head vector is not equal to length of tail water head vector"); } if(is.null(L)) { stop("weir length (along flow) is NULL"); } if(is.null(B) | B <= 0) { stop("channel width is NULL or <= 0"); } if(is.null(P) | P <= 0) { stop("weir height is NULL or <= 0"); } if(! is.null(contractratio) & length(contractratio) != length(h)) { stop("user provided contraction ratio vector is not equal to length of head vector"); } if(! is.null(A) & length(A) != length(h)) { stop("user provided approach area vector is not equal to length of head vector"); } if(B < b) { stop("user provided channel width and weir width are incompatible"); } if(length(L) == 1) L <- rep(L, length(h)); if(length(L) != length(h)) { stop("length of weir-length vector is not equal to length of head vector"); } if(! is.null(R) & (R < 0 | R > min(L))) { stop("implausible radius of curvature on crest"); } if(! is.null(r) & (r < 0 | r > b)) { stop("implausible radius of curvature on abutment"); } if(length(alpha) == 1) alpha <- rep(alpha, length(h)); if(length(alpha) != length(h)) { stop("alpha vector is not equal to length of head vector"); } if(! is.null(kc)) { if(length(kc) == 1) kc <- rep(kc, length(h)); if(length(kc) != length(h)) { stop("contraction coefficient is not equal to length of head vector"); } } if(! is.null(kr)) { if(length(kr) == 1) kr <- rep(kr, length(h)); if(length(kr) != length(h)) { stop("rounding coefficient is not equal to length of head vector"); } } if(! is.null(ks)) { if(length(ks) == 1) ks <- rep(ks, length(h)); if(length(ks) != length(h)) { stop("downstream slope coefficient is not equal to length of head vector"); } } if(! is.null(C)) { if(length(C) == 1) C <- rep(C, length(h)); if(length(C) != length(h)) { stop("discharge coefficient is not equal to length of head vector"); } } Qs <- Qo <- Qerr <- vector(mode="numeric", length=length(h)); messages <- Cs <- kcs <- krs <- kss <- Vels <- bBs <- Qs; g <- 32.2; g2 <- 2*g; Rhkr <- get("broadcrest.roundingtable", .weir.nomographs); for(i in 1:length(h)) { it <- 0; messages[i] <- "ok"; hh <- h[i]; R.over.h <- R/hh; r.over.b <- r/b; if(ht[i]/hh >= 0.85) { Qo[i] <- NA; Qs[i] <- NA; Qerr[i] <- NA; Vels[i] <- NA; Cs[i] <- NA; kcs[i] <- NA; krs[i] <- NA; kss[i] <- NA; messages[i] <- "submerged"; next; } if(hh == 0) { Qo[i] <- 0.00; Qs[i] <- 0.00; Qerr[i] <- 0.00; Vels[i] <- 0.00; Cs[i] <- NA; kcs[i] <- NA; krs[i] <- NA; kss[i] <- NA; messages[i] <- "head zero"; next; } if(is.null(kr)) { the.kr <- approx(Rhkr$R.over.h, Rhkr$kr, R.over.h, rule=2)$y } else { the.kr <- kr[i]; } h.over.L <- hh/L[i]; h.over.P <- hh/P; if(slopeus == 0) { fig6 <- get("0.0000", .weir.nomographs$fig6); h.over.L.critical <- approx(fig6$h.over.P, fig6$h.over.L, h.over.P, rule=2)$y; } else if(slopeus == 1) { fig6 <- get("1.0000", .weir.nomographs$fig6); h.over.L.critical <- approx(fig6$h.over.P, fig6$h.over.L, h.over.P, rule=2)$y; } else { slopes6 <- as.numeric(ls(.weir.nomographs$fig6)); tmp <- slopes6[slopes6 <= slopeus]; if(length(tmp) != 0) slopes6.min <- max(tmp); tmp <- slopes6[slopes6 >= slopeus]; if(length(tmp) != 0) slopes6.max <- min(tmp); if(slopeus < 1) { if(slopes6.min == slopes6.max) { fig6 <- get(sprintf("%.4f",slopes6.min), .weir.nomographs$fig6); h.over.L.critical <- approx(fig6$h.over.P, fig6$h.over.L, h.over.P, rule=2)$y; } else { fig6 <- get(sprintf("%.4f",slopes6.min), .weir.nomographs$fig6); h.over.L.min <- approx(fig6$h.over.P, fig6$h.over.L, h.over.P, rule=2)$y; fig6 <- get(sprintf("%.4f",slopes6.max), .weir.nomographs$fig6); h.over.L.max <- approx(fig6$h.over.P, fig6$h.over.L, h.over.P, rule=2)$y; h.over.L.critical <- approx(c(slopes6.min,slopes6.max), c(h.over.L.min, h.over.L.max), slopeus)$y; } } else { h.over.L.critical <- 2.4; } } if(h.over.L >= h.over.L.critical) { Qo[i] <- NA; Qs[i] <- NA; Qerr[i] <- NA; Vels[i] <- NA; Cs[i] <- NA; kcs[i] <- NA; krs[i] <- NA; kss[i] <- NA; messages[i] <- "sharp-crested"; next; } if(is.null(kc)) { if(is.null(contractratio)) { b.over.B <- b/B; } else { b.over.B <- contractratio[i]; } bBs[i] <- b.over.B; b.over.B.ratios <- as.numeric(ls(.weir.nomographs$fig3)); tmp <- b.over.B.ratios[b.over.B.ratios < b.over.B]; if(length(tmp) != 0) b.over.B.ratios.min <- max(tmp); tmp <- b.over.B.ratios[b.over.B.ratios > b.over.B]; if(length(tmp) != 0) b.over.B.ratios.max <- min(tmp); if(b.over.B < 0.90 & b.over.B >= 0.20) { if(b.over.B == 0.20) b.over.B.ratios.min <- 0.20; fig3 <- get(sprintf("%.2f",b.over.B.ratios.min), .weir.nomographs$fig3); kc.min <- approx(fig3$h.over.P, fig3$kc, h.over.P, rule=2)$y; fig3 <- get(sprintf("%.2f",b.over.B.ratios.max), .weir.nomographs$fig3); kc.max <- approx(fig3$h.over.P, fig3$kc, h.over.P, rule=2)$y; the.kc <- approx(c(b.over.B.ratios.min,b.over.B.ratios.max), c(kc.min, kc.max), b.over.B)$y; } else if(b.over.B <= 0.20) { Qo[i] <- NA; Qs[i] <- NA; Qerr[i] <- NA; Vels[i] <- NA; Cs[i] <- NA; kcs[i] <- NA; krs[i] <- NA; kss[i] <- NA; messages[i] <- "too much contraction"; next; } else { fig3 <- get(sprintf("%.2f",b.over.B.ratios.min), .weir.nomographs$fig3); kc.min <- approx(fig3$h.over.P, fig3$kc, h.over.P, rule=2)$y; the.kc <- approx(c(b.over.B.ratios.min, 1), c(kc.min, 1), b.over.B)$y; } if(r.over.b > 0.12) { the.kc <- 1.00; } else if(r.over.b > 0) { the.kc <- approx(c(0,0.12), c(the.kc,1), r.over.b, rule=2)$y; } } else { the.kc <- kc[i]; } if(is.null(C)) { if(h.over.L < 0.10) { if(low.head.class == "paved") { lowhead <- get("fig23.paved", .weir.nomographs); } else { lowhead <- get("fig23.gravel", .weir.nomographs); } the.C <- approx(lowhead$H, lowhead$C, hh, rule=2)$y; } else { if(slopeus == 0) { fig7 <- get("0.0000", .weir.nomographs$fig7); the.C <- approx(fig7$h.over.L, fig7$C, h.over.L, rule=2)$y; } else if(slopeus == 2) { fig7 <- get("2.0000", .weir.nomographs$fig7); the.C <- approx(fig7$h.over.L, fig7$C, h.over.L, rule=2)$y; } else { slopes7 <- as.numeric(ls(.weir.nomographs$fig7)); tmp <- slopes7[slopes7 <= slopeus]; if(length(tmp) != 0) slopes7.min <- max(tmp); tmp <- slopes7[slopes7 >= slopeus]; if(length(tmp) != 0) slopes7.max <- min(tmp); if(slopeus < 2) { if(slopes7.min == slopes7.max) { fig7 <- get(sprintf("%.4f",slopes7.min), .weir.nomographs$fig7); the.C <- approx(fig7$h.over.L, fig7$C, h.over.L, rule=2)$y; } else { fig7 <- get(sprintf("%.4f",slopes7.min), .weir.nomographs$fig7); C.min <- approx(fig7$h.over.L, fig7$C, h.over.L, rule=2)$y; fig7 <- get(sprintf("%.4f",slopes7.max), .weir.nomographs$fig7); C.max <- approx(fig7$h.over.L, fig7$C, h.over.L, rule=2)$y; the.C <- approx(c(slopes7.min, slopes7.max), c(C.min, C.max), slopeus)$y; } } else { Qo[i] <- NA; Qs[i] <- NA; Qerr[i] <- NA; Vels[i] <- NA; Cs[i] <- NA; kcs[i] <- NA; krs[i] <- NA; kss[i] <- NA; messages[i] <- "slopeus too shallow to determine C"; next; } } } } else { the.C <- C[i]; } if(is.null(ks)) { if(slopeds > 1) { if(slopeds < 2) { the.ks <- 1; } else if(slopeds > 5) { Qo[i] <- NA; Qs[i] <- NA; Qerr[i] <- NA; Vels[i] <- NA; Cs[i] <- the.C; kcs[i] <- the.kc; krs[i] <- the.kr; kss[i] <- NA; messages[i] <- "slopeds too shallow to determine ks"; next; } else { tmpe <- get("broadcrest.downstreamtable", .weir.nomographs); slopes <- as.numeric(get("slopes", tmpe)); h.over.Ls <- get("h.over.L", tmpe); tmp <- slopes[slopes <= slopeds]; if(length(tmp) != 0) slopes.min <- max(tmp); tmp <- slopes[slopes >= slopeds]; if(length(tmp) != 0) slopes.max <- min(tmp); if(slopes.min == slopes.max) { tmp <- get(sprintf("%.4f", slopes.min), tmpe); the.ks <- approx(h.over.Ls, tmp, h.over.P, rule=2)$y; } else { tmp <- get(sprintf("%.4f", slopes.min), tmpe); ks.min <- approx(h.over.Ls, tmp, h.over.L, rule=2)$y; tmp <- get(sprintf("%.4f", slopes.max), tmpe); ks.max <- approx(h.over.Ls, tmp, h.over.L, rule=2)$y; the.ks <- approx(c(slopes.min, slopes.max), c(ks.min, ks.max), slopeds)$y; } } } else { the.ks <- 1; } } else { the.ks <- ks[i]; } Cs[i] <- the.C; kcs[i] <- the.kc; krs[i] <- the.kr; kss[i] <- the.ks; bigOval <- the.kc*the.kr*the.ks*b; Qint <- bigOval*the.C*hh^1.5; Qo[i] <- Qold <- Qint; the.alpha <- alpha[i]; the.A <- ifelse(is.null(A), (hh+P)*B, A[i]); "afunc" <- function(Q) { vel <- Q/the.A; vhead <- vel^2/g2; Vels[i] <- vhead; H <- hh + the.alpha * vhead; if(h.over.L < 0.10) { if(low.head.class == "paved") { lowhead <- get("fig23.paved", .weir.nomographs); } else { lowhead <- get("fig23.gravel", .weir.nomographs); } if(is.null(C)) { the.C <- approx(lowhead$H, lowhead$C, hh, rule=2)$y; Cs[i] <- the.C; } else { the.C <- C[i]; } } Qtmp <- bigOval*the.C*H^1.5; return(Qtmp); } while(1) { it <- it + 1; Qnew <- afunc(Qold); if(Qnew == Inf) { Qo[i] <- NA; Qs[i] <- NA; messages[i] <- "nonconvergence"; break; } err <- abs(Qnew - Qold); Qerr[i] <- err; if(it > maxit || err < eps) break; Qold <- Qnew; } Qs[i] <- Qnew; Vels[i] <- (Qnew/the.A)^2/g2; } if(extended) { z <- data.frame(head=h, flow=round(Qs, digits=flowdigits), delta=c(NA,diff(Qs)), flowo=round(Qo, digits=flowdigits), error=Qerr, velhead=round(Vels, digits=flowdigits), H=round(h+Vels, digits=flowdigits), ht=ht, L=L, b.over.B=bBs, h.over.L=h/L, h.over.P=h/P, C=round(Cs, digits=coedigits), kc=round(kcs, digits=coedigits), kr=round(krs, digits=coedigits), ks=round(kss, digits=coedigits), source="weir3a5.broadcrest", message=messages); } else { z <- data.frame(head=h, flow=round(Qs, digits=flowdigits), flowo=round(Qo, digits=flowdigits), velhead=round(Vels, digits=flowdigits), C=round(Cs, digits=coedigits), kc=round(kcs, digits=coedigits), kr=round(krs, digits=coedigits), ks=round(kss, digits=coedigits), source="weir3a5.broadcrest", message=messages); } att <- attributes(z); att$header <- header; attributes(z) <- att; return(z); }
delete_cols <- function (ht, idx) { if (any(is.na(idx))) stop("Tried to delete a non-existent column") subset_idx <- seq_len(ncol(ht))[-idx] subset_cols(ht, subset_idx) } subset_cols <- function (ht, idx) { assert_that(is_huxtable(ht), is.numeric(idx), all(idx >= 1L), all(idx <= ncol(ht))) res <- as.data.frame(ht)[, idx, drop = FALSE] res <- new_huxtable(res) res <- arrange_spans(res, ht, cols = idx) for (a in huxtable_table_attrs) { attr(res, a) <- attr(ht, a) } for (a in huxtable_row_attrs) { attr(res, a) <- attr(ht, a) } for (a in huxtable_col_attrs) { attr(res, a) <- attr(ht, a)[idx] } for (a in setdiff(huxtable_cell_attrs, c("rowspan", "colspan"))) { attr(res, a) <- attr(ht, a)[, idx, drop = FALSE] } res <- prune_borders(res, ht, cols = idx) res <- renormalize_col_width(res) res <- set_attr_dimnames(res) res } subset_rows <- function (ht, idx) { assert_that(is_huxtable(ht), is.numeric(idx), all(idx >= 1L), all(idx <= nrow(ht))) res <- as.data.frame(ht)[idx, , drop = FALSE] res <- new_huxtable(res) res <- arrange_spans(res, ht, rows = idx) for (a in huxtable_table_attrs) { attr(res, a) <- attr(ht, a) } for (a in huxtable_row_attrs) { attr(res, a) <- attr(ht, a)[idx] } for (a in huxtable_col_attrs) { attr(res, a) <- attr(ht, a) } for (a in setdiff(huxtable_cell_attrs, c("rowspan", "colspan"))) { attr(res, a) <- attr(ht, a)[idx, , drop = FALSE] } res <- prune_borders(res, ht, rows = idx) res <- renormalize_row_height(res) res <- set_attr_dimnames(res) res } replace_properties <- function (ht, i, j, value) { assert_that( is_hux(ht), is_hux(value), is.numeric(i), all(i >= 1L), all(i <= nrow(ht)), is.numeric(j), all(j >= 1L), all(j <= ncol(ht)), length(i) == nrow(value), length(j) == ncol(value) ) for (a in huxtable_cell_attrs) { attr(ht, a)[i, j] <- attr(value, a) } if (identical(i, seq_len(nrow(ht)))) { old_cw <- col_width(ht)[j] for (a in huxtable_col_attrs) { attr(ht, a)[j] <- attr(value, a) } new_cw <- col_width(ht)[j] if (is.numeric(old_cw) && is.numeric(new_cw)) { col_width(ht)[j] <- new_cw/sum(new_cw) * sum(old_cw) } } if (identical(j, seq_len(ncol(ht)))) { old_rh <- row_height(ht)[j] for (a in huxtable_row_attrs) { attr(ht, a)[i] <- attr(value, a) } new_rh <- row_height(ht)[j] if (is.numeric(old_rh) && is.numeric(new_rh)) { row_height(ht)[j] <- new_rh/sum(new_rh) * sum(old_rh) } } replace_props <- function (getter, setter) { ht <<- setter(ht, `[<-`(getter(ht), i, j, value = getter(value))) } mapply( FUN = replace_props, huxtable_border_df$getter, huxtable_border_df$setter ) ht <- set_attr_dimnames(ht) ht } arrange_spans <- function ( new_ht, old_ht, rows = seq_len(nrow(old_ht)), cols = seq_len(ncol(old_ht)) ) { if (ncol(new_ht) == 0 || nrow(new_ht) == 0) return(new_ht) dc <- display_cells(old_ht) stride <- max(dim(old_ht)) merge_sets <- dc$display_row * stride + dc$display_col dim(merge_sets) <- dim(old_ht) row_number <- dc$row - dc$display_row + 1L col_number <- dc$col - dc$display_col + 1L dim(row_number) <- dim(col_number) <- dim(old_ht) merge_sets <- merge_sets[rows, cols, drop = FALSE] row_number <- row_number[rows, cols, drop = FALSE] col_number <- col_number[rows, cols, drop = FALSE] merge_sets <- rbind(merge_sets, 0) merge_sets <- cbind(merge_sets, 0) row_number <- rbind(row_number, 0) row_number <- cbind(row_number, 0) col_number <- rbind(col_number, 0) col_number <- cbind(col_number, 0) nrs <- rowspan(new_ht) ncs <- colspan(new_ht) row_seq <- seq_len(nrow(new_ht) + 1) col_seq <- seq_len(ncol(new_ht) + 1) done <- matrix(FALSE, nrow(new_ht), ncol(new_ht)) for (i in seq_len(nrow(new_ht))) for (j in seq_len(ncol(new_ht))) { ms <- merge_sets[i, j] if (done[i, j]) next end_row <- min(which(row_seq >= i & merge_sets[, j] != ms)) - 1 end_col <- min(which(col_seq >= j & merge_sets[i, ] != ms)) - 1 rn <- row_number[seq(i, end_row), j] cn <- col_number[i, seq(j, end_col)] all_rn <- seq(min(rn), max(rn)) all_cn <- seq(min(cn), max(cn)) all_matched_row <- i - 1 + max(match(all_rn, rn)) all_matched_col <- j - 1 + max(match(all_cn, cn)) end_row <- min(end_row, all_matched_row, na.rm = TRUE) end_col <- min(end_col, all_matched_col, na.rm = TRUE) nrs[i, j] <- end_row - i + 1 ncs[i, j] <- end_col - j + 1 done[seq(i, end_row), seq(j, end_col)] <- TRUE } rowspan(new_ht) <- nrs colspan(new_ht) <- ncs new_ht } prune_borders <- function ( new_ht, old_ht, rows = seq_len(nrow(old_ht)), cols = seq_len(ncol(old_ht)) ) { prune_props <- function (getter, setter) { new_ht <<- setter(new_ht, getter(old_ht)[rows, cols]) } mapply( FUN = prune_props, huxtable_border_df$getter, huxtable_border_df$setter ) new_ht } normalize_index <- function(idx, max_dim, dim_names) { if (missing(idx)) return(seq_len(max_dim)) UseMethod("normalize_index") } normalize_index.matrix <- function(idx, max_dim, dim_names) { stop("You can't subset a huxtable with a matrix") } normalize_index.logical <- function(idx, max_dim, dim_names) { if (length(idx) > max_dim) { stop("More rows/columns specified than found in huxtable") } if (max_dim %% length(idx) > 0) { warning("Length of subscript does not divide huxtable dimension exactly") } idx <- rep(idx, length.out = max_dim) which(idx) } normalize_index.character <- function(idx, max_dim, dim_names) { if (any(is.na(idx))) stop("NA in subscript") match(idx, dim_names) } normalize_index.numeric <- function(idx, max_dim, dim_names) { if (any(is.na(idx))) stop("NA in subscript") if (any(idx < 0)) { if (! all(idx <= 0)) stop("Can't mix positive and negative subscripts") if (any(-idx > max_dim)) stop("Negative subscript out of bounds") idx <- seq_len(max_dim)[idx] } idx_oob <- idx > max_dim if (any(idx_oob)) { filled_in_seq <- seq(max_dim + 1, max(idx[idx_oob])) if (! identical(as.integer(sort(idx[idx_oob])), filled_in_seq)) { stop("Missing new rows/columns in subscript: huxtable dimension is ", max_dim, "but subscripts were ", paste(idx, collapse = " ")) } idx[idx_oob] <- NA_integer_ } idx } normalize_index.default <- function(idx, max_dim, dim_names) { stop("Unrecognized subscript of type ", typeof(idx)) }
predict_survival.model_fit <- function(object, new_data, time, interval = "none", level = 0.95, ...) { check_spec_pred_type(object, "survival") if (inherits(object$fit, "try-error")) { rlang::warn("Model fit failed; cannot make predictions.") return(NULL) } new_data <- prepare_data(object, new_data) if (!is.null(object$spec$method$pred$survival$pre)) new_data <- object$spec$method$pred$survival$pre(new_data, object) object$spec$method$pred$survival$args$time <- time pred_call <- make_pred_call(object$spec$method$pred$survival) res <- eval_tidy(pred_call) if(!is.null(object$spec$method$pred$survival$post)) { res <- object$spec$method$pred$survival$post(res, object) } res } predict_survival <- function (object, ...) UseMethod("predict_survival")
nullSp <- function(A){ m <- dim(A)[1] n <- dim(A)[2] val <- svd(A, nv = n) V <- val$v S <- val$d if(m > 1){ s <- S } else if(m == 1){ s <- S[1] } else{ s <- 0 } tol <- max(m,n)*max(s)*.Machine$double.eps r <- sum(s > tol) if(r+1>n){ N <- matrix(0,dim(V)[1],0) } else{ N <- V[,(r+1):n, drop = FALSE] } return(N) }
context("plot missing data profile") test_that("test return object", { plot_obj <- plot_missing(airquality) expect_true(is.ggplot(plot_obj)) })
table.SFM <- table.CAPM <- function (Ra, Rb, scale = NA, Rf = 0, digits = 4) { Ra = checkData(Ra) Rb = checkData(Rb) if(!is.null(dim(Rf))) Rf = checkData(Rf) columns.a = ncol(Ra) columns.b = ncol(Rb) columnnames.a = colnames(Ra) columnnames.b = colnames(Rb) Ra.excess = Return.excess(Ra, Rf) Rb.excess = Return.excess(Rb, Rf) if(is.na(scale)) { freq = periodicity(Ra) switch(freq$scale, minute = {stop("Data periodicity too high")}, hourly = {stop("Data periodicity too high")}, daily = {scale = 252}, weekly = {scale = 52}, monthly = {scale = 12}, quarterly = {scale = 4}, yearly = {scale = 1} ) } for(column.a in 1:columns.a) { for(column.b in 1:columns.b) { merged.assets = merge(Ra.excess[,column.a,drop=FALSE], Rb.excess[,column.b,drop=FALSE]) merged.assets = as.data.frame(na.omit(merged.assets)) model.lm = lm(merged.assets[,1] ~ merged.assets[,2]) alpha = coef(model.lm)[[1]] beta = coef(model.lm)[[2]] CAPMbull = CAPM.beta.bull(Ra[,column.a], Rb[,column.b],Rf) CAPMbear = CAPM.beta.bear(Ra[,column.a], Rb[,column.b],Rf) htest = cor.test(as.numeric(merged.assets[,1]), as.numeric(merged.assets[,2])) active.premium = ActivePremium(Ra=Ra[,column.a],Rb=Rb[,column.b], scale = scale) tracking.error = TrackingError(Ra[,column.a], Rb[,column.b],scale=scale) treynor.ratio = TreynorRatio(Ra=Ra[,column.a], Rb=Rb[,column.b], Rf = Rf, scale = scale) z = c( alpha, beta, CAPMbull, CAPMbear, summary(model.lm)$r.squared, ((1+alpha)^scale - 1), htest$estimate, htest$p.value, tracking.error, active.premium, active.premium/tracking.error, treynor.ratio ) znames = c( "Alpha", "Beta", "Beta+", "Beta-", "R-squared", "Annualized Alpha", "Correlation", "Correlation p-value", "Tracking Error", "Active Premium", "Information Ratio", "Treynor Ratio" ) if(column.a == 1 & column.b == 1) { result.df = data.frame(Value = z, row.names = znames) colnames(result.df) = paste(columnnames.a[column.a], columnnames.b[column.b], sep = " to ") } else { nextcolumn = data.frame(Value = z, row.names = znames) colnames(nextcolumn) = paste(columnnames.a[column.a], columnnames.b[column.b], sep = " to ") result.df = cbind(result.df, nextcolumn) } } } result.df = base::round(result.df, digits) result.df }
open_tunnel <- function(remote_host, user = NULL, password = NULL, tunnel_dir = "~/.pecan/tunnel/", wait.time = 15, tunnel_script = '~/pecan/web/sshtunnel.sh'){ dir.create(tunnel_dir) if(is.null(user)){ user <- readline("Username:: ") } if(is.null(password)){ password <- getPass::getPass() } sshTunnel <- file.path(tunnel_dir, "tunnel") sshPID <- file.path(tunnel_dir, "pid") sshPassFile <- file.path(tunnel_dir, "password") if(file.exists(sshTunnel)){ PEcAn.logger::logger.warn("Tunnel already exists. If tunnel is not working try calling kill.tunnel then reopen") return(TRUE) } PEcAn.logger::logger.warn(sshPassFile) write(password, file = sshPassFile) stat <- system(paste(tunnel_script, remote_host, user, tunnel_dir), wait=FALSE) Sys.sleep(wait.time) if (file.exists(sshPassFile)) { file.remove(sshPassFile) PEcAn.logger::logger.error("Tunnel open failed") return(FALSE) } if (file.exists(sshPID)) { pid <- readLines(sshPID, n = -1) return(as.numeric(pid)) } else { return(TRUE) } }
pimamh=function(Niter=10^4,scale=.01){ library(MASS) da=cbind(Pima.tr$type,Pima.tr$bmi) da[,1]=da[,1]-1 like=function(a,b){ sum(pnorm(q=a+outer(X=b,Y=da[,2],FUN="*"),log=T)*da[,1]+pnorm(q=-a-outer(X=b,Y=da[,2],FUN="*"),log=T)*(1-da[,1]))} grad=function(a,b){ don=pnorm(q=a+outer(X=b,Y=da[,2],FUN="*")) x1=sum((dnorm(x=a+outer(X=b,Y=da[,2],FUN="*"))/don)*da[,1]- (dnorm(x=-a-outer(X=b,Y=da[,2],FUN="*"))/(1-don))*(1-da[,1])) x2=sum((dnorm(x=a+outer(X=b,Y=da[,2],FUN="*"))/don)*da[,2]*da[,1]- (dnorm(x=-a-outer(X=b,Y=da[,2],FUN="*"))/(1-don))*da[,2]*(1-da[,1])) return(c(x1,x2)) } the=matrix(glm(da[,1]~da[,2],family=binomial(link="probit"))$coef,ncol=2) curmean=the[1,]+0.5*scale^2*grad(the[1,1],the[1,2]) likecur=like(the[1,1],the[1,2]) for (t in 2:Niter){ prop=curmean+scale*rnorm(2) propmean=prop+0.5*scale^2*grad(prop[1],prop[2]) if (log(runif(1))>like(prop[1],prop[2])-likecur-sum(dnorm(prop,mean=curmean,sd=scale,lo=T))+ sum(dnorm(the[t-1,],mean=propmean,sd=scale,lo=T))){ prop=the[t-1,];propmean=curmean } the=rbind(the,prop) curmean=propmean } be1=seq(min(the[,1]),max(the[,1]),le=100) be2=seq(min(the[,2]),max(the[,2]),le=130) li=matrix(0,ncol=130,nro=100) for (i in 1:100) for (j in 1:130) li[i,j]=like(be1[i],be2[j]) par(mar=c(4,4,1,1)) image(be1,be2,li,xlab=expression(beta[1]),ylab=expression(beta[2])) contour(be1,be2,li,add=T,ncla=100) subs=seq(1,Niter,le=10^3) points(unique(the[subs,1]),unique(the[subs,2]),cex=.4,pch=19) }
calc_cat_stats <- function(stat_dat, stat_key, rv, plausibility = FALSE, plausibility_key) { if (base::missing(plausibility_key)) { stopifnot(isFALSE(plausibility)) } statistics <- list() key_cols <- get_key_col(rv) key_col_name_src <- key_cols$source key_col_name_tar <- key_cols$target statistics$source_data <- tryCatch( expr = { f <- stat_dat[get("source_system_name") == rv$source$system_name, get("filter")] f <- setdiff(f, NA) if (length(f) > 0) { where_filter <- get_where_filter(f) } else { where_filter <- NULL } if (isFALSE(plausibility)) { source_data <- categorical_analysis( data = rv$data_source[[stat_dat[get("source_system_name") == rv$source$system_name, get(key_col_name_src)]]], var = stat_key, levellimit = Inf, filter = where_filter ) } else { source_data <- categorical_analysis( data = rv$data_source[[plausibility_key]], var = stat_key, levellimit = Inf, filter = where_filter ) } source_data }, error = function(e) { DIZutils::feedback( paste0("Error occured when calculating source catStats: ", e), findme = "b8e039a302", type = "Error", logfile_dir = rv$log$logfile_dir ) source_data <- NULL source_data }) statistics$target_data <- tryCatch( expr = { f <- stat_dat[get("source_system_name") == rv$target$system_name, get("filter")] f <- setdiff(f, NA) if (length(f) > 0) { where_filter <- get_where_filter(f) } else { where_filter <- NULL } if (isFALSE(plausibility)) { target_data <- categorical_analysis( data = rv$data_target[[stat_dat[get("source_system_name") == rv$target$system_name, get(key_col_name_tar)]]], var = stat_key, levellimit = Inf, filter = where_filter ) } else { target_data <- categorical_analysis( data = rv$data_target[[plausibility_key]], var = stat_key, levellimit = Inf, filter = where_filter ) } target_data }, error = function(e) { DIZutils::feedback( paste0("Error occured when calculating target catStats: ", e), findme = "5b1a5937e5", type = "Error", logfile_dir = rv$log$logfile_dir ) target_data <- NULL target_data }) return(statistics) }
getauthorrecordfull <- function(id, code = NA) { repec_api_with_id(method = 'getauthorrecordfull', id = id, code = code) } get_author_record_full <- getauthorrecordfull
gensilwidth <- function (clust, dist, p=1) { clust <- clustify(clust) if (any(table(clust)<1)) stop("All clusters must have at least one member") clust <- as.numeric(clustify(clust)) numclu <- max(clust) numplt <- length(clust) home <- rep(0,numplt) neigh <- rep(0,numplt) val <- rep(0,numplt) names <- attr(dist,'Labels') disptc <- matrix(0, nrow = numplt, ncol = numclu) if (!inherits(dist,'dist')) { stop("The second argument must be an object of class 'dist'") } dist <- as.matrix(dist) if (max(dist) > 1) dist <- dist/max(dist) card <- rep(0,numclu) for (i in 1:numclu) { card[i] <- sum(clust==i) } if (p == -Inf) { for (i in 1:numplt) { for (j in 1:numclu) { if (clust[i] == j) { if (card[j] > 1) { mask <- clust==j mask[i] <- FALSE disptc[i,j] <- min(dist[i,mask]) } else { disptc[i,j] <- 0 } } else { disptc[i,j] <- min(dist[i,clust==j]) } } } } else if (p == Inf) { for (i in 1:numplt) { for (j in 1:numclu) { if (clust[i] == j) { if (card[j] > 1) { mask <- clust==j mask[i] <- FALSE disptc[i,j] <- max(dist[i,mask]) } else { disptc[i,j] <- 0 } } else { disptc[i,j] <- max(dist[i,clust==j]) } } } } else if (p == 0) { for (i in 1:numplt) { for (j in 1:numclu) { if (clust[i] == j) { if (card[j] > 1) { mask <- clust==j mask[i] <- FALSE tmp <- dist[i,mask] tmp[tmp==0] <- 1e-10 disptc[i,j] <- prod(tmp)^(1/(card[j]-1)) } else { disptc[i,j] <- 0 } } else { disptc[i,j] <- prod(dist[i,clust==j])^(1/card[j]) } } } } else { for (i in 1:numplt) { for (j in 1:numclu) { if (clust[i] == j) { if (card[j] > 1) { mask <- clust == j mask[i] <- FALSE disptc[i,j] <- mean(dist[i,mask]^p)^(1/p) } else { disptc[i, j] <- 0 } } else { disptc[i, j] <- mean(dist[i,clust==j]^p)^(1/p) } } } } for (i in 1:numplt) { home[i] <- disptc[i,clust[i]] val[i] <- min(disptc[i,-clust[i]]) neigh[i] <- which(disptc[i,] == val[i])[1] } sils <- (val - home) / pmax(home,val) for (i in 1:numclu) { if (card[i] == 1) sils[clust==i] <- 0 } out <- as.matrix(cbind(clust,neigh,sils)) colnames(out) <- c('cluster','neighbor','sil_width') rownames(out) <- names attr(out,'class') <- 'silhouette' attr(out,'call') <- match.call() attr(out,'Ordered') <- FALSE out }
anova.glmRob <- function(object, ..., test = c("none", "Chisq", "F", "Cp")) { test <- match.arg(test) margs <- function(...) nargs() if(margs(...)) return(anova.glmRoblist(list(object, ...), test = test)) Terms <- object$terms term.labels <- attr(Terms, "term.labels") nt <- length(term.labels) m <- model.frame(object) x <- model.matrix(Terms, m, contrasts = object$contrasts) asgn <- attr(x, "assign") control <- object$control if(is.null(control)) { fit.method <- object$fit.method if(fit.method=="cubif") control <- glmRob.cubif.control() else if(fit.method == "mallows") control <- glmRob.mallows.control() else if(fit.method == "misclass") control <- glmRob.misclass.control() else stop(paste("method ", fit.method," does not exist")) } Family <- family(object) a <- attributes(m) y <- model.extract(m, "response") w <- model.extract(m, "weights") if(!length(w)) w <- rep(1, nrow(m)) offset <- attr(Terms, "offset") if(is.null(offset)) offset <- 0 else offset <- m[[offset]] dev.res <- double(nt) df.res <- dev.res nulld <- object$null.deviance if(is.null(nulld)) nulld <- sum(w * (y - weighted.mean(y, w))^2) dev.res[1] <- nulld df.res[1] <- nrow(x) - attr(Terms, "intercept") if(nt > 1) { for(iterm in seq(nt, 2)) { idx <- which(asgn == iterm) x <- x[ , -idx, drop = FALSE] asgn <- asgn[-idx] fit.call <- object$call fit.call[[1]] <- as.name(paste('glmRob.', object$method, sep = '')) fit.call$x <- x fit.call$y <- y fit.call$control <- control fit.call$family <- family(object) fit.call$offset <- offset fit.call$Terms <- NULL fit.call$null.dev <- TRUE fit.call$formula <- NULL fit.call$data <- NULL fit <- eval(fit.call, sys.parent()) dev.res[iterm] <- deviance(fit) df.res[iterm] <- fit$df.resid } } if(nt) { dev.res <- c(dev.res, deviance(object)) df.res <- c(df.res, object$df.resid) dev <- c(NA, - diff(dev.res)) df <- c(NA, - diff(df.res)) } else dev <- df <- as.numeric(NA) heading <- c("Analysis of Deviance Table\n", paste(Family$family[1], "model\n"), paste("Response: ", as.character(formula(object))[2], "\n", sep = ""), "Terms added sequentially (first to last)") aod <- data.frame(Df = df, Deviance = dev, "Resid. Df" = df.res, "Resid. Dev" = dev.res, row.names = c("NULL", term.labels), check.names = FALSE) attr(aod, "heading") <- heading oldClass(aod) <- c("anova", "data.frame") if(test == "none") return(aod) else stat.anova(aod, test, deviance(object)/object$df.resid, object$df.resid, nrow(x)) }
rmrow.foldert <- function(object, name) { if (!is.foldert(object)) stop("rmrow.foldert applies to an object of class 'foldert'.") xf <- list() for (k in 1:length(object)) { objk <- object[[k]] xf[[k]] <- objk[!(rownames(objk) %in% name), ] } attributes(xf) <- attributes(object) return(xf) }
setClass("modelObjFormula", contains = c("modelObj")) .newModelObjFormula <- function(model, solver.method, solver.args, predict.method, predict.args) { solver <- .newMethodObjSolverFormula(method = solver.method, args = solver.args) predictor <- .newMethodObjPredict(method = predict.method, args = predict.args) return( new("modelObjFormula", model = model, solver = solver, predictor = predictor) ) }
names_dbrows <- function(w_map = NULL, myWay = "By Row", kindExpt = "DBUDC", data_dim_each_block = NULL, planter = "serpentine", w_map_letters = NULL, expt_name = NULL, Checks = NULL) { checks <- Checks if (kindExpt == "DBUDC") { if (myWay == "By Row") { my_row_sets <- automatically_cuts(data = w_map, planter_mov = planter, way = "By Row", dim_data = data_dim_each_block)[[1]] blocks <- length(my_row_sets) w_map_letters1 <- w_map_letters Index_block <- LETTERS[1:blocks] Name_expt <- expt_name if (length(Name_expt) == blocks || !is.null(Name_expt)) { name_blocks <- Name_expt }else { name_blocks <- paste(rep("Expt", blocks), 1:blocks, sep = "") } z <- 1 for(i in Index_block){ w_map_letters1[w_map_letters1 == i] <- name_blocks[z] z <- z + 1 } checks_ch <- as.character(checks) for(i in nrow(w_map_letters1):1) { for(j in 1:ncol(w_map_letters1)) { if (any(checks_ch %in% w_map_letters1[i, j]) && w_map_letters1[i,j] != "Filler") { if (j != ncol(w_map_letters1)){ if(w_map_letters1[i, j + 1] == "Filler") { w_map_letters1[i, j] <- w_map_letters1[i, j - 1] }else w_map_letters1[i, j] <- w_map_letters1[i, j + 1] }else if (j == ncol(w_map_letters1)) { w_map_letters1[i, j] <- w_map_letters1[i, j - 1] } } } } split_names <- w_map_letters1 }else{ return(NULL) } } return(list(my_names = split_names)) }
fdata2model <- function(vfunc, vnf, response, data, basis.x=NULL,pf,tf){ print("fdata2model") kterms = 1 vs.list=mean.list=name.coef=nam=beta.l=list() bsp1=TRUE if (length(vnf)>0) { XX=data[["df"]][,c(response,vnf)] for ( i in 1:length(vnf)){ if (kterms > 1) pf <- paste(pf, "+", vnf[i], sep = "") else pf <- paste(pf, vnf[i], sep = "") kterms <- kterms + 1 } if (attr(tf,"intercept")==0) { pf<- paste(pf,-1,sep="") } } else { XX=data$df[response] names(XX)=response } lenfunc<-length(vfunc)>0 if (lenfunc) { for (i in 1:length(vfunc)) { if (class(data[[vfunc[i]]])[1]=="fdata"){ tt<-data[[vfunc[i]]][["argvals"]] rtt<-data[[vfunc[i]]][["rangeval"]] fdat<-data[[vfunc[i]]]; dat<-data[[vfunc[i]]]$data if (is.null(basis.x[[vfunc[i]]])) basis.x[[vfunc[i]]]<-create.fdata.basis(fdat,l=1:7) else if (basis.x[[vfunc[i]]]$type=="pc" | basis.x[[vfunc[i]]]$type=="pls") bsp1=FALSE if (bsp1) { if (is.null(rownames(dat))) rownames(fdat$data)<-1:nrow(dat) fdnames=list("time"=tt,"reps"=rownames(fdat[["data"]]),"values"="values") xcc<-fdata.cen(data[[vfunc[i]]]) mean.list[[vfunc[i]]]=xcc[[2]] if (!is.null( basis.x[[vfunc[i]]]$dropind)) { int<-setdiff(1:basis.x[[vfunc[i]]]$nbasis,basis.x[[vfunc[i]]]$dropind) basis.x[[vfunc[i]]]$nbasis<-length(int) basis.x[[vfunc[i]]]$dropind<-NULL basis.x[[vfunc[i]]]$names<-basis.x[[vfunc[i]]]$names[int] } x.fd = Data2fd(argvals = tt, y = t(xcc[[1]]$data),basisobj = basis.x[[vfunc[i]]],fdnames=fdnames) r=x.fd[[2]][[3]] J=inprod(basis.x[[vfunc[i]]],basis.x[[vfunc[i]]]) J12=inprod(basis.x[[vfunc[i]]]) Z =t(x.fd$coefs) %*% J colnames(J)=colnames(Z) = name.coef[[vfunc[i]]]=paste(vfunc[i],".",basis.x[[vfunc[i]]]$names,sep="") XX = cbind(XX,Z) for ( j in 1:length(colnames(Z))){ if (kterms >= 1) pf <- paste(pf, "+", colnames(Z)[j], sep = "") else pf <- paste(pf, colnames(Z)[j], sep = "") kterms <- kterms + 1 } vs.list[[vfunc[i]]]<-J } else { l<-basis.x[[vfunc[i]]]$l lenl<-length(l) vs <- t(basis.x[[vfunc[i]]]$basis$data) Z<-basis.x[[vfunc[i]]]$x[,l,drop=FALSE] response = "y" colnames(Z) = name.coef[[vfunc[i]]]=paste(vfunc[i], ".",colnames(Z),sep ="") name.coef[[vfunc[i]]]<-colnames(Z) XX = cbind(XX,Z) vs.list[[vfunc[i]]]=basis.x[[vfunc[i]]]$basis mean.list[[vfunc[i]]]=basis.x[[vfunc[i]]]$mean for ( j in 1:length(colnames(Z))){ if (kterms >= 1) pf <- paste(pf, "+", name.coef[[vfunc[i]]][j], sep = "") else pf <- paste(pf, name.coef[[vfunc[i]]][j], sep = "") kterms <- kterms + 1 } } } } } else pf <- tf pf<-as.formula(pf) if (!is.data.frame(XX)) XX=data.frame(XX) print("sale fdata2model") return(list(pf=pf,vs.list=vs.list,mean.list=mean.list,XX=XX,basis.x=basis.x)) }
ConvertData <- function(input, yesLabel = NULL, noLabel = NULL, missLabel = NULL, data.type = c("WHO2012", "WHO2016")[1]){ if(is.null(yesLabel) || is.null(noLabel) || is.null(missLabel)){ stop("Error: please specify what values are used in the data to represent yes, no, and missing") } ynm <- c("Y", "", ".") if(data.type == "WHO2016") ynm <- c("y", "n", "-") output <- data.frame(matrix("", dim(input)[1], dim(input)[2]), stringsAsFactors = FALSE) unchanged <- NULL if(length(unique(input[, 1])) != length(input[, 1])){ stop("Error: duplicate ID in the first column, please check the first column is ID and contains only unique values.") } output[, 1] <- input[, 1] for(i in 2:dim(input)[2]){ tmp <- as.character(input[, i]) if(sum(!(tmp %in% c(yesLabel, noLabel, missLabel))) > 0){ unchanged <- c(unchanged, colnames(input)[i]) output[, i] <- tmp }else{ output[which(tmp %in% yesLabel), i] <- ynm[1] output[which(tmp %in% noLabel), i] <- ynm[2] output[which(tmp %in% missLabel), i] <- ynm[3] } } if(length(unchanged) > 0){ warning(paste("The following columns not recognized as symptoms and not modified:\n", paste(unchanged, collapse = ", "), "\n")) } colnames(output) <- colnames(input) return(output) } getPHMRC_url <- function(type){ if(type == "adult"){ return(url('http://ghdx.healthdata.org/sites/default/files/record-attached-files/IHME_PHMRC_VA_DATA_ADULT_Y2013M09D11_0.csv')) }else if(type == "child"){ return(url('http://ghdx.healthdata.org/sites/default/files/record-attached-files/IHME_PHMRC_VA_DATA_CHILD_Y2013M09D11_0.csv')) }else if(type == "neonate"){ return(url('http://ghdx.healthdata.org/sites/default/files/record-attached-files/IHME_PHMRC_VA_DATA_NEONATE_Y2013M09D11_0.csv')) }else{ stop("Unknown type") } } ConvertData.phmrc <- function(input, input.test = NULL, cause = NULL, phmrc.type = c("adult", "child", "neonate")[1], cutoff = c("default", "adapt")[1], ...){ if(phmrc.type == "adult"){ out <- .phmrc_adult_convert(input, input.test, cause = cause, type = cutoff) }else if(phmrc.type == "child"){ out <- .phmrc_child_convert(input, input.test, cause = cause, type = cutoff) warnings("Child data conversion is experimental.") }else if(phmrc.type == "neonate"){ stop("child data conversion still under development...") } return(out) } .phmrc_adult_convert <- function(input, input.test, cause, type = c("default", "adapt")[1]){ if(is.null(cause)){ cause <- "va34" } if(!is.null(input.test)){ if(length(which(colnames(input) != colnames(input.test)))){ stop("Columns do not match in the two dataset") } N <- dim(input)[1] input <- rbind(input, input.test) }else{ N <- dim(input)[1] } if(colnames(input)[1] != "site"){ cat("The first column is assumed to be ID by default\n") id <- input[, 1] }else{ cat("The first column is site, assign IDs to each row by default\n") id <- seq(1:dim(input)[1]) } if(cause %in% colnames(input) == FALSE){ stop("No cause of death column find in data") }else{ gs <- input[, cause] } age <- which(colnames(input) == "g1_07a") sex <- which(colnames(input) == "g1_05") first_symp <- which(colnames(input) == "a1_01_1") last_symp <- which(colnames(input) == "a5_04") if(length(age) != 1){ stop("Age variable g1_07a not in input data.") } if(length(sex) != 1){ stop("Gender variable g1_05 not in input data.") } if(length(first_symp) != 1 || length(last_symp) != 1){ stop("Symptoms not correctly specified in input format.") } symps_raw <- input[, c(sex, age, first_symp : last_symp)] symps_raw <- data.frame(symps_raw, stringsAsFactors = FALSE) symps_binary <- matrix("", dim(symps_raw)[1], dim(symps_raw)[2]) symps_binary[which(symps_raw == "Yes")] <- "Y" symps_binary[which(symps_raw == "No")] <- "" symps_binary[which(symps_raw == "Don't Know")] <- "." symps_binary[which(symps_raw == "Refused to Answer")] <- "." symps_binary[which(symps_raw == "")] <- "." symps_binary <- data.frame(symps_binary) colnames(symps_binary) <- colnames(as.matrix(symps_raw)) if(type == "default"){ symps_binary <- .toBinary_file9(symps_raw, symps_binary, adapt = FALSE, cause = NULL) }else if(type == "adapt"){ symps_binary <- .toBinary_file9(symps_raw, symps_binary, adapt = TRUE, cause = gs) }else{ stop("Unknown cutoff type argument given.") } symps_binary <- .toBinary_file10(symps_raw, symps_binary) symps_binary <- .toBinary_unhandeled(symps_raw, symps_binary) for(i in 1:dim(symps_binary)[2]){ symps_binary[, i] <- as.character(symps_binary[, i]) symps_binary[which(symps_binary[,i] == "YesYes"), i] <- "Y" symps_binary[which(symps_binary[,i] == "NoNo"), i] <- "" symps_binary[which(symps_binary[,i] == "MissingMissing"), i] <- "." } n.empty <- length(which(is.na(symps_binary))) n.yes <- length(which(symps_binary == "Y")) n.no <- length(which(symps_binary == "")) n.notknown <- length(which(symps_binary == ".")) if(n.empty != 0){ cat("There are cells not converted by default rules! Left as NA\n") } if(N == dim(input)[1]){ cat(paste0(N, " deaths in input. Format: adult\n")) }else{ cat(paste0(N, " deaths in input. Format: adult\n")) cat(paste0(dim(input)[1]-N, " deaths in test input. Format: adult\n")) } cat(paste0(dim(symps_binary)[2], " binary symptoms generated\n")) cat(paste0("\nNumber of Yes ", n.yes, "\n", "Number of No ", n.no, "\n", "Number of Not known ", n.notknown, "\n")) data.out <- cbind(id, gs, symps_binary) colnames(data.out)[1:2] <- c("ID", "Cause") if(!is.null(input.test)){ out <- data.out[1:N, ] out.test <- data.out[-(1:N), ] }else{ out <- data.out out.test <- NULL } return(list(output = out, output.test = out.test)) } .phmrc_child_convert <- function(input, input.test, cause, type = c("default", "adapt")[2]) { cause <- NULL type <- "default" if(is.null(cause)){ cause <- "va34" } if(!is.null(input.test)){ if(length(which(colnames(input) != colnames(input.test)))){ stop("Columns do not match in the two dataset") } if(cause %in% colnames(input.test)){ } N <- dim(input)[1] input <- rbind(input, input.test) }else{ N <- dim(input)[1] } if(colnames(input)[1] != "site"){ cat("The first column is assumed to be ID by default\n") id <- input[, 1] }else{ cat("The first column is site, assign IDs to each row by default\n") id <- seq(1:dim(input)[1]) } if(cause %in% colnames(input) == FALSE){ stop("No cause of death column find in data") }else{ gs <- input[, cause] } age <- which(colnames(input) == "g1_07a") sex <- which(colnames(input) == "g1_05") first_symp <- which(colnames(input) == "c1_01") last_symp <- which(colnames(input) == "c5_19") if(length(age) != 1){ stop("Age variable g1_07a not in input data.") } if(length(sex) != 1){ stop("Gender variable g1_05 not in input data.") } if(length(first_symp) != 1 || length(last_symp) != 1){ stop("Symptoms not correctly specified in input format.") } symps_raw <- input[, c(sex, age, first_symp : last_symp)] symps_raw <- data.frame(symps_raw, stringsAsFactors = FALSE) symps_binary <- matrix("", dim(symps_raw)[1], dim(symps_raw)[2]) symps_binary[which(symps_raw == "Yes")] <- "Y" symps_binary[which(symps_raw == "No")] <- "" symps_binary[which(symps_raw == "Don't Know")] <- "." symps_binary[which(symps_raw == "Refused to Answer")] <- "." symps_binary[which(symps_raw == "")] <- "." symps_binary <- data.frame(symps_binary) colnames(symps_binary) <- colnames(as.matrix(symps_raw)) if(type == "default"){ symps_binary <- .toBinary_file9_child(symps_raw, symps_binary, adapt = FALSE, cause = NULL) }else if(type == "adapt"){ symps_binary <- .toBinary_file9_child(symps_raw, symps_binary, adapt = TRUE, cause = gs) }else{ stop("Unknown cutoff argument given") } symps_binary <- .toBinary_file10_child(symps_raw, symps_binary) symps_binary <- .toBinary_unhandeled_child(symps_raw, symps_binary) for(i in 1:dim(symps_binary)[2]){ symps_binary[, i] <- as.character(symps_binary[, i]) symps_binary[which(is.na(symps_binary[,i])), i] <- "MissingMissing" symps_binary[which(symps_binary[,i] == "YesYes"), i] <- "Y" symps_binary[which(symps_binary[,i] == "NoNo"), i] <- "" symps_binary[which(symps_binary[,i] == "MissingMissing"), i] <- "." } n.empty <- length(which(is.na(symps_binary))) n.yes <- length(which(symps_binary == "Y")) n.no <- length(which(symps_binary == "")) n.notknown <- length(which(symps_binary == ".")) if(n.empty != 0){ cat("There are cells not converted by default rules! Left as NA\n") } if(N == dim(input)[1]){ cat(paste0(N, " deaths in input. Format: adult\n")) }else{ cat(paste0(N, " deaths in input. Format: adult\n")) cat(paste0(dim(input)[1]-N, " deaths in test input. Format: adult\n")) } cat(paste0(dim(symps_binary)[2], " binary symptoms generated\n")) cat(paste0("\nNumber of Yes ", n.yes, "\n", "Number of No ", n.no, "\n", "Number of Not known ", n.notknown, "\n")) data.out <- cbind(id, gs, symps_binary) colnames(data.out)[1:2] <- c("ID", "Cause") if(!is.null(input.test)){ out <- data.out[1:N, ] out.test <- data.out[-(1:N), ] }else{ out <- data.out out.test <- NULL } return(list(output = out, output.test = out.test)) } .toBinary_cutoff <- function(vec, cut, missLabel = NULL, adapt = FALSE, cause = NULL){ if(is.null(missLabel)){ missLabel <- c("Don't Know", "Refused to Answer") } vec <- as.character(vec) vec[which(vec %in% missLabel)] <- "." vec.num <- suppressWarnings(as.numeric(vec)) num <- which(!is.na(vec.num)) if(adapt){ tmp <- data.frame(cause = cause[num], duration = vec.num[num]) tmp2 <- aggregate(duration ~ cause, tmp, function(x){ mean(x)}) med <- median(tmp2[, 2]) MAD <- median(abs(tmp[, 2] - med)) if(!(is.na(med) || is.na(MAD))){ cut <- med + 2 * MAD } } vec[num] <- as.character(as.numeric(vec[num]) > cut) vec[vec == "TRUE"] <- "YesYes" vec[vec == "FALSE"] <- "NoNo" return(vec) } .toBinary_file9 <- function(symps_raw, symps, missLabel = NULL, adapt = FALSE, cause = NULL){ symps$a2_01 <- .toBinary_cutoff(symps_raw$a2_01, 528.8, missLabel, adapt, cause) symps$a2_03 <- .toBinary_cutoff(symps_raw$a2_03, 8.8, missLabel, adapt, cause) symps$a2_08 <- .toBinary_cutoff(symps_raw$a2_08, 3.1, missLabel, adapt, cause) symps$a2_15 <- .toBinary_cutoff(symps_raw$a2_15, 0.3, missLabel, adapt, cause) symps$a2_22 <- .toBinary_cutoff(symps_raw$a2_22, 54.1, missLabel, adapt, cause) symps$a2_24 <- .toBinary_cutoff(symps_raw$a2_24, 55.2, missLabel, adapt, cause) symps$a2_26 <- .toBinary_cutoff(symps_raw$a2_26, 36, missLabel, adapt, cause) symps$a2_28 <- .toBinary_cutoff(symps_raw$a2_28, 20.3, missLabel, adapt, cause) symps$a2_33 <- .toBinary_cutoff(symps_raw$a2_33, 107, missLabel, adapt, cause) symps$a2_37 <- .toBinary_cutoff(symps_raw$a2_37, 100.3, missLabel, adapt, cause) symps$a2_41 <- .toBinary_cutoff(symps_raw$a2_41, 43, missLabel, adapt, cause) symps$a2_48 <- .toBinary_cutoff(symps_raw$a2_48, 4.9, missLabel, adapt, cause) symps$a2_54 <- .toBinary_cutoff(symps_raw$a2_54, 3.2, missLabel, adapt, cause) symps$a2_58 <- .toBinary_cutoff(symps_raw$a2_58, 55.2, missLabel, adapt, cause) symps$a2_62 <- .toBinary_cutoff(symps_raw$a2_62, 16.7, missLabel, adapt, cause) symps$a2_65 <- .toBinary_cutoff(symps_raw$a2_65, 45.4, missLabel, adapt, cause) symps$a2_68 <- .toBinary_cutoff(symps_raw$a2_68, 34.4, missLabel, adapt, cause) symps$a2_70 <- .toBinary_cutoff(symps_raw$a2_70, 3.2, missLabel, adapt, cause) symps$a2_73 <- .toBinary_cutoff(symps_raw$a2_73, 2.2, missLabel, adapt, cause) symps$a2_76 <- .toBinary_cutoff(symps_raw$a2_76, 1.1, missLabel, adapt, cause) symps$a2_79 <- .toBinary_cutoff(symps_raw$a2_79, 7.8, missLabel, adapt, cause) symps$a2_83 <- .toBinary_cutoff(symps_raw$a2_83, 0.0, missLabel, adapt, cause) symps$a2_86 <- .toBinary_cutoff(symps_raw$a2_86, 20.4, missLabel, adapt, cause) symps$a3_08 <- .toBinary_cutoff(symps_raw$a3_08, 2.9, missLabel, adapt, cause) symps$a4_03 <- .toBinary_cutoff(symps_raw$a4_03, 1.2, missLabel, adapt, cause) symps$a4_04 <- .toBinary_cutoff(symps_raw$a4_03, 4.2, missLabel, adapt, cause) symps$a5_04 <- .toBinary_cutoff(symps_raw$a5_04, 8.5, missLabel, adapt, cause) symps$g1_07a <- .toBinary_cutoff(symps_raw$g1_07a, 67.6, missLabel, adapt, cause) return(symps) } .toBinary_file9_child <- function(symps_raw, symps, missLabel = NULL, adapt = FALSE, cause = NULL){ symps$c1_05 <- .toBinary_cutoff(symps_raw$c1_05, 21.4, missLabel, adapt, cause) symps$c1_08b <- .toBinary_cutoff(symps_raw$c1_08b, 2623, missLabel, adapt, cause) symps$c1_20 <- .toBinary_cutoff(symps_raw$c1_20, 1574.3, missLabel, adapt, cause) symps$c1_21 <- .toBinary_cutoff(symps_raw$c1_21, 63.4, missLabel, adapt, cause) symps$c1_25 <- .toBinary_cutoff(symps_raw$c1_25, 1618.6, missLabel, adapt, cause) symps$c4_02 <- .toBinary_cutoff(symps_raw$c4_02, 337.3, missLabel, adapt, cause) symps$c4_08 <- .toBinary_cutoff(symps_raw$c4_08, 99.9, missLabel, adapt, cause) symps$c4_10 <- .toBinary_cutoff(symps_raw$c4_10, 15.6, missLabel, adapt, cause) symps$c4_13 <- .toBinary_cutoff(symps_raw$c4_13, 5.7, missLabel, adapt, cause) symps$c4_17 <- .toBinary_cutoff(symps_raw$c4_17, 9.1, missLabel, adapt, cause) symps$c4_19 <- .toBinary_cutoff(symps_raw$c4_19, 1.5, missLabel, adapt, cause) symps$c4_33 <- .toBinary_cutoff(symps_raw$c4_33, 1.1, missLabel, adapt, cause) symps$c4_37 <- .toBinary_cutoff(symps_raw$c4_37, 2.2, missLabel, adapt, cause) symps$c4_49 <- .toBinary_cutoff(symps_raw$c4_49, .6, missLabel, adapt, cause) symps$g1_07a <- .toBinary_cutoff(symps_raw$g1_07a, 2.4, missLabel, adapt, cause) return(symps) } .toBinary_group <- function(vec, gtrue, gfalse, gna){ vec <- as.character(vec) for(i in gtrue){ vec[which(vec == i)] <- "YesYes" } for(i in gfalse){ vec[which(vec == i)] <- "NoNo" } for(i in gna){ vec[which(vec == i)] <- "MissingMissing" } return(vec) } .toBinary_group2 <- function(vec1, vec2, gtrue, gfalse, gna){ vec1 <- as.character(vec1) vec2 <- as.character(vec2) for(i in gtrue){ vec1[which(vec1 == i)] <- "YesYes" } for(i in gfalse){ vec1[which(vec1 == i)] <- "NoNo" } for(i in gna){ vec1[which(vec1 == i)] <- "MissingMissing" } for(i in gtrue){ vec1[which(vec2 == i)] <- "YesYes" } return(vec1) } .toBinary_file10 <- function(raw, new){ new$a2_19 <- .toBinary_group(raw$a2_19, c("Moderate", "Large"), c("Slight"), c("Don't Know")) new$a2_04 <- .toBinary_group(raw$a2_04, c("Moderate", "Severe"), c("Mild"), c("Don't Know")) new$a2_05 <- .toBinary_group(raw$a2_05, c("Continuous"), c("On and Off", "Only at Night"), c("Don't Know")) new$a2_05_s1 <- .toBinary_group(raw$a2_05, c("On and Off"), c("Continuous", "Only at Night"), c("Don't Know")) new$a2_09_1a <- .toBinary_group2(raw$a2_09_1a, raw$a2_09_2a, c("Face"), c("Trunk", "Extremities", "Everywhere", "Other"), c("Don't Know")) new$a2_09_1a_s1 <- .toBinary_group2(raw$a2_09_1a, raw$a2_09_2a, c("Trunk"), c("Face", "Extremities", "Everywhere", "Other"), c("Don't Know")) new$a2_09_1a_s2 <- .toBinary_group2(raw$a2_09_1a, raw$a2_09_2a, c("Extremities"), c("Trunk", "Face", "Everywhere", "Other"), c("Don't Know")) new$a2_09_1a_s3 <- .toBinary_group2(raw$a2_09_1a, raw$a2_09_2a, c("Everywhere"), c("Trunk", "Extremities", "Face", "Other"), c("Don't Know")) new$a2_09_1b <- .toBinary_group2(raw$a2_09_1a, raw$a2_09_2a, c("Other"), c("Trunk", "Extremities", "Face", "Everywhere"), c("Don't Know")) new <- new[, -which(colnames(new) == "a2_09_2a")] new <- new[, -which(colnames(new) == "a2_09_2b")] new$a2_39_1 <- .toBinary_group2(raw$a2_39_1, raw$a2_39_2, c("Lying"), c("Sitting", "Walking/Exertion", "Didn't matter"), c("Didn't matter", "Refused to Answer","Don't Know")) new$a2_39_1_s1 <- .toBinary_group2(raw$a2_39_1, raw$a2_39_2, c("Sitting"), c("Lying", "Walking/Exertion", "Didn't matter"), c("Didn't matter", "Refused to Answer","Don't Know")) new$a2_39_1_s2 <- .toBinary_group2(raw$a2_39_1, raw$a2_39_2, c("Walking/Exertion"), c("Sitting", "Lying", "Didn't matter"), c("Didn't matter", "Refused to Answer","Don't Know")) new$a2_39_1_s3 <- .toBinary_group2(raw$a2_39_1, raw$a2_39_2, c("Didn't matter"), c("Lying", "Sitting", "Walking/Exertion"), c("Refused to Answer","Don't Know")) new <- new[, -which(colnames(new) == "a2_39_2")] new$a2_38 <- .toBinary_group(raw$a2_38, c("Continuous"), c("On and Off" ), c("Don't Know")) new$a2_38_s1 <- .toBinary_group(raw$a2_38, c("On and Off"), c("Continuous" ), c("Don't Know")) new$a2_44 <- .toBinary_group(raw$a2_44, c(">24 hr" ), c("<30 minutes", "0.5-24 hours"), c("Don't Know", "Refused to Answer")) new$a2_46a <- .toBinary_group(raw$a2_46a, c("Upper/middle chest", "Lower chest" ), c("Left Arm", "Other" ), c("Don't Know", "Refused to Answer")) new$a2_46a_s1 <- .toBinary_group(raw$a2_46a, c("Left Arm" ), c("Upper/middle chest", "Lower chest", "Other"), c("Don't Know", "Refused to Answer")) new$a2_46b <- .toBinary_group(raw$a2_46a, c("Other" ), c("Left Arm", "Upper/middle chest", "Lower chest" ), c("Don't Know", "Refused to Answer")) new$a2_59 <- .toBinary_group(raw$a2_59, c("Both" ), c("Liquids", "Solids"), c("Don't Know", "Refused to Answer")) new$a2_63_1 <- .toBinary_group(raw$a2_63_1, c("Lower belly" ), c("Upper belly"), c("Don't Know", "Refused to Answer")) new$a2_63_2 <- .toBinary_group(raw$a2_63_2, c("Lower belly" ), c("Upper belly"), c("Don't Know", "Refused to Answer")) new$a2_71 <- .toBinary_group(raw$a2_71, c("Rapidly/Fast"), c("Slow(ly)"), c("Don't Know", "Refused to Answer")) new$a2_75 <- .toBinary_group(raw$a2_75, c("Suddenly"), c("Slowly"), c("Don't Know")) new$a2_80 <- .toBinary_group(raw$a2_80, c("Suddenly"), c("Slowly"), c("Don't Know")) new$a4_06 <- .toBinary_group(raw$a4_06, c("Moderate", "High"), c("Low"), c("Don't Know", "Refused to Answer")) new$a4_06_s1 <- .toBinary_group(raw$a4_06, c("Low"), c("Moderate", "High"), c("Don't Know", "Refused to Answer")) return(new[, order(colnames(new))]) } .toBinary_file10_child <- function(raw, new){ new$c1_01 <- .toBinary_group(raw$c1_01, c("Multiple"), c("Singleton"), c("Don't Know", "")) new$c1_02 <- .toBinary_group(raw$c1_02, c("Second", "Third or More"), c("First"), c("Don't Know")) new$c1_04 <- .toBinary_group(raw$c1_04, c("After"), c("During"), c("Don't Know")) new$c1_06a <- .toBinary_group(raw$c1_06a, c("Home", "Other"), c("Hospital", "On Route to Health Facility", "Other Health Facility"), c("Don't Know")) new$c1_07 <- .toBinary_group(raw$c1_07, c("Very small", "smaller than usual"), c("About average", "larger than usual"), c("Don't Know", "")) new$c1_22a <- .toBinary_group(raw$c1_22a, c("Home", "On Route to Health Facility"), c("Hospital", "Other", "Other Health Facility"), c("Don't Know")) new$c4_04 <- .toBinary_group(raw$c4_04, c("Severe"), c("Mild", "Moderate"), c("Don't Know")) new$c4_05 <- .toBinary_group(raw$c4_05, c("On and Off", "Only at Night"), c("Continuous"), c("Don't Know")) new$c4_07b <- .toBinary_group(raw$c4_07b, 2:30, 0:1, NA) new$c4_31_1 <- .toBinary_group(raw$c4_31_1, c("Face"), c("Everywhere", "Extremities", "Other", "Trunk"), c("Don't Know")) new$c4_32 <- .toBinary_group(raw$c4_32, c("Face"), c("Everywhere", "Extremities", "Other", "Trunk"), c("Don't Know")) return(new[, order(colnames(new))]) } .toBinary_unhandeled <- function(raw, new){ new$a2_66 <- .toBinary_group(raw$a2_66, c("Rapidly/Fast"), c("Slow(ly)"), c("Don't Know")) new <- new[, -which(colnames(new) == "a2_87_10b")] new <- new[, -which(colnames(new) == "a3_11")] new <- new[, -which(colnames(new) == "a3_16")] new <- new[, -which(colnames(new) == "a4_02_5b")] new$g1_05 <- .toBinary_group(raw$g1_05 , c("Female"), c("Male" ), c("Don't Know", "")) new$g1_05_s1 <- .toBinary_group(raw$g1_05 , c("Male"), c("Female" ), c("Don't Know", "")) return(new[, order(colnames(new))]) } .toBinary_unhandeled_child <- function(raw, new){ cols.to.remove <- c("c1_08a", "c1_10", "c1_11", "c1_10d", "c1_10m", "c1_10y", "c1_194b", "c1_24", paste0("c1_24", c("d", "m", "y")), "c1_26", "c4_07a", "c4_31_2", "c4_45", "c4_47_8b", paste0("c5_06_1", c("d", "m", "y")), paste0("c5_06_2", c("d", "m", "y")), "c5_07_1", "c5_07_2", paste0("c5_08", c("d", "m", "y"))) new <- new[, -which(colnames(new) %in% cols.to.remove)] new$c4_27 <- .toBinary_group(raw$c4_27, c("<6 hours"), c("24 hours or more", "6-23 hours"), c("Don't Know")) new$g1_05 <- .toBinary_group(raw$g1_05 , c("Female"), c("Male" ), c("Don't Know", "")) new$g1_05_s1 <- .toBinary_group(raw$g1_05 , c("Male"), c("Female" ), c("Don't Know", "")) return(new[, order(colnames(new))]) }
rotonmat <- function(X,refmat,tarmat,scale=TRUE,reflection=FALSE, weights=NULL, centerweight=FALSE,getTrafo=FALSE) { ro <- rotonto(tarmat,refmat,scale=scale,signref=F,reflection=reflection, weights=weights, centerweight=centerweight) hmat <- getTrafo4x4(ro) Xrot <- homg2mat(hmat%*%mat2homg(X)) if (!getTrafo) return(Xrot) else return(list(Xrot=Xrot,trafo=hmat)) }
checkSPC <- function(x) { sn <- slotNames(x) s.test <- sapply(sn, function(i) .hasSlot(x, name=i)) res <- FALSE if(all(s.test)) { res <- TRUE } return(res) }
rectint <- function(x, y) { stopifnot(is.numeric(x), is.numeric(y)) if (is.vector(x) && length(x) == 4 && is.vector(y) && length(y) == 4) { if (any(c(x[3], x[4], y[3], y[4]) < 0)) stop("All widths and heights must be greater than 0.") if (x[1]+x[3] <= y[1] || y[1]+y[3] <= x[1] || x[2]+x[4] <= y[2] || y[2]+y[4] <= x[2]) { return(0) } else { if (x[1] > y[1]) { tmp <- x; x <- y; y <- tmp } z1 <- y[1] z2 <- max(x[2], y[2]) z3 <- min(x[1]+x[3], y[1]+y[3]) z4 <- min(x[2]+x[4], y[2]+y[4]) area <- (z3-z1) * (z4-z2) return(area) } } else if (is.matrix(x) && ncol(x) == 4 && is.matrix(y) && ncol(y) == 4) { nx <- nrow(x); ny <- nrow(y) R <- matrix(NA, nrow = nx, ncol = ny) for (i in 1:nx) { for (j in 1:ny) { R[i, j] <- rectint(x[i, ], y[j, ]) } } return(R) } else { stop("All lengths and no. of matrix columns must be equal to 4.") } }
qat_analyse_roc_rule_dynamic_1d <- function(measurement_vector, max_upward_vector=NULL, max_downward_vector=NULL, upward_vector_name=NULL, downward_vector_name=NULL, upward_vector_identifier=NULL, downward_vector_identifier=NULL) { flagvector <- array(0.0, length(measurement_vector)) if(length(measurement_vector) != length(max_downward_vector)) { max_downward_vector <- array(NaN, length(measurement_vector)) } if(length(measurement_vector) != length(max_upward_vector)) { max_upward_vector <- array(NaN, length(measurement_vector)) } for (ii in 2:length(measurement_vector)) { if (!is.na(measurement_vector[ii]) && !is.na(measurement_vector[ii-1])) { if (!is.na(max_upward_vector[ii])) { if ((measurement_vector[ii]-measurement_vector[ii-1]) > max_upward_vector[ii]) { flagvector[ii] <- 1 } } if (!is.na(max_downward_vector[ii])) { if ((measurement_vector[ii]-measurement_vector[ii-1]) < (-1.* max_downward_vector[ii])) { flagvector[ii] <- -1 } } } } resultlist<- c(list(flagvector), list(max_upward_vector), list(max_downward_vector), list(upward_vector_name), list(downward_vector_name), list(upward_vector_identifier), list(downward_vector_identifier)) names(resultlist)<-c("flagvector", "max_upward_vector", "max_downward_vector", "upward_vector_name", "downward_vector_name", "upward_vector_identifier", "downward_vector_identifier") return(resultlist) }
limer_get_participant_property <- function(iSurveyID, aTokenQueryProperties, aTokenProperties) { params <- as.list(environment()) result <- limer_call_limer(method = "get_participant_properties", params = params) return(result) }
diff_abundance <- function(...) { lifecycle::deprecate_warn("0.2.0", "diff_abundance()", "calculate_diff_abundance()", details = "This function has been renamed." ) calculate_diff_abundance(...) } calculate_diff_abundance <- function(data, sample, condition, grouping, intensity_log2, missingness = missingness, comparison = comparison, mean = NULL, sd = NULL, n_samples = NULL, ref_condition = "all", filter_NA_missingness = TRUE, method = c("moderated_t-test", "t-test", "t-test_mean_sd", "proDA"), p_adj_method = "BH", retain_columns = NULL) { . <- NULL if (!(ref_condition %in% unique(pull(data, {{ condition }}))) & ref_condition != "all") { stop(strwrap("The name provided to ref_condition cannot be found in your conditions! Please provide a valid reference condition.", prefix = "\n", initial = "")) } method <- match.arg(method) if (method != "t-test_mean_sd") { if (max(pull(data, {{ intensity_log2 }}), na.rm = TRUE) > 1000) { stop("Please log2 transform your intensities.") } } if (method == "t-test_mean_sd") { if (max(pull(data, {{ mean }}), na.rm = TRUE) > 1000) { stop("Please log2 transform your data.") } } if (method == "t-test") { message("[1/2] Create input for t-tests ... ", appendLF = FALSE) t_test_missingness_obs <- data %>% tidyr::drop_na({{ missingness }}, {{ intensity_log2 }}) %>% dplyr::group_by({{ comparison }}, {{ grouping }}) %>% dplyr::mutate(n_obs = dplyr::n()) %>% dplyr::ungroup() %>% dplyr::distinct({{ grouping }}, {{ comparison }}, {{ missingness }}, .data$n_obs) t_test_input <- data %>% tidyr::drop_na({{ intensity_log2 }}) %>% dplyr::group_by({{ comparison }}, {{ grouping }}, {{ condition }}) %>% dplyr::summarize(intensity = list({{ intensity_log2 }}), .groups = "drop") %>% dplyr::mutate(type = ifelse({{ condition }} == stringr::str_extract({{ comparison }}, pattern = "(?<=_vs_).+"), "control", "treated" )) %>% dplyr::select(-{{ condition }}) %>% tidyr::pivot_wider(names_from = .data$type, values_from = .data$intensity, values_fill = list(NA)) message("DONE", appendLF = TRUE) message("[2/2] Calculate t-tests ... ", appendLF = FALSE) t_test_result <- t_test_input %>% dplyr::mutate(pval = purrr::map2( .x = .data$treated, .y = .data$control, .f = function(.x, .y) { tryCatch( { suppressWarnings(stats::t.test(.x, .y)) }, error = function(error) { NA } ) } )) %>% dplyr::mutate(std_error = purrr::map_dbl( .x = .data$pval, .f = ~ tryCatch( { .x$stderr }, error = function(error) { NA } ) )) %>% dplyr::mutate(pval = purrr::map_dbl( .x = .data$pval, .f = ~ tryCatch( { .x$p.value }, error = function(error) { NA } ) )) %>% dplyr::mutate(diff = map2_dbl( .x = .data$treated, .y = .data$control, .f = function(.x, .y) { suppressWarnings(mean(.x, na.rm = TRUE)) - suppressWarnings(mean(.y, na.rm = TRUE)) } )) %>% dplyr::mutate(diff = ifelse(diff == "NaN", NA, diff)) %>% dplyr::group_by({{ comparison }}) %>% dplyr::mutate(adj_pval = stats::p.adjust(.data$pval, method = p_adj_method)) %>% dplyr::ungroup() %>% dplyr::select(-c(.data$control, .data$treated)) %>% dplyr::left_join(t_test_missingness_obs, by = c(rlang::as_name(rlang::enquo(grouping)), "comparison")) %>% dplyr::arrange(.data$adj_pval, .data$pval) message("DONE", appendLF = TRUE) if (!missing(retain_columns)) { t_test_result <- data %>% dplyr::ungroup() %>% dplyr::select( !!enquo(retain_columns), {{ intensity_log2 }}, colnames(t_test_result)[!colnames(t_test_result) %in% c( "pval", "std_error", "diff", "adj_pval", "n_obs" )] ) %>% tidyr::drop_na({{ intensity_log2 }}) %>% dplyr::select(-{{ intensity_log2 }}) %>% dplyr::distinct() %>% dplyr::right_join(t_test_result, by = colnames(t_test_result)[!colnames(t_test_result) %in% c( "pval", "std_error", "diff", "adj_pval", "n_obs" )]) %>% dplyr::arrange(.data$adj_pval, .data$pval) } if (filter_NA_missingness == TRUE) { t_test_result <- t_test_result %>% tidyr::drop_na({{ missingness }}) %>% dplyr::group_by({{ comparison }}) %>% dplyr::mutate(adj_pval = stats::p.adjust(.data$pval, method = p_adj_method)) %>% dplyr::ungroup() %>% dplyr::arrange(.data$adj_pval, .data$pval) return(t_test_result) } if (filter_NA_missingness == FALSE) { return(t_test_result) } } if (method == "t-test_mean_sd") { if (ref_condition == "all") { all_conditions <- unique(dplyr::pull(data, {{ condition }})) all_combinations <- tibble::as_tibble(t(combn(all_conditions, m = 2))) %>% dplyr::mutate(combinations = paste0(.data$V1, "_vs_", .data$V2)) message( strwrap("All pairwise comparisons are created from all conditions and their missingness type is assigned.\n The created comparisons are: \n", prefix = "\n", initial = ""), paste(all_combinations$combinations, collapse = "\n") ) } if (ref_condition != "all") { conditions_no_ref <- unique(dplyr::pull(data, !!ensym(condition)))[!unique(pull(data, !!ensym(condition))) %in% ref_condition] all_combinations <- tibble::tibble(V1 = conditions_no_ref, V2 = ref_condition) %>% dplyr::mutate(combinations = paste0(.data$V1, "_vs_", .data$V2)) } all_combinations <- all_combinations %>% tidyr::pivot_longer(cols = c(.data$V1, .data$V2), names_to = "name", values_to = rlang::as_name(rlang::enquo(condition))) %>% dplyr::select(-.data$name) %>% dplyr::group_by({{ condition }}) %>% dplyr::mutate(comparison = list(.data$combinations)) %>% dplyr::distinct(.data$comparison, {{ condition }}) t_test_mean_sd_result <- data %>% dplyr::ungroup() %>% dplyr::distinct({{ condition }}, {{ grouping }}, {{ mean }}, {{ sd }}, {{ n_samples }}) %>% tidyr::drop_na() %>% dplyr::left_join(all_combinations, by = rlang::as_name(rlang::enquo(condition))) %>% tidyr::unnest(.data$comparison) %>% dplyr::rename(mean = {{ mean }}, sd = {{ sd }}, n = {{ n_samples }}) %>% dplyr::mutate({{ condition }} := ifelse({{ condition }} == stringr::str_extract(.data$comparison, pattern = "(?<=_vs_).+"), "control", "treated" )) %>% tidyr::pivot_wider(names_from = {{ condition }}, values_from = c(.data$mean, .data$sd, .data$n)) %>% dplyr::mutate(ttest_protti( mean1 = .data$mean_control, mean2 = .data$mean_treated, sd1 = .data$sd_control, sd2 = .data$sd_treated, n1 = .data$n_control, n2 = .data$n_treated )) %>% tidyr::drop_na(.data$pval) %>% dplyr::group_by(.data$comparison) %>% dplyr::mutate(adj_pval = stats::p.adjust(.data$pval, method = p_adj_method)) %>% dplyr::arrange(.data$adj_pval, .data$pval) if (!missing(retain_columns)) { t_test_mean_sd_result <- data %>% dplyr::ungroup() %>% dplyr::select(!!enquo(retain_columns), colnames(t_test_mean_sd_result)[!colnames(t_test_mean_sd_result) %in% c( "mean_control", "mean_treated", "sd_control", "sd_treated", "n_control", "n_treated", "pval", "std_error", "diff", "adj_pval", "t_statistic", "comparison" )]) %>% dplyr::distinct() %>% dplyr::right_join(t_test_mean_sd_result, by = colnames(t_test_mean_sd_result)[!colnames(t_test_mean_sd_result) %in% c( "mean_control", "mean_treated", "sd_control", "sd_treated", "n_control", "n_treated", "pval", "std_error", "diff", "adj_pval", "t_statistic", "comparison" )]) %>% dplyr::arrange(.data$adj_pval, .data$pval) } return(t_test_mean_sd_result) } if (method == "moderated_t-test") { if (!requireNamespace("limma", quietly = TRUE)) { stop("Package \"limma\" is needed for this function to work. Please install it.", call. = FALSE) } conditions_no_ref <- unique(pull(data, {{ condition }}))[!unique(pull(data, {{ condition }})) %in% ref_condition] message("[1/7] Creating moderated t-test input data ... ", appendLF = FALSE) moderated_t_test_input <- data %>% dplyr::distinct({{ grouping }}, {{ sample }}, {{ intensity_log2 }}) %>% tidyr::drop_na({{ intensity_log2 }}) %>% dplyr::arrange({{ sample }}) %>% tidyr::pivot_wider(names_from = {{ sample }}, values_from = {{ intensity_log2 }}) %>% tibble::column_to_rownames(var = rlang::as_name(rlang::enquo(grouping))) %>% as.matrix() message("DONE", appendLF = TRUE) message("[2/7] Defining moderated t-test design ... ", appendLF = FALSE) moderated_t_test_map <- data %>% dplyr::distinct({{ sample }}, {{ condition }}) %>% dplyr::mutate({{ condition }} := paste0("x", {{ condition }})) %>% dplyr::arrange({{ sample }}) moderated_t_test_design <- stats::model.matrix(~ 0 + factor( stringr::str_replace_all( dplyr::pull(moderated_t_test_map, {{ condition }}), pattern = " ", replacement = "_" ) )) colnames(moderated_t_test_design) <- levels(factor( stringr::str_replace_all( dplyr::pull( moderated_t_test_map, {{ condition }} ), pattern = " ", replacement = "_" ) )) message("DONE", appendLF = TRUE) message("[3/7] Fitting lmFit model ... ", appendLF = FALSE) moderated_t_test_fit <- suppressWarnings(limma::lmFit(moderated_t_test_input, moderated_t_test_design)) message("DONE", appendLF = TRUE) message("[4/7] Construct matrix of custom contrasts ... ", appendLF = FALSE) names <- paste0( "x", stringr::str_extract(unique(dplyr::pull(data, {{ comparison }})), pattern = ".+(?=_vs_)"), "_vs_x", stringr::str_extract(unique(dplyr::pull(data, {{ comparison }})), pattern = "(?<=_vs_).+") ) comparisons <- paste0( "x", stringr::str_extract( stringr::str_replace_all( unique(dplyr::pull( data, {{ comparison }} )), pattern = " ", replacement = "_" ), pattern = ".+(?=_vs_)" ), "-x", stringr::str_extract( stringr::str_replace_all( unique(dplyr::pull( data, {{ comparison }} )), pattern = " ", replacement = "_" ), pattern = "(?<=_vs_).+" ) ) combinations <- purrr::map2( .x = names, .y = comparisons, .f = function(x, y) { rlang::exprs(!!rlang::as_name(x) := !!y) } ) contrast_matrix <- eval(rlang::expr(limma::makeContrasts(!!!unlist(combinations), levels = moderated_t_test_design))) message("DONE", appendLF = TRUE) message("[5/7] Compute contrasts from linear model fit ... ", appendLF = FALSE) moderated_t_test_fit2 <- limma::contrasts.fit(moderated_t_test_fit, contrast_matrix) message("DONE", appendLF = TRUE) message("[6/7] Compute empirical Bayes statistics ... ", appendLF = FALSE) moderated_t_test_fit3 <- limma::eBayes(moderated_t_test_fit2) message("DONE", appendLF = TRUE) message("[7/7] Create result table ... ", appendLF = FALSE) moderated_t_test_missingness <- data %>% tidyr::drop_na({{ missingness }}, {{ intensity_log2 }}) %>% dplyr::group_by({{ comparison }}, {{ grouping }}) %>% dplyr::mutate(n_obs = dplyr::n()) %>% dplyr::ungroup() %>% dplyr::distinct({{ grouping }}, {{ comparison }}, {{ missingness }}, .data$n_obs) moderated_t_test_result <- purrr::map_dfr( .x = names, .f = ~ limma::topTable(moderated_t_test_fit3, coef = .x, number = Inf, confint = TRUE, sort.by = "p", adjust.method = p_adj_method ) %>% tibble::rownames_to_column(rlang::as_name(rlang::enquo(grouping))) %>% dplyr::mutate(comparison = .x) ) %>% dplyr::mutate(comparison = stringr::str_replace_all({{ comparison }}, pattern = "^x|(?<=_vs_)x", replacement = "")) %>% dplyr::rename( diff = .data$logFC, CI_2.5 = .data$CI.L, CI_97.5 = .data$CI.R, t_statistic = .data$t, avg_abundance = .data$AveExpr, pval = .data$P.Value, adj_pval = .data$adj.P.Val ) %>% dplyr::left_join(moderated_t_test_missingness, by = c(rlang::as_name(rlang::enquo(grouping)), "comparison")) message("DONE", appendLF = TRUE) if (!missing(retain_columns)) { moderated_t_test_result <- data %>% dplyr::ungroup() %>% dplyr::select( !!enquo(retain_columns), {{ intensity_log2 }}, colnames(moderated_t_test_result)[!colnames(moderated_t_test_result) %in% c( "CI_2.5", "CI_97.5", "avg_abundance", "pval", "diff", "adj_pval", "t_statistic", "B", "n_obs" )] ) %>% tidyr::drop_na({{ intensity_log2 }}) %>% dplyr::select(-{{ intensity_log2 }}) %>% dplyr::distinct() %>% dplyr::right_join(moderated_t_test_result, by = colnames(moderated_t_test_result)[!colnames(moderated_t_test_result) %in% c( "CI_2.5", "CI_97.5", "avg_abundance", "pval", "diff", "adj_pval", "t_statistic", "B", "n_obs" )]) %>% dplyr::arrange(.data$adj_pval, .data$pval) } if (filter_NA_missingness == TRUE) { moderated_t_test_result <- moderated_t_test_result %>% tidyr::drop_na({{ missingness }}) %>% dplyr::group_by(.data$comparison) %>% dplyr::mutate(adj_pval = stats::p.adjust(.data$pval, method = p_adj_method)) %>% dplyr::ungroup() %>% dplyr::arrange(.data$adj_pval, .data$pval) return(moderated_t_test_result) } if (filter_NA_missingness == FALSE) { return(moderated_t_test_result) } } if (method == "proDA") { if (!requireNamespace("proDA", quietly = TRUE)) { stop("Package \"proDA\" is needed for this function to work. Please install it.", call. = FALSE) } message("[1/5] Creating proDA input data ... ", appendLF = FALSE) proDA_input <- data %>% dplyr::distinct({{ grouping }}, {{ sample }}, {{ intensity_log2 }}) %>% dplyr::arrange({{ sample }}) %>% tidyr::pivot_wider(names_from = {{ sample }}, values_from = {{ intensity_log2 }}) %>% tibble::column_to_rownames(var = rlang::as_name(rlang::enquo(grouping))) %>% as.matrix() message("DONE", appendLF = TRUE) message("[2/5] Defining proDA design ... ", appendLF = FALSE) proDA_map <- data %>% dplyr::distinct({{ sample }}, {{ condition }}) %>% dplyr::arrange({{ sample }}) proDA_design <- paste0("x", stringr::str_replace_all(dplyr::pull(proDA_map, {{ condition }}), pattern = " ", replacement = "_")) message("DONE", appendLF = TRUE) message("[3/5] Fitting proDA model (can take a few minutes) ... ", appendLF = FALSE) proDA_fit <- proDA::proDA(proDA_input, design = proDA_design ) message("DONE", appendLF = TRUE) message("[4/5] Define missingness levels for filtering ... ", appendLF = FALSE) proDA_missingness <- data %>% tidyr::drop_na({{ missingness }}, {{ intensity_log2 }}) %>% dplyr::group_by({{ comparison }}, {{ grouping }}) %>% dplyr::mutate(n_obs = dplyr::n()) %>% dplyr::ungroup() %>% dplyr::distinct({{ grouping }}, {{ comparison }}, {{ missingness }}, .data$n_obs) proDA_filter <- proDA_missingness %>% dplyr::distinct({{ grouping }}, {{ comparison }}) %>% split(.$comparison) %>% purrr::map(dplyr::select, -{{ comparison }}) message("DONE", appendLF = TRUE) message("[5/5] Extracting differential abundance from model and apply filter ... ", appendLF = FALSE) names <- unique(dplyr::pull(data, {{ comparison }})) comparisons <- paste0( "x", stringr::str_extract( stringr::str_replace_all( unique(dplyr::pull( data, {{ comparison }} )), pattern = " ", replacement = "_" ), pattern = ".+(?=_vs_)" ), " - x", stringr::str_extract( stringr::str_replace_all( unique(dplyr::pull( data, {{ comparison }} )), pattern = " ", replacement = "_" ), pattern = "(?<=_vs_).+" ) ) proDA_result <- names %>% purrr::map(~proDA_fit) %>% purrr::set_names(nm = names) %>% purrr::map2( .y = comparisons, .f = ~ proDA::test_diff(.x, contrast = .y, sort_by = "adj_pval") ) if (filter_NA_missingness == TRUE) { proDA_result <- proDA_result %>% purrr::map2( .y = proDA_filter, .f = ~ dplyr::inner_join(.x, .y, by = c("name" = as_label(enquo(grouping)))) ) %>% purrr::map2( .y = names(.), .f = ~ dplyr::mutate(.x, comparison = str_replace_all(.y, pattern = "`", replacement = "")) ) %>% purrr::map_dfr(~ dplyr::mutate(.x, adj_pval = p.adjust(.data$pval, method = p_adj_method))) %>% dplyr::select(-.data$n_obs, -.data$n_approx) %>% dplyr::rename({{ grouping }} := .data$name, std_error = .data$se) %>% dplyr::left_join(proDA_missingness, by = c(rlang::as_name(rlang::enquo(grouping)), "comparison")) message("DONE", appendLF = TRUE) } if (filter_NA_missingness == FALSE) { proDA_result <- proDA_result %>% purrr::map2( .y = names(.), .f = ~ dplyr::mutate(.x, comparison = str_replace_all(.y, pattern = "`", replacement = "")) ) %>% purrr::map_dfr(~ dplyr::mutate(.x, adj_pval = p.adjust(.data$pval, method = p_adj_method))) %>% dplyr::select(-.data$n_obs) %>% dplyr::select(-.data$n_obs, -.data$n_approx) %>% dplyr::rename({{ grouping }} := .data$name, std_error = .data$se) %>% dplyr::left_join(proDA_missingness, by = c(rlang::as_name(rlang::enquo(grouping)), "comparison")) message("DONE", appendLF = TRUE) } if (!missing(retain_columns)) { proDA_result <- data %>% dplyr::ungroup() %>% dplyr::select( !!enquo(retain_columns), {{ intensity_log2 }}, colnames(proDA_result)[!colnames(proDA_result) %in% c( "std_error", "avg_abundance", "pval", "diff", "adj_pval", "t_statistic", "df", "n_obs" )] ) %>% tidyr::drop_na({{ intensity_log2 }}) %>% dplyr::select(-{{ intensity_log2 }}) %>% dplyr::distinct() %>% dplyr::right_join(proDA_result, by = colnames(proDA_result)[!colnames(proDA_result) %in% c( "std_error", "avg_abundance", "pval", "diff", "adj_pval", "t_statistic", "df", "n_obs" )]) %>% dplyr::arrange(.data$adj_pval, .data$pval) } return(proDA_result) } }
update.Rout <- FALSE SEED <- 123456 mkmsg.e <- function(...) { makemsg.e("unuran\\.details",...) } context("[details] - print 'Runuran' objects") test_unuran.details <- function(distr, method, name=toupper(method), skip.on.cran=TRUE) { set.seed(SEED) unr <- unuran.new(distr, method) test_that(paste0("[details-",name,"]"), { if (isTRUE(skip.on.cran)) { skip_on_cran() } expect_known_output( { print(unuran.details(unr,show=TRUE, return.list=FALSE)) print(unuran.details(unr,show=FALSE,return.list=TRUE)) print(unuran.details(unr,show=FALSE,debug=TRUE)) }, file=file.path("saves", paste0(name,".Rout")), update=update.Rout) }) } test_unuran.details("binomial(20,0.5)", "dari") test_unuran.details("binomial(20,0.5)", "dau") test_unuran.details("binomial(20,0.5)", "dgt") test_unuran.details("binomial(20,0.5)", "dsrou") test_unuran.details("binomial(20,0.5)", "dss") test_unuran.details("binomial(20,0.5)", "dstd") test_unuran.details("normal(1,2)", "arou") test_unuran.details("normal(1,2)", "ars") test_unuran.details("normal(1,2)", "cstd") test_unuran.details("normal(1,2)", "hinv", skip.on.cran=TRUE) test_unuran.details("gamma(0.5)", "itdr") test_unuran.details("normal(1,2)", "ninv") test_unuran.details("normal(1,2)", "nrou") test_unuran.details("normal(1,2)", "pinv", skip.on.cran=TRUE) test_unuran.details("normal(1,2)", "srou") test_unuran.details("normal(1,2)", "ssr") test_unuran.details("normal(1,2)", "tabl") test_unuran.details("normal(1,2)", "tdr") test_unuran.details("normal(1,2)", "utdr") context("[details] - Invalid arguments") test_that("[details-i01] calling unuran.details with invalid arguments", { msg <- mkmsg.e("Argument 'unr' must be of class 'unuran'") expect_error( unuran.details(1), msg) })
print.animint <- function(x, ...){ if(is.null(x$out.dir)){ message('Saving animint in temporary directory; specify output directory using animint(out.dir="path/to/directory")') } animint2dir(x, x$out.dir, ...) } animint <- function(...){ L <- list(...) default.name.vec <- plot.num.vec <- paste0("plot", seq_along(L)) match.name.list <- lapply(match.call()[-1], paste) first.name.vec <- sapply(match.name.list, "[", 1) sub.name.vec <- gsub("[^a-zA-Z0-9]", "", first.name.vec) name.ok <- grepl("^[a-zA-Z][a-zA-Z0-9]*$", sub.name.vec) use.name <- sapply(match.name.list, length)==1 & name.ok default.name.vec[use.name] <- sub.name.vec[use.name] if(is.null(names(L))){ names(L) <- default.name.vec } still.empty <- names(L)=="" names(L)[still.empty] <- default.name.vec[still.empty] name.tab <- table(names(L)) is.rep <- names(L) %in% names(name.tab)[1 < name.tab] names(L)[is.rep] <- plot.num.vec[is.rep] structure(L, class="animint") }
Utilities3 <- Utilities %>% filter(year > 2000 | month > 6) ut.lm3 <- lm(thermsPerDay ~ month + I(month^2), data = Utilities3) msummary(ut.lm3) fit3 <- makeFun(ut.lm3) gf_point(thermsPerDay ~ month, data = Utilities3) %>% gf_function(fit3, color = "red", alpha = 0.6) ut.lm3 %>% Effect("month", ., partial.residuals = TRUE) %>% plot("month") plot(ut.lm3, w = 1:2)
build.dist.struct <- function(z, X, exact = NULL, calip.option = 'propensity', calip.cov = NULL, caliper = 0.2, verbose = FALSE){ cal.penalty <- 100 if(is.null(exact)) exact = rep(1, length(z)) if(!(calip.option %in% c('propensity','user','none'))){ stop('Invalid calip.option specified.') } if (is.vector(X)) X <- matrix(X, length(X), 1) if(!(length(z) == (dim(X)[1]))){ stop("Length of z does not match row count in X") } if(!(length(exact) == length(z))){ stop("Length of exact does not match length of z") } if(!(all((z == 1) | (z == 0)))){ stop("The z argument must contain only 1s and 0s") } if(is.data.frame(X) || is.character(X)){ if(!is.data.frame(X)) X <- as.data.frame(X) X.chars <- which(laply(X, function(y) 'character' %in% class(y))) if(length(X.chars) > 0){ if (verbose) print('Character variables found in X, converting to factors.') for(i in X.chars){ X[,i] <- factor(X[,i]) } } X.factors <- which(laply(X, function(y) 'factor' %in% class(y))) for(i in which(laply(X, function(x) any(is.na(x))))){ if (verbose) print(paste('Missing values found in column', i ,'of X; imputing and adding missingness indicators')) if(i %in% X.factors){ X[,i] <- addNA(X[,i]) }else{ X[[paste(colnames(X)[i],'NA', sep = '')]] <- is.na(X[,i]) X[which(is.na(X[,i])),i] <- mean(X[,i], na.rm = TRUE) } } for(i in rev(X.factors)){ dummyXi <- model.matrix(as.formula( paste('~',colnames(X)[i], '-1')),data=X) X <- cbind(X[,-i], dummyXi) } }else{ for(i in c(1:ncol(X))){ if(any(is.na(X[,i]))){ X <- cbind(X,is.na(X[,i])) colnames(X)[ncol(X)] <- paste(colnames(X)[i],'NA', sep = '') X[which(is.na(X[,i])),i] <- mean(X[,i], na.rm = TRUE) } } } varying <- apply(X,2, function(x) length(unique(x)) > 1) if(!all(varying) && verbose) print('Constant-value columns found in X, they will not be used to calculate Mahalanobis distance.') X <- X[,which(varying),drop = FALSE] if (calip.option == 'propensity') { calip.cov <- glm.fit(cbind(rep(1, nrow(X)),X), z, family = binomial())$linear.predictors cal <- sd(calip.cov) * caliper }else if(calip.option == 'user'){ stopifnot(!is.null(calip.cov)) cal <- sd(calip.cov) * caliper } nobs <- length(z) rX <- as.matrix(X) for (j in 1:(dim(rX)[2])) rX[, j] <- rank(rX[, j]) cv <- cov(rX) vuntied <- var(1:nobs) rat <- sqrt(vuntied/diag(cv)) if(length(rat) == 1){ cv <- as.matrix(rat) %*% cv %*% as.matrix(rat) }else{ cv <- diag(rat) %*% cv %*% diag(rat) } icov <- ginv(cv) nums <- 1:nobs ctrl.nums <- 1:(sum(z == 0)) treated <- nums[z == 1] dist.struct <- list() for (i in c(1:length(treated))) { controls <- nums[(z == 0) & (exact == exact[treated[i]])] control.names <- ctrl.nums[exact[z == 0] == exact[treated[i]]] costi <- mahalanobis(rX[controls, ,drop=FALSE], rX[treated[i], ], icov, inverted = T) if (calip.option != 'none') { calip.update <- rep(0, length(costi)) calip.update[abs(calip.cov[treated[i]] - calip.cov[controls]) - cal > 0] <- Inf costi <- costi + calip.update } names(costi) <- control.names dist.struct[[i]] <- costi[is.finite(costi)] } if (sum(laply(dist.struct, length)) == 0) stop('All matches forbidden. Considering using a wider caliper?') return(dist.struct) }
set.branch.mode <- function(lprec, columns, modes) { if(length(columns) != length(modes)) stop(sQuote("columns"), " and ", sQuote("modes"), " must be the same length") if(is.character(modes)) { modes <- pmatch(modes, c("ceiling", "floor", "auto", "default"), nomatch = NA) if(any(is.na(modes))) stop("invalid mode") else modes <- modes - 1 } .Call(RlpSolve_set_var_branch, lprec, as.integer(columns), as.integer(modes)) invisible() }
forest_plot = function(coef, se, sort = TRUE, exp = FALSE) { if(is.null(rownames(coef))) rownames(coef) = paste0('SNP', 1:nrow(coef)) if(is.null(colnames(coef))) colnames(coef) = paste0('Study', 1:ncol(coef)) if(sort) { means = rowMeans(coef) coef = coef[order(means),] se = se[order(means),] } lower = coef - qnorm(.975)*se upper = coef + qnorm(.975)*se snp = rownames(coef) study = colnames(coef) d3 = cbind(as.vector(t(coef)), as.vector(t(lower)), as.vector(t(upper))) if(exp) d3 = exp(d3) colnames(d3) = c('coef', 'lower', 'upper') rownames(d3) = rep(snp, rep(length(study), length(snp))) clrs = fpColors(box="black", lines="black", summary="black") tabletext =list(rep(snp, rep(length(study), length(snp))), rep(study, length(snp))) hrzl_lines = vector('list', nrow(coef) - 1) for(i in 1:(nrow(coef) - 1)) hrzl_lines[[i]] = gpar(lty=2) names(hrzl_lines) = as.character((1:(nrow(coef) - 1)) * length(study) + 1) forestplot(tabletext, hrzl_lines = hrzl_lines, d3, ol = clrs, zero = ifelse(exp, 1, 0), xlab="GxE effect size") }
.addAxis <- function(xlim, ylim, tckLab, tck, tckMinor, ...) { tckLab <- rep(tckLab, length.out = 2); tck <- rep(tck, length.out = 2); tckMinor <- rep(tckMinor, length.out = 2); mai <- par()$mai; par(cex = par()$cex * 0.8); par(mai = mai); par(mex = par()$cex); lim <- list(xlim, ylim); rotate <- list(0, 90) for (i in 1:2) { if (((i == 1) && (par()$xaxt != "n")) || ((i == 2) && (par()$yaxt != "n"))) { ticks <- pretty(lim[[i]]); ticksMinor <- pretty(c(0, diff(ticks)[1])); ticksMinor <- (sort(rep(ticks, length(ticksMinor))) + rep(ticksMinor, length(ticks))); ticks <- ticks[ticks > lim[[i]][1] & ticks < lim[[i]][2]]; ticksMinor <- ticksMinor[ticksMinor > lim[[i]][1] & ticksMinor < lim[[i]][2]]; if (!tckLab[i]) { tickLabels <- FALSE; } else { tickLabels <- as.character(ticks); } axis(side = i, at = ticks, labels = tickLabels, tck = tck[i], srt = rotate[[i]]); axis(side = i, at = ticksMinor, labels = FALSE, tck = tckMinor[i]); } } invisible(NULL); } .addAxis2 <- function (side=1:2, xlim, ylim, tckLab, tck, tckMinor, ...) { tckLab <- rep(tckLab, length.out = 4) tck <- rep(tck, length.out = 4) tckMinor <- rep(tckMinor, length.out = 4) mai <- par()$mai lim <- list(xlim,ylim,xlim,ylim) rotate <- list(0,90,0,90) for (i in side) { if (((i %in% c(1,3)) && (par()$xaxt != "n")) || ((i %in% c(2,4)) && (par()$yaxt != "n"))) { ticks <- pretty(lim[[i]]) ticksMinor <- pretty(c(0, diff(ticks)[1])) ticksMinor <- (sort(rep(ticks, length(ticksMinor))) + rep(ticksMinor, length(ticks))) ticks <- ticks[ticks > lim[[i]][1] & ticks < lim[[i]][2]] ticksMinor <- ticksMinor[ticksMinor > lim[[i]][1] & ticksMinor < lim[[i]][2]] if (!tckLab[i]) { tickLabels <- FALSE } else { tickLabels <- as.character(ticks) } axis(side = i, at = ticks, labels = tickLabels, tck = tck[i], srt = rotate[[i]], ...) axis(side = i, at = ticksMinor, labels = FALSE, tck = tckMinor[i], ...) } } invisible(NULL) } .addCorners <- function(polys, ptSummary) { xlim <- range(polys$X) ylim <- range(polys$Y) corners <- list(tl=c(xlim[1], ylim[2]), tr=c(xlim[2], ylim[2]), bl=c(xlim[1], ylim[1]), br=c(xlim[2], ylim[1])); tests <- list(tl=c(min, max), tr=c(max, max), bl=c(min, min), br=c(max, min)); for (c in names(corners)) { if (nrow(polys[polys$X == (corners[[c]])[1] & polys$Y == (corners[[c]])[2], ]) > 0) next polysA <- polys[polys$X == (corners[[c]])[1], ] if (nrow(polysA) > 0) PIDsA <- polysA[polysA$Y == ((tests[[c]])[2])[[1]](polysA$Y), "PID"] polysB <- polys[polys$Y == (corners[[c]])[2], ] if (nrow(polysB) > 0) PIDsB <- polysB[polysB$X == ((tests[[c]])[1])[[1]](polysB$X), "PID"] if (nrow(polysA) == 0 || nrow(polysB) == 0) { warning(paste("Unable to close a corner (", c, ").", sep="")); next } cand <- intersect(PIDsA, PIDsB) if (length(cand) == 0) stop(paste("Unable to close a corner (", c, ") since no candidates exist.", sep="")); if (length(cand) > 1) { pts <- data.frame (x=ptSummary[cand, "x"], y=ptSummary[cand, "y"]) pts$cornerX <- (corners[[c]])[1]; pts$cornerY <- (corners[[c]])[2]; pts$dist <- sqrt((pts$x - pts$cornerX)^2 + (pts$y - pts$cornerY)^2) shortest <- which(pts$dist == min(pts$dist)) if (length(shortest) != 1) stop(paste( "Unable to determine the appropriate polygon to close corner ", c, ".", sep="")) cand <- cand[shortest] } newPoly <- polys[polys$PID == cand, ] polys <- polys[polys$PID != cand, ] xydata <- data.frame(X=c(newPoly$X, corners[[c]][1]), Y=c(newPoly$Y, corners[[c]][2])); newPoly <- calcConvexHull(xydata) newPoly$PID <- cand polys <- rbind(polys, newPoly); } polys <- polys[order(polys$PID), ] return (polys) } .addBubblesLegend <- function(radii.leg, usr.xdiff, usr.ydiff, symbol.zero, symbol.fg, symbol.bg, legend.pos, legend.breaks, legend.type, legend.title, legend.cex, ...) { ratio.y.x = (usr.ydiff / par("pin")[2]) / (usr.xdiff / par("pin")[1]) gap.x <- par("cxy")[1] * legend.cex / 2 gap.y <- par("cxy")[2] * legend.cex / 2 radii.leg.y <- radii.leg * ratio.y.x leg.tex.w <- strwidth(legend.breaks, units = "user") * legend.cex title.w = strwidth(legend.title) max.tex.w <- max(leg.tex.w) switch(legend.type, nested = { legend.height <- 2 * max(radii.leg.y) + 3 * gap.y legend.width <- 2 * max(radii.leg) + gap.x + max.tex.w }, horiz = { legend.height <- 2 * max(radii.leg.y) + 3 * gap.y legend.width <- 2 * sum(radii.leg) + (length(legend.breaks) - 1) * gap.x }, vert = { legend.height <- 2 * sum(radii.leg.y) + (length(legend.breaks) - 1) * gap.y + 3 * gap.y legend.width <- 2 * max(radii.leg) + gap.x + max.tex.w } ) if (title.w > legend.width) { w.adj <- (title.w - legend.width) / 2 } else { w.adj <- 0 } if (class(legend.pos) == "numeric") { legend.loc <- legend.pos } else { corners <- c("bottomleft", "bottomright", "topleft", "topright") if (legend.pos %in% corners) { legend.loc <- switch(legend.pos, bottomleft = c(par("usr")[1] + 0.025 * usr.xdiff + w.adj, par("usr")[3] + 0.025 * usr.ydiff + legend.height), bottomright = c(par("usr")[2] - (0.025 * usr.xdiff + legend.width + w.adj), par("usr")[3] + 0.025 * usr.ydiff + legend.height), topleft = c(par("usr")[1] + 0.025 * usr.xdiff + w.adj, par("usr")[4] - 0.025 * usr.ydiff), topright = c(par("usr")[2] - (0.025 * usr.xdiff + legend.width + w.adj), par("usr")[4] - 0.025 * usr.ydiff)); } } switch(legend.type, nested = { legend.loc[1] <- legend.loc[1] + max(radii.leg) legend.loc[2] <- legend.loc[2] - legend.height r <- rev(radii.leg) bb <- rev(legend.breaks) x.text.leg <- legend.loc[1] + max(r) + gap.x + max.tex.w for (i in 1:length(r)) { symbols(legend.loc[1], legend.loc[2] + r[i] * ratio.y.x, circles=r[i], inches=FALSE, add=TRUE, bg=symbol.bg[length(r)-i+1], fg=symbol.fg) lines(c(legend.loc[1], legend.loc[1] + r[1] + gap.x), rep(legend.loc[2] + 2 * r[i] * ratio.y.x, 2)) text(x.text.leg, legend.loc[2] + 2 * r[i] * ratio.y.x, bb[i], adj=c(1, .5), cex=legend.cex) } x.title.leg <- legend.loc[1] - max(radii.leg) + (legend.width / 2) text(x.title.leg, legend.loc[2]+legend.height, legend.title, adj=c(0.5,0.5), cex=legend.cex+0.2, col="black") zlab <- c(x.title.leg, legend.loc[2]+legend.height/4) }, horiz = { legend.loc[2] <- legend.loc[2] + max(radii.leg.y) - legend.height offset <- vector() for (i in 1:length(radii.leg)) offset[i] <- 2 * sum(radii.leg[1:i]) - radii.leg[i] + (i - 1) * gap.x symbols(legend.loc[1] + offset, rep(legend.loc[2],length(radii.leg)), circles = radii.leg, inches = FALSE, bg = symbol.bg, fg = symbol.fg, add = TRUE) text(legend.loc[1] + offset, legend.loc[2] + radii.leg.y + gap.y, legend.breaks, adj = c(0.5, 0.5), cex = legend.cex) text(legend.loc[1] + legend.width / 2, legend.loc[2] + legend.height - max(radii.leg.y), legend.title, adj = c(0.5, 0.5), cex = legend.cex + 0.2, col = "black") zlab <- c(legend.loc[1], legend.loc[2] - legend.height / 8) }, vert = { if (any(legend.pos == c("bottomleft","topleft"))) legend.loc[1] <- legend.loc[1] + 0.05 * usr.xdiff offset <- vector() for (i in 1:length(legend.breaks)) offset[i] <- gap.y + 2 * sum(radii.leg.y[1:i]) - radii.leg.y[i] + i * gap.y symbols(rep(legend.loc[1], length(legend.breaks)), legend.loc[2] - offset, circles = radii.leg, bg = symbol.bg, fg = symbol.fg, inches = FALSE, add = TRUE) x.text.leg <- legend.loc[1] + max(radii.leg) + gap.x + max.tex.w text(rep(x.text.leg, length(legend.breaks)), legend.loc[2] - offset, legend.breaks, cex = legend.cex, adj = c(1, 0.5), col="black") text(legend.loc[1] + legend.width / 2 - max(radii.leg), legend.loc[2], legend.title, adj = c(0.5, 0.5), cex = legend.cex + 0.2, col = "black") zlab <- c(legend.loc[1] + legend.width / 8, legend.loc[2]) } ) if (!is.logical(symbol.zero)) legend(zlab[1], zlab[2], legend = "zero", pch = symbol.zero, xjust = 0, yjust = 1, bty = "n", cex = 0.8, x.intersp = 0.5) invisible() } .addFeature <- function(feature, data, polyProps, isEventData, cex = NULL, col = NULL, font = NULL, pch = NULL, ...) { data <- .mat2df(data); if (isEventData) { type <- "e"; } else { type <- "p"; } if (feature == "points") { relevantProps <- c("cex", "col", "pch"); } else { relevantProps <- c("cex", "col", "font"); } polyProps <- .validatePolyProps(polyProps, parCols = relevantProps); if (is.character(polyProps)) stop(paste("Invalid PolyData 'polyProps'.\n", polyProps, sep="")); parValues <- list(cex = par("cex"), col = par("col"), font = par("font"), pch = par("pch")); parValues <- parValues[setdiff(names(parValues), names(polyProps))]; parValues <- parValues[intersect(names(parValues), relevantProps)]; if (!is.null(cex)) parValues[["cex"]] <- cex; if (!is.null(col)) parValues[["col"]] <- col; if (!is.null(font)) parValues[["font"]] <- font; if (!is.null(pch)) parValues[["pch"]] <- pch; if (is.null(polyProps)) { if (isEventData) { polyProps <- data.frame(EID = unique(data$EID)); } else { polyProps <- data.frame(PID = unique(data$PID)); } } if (!isEventData && is.element("SID", names(data)) && !is.element("SID", names(polyProps))) { p <- data[is.element(data$PID, unique(polyProps$PID)), c("PID", "SID")]; polyProps <- merge(polyProps, p[!duplicated(paste(p$PID, p$SID)), c("PID", "SID")], by="PID"); } if (length(parValues) > 1) polyProps <- .addProps(type = type, polyProps = polyProps, parValues); polyPropsReturn <- polyProps; if (isEventData) { data <- data.frame(data[is.element(data$EID, unique(polyProps$EID)), ]); } else { if (is.element("SID", names(polyProps))) { if (!is.element("SID", names(data))) stop("Since 'polyProps' contains an SID column, 'data' must as well.\n"); data <- data[is.element(paste(data$PID, data$SID), unique(paste(polyProps$PID, polyProps$SID))), ]; } else { data <- data[is.element(data$PID, unique(polyProps$PID)), ]; } } propColumns <- intersect(names(polyProps), relevantProps); exprStr <- paste("paste(", paste(paste('polyProps[, "', propColumns, '"]', sep=""), collapse=", "), ");", sep=""); polyProps$props <- eval(parse(text=exprStr)) if (isEventData) { data <- merge(data, polyProps[, c("EID", "props")], by="EID"); } else { if (is.element("SID", names(polyProps))) { data <- merge(data, polyProps[, c("PID", "SID", "props")], by=c("PID", "SID")); } else { data <- merge(data, polyProps[, c("PID", "props")], by="PID"); } } data <- split(data, data$props); polyProps <- polyProps[!duplicated(polyProps$props), ]; for (c in names(data)) { d <- (data[[c]]); p <- (as.list(polyProps[polyProps$props == c, propColumns])); if (feature == "labels") { text(x = d$X, y = d$Y, labels = as.character(d$label), cex = p$cex, col = p$col, font = p$font, ...); } else { points (x = d$X, y = d$Y, cex = p$cex, col = p$col, pch = p$pch, ...); } } return (polyPropsReturn); } .addLabels <- function(projection = NULL, ...) { dots <- list(...); main=dots$main; sub=dots$sub; xlab=dots$xlab; ylab=dots$ylab; if (!is.null(projection) && !is.na(projection) && projection == "UTM") { if (is.null(xlab)) xlab <- "UTM Easting (km)"; if (is.null(ylab)) ylab <- "UTM Northing (km)"; } else if (!is.null(projection) && !is.na(projection) && projection == "LL") { if (is.null(xlab)) xlab <- "Longitude (\u00B0)" if (is.null(ylab)) ylab <- "Latitude (\u00B0)" } else { if (is.null(xlab)) xlab <- "X"; if (is.null(ylab)) ylab <- "Y"; } if (is.null(main)) main <- ""; if (is.null(sub)) sub <- ""; title (main=main, sub=sub, xlab=xlab, ylab=ylab) invisible(NULL); } .addProps <- function(type, polyProps, ...) { param <- list(...); newParam <- list(); for (i in 1:length(param)) { if (is.list(param[[i]])) { newParam <- c(newParam, param[[i]]); } else { newParam <- c(newParam, param[i]); } } param <- newParam; if (type == "e") { polyProps$IDX <- polyProps$EID; } else if (type == "p") { polyProps$IDX <- polyProps$PID; } else { stop ( "Unknown 'type'. Must be either \"e\" or \"p\"."); } uIDX <- unique(polyProps$IDX); for (c in names(param)) { if (!is.null(param[[c]])) { if (is.element(c, names(polyProps))) { polyProps <- data.frame(polyProps[, !is.element(names(polyProps), c)]); if (ncol(polyProps) == 1) { if (type == "p") names(polyProps) <- "PID"; if (type == "e") names(polyProps) <- "EID"; } } newColumn <- data.frame(IDX=uIDX); newColumn[, c] <- rep(param[[c]], length.out = length(uIDX)); polyProps <- merge(polyProps, newColumn, by = "IDX"); } } polyProps <- data.frame(polyProps[, !is.element(names(polyProps), "IDX")]); if (ncol(polyProps) == 1) { if (type == "p") names(polyProps) <- "PID"; if (type == "e") names(polyProps) <- "EID"; } return (polyProps); } .calcDist <- function(polys) { if (!is.null(attr(polys, "projection")) && !is.na(attr(polys, "projection")) && ((attr(polys, "projection") == "UTM") || (attr(polys, "projection") == 1))) { len <- nrow(polys) D <- c(sqrt((polys$X[1:(len-1)] - polys$X[2:len])^2 + (polys$Y[1:(len-1)] - polys$Y[2:len])^2), 0); } else if (!is.null(attr(polys, "projection")) && !is.na(attr(polys, "projection")) && (attr(polys, "projection") == "LL")) { R <- 6371.3; polys[, c("X", "Y")] <- polys[, c("X", "Y")] * pi / 180.0 len <- nrow(polys) s0 <- 1:(len - 1); s1 <- 2:len; dlon <- polys$X[s1] - polys$X[s0]; dlat <- polys$Y[s1] - polys$Y[s0]; cosPolysY <- cos(polys$Y); a <- (sin(dlat / 2))^2 + cosPolysY[s0] * cosPolysY[s1] * (sin(dlon / 2))^2; a <- sqrt(a); a[a > 1] <- 1; cc <- 2 * asin(a); D <- c(R * cc, 0); } else { stop(paste( "Invalid projection attribute. Supported projections include \"LL\",", "\"UTM\", and 1.\n")); } return (D); } .calcOrientation <- function(polys) { inRows <- nrow(polys); outCapacity <- nrow(polys); if (!is.element("SID", names(polys))) { inID <- c(polys$PID, integer(length = inRows), polys$POS); } else { inID <- c(polys$PID, polys$SID, polys$POS); } inXY <- c(polys$X, polys$Y); results <- .C("calcOrientation", inID = as.integer(inID), inXY = as.double(inXY), inVerts = as.integer(inRows), outID = integer(2 * outCapacity), outOrientation = double(outCapacity), outRows = as.integer(outCapacity), outStatus = integer(1), PACKAGE = "PBSmapping"); if (results$outStatus == 1) { stop( "Insufficient physical memory for processing.\n"); } if (results$outStatus == 2) { stop(paste( "Insufficient memory allocated for output. Please upgrade to the latest", "version of the software, and if that does not fix this problem, please", "file a bug report.\n", sep = "\n")); } outRows <- as.vector(results$outRows); if (outRows > 0) { d <- data.frame(PID = results$outID[1:outRows], SID = results$outID[(outCapacity+1):(outCapacity+outRows)], orientation = results$outOrientation[1:outRows]); if (!is.element("SID", names(polys))) d$SID <- NULL; invisible(d); } else { invisible(NULL); } } .checkClipLimits <- function(limits) { if (limits[1] > limits[2]) stop("xlim[1] is larger than xlim[2]") if (limits[3] > limits[4]) stop("ylim[1] is larger than ylim[2]") if (limits[1] > 360 || limits[2] < -20) stop("xlim are outside of the range of c(-20,360)") if (limits[3] > 90 || limits[4] < -90) stop("ylim are outside of the range of c(-90,90)") } .checkProjection <- function(projectionPlot, projectionPoly) { if (is.null(projectionPlot)) { projMapStr <- "NULL"; } else { projMapStr <- as.character(projectionPlot); } if (is.null(projectionPoly)) { projPolyStr <- "NULL"; } else { projPolyStr <- as.character(projectionPoly); } msg <- paste( "The data's 'projection' attribute (", projPolyStr, ") differs from the\n", "projection of the plot region (", projMapStr, ").\n", sep=""); if (xor(is.null(projectionPlot), is.null(projectionPoly))) { warning(msg); } else if ((!is.null(projectionPlot) && !is.null(projectionPoly)) && (xor(is.na(projectionPlot), is.na(projectionPoly)))) { warning(msg); } else if (!is.null(projectionPlot) && !is.null(projectionPoly) && !is.na(projectionPlot) && !is.na(projectionPoly) && (projectionPlot != projectionPoly)) { warning(msg); } } .checkRDeps <- function(caller = "unspecified", requires = NULL) { if (is.null(version$language) || (version$language != "R")) { stop (paste (" The function '", caller, "' requires several dependencies available only in R.\n", "Please try again from within R.\n", sep="")); } err <- NULL; for (pkg in requires) { if (!require(pkg, character.only = TRUE)) { err <- append (err, pkg); } } if (!is.null (err)) { err <- paste (err, collapse="', '"); stop (paste (" The function '", caller, "' requires the package(s) '", err, "'.\n", "Please install the package(s) and try again.\n", sep="")); } } .clip <- function(polys, xlim, ylim, isPolygons, keepExtra) { if (keepExtra) pdata <- extractPolyData(polys); attrNames <- setdiff(names(attributes(polys)), c("names", "row.names", "class")); attrValues <- attributes(polys)[attrNames]; inRows <- nrow(polys); outCapacity <- as.integer(2 * inRows); if (!is.element("SID", names(polys))) { inID <- c(polys$PID, integer(length = inRows), polys$POS); } else { inID <- c(polys$PID, polys$SID, polys$POS); } inXY <- c(polys$X, polys$Y); limits <- c(xlim, ylim); results <- .C("clip", inID = as.integer(inID), inXY = as.double(inXY), inVerts = as.integer(inRows), polygons = as.integer(isPolygons), limits = as.double(limits), outID = integer(4 * outCapacity), outXY = double(2 * outCapacity), outRows = as.integer(outCapacity), outStatus = integer(1), PACKAGE = "PBSmapping"); if (results$outStatus == 1) { stop( "Insufficient physical memory for processing.\n"); } if (results$outStatus == 2) { stop(paste( "Insufficient memory allocated for output. Please upgrade to the latest", "version of the software, and if that does not fix this problem, please", "file a bug report.\n", sep = "\n")); } outRows <- as.vector(results$outRows); if (outRows > 0) { d <- data.frame(PID = results$outID[1:outRows], SID = results$outID[(outCapacity+1):(outCapacity+outRows)], POS = results$outID[(2*outCapacity+1):(2*outCapacity+outRows)], oldPOS = results$outID[(3*outCapacity+1):(3*outCapacity+outRows)], X = results$outXY[1:outRows], Y = results$outXY[(outCapacity+1):(outCapacity+outRows)]); if (!is.element("SID", names(polys))) d$SID <- NULL; d$oldPOS[d$oldPOS == -1] <- NA; if (keepExtra) d <- merge(x = d, y = pdata, all.x = TRUE, by = intersect(c("PID", "SID"), names(d))); attributes(d) <- c(attributes(d), attrValues); if (all(d$X == xlim[1]) || all(d$X == xlim[2]) || all(d$Y == ylim[1]) || all(d$Y == ylim[2])) return(NULL); return(d); } else { return(NULL); } } .closestPoint <- function(pts, pt) { pts$Xorig <- pt$X pts$Yorig <- pt$Y pts$dist <- (pts$Xorig - pts$X) ^ 2 + (pts$Yorig - pts$Y) ^ 2 return (pts$dist == min(pts$dist)) } .createFastIDdig <- function(polysA, polysB = NULL, cols) { if ((length(cols) == 2) && all(is.element(cols, names(polysA)))) { digitsL <- floor(log10(max(polysA[[cols[1]]])) + 1); digitsR <- floor(log10(max(polysA[[cols[2]]])) + 1); if (!is.null(polysB)) { if (is.element(cols[1], names(polysB))) digitsL <- max(digitsL, floor(log10(max(polysB[[cols[1]]])) + 1)); if (is.element(cols[2], names(polysB))) digitsR <- max(digitsR, floor(log10(max(polysB[[cols[2]]])) + 1)); } if ((digitsL + digitsR) <= 15) { return (digitsR); } else { return (0); } } else { return (NULL); } } .createGridIDs <- function(d, addSID, byrow) { if (addSID && !byrow) { tmp <- d$PID; d$PID <- d$SID; d$SID <- tmp; } else if (!addSID && byrow) { d$PID <- (d$SID - 1) * (length(unique(d$X)) - 1) + d$PID; d$SID <- NULL; } else if (!addSID && !byrow) { d$PID <- (d$PID - 1) * (length(unique(d$Y)) - 1) + d$SID; d$SID <- NULL; } return (d); } .createIDs <- function(x, cols, fastIDdig = NULL) { presentCols <- cols[is.element(cols, names(x))] if (length(presentCols) == 1) { return (x[[presentCols]]); } else if (length(presentCols) == 2) { if (is.null(fastIDdig)) { fastIDdig <- .createFastIDdig(polysA=x, polysB=NULL, cols=presentCols); } if (fastIDdig > 0) { return (as.double(x[[presentCols[1]]] + (x[[presentCols[2]]] / 10^fastIDdig))); } else { return (paste(x[[presentCols[1]]], x[[presentCols[2]]], sep = "-")); } } else if (length(presentCols) > 2) { exprStr <- paste("paste(", paste(paste("x$", presentCols, sep=""), collapse=", "), ");", sep=""); return (eval(parse(text=exprStr))); } return (NULL); } .expandEdges <- function(polys, pts, xlim, ylim) { polyRange <- c(range(polys$X), range(polys$Y)) ptsRange <- c(range(pts$X), range(pts$Y)) toFixPts <- c(ptsRange[1] < polyRange[1], ptsRange[2] > polyRange[2], ptsRange[3] < polyRange[3], ptsRange[4] > polyRange[4]) toFixLim <- c(signif(xlim[1], 5) < signif(polyRange[1], 5), signif(xlim[2], 5) > signif(polyRange[2], 5), signif(ylim[1], 5) < signif(polyRange[3], 5), signif(ylim[2], 5) > signif(polyRange[4], 5)) toFix <- toFixPts | toFixLim if (!any(toFix)) return (polys) for (side in which(toFix)) { if (side == 1) { PID <- which(pts$X < polyRange[side]) } else if (side == 2) { PID <- which(pts$X > polyRange[side]) } else if (side == 3) { PID <- which(pts$Y < polyRange[side]) } else if (side == 4) { PID <- which(pts$Y > polyRange[side]) } else { stop ("Internal error: unrecognized value of \"size\" in point check.") } if (length(PID) == 0) { if (side == 1 || side == 2) { PID <- which(.closestPoint(pts, data.frame(X=xlim[side], Y=mean(ylim)))) } else if (side == 3 || side == 4) { PID <- which(.closestPoint(pts, data.frame(X=mean(xlim), Y=ylim[side - 2]))) } else { stop ("Internal error: unrecognized value of \"size\" in limit check.") } } if (length(PID) != 1) stop ("Internal error: unable to determine appropriate PID for expansion.") newPoly <- polys[polys$PID == PID, ] polys <- polys[polys$PID != PID, ] if (side == 1 || side == 2) { newXY <- data.frame(X=c(newPoly$X, rep(xlim[side], 2)), Y=c(newPoly$Y, range(newPoly$Y))) } else if (side == 3 || side == 4) { newXY <- data.frame(X=c(newPoly$X, range(newPoly$X)), Y=c(newPoly$Y, rep(ylim[side - 2], 2))) } else { stop ("Internal error: unrecognized value of \"size\" in data frame setup.") } newPoly <- calcConvexHull(newXY) newPoly$PID <- PID polys <- rbind(polys, newPoly) } polys <- polys[order(polys$PID), ] return (polys); } .fixGSHHSWorld <- function (world) { xlim <- range(world$X) ylim <- range(world$Y) ylim[1] <- -90 event <- data.frame(EID = 1, X = 85, Y = -72) event <- findPolys(event, world) pid <- event$PID[1] curAnt <- world[is.element(world$PID,pid), ] if (curAnt$X[1] > curAnt$X[nrow(curAnt)]) curAnt <- curAnt[nrow(curAnt):1, ] left <- curAnt[c(1,1:nrow(curAnt)), ] left$X <- left$X - 360 left$Y[1] <- -90 right <- curAnt[c(1:nrow(curAnt), nrow(curAnt)), ] right$X <- right$X + 360 right$Y[nrow(right)] <- -90 curAnt <- rbind(left, curAnt, right) curAnt$POS <- 1:nrow(curAnt) curAnt <- clipPolys(curAnt, xlim, ylim) curAnt$oldPOS <- NULL world <- rbind(world[world$PID < pid, ], curAnt, world[world$PID > pid, ]) row.names(world) <- 1:length(row.names(world)) invisible(world) } .getBasename <- function (fn, ext) { if (!file.exists (paste(fn, ".", ext, sep=""))) { fn <- sub ("\\..{3}$", "", fn); if (!file.exists (paste(fn, ".", ext, sep=""))) { stop (paste ("Cannot find the file \"", fn, ".", ext, "\".", sep="")); } } return (fn); } .getGridPars <- function (polys, fullValidation = TRUE) { res <- list(); res$x <- sort(unique(polys$X)); res$y <- sort(unique(polys$Y)); lenx <- length(res$x); leny <- length(res$y); if ((lenx < 2) || (leny < 2)) { return (NULL); } if (is.element("SID", names(polys))) { res$addSID <- TRUE; } else { res$addSID <- FALSE; } if (lenx == 2 && leny == 2) { res$byrow <- TRUE; } else if (lenx == 2) { if (polys[1, "PID"] + 1 == polys[5, "PID"]) { res$byrow <- FALSE; } else { res$byrow <- TRUE; } } else { if (polys[1, "PID"] + 1 == polys[5, "PID"]) { res$byrow <- TRUE; } else { res$byrow <- FALSE; } } res$projection <- attr(polys, "projection"); res$zone <- attr(polys, "zone"); if (fullValidation) { t <- makeGrid(x = res$x, y = res$y, byrow = res$byrow, addSID = res$addSID, projection = res$projection, zone = res$zone); if (is.character (all.equal (polys, t))) { return (NULL); } } return (res); } .initPlotRegion <- function(projection, xlim, ylim, plt) { if ((missing(xlim) || is.null(xlim)) || !is.vector(xlim) || (length(xlim) != 2) || (missing(ylim) || is.null(ylim)) || !is.vector(ylim) || (length(ylim) != 2)) { stop( "xlim and/or ylim is missing or invalid.\n"); } if (diff(ylim) == 0 || diff(xlim) == 0) { stop( "xlim/ylim must specify a region with area greater than 0.\n"); } if(!par()$new) frame(); if (is.null(plt)) plt <- par("plt"); if (is.null(projection)) stop( "'projection' argument must not equal NULL.\n"); if (!is.na(projection)) { xyRatio <- ifelse(projection == "LL", cos((mean(ylim) * pi) / 180), 1); aspPlotRegion <- (par()$fin[1]*diff(plt[1:2])) / (par()$fin[2]*diff(plt[3:4])); if (is.infinite(aspPlotRegion)) stop("Plot region must have an area greater than 0.\n"); aspPolySet <- diff(xlim) / diff(ylim) * xyRatio; if (is.numeric(projection)) aspPolySet <- aspPolySet / projection; if (is.infinite(aspPolySet) || (aspPolySet == 0)) stop(paste( "Either 'projection' is 0 or 'xlim'/'ylim' specify a region with an area", "of 0.\n", sep="\n")); if (aspPlotRegion < aspPolySet) { pinX <- par()$fin[1]*diff(plt[1:2]); pinY <- pinX * aspPolySet^-1; toMove <- (diff(plt[3:4]) - pinY/par()$fin[2]) / 2; plt[3:4] <- plt[3:4] + c(toMove, -toMove); } else if (aspPlotRegion > aspPolySet) { pinY <- par()$fin[2]*diff(plt[3:4]); pinX <- pinY * aspPolySet; toMove <- (diff(plt[1:2]) - pinX/par()$fin[1]) / 2; plt[1:2] <- plt[1:2] + c(toMove, -toMove); } par(mai=c(par()$fin[2]*plt[3], par()$fin[1]*plt[1], par()$fin[2]*(1-plt[4]), par()$fin[1]*(1-plt[2]))); parPlt <- signif(as.double(par()$plt), digits=5); locPlt <- signif(as.double(plt), digits=5); if (any(parPlt != locPlt)) par(plt = plt); } par(usr = c(xlim, ylim)); invisible(NULL); } .insertNAs <- function(polys, idx) { sel.polys <- polys[is.element(names(polys), idx)] if (is.null(unlist(sel.polys))) return (NA) lenPolys <- lapply(sel.polys, "length") nPolys <- length(lenPolys) TFT <- rep(c(TRUE, FALSE), length.out=(nPolys * 2) - 1) reps <- rep(1, len=(nPolys * 2) - 1) reps[TFT] <- unlist(lenPolys) NAs <- rep(!TFT, times=reps) new.polys <- vector(length=(length(unlist(sel.polys)) + nPolys - 1)) new.polys[NAs] <- NA new.polys[!NAs] <- unlist(sel.polys) return (new.polys) } .is.in =function(events, polys, use.names=TRUE) { if (!is.PolySet(polys)) stop("Supply a PolySet to argument 'polys'") if (!all(c(is.element(c("X","Y"),colnames(events)),is.element(c("X","Y"),colnames(polys))))) stop("Objects 'events' and 'polys' must have column names 'X' and 'Y'") if (!is.EventData(events)) events = as.EventData(data.frame(EID=1:nrow(events), events), projection=attributes(polys)$projection) inEvents = nrow(events) inEventsID = events$EID inEventsXY = c(events$X, events$Y) inPolys = nrow(polys) if (!is.element("SID", names(polys))) { inPolysID = c(polys$PID, integer(length=inPolys), polys$POS) } else { inPolysID = c(polys$PID, polys$SID, polys$POS) } inPolysXY = c(polys$X, polys$Y) outCapacity <- nrow(events) results <- .C("findPolys", inEventsID = as.integer(inEventsID), inEventsXY = as.double(inEventsXY), inEvents = as.integer(inEvents), inPolysID = as.integer(inPolysID), inPolysXY = as.double(inPolysXY), inPolys = as.integer(inPolys), outID = integer(4 * outCapacity), outRows = as.integer(outCapacity), outStatus = integer(1), PACKAGE = "PBSmapping") outRows <- as.vector(results$outRows) if (outRows == 0) { e.out = events e.in = events[0,] e.bdry = 0 } else { d <- data.frame(EID = results$outID[1:outRows], PID = results$outID[(outCapacity+1):(outCapacity+outRows)], SID = results$outID[(2*outCapacity+1):(2*outCapacity+outRows)], Bdry = results$outID[(3*outCapacity+1):(3*outCapacity+outRows)]) e.in = events[is.element(events$EID,d$EID),] e.out = events[!is.element(events$EID,d$EID),] e.bdry = d$Bdry } out= list() out[["e.in"]] = e.in out[["e.out"]] = e.out out[["all.in"]] = nrow(e.in)==nrow(events) out[["all.out"]] = nrow(e.out)==nrow(events) out[["all.bdry"]] = all(e.bdry==1) return(out) } .is.in.defunct =function(events, polys, use.names=TRUE) { if (!all(c(is.element(c("X","Y"),colnames(events)),is.element(c("X","Y"),colnames(polys))))) stop("Objects 'events' and 'polys' must have column names 'X' and 'Y'") .checkRDeps(".is.in", c("sp")) eval(parse(text="in.out = .Call(\"R_point_in_polygon_sp\", as.numeric(events[,\"X\"]), as.numeric(events[,\"Y\"]), as.numeric(polys[,\"X\"]), as.numeric(polys[,\"Y\"]), PACKAGE = \"sp\")")) if (use.names) { if(is.PolySet(events) || is.PolyData(events)) names(in.out) = .createIDs(events, intersect(c("PID","SID"), colnames(events))) if(is.EventData(events)) names(in.out) = events[,"EID"] } out = list() out[["in.out"]] = in.out out[["all.in"]] = all(as.logical(in.out)) return(out) } .mat2df <- function(data) { pbsClass <- intersect(attributes(data)$class, c("EventData", "LocationSet", "PolyData", "PolySet")); attrNames <- names(attributes(data)); if(all(is.element(attrNames, c("dim", "dimnames", "class")) == TRUE)) { addValues <- NULL; } else { addNames <- setdiff(attrNames, c("dim", "dimnames", "class")); addValues <- attributes(data)[addNames]; } data <- data.frame(unclass(data)); if(!is.null(addValues)) { attributes(data) <- c(attributes(data), addValues); } if(length(pbsClass) > 0) { attr(data, "class") <- c(pbsClass, "data.frame"); } return(data); } .rollupPolys <- function(polys, rollupMode, exteriorCCW, closedPolys, addRetrace) { attrNames <- setdiff(names(attributes(polys)), c("names", "row.names", "class")); attrValues <- attributes(polys)[attrNames]; inRows <- nrow(polys); outCapacity <- 2 * inRows; if (!is.element("SID", names(polys))) { inID <- c(polys$PID, integer(length = inRows)); } else { inID <- c(polys$PID, polys$SID); } inXY <- c(polys$X, polys$Y); results <- .C("rollupPolys", inID = as.integer(inID), inPOS = as.double(polys$POS), inXY = as.double(inXY), inVerts = as.integer(inRows), outID = integer(3 * outCapacity), outXY = double(2 * outCapacity), outRows = as.integer(outCapacity), rollupMode = as.integer(rollupMode), exteriorCCW = as.integer(exteriorCCW), closedPolys = as.integer(closedPolys), addRetrace = as.integer(addRetrace), outStatus = integer(1), PACKAGE = "PBSmapping"); if (results$outStatus == 1) { stop( "Insufficient physical memory for processing.\n"); } if (results$outStatus == 2) { stop(paste( "Insufficient memory allocated for output. Please upgrade to the latest", "version of the software, and if that does not fix this problem, please", "file a bug report.\n", sep = "\n")); } if (results$outStatus == 3) { stop(paste( "Unable to rollup the polygons, as one or more children did not have a", "parent.\n")); } outRows <- as.vector(results$outRows); if (outRows > 0) { d <- data.frame(PID = results$outID[1:outRows], SID = results$outID[(outCapacity+1):(outCapacity+outRows)], POS = results$outID[(2*outCapacity+1):(2*outCapacity+outRows)], X = results$outXY[1:outRows], Y = results$outXY[(outCapacity+1):(outCapacity+outRows)]); if (!is.element("SID", names(polys)) || rollupMode == 1) d$SID <- NULL; attributes(d) <- c(attributes(d), attrValues); invisible(d); } else { invisible(NULL); } } .plotMaps <- function(polys, xlim, ylim, projection, plt, polyProps, border, lty, col, colHoles, density, angle, bg, axes, tckLab, tck, tckMinor, isType, ...) { legalNames <- c("adj", "ann", "ask", "bg", "bty", "cex", "cex.axis", "cex.lab", "cex.main", "cex.sub", "col", "col.axis", "col.lab", "col.main", "col.sub", "crt", "csi", "err", "exp", "fg", "font", "font.axis", "font.lab", "font.main", "font.sub", "lab", "las", "lty", "lwd", "mgp", "mkh", "pch", "smo", "srt", "tck", "tcl", "tmag", "type", "xaxp", "xaxs", "xaxt", "xpd", "yaxp", "yaxs", "yaxt"); if (!is.null(version$language) && (version$language == "R")) { legalNames <- setdiff(legalNames, "csi"); } legalNames <- intersect(legalNames, names(par())); backupPar <- par(legalNames); on.exit(par(backupPar)); dots <- list(...); extraArgs <- setdiff(names(dots), legalNames); extraArgs <- setdiff(extraArgs, c("main", "sub", "type", "xlab", "ylab")); if (length(extraArgs) > 0) { warning(paste( "Ignored unrecognized argument '", paste(extraArgs, collapse="', '"), "'.\n", sep = "")); } if (isType == "points") legalNames <- setdiff(legalNames, c("cex", "pch")); par(dots[intersect(names(dots), legalNames)]); if (is.null(projection) || is.na(projection)) projection <- FALSE; if (is.logical(projection)) { if (projection) { if (!is.null(attr(polys, "projection"))) { projection <- attr(polys, "projection"); } else { projection <- 1; warning( "'projection' set to 1:1 since unspecified 'projection' argument/attribute.\n"); } } else { projection <- NA; } } else { if (is.numeric(projection) || is.element(projection, c("LL", "UTM"))) { if (!is.null(attr(polys, "projection")) && !is.element(projection, attr(polys, "projection"))) { projection <- attr(polys, "projection"); warning( "'projection' argument overwritten with PolySet's 'projection' attribute.\n"); } } else { stop(paste( "Either omit 'projection' argument or set it to a numeric value, \"LL\", or", "\"UTM\".\n", sep="\n")); } } if (!is.null(polys)) attr(polys, "projection") <- projection; labelProjection <- projection; if (is.null(polys)) { if (is.null(xlim) || is.null(ylim) || is.null(projection)) { stop( "To plot a NULL PolySet, pass 'xlim', 'ylim', and 'projection' arguments.\n"); } } else { polys <- .validateXYData(polys); if (is.character(polys)) stop(paste("Invalid PolySet.\n", polys, sep="")); } if (is.null(xlim)) xlim <- range(polys$X); if (is.null(ylim)) ylim <- range(polys$Y); if (is.element("type", names(dots))) { if (dots$type == "n") { polys <- NULL; } else { stop( "Either omit 'type' argument or set it to \"n\".\n"); } } if (!is.null(polys)) { par(col = 1); } else { if (length(col) > 1) { stop(paste( "Either omit 'col' argument or set it to a single-element vector when 'polys'", "equals NULL or 'type = \"n\"'.\n", sep = "\n")); } else if (!is.null(col)) { par(col = col); } } options(map.xlim = xlim); options(map.ylim = ylim); options(map.projection = projection); .initPlotRegion(projection=projection, xlim=xlim, ylim=ylim, plt=plt); if (!is.null(bg)) polygon(x=xlim[c(1,2,2,1)], y=ylim[c(1,1,2,2)], col=bg, border=0, xpd=TRUE); if (!is.null(polys)) { if (isType == "polygons") { ret <- addPolys(polys, xlim = xlim, ylim = ylim, polyProps = polyProps, border = border, lty = lty, col = col, colHoles = colHoles, density = density, angle = angle); } else if (isType == "lines") { ret <- addLines(polys, xlim = xlim, ylim = ylim, polyProps = polyProps, lty = lty, col = col); } else if (isType == "points") { cex <- list(...)$cex; pch <- list(...)$pch; ret <- addPoints(polys, xlim = xlim, ylim = ylim, polyProps = polyProps, cex = cex, col = col, pch = pch); } else { stop( "Unrecognized 'isType'.\n"); } } else { ret <- NULL; } if (axes) { .addAxis(xlim = xlim, ylim = ylim, tckLab = tckLab, tck = tck, tckMinor = tckMinor, ...); } else { options(map.xline = 1); options(map.yline = 1); } .addLabels(projection = labelProjection, ...); if (axes) { box(); } invisible(ret); } .preparePolyProps <- function(polysPID, polysSID, polyProps) { if (is.null(polyProps)) { polyProps <- data.frame(PID = unique(polysPID)); } else { polyProps <- .validatePolyData(polyProps); if (is.character(polyProps)) stop(paste("Invalid PolyData 'polyProps'.\n", polyProps, sep="")); } if (!is.null(polysSID) && !is.element("SID", names(polyProps))) { p <- data.frame(PID=polysPID, SID=polysSID); p <- p[!duplicated(.createIDs(p, cols = c("PID", "SID"))), ] p <- p[is.element(p$PID, unique(polyProps$PID)), ]; polyProps <- merge(polyProps, p, by="PID"); } return (polyProps); } .validateData <- function(data, className, requiredCols=NULL, requiredAttr=NULL, noFactorCols=NULL, noNACols=NULL, keyCols=NULL, numericCols=NULL) { fnam = as.character(substitute(data)) if (is.matrix(data)) { data <- .mat2df(data); } if (is.data.frame(data) && (nrow(data) > 0)) { if (!is.null(className) && (class(data)[1] != "data.frame")) { if (class(data)[1] != className) { return(paste("Unexpected class (", class(data)[1], ").\n", sep="")); } } if (!is.null(requiredCols) && !all(is.element(requiredCols, names(data)))) { return(paste("One or more of the required columns is missing.\n", "Required columns: ", paste(requiredCols, collapse = ", "), ".\n", sep="")); } if (!is.null(requiredAttr) && !all(is.element(requiredAttr, names(attributes(data))))) { return(paste("One or more of the required attributes is missing.\n", "Required attributes: ", paste(requiredAttr, collapse = ", "), ".\n", sep="")); } presentCols <- intersect(noNACols, names(data)); if (length(presentCols) > 0) { exprStr <- paste(paste("any(is.na(data$", presentCols, "))", sep=""), collapse=" || "); if (eval(parse(text=exprStr))) { return(paste("One or more columns (where NAs are not allowed) contains NAs.\n", "Columns that cannot contain NAs: ", paste(presentCols, collapse = ", "), ".\n", sep="")); } } presentCols <- intersect(noFactorCols, names(data)); if (length(presentCols) > 0) { exprStr <- paste(paste("is.factor(data$", presentCols, ")", sep=""), collapse=" || "); if (eval(parse(text=exprStr))) { return(paste("One or more columns contains factors where they are not allowed.\n", "Columns that cannot contain factors: ", paste(presentCols, collapse = ", "), ".\n", sep="")); } } presentCols <- intersect(keyCols, names(data)); if (length(presentCols) > 0) { if (length(presentCols) == 1) { keys <- data[[presentCols]]; } else if ((length(presentCols) == 2) && ((length(intersect(presentCols, c("PID","SID","POS","EID"))) == 2) || (all(is.integer(data[[presentCols[1]]])) && all(is.integer(data[[presentCols[2]]]))))) { keys <- .createIDs(data, cols=presentCols); } else { keys = apply(data[,presentCols],1,paste0,collapse=".") } if (any(duplicated(keys))) { return(paste("The 'key' for each record is not unique.\n", "Columns in key: ", paste(presentCols, collapse = ", "), ".\n", sep="")); } } presentCols <- intersect(numericCols, names(data)); if (length(presentCols) > 0) { exprStr <- paste(paste("any(!is.numeric(data$", presentCols, "))", sep=""), collapse=" || "); if (eval(parse(text=exprStr))) { return(paste("One or more columns requires numeric values, but contains non-numerics.\n", "Columns that must contain numerics: ", paste(presentCols, collapse = ", "), ".\n", sep="")); } } if (!is.null(className) && className == "PolySet") { idx <- .createIDs(data, cols=c("PID", "SID")); idxFirst <- which(!duplicated(idx)); idxLast <- c((idxFirst-1)[-1], length(idx)); holes <- (data$POS[idxFirst] > data$POS[idxLast]) idxOuter <- rep(!holes, times=((idxLast-idxFirst)+1)) idxInner <- !idxOuter; lt <- c(data$POS[1:(nrow(data)-1)] < data$POS[2:(nrow(data))], FALSE); lt[idxLast] <- TRUE; j <- any(!lt[idxOuter]) if (j) { j <- !lt; j[idxInner] <- FALSE; j <- which(j) + 1; return(paste("POS column must contain increasing values for outer contours.\n", "Offending rows: ", paste(j, collapse=", "), ".\n", sep="")); } lt[idxLast] <- FALSE; j <- any(lt[idxInner]) if (j) { j <- lt; j[idxOuter] <- FALSE; j <- which(j); return(paste("POS column must contain decreasing values for inner contours.\n", "Offending rows: ", paste(j, collapse=", "), ".\n", sep="")); } if (any(class(data) == "PolySet")) { polys = data polys$idx <- .createIDs(polys, cols=c("PID", "SID")); names(holes) = unique(idx) if (any(holes)) { solids = !holes snams = names(solids)[solids] snums = (1:length(solids))[solids] plist = list() for (i in 1:length(snums)) { ii = snums[i] iii = snams[i] if (iii==rev(names(solids))[1] || solids[ii+1]) next endhole = ifelse (is.na(snums[i+1]) && rev(holes)[1], length(holes), (snums[i+1]-1)) iholes = holes[(ii+1):endhole] if (!all(iholes)) stop ("Check '.validateData' code") jjj = names(iholes) jdx = idx[is.element(idx,jjj)] isolid = polys[is.element(polys$idx,iii),] ihole = polys[is.element(polys$idx, jjj),] e.in.p = .is.in(ihole, isolid) if (e.in.p$all.in) next e.bad = e.in.p$e.out plist[[iii]] = list() plist[[iii]][["solid"]] = isolid plist[[iii]][["hole.vout"]] = list() j.bad = split(e.bad, e.bad$idx) plist[[iii]][["hole.vout"]] = j.bad } if (length(plist)>0) { assign ("solids_holes", plist, envir=.PBSmapEnv) swo = sapply(plist, function(x){length(x$hole.vout)}) swo = sapply(plist, function(x){nh=length(x$hole.vout); nv=sapply(x$hole.vout,nrow); paste0(nh, " hole",ifelse(nh>1,"s",""),": ", paste0("[",names(nv),"]=", nv,"v",collapse="; "))}) swo.txt = paste0(" Solid ",names(swo)," --> ", swo, collapse="\n") cat(paste0("\n******* WARNING *******\n", fnam, ": Hole vertices (v) exist outside solids [PID.SID]:\n", swo.txt, "\nSee object '.PBSmapEnv$solids_holes' for details.\n\n")) } } } } } else { return(paste("The object must be either a matrix or a data frame.\n")); } return(data); } .validateEventData <- function(EventData) { return(.validateData(EventData, className = "EventData", requiredCols = c("EID", "X", "Y"), requiredAttr = NULL, noFactorCols = c("EID", "X", "Y"), noNACols = c("EID", "X", "Y"), keyCols = c("EID"), numericCols = c("EID", "X", "Y"))); } .validateLocationSet <- function(LocationSet) { return(.validateData(LocationSet, className = "LocationSet", requiredCols = c("EID", "PID", "Bdry"), requiredAttr = NULL, noFactorCols = c("EID", "PID", "SID", "Bdry"), noNACols = c("EID", "PID", "SID", "Bdry"), keyCols = c("EID", "PID", "SID"), numericCols = c("EID", "PID", "SID"))); } .validatePolyData <- function(PolyData) { return(.validateData(PolyData, className = "PolyData", requiredCols = c("PID"), requiredAttr = NULL, noFactorCols = c("PID", "SID"), noNACols = c("PID", "SID"), keyCols = c("PID", "SID"), numericCols = c("PID", "SID"))); } .validatePolyProps <- function(polyProps, parCols = NULL) { if (is.null(polyProps)) return (NULL); return (.validateData(polyProps, className = "PolyData", requiredCols = NULL, requiredAttr = NULL, noFactorCols = parCols, noNACols = NULL, keyCols = NULL, numericCols = NULL)); } .validatePolySet <- function(polys) { return(.validateData(polys, className = "PolySet", requiredCols = c("PID", "POS", "X", "Y"), requiredAttr = NULL, noFactorCols = c("PID", "SID", "POS", "X", "Y"), noNACols = c("PID", "SID", "POS", "X", "Y"), keyCols = c("PID", "SID", "POS"), numericCols = c("PID", "SID", "POS", "X", "Y"))); } .validateXYData <- function(xyData) { return(.validateData(xyData, className = NULL, requiredCols = c("X", "Y"), requiredAttr = NULL, noFactorCols = c("X", "Y"), noNACols = c("X", "Y"), keyCols = NULL, numericCols = c("X", "Y"))); }
.onAttach <- function(...) { ver <- utils::packageVersion("bayesplot") packageStartupMessage("This is bayesplot version ", ver) packageStartupMessage("- Online documentation and vignettes at mc-stan.org/bayesplot") packageStartupMessage("- bayesplot theme set to bayesplot::theme_default()") packageStartupMessage(" * Does _not_ affect other ggplot2 plots") packageStartupMessage(" * See ?bayesplot_theme_set for details on theme setting") }
"spCopulaCoxph" <- function(formula, data, na.action, prediction=NULL, mcmc=list(nburn=3000, nsave=2000, nskip=0, ndisplay=500), prior=NULL, state=NULL, scale.designX=TRUE, Coordinates, DIST=NULL, Knots=NULL) { Call <- match.call(); indx <- match(c("formula", "data", "na.action", "truncation_time", "subject.num"), names(Call), nomatch=0) if (indx[1] ==0) stop("A formula argument is required"); temp <- Call[c(1,indx)] temp[[1L]] <- quote(stats::model.frame) special <- c("baseline", "frailtyprior", "truncation_time", "subject.num", "bspline") temp$formula <- if (missing(data)) terms(formula, special) else terms(formula, special, data = data) if (is.R()) m <- eval(temp, parent.frame()) else m <- eval(temp, sys.parent()) Terms <- attr(m, 'terms') if(any(names(m)=="(truncation_time)")){ truncation_time = m[,"(truncation_time)"] }else{ truncation_time = NULL } if(any(names(m)=="(subject.num)")){ subject.num = m[,"(subject.num)"] }else{ subject.num = NULL } Y <- model.extract(m, "response") if (!inherits(Y, "Surv")) stop("Response must be a survival object") baseline0 <- attr(Terms, "specials")$baseline frailtyprior0<- attr(Terms, "specials")$frailtyprior bspline0<- attr(Terms, "specials")$bspline if (length(frailtyprior0)) { temp <- survival::untangle.specials(Terms, 'frailtyprior', 1) dropfrail <- c(temp$terms) frail.terms <- m[[temp$vars]] }else{ dropfrail <- NULL frail.terms <- NULL; } if (length(baseline0)) { temp <- survival::untangle.specials(Terms, 'baseline', 1) dropXtf <- c(temp$terms) Xtf <- m[[temp$vars]] }else{ dropXtf <- NULL Xtf <- NULL } if (length(bspline0)) { temp <- survival::untangle.specials(Terms, 'bspline', 1) X.bs = NULL; n.bs = rep(0, length(temp$vars)); for(ii in 1:length(temp$vars)){ X.bs = cbind(X.bs, m[[temp$vars[ii]]]); n.bs[ii] = ncol(m[[temp$vars[ii]]]); } }else{ X.bs <- NULL; n.bs <- NULL; } dropx <- c(dropfrail, dropXtf) if (length(dropx)) { newTerms <- Terms[-dropx] if (is.R()) attr(newTerms, 'intercept') <- attr(Terms, 'intercept') } else newTerms <- Terms X <- model.matrix(newTerms, m); if (is.R()) { assign <- lapply(survival::attrassign(X, newTerms)[-1], function(x) x-1) xlevels <- .getXlevels(newTerms, m) contr.save <- attr(X, 'contrasts') }else { assign <- lapply(attr(X, 'assign')[-1], function(x) x -1) xvars <- as.character(attr(newTerms, 'variables')) xvars <- xvars[-attr(newTerms, 'response')] if (length(xvars) >0) { xlevels <- lapply(m[xvars], levels) xlevels <- xlevels[!unlist(lapply(xlevels, is.null))] if(length(xlevels) == 0) xlevels <- NULL } else xlevels <- NULL contr.save <- attr(X, 'contrasts') } adrop <- 0 Xatt <- attributes(X) xdrop <- Xatt$assign %in% adrop X <- X[, !xdrop, drop=FALSE] attr(X, "assign") <- Xatt$assign[!xdrop] n <- nrow(X) p <- ncol(X) if(p==0){ stop("covariate is required") X.scaled <- NULL; X1 = cbind(rep(1,n), X.scaled); }else{ if(scale.designX){ X.scaled <- scale(X); }else{ X.scaled <- scale(X, center=rep(0,p), scale=rep(1,p)); } X.center = attributes(X.scaled)$`scaled:center`; X.scale = attributes(X.scaled)$`scaled:scale`; X1 = cbind(rep(1,n), X.scaled); } t1 = Y[,1]; t2 = Y[,1]; type <- attr(Y, "type") exactsurv <- Y[,ncol(Y)] ==1 if (any(exactsurv)) { t1[exactsurv]=Y[exactsurv,1]; t2[exactsurv]=Y[exactsurv,1]; } if (type== 'counting') stop ("Invalid survival type") if (type=='interval') { intsurv <- Y[,3]==3; if (any(intsurv)){ t1[intsurv]=Y[intsurv,1]; t2[intsurv]=Y[intsurv,2]; } } delta = Y[,ncol(Y)]; if (!all(is.finite(Y))) { stop("Invalid survival times for this distribution") } else { if (type=='left') delta <- 2- delta; } if(is.null(DIST)){ DIST <- function(x, y) fields::rdist(x, y) } model.name <- "Spatial Copula Cox PH model with piecewise constant baseline hazards" if(sum(delta%in%c(0,1))!=n) stop("This function currently only supports right-censored data.") if(p==0){ s0 <- prediction$spred; if(ncol(s0)!=2) stop("Make sure that prediction$spred is a matrix with two columns.") if(is.null(s0)) s0=Coordinates npred = nrow(s0); xpred = cbind(rep(1,npred)); }else{ xpred <- prediction$xpred; s0 <- prediction$spred; if(is.null(xpred)){ xpred = X; s0 = Coordinates; } if(is.vector(xpred)) xpred=matrix(xpred, nrow=1); if(ncol(xpred)!=p) stop("Please make sure the number of columns for xpred equals the number of covariates!"); xpred = cbind(xpred); npred = nrow(xpred); if(nrow(s0)!=npred) stop("Error: nrow(xpred) is not equal to nrow(spred) in prediction"); for(i in 1:npred) xpred[i,] = (xpred[i,]-X.center)/X.scale; } s = Coordinates; if(is.null(s)) stop("please specify Coordinates for each subject"); if(nrow(s)!=n) stop("the number of coordinates should be equal to the sample size") dnn = DIST(s, s); if(min(dnn[row(dnn)!=col(dnn)])<=0) stop("each subject should have different Coordinates"); if(is.null(Knots)){ nknots = prior$nknots; if(is.null(nknots)) nknots=n; }else{ nknots = nrow(Knots); } if(is.null(Knots)){ if(nknots<n){ ss = as.matrix(fields::cover.design(s, nd=nknots, DIST=DIST)$design); }else{ ss = s; } }else{ ss = Knots; } dnm = DIST(s, ss); dmm = DIST(ss, ss); nblock=prior$nblock; if(is.null(nblock)) nblock=n; if(nblock==n){ s0tmp = s; Dtmp = DIST(s, s0tmp); idtmp = apply(Dtmp, 1, which.min); clustindx=diag(1,n, n); }else{ s0tmp = as.matrix(fields::cover.design(s, nd=nblock, DIST=DIST)$design); Dtmp = DIST(s, s0tmp); idtmp = apply(Dtmp, 1, which.min); nblock=length(table(idtmp)); idnames = as.numeric(names(table(idtmp))) clustindx=matrix(0, n, nblock); for(jj in 1:nblock){ clustindx[which(idtmp==idnames[jj]),jj] = 1; } } ds0n <- DIST(s, s0); ds0m <- DIST(ss, s0); Ds0tmps0 <- DIST(s0, s0tmp); idpred <- apply(Ds0tmps0, 1, which.min); ds0block <- matrix(0, n, npred); for(i in 1:n){ for(j in 1:npred){ ds0block[i,j] = (idtmp[i]==idpred[j])+0 } } tbase1 = t1; tbase2 = t2; deltabase = delta; Xbase.scaled = X.scaled; for(i in 1:n){ if(deltabase[i]==0) tbase2[i]=NA; if(deltabase[i]==2) tbase1[i]=NA; } fit0 <- survival::survreg(formula = survival::Surv(tbase1, tbase2, type="interval2")~Xbase.scaled, dist="exponential"); nburn <- mcmc$nburn; nsave <- mcmc$nsave; nskip <- mcmc$nskip; ndisplay <- mcmc$ndisplay; r0 <- prior$r0; if(is.null(r0)) r0 = 1; h0 <- prior$h0; if(is.null(h0)) h0 = as.vector( exp( -fit0$coefficients[1] ) ); v0 <- prior$v0; if(is.null(v0)) v0=0; vhat <- prior$vhat; if(is.null(vhat)) vhat <- as.vector( exp( -2*fit0$coefficients[1] )*fit0$var[1,1] ); beta0 <- prior$beta0; if(is.null(beta0)) beta0 <- rep(0,p); S0 <- prior$S0; if(is.null(S0)) S0=diag(1e10, p); S0inv <- solve(S0); Shat <- prior$Shat; if(is.null(Shat)) Shat <- as.matrix(fit0$var[c(2:(1+p)),c(2:(1+p))])/(fit0$scale)^2; M <- prior$M; if(is.null(M)) M <- 20; M1<- M+1; d <- prior$cutpoints; if(is.null(d)){ d = as.vector(quantile(t1, probs=seq(0,1,length=M1))); d = d[-1]; d[M] = Inf; } d <- c(0, d); if(!(M1==length(d))) stop("error: M is not equal to length(cutpoints)"); theta0 <- prior$theta0; if(is.null(theta0)) theta0 <- c(1.0, 1.0, 1.0, 1.0); spS0 <- prior$spS0; if(is.null(spS0)) spS0 <- diag(c(0.5,0.1)); h = c(0, rep(h0, M)); hcen=state$hcen; if(is.null(hcen)) hcen=h0; beta=state$beta; if(is.null(beta)) beta=as.vector( -fit0$coefficients[-1] ); theta = state$theta; if(is.null(theta)) theta <- c(0.98, 1); foo <- .Call("spCopulaCoxph", nburn_ = nburn, nsave_ = nsave, nskip_ = nskip, ndisplay_ = ndisplay, tobs_ = t1, delta_ = delta, X_=X.scaled, d_ = d, h_ = h, r0_ = r0, hcen_=hcen, h0_ = h0, v0_ = v0, vhat_ = vhat, beta_ = beta, beta0_ = beta0, S0inv_ = S0inv, Shat_=Shat, l0_ = round(min(1000,nburn/2)), adapter_ = (2.38)^2, xpred_ = as.matrix(xpred), ds0n_=ds0n, dnn_=dnn, theta_=theta, theta0_=theta0, spS0_=spS0, dnm_=dnm, dmm_=dmm, clustindx_=clustindx, ds0m_=ds0m, ds0block_=ds0block, PACKAGE = "spBayesSurv"); beta.scaled = matrix(foo$beta, p, nsave); beta.original = matrix(beta.scaled, p, nsave)/matrix(rep(X.scale, nsave), p, nsave); coeff1 <- c(apply(beta.original, 1, mean)); coeff2 <- c(apply(foo$theta, 1, mean)); coeff <- c(coeff1, coeff2); names(coeff) = c(colnames(X.scaled), "sill", "range"); output <- list(modelname=model.name, terms=m, coefficients=coeff, call=Call, prior=prior, mcmc=mcmc, n=n, p=p, Surv=survival::Surv(tbase1, tbase2, type="interval2"), X.scaled=X.scaled, X = X, beta = beta.original, beta.scaled = beta.scaled, h.scaled = foo$h, d.scaled = foo$d, cutpoints = foo$d[,1], hcen.scaled = foo$hcen, M=M, ratebeta = foo$ratebeta, ratehcen = foo$ratehcen, theta = foo$theta, ratebeta = foo$ratebeta, ratetheta = foo$ratetheta, rateh = foo$rateh, cpo = foo$cpo, Coordinates = s, Tpred = foo$Tpred, Zpred = foo$Zpred); class(output) <- c("spCopulaCoxph") output } "print.spCopulaCoxph" <- function (x, digits = max(3, getOption("digits") - 3), ...) { cat(x$modelname,"\nCall:\n", sep = "") print(x$call) cat("\nPosterior means for regression coefficients:\n") if(x$p>0){ print.default(format(x$coefficients[1:x$p], digits = digits), print.gap = 2, quote = FALSE) } cat("\nLPML:", sum(log(x$cpo))) cat("\nn=",x$n, "\n", sep="") invisible(x) } "plot.spCopulaCoxph" <- function(x, xnewdata, tgrid=NULL, CI=0.95, PLOT=TRUE, ...) { if(is.null(tgrid)) tgrid = seq(0.01, max(x$Surv[,1], na.rm=T), length.out=200) if(missing(xnewdata)) { stop("please specify xnewdata") }else{ rnames = row.names(xnewdata) m = x$terms Terms = attr(m, 'terms') baseline0 <- attr(Terms, "specials")$baseline frailtyprior0<- attr(Terms, "specials")$frailtyprior dropx <- NULL if (length(frailtyprior0)) { temp <- survival::untangle.specials(Terms, 'frailtyprior', 1) dropx <- c(dropx, temp$terms) frail.terms <- m[[temp$vars]] }else{ frail.terms <- NULL; } if (length(baseline0)) { temp <- survival::untangle.specials(Terms, 'baseline', 1) dropx <- c(dropx, temp$terms) Xtf <- m[[temp$vars]] }else{ Xtf <- NULL; } if (length(dropx)) { newTerms <- Terms[-dropx] if (is.R()) attr(newTerms, 'intercept') <- attr(Terms, 'intercept') } else newTerms <- Terms newTerms <- delete.response(newTerms) mnew <- model.frame(newTerms, xnewdata, na.action = na.omit, xlev = .getXlevels(newTerms, m)) Xnew <- model.matrix(newTerms, mnew); if (is.R()) { assign <- lapply(survival::attrassign(Xnew, newTerms)[-1], function(x) x-1) xlevels <- .getXlevels(newTerms, mnew) contr.save <- attr(Xnew, 'contrasts') }else { assign <- lapply(attr(Xnew, 'assign')[-1], function(x) x -1) xvars <- as.character(attr(newTerms, 'variables')) xvars <- xvars[-attr(newTerms, 'response')] if (length(xvars) >0) { xlevels <- lapply(mnew[xvars], levels) xlevels <- xlevels[!unlist(lapply(xlevels, is.null))] if(length(xlevels) == 0) xlevels <- NULL } else xlevels <- NULL contr.save <- attr(Xnew, 'contrasts') } adrop <- 0 Xatt <- attributes(Xnew) xdrop <- Xatt$assign %in% adrop Xnew <- Xnew[, !xdrop, drop=FALSE] attr(Xnew, "assign") <- Xatt$assign[!xdrop] xpred = Xnew if(ncol(xpred)!=x$p) stop("please make sure the number of columns matches!"); } X.center = attributes(x$X.scaled)$`scaled:center`; X.scale = attributes(x$X.scaled)$`scaled:scale`; xpred = cbind(xpred); nxpred = nrow(xpred); for(i in 1:nxpred) xpred[i,] = (xpred[i,]-X.center)/X.scale; betafitted = x$beta.scaled; estimates <- .Call("CoxPHplots", xpred, tgrid, betafitted, x$h.scaled, x$d.scaled, CI, PACKAGE = "spBayesSurv"); if(PLOT){ par(cex=1.5,mar=c(4.1,4.1,1,1),cex.lab=1.4,cex.axis=1.1) plot(tgrid, estimates$Shat[,1], "l", lwd=3, xlab="time", ylab="survival", xlim=c(0, max(tgrid)), ylim=c(0,1)); for(i in 1:nxpred){ polygon(x=c(rev(tgrid),tgrid), y=c(rev(estimates$Shatlow[,i]),estimates$Shatup[,i]), border=NA,col="lightgray"); } for(i in 1:nxpred){ lines(tgrid, estimates$Shat[,i], lty=i, lwd=3, col=i); } legend("topright", rnames, col = 1:nxpred, lty=1:nxpred, ...) } estimates$tgrid=tgrid; invisible(estimates) } "summary.spCopulaCoxph" <- function(object, CI.level=0.95, ...) { ans <- c(object[c("call", "modelname")]) ans$cpo <- object$cpo mat <- as.matrix(object$beta) coef.p <- object$coefficients[(1:object$p)]; coef.m <- apply(mat, 1, median) coef.sd <- apply(mat, 1, sd) limm <- apply(mat, 1, function(x) as.vector(quantile(x, probs=c((1-CI.level)/2, 1-(1-CI.level)/2))) ) coef.l <- limm[1,] coef.u <- limm[2,] coef.table <- cbind(coef.p, coef.m, coef.sd, coef.l , coef.u) dimnames(coef.table) <- list(names(coef.p), c("Mean", "Median", "Std. Dev.", paste(CI.level*100, "%CI-Low", sep=""), paste(CI.level*100, "%CI-Upp", sep=""))) ans$coeff <- coef.table mat <- as.matrix(object$theta) coef.p <- object$coefficients[-(1:object$p)]; coef.m <- apply(mat, 1, median) coef.sd <- apply(mat, 1, sd) limm <- apply(mat, 1, function(x) as.vector(quantile(x, probs=c((1-CI.level)/2, 1-(1-CI.level)/2))) ) coef.l <- limm[1,] coef.u <- limm[2,] coef.table <- cbind(coef.p, coef.m, coef.sd, coef.l , coef.u) dimnames(coef.table) <- list(names(coef.p), c("Mean", "Median", "Std. Dev.", paste(CI.level*100, "%CI-Low", sep=""), paste(CI.level*100, "%CI-Upp", sep=""))) ans$sill.range <- coef.table ans$n <- object$n ans$p <- object$p ans$LPML <- sum(log(object$cpo)) ans$ratebeta = object$ratebeta; ans$ratetheta = object$ratetheta; class(ans) <- "summary.spCopulaCoxph" return(ans) } "print.summary.spCopulaCoxph"<-function (x, digits = max(3, getOption("digits") - 3), ...) { cat(x$modelname,"\nCall:\n", sep = "") print(x$call) if(x$p>0){ cat("\nPosterior inference of regression coefficients\n") cat("(Adaptive M-H acceptance rate: ", x$ratebeta, "):\n", sep="") print.default(format(x$coeff, digits = digits), print.gap = 2, quote = FALSE) } cat("\nPosterior inference of spatial sill and range parameters\n") cat("(Adaptive M-H acceptance rate: ", x$ratetheta, "):\n", sep="") print.default(format(x$sill.range, digits = digits), print.gap = 2, quote = FALSE) cat("\nLog pseudo marginal likelihood: LPML=", x$LPML, sep="") cat("\nNumber of subjects: n=", x$n, "\n", sep="") invisible(x) }
Rcpp::sourceCpp("test-BSpline.cpp") x <- seq.int(0, 10, 0.02) inter_knots <- c(2.4, 3.5, 5.2, 8) bound_knots <- c(- 1, 12) degree <- 4 foo <- function(...) { mat <- bSpline(..., intercept = TRUE) imat <- ibs(..., intercept = TRUE) d1mat <- deriv(mat) d2mat <- deriv(d1mat) d3mat <- deriv(d2mat) list(basis = mat, integral = imat, d1 = d1mat, d2 = d2mat, d3 = d3mat, degree = attr(mat, "degree"), internal_knots = knots(mat), boundary_knots = attr(mat, "Boundary.knots")) } res <- foo(x = x, knots = inter_knots, degree = degree, Boundary.knots = bound_knots) res00 <- rcpp_bspline00(x, inter_knots, degree, bound_knots) expect_equivalent(res, res00) res01 <- rcpp_bspline01(x, inter_knots, degree, bound_knots) expect_equivalent(res, res01) res02 <- rcpp_bspline02(x, inter_knots, degree, bound_knots) expect_equivalent(res, res02) res03 <- rcpp_bspline03(x, inter_knots, degree, bound_knots) expect_equivalent(res, res03) res04 <- rcpp_bspline04(x, inter_knots, degree, bound_knots) expect_equivalent(res, res04) res05 <- rcpp_bspline05(x, inter_knots, degree, bound_knots) expect_equivalent(res, res05) res1 <- rcpp_bspline1(x, inter_knots, degree, bound_knots) expect_equivalent(res, res1) res2 <- rcpp_bspline2(x, 10, degree, bound_knots) res20 <- foo(x = x, degree = degree, df = 10, Boundary.knots = bound_knots) expect_equivalent(res20, res2) knot_seq <- sort(c(rep(bound_knots, each = degree + 1), inter_knots)) res31 <- rcpp_bspline3(x, degree, knot_seq) expect_equivalent(res, res31) knot_seq <- sort(c(seq.int(0, 10, 1), 1, rep(4, 3), rep(7, 2))) res32 <- rcpp_bspline3(x, degree, knot_seq) expect_equivalent( res32$basis, splines::splineDesign(knot_seq, x, ord = degree + 1, outer.ok = TRUE) ) expect_equivalent( res32$d1, splines::splineDesign(knot_seq, x, ord = degree + 1, outer.ok = TRUE, derivs = 1) ) expect_equivalent( res32$d2, splines::splineDesign(knot_seq, x, ord = degree + 1, outer.ok = TRUE, derivs = 2) ) res4 <- rcpp_bspline4(x, inter_knots, degree, bound_knots) expect_equivalent(res, res4) res5 <- rcpp_bspline5(x, inter_knots, degree, bound_knots) expect_equivalent(res, res5) res6 <- rcpp_bspline6(x, inter_knots, degree, bound_knots) expect_equivalent(res, res6)
test_that("dd_interaction works", { skip_on_os('solaris') skip_if_not(sf::sf_use_s2()) .act <- ds_dd_interaction(de_county, starts_with('pop_')) .exp <- c(0.307176832960713, 0.307176832960713, 0.307176832960713) expect_equal(.act, .exp, tolerance = 1e-6) }) test_that("dd_interaction .name works", { .act <- ds_dd_interaction(de_county, starts_with('pop_'), .name = 'special_name') expect_true('special_name' %in% names(.act)) }) test_that("dd_interaction .comp works", { skip_on_os('solaris') skip_if_not(sf::sf_use_s2()) .act <- ds_dd_interaction(de_county, starts_with('pop_'), .comp = TRUE) .exp <- c(0.0554361331858142, 0.173723023598303, 0.0780176761765964) expect_equal(.act, .exp, tolerance = 1e-6) })
get_facets <- function(plot_click) { is_panel_var <- grepl("panelvar", names(plot_click), fixed = TRUE) panelvars <- names(plot_click)[is_panel_var] facet_levels <- plot_click[is_panel_var] facet_vars <- plot_click$mapping[names(plot_click$mapping) %in% panelvars] facets <- list(levels = facet_levels, vars = facet_vars) facets } get_facet_characteristics <- function(built_plot) { facets_quos <- get_facet_quos(built_plot) facets_names <- names(facets_quos) plot_data <- built_plot$plot$data facets_data <- lapply(facets_quos, ggann_eval_facet, data = plot_data ) facets_out <- list() for (facet_name in facets_names) { facet_data <- facets_data[[facet_name]] if (!facet_name %in% names(plot_data)) { data_name <- match_facet_var( facet_name, facet_data, plot_data ) } else { data_name <- facet_name } facet_factor <- inherits(facets_data[[facet_name]], "factor") facet_list <- list(facet = list( facet_name = facet_name, data_name = data_name, facet_factor = facet_factor )) names(facet_list) <- facet_name facets_out <- c(facets_out, facet_list) } facets_out } correct_facets <- function(clicked_facets, facet_characteristics) { facets_out <- clicked_facets if (length(clicked_facets$vars) > 0) { for (panelvar in names(clicked_facets$vars)) { facet_name <- clicked_facets$vars[[panelvar]] facets_out$vars[[panelvar]] <- facet_characteristics[[facet_name]]$data_name facet_factor <- facet_characteristics[[facet_name]]$facet_factor if (isTRUE(facet_factor)) { facets_out$levels[[panelvar]] <- call( "factor", facets_out$levels[[panelvar]] ) } } } facets_out } ggann_eval_facet <- function(facet, data) { if (rlang::quo_is_symbol(facet)) { facet <- as.character(rlang::quo_get_expr(facet)) if (facet %in% names(data)) { out <- data[[facet]] } else { out <- NULL } return(out) } rlang::eval_tidy(facet, data) } get_facet_quos <- function(built_plot) { plot_facets <- list( built_plot$layout$facet_params$rows, built_plot$layout$facet_params$cols, built_plot$layout$facet_params$facets ) plot_facets <- purrr::compact(plot_facets) unlist(plot_facets) } match_facet_var <- function(facet, facet_data, plot_data) { matching_cols <- purrr::map_lgl( plot_data, function(x) all(as.character(x) == as.character(facet_data)) ) matching_cols <- matching_cols[matching_cols == TRUE] if (length(matching_cols) == 1) { matched_facet_var <- names(matching_cols) } else { var_between_brackets <- sub("^.*?\\((.*)\\)[^)]*$", "\\1", facet) if (!var_between_brackets %in% names(plot_data)) { var_before_comma <- sub(",.*", "\\1", var_between_brackets) if (!var_before_comma %in% names(plot_data)) { stop( "facet variable `", facet, "` could not be found in the plot data" ) } matched_facet_var <- var_before_comma } else { matched_facet_var <- var_between_brackets } } matched_facet_var }
context("Ex script 9/9 (isopod)") test_that("Isopod ex works",{ mix.filename <- system.file("extdata", "isopod_consumer.csv", package = "MixSIAR") mix <- load_mix_data(filename=mix.filename, iso_names=c("c16.4w3","c18.2w6","c18.3w3","c18.4w3","c20.4w6","c20.5w3","c22.5w3","c22.6w3"), factors="Site", fac_random=TRUE, fac_nested=FALSE, cont_effects=NULL) source.filename <- system.file("extdata", "isopod_sources.csv", package = "MixSIAR") source <- load_source_data(filename=source.filename, source_factors=NULL, conc_dep=FALSE, data_type="means", mix) discr.filename <- system.file("extdata", "isopod_discrimination.csv", package = "MixSIAR") discr <- load_discr_data(filename=discr.filename, mix) model_filename <- "MixSIAR_model.txt" resid_err <- TRUE process_err <- FALSE write_JAGS_model(model_filename, resid_err, process_err, mix, source) run <- list(chainLength=3, burn=1, thin=1, chains=3, calcDIC=TRUE) invisible(capture.output( jags.1 <- run_model(run, mix, source, discr, model_filename) )) expect_is(jags.1,"rjags") file.remove(model_filename) })
circle_points = function(center = c(0, 0), radius = 1, npoints = 360) { angles = seq(0, 2 * pi, length.out = npoints) return(tibble(x = center[1] + radius * cos(angles), y = center[2] + radius * sin(angles))) } width = 50 height = 94 / 2 key_height = 19 inner_key_width = 12 outer_key_width = 16 backboard_width = 6 backboard_offset = 4 neck_length = 0.5 hoop_radius = 0.75 hoop_center_y = backboard_offset + neck_length + hoop_radius three_point_radius = 23.75 three_point_side_radius = 22 three_point_side_height = 14 plot_court = function(court_theme = court_themes$dark, use_short_three = FALSE) { if (use_short_three) { three_point_radius = 22 three_point_side_height = 0 } court_points = tibble( x = c(width / 2, width / 2, -width / 2, -width / 2, width / 2), y = c(height, 0, 0, height, height), desc = "perimeter" ) court_points = bind_rows(court_points , tibble( x = c(outer_key_width / 2, outer_key_width / 2, -outer_key_width / 2, -outer_key_width / 2), y = c(0, key_height, key_height, 0), desc = "outer_key" )) court_points = bind_rows(court_points , tibble( x = c(-backboard_width / 2, backboard_width / 2), y = c(backboard_offset, backboard_offset), desc = "backboard" )) court_points = bind_rows(court_points , tibble( x = c(0, 0), y = c(backboard_offset, backboard_offset + neck_length), desc = "neck" )) foul_circle = circle_points(center = c(0, key_height), radius = inner_key_width / 2) foul_circle_top = filter(foul_circle, y > key_height) %>% mutate(desc = "foul_circle_top") foul_circle_bottom = filter(foul_circle, y < key_height) %>% mutate( angle = atan((y - key_height) / x) * 180 / pi, angle_group = floor((angle - 5.625) / 11.25), desc = paste0("foul_circle_bottom_", angle_group) ) %>% filter(angle_group %% 2 == 0) %>% select(x, y, desc) hoop = circle_points(center = c(0, hoop_center_y), radius = hoop_radius) %>% mutate(desc = "hoop") restricted = circle_points(center = c(0, hoop_center_y), radius = 4) %>% filter(y >= hoop_center_y) %>% mutate(desc = "restricted") three_point_circle = circle_points(center = c(0, hoop_center_y), radius = three_point_radius) %>% filter(y >= three_point_side_height, y >= hoop_center_y) three_point_line = tibble( x = c(three_point_side_radius, three_point_side_radius, three_point_circle$x, -three_point_side_radius, -three_point_side_radius), y = c(0, three_point_side_height, three_point_circle$y, three_point_side_height, 0), desc = "three_point_line" ) court_points = bind_rows( court_points, foul_circle_top, foul_circle_bottom, hoop, restricted, three_point_line ) court_points <<- court_points ggplot() + geom_path( data = court_points, aes(x = x, y = y, group = desc), color = court_theme$lines ) + coord_fixed(ylim = c(0, 35), xlim = c(-25, 25)) + theme_minimal(base_size = 22) + theme( text = element_text(color = court_theme$text), plot.background = element_rect(fill = court_theme$court, color = court_theme$court), panel.background = element_rect(fill = court_theme$court, color = court_theme$court), panel.grid = element_blank(), panel.border = element_blank(), axis.text = element_blank(), axis.title = element_blank(), axis.ticks = element_blank(), legend.background = element_rect(fill = court_theme$court, color = court_theme$court), legend.margin = margin(-1, 0, 0, 0, unit = "lines"), legend.position = "bottom", legend.key = element_blank(), legend.text = element_text(size = rel(1.0)) ) }
dataTOSTpairedClass <- R6::R6Class( "dataTOSTpairedClass", inherit = dataTOSTpairedBase, private = list( .init = function() { ci <- 100 - as.integer(self$options$alpha * 200) tt <- self$results$tost eqb <- self$results$eqb desc <- self$results$desc plots <- self$results$plots for (pair in self$options$pairs) { tt$setRow(rowKey=pair, list(i1=pair[[1]], i2=pair[[2]])) eqb$setRow(rowKey=pair, list(i1=pair[[1]], i2=pair[[2]])) desc$setRow(rowKey=pair, list(`name[1]`=pair[[1]], `name[2]`=pair[[2]])) plots$get(key=pair)$setTitle(paste(pair[[1]], '-', pair[[2]])) } eqb$getColumn('cil[cohen]')$setSuperTitle(jmvcore::format('{}% Confidence interval', ci)) eqb$getColumn('ciu[cohen]')$setSuperTitle(jmvcore::format('{}% Confidence interval', ci)) eqb$getColumn('cil[raw]')$setSuperTitle(jmvcore::format('{}% Confidence interval', ci)) eqb$getColumn('ciu[raw]')$setSuperTitle(jmvcore::format('{}% Confidence interval', ci)) }, .run = function() { tt <- self$results$tost eqb <- self$results$eqb desc <- self$results$desc plots <- self$results$plots for (pair in self$options$pairs) { if (is.null(pair[[1]])) next() if (is.null(pair[[2]])) next() i1 <- jmvcore::toNumeric(self$data[[pair[[1]] ]]) i2 <- jmvcore::toNumeric(self$data[[pair[[2]] ]]) data <- data.frame(i1=i1, i2=i2) data <- na.omit(data) n <- nrow(data) i1 <- data$i1 i2 <- data$i2 m1 <- base::mean(i1) m2 <- base::mean(i2) med1 <- stats::median(i1) med2 <- stats::median(i2) sd1 <- stats::sd(i1) sd2 <- stats::sd(i2) se1 <- sd1/sqrt(n) se2 <- sd2/sqrt(n) res <- t.test(i1, i2, paired=TRUE) t <- unname(res$statistic) p <- unname(res$p.value) df <- unname(res$parameter) alpha <- self$options$alpha low_eqbound <- self$options$low_eqbound high_eqbound <- self$options$high_eqbound low_eqbound_dz <- self$options$low_eqbound_dz high_eqbound_dz <- self$options$high_eqbound_dz r12 <- stats::cor(i1, i2) sdif<-sqrt(sd1^2+sd2^2-2*r12*sd1*sd2) if (low_eqbound_dz != -999999999 && low_eqbound_dz != -999999999) { low_eqbound <- low_eqbound_d * sdif high_eqbound <- high_eqbound_d * sdif } else if (self$options$eqbound_type == 'd') { low_eqbound_dz <- low_eqbound high_eqbound_dz <- high_eqbound low_eqbound <- low_eqbound * sdif high_eqbound <- high_eqbound * sdif } else { low_eqbound_dz <- low_eqbound / sdif high_eqbound_dz <- high_eqbound / sdif } se<-sdif/sqrt(n) t<-(m1-m2)/se degree_f<-n-1 pttest<-2*pt(abs(t), degree_f, lower.tail=FALSE) t1<-((m1-m2)-(low_eqbound_dz*sdif))/se p1<-pt(t1, degree_f, lower.tail=FALSE) t2<-((m1-m2)-(high_eqbound_dz*sdif))/se p2<-pt(t2, degree_f, lower.tail=TRUE) ttost<-ifelse(abs(t1) < abs(t2), t1, t2) LL90<-((m1-m2)-qt(1-alpha, degree_f)*se) UL90<-((m1-m2)+qt(1-alpha, degree_f)*se) ptost<-max(p1,p2) dif<-(m1-m2) LL95<-((m1-m2)-qt(1-(alpha/2), degree_f)*se) UL95<-((m1-m2)+qt(1-(alpha/2), degree_f)*se) tt$setRow(rowKey=pair, list( `t[0]`=t, `df[0]`=df, `p[0]`=p, `t[1]`=t2, `df[1]`=degree_f, `p[1]`=p2, `t[2]`=t1, `df[2]`=degree_f, `p[2]`=p1)) eqb$setRow(rowKey=pair, list( `low[raw]`=low_eqbound, `high[raw]`=high_eqbound, `cil[raw]`=LL90, `ciu[raw]`=UL90, `low[cohen]`=low_eqbound_dz, `high[cohen]`=high_eqbound_dz)) desc$setRow(rowKey=pair, list( `n[1]`=n, `m[1]`=m1, `med[1]`=med1, `sd[1]`=sd1, `se[1]`=se1, `n[2]`=n, `m[2]`=m2, `med[2]`=med2, `sd[2]`=sd2, `se[2]`=se2)) plot <- plots$get(key=pair) points <- data.frame( m=dif, cil=LL90, ciu=UL90, low=low_eqbound, high=high_eqbound, stringsAsFactors=FALSE) plot$setState(points) } }, .plot=function(image, ggtheme, theme, ...) { if (is.null(image$state)) return(FALSE) tostplot(image, ggtheme, theme) return(TRUE) }) )
UhligPenalty <- function(g, first, last, constrained, impulses, scales, pen){ func <- 0.0 q <- matrix(stereo(v=g)) for(k in first:last){ ik <- (impulses[k, , ]%*%q) / scales for(i in 1:length(constrained)){ if(constrained[i]<0){ value <- ik[-1.0*constrained[i]] }else{ value <- -1.0 * ik[constrained[i]] } if(value<0){ func <- func + value }else{ func <- func + pen * value } } } acc <- func return(acc) }
pandemic_stats <- function(object){ if (!is(object, "pandemicPredicted")) stop("Please use the output of the posterior_predict() function.") if(missing(object)) stop("object is a required argument. See help(pandemic_stats) for more information.") t = length(object$data[[1]]) ST_horizon = ncol(object$predictive_Short) LT_horizon = ncol(object$predictive_Long) longHorizon = ncol(methods::slot(object$fit,"sim")$fullPred$thousandLongPred) date_full <- as.Date(object$data$date[1]:(max(object$data$date) + longHorizon), origin = "1970-01-01") ST_predict <- data.frame( date = date_full[(t+1):(t+ST_horizon)], q2.5 = apply(object$predictive_Short,2,stats::quantile,.025), med = apply(object$predictive_Short,2,stats::median), q97.5 = apply(object$predictive_Short,2,stats::quantile,.975), mean = colMeans(object$predictive_Short)) row.names(ST_predict) <- NULL if(object$cases_type == "confirmed"){ cumulative_y = object$data$cases[t] } else{ cumulative_y = object$data$deaths[t] } if(cumulative_y > 1000){ lowquant <- apply(methods::slot(object$fit,"sim")$fullPred$thousandLongPred,2,stats::quantile,.025) medquant <- apply(methods::slot(object$fit,"sim")$fullPred$thousandLongPred,2,stats::median) highquant <- apply(methods::slot(object$fit,"sim")$fullPred$thousandLongPred,2,stats::quantile,.975) } else{ lowquant <- c(cumulative_y , apply(methods::slot(object$fit,"sim")$fullPred$thousandShortPred,2,stats::quantile,.025)) lowquant <- (lowquant - lag(lowquant, default = 0))[-1] medquant <- c(cumulative_y, apply(methods::slot(object$fit,"sim")$fullPred$thousandShortPred,2,stats::median)) medquant <- (medquant - lag(medquant,default = 0))[-1] highquant <- c(cumulative_y, apply(methods::slot(object$fit,"sim")$fullPred$thousandShortPred,2,stats::quantile,.975)) highquant <- (highquant - lag(highquant, default = 0))[-1] } TNC2.5 = sum(lowquant) + cumulative_y TNC50 = sum(medquant) + cumulative_y TNC97.5 = sum(highquant) + cumulative_y peak2.5 <- peak50 <- peak97.5 <- NULL end2.5 <- end50 <- end97.5 <- NULL index_season <-NULL if(!is.null(object$seasonal_effect)){ s_code <- seasonal_code(date_full, object$seasonal_effect) for (i in 1:length(s_code)){ index_aux <- which((seq(1,(t+longHorizon),1) - s_code[i]) %% 7 == 0) index_season<-c(index_aux, index_season) } index_season<-sort(index_season) } chain_mu <- cbind(object$pastMu, methods::slot(object$fit,"sim")$fullPred$thousandMus) mu50 <- apply(chain_mu, 2, stats::quantile, probs = 0.5) peak50 <- date_full[which.max(mu50)] q <- .99 med_cumulative <- apply(as.matrix(mu50),2,cumsum) med_percent<- med_cumulative / med_cumulative[t + longHorizon] med_end <- which(med_percent - q > 0)[1] end50 <- date_full[med_end] mu25 <- apply(chain_mu, 2, stats::quantile, probs = 0.025) mu975 <- apply(chain_mu, 2, stats::quantile, probs = .975) mu25_aux <- if(is.null(object$seasonal_effect)) mu25 else mu25[-index_season] posMaxq2.5 <- which.max(mu25_aux) aux <- if (is.null(object$seasonal_effect)) mu975 - mu25_aux[posMaxq2.5] else mu975[-index_season] - mu25_aux[posMaxq2.5] aux2 <- aux[ posMaxq2.5 : length(aux)] val <- ifelse( length(aux2[aux2 < 0]) > 0, min(aux2[aux2 > 0]), aux[length(aux)]) date_max <- which(aux == val) aux <- if(is.null(object$seasonal_effect)) mu975 - mu25_aux[posMaxq2.5] else mu975[-index_season] - mu25_aux[posMaxq2.5] aux2 <- aux[1:posMaxq2.5] val <- min(aux2[aux2>0]) date_min <- which(aux == val) date_full_aux <- if(is.null(object$seasonal_effect)) date_full else date_full[-index_season] peak2.5 <- date_full_aux[date_min] peak97.5 <- date_full_aux[date_max] low_cumulative <- apply(as.matrix(mu25),2,cumsum) low_percent <- low_cumulative / low_cumulative[t + longHorizon] low_end <- which(low_percent - q > 0)[1] end2.5 <- date_full[low_end] high_cumulative <- apply(as.matrix(mu975),2,cumsum) high_percent <- high_cumulative / high_cumulative[t + longHorizon] high_end <- which( high_percent - q > 0)[1] end97.5 <- date_full[high_end] LT_predict <- data.frame( date = date_full[(t+1):(t+LT_horizon)], q2.5 = lowquant[1:LT_horizon], med = medquant[1:LT_horizon], q97.5 = highquant[1:LT_horizon], mean = colMeans(object$predictive_Long)) row.names(LT_predict) <- NULL LT_summary <- list(total_cases_LB = TNC2.5, total_cases_med = TNC50, total_cases_UB = TNC97.5, peak_date_LB = peak2.5 , peak_date_med = peak50 , peak_date_UB = peak97.5, end_date_LB = end2.5, end_date_med = end50, end_date_UB = end97.5) muplot <- data.frame(date = date_full[1:(t+LT_horizon)], mu = mu50[1:(t+LT_horizon)]) row.names(muplot) <-NULL dataplot <- list(data = object$data, location = object$location, case_type = object$cases_type) output <- list( data = dataplot, ST_predict = ST_predict, LT_predict = LT_predict, LT_summary = LT_summary, mu = muplot ) class(output) = "pandemicStats" return(output) }