code
stringlengths
1
13.8M
isDictionaryLoaded <- function(){ options("loadedDictionary" = function(){return(exists(".loadedDictionary"))}) return(options()$loadedDictionary()) }
fish.kent <- function(x, logged = FALSE) { n <- dim(x)[1] estim <- Rfast::vmf.mle(x) k <- estim$kappa mu <- - estim$mu mu[1] <- 1 + mu[1] i3 <- diag(3) P <- i3 - tcrossprod(mu)/mu[1] y <- tcrossprod(x, P)[, 2:3] lam <- eigen( crossprod(y) )$values/n rat <- besselI(k, 0.5, expon.scaled = TRUE)/besselI(k, 2.5, expon.scaled = TRUE) Ta <- n * (k/2)^2 * rat * (lam[1] - lam[2])^2 pvalue <- pchisq(Ta, 2, lower.tail = FALSE, log.p = logged) res <- c(Ta, pvalue) names(res) <- c("test", "p-value") res }
binomGraphs <- function(bound,region="below",size=100,prob=0.5,graph=TRUE, xlab="x") { if (!is.numeric(bound)) stop("Specify one or two numerical boundaries") below <- grepl("^be[lf]",region,perl=TRUE) above <- grepl("^a[bf]",region,perl=TRUE) between <- grepl("^bet|^in",region,perl=TRUE) outside <- grepl("^out",region,perl=TRUE) if (length(bound)==1 & !(below | above)) stop("Specify region=\"below\" or region=\"above\"") if (length(bound)==2 & !(between | outside)) stop("Specify region=\"between\" or region=\"outside\"") if (length(bound)>2) stop("Specify one or two numerical boundaries") if (length(bound)==2 & bound[1]>bound[2]) bound <- rev(bound) sd <- sqrt(size*prob*(1-prob)) if (below) { area <- pbinom(bound,size=size,prob=prob) if (graph) { upper <- ceiling(max(qbinom(.9999,size=size,prob=prob),bound+0.1*sd)) lower <- floor(min(qbinom(0.0001,size=size,prob=prob),bound-0.1*sd)) nvals <- lower:upper Shading <- ifelse(nvals <= bound,"lightblue",NA) plot(nvals,dbinom(nvals,size=size,prob=prob),type="h",col=NA,axes=FALSE, xlab=xlab,ylab="p(x)",xlim=c(lower-0.5,upper+0.5), main=paste("binom(",size,",",prob,") Distribution:\nShaded Area = ",round(area,3),sep="")) rect(nvals-0.5,rep(0,times=size+1),nvals+0.5,dbinom(nvals,size=size,prob=prob), col=Shading,border="black") axis(2) places <- c(lower,floor(bound),upper) axis(1,at=places,labels=c("",as.character(places[2]),"")) } } if (above) { area <- pbinom(bound,size=size,prob=prob,lower.tail=FALSE) if (graph) { upper <- ceiling(max(qbinom(.9999,size=size,prob=prob),bound+0.1*sd)) lower <- floor(min(qbinom(0.0001,size=size,prob=prob),bound-0.1*sd)) nvals <- lower:upper Shading <- ifelse(nvals > bound,"lightblue",NA) plot(nvals,dbinom(nvals,size=size,prob=prob),type="h",col=NA,axes=FALSE, xlab=xlab,ylab="p(x)",xlim=c(lower-0.5,upper+0.5), main=paste("binom(",size,",",prob,") Distribution:\nShaded Area = ",round(area,3),sep="")) rect(nvals-0.5,rep(0,times=size+1),nvals+0.5,dbinom(nvals,size=size,prob=prob), col=Shading,border="black") axis(2) places <- c(lower,floor(bound)+1,upper) axis(1,at=places,labels=c("",as.character(places[2]),"")) } } if (between) { area <- pbinom(bound[2],size=size,prob=prob)-pbinom(bound[1]-1,size=size,prob=prob) if (graph) { upper <- ceiling(max(qbinom(.9999,size=size,prob=prob),bound+0.1*sd)) lower <- floor(min(qbinom(0.0001,size=size,prob=prob),bound-0.1*sd)) nvals <- lower:upper Shading <- ifelse((bound[1] <= nvals & nvals <= bound[2]),"lightblue",NA) plot(nvals,dbinom(nvals,size=size,prob=prob),type="h",col=NA,axes=FALSE, xlab=xlab,ylab="p(x)",xlim=c(lower-0.5,upper+0.5), main=paste("binom(",size,",",prob,") Distribution:\nShaded Area = ",round(area,3),sep="")) rect(nvals-0.5,rep(0,times=size+1),nvals+0.5,dbinom(nvals,size=size,prob=prob), col=Shading,border="black") axis(2) places <- c(lower,floor(bound[1]),floor(bound[2]),upper) axis(1,at=places,labels=c("",as.character(places[2:3]),"")) } } if (outside) { area <- pbinom(bound[2],size=size,prob=prob,lower.tail=FALSE)+pbinom(bound[1]-1,size=size,prob=prob) if (graph) { upper <- ceiling(max(qbinom(.9999,size=size,prob=prob),bound+0.1*sd)) lower <- floor(min(qbinom(0.0001,size=size,prob=prob),bound-0.1*sd)) nvals <- lower:upper Shading <- ifelse(bound[1] <= nvals & nvals <= bound[2],NA,"lightblue") plot(nvals,dbinom(nvals,size=size,prob=prob),type="h",col=NA,axes=FALSE, xlab=xlab,ylab="p(x)",xlim=c(lower-0.5,upper+0.5), main=paste("binom(",size,",",prob,") Distribution:\nShaded Area = ",round(area,3),sep="")) rect(nvals-0.5,rep(0,times=size+1),nvals+0.5,dbinom(nvals,size=size,prob=prob), col=Shading,border="black") axis(2) places <- c(lower,floor(bound[1])-1,floor(bound[2])+1,upper) axis(1,at=places,labels=c("",as.character(places[2:3]),"")) } } }
Dunnetts.K.fcn.to.integrate.1 <- function (s, d, n, df, k, rho) { arg.mat <- cbind.no.warn(s = as.vector(s), d = as.vector(d), n = as.vector(n), df = as.vector(df), k = as.vector(k), rho = as.vector(rho)) for (i in c("s", "d", "n", "df", "k", "rho")) assign(i, arg.mat[, i]) N <- length(s) ret.val <- numeric(N) for (i in 1:N) { ret.val[i] <- Dunnetts.K.F1(d[i] * s[i], k[i], rho[i]) * dchi(sqrt(df[i]) * s[i], df[i]) * sqrt(df[i]) } ret.val }
fit_MRMC_casewise<- function( dataList, DrawCurve = FALSE, type_to_be_passed_into_plot="p", verbose = TRUE, print_CI_of_AUC = TRUE, PreciseLogLikelihood = FALSE, summary =TRUE, dataList.Name = "", prior=1, ModifiedPoisson=TRUE, mesh.for.drawing.curve=10000, significantLevel = 0.7, cha = 1, war = floor(ite/5), ite = 10000, dig = 3, see = 1234569, Null.Hypothesis=FALSE, prototype = FALSE, model_reparametrized =FALSE, Model_MRMC_non_hierarchical = TRUE, ww=-0.81, www =1, mm=0.65, mmm=1, vv=5.31, vvv=1, zz= 1.55, zzz=1, ... ){ M <- dataList$M scr <- system.file("extdata", "Model_MRMC_Multinomial_casewise.stan", package="BayesianFROC") scrr <- system.file("extdata", "Model_MRMC_Multinomial_casewise.rds", package="BayesianFROC") data <-metadata_to_fit_MRMC_casewise(dataList,ModifiedPoisson) data <- c(data, prior = prior, PreciseLogLikelihood=PreciseLogLikelihood, ww = ww, www = www, mm = mm, mmm = mmm, vv = vv, vvv = vvv, zz = zz, zzz = zzz, prototype=prototype ) m<-data$m ;S<-data$S; NL<-data$NL;NI<-data$NI;c<-data$c;q<-data$q; h<-data$h; f<-data$f; hh<-data$hh; hhN<-data$hhN; ff<-data$ff;ffN<-data$ffN; harray<-data$harray; farray<-data$farray; hharray<-data$hharray; ffarray<-data$ffarray; hharrayN<-data$hharrayN; ffarrayN<-data$ffarrayN; C<-as.integer(data$C) M<-as.integer(data$M) N<-as.integer(data$N) Q<-as.integer(data$Q) NI_deseased <- data$NI_deseased if (summary==FALSE)message("\n* Now, the Hamiltonian Monte Carlo simulation is running...") rstan_options(auto_write = TRUE) if(scrr=="")message("Now, the Stan file is being compiled and it tooks a few minuites, wait ...") if(!(scrr==""))message("Already, the Stan file has been compiled. But...Darn it!") scr <- rstan::stan_model(scr) init_fun <- function(...) list( w=array(0,c(NI_deseased,M,Q)), dz =array(1,c(C-1,NI_deseased,M,Q)), modalityID_dummy_array_slop_mu =array(1,c(NI_deseased,M,Q)), readerID_dummy_array_slop_mu =array(1,c(NI_deseased,M,Q)), caseID_dummy_array_slop_mu =array(1,c(NI_deseased,M,Q)), ground_v =1, modalityID_dummy_array_slop_v =array(1,c(NI_deseased,M,Q)), readerID_dummy_array_slop_v =array(1,c(NI_deseased,M,Q)), caseID_dummy_array_slop_v =array(1,c(NI_deseased,M,Q)) ) invisible(utils::capture.output( fit <- rstan::sampling( init = init_fun, object= scr, data=data, verbose = FALSE, seed=see, chains=cha, warmup=war, iter=ite , control = list(adapt_delta = 0.9999999, max_treedepth = 15),... ) )) convergence <- ConfirmConvergence(fit) fit.new.class <- methods::as(fit,"stanfitExtended") fit.new.class@metadata <-data fit.new.class@dataList <-dataList fit.new.class@studyDesign <- "MRMC" fit.new.class@PreciseLogLikelihood <- PreciseLogLikelihood fit.new.class@ModifiedPoisson <- ModifiedPoisson if(PreciseLogLikelihood==TRUE) {fit.new.class@WAIC <- waic(fit,dig,summary=FALSE)} fit.new.class@convergence <- convergence fit.new.class@prototype <- prototype if ( dataList.Name=="" ) dataList.Name <- deparse(substitute(dataList)) [email protected] <- dataList.Name e <- extract(fit) p.value <- mean(e$p_value_logicals) fit.new.class@posterior_predictive_pvalue_for_chi_square_goodness_of_fit <- p.value invisible(fit.new.class) }
`[.index0` <- function(x, i, j, ...) { if (!missing(i)) i <- i + 1 if (!missing(j)) j <- j + 1 as.index0(NextMethod()) } `[<-.index0` <- function(x, i, j, ..., value) { if (!missing(i)) i <- i + 1 if (!missing(j)) j <- j + 1 as.index0(NextMethod()) } as.index0 <- function(x) { class(x) <- union(class(x), 'index0') x } as.index1 <- function(x) { class(x) <- setdiff(class(x), 'index0') x } is.index0 <- function(x) { inherits(x, 'index0') } index_from_0 <- as.index0 print.index0 <- function(x, ...) { print(as.index1(x)) cat('indexed from 0\n') invisible(x) }
tmp_02_save <- tempfile() tmp_02_dump <- tempfile() tmp_03_save <- tempfile() tmp_03_dump <- tempfile() teardown(unlink(c(tmp_02_save, tmp_02_dump, tmp_03_save, tmp_03_dump), recursive = TRUE)) test_that("default invalidValueTreatment attribute is exported correctly for linear models", { lm_model_0 <- lm(Sepal.Length ~ ., data = iris[, -5]) lm_model_1 <- pmml(lm_model_0) ms <- xmlToList(lm_model_1)$RegressionModel$MiningSchema expect_equal(unlist(ms), c( "Sepal.Length", "predicted", "returnInvalid", "Sepal.Width", "active", "returnInvalid", "Petal.Length", "active", "returnInvalid", "Petal.Width", "active", "returnInvalid" )) }) test_that("invalidValueTreatment attribute is exported correctly for xgboost models", { skip_if_not_installed("xgboost") library(xgboost) data(agaricus.train, package = "xgboost") train <- agaricus.train invisible(capture.output(model_fit <- xgboost( data = train$data, label = train$label, max_depth = 2, eta = 1, nthread = 2, nrounds = 2, objective = "binary:logistic", save_name = tmp_02_save ))) xgb.dump(model_fit, tmp_02_dump) model_pmml <- pmml( model = model_fit, input_feature_names = colnames(train$data), output_label_name = "f", output_categories = c("0", "1"), xgb_dump_file = tmp_02_dump ) ms2 <- unlist(xmlToList(model_pmml)$MiningModel$MiningSchema) expect_equal(ms2, c( "odor", "active", "returnInvalid", "stalk-root", "active", "returnInvalid", "spore-print-color", "active", "returnInvalid", "f", "predicted", "returnInvalid" )) ms3 <- unlist(xmlToList(model_pmml)$MiningModel$Segmentation[[2]]$MiningSchema) expect_equal(ms3, c( "odor", "active", "asIs", "stalk-root", "active", "asIs", "spore-print-color", "active", "asIs", "f", "predicted", "asIs" )) ms4 <- unlist(xmlToList(model_pmml)$MiningModel$Segmentation[[5]]$MiningSchema) expect_equal(ms4, c( "odor", "active", "asIs", "stalk-root", "active", "asIs", "spore-print-color", "active", "asIs", "f", "predicted", "asIs" )) ms5 <- unlist(xmlToList(model_pmml)$MiningModel$Segmentation[[8]]$MiningSchema) expect_equal(ms5, c( "predictedValueTree0", "active", "continuous", "asIs", "predictedValueTree1", "active", "continuous", "asIs" )) model_pmml_2 <- pmml( model = model_fit, input_feature_names = colnames(train$data), output_label_name = "f", output_categories = c("0", "1"), xgb_dump_file = tmp_02_dump, parent_invalid_value_treatment = "returnInvalid", child_invalid_value_treatment = "returnInvalid" ) ms22 <- xmlToList(model_pmml_2)$MiningModel$MiningSchema expect_equal(unlist(ms22), c( "odor", "active", "returnInvalid", "stalk-root", "active", "returnInvalid", "spore-print-color", "active", "returnInvalid", "f", "predicted", "returnInvalid" )) ms23 <- unlist(xmlToList(model_pmml_2)$MiningModel$Segmentation[[2]]$MiningSchema) expect_equal(ms23, c( "odor", "active", "returnInvalid", "stalk-root", "active", "returnInvalid", "spore-print-color", "active", "returnInvalid", "f", "predicted", "returnInvalid" )) ms24 <- unlist(xmlToList(model_pmml_2)$MiningModel$Segmentation[[5]]$MiningSchema) expect_equal(ms24, c( "odor", "active", "returnInvalid", "stalk-root", "active", "returnInvalid", "spore-print-color", "active", "returnInvalid", "f", "predicted", "returnInvalid" )) ms25 <- unlist(xmlToList(model_pmml_2)$MiningModel$Segmentation[[8]]$MiningSchema) expect_equal(ms25, c( "predictedValueTree0", "active", "continuous", "returnInvalid", "predictedValueTree1", "active", "continuous", "returnInvalid" )) model_pmml_3 <- pmml( model = model_fit, input_feature_names = colnames(train$data), output_label_name = "f", output_categories = c("0", "1"), xgb_dump_file = tmp_02_dump, parent_invalid_value_treatment = "asIs" ) ms32 <- xmlToList(model_pmml_3)$MiningModel$MiningSchema expect_equal(unlist(ms32), c( "odor", "active", "asIs", "stalk-root", "active", "asIs", "spore-print-color", "active", "asIs", "f", "predicted", "asIs" )) ms33 <- unlist(xmlToList(model_pmml_3)$MiningModel$Segmentation[[2]]$MiningSchema) expect_equal(ms33, c( "odor", "active", "asIs", "stalk-root", "active", "asIs", "spore-print-color", "active", "asIs", "f", "predicted", "asIs" )) ms34 <- unlist(xmlToList(model_pmml_3)$MiningModel$Segmentation[[5]]$MiningSchema) expect_equal(ms34, c( "odor", "active", "asIs", "stalk-root", "active", "asIs", "spore-print-color", "active", "asIs", "f", "predicted", "asIs" )) ms35 <- unlist(xmlToList(model_pmml_3)$MiningModel$Segmentation[[8]]$MiningSchema) expect_equal(ms35, c( "predictedValueTree0", "active", "continuous", "asIs", "predictedValueTree1", "active", "continuous", "asIs" )) }) test_that("invalidValueTreatment attribute is exported correctly for randomForest models", { skip_if_not_installed("randomForest") require("randomForest") rf_fit <- randomForest(Species ~ ., data = iris, ntree = 3) rf_fit_pmml_1 <- pmml(rf_fit) expect_equal( unlist(xmlToList(rf_fit_pmml_1)$MiningModel$MiningSchema), c( "Species", "predicted", "returnInvalid", "Sepal.Length", "active", "returnInvalid", "Sepal.Width", "active", "returnInvalid", "Petal.Length", "active", "returnInvalid", "Petal.Width", "active", "returnInvalid" ) ) expect_equal( unlist(xmlToList(rf_fit_pmml_1)$MiningModel$Segmentation[[2]]$MiningSchema), c( "Species", "predicted", "asIs", "Sepal.Length", "active", "asIs", "Sepal.Width", "active", "asIs", "Petal.Length", "active", "asIs", "Petal.Width", "active", "asIs" ) ) expect_equal( unlist(xmlToList(rf_fit_pmml_1)$MiningModel$Segmentation[[5]]$MiningSchema), c( "Species", "predicted", "asIs", "Sepal.Length", "active", "asIs", "Sepal.Width", "active", "asIs", "Petal.Length", "active", "asIs", "Petal.Width", "active", "asIs" ) ) expect_equal( unlist(xmlToList(rf_fit_pmml_1)$MiningModel$Segmentation[[8]]$MiningSchema), c( "Species", "predicted", "asIs", "Sepal.Length", "active", "asIs", "Sepal.Width", "active", "asIs", "Petal.Length", "active", "asIs", "Petal.Width", "active", "asIs" ) ) rf_fit_pmml_2 <- pmml(rf_fit, parent_invalid_value_treatment = "returnInvalid", child_invalid_value_treatment = "returnInvalid" ) expect_equal( unlist(xmlToList(rf_fit_pmml_2)$MiningModel$MiningSchema), c( "Species", "predicted", "returnInvalid", "Sepal.Length", "active", "returnInvalid", "Sepal.Width", "active", "returnInvalid", "Petal.Length", "active", "returnInvalid", "Petal.Width", "active", "returnInvalid" ) ) expect_equal( unlist(xmlToList(rf_fit_pmml_2)$MiningModel$Segmentation[[2]]$MiningSchema), c( "Species", "predicted", "returnInvalid", "Sepal.Length", "active", "returnInvalid", "Sepal.Width", "active", "returnInvalid", "Petal.Length", "active", "returnInvalid", "Petal.Width", "active", "returnInvalid" ) ) expect_equal( unlist(xmlToList(rf_fit_pmml_2)$MiningModel$Segmentation[[5]]$MiningSchema), c( "Species", "predicted", "returnInvalid", "Sepal.Length", "active", "returnInvalid", "Sepal.Width", "active", "returnInvalid", "Petal.Length", "active", "returnInvalid", "Petal.Width", "active", "returnInvalid" ) ) expect_equal( unlist(xmlToList(rf_fit_pmml_2)$MiningModel$Segmentation[[8]]$MiningSchema), c( "Species", "predicted", "returnInvalid", "Sepal.Length", "active", "returnInvalid", "Sepal.Width", "active", "returnInvalid", "Petal.Length", "active", "returnInvalid", "Petal.Width", "active", "returnInvalid" ) ) rf_fit_pmml_3 <- pmml(rf_fit, parent_invalid_value_treatment = "asIs" ) expect_equal( unlist(xmlToList(rf_fit_pmml_3)$MiningModel$MiningSchema), c( "Species", "predicted", "asIs", "Sepal.Length", "active", "asIs", "Sepal.Width", "active", "asIs", "Petal.Length", "active", "asIs", "Petal.Width", "active", "asIs" ) ) expect_equal( unlist(xmlToList(rf_fit_pmml_3)$MiningModel$Segmentation[[2]]$MiningSchema), c( "Species", "predicted", "asIs", "Sepal.Length", "active", "asIs", "Sepal.Width", "active", "asIs", "Petal.Length", "active", "asIs", "Petal.Width", "active", "asIs" ) ) expect_equal( unlist(xmlToList(rf_fit_pmml_3)$MiningModel$Segmentation[[5]]$MiningSchema), c( "Species", "predicted", "asIs", "Sepal.Length", "active", "asIs", "Sepal.Width", "active", "asIs", "Petal.Length", "active", "asIs", "Petal.Width", "active", "asIs" ) ) expect_equal( unlist(xmlToList(rf_fit_pmml_3)$MiningModel$Segmentation[[8]]$MiningSchema), c( "Species", "predicted", "asIs", "Sepal.Length", "active", "asIs", "Sepal.Width", "active", "asIs", "Petal.Length", "active", "asIs", "Petal.Width", "active", "asIs" ) ) }) test_that("error is thrown if invalidValueTreatment argument is incorrect", { skip_if_not_installed("xgboost") library(xgboost) data(agaricus.train, package = "xgboost") train <- agaricus.train invisible(capture.output(model_fit_2 <- xgboost( data = train$data, label = train$label, max_depth = 2, eta = 1, nthread = 2, nrounds = 2, objective = "binary:logistic", save_name = tmp_03_save ))) xgb.dump(model_fit_2, tmp_03_dump) model_pmml_5 <- pmml( model = model_fit_2, input_feature_names = colnames(train$data), output_label_name = "f", output_categories = c("0", "1"), xgb_dump_file = tmp_03_dump ) expect_error( pmml( model = model_fit_2, input_feature_names = colnames(train$data), output_label_name = "f", output_categories = c("0", "1"), xgb_dump_file = tmp_03_dump, parent_invalid_value_treatment = "foobar" ), "\"foobar\" is not a valid enumeration value for parent_invalid_value_treatment. Use one of the following: returnInvalid, asIs, asMissing." ) expect_error( pmml( model = model_fit_2, input_feature_names = colnames(train$data), output_label_name = "f", output_categories = c("0", "1"), xgb_dump_file = tmp_03_dump, child_invalid_value_treatment = "asis" ), "\"asis\" is not a valid enumeration value for child_invalid_value_treatment. Use one of the following: returnInvalid, asIs, asMissing." ) })
context("spark apply bundle") sc <- testthat_spark_connection() test_that("'spark_apply_bundle' can `worker_spark_apply_unbundle`", { bundlePath <- spark_apply_bundle() unbundlePath <- worker_spark_apply_unbundle(bundlePath, tempdir(), "package") unlink(bundlePath, recursive = TRUE) unlink(unbundlePath, recursive = TRUE) succeed() }) available_packages_mock <- function() { packages_sample <- dir( getwd(), recursive = TRUE, pattern = "packages-sample.rds", full.names = TRUE ) as.matrix( readRDS(file = packages_sample) ) } test_that("'spark_apply_packages' uses different names for different packages", { with_mock( `available.packages` = available_packages_mock, expect_true( length(spark_apply_packages("purrr")) > 0 ) ) }) test_that("'spark_apply_bundle_file' uses different names for different packages", { purrr_file <- spark_apply_bundle_file(spark_apply_packages("purrr"), tempdir()) tidyr_file <- spark_apply_bundle_file(spark_apply_packages("tidyr"), tempdir()) expect_true(purrr_file != tidyr_file) })
big_prodMat <- function(X, A.col, ind.row = rows_along(X), ind.col = cols_along(X), ncores = 1, block.size = block_size(nrow(X), ncores), center = NULL, scale = NULL) { check_args() assert_lengths(ind.col, rows_along(A.col)) if (length(ind.row) == 0 || length(ind.col) == 0) return(matrix(0, length(ind.row), ncol(A.col))) if (!is.null(scale)) { assert_lengths(scale, ind.col) A.col <- A.col / as_vec(scale) } if (!is.null(center)) { assert_lengths(center, ind.col) center2 <- crossprod(as_vec(center), A.col) } res <- big_parallelize(X, function(X, ind, A.col, ind.row, ind.col, block.size) { prod_FBM_block_mat(X, A.col[ind, , drop = FALSE], ind.row, ind.col[ind], block.size) }, p.combine = plus, ind = seq_along(ind.col), ncores = ncores, A.col = A.col, ind.row = ind.row, ind.col = ind.col, block.size = block.size) `if`(is.null(center), res, centering(res, center2)) } setMethod("%*%", signature(x = "FBM", y = "matrix"), function(x, y) prod_FBM_mat(x, y)) setMethod("%*%", signature(x = "matrix", y = "FBM"), function(x, y) prod_mat_FBM(x, y)) big_cprodMat <- function(X, A.row, ind.row = rows_along(X), ind.col = cols_along(X), ncores = 1, block.size = block_size(nrow(X), ncores), center = NULL, scale = NULL) { check_args() assert_lengths(ind.row, rows_along(A.row)) if (length(ind.row) == 0 || length(ind.col) == 0) return(matrix(0, length(ind.col), ncol(A.row))) if (!is.null(scale)) { assert_lengths(scale, ind.col) scale <- as_vec(scale) } if (!is.null(center)) { assert_lengths(center, ind.col) center <- as_vec(center) } res <- big_parallelize(X, function(X, ind, A.row, ind.row, block.size) { cprod_FBM_block_mat(X, A.row, ind.row, ind, block.size) }, p.combine = rbind, ind = ind.col, ncores = ncores, A.row = A.row, ind.row = ind.row, block.size = block.size) if (!is.null(center)) res <- res - tcrossprod(center, colSums(A.row)) if (!is.null(scale)) res <- res / scale res } setMethod("crossprod", signature(x = "FBM", y = "matrix"), function(x, y) crossprod_FBM_mat(x, y)) setMethod("tcrossprod", signature(x = "FBM", y = "matrix"), function(x, y) tcrossprod_FBM_mat(x, y)) setMethod("crossprod", signature(x = "matrix", y = "FBM"), function(x, y) crossprod_mat_FBM(x, y)) setMethod("tcrossprod", signature(x = "matrix", y = "FBM"), function(x, y) tcrossprod_mat_FBM(x, y))
library(leafdown) library(shiny) context("Test 'add_data'") test_that("Add data correctly", { my_leafdown <- init_leafdown() data <- my_leafdown$curr_data data$y <- 1:nrow(data) my_leafdown$add_data(data) expect_true(identical(data, my_leafdown$curr_data)) }) test_that("Add 'Null' as data throws error", { my_leafdown <- init_leafdown() expect_error(my_leafdown$add_data(NULL), "The given data must be a data.frame") }) test_that("Add empty List as data throws error", { my_leafdown <- init_leafdown() expect_error(my_leafdown$add_data(data.frame()), "You cannot remove columns from the existing meta-data. Only add to it") }) test_that("Changed values in data throws error", { my_leafdown <- init_leafdown() data <- my_leafdown$curr_data col <- 1 row <- 42 data[row, col] <- NA expect_error(my_leafdown$add_data(data), "You cannot change the existing meta-data. Only add to it") }) test_that("Missing columns in data throws error", { my_leafdown <- init_leafdown() data <- my_leafdown$curr_data col <- floor(runif(1, min=1, max=dim(data)[2])) data <- data[, -col] expect_error(my_leafdown$add_data(data), "You cannot remove columns from the existing meta-data. Only add to it") }) test_that("Missing row in data throws error", { my_leafdown <- init_leafdown() data <- my_leafdown$curr_data row <- floor(runif(1, min=1, max=dim(data)[1])) data <- data[-row, ] expect_error(my_leafdown$add_data(data), "You cannot change the existing meta-data. Only add to it") }) test_that("Reordering Data throws correct error", { my_leafdown <- init_leafdown() data <- my_leafdown$curr_data data$y <- nrow(data):1 data <- data[order(data$y), ] expect_error(my_leafdown$add_data(data), "Please do not reorder the data. Use left_joins to add the data") })
options(sd_num_thread=1L) x <- c("ca", "abc", "cba") expect_equal(stringsimmatrix(x), t(stringsimmatrix(x)))
KLentropy=function(x,k,weights=FALSE,stderror=FALSE){ dim=dim(as.matrix(x)); n=dim[1]; d=dim[2] V=pi^(d/2)/gamma(1+d/2) if(length(weights)>1){ w=weights }else if(weights==TRUE){ w=L2OptW(k,d) }else{ w=c(rep(0,k-1),1) } rho=knn.dist(x,k=k) H=(1/n)*colSums(t(log(t(rho)^d*V*(n-1))-digamma(1:k))) value=list(); value[[1]]=H; value[[2]]=sum(H*w) if(stderror==TRUE){ H2=(1/n)*sum((log(rho[,k]^d*V*(n-1))-digamma(k))^2) value[[3]]=n^(-1/2)*sqrt(H2-(value[[2]])^2) names(value)=c("Unweighted","Estimate","StdError") } else { names(value)=c("Unweighted","Estimate") } return(value) }
context("binPeaks") p <- list(createMassPeaks(mass=seq(100, 500, 100), intensity=1:5), createMassPeaks(mass=c(seq(100.2, 300.2, 100), 395), intensity=1:4)) p2 <- c(createMassPeaks(mass=c(1.009, 1.01, 3), intensity=c(2, 1, 1), snr=1:3), createMassPeaks(mass=c(1, 3), intensity=1:2, snr=1:2), createMassPeaks(mass=c(1.03, 3), intensity=1:2, snr=1:2)) test_that("binPeaks throws errors", { expect_error(binPeaks(list()), "no list of MALDIquant::MassPeaks") expect_error(binPeaks(p, method="foobar"), ".*arg.* should be one of .*strict.*, .*relaxed.*") }) test_that("binPeaks bins peaks strict", { b <- binPeaks(p, tolerance=0.002) expect_true(all(b[[1]]@mass[1:3]==b[[2]]@mass[1:3])) expect_false(all(b[[1]]@mass[4]==b[[2]]@mass[4])) expect_true(length(b[[1]])==5) expect_true(length(b[[2]])==4) expect_false(all(p[[1]]@mass==b[[1]]@mass)) expect_false(all(p[[2]]@mass==b[[2]]@mass)) b <- binPeaks(p, tolerance=0.1) expect_true(all(b[[1]]@mass[1:4]==b[[2]]@mass[1:4])) expect_true(length(b[[1]])==5) expect_true(length(b[[2]])==4) expect_false(all(p[[1]]@mass==b[[1]]@mass)) expect_false(all(p[[2]]@mass==b[[2]]@mass)) }) test_that("binPeaks bins peaks releaxed", { b <- binPeaks(p2, method="relaxed", tolerance=0.05) expect_true(all(b[[1]]@mass==c(1.01, 1.013, 3))) ip <- sort(p2[[1]]@mass, index.return=TRUE) ib <- sort(b[[1]]@mass, index.return=TRUE) expect_equal(ip$ix, ib$ix) expect_false(all(p2[[1]]@intensity == b[[1]]@intensity)) expect_false(all(p2[[1]]@snr== b[[1]]@snr)) expect_true(all(b[[1]]@intensity == c(1, 2, 1))) expect_true(all(b[[2]]@intensity == 1:2)) expect_true(all(b[[3]]@intensity == 1:2)) expect_true(all(b[[1]]@snr == c(2, 1, 3))) expect_true(all(b[[2]]@snr == 1:2)) expect_true(all(b[[3]]@snr == 1:2)) }) test_that("binPeaks bins peaks to reference", { ref <- createMassPeaks(mass=1:3, intensity=1:3, snr=1:3) r <- c(createMassPeaks(mass=c(1, 1.01, 3), intensity=c(2, 1, 1), snr=1:3), createMassPeaks(mass=c(1, 3), intensity=1:2, snr=1:2), createMassPeaks(mass=c(1, 3), intensity=1:2, snr=1:2)) expect_equal(binPeaks(c(ref, p2), method="reference", tolerance=0.05)[-1], r) }) test_that("binPeaks don't introduce new peaks; issue 61", { p1 <- createMassPeaks(1:5, 1:5, metaData=list(name="foo")) p0 <- createMassPeaks(numeric(), numeric(), metaData=list(name="bar")) expect_equal(binPeaks(list(p1, p0)), list(p1, p0)) expect_equal(binPeaks(list(p0, p1)), list(p0, p1)) expect_equal(binPeaks(list(p0, p0, p1)), list(p0, p0, p1)) expect_equal(binPeaks(list(p0, p1, p1)), list(p0, p1, p1)) })
abe.mcmc.DrawParameters <- function(cal.cbs, covariates = c(), mcmc = 2500, burnin = 500, thin = 50, chains = 2, mc.cores = NULL, trace = 100) { draw_level_2 <- function(covars, level_1, hyper_prior) { draw <- bayesm::rmultireg(Y = log(t(level_1[c("lambda", "mu"), ])), X = covars, Bbar = hyper_prior$beta_0, A = hyper_prior$A_0, nu = hyper_prior$nu_00, V = hyper_prior$gamma_00) return(list(beta = t(draw$B), gamma = draw$Sigma)) } draw_z <- function(data, level_1) { tx <- data$t.x Tcal <- data$T.cal lambda <- level_1["lambda", ] mu <- level_1["mu", ] mu_lam <- mu + lambda t_diff <- Tcal - tx prob <- 1 / (1 + (mu / mu_lam) * (exp(mu_lam * t_diff) - 1)) z <- as.numeric(runif(length(prob)) < prob) return(z) } draw_tau <- function(data, level_1) { N <- nrow(data) tx <- data$t.x Tcal <- data$T.cal lambda <- level_1["lambda", ] mu <- level_1["mu", ] mu_lam <- mu + lambda z <- level_1["z", ] alive <- z == 1 tau <- numeric(N) if (any(alive)) { tau[alive] <- Tcal[alive] + rexp(sum(alive), mu[alive]) } if (any(!alive)) { mu_lam_tx <- pmin(700, mu_lam[!alive] * tx[!alive]) mu_lam_Tcal <- pmin(700, mu_lam[!alive] * Tcal[!alive]) rand <- runif(n = sum(!alive)) tau[!alive] <- -log( (1 - rand) * exp(-mu_lam_tx) + rand * exp(-mu_lam_Tcal)) / mu_lam[!alive] } return(tau) } draw_level_1 <- function(data, covars, level_1, level_2) { N <- nrow(data) x <- data$x Tcal <- data$T.cal z <- level_1["z", ] tau <- level_1["tau", ] mvmean <- covars[, ] %*% t(level_2$beta) gamma <- level_2$gamma inv_gamma <- solve(gamma) cur_lambda <- level_1["lambda", ] cur_mu <- level_1["mu", ] log_post <- function(log_theta) { log_lambda <- log_theta[1, ] log_mu <- log_theta[2, ] diff_lambda <- log_lambda - mvmean[, 1] diff_mu <- log_mu - mvmean[, 2] likel <- x * log_lambda + (1 - z) * log_mu - (exp(log_lambda) + exp(log_mu)) * (z * Tcal + (1 - z) * tau) prior <- -0.5 * (diff_lambda ^ 2 * inv_gamma[1, 1] + 2 * diff_lambda * diff_mu * inv_gamma[1, 2] + diff_mu ^ 2 * inv_gamma[2, 2]) post <- likel + prior post[log_mu > 5] <- -Inf return(post) } cur_log_theta <- rbind(log(cur_lambda), log(cur_mu)) cur_post <- log_post(cur_log_theta) step <- function(cur_log_theta, cur_post) { new_log_theta <- cur_log_theta + rbind(gamma[1, 1] * rt(N, df = 3), gamma[2, 2] * rt(n = N, df = 3)) new_log_theta[1, ] <- pmax(pmin(new_log_theta[1, ], 70), -70) new_log_theta[2, ] <- pmax(pmin(new_log_theta[2, ], 70), -70) new_post <- log_post(new_log_theta) mhratio <- exp(new_post - cur_post) accepted <- mhratio > runif(n = N) cur_log_theta[, accepted] <- new_log_theta[, accepted] cur_post[accepted] <- new_post[accepted] list(cur_log_theta = cur_log_theta, cur_post = cur_post) } iter <- 1 for (i in 1:iter) { draw <- step(cur_log_theta, cur_post) cur_log_theta <- draw$cur_log_theta cur_post <- draw$cur_post } cur_theta <- exp(cur_log_theta) return(list(lambda = cur_theta[1, ], mu = cur_theta[2, ])) } run_single_chain <- function(chain_id, data, hyper_prior) { nr_of_cust <- nrow(data) nr_of_draws <- (mcmc - 1) %/% thin + 1 level_1_draws <- array(NA_real_, dim = c(nr_of_draws, 4, nr_of_cust)) dimnames(level_1_draws)[[2]] <- c("lambda", "mu", "tau", "z") level_2_draws <- array(NA_real_, dim = c(nr_of_draws, 2 * K + 3)) nm <- c("log_lambda", "log_mu") if (K > 1) nm <- paste(rep(nm, times = K), rep(colnames(covars), each = 2), sep = "_") dimnames(level_2_draws)[[2]] <- c(nm, "var_log_lambda", "cov_log_lambda_log_mu", "var_log_mu") level_1 <- level_1_draws[1, , ] level_1["lambda", ] <- mean(data$x) / mean(ifelse(data$t.x == 0, data$T.cal, data$t.x)) level_1["mu", ] <- 1 / (data$t.x + 0.5 / level_1["lambda", ]) hyper_prior$beta_0[1, "log_lambda"] <- log(mean(level_1["lambda", ])) hyper_prior$beta_0[1, "log_mu"] <- log(mean(level_1["mu", ])) for (step in 1:(burnin + mcmc)) { if (step %% trace == 0) cat("chain:", chain_id, "step:", step, "of", (burnin + mcmc), "\n") level_1["z", ] <- draw_z(data, level_1) level_1["tau", ] <- draw_tau(data, level_1) level_2 <- draw_level_2(covars, level_1, hyper_prior) draw <- draw_level_1(data, covars, level_1, level_2) level_1["lambda", ] <- draw$lambda level_1["mu", ] <- draw$mu if ( (step - burnin) > 0 & (step - 1 - burnin) %% thin == 0) { idx <- (step - 1 - burnin) %/% thin + 1 level_1_draws[idx, , ] <- level_1 level_2_draws[idx, ] <- c(level_2$beta, level_2$gamma[1, 1], level_2$gamma[1, 2], level_2$gamma[2, 2]) } } return(list( "level_1" = lapply(1:nr_of_cust, function(i) mcmc(level_1_draws[, , i], start = burnin, thin = thin)), "level_2" = mcmc(level_2_draws, start = burnin, thin = thin))) } stopifnot(is.data.frame(cal.cbs)) stopifnot(all(c("x", "t.x", "T.cal") %in% names(cal.cbs))) stopifnot(all(covariates %in% names(cal.cbs))) cal.cbs[, "intercept"] <- 1 covariates <- c("intercept", covariates) K <- length(covariates) covars <- as.matrix(subset(cal.cbs, select = covariates)) beta_0 <- matrix(0, nrow = K, ncol = 2, dimnames = list(NULL, c("log_lambda", "log_mu"))) A_0 <- diag(rep(0.01, K), ncol = K, nrow = K) nu_00 <- 3 + K gamma_00 <- nu_00 * diag(2) hyper_prior <- list(beta_0 = beta_0, A_0 = A_0, nu_00 = nu_00, gamma_00 = gamma_00) ncores <- ifelse(!is.null(mc.cores), min(chains, mc.cores), ifelse(.Platform$OS.type == "windows", 1, min(chains, detectCores()))) if (ncores > 1) cat("running in parallel on", ncores, "cores\n") draws <- mclapply(1:chains, function(i) run_single_chain(i, cal.cbs, hyper_prior = hyper_prior), mc.cores = ncores) out <- list(level_1 = lapply(1:nrow(cal.cbs), function(i) mcmc.list(lapply(draws, function(draw) draw$level_1[[i]]))), level_2 = mcmc.list(lapply(draws, function(draw) draw$level_2))) if ("cust" %in% names(cal.cbs)) names(out$level_1) <- cal.cbs$cust return(out) } abe.GenerateData <- function(n, T.cal, T.star, params, date.zero = "2000-01-01", covariates = NULL) { T.cal.fix <- max(T.cal) T.cal <- rep(T.cal, length.out = n) T.zero <- T.cal.fix - T.cal date.zero <- as.POSIXct(date.zero) if (!is.matrix(params$beta)) params$beta <- matrix(params$beta, nrow = 1, ncol = 2) nr_covars <- nrow(params$beta) if (!is.null(covariates)) { covars <- covariates if (is.data.frame(covars)) covars <- as.matrix(covars) if (!is.matrix(covars)) covars <- matrix(covars, ncol = 1, dimnames = list(NULL, "covariate_1")) if (!all(covars[, 1] == 1)) covars <- cbind("intercept" = rep(1, nrow(covars)), covars) if (is.null(colnames(covars)) & ncol(covars) > 1) colnames(covars)[-1] <- paste("covariate", 1:(nr_covars - 1), sep = "_") if (nr_covars != ncol(covars)) stop("provided number of covariate columns does not match implied covariate number by parameter `beta`") if (n != nrow(covars)) covars <- covars[sample(1:nrow(covars), n, replace = TRUE), ] } else { covars <- matrix(c(rep(1, n), runif( (nr_covars - 1) * n, -1, 1)), nrow = n, ncol = nr_covars) colnames(covars) <- paste("covariate", 0:(nr_covars - 1), sep = "_") colnames(covars)[1] <- "intercept" } thetas <- exp( (covars %*% params$beta) + mvtnorm::rmvnorm(n, mean = c(0, 0), sigma = params$gamma)) lambdas <- thetas[, 1] mus <- thetas[, 2] taus <- rexp(n, rate = mus) elog_list <- lapply(1:n, function(i) { minT <- min(T.cal[i] + max(T.star), taus[i]) itt_draws <- max(10, round(minT * lambdas[i] * 1.5)) itt_fn <- function(n) rexp(n, rate = lambdas[i]) itts <- itt_fn(itt_draws) if (sum(itts) < minT) itts <- c(itts, itt_fn(itt_draws * 4)) if (sum(itts) < minT) itts <- c(itts, itt_fn(itt_draws * 800)) if (sum(itts) < minT) stop("not enough inter-transaction times sampled: ", sum(itts), " < ", minT) ts <- cumsum(c(0, itts)) ts <- ts[ts <= taus[i]] ts <- T.zero[i] + ts ts <- ts[ts <= (T.cal.fix + max(T.star))] return(ts) }) elog <- data.table("cust" = rep(1:n, sapply(elog_list, length)), "t" = unlist(elog_list)) elog[["date"]] <- date.zero + elog[["t"]] * 3600 * 24 * 7 date.cal <- date.zero + T.cal.fix * 3600 * 24 * 7 date.tot <- date.cal + T.star * 3600 * 24 * 7 cbs <- elog2cbs(elog, T.cal = date.cal) if (length(T.star) == 1) set(cbs, j = "T.star", value = T.star[1]) xstar.cols <- if (length(T.star) == 1) "x.star" else paste0("x.star", T.star) for (j in 1:length(date.tot)) { set(cbs, j = xstar.cols[j], value = sapply(elog_list, function(t) sum(t > T.cal.fix & t <= T.cal.fix + T.star[j]))) } set(cbs, j = "lambda", value = lambdas) set(cbs, j = "mu", value = mus) set(cbs, j = "tau", value = taus) set(cbs, j = "alive", value = (T.zero + taus) > T.cal.fix) cbs <- cbind(cbs, covars) return(list("cbs" = setDF(cbs), "elog" = setDF(elog))) }
source("ESEUR_config.r") pal_col=rainbow(3) source(paste0(ESEUR_dir, "projects/agile-work/feat-common-7dig.R")) plot_two_ratio=function(red_vals, blue_vals) { plot(blue_vals, type="l", col=pal_col[1], xaxs="i", yaxs="i", xlim=c(0, 820), ylim=c(0, 7), xlab="Work days since Apr 2009", ylab="") lines(red_vals, col=pal_col[2]) lines(red_vals/blue_vals, col=pal_col[3]) } all_bugs=sum_starts(subset(p, grepl(".*Bug$", p$Type))$Dev.Started) all_bugs=all_bugs[-weekends] non_bugs=sum_starts(subset(p, !grepl(".*Bug$", p$Type))$Dev.Started) non_bugs=non_bugs[-weekends] plot_two_ratio(rollmean(all_bugs, 25), rollmean(non_bugs, 25)) legend(x="topleft", legend=c("New features", "Bug fixes", "Bug-fix/New-feature"), bty="n", fill=pal_col, cex=1.2)
jumbotron <- function(header , content, button = TRUE, ...){ button_label = c(...) if (button){ div(class = "jumbotron", h1(header), p(content), p(a(class = "btn btn-primary btn-lg button", id='tabBut', button_label))) } else { div(class = "jumbotron", h1(header), p(content)) } }
meechua_reg<-function(x){ models <- dlply(mee_chua_sort, "mu", function(df) lm(after~before, data = df)) mod_coef<-ldply(models, coef) results <- ldply(models,function(i)coef(summary(i))) se<-results[,"Std. Error"] se_after<- se[seq(1,length(se),2)] Variable<-rep(c("Before","Intercept"),times=101) res_model_tab<-cbind(Variable,results) res_model_tab<-as.data.frame(res_model_tab) models<<-models mod_coef<<-mod_coef se_after<<-se_after formattable(res_model_tab, align =c("l","c","c","c","c","r"), list(`Indicator Name` = formatter("span", style = ~ style(color = "grey",font.weight = "bold")) )) }
dfp_getTrafficAdjustmentsByStatement <- function(request_data, as_df=TRUE, verbose=FALSE){ request_body <- form_request_body(service='AdjustmentService', root_name='getTrafficAdjustmentsByStatement', data=request_data) httr_response <- execute_soap_request(request_body=request_body, verbose=verbose) result <- parse_soap_response(httr_response=httr_response, resp_element='getTrafficAdjustmentsByStatementResponse', as_df=as_df) return(result) } dfp_updateTrafficAdjustments <- function(request_data, as_df=TRUE, verbose=FALSE){ request_body <- form_request_body(service='AdjustmentService', root_name='updateTrafficAdjustments', data=request_data) httr_response <- execute_soap_request(request_body=request_body, verbose=verbose) result <- parse_soap_response(httr_response=httr_response, resp_element='updateTrafficAdjustmentsResponse', as_df=as_df) return(result) }
textplot <- function(object, halign="center", valign="center", cex, max.cex = 1, cmar=2, rmar=0.5, show.rownames=TRUE, show.colnames=TRUE, hadj=1, vadj=NULL, row.valign="center", heading.valign = "bottom", mar= c(0,0,0,0)+0.1, col.data=par("col"), col.rownames=par("col"), col.colnames=par("col"), wrap = TRUE, wrap.colnames = 10, wrap.rownames = 10, ... ) UseMethod('textplot') textplot.default <- function(object, halign=c("center","left","right"), valign=c("center","top","bottom"), cex, max.cex, cmar, rmar, show.rownames, show.colnames, hadj, vadj, row.valign, heading.valign, mar, col.data, col.rownames, col.colnames, wrap, wrap.colnames, wrap.rownames,... ) { if (is.matrix(object) || (is.vector(object) && length(object)>1) ) return(textplot.matrix(object, halign, valign, cex, ... )) halign <- match.arg(halign) valign <- match.arg(valign) textplot.character(object, halign, valign, cex, ...) } textplot.data.frame <- function(object, halign=c("center","left","right"), valign=c("center","top","bottom"), cex, max.cex = 1, cmar=2, rmar=0.5, show.rownames=TRUE, show.colnames=TRUE, hadj=1, vadj=NULL, row.valign="center", heading.valign = "bottom", mar= c(0,0,0,0)+0.1, col.data=par("col"), col.rownames=par("col"), col.colnames=par("col"), wrap = TRUE, wrap.colnames = 10, wrap.rownames = 10, ... ){ textplot.matrix(object, halign, valign, cex, max.cex, cmar, rmar, show.rownames, show.colnames, hadj, vadj, row.valign, heading.valign, mar, col.data, col.rownames, col.colnames, wrap, wrap.colnames, wrap.rownames, ... ) } textplot.matrix <- function(object, halign=c("center","left","right"), valign=c("center","top","bottom"), cex, max.cex = 1, cmar=2, rmar=0.5, show.rownames=TRUE, show.colnames=TRUE, hadj=1, vadj=NULL, row.valign="center", heading.valign = "bottom", mar= c(0,0,0,0)+0.1, col.data=par("col"), col.rownames=par("col"), col.colnames=par("col"), wrap = TRUE, wrap.colnames = 10, wrap.rownames = 10, ... ) { if(is.vector(object)) object <- t(as.matrix(object)) else object <- as.matrix(object) if(length(col.data)==1) col.data <- matrix(col.data, nrow=nrow(object), ncol=ncol(object)) else if( nrow(col.data)!=nrow(object) || ncol(col.data)!=ncol(object) ) stop("Dimensions of 'col.data' do not match dimensions of 'object'.") if(length(col.rownames)==1) col.rownames <- rep(col.rownames, nrow(object)) if(length(col.colnames)==1) if(show.rownames) col.colnames <- rep(col.colnames, ncol(object)+1) else col.colnames <- rep(col.colnames, ncol(object)) halign=match.arg(halign) valign=match.arg(valign) opar <- par()[c("mar","xpd","cex")] on.exit( par(opar) ) par(mar=mar, xpd=FALSE ) plot.new() plot.window(xlim=c(0,1),ylim=c(0,1), log = "", asp=NA) if( is.null(colnames(object) ) ) colnames(object) <- paste( "[,", 1:ncol(object), "]", sep="" ) if( is.null(rownames(object)) ) rownames(object) <- paste( "[", 1:nrow(object), ",]", sep="") if( show.rownames ) { if(wrap) row.names = sapply(rownames(object), function(x) paste(strwrap(x,wrap.rownames), collapse = "\n"), USE.NAMES=FALSE) else row.names = rownames(object) object <- cbind( row.names, object ) col.data <- cbind( col.rownames, col.data ) } if( show.colnames ) { if(wrap) column.names = sapply(colnames(object), function(x) paste(strwrap(x,wrap.colnames), collapse = "\n"), USE.NAMES=FALSE) else column.names = colnames(object) object <- rbind( column.names, object ) col.data <- rbind( col.colnames, col.data ) } if( missing(cex) ) { cex <- max.cex lastloop <- FALSE } else { lastloop <- TRUE } for (i in 1:20) { oldcex <- cex colwidth = apply( object, 2, function(XX) max(strwidth(XX, cex=cex)) ) + strwidth("W",cex=cex) * cmar width = sum(colwidth) rowheight = apply(object,1, function(X) max(strheight(X,cex=cex)) ) + strheight("(",cex=cex) * (1 + rmar ) height=sum(rowheight) if(lastloop) break cex <- cex / max(width,height) if (abs(oldcex - cex) < 0.001) { lastloop <- TRUE } } if(cex>max.cex) { cex = max.cex colwidth = apply( object, 2, function(XX) max(strwidth(XX, cex=cex)) ) + strwidth("W",cex=cex) * cmar width = sum(colwidth) rowheight = apply(object,1, function(X) max(strheight(X,cex=cex)) ) + strheight("(",cex=cex) * (1 + rmar ) height=sum(rowheight) } if(halign=="left") xpos <- 0 else if(halign=="center") xpos <- 0 + (1-width)/2 else xpos <- 0 + (1-width) if(valign=="top") ypos <- 1 else if (valign=="center") ypos <- 1 - (1-height)/2 else ypos <- 0 + height x <- xpos y <- ypos xpos<-x for(i in 1:ncol(object)) { xpos <- xpos + colwidth[i] for(j in 1:nrow(object)) { if( show.colnames && j==1 ){ if (i==1 && j==1){} else { if(heading.valign=="top") { ypos = y vadj = 1 } if(heading.valign=="bottom") { ypos = y - rowheight[1] + strheight("(",cex=cex) * (1 + rmar) vadj = 0 } if(heading.valign=="center") { ypos = y - rowheight[1]/2 + strheight("(",cex=cex) * (1 + rmar)/2 vadj = .5 } text(xpos, ypos, object[j,i], adj=c(hadj,vadj), cex=cex, font=2, col=col.data[j,i], ... ) } } else { if(row.valign=="top") { ypos = y - sum(rowheight[0:(j-1)]) vadj = 1 } if(row.valign=="bottom") { ypos = y - sum(rowheight[1:(j)]) + strheight("(",cex=cex) * (1 + rmar) vadj = 0 } if(row.valign=="center") { ypos = y - (sum(rowheight[1:(j)]) + sum(rowheight[0:(j-1)]))/2 + strheight("(",cex=cex) * (1 + rmar)/2 vadj = .5 } if(show.rownames && i==1) font = 2 else font = 1 text(xpos, ypos, object[j,i], adj=c(hadj,vadj), cex=cex, font=font, col=col.data[j,i], ... ) } } } par(opar) } textplot.character <- function (object, halign = c("center", "left", "right"), valign = c("center", "top", "bottom"), cex, max.cex = 1, cmar=2, rmar=0.5, show.rownames=TRUE, show.colnames=TRUE, hadj=1, vadj=NULL, row.valign="center", heading.valign = "bottom", mar= c(0,0,3,0)+0.1, col.data=par("col"), col.rownames=par("col"), col.colnames=par("col"), wrap = TRUE, wrap.colnames = 10, wrap.rownames = 10, fixed.width=TRUE, cspace=1, lspace=1, tab.width=8, ...) { object <- paste(object,collapse="\n",sep="") object <- replaceTabs(object, width=tab.width) halign = match.arg(halign) valign = match.arg(valign) plot.new() opar <- par()[c("mar","xpd","cex","family")] on.exit( par(opar) ) par(mar=mar,xpd=FALSE ) if(fixed.width) par(family="mono") plot.window(xlim = c(0, 1), ylim = c(0, 1), log = "", asp = NA) slist <- unlist(lapply(object, function(x) strsplit(x,'\n'))) slist <- lapply(slist, function(x) unlist(strsplit(x,''))) slen <- sapply(slist, length) slines <- length(slist) if (missing(cex)) { lastloop <- FALSE cex <- 1 } else lastloop <- TRUE for (i in 1:20) { oldcex <- cex cwidth <- max(sapply(unlist(slist), strwidth, cex=cex)) * cspace cheight <- max(sapply(unlist(slist), strheight, cex=cex)) * ( lspace + 0.5 ) width <- strwidth(object, cex=cex) height <- strheight(object, cex=cex) if(lastloop) break cex <- cex / max(width, height) if (abs(oldcex - cex) < 0.001) { lastloop <- TRUE } } if (halign == "left") xpos <- 0 else if (halign == "center") xpos <- 0 + (1 - width)/2 else xpos <- 0 + (1 - width) if (valign == "top") ypos <- 1 else if (valign == "center") ypos <- 1 - (1 - height)/2 else ypos <- 1 - (1 - height) text(x=xpos, y=ypos, labels=object, adj=c(0,1), cex=cex, ...) par(opar) invisible(cex) }
source("ESEUR_config.r") library("plyr") plot_layout(2, 1) pal_col=rainbow(4) plot_foil=function(df) { lines(df$Thematic, df$False_Pos, type="b", col=df$col_str) } plot_period=function(period_str) { DCweek=subset(DC, Period == period_str) plot(0, type="n", xaxt="n", yaxs="i", xlim=c(1, 4), ylim=c(0, max(DC$False_Pos)), xlab="", ylab="False positive (percent)\n") axis(1, at=1:4, label=c("Neutral", "Low", "Medium", "High")) text(3, 5, gsub("_", " ", period_str), cex=1.3) plot_foil(subset(DCweek, Foils == "Before")) plot_foil(subset(DCweek, Foils == "After")) plot_foil(subset(DCweek, Foils == "Famous")) plot_foil(subset(DCweek, Foils == "Fictitious")) legend(x="topleft", legend=c("Before", "After", "Famous", "Fictitious"), bty="n", fill=pal_col, cex=1.2) } DC=read.csv(paste0(ESEUR_dir, "sourcecode/DoolingChristiaansen77.csv.xz"), as.is=TRUE) Foil_str=unique(DC$Foils) DC$col_str=mapvalues(DC$Foils, Foil_str, pal_col) DCweek=subset(DC, Period == "1_week") plot_period("2_days") plot_period("1_week")
github_info <- function(path = ".", remote = "origin", .token = NULL) { remote_url <- get_remote_url(path, remote) repo <- extract_repo(remote_url) get_repo_data(repo, .token) } get_repo_data <- function(repo, .token = NULL) { req <- gh::gh("/repos/:repo", repo = repo, .token = .token) return(req) } get_remote_url <- function(path, remote) { remote_names <- gert::git_remote_list(path) if (!length(remote_names)) { stop("Failed to lookup git remotes") } remote_name <- remote if (!(remote_name %in% remote_names)) { stop(sprintf( "No remote named '%s' found in remotes: '%s'.", remote_name, remote_names )) } return(remote_names[remote_names$name == remote]$url) } extract_repo <- function(url) { re <- "github[^/:]*[/:]([^/]+)/(.*?)(?:\\.git)?$" m <- regexec(re, url) match <- regmatches(url, m)[[1]] if (length(match) == 0) { stop("Unrecognized repo format: ", url) } paste0(match[2], "/", match[3]) }
opticskxi_pipeline <- function(m_data, df_params = expand.grid(n_xi = 1:10, pts = c(20, 30, 40), dist = c('euclidean', 'abscorrelation'), dim_red = c('identity', 'PCA', 'ICA'), n_dimred_comp = c(5, 10, 20)), n_cores = 1) { if (!all(c('n_xi', 'pts', 'dist') %in% names(df_params))) { stop('Missing required columns in parameter grid.') } if (!'dim_red' %in% names(df_params)) { df_params %<>% cbind(dim_red = 'identity') } uniq_names <- c('dim_red', 'n_dimred_comp') df_params <- fetch_dimred(m_data, df_params, uniq_names, n_cores) uniq_names %<>% c('dist') df_params %<>% derive_column(uniq_names, c('m_dimred', 'dist'), amap::Dist, 'm_dist', c('x', 'method'), mc.cores = n_cores) uniq_names %<>% c('pts') df_params %<>% derive_column(uniq_names, c('m_dist', 'pts'), dbscan::optics, 'optics', c('x', 'minPts'), mc.cores = n_cores) df_params <- fetch_opticskxi(df_params, n_cores) m_dist <- dist(m_data) %>% as.matrix df_params$metrics <- parallel::mclapply(df_params$clusters, get_kxi_metrics, m_dist, mc.cores = n_cores) df_params } get_best_kxi <- function(df_kxi, metric = 'avg.silwidth', rank = 1) { if (all(unlist(df_kxi$metrics) == 0)) stop('All metrics equal 0') metric_value <- as.matrix(as.data.frame(df_kxi$metrics))[metric, ] if (all(metric_value == 0)) stop(paste('All', metric, 'values equal 0')) df_kxi %<>% `[`(order(metric_value, decreasing = TRUE)[rank], ) if (length(rank) == 1) { df_kxi %<>% as.list df_kxi[c('optics', 'clusters', 'metrics')] %<>% lapply(`[[`, 1) } df_kxi } fetch_dimred <- function(m_data, df_params, uniq_names, n_cores) { df_params[df_params$dim_red == 'identity', 'n_dimred_comp'] <- NA df_params %<>% unique %>% `rownames<-`(NULL) df_params$m_data <- list(m_data) df_params <- derive_column(df_params, uniq_names, c('m_data', 'dim_red', 'n_dimred_comp'), .fetch_dimred, 'm_dimred', mc.cores = n_cores) } .fetch_dimred <- function(m_data, dim_red, n_dimred_comp) { n_dimred_comp <- as.numeric(n_dimred_comp) switch(dim_red, identity = m_data, PCA = stats::prcomp(m_data)$x[, seq_len(n_dimred_comp)], ICA = { set.seed(0) fastICA::fastICA(m_data, n_dimred_comp)$S %>% `colnames<-`(paste0('IC', seq_len(ncol(.)))) }) } fetch_opticskxi <- function(df_params, n_cores) { df_opt <- data.frame(t(df_params[c('optics', 'n_xi', 'pts')]), stringsAsFactors = FALSE) df_params$clusters <- parallel::mclapply(df_opt, function(params) do.call(opticskxi, params), mc.cores = n_cores) df_params } derive_column <- function(df_prm, uniq_names, df_names, fun, col_name, param_names = df_names, ...) { uniq_idxs <- which(!duplicated(df_prm[uniq_names])) uniq_params <- df_prm[uniq_idxs, df_names] uniq_df <- df_prm[uniq_idxs, uniq_names] uniq_df[[col_name]] <- parallel::mclapply( data.frame(t(uniq_params), stringsAsFactors = FALSE), .derive_column, fun, param_names, ...) df_prm %<>% `[`(-match(df_names[1], names(.))) merge(uniq_df, df_prm, by = uniq_names) } .derive_column <- function(params, fun, param_names) { do.call(fun, as.list(stats::setNames(params, param_names))) } get_kxi_metrics <- function(clusters, m_dist, metrics = c('avg.silwidth', 'bw.ratio', 'ch', 'pearsongamma', 'dunn', 'dunn2', 'entropy', 'widestgap', 'sindex')) { if (length(table(clusters)) < 2) return(rep(0, length(metrics))) ids <- which(!is.na(clusters)) m_dist[ids, ids] %>% fpc::cluster.stats(clusters[ids]) %>% `[[<-`('bw.ratio', 1 / .$wb.ratio) %>% `[`(metrics) %>% unlist }
context("test-likelihood_st.R") test_that("Luetkepohl Netsunajev 5*5 example", { v1 <- vars::VAR(LN, p = 3, type = 'const') u <- residuals(v1) transition_f <- function(gamma, cc, st){ G <- (1 + exp(-exp(gamma)*(st - cc)))^(-1) return(G) } G_grid <- mapply(transition_f, -2.77, 167, MoreArgs = list(st = seq(1:447))) B <- matrix(c(0.213883587513229, 0.772120510734492, -0.132282532851005, -0.0318059401299042, 0.183421072804760, -0.000909983103775138, 0.0611927897127684, -0.133387139716194, 0.224482965869132, -0.178566415153278, -0.489608073426655, 1.34883810601586, 3.16440093460292, 1.18136247975495, -0.349727160207559, -0.241998772722667, 1.07756860248053, 0.547129661435694, -2.40448854722913, -2.27634107379356, 0.885487887527691, 0.0288063531310017, 0.0196527566892526, 0.0206577929300702, 0.00150251343596967), nrow = 5, byrow = T) Lambda <- c(0.0199927489696526, 0.314911226555606, 0.548190884220239, 0.866994133953794, 0.926892018919112)*diag(5) expect_equal(round(LikelihoodST(parameter = c(B, diag(Lambda)), u = u, G = G_grid, k = 5, Tob = 447, RestrictionMatrix = matrix(NA, 5,5), restrictions = 0), 3), 2976.656) }) test_that("Random 2*2 example works", { set.seed(12123) u <- matrix(rnorm(400, sd = 1.2), 200, 2) transition_f <- function(gamma, cc, st){ G <- (1 + exp(-exp(gamma)*(st - cc)))^(-1) return(G) } G_grid <- mapply(transition_f, -2, 100, MoreArgs = list(st = seq(1:200))) B <- matrix(c(rnorm(mean = 3, 4)), nrow = 2) Lambda <- c(rnorm(mean = 2, 2))*diag(2) expect_equal(round(LikelihoodST(parameter = c(B, diag(Lambda)), u = u, G = G_grid, k = 2, Tob = 200, RestrictionMatrix = matrix(NA, 2, 2), restrictions = 0), 3), 906.717) }) test_that("2*2 example with negative variance", { set.seed(12123) u <- matrix(rnorm(400, sd = 1.2), 200, 2) transition_f <- function(gamma, cc, st){ G <- (1 + exp(-exp(gamma)*(st - cc)))^(-1) return(G) } G_grid <- mapply(transition_f, -2, 100, MoreArgs = list(st = seq(1:200))) B <- matrix(c(rnorm(mean = 3, 4)), nrow = 2) Lambda <- c(-2, 2)*diag(2) expect_equal(round(LikelihoodST(parameter = c(B, diag(Lambda)), u = u, G = G_grid, k = 2, Tob = 200, RestrictionMatrix = matrix(NA, 2, 2), restrictions = 0), 3), 1e25) })
data("dataHigherMoments") context("Inputchecks - higherMomentsIV - Parameter formula") test_that("Fail if bad 2nd RHS", { expect_error(higherMomentsIV(y~X1+X2+P||IIV(g=x2, iiv=g, X1), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2|P|IIV(g=x2, iiv=g, X1), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+P|X2|IIV(g=x2, iiv=g, X1), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P2|IIV(g=x2, iiv=g, X1), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1|X1|IIV(g=x2, iiv=g, X1), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~P|P|IIV(g=x2, iiv=g, X1), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+log(P)|P|IIV(iiv=gp, g=x2, X1, X2), data = dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|log(P)|IIV(iiv=gp, g=x2, X1, X2), data = dataHigherMoments), regexp = "The above errors were encountered!") }) test_that("Fail if more than a single endo regressor is given", { expect_error(higherMomentsIV(y~X1+X2+P|P+X1|IIV(iiv=gp, g=x2, X2), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P+X2|IIV(iiv=gp, g=x2, X1), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|X1+X2|IIV(iiv=gp,g=x2, P), data=dataHigherMoments), regexp = "The above errors were encountered!") }) test_that("Fail if bad 3rd RHS", { expect_error(higherMomentsIV(y~X1+X2+P|P), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2, iiv=g, X3), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+P|P|IIV(g=x2, iiv=g, X2), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X2+P|P|IIV(g=x2, iiv=g, X1), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2, iiv=g, P), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2, iiv=g, X1, P), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P+X1|IIV(g=x2, iiv=g, X1, X2), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P+X2|IIV(g=x2, iiv=g, X1, X2), data=dataHigherMoments), regexp = "The above errors were encountered!") }) test_that("Fail if > 4RHS",{ expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2, iiv=g, X1)|IIV(g=x2, iiv=g, X2)|IIV(g=x3, iiv=g, X2), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2, iiv=g, X1)| X2|X1), regexp = "The above errors were encountered!") }) test_that("Fail if bad LHS", { expect_error(higherMomentsIV(~X1+X2+P|P|IIV(g=x2, iiv=g, X1), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y|X1~X2+P|P|IIV(g=x2, iiv=g, X1), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~y+X2+P|P|IIV(g=x2, iiv=g, X1), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(X1~X1+X2+P|P|IIV(g=x2, iiv=g, X1), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y+IIV(g=x2, iiv=g, X1)~X1+X2+P|P|IIV(g=x2, iiv=g, X1), data=dataHigherMoments), regexp = "The above errors were encountered!") }) test_that("Fail if formula contains dot (.)", { expect_error(higherMomentsIV(y~X1+X2+.|P|IIV(g=x2, iiv=gp, X1), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(.~X1+X2+X2|P|IIV(g=x2, iiv=gp, X1), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+X2|.|IIV(g=x2, iiv=gp, X1), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+X2|P|IIV(g=x2, iiv=gp, .), data=dataHigherMoments), regexp = "The above errors were encountered!") }) test_that("Fail if no special function", { expect_error(higherMomentsIV(y~X1+X2+P|P|x2+gp+X1, data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|X1+X2), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV+IIV(g=x2, iiv=gp, X2), data=dataHigherMoments), regexp = "The above errors were encountered!") }) test_that("Fail if missing regressors in IIV", { expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2, iiv=gp), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2, iiv=gp, ), data=dataHigherMoments), regexp = "The above errors were encountered!") }) test_that("Fail if missing iiv in IIV", { expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2, X1), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2, iiv=, X1), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2, iiv = NULL, X1), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2, iiv = NA_character_, X1), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2, iiv = character(0), X1), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2, iiv = "", X1), data=dataHigherMoments), regexp = "The above errors were encountered!") }) test_that("Fail if missing g in IIV", { expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(iiv=gy, X1), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=NULL,iiv=gy, X1), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=NA_character_, iiv=gy, X1), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=character(0), iiv=gy, X1), data=dataHigherMoments), regexp = "The above errors were encountered!") }) test_that("Fail if invalid iiv in IIV", { expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2, iiv=gpp, X1), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2, iiv=p, X1), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2, iiv=y3, X1), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2, iiv=c(g, gy), X1), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2, iiv=c("g", "g"), X1), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2, iiv=list(g), X1), data=dataHigherMoments), regexp = "The above errors were encountered!") }) test_that("Fail if multiple iiv in IIV", { expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2, iiv=g,iiv=g, X1), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2, iiv=g,(iiv=g), X1), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2, iiv=g,iiv=gp, X1), data=dataHigherMoments), regexp = "The above errors were encountered!") }) test_that("Fail if multiple g in IIV", { expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2, g=x3, iiv=g, X1), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2, g=x3, iiv=g, X1)+IIV(iiv=gp, X1), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=c(x2,x3), iiv=g, X1)+IIV(iiv=gp, X1), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=c("x2","x3"), iiv=g, X1)+IIV(iiv=gp, X1), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=list("x2","x3"), iiv=g, X1)+IIV(iiv=gp, X1), data=dataHigherMoments), regexp = "The above errors were encountered!") }) test_that("Fail if invalid colname in IIV", { expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2, iiv=g), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2, iiv=g, X3), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2, iiv=g, P), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2, iiv=g, X1, P), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2, iiv=g, X2, P), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2, iiv=g, X1, X3), data=dataHigherMoments), regexp = "The above errors were encountered!") }) test_that("Fail if non existent special function", { expect_error(higherMomentsIV(y~X1+X2+P|P|iiv(g=x2, iiv=g, X1,X2), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2, iiv=g, X1,X2)+iiv(g=x2, iiv=gy, X2), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2, iiv=g, X1,X2)+brunz(), data=dataHigherMoments), regexp = "The above errors were encountered!") }) test_that("Fail if transformation inside special", { expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2, iiv=g, log(X1)), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2, iiv=g, log(X1+X2)), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2, iiv=g, I(X1^2)), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x^2, iiv=g, X1), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=log(x), iiv=g, X1), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2, iiv=g*p, X1), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(iiv=g2*p, X1), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(iiv=x2*p, X1), data=dataHigherMoments), regexp = "The above errors were encountered!") }) test_that("Fail if transformation only for one var but not in special", { expect_error(higherMomentsIV(y~X1+log(X2)+P|P|IIV(g=x2, iiv=g, X2), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+log(X2)+P|P|IIV(g=x2, iiv=g, log(X1)), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~log(X1)+log(X2)+P|P|IIV(g=x2, iiv=g, log(X1+X2)), data=dataHigherMoments), regexp = "The above errors were encountered!") }) test_that("Fail if special outside RHS3", { expect_error(higherMomentsIV(y~IIV(g=x2, iiv=g,X1)+X2+P|P|IIV(g=x2, iiv=g,X2), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(IIV(g=x2, iiv=yp,y)~X1+X2+P|P|IIV(g=x2, iiv=g,X2), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|IIV(g=x2, iiv=yp,X1)|IIV(g=x2, iiv=g,X2), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2, iiv=yp,P)|IIV(g=x2, iiv=g,X2), data=dataHigherMoments), regexp = "The above errors were encountered!") }) test_that("Fail if missing g but IIV does require it", { expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(iiv=g, X1), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(iiv=gp, X1), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(iiv=gy, X1), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=,iiv=g, X1), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=,iiv=gp, X1), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=,iiv=gy, X1), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=NULL,iiv=g, X1), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=NULL,iiv=gp, X1), data=dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=NULL,iiv=gy, X1), data=dataHigherMoments), regexp = "The above errors were encountered!") }) test_that("Warning if g but IIV does not need it", { expect_warning(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2,iiv=yp, X1, X2), data=dataHigherMoments), regexp = "ignored", all = TRUE) expect_warning(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2,iiv=p2, X1, X2), data=dataHigherMoments), regexp = "ignored", all = TRUE) expect_warning(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2,iiv=y2, X1, X2), data=dataHigherMoments), regexp = "ignored", all = TRUE) }) test_that("Warning if exo regr but IIV does not need it", { expect_warning(higherMomentsIV(y~X1+X2+P|P|IIV(iiv=yp, X1, X2), data=dataHigherMoments), regexp = "ignored because they are not needed to built", all = TRUE) expect_warning(higherMomentsIV(y~X1+X2+P|P|IIV(iiv=p2, X1, X2), data=dataHigherMoments), regexp = "ignored because they are not needed to built", all = TRUE) expect_warning(higherMomentsIV(y~X1+X2+P|P|IIV(iiv=y2, X1, X2), data=dataHigherMoments), regexp = "ignored because they are not needed to built", all = TRUE) }) test_that("Silent if no g and IIV does not need it", { expect_silent(higherMomentsIV(y~X1+P|P|IIV(iiv=yp)+IIV(iiv=yp)+IIV(iiv=y2), data=dataHigherMoments, verbose = FALSE)) expect_silent(higherMomentsIV(y~X1+X2+P|P|IIV(g=,iiv=yp)+IIV(g=,iiv=p2)+IIV(g=,iiv=y2), data=dataHigherMoments, verbose=FALSE)) expect_silent(higherMomentsIV(y~X1+X2+P|P|IIV(g=NULL,iiv=yp)+IIV(g=,iiv=p2)+IIV(g=,iiv=y2), data=dataHigherMoments, verbose = FALSE)) }) context("Inputchecks - higherMomentsIV - Parameter data") test_that("Fail if is NA, NULL or missing", { expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2,iiv=g, X1), data= ), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2,iiv=g, X1), data=NULL), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2,iiv=g, X1), data=NA_real_), regexp = "The above errors were encountered!") }) test_that("Fail if not data.frame", { expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2,iiv=g, X1), data= c(y=1:10, X1=1:10, X2=1:10, P=1:10)), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2,iiv=g, X1), data= list(y=1:10, X1=1:10, X2=1:10, P=1:10)), regexp = "The above errors were encountered!") }) test_that("Fail if no rows or cols",{ expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2,iiv=g, X1), data= data.frame()), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2,iiv=g, X1), data= data.frame(y=integer(), X1=numeric(), X2=numeric(), P=integer())), regexp = "The above errors were encountered!") }) test_that("Fail if contains any non-finite", { call.args <- list(formula=y~X1+X2+P|P|IIV(g=x2,iiv=g, X1)) test.nonfinite.in.data(data = dataHigherMoments, name.col = "y", fct = higherMomentsIV, call.args = call.args) test.nonfinite.in.data(data = dataHigherMoments, name.col = "X1", fct = higherMomentsIV, call.args = call.args) test.nonfinite.in.data(data = dataHigherMoments, name.col = "X2", fct = higherMomentsIV, call.args = call.args) test.nonfinite.in.data(data = dataHigherMoments, name.col = "P", fct = higherMomentsIV, call.args = call.args) }) test_that("Fail if EIV not in data", { expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2,iiv=g, X1)|EIV,data= dataHigherMoments), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2,iiv=g, X1)|X1+eiv,data= dataHigherMoments), regexp = "The above errors were encountered!") }) test_that("Fail if wrong data type in endo", { expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2,iiv=g, X1),data= data.frame(y=1:10, X1=1:10, X2=1:10, P=factor(1:10))), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2,iiv=g, X1),data= data.frame(y=1:10, X1=1:10, X2=1:10, P=as.character(1:10), stringsAsFactors=FALSE)), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2,iiv=g, X1),data= data.frame(y=1:10, X1=1:10, X2=1:10, P=as.logical(0:9))), regexp = "The above errors were encountered!") }) test_that("Fail if wrong data type in exo used in IIV", { expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2,iiv=g, X1),data= data.frame(y=1:10, X1=factor(1:10), X2=1:10, P=1:10)), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2,iiv=g, X1),data=data.frame(y=1:10, X1=as.character(1:10), X2=1:10, P=1:10, stringsAsFactors=FALSE)), regexp = "The above errors were encountered!") expect_error(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2,iiv=g, X1),data= data.frame(y=1:10, X1=as.logical(0:9), X2=1:10, P=1:10)), regexp = "The above errors were encountered!") }) test_that("Allow wrong data type in irrelevant columns", { expect_silent(higherMomentsIV(y~X1+X2+P|P|IIV(g=x2,iiv=g,X2)+IIV(iiv=p2)+IIV(iiv=y2)+IIV(iiv=gp,g=x2,X1), verbose=FALSE, data = cbind(dataHigherMoments, unused1=as.logical(0:9), unused2=as.character(1:10),unused3=as.factor(1:10), stringsAsFactors = FALSE))) }) context("Inputchecks - higherMomentsIV - Parameter verbose") test.single.logical(function.to.test = higherMomentsIV, parameter.name="verbose", formula=y~X1+X2+P|P|IIV(g=x2,iiv=g, X1, X2), function.std.data=dataHigherMoments)
lastAdd <- function(fun) { if (!is.function(fun)) stop("fun must be a function") if (!exists(".Last", envir = .GlobalEnv, mode = "function")) { return(fun) } else { Last <- get(".Last", envir = .GlobalEnv, mode = "function") newfun <- function(...) { browser() fun() Last() } return(newfun) } }
expected <- eval(parse(text="logical(0)")); test(id=0, code={ argv <- eval(parse(text="list(structure(integer(0), .Label = character(0), class = \"factor\"))")); do.call(`>=`, argv); }, o=expected);
context("rr_publisher_id") test_that("rr_publisher_id() works", { expect_error(rr_publisher_id("a"), regexp = "All provided IDs should be integers") skip_on_cran() use_cassette("rr_publisher_id", { res <- rr_publisher_id(55) expect_is(res, "data.frame") expect_named(res, c("romeoid", "publisher", "alias", "romeocolour", "preprint", "postprint", "pdf")) expect_is(res$romeoid, "numeric") expect_is(res$publisher, "character") expect_is(res$alias, "character") expect_is(res$romeocolour, "character") expect_is(res$preprint, "character") expect_is(res$postprint, "character") expect_is(res$pdf, "character") expect_equal(res$alias, "OUP") expect_equal(res$pdf, "unclear") }) use_cassette("rr_publisher_id_multiple", { res <- rr_publisher_id(c(55, 735)) expect_is(res, "data.frame") expect_named(res, c("romeoid", "publisher", "alias", "romeocolour", "preprint", "postprint", "pdf")) expect_equal(dim(res), c(2, 7)) expect_is(res$romeoid, "numeric") expect_is(res$publisher, "character") expect_is(res$alias, "character") expect_is(res$romeocolour, "character") expect_is(res$preprint, "character") expect_is(res$postprint, "character") expect_is(res$pdf, "character") expect_equal(res$romeoid, c(55, 735)) }) use_cassette("rr_publisher_id_notfound", { expect_error(rr_publisher_id(1500000), "No publisher was found. Maybe try another query? ;)", fixed = TRUE) }) expect_error(rr_publisher_id("azerty"), "All provided IDs should be integers") use_cassette("api_unreachable_publisher", { expect_error(rr_publisher_id(55), paste0("The API endpoint could not be reached. Please try", " again later.")) }) })
testthat::context("Testing time.functions") testthat::test_that("tloglin functions correctly", { timefun <- tloglin(pool.rate="rel", method.rate="common") expect_equal(timefun$nparam, 1) expect_equal(timefun$apool, c("rate"="rel")) expect_equal(timefun$amethod, c("rate"="common")) expect_equal(timefun$name, "loglin") timefun <- tloglin(pool.rate="abs", method.rate="random") expect_equal(timefun$nparam, 1) expect_equal(timefun$apool, c("rate"="abs")) expect_equal(timefun$amethod, c("rate"="random")) expect_equal(timefun$name, "loglin") }) testthat::test_that("temax functions correctly", { timefun <- temax(pool.emax="rel", method.emax="common", pool.et50="rel", method.et50="common") expect_equal(timefun$nparam, 2) timefun <- temax(pool.emax="rel", method.emax="common", pool.et50="rel", method.et50="common", pool.hill="rel", method.hill="common") expect_equal(timefun$nparam, 3) expect_message(temax(pool.emax="rel", method.emax="common", pool.et50="rel", method.et50="common"), "et50") expect_message(temax(pool.emax="rel", method.emax="common", pool.et50="rel", method.et50="common", pool.hill="abs", method.hill="random"), "hill") timefun <- temax(pool.emax="abs", method.emax="random", pool.et50="rel", method.et50="random", pool.hill="abs", method.hill="common") expect_equal(timefun$apool, c(emax="abs", et50="rel", hill="abs")) expect_equal(timefun$amethod, c(emax="random", et50="random", hill="common")) })
Bornmann07 <- structure(list(Id = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L, 24L, 25L, 26L, 27L, 28L, 29L, 30L, 31L, 32L, 33L, 34L, 35L, 36L, 37L, 38L, 39L, 40L, 41L, 42L, 43L, 44L, 45L, 48L, 49L, 50L, 46L, 47L, 51L, 52L, 53L, 57L, 56L, 55L, 54L, 58L, 59L, 60L, 61L, 62L, 63L, 64L, 65L, 66L), Study = c("Ackers (2000a; Marie Curie)", "Ackers (2000b; Marie Curie)", "Ackers (2000c; Marie Curie)", "Ackers (2000d; Marie Curie)", "Ackers (2000e; Marie Curie)", "Ackers (2000f; Marie Curie)", "Ackers (2000g; Marie Curie)", "Allmendinger (2002a; DFG)", "Allmendinger (2002b; DFG)", "Allmendinger (2002c; DFG)", "Allmendinger (2002d; DFG)", "Allmendinger (2002e; DFG)", "Allmendinger (2002f; DFG)", "Allmendinger (2002g; DFG)", "Bazeley (1998; ARC)", "Bornmann (2005; BIF)", "Brouns (2000a; NWO/ KNAW)", "Brouns (2000b; NWO/ KNAW)", "Brouns (2000c; NWO/ KNAW)", "Brouns (2000d; NWO/ KNAW)", "Brouns (2000e; NWO/ KNAW)", "Dexter (2002a; Wellcome Trust)", "Dexter (2002b; Wellcome Trust)", "Dexter (2002c; Wellcome Trust)", "Emery (1992; NIH)", "Friesen (1998a; MRC)", "Friesen (1998b; MRC)", "Friesen (1998c; MRC)", "Goldsmith (2002a; NSF)", "Goldsmith (2002b; NSF)", "Grant (1997a; Wellcome Trust)", "Grant (1997b; Wellcome Trust)", "Grant (1997c; MRC)", "Grant (1997d; MRC)", "Jayasinghe (2001; ARC)", "National Science Foundation (2005a)", "National Science Foundation (2005b)", "National Science Foundation (2005c)", "National Science Foundation (2005d)", "National Science Foundation (2005e)", "National Science Foundation (2005f)", "National Science Foundation (2005g)", "National Science Foundation (2005h)", "Over (1996; ARC)", "Sigelman (1987; NSF)", "Taplick (2005a; EMBO)", "Taplick (2005b; EMBO)", "Taplick (2005c; EMBO)", "Viner (2004a; EPSRC)", "Viner (2004b; EPSRC)", "Ward (1998; NHMRC)", "Wellcome Trust (1997)", "Wenneras (1997; MRC)", "Willems (2001a; DFG)", "Willems (2001b; DFG)", "Willems (2001c; DFG)", "Willems (2001d; DFG)", "Wood (1997a; ARC)", "Wood (1997b; ARC)", "Wood (1997c; ARC)", "Wood (1997d; ARC)", "Wood (1997e; ARC)", "Wood (1997f; ARC)", "Wood (1997g; ARC)", "Wood (1997h; ARC)", "Wood (1997i; ARC)"), Cluster = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 4L, 5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 7L, 8L, 8L, 8L, 9L, 9L, 10L, 10L, 10L, 10L, 11L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 13L, 14L, 16L, 16L, 16L, 15L, 15L, 17L, 18L, 19L, 20L, 20L, 20L, 20L, 21L, 21L, 21L, 21L, 21L, 21L, 21L, 21L, 21L), logOR = c(-0.40108, -0.05727, -0.29852, 0.36094, -0.33336, -0.07173, -0.16793, -0.55585, -0.09217, 0.48184, -0.25672, -0.429, -0.55207, -1.113, -0.24714, -0.45176, -0.44629, -0.87855, 1.50539, -0.8546, -0.09465, 0.04879, -0.14259, -0.89097, 0.35229, -0.05753, -0.20078, -0.27131, -0.31304, -0.05053, -0.03353, 0.48551, 0.14548, -0.5499, -0.00307, 0.18275, 0.08592, -0.02845, 0.11214, 0.0739, 0.00872, 0.06467, 0.07257, 0.10536, -0.86392, -0.1039, -0.31322, -0.16188, 0.35424, 0.05373, 0.08573, 0.71562, -1.42885, -0.07833, -0.10434, -0.07452, -0.08312, -0.26194, -0.43191, -0.56531, -1.48881, -0.15985, 0.11464, -0.17096, 0.02763, 0.66155), v = c(0.0139169209, 0.0342879289, 0.0339112225, 0.03404025, 0.0128210329, 0.0136118889, 0.00583696, 0.3964969024, 0.5866794025, 0.7119478129, 0.2932547409, 0.43652449, 0.136161, 0.3360289024, 0.1291467969, 0.0092083216, 0.5400045225, 0.3606843249, 0.3146649025, 0.1750836649, 0.0834227689, 0.0438567364, 0.0225690529, 0.3852560761, 0.0899220169, 0.0056896849, 0.0768620176, 0.0157301764, 0.0106688241, 0.0051955264, 0.0235591801, 0.20967241, 0.0372219849, 0.1441341225, 0.01532644, 0.0009903609, 0.0009897316, 0.0010686361, 0.0009853321, 0.0009653449, 0.0008838729, 0.0008305924, 0.0007963684, 0.1429520481, 0.6091334209, 0.0151831684, 0.0035414401, 0.0460274116, 0.0258984649, 0.0228644641, 0.0510714801, 0.2265188836, 0.3550729744, 0.0065788321, 0.0057441241, 0.0062805625, 0.0055234624, 0.1470952609, 0.1526230489, 0.6184092321, 1.1067250401, 0.2695997929, 0.0751527396, 0.4548558249, 0.0569920129, 0.2744397769), Year = c(1996L, 1996L, 1996L, 1996L, 1996L, 1996L, 1996L, 1993L, 1994L, 1995L, 1996L, 1997L, 1998L, 1999L, 1995L, 1992L, 1994L, 1994L, 1994L, 1994L, 1994L, 2000L, 2000L, 2000L, 1990L, 1998L, 1998L, 1998L, 1979L, 1993L, 1996L, 1996L, 1996L, 1995L, 1996L, 1997L, 1998L, 1999L, 2000L, 2001L, 2002L, 2003L, 2004L, 1993L, 1986L, 2002L, 2000L, 2002L, 1994L, 1998L, 1996L, 1995L, 2001L, 2000L, 1999L, 1998L, 1997L, 1995L, 1995L, 1995L, 1995L, 1995L, 1995L, 1995L, 1995L, 1995L), Type = structure(c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 2L, 1L, 2L, 2L, 2L, 2L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("Grant", "Fellowship"), class = "factor"), Discipline = structure(c(1L, 1L, 1L, 1L, 3L, 1L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 2L, 3L, 3L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 4L, 4L, 2L, 2L, 2L, 2L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 3L, 2L, 2L, 2L, 1L, 1L, 2L, 2L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 3L, 1L, 3L, 1L), .Label = c("Physical sciences", "Life sciences/biology", "Social sciences/humanities", "Multidisciplinary"), class = "factor"), Country = structure(c(5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 3L, 5L, 5L, 5L, 5L, 5L, 5L, 4L, 4L, 4L, 1L, 2L, 2L, 2L, 1L, 1L, 4L, 4L, 4L, 4L, 3L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 3L, 1L, 5L, 5L, 5L, 4L, 4L, 3L, 4L, 5L, 5L, 5L, 5L, 5L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), .Label = c("United States", "Canada", "Australia", "United Kingdom", "Europe"), class = "factor")), .Names = c("Id", "Study", "Cluster", "logOR", "v", "Year", "Type", "Discipline", "Country"), row.names = c(NA, -66L), class = "data.frame")
module_correctedstats_server <- function(input, output, session, rv, input_re) { observe({ req(rv$corrected_finished) output$regression_stats_corrected_h <- renderUI({ output$dt_reg_corrected_h <- DT::renderDataTable({ dt <- rv$reg_stats_corrected_h render_regressionstatistics(dt, mode = "corrected", minmax = rv$minmax) }) d <- DT::dataTableOutput("moduleCorrectedStatistics-dt_reg_corrected_h") do.call(tagList, list(d)) }) output$regression_stats_corrected_c <- renderUI({ output$dt_reg_corrected_c <- DT::renderDataTable({ dt <- rv$reg_stats_corrected_c render_regressionstatistics(dt, mode = "corrected", minmax = rv$minmax) }) d <- DT::dataTableOutput("moduleCorrectedStatistics-dt_reg_corrected_c") do.call(tagList, list(d)) }) output$download_regstat_corrected_h <- downloadHandler( filename = function() { paste0( rv$sample_locus_name, "_corrected_regression_stats_h_", gsub("\\-", "", substr(Sys.time(), 1, 10)), "_", gsub("\\:", "", substr(Sys.time(), 12, 16)), ".csv" ) }, content = function(file) { rBiasCorrection::write_csv( table = rv$reg_stats_corrected_h[, -which( colnames(rv$reg_stats_corrected_h) == "better_model") , with = FALSE], filename = file) }, contentType = "text/csv" ) output$download_regstat_corrected_c <- downloadHandler( filename = function() { paste0( rv$sample_locus_name, "_corrected_regression_stats_c_", gsub("\\-", "", substr(Sys.time(), 1, 10)), "_", gsub("\\:", "", substr(Sys.time(), 12, 16)), ".csv" ) }, content = function(file) { rBiasCorrection::write_csv( table = rv$reg_stats_corrected_c[, -which( colnames(rv$reg_stats_corrected_c) == "better_model") , with = FALSE], filename = file) }, contentType = "text/csv" ) output$substitutions_corrected_h <- DT::renderDataTable({ DT::datatable(rv$substitutions_corrected_h, options = list(scrollX = TRUE, pageLength = 20, dom = "ltip"), rownames = FALSE) %>% DT::formatRound(columns = c(3:4), digits = 3) }) output$substitutions_corrected_c <- DT::renderDataTable({ DT::datatable(rv$substitutions_corrected_c, options = list(scrollX = TRUE, pageLength = 20, dom = "ltip"), rownames = FALSE) %>% DT::formatRound(columns = c(3:4), digits = 3) }) output$download_subs_corrected_h <- downloadHandler( filename = function() { paste0(rv$sample_locus_name, "_substituted_corrected_h_", rBiasCorrection::get_timestamp(), ".csv") }, content = function(file) { rBiasCorrection::write_csv( table = rv$substitutions_corrected_h, filename = file) }, contentType = "text/csv" ) output$download_subs_corrected_c <- downloadHandler( filename = function() { paste0(rv$sample_locus_name, "_substituted_corrected_c_", rBiasCorrection::get_timestamp(), ".csv") }, content = function(file) { rBiasCorrection::write_csv( table = rv$substitutions_corrected_c, filename = file) }, contentType = "text/csv" ) }) } module_correctedstatistics_ui <- function(id) { ns <- NS(id) tagList( fluidRow( column( 9, box( title = "Regression Statistics (corrected)", tabsetPanel( tabPanel( "Hyperbolic Correction", uiOutput(ns("regression_stats_corrected_h")) ), tabPanel( "Cubic Correction", uiOutput(ns("regression_stats_corrected_c")) ) ), width = 12 ) ), column( 3, box( title = "Download Regression Statistics (corrected)", uiOutput(ns("statistics_select")), div(class = "row", style = "text-align: center", downloadButton( ns("download_regstat_corrected_h"), "Download regression statistics (hyperbolic correction)", style = paste0( "white-space: normal; ", "text-align:center; ", "padding: 9.5px 9.5px 9.5px 9.5px; ", "margin: 6px 10px 6px 10px;"))), div(class = "row", style = "text-align: center", downloadButton( ns("download_regstat_corrected_c"), "Download regression statistics (cubic correction)", style = paste0( "white-space: normal; ", "text-align:center; ", "padding: 9.5px 9.5px 9.5px 9.5px; ", "margin: 6px 10px 6px 10px;"))), tags$hr(), width = 12 ) ) ), fluidRow( column( 9, box( title = "Substitutions (corrected)", tabsetPanel( tabPanel( "Hyperbolic Correction", DT::dataTableOutput(ns("substitutions_corrected_h")) ), tabPanel( "Cubic Correction", DT::dataTableOutput(ns("substitutions_corrected_c")) ) ), width = 12 ) ), column( 3, box( title = "Download substitutions (corrected)", div(class = "row", style = "text-align: center", downloadButton( ns("download_subs_corrected_h"), "Download substitutions (hyperbolic correction)", style = paste0( "white-space: normal; ", "text-align:center; ", "padding: 9.5px 9.5px 9.5px 9.5px; ", "margin: 6px 10px 6px 10px;"))), div(class = "row", style = "text-align: center", downloadButton( ns("download_subs_corrected_c"), "Download substitutions (cubic correction)", style = paste0( "white-space: normal; ", "text-align:center; ", "padding: 9.5px 9.5px 9.5px 9.5px; ", "margin: 6px 10px 6px 10px;"))), tags$hr(), width = 12 ) ) ) ) }
arrange.tbl_lazy <- function(.data, ..., .by_group = FALSE) { dots <- quos(...) dots <- partial_eval_dots(dots, vars = op_vars(.data)) names(dots) <- NULL if (is_empty(dots)) { return(.data) } add_op_single( "arrange", .data, dots = dots, args = list(.by_group = .by_group) ) } op_sort.op_arrange <- function(op) { op$dots } op_desc.op_arrange <- function(x, ...) { op_desc(x$x, ...) } sql_build.op_arrange <- function(op, con, ...) { order_vars <- translate_sql_(op$dots, con, context = list(clause = "ORDER")) if (op$args$.by_group) { order_vars <- c.sql(ident(op_grps(op$x)), order_vars, con = con) } select_query( sql_build(op$x, con), order_by = order_vars ) }
clusterPreset<- function( cloudProvider = c("","ECSFargateProvider"), container = c("", "rbaseDoRedis", "rbaseRedisParam", "biocDoRedis", "biocRedisParam" ) ){ cloudProvider <- match.arg(cloudProvider) container <- match.arg(container) provider <- NULL workerContainer <- NULL if(cloudProvider == "ECSFargateProvider"){ loadPackage("ECSFargateProvider") eval(parse(text = "provider <- ECSFargateProvider::ECSFargateProvider()")) } if(container == "rbaseDoRedis"){ loadPackage("doRedisContainer") eval(parse(text = "workerContainer <- doRedisContainer::doRedisWorkerContainer(image = \"r-base\")")) } if(container == "rbaseRedisParam"){ loadPackage("RedisParamContainer") eval(parse(text = "workerContainer <- RedisParamContainer::RedisParamWorkerContainer(image = \"r-base\")")) } if(container == "biocDoRedis"){ loadPackage("doRedisContainer") eval(parse(text = "workerContainer <- doRedisContainer::doRedisWorkerContainer(image = \"bioconductor\")")) } if(container == "biocRedisParam"){ loadPackage("RedisParamContainer") eval(parse(text = "workerContainer <- RedisParamContainer::RedisParamWorkerContainer(image = \"bioconductor\")")) } if(container!=""&&is.null(workerContainer)){ stop("Somethine is wrong") } packageSetting$cloudProvider <- provider packageSetting$workerContainer <- workerContainer invisible(NULL) } CloudPrivateServer <- function(publicIp = character(0), publicPort = integer(0), privateIp = character(0), privatePort = integer(0), password = "", serverWorkerSameLAN = FALSE, serverClientSameLAN = FALSE ){ list(publicIp = publicIp, publicPort = publicPort, privateIp = privateIp, privatePort = privatePort, password = password, serverWorkerSameLAN = serverWorkerSameLAN, serverClientSameLAN = serverClientSameLAN) }
context("bRacatus") input_data <- giftRegions ("Babiana tubulosa") input_data2 <- getOcc ("Babiana tubulosa") test_that("Expected data structure",{ expect_equal(class(input_data),"list") expect_true("Presence" %in% names(input_data)) expect_true("Native" %in% names(input_data)) expect_true("Alien" %in% names(input_data)) expect_equal(class(input_data2),"data.frame") })
data.into.Grid <- function(dataset.one.species, dimension, shift, resolution=1){ grid <- matrix(0,dimension[1],dimension[2]) long <- dataset.one.species$long lat <- dataset.one.species$lat long <- long - shift[1] lat <- lat - shift[2] long <- round(long / resolution) lat <- round(lat / resolution) for (i in 1:length(long)){ grid[long[i]+1,lat[i]+1] <- 1 } return(grid) }
person_changes <- function(api_key, id, start_date=NA, end_date=NA){ l <- list(start_date=start_date, end_date=end_date) l <- l[!is.na(l)] if(length(l)>0){ params <- paste("&", names(l), "=", stri_join_list(l, sep = ","), sep = "", collapse = "") url <- fromJSON(GET(url=paste("http://api.themoviedb.org/3/person/", id, "/changes?api_key=", api_key, params, sep=""))$url) } else{ url <- fromJSON(GET(url=paste("http://api.themoviedb.org/3/person/", id, "/changes?api_key=", api_key, sep=""))$url) } return(url) }
bfs_get_data <- function(url_bfs = NULL, language = "de", number_bfs = NULL, query = "all", column_name_type = "text", variable_value_type = "text", clean_names = FALSE) { if (missing(language)) stop("must choose a language, either 'de', 'fr', 'it' or 'en'", call. = FALSE) language <- match.arg(arg = language, choices = c("de", "fr", "it", "en")) if(is.null(number_bfs) & is.null(url_bfs)) { stop("Please fill url_bfs or number_bfs", call. = FALSE) } if(!is.null(number_bfs) & !is.null(url_bfs)) { stop("Please fill only url_bfs or number_bfs", call. = FALSE) } if(!is.null(url_bfs) & is.null(number_bfs)) { html_raw <- xml2::read_html(url_bfs) html_table <- rvest::html_node(html_raw, ".table") df_table <- rvest::html_table(html_table) number_bfs <- df_table$X2[grepl("px", df_table$X2)] if(!startsWith(number_bfs, "px")) { stop("The bfs number extracted do not start with 'px' from URL: ", url_bfs, "\nPlease add manually the bfs number with bfs_number.", call. = FALSE) } number_bfs } pxweb_api_url <- paste0("https://www.pxweb.bfs.admin.ch/api/v1/", language, "/", number_bfs, "/", number_bfs, ".px") df_json <- jsonlite::fromJSON(txt = pxweb_api_url) if(query == "all") { variables <- df_json$variables$code values <- df_json$variables$values df <- rbind(rep("*", length(values))) names(df) <- variables dims <- as.list(df) pxq <- pxweb::pxweb_query(dims) } else { if(!is.list(query)) { variables <- paste(df_json$variables$code, collapse = ", ") stop(paste0("`query` should be a list using the variables: ", variables, "."), call. = FALSE) } dims <- query pxq <- pxweb::pxweb_query(dims) } df_pxweb <- pxweb::pxweb_get_data(url = pxweb_api_url, query = pxq, column.name.type = column_name_type, variable.value.type = variable_value_type) tbl <- tibble::as_tibble(df_pxweb) if(clean_names) { tbl <- janitor::clean_names(tbl) } return(tbl) }
library(testthat) library(Publish) data(Diabetes) test_that("regressiontable: transformed variables and factor levels",{ Diabetes$hyp1 <- factor(1*(Diabetes$bp.1s>140)) Diabetes$ofak <- ordered(sample(letters[1:11],size=NROW(Diabetes),replace=1L)) levels(Diabetes$frame) <- c("+large","medi()um=.<",">8") f <- glm(hyp1~frame+gender+log(age)+I(chol>245)+ofak,data=Diabetes,family="binomial") regressionTable(f) summary(regressionTable(f)) }) test_that("plot.regressionTable",{ Diabetes$hyp1 <- factor(1*(Diabetes$bp.1s>140)) Diabetes$ofak <- ordered(sample(letters[1:11],size=NROW(Diabetes),replace=1L)) levels(Diabetes$frame) <- c("+large","medi()um=.<",">8") f <- glm(hyp1~frame+gender+log(age)+I(chol>245)+ofak,data=Diabetes,family="binomial") f <- glm(hyp1~log(age)+I(chol>245),data=Diabetes,family="binomial") u <- regressionTable(f) plot(u) })
makeTdmRandomSeed <- function(ID=0) { seedModBuf <- ID; getSeed <- function() { seedModBuf <<- seedModBuf+1; seed <- as.integer(Sys.time()) %% (seedModBuf+100001) } getSeed; } tdmRandomSeed <- makeTdmRandomSeed();
NULL spark_apply_worker_config <- function( sc, debug, profile, schema = FALSE, arrow = FALSE, fetch_result_as_sdf = TRUE, single_binary_column = FALSE) { worker_config_serialize( c( list( debug = isTRUE(debug), profile = isTRUE(profile), schema = isTRUE(schema), arrow = isTRUE(arrow), fetch_result_as_sdf = isTRUE(fetch_result_as_sdf), spark_version = spark_version(sc), single_binary_column = single_binary_column ), sc$config ) ) } spark_apply <- function(x, f, columns = NULL, memory = TRUE, group_by = NULL, packages = NULL, context = NULL, name = NULL, barrier = NULL, fetch_result_as_sdf = TRUE, partition_index_param = "", arrow_max_records_per_batch = NULL, auto_deps = FALSE, ...) { if (!is.character(partition_index_param)) { stop("Expected 'partition_index_param' to be a string.") } memory <- force(memory) args <- list(...) if (identical(fetch_result_as_sdf, FALSE)) { columns <- list(spark_apply_binary_result = "spark_apply_binary_result") } else { if (!identical(names(columns), NULL)) { columns <- as.list(columns) } } assert_that(is.function(f) || is.raw(f) || is.language(f)) if (is.language(f)) f <- rlang::as_closure(f) sc <- spark_connection(x) sdf <- spark_dataframe(x) sdf_columns <- colnames(x) if (identical(barrier, TRUE)) { args$rdd <- TRUE if (spark_version(sc) < "2.4.0") { stop("Barrier execution is only available for spark 2.4.0 or greater.") } if (is.null(columns)) { stop("Barrier execution requires explicit columns names.") } } if (spark_version(sc) < "2.0.0") args$rdd <- TRUE if (identical(args$rdd, TRUE)) { rdd_base <- invoke(sdf, "rdd") if (identical(columns, NULL)) columns <- colnames(x) } grouped <- !is.null(group_by) rlang <- spark_config_value(sc$config, "sparklyr.apply.rlang", FALSE) packages_config <- spark_config_value(sc$config, "sparklyr.apply.packages", NULL) proc_env <- c(connection_config(sc, "sparklyr.apply.env."), args$env) serialize_version <- spark_config_value(sc$config, "sparklyr.apply.serializer", 2) time_zone <- "" records_per_batch <- NULL arrow <- if (!is.null(args$arrow)) args$arrow else arrow_enabled(sc, sdf) if (identical(fetch_result_as_sdf, FALSE) && identical(arrow, TRUE)) { warning("Disabling arrow due to its potential incompatibility with fetch_result_as_sdf = FALSE") arrow <- FALSE } if (arrow) { time_zone <- spark_session(sc) %>% invoke("sessionState") %>% invoke("conf") %>% invoke("sessionLocalTimeZone") records_per_batch <- as.integer( arrow_max_records_per_batch %||% spark_session_config(sc)[["spark.sql.execution.arrow.maxRecordsPerBatch"]] %||% 10000 ) } if (sdf_is_streaming(sdf)) { sdf_limit <- sdf } else { sdf_limit <- invoke( sdf, "limit", cast_scalar_integer( spark_config_value(sc$config, "sparklyr.apply.schema.infer", 10) ) ) } if (!is.null(args$names)) { columns <- args$names } if (!is.null(group_by) && sdf_is_streaming(sdf)) { stop("'group_by' is unsupported with streams.") } if (identical(packages, NULL)) { if (identical(packages_config, NULL)) { packages <- TRUE } else { packages <- packages_config } } columns_typed <- length(names(columns)) > 0 if (rlang) warning("The `rlang` parameter is under active development.") if (spark_master_is_local(sc$master)) packages <- FALSE if (identical(tolower(sc$method), "livy") && identical(packages, TRUE)) packages <- FALSE context <- list( column_types = translate_spark_column_types(x), partition_index_param = partition_index_param, user_context = context ) rlang_serialize <- spark_apply_rlang_serialize() create_rlang_closure <- (rlang && !is.null(rlang_serialize)) serializer <- spark_apply_serializer() serialize_impl <- ( if (is.list(serializer)) { function(x, ...) serializer$serializer(x) } else { serializer }) deserializer <- spark_apply_deserializer() closure <- ( if (create_rlang_closure) { serialize_impl(NULL, version = serialize_version) } else if (is.function(f)) { suppressWarnings(serialize_impl(f, version = serialize_version)) } else { f }) context_serialize <- serialize_impl(context, version = serialize_version) closure_rlang <- if (create_rlang_closure) rlang_serialize(f) else raw() if (isTRUE(args$debug)) { message("Debugging spark_apply(), connect to worker debugging session as follows:") message(" 1. Find the workers <sessionid> and <port> in the worker logs, from RStudio click") message(" 'Log' under the connection, look for the last entry with contents:") message(" 'Session (<sessionid>) is waiting for sparklyr client to connect to port <port>'") message(" 2. From a new R session run:") message(" debugonce(sparklyr:::spark_worker_main)") message(" sparklyr:::spark_worker_main(<sessionid>, <port>)") } if (grouped) { colpos <- which(colnames(x) %in% group_by) if (length(colpos) != length(group_by)) stop("Not all group_by columns found.") group_by_list <- as.list(as.integer(colpos - 1)) if (!columns_typed) { columns <- c(group_by, columns) } if (identical(args$rdd, TRUE)) { rdd_base <- invoke_static(sc, "sparklyr.ApplyUtils", "groupBy", rdd_base, group_by_list) } else if (arrow) { sdf <- invoke_static(sc, "sparklyr.ApplyUtils", "groupByArrow", sdf, group_by_list, time_zone, records_per_batch) sdf_limit <- invoke_static(sc, "sparklyr.ApplyUtils", "groupByArrow", sdf_limit, group_by_list, time_zone, records_per_batch) } else { sdf <- invoke_static(sc, "sparklyr.ApplyUtils", "groupBy", sdf, group_by_list) sdf_limit <- invoke_static(sc, "sparklyr.ApplyUtils", "groupBy", sdf_limit, group_by_list) } } worker_port <- spark_config_value(sc$config, "sparklyr.gateway.port", "8880") packages <- unlist(packages) if (auto_deps && !spark_apply_packages_is_bundle(packages)) { required_pkgs <- infer_required_r_packages(f) if (is.character(packages)) { packages <- union(packages, required_pkgs) } else { packages <- required_pkgs } } bundle_path <- get_spark_apply_bundle_path(sc, packages) spark_apply_options <- lapply( connection_config(sc, "sparklyr.apply.options."), as.character ) if (!is.null(records_per_batch)) spark_apply_options[["maxRecordsPerBatch"]] <- as.character(records_per_batch) if (identical(args$rdd, TRUE)) { if (identical(barrier, TRUE)) { rdd <- invoke_static( sc, "sparklyr.RDDBarrier", "transformBarrier", rdd_base, closure, as.list(sdf_columns), spark_apply_worker_config( sc, args$debug, args$profile, arrow = arrow, fetch_result_as_sdf = fetch_result_as_sdf, single_binary_column = args$single_binary_column ), as.integer(worker_port), as.list(group_by), closure_rlang, bundle_path, as.integer(60), as.environment(proc_env), context_serialize, as.environment(spark_apply_options), serialize(serializer, NULL, version = serialize_version), serialize(deserializer, NULL, version = serialize_version) ) } else { rdd <- invoke_static( sc, "sparklyr.WorkerHelper", "computeRdd", rdd_base, closure, spark_apply_worker_config( sc, args$debug, args$profile, arrow = arrow, fetch_result_as_sdf = fetch_result_as_sdf, single_binary_column = args$single_binary_column ), as.integer(worker_port), as.list(sdf_columns), as.list(group_by), closure_rlang, bundle_path, as.environment(proc_env), as.integer(60), context_serialize, as.environment(spark_apply_options), serialize(serializer, NULL, version = serialize_version), serialize(deserializer, NULL, version = serialize_version) ) } if (memory) rdd <- invoke(rdd, "cache") schema <- spark_schema_from_rdd(sc, rdd, columns) transformed <- invoke(hive_context(sc), "createDataFrame", rdd, schema) } else { json_cols <- c() if (identical(columns, NULL) || is.character(columns)) { columns_schema <- spark_data_build_types( sc, list( names = "character", types = "character", json_cols = "character" ) ) columns_op <- invoke_static( sc, "sparklyr.WorkerHelper", "computeSdf", sdf_limit, columns_schema, closure, spark_apply_worker_config( sc, args$debug, args$profile, schema = TRUE, arrow = arrow, fetch_result_as_sdf = fetch_result_as_sdf, single_binary_column = args$single_binary_column ), as.integer(worker_port), as.list(sdf_columns), as.list(group_by), closure_rlang, bundle_path, as.environment(proc_env), as.integer(60), context_serialize, as.environment(spark_apply_options), spark_session(sc), time_zone, serialize(serializer, NULL, version = serialize_version), serialize(deserializer, NULL, version = serialize_version) ) columns_query <- columns_op %>% sdf_collect() columns_infer <- strsplit(columns_query[1, ]$types, split = "\\|")[[1]] names(columns_infer) <- strsplit(columns_query[1, ]$names, split = "\\|")[[1]] json_cols <- array(strsplit(columns_query[1, ]$json_cols, split = "\\|")[[1]]) if (is.character(columns)) { names(columns_infer)[seq_along(columns)] <- columns } columns <- columns_infer if (identical(args$schema, TRUE)) { return(columns) } } schema <- spark_data_build_types(sc, columns) transformed <- invoke_static( sc, "sparklyr.WorkerHelper", "computeSdf", sdf, schema, closure, spark_apply_worker_config( sc, args$debug, args$profile, arrow = arrow, fetch_result_as_sdf = fetch_result_as_sdf, single_binary_column = args$single_binary_column ), as.integer(worker_port), as.list(sdf_columns), as.list(group_by), closure_rlang, bundle_path, as.environment(proc_env), as.integer(60), context_serialize, as.environment(spark_apply_options), spark_session(sc), time_zone, serialize(serializer, NULL, version = serialize_version), serialize(deserializer, NULL, version = serialize_version) ) if (spark_version(sc) >= "2.4.0" && !is.na(json_cols) && length(json_cols) > 0) { transformed <- invoke_static( sc, "sparklyr.StructColumnUtils", "parseJsonColumns", transformed, json_cols ) } } if (identical(barrier, TRUE)) { registered <- transformed } else { name <- name %||% random_string("sparklyr_tmp_") registered <- sdf_register(transformed, name = name) if (memory && !identical(args$rdd, TRUE) && !sdf_is_streaming(sdf)) tbl_cache(sc, name, force = FALSE) } if (identical(fetch_result_as_sdf, FALSE)) { registered %>% sdf_collect(arrow = arrow) %>% ( function(x) { lapply(x$spark_apply_binary_result, function(res) deserializer(res[[1]])) }) } else { registered } } spark_apply_rlang_serialize <- function() { rlang_serialize <- core_get_package_function("rlang", "serialise_bytes") if (is.null(rlang_serialize)) { core_get_package_function("rlanglabs", "serialise_bytes") } else { rlang_serialize } } spark_apply_serializer <- function() { serializer <- getOption("sparklyr.spark_apply.serializer") impl <- ( if (identical(serializer, "qs")) { qserialize <- core_get_package_function("qs", "qserialize") if (is.null(qserialize)) { stop( "Unable to locate qs::qserialize(). Please ensure 'qs' is installed." ) } function(x, ...) qserialize(x) } else if (is.null(serializer)) { function(x, version = NULL) serialize(x, NULL, version = version) } else { list(serializer = serializer) }) impl } spark_apply_deserializer <- function() { if (identical(getOption("sparklyr.spark_apply.serializer"), "qs")) { impl <- core_get_package_function("qs", "qdeserialize") if (is.null(impl)) { stop( "Unable to locate qs::qdeserialize(). Please ensure 'qs' is installed." ) } impl } else { getOption("sparklyr.spark_apply.deserializer") %||% unserialize } } spark_apply_log <- function(..., level = "INFO") { worker_log_level(..., level = level, component = "RClosure") }
context("Test outputs of C++ functions directly") dtm <- nih_sample_dtm k <- 10 alpha <- rep(0.1, k) eta <- matrix(0.05, nrow = k, ncol = ncol(dtm)) counts <- initialize_topic_counts( dtm = dtm, k = 4, alpha = rep(0.1, 10), eta = matrix(0.05, nrow = 10, ncol = ncol(dtm)), threads = 1 ) m <- fit_lda_c( Docs = counts$Docs, Zd_in = counts$Zd, eta_in = eta, alpha_in = alpha, Cd_in = counts$Cd, Cv_in = counts$Cv, Ck_in = counts$Ck, Beta_in = counts$Cv, iterations = 20, burnin = 10, freeze_topics = FALSE, calc_likelihood = TRUE, optimize_alpha = TRUE, verbose = FALSE ) test_that("checksums match expectation",{ sum_tokens <- sum(dtm) expect_equal(sum(m$Cd), sum_tokens) expect_equal(sum(m$Cv), sum_tokens) expect_equal(sum(m$Cd_mean), sum_tokens) expect_equal(sum(m$Cv_mean), sum_tokens) }) test_that("optimize_alpha doesn't break anything",{ expect_equal(sum(m$alpha), sum(alpha)) expect_true(sum(is.na(rowSums(m$log_likelihood))) == 0, "log likelihood check") })
show_DBIDriver <- function(object) { tryCatch( show_driver(object), error = function(e) NULL ) invisible(NULL) } setMethod("show", signature("DBIDriver"), show_DBIDriver)
.varCRDDiff <- function(nclus, nindiv, prtreat, tauy=NULL, sigma2y=NULL, totalvar=NULL, iccy=NULL, r2between = 0, r2within = 0, numpredictor = 0, assurance=NULL) { if(is.null(tauy)) { if(is.null(iccy)) { tauy <- totalvar - sigma2y } else { tauy <- iccy * totalvar } } if(is.null(sigma2y)) { if(is.null(iccy)) { sigma2y <- totalvar - tauy } else { sigma2y <- (1 - iccy) * totalvar } } if(length(nindiv) > 1) { sigma2y <- sigma2y * (1 - r2within) tauy <- tauy * (1 - r2between) D <- 1/sigma2y F <- 0 - (tauy)/(sigma2y * (sigma2y + nindiv*tauy)) ntreat <- round(prtreat*nclus) prtreat <- ntreat/nclus terms <- nindiv * (D + nindiv*F) termstotal <- sum(terms) termstreatment <- sum(terms[1:ntreat]) vargamma1 <- termstotal/(termstotal*termstreatment - termstreatment^2) varclusmean <- vargamma1 * (nclus * prtreat * (1 - prtreat)) } else { ntreat <- round(prtreat*nclus) prtreat <- ntreat/nclus varclusmean <- ((sigma2y * (1 - r2within)) / nindiv) + (tauy * (1 - r2between)) } if(!is.null(assurance)) { df <- nclus - 2 - numpredictor varclusmean <- varclusmean * qchisq(assurance, df) / df } denominator <- nclus * prtreat * (1 - prtreat) return(varclusmean/denominator) } .costCRD <- function(nclus, nindiv, cluscost, indivcost, diffsize = NULL) { nindiv[nindiv == "> 100000"] <- Inf nindiv <- as.numeric(nindiv) if(!is.null(diffsize)) nindiv <- .findNindivVec(nindiv, diffsize, nclus) result <- NULL if(length(nindiv) > 1) { result <- (nclus * cluscost) + sum(nindiv * indivcost) } else { result <- nclus * (cluscost + (nindiv * indivcost)) } return(result) } .findWidthCRDDiff <- function(nclus, nindiv, prtreat, tauy=NULL, sigma2y=NULL, totalvar=NULL, iccy=NULL, r2between = 0, r2within = 0, numpredictor = 0, assurance=NULL, conf.level = 0.95, diffsize = NULL) { nclus <- as.numeric(nclus) prtreat <- round(nclus * prtreat)/nclus nindiv <- as.numeric(nindiv) if(!is.null(diffsize)) nindiv <- .findNindivVec(nindiv, diffsize, nclus) v <- .varCRDDiff(nclus=nclus, nindiv=nindiv, prtreat=prtreat, tauy=tauy, sigma2y=sigma2y, totalvar=totalvar, iccy=iccy, r2between = r2between, r2within = r2within, numpredictor = numpredictor, assurance=assurance) alpha <- 1 - conf.level width <- 2 * sqrt(v) * qt(1 - alpha/2, nclus - 2 - numpredictor) return(width) } .findNindivVec <- function(nindiv, diffsize, nclus) { isInteger <- all(round(diffsize) == diffsize) result <- NULL if(isInteger) { result <- rep(nindiv + diffsize, length.out=nclus) } else { result <- rep(round(nindiv * diffsize), length.out=nclus) } result[result < 1] <- 1 result } .findNclusCRDDiff <- function(width, nindiv, prtreat, tauy=NULL, sigma2y=NULL, totalvar=NULL, iccy=NULL, r2between = 0, r2within = 0, numpredictor = 0, assurance=NULL, conf.level = 0.95, diffsize=NULL) { nclus <- seq(100, 1000, 100) result <- sapply(nclus, .findWidthCRDDiff, nindiv=nindiv, prtreat=prtreat, tauy=tauy, sigma2y=sigma2y, totalvar=totalvar, iccy=iccy, r2between = r2between, r2within = r2within, numpredictor = numpredictor, assurance=assurance, conf.level=conf.level, diffsize=diffsize) if(all(width > result)) { nclus <- seq(ceiling(2 * (1/min(prtreat, 1 - prtreat))) + numpredictor, 100, 1) result <- sapply(nclus, .findWidthCRDDiff, nindiv=nindiv, prtreat=prtreat, tauy=tauy, sigma2y=sigma2y, totalvar=totalvar, iccy=iccy, r2between = r2between, r2within = r2within, numpredictor = numpredictor, assurance=assurance, conf.level=conf.level, diffsize=diffsize) if(all(width > result)) { return(3 + numpredictor) } else if (all(width < result)) { return(100) } else { return(nclus[which(width > result)[1]]) } } else if (all(width < result)) { start <- 1000 repeat { nclus <- seq(start, start + 1000, 100) result <- sapply(nclus, .findWidthCRDDiff, nindiv=nindiv, prtreat=prtreat, tauy=tauy, sigma2y=sigma2y, totalvar=totalvar, iccy=iccy, r2between = r2between, r2within = r2within, numpredictor = numpredictor, assurance=assurance, conf.level=conf.level, diffsize=diffsize) if(all(width > result)) { return(start) } else if (all(width < result)) { start <- start + 1000 } else { minval <- nclus[which(width > result)[1] - 1] maxval <- nclus[which(width > result)[1]] nclus <- seq(minval, maxval, 1) result <- sapply(nclus, .findWidthCRDDiff, nindiv=nindiv, prtreat=prtreat, tauy=tauy, sigma2y=sigma2y, totalvar=totalvar, iccy=iccy, r2between = r2between, r2within = r2within, numpredictor = numpredictor, assurance=assurance, conf.level=conf.level, diffsize=diffsize) if(all(width > result)) { return(minval) } else if (all(width < result)) { return(maxval) } else { return(nclus[which(width > result)[1]]) } } } } else { minval <- nclus[which(width > result)[1] - 1] maxval <- nclus[which(width > result)[1]] nclus <- seq(minval, maxval, 1) result <- sapply(nclus, .findWidthCRDDiff, nindiv=nindiv, prtreat=prtreat, tauy=tauy, sigma2y=sigma2y, totalvar=totalvar, iccy=iccy, r2between = r2between, r2within = r2within, numpredictor = numpredictor, assurance=assurance, conf.level=conf.level, diffsize=diffsize) if(all(width > result)) { return(minval) } else if (all(width < result)) { return(maxval) } else { return(nclus[which(width > result)[1]]) } } } .findNindivCRDDiff <- function(width, nclus, prtreat, tauy=NULL, sigma2y=NULL, totalvar=NULL, iccy=NULL, r2between = 0, r2within = 0, numpredictor = 0, assurance=NULL, conf.level = 0.95, diffsize = NULL) { baremaximum <- .findWidthCRDDiff(nclus=nclus, nindiv=100000, prtreat=prtreat, tauy=tauy, sigma2y=sigma2y, totalvar=totalvar, iccy=iccy, r2between = r2between, r2within = r2within, numpredictor = numpredictor, assurance=assurance, conf.level=conf.level, diffsize=diffsize) if(width < baremaximum) return("> 100000") nindiv <- seq(100, 1000, 100) result <- sapply(nindiv, .findWidthCRDDiff, nclus=nclus, prtreat=prtreat, tauy=tauy, sigma2y=sigma2y, totalvar=totalvar, iccy=iccy, r2between = r2between, r2within = r2within, numpredictor = numpredictor, assurance=assurance, conf.level=conf.level, diffsize=diffsize) if(all(width > result)) { nindiv <- seq(2, 100, 1) result <- sapply(nindiv, .findWidthCRDDiff, nclus=nclus, prtreat=prtreat, tauy=tauy, sigma2y=sigma2y, totalvar=totalvar, iccy=iccy, r2between = r2between, r2within = r2within, numpredictor = numpredictor, assurance=assurance, conf.level=conf.level, diffsize=diffsize) if(all(width > result)) { return(2) } else if (all(width < result)) { return(100) } else { return(nindiv[which(width > result)[1]]) } } else if (all(width < result)) { start <- 1000 repeat { nindiv <- seq(start, start + 1000, 100) result <- sapply(nindiv, .findWidthCRDDiff, nclus=nclus, prtreat=prtreat, tauy=tauy, sigma2y=sigma2y, totalvar=totalvar, iccy=iccy, r2between = r2between, r2within = r2within, numpredictor = numpredictor, assurance=assurance, conf.level=conf.level, diffsize=diffsize) if(all(width > result)) { return(start) } else if (all(width < result)) { start <- start + 1000 } else { minval <- nindiv[which(width > result)[1] - 1] maxval <- nindiv[which(width > result)[1]] nindiv <- seq(minval, maxval, 1) result <- sapply(nindiv, .findWidthCRDDiff, nclus=nclus, prtreat=prtreat, tauy=tauy, sigma2y=sigma2y, totalvar=totalvar, iccy=iccy, r2between = r2between, r2within = r2within, numpredictor = numpredictor, assurance=assurance, conf.level=conf.level, diffsize=diffsize) if(all(width > result)) { return(minval) } else if (all(width < result)) { return(maxval) } else { return(nindiv[which(width > result)[1]]) } } } } else { minval <- nindiv[which(width > result)[1] - 1] maxval <- nindiv[which(width > result)[1]] nindiv <- seq(minval, maxval, 1) result <- sapply(nindiv, .findWidthCRDDiff, nclus=nclus, prtreat=prtreat, tauy=tauy, sigma2y=sigma2y, totalvar=totalvar, iccy=iccy, r2between = r2between, r2within = r2within, numpredictor = numpredictor, assurance=assurance, conf.level=conf.level, diffsize=diffsize) if(all(width > result)) { return(minval) } else if (all(width < result)) { return(maxval) } else { return(nindiv[which(width > result)[1]]) } } } .findMinCostCRDDiff <- function(width, cluscost=0, indivcost=1, prtreat, tauy=NULL, sigma2y=NULL, totalvar=NULL, iccy=NULL, r2between = 0, r2within = 0, numpredictor = 0, assurance=NULL, conf.level = 0.95, diffsize = NULL) { nclus <- seq(100, 1100, 100) repeat { nindiv <- sapply(nclus, .findNindivCRDDiff, width=width, prtreat=prtreat, tauy=tauy, sigma2y=sigma2y, totalvar=totalvar, iccy=iccy, r2between = r2between, r2within = r2within, numpredictor = numpredictor, assurance=assurance, conf.level=conf.level, diffsize=diffsize) cost <- mapply(.costCRD, nclus=nclus, nindiv=nindiv, MoreArgs=list(cluscost=cluscost, indivcost=indivcost, diffsize=diffsize), SIMPLIFY=TRUE) if(!all(cost == Inf)) break nclus <- nclus + 1000 } posmin <- which(cost == min(cost)) if(length(posmin) > 1) posmin <- posmin[1] if(posmin == 1) { nclus <- seq(ceiling(2 * (1/min(prtreat, 1 - prtreat))) + numpredictor, 200, 1) nindiv <- sapply(nclus, .findNindivCRDDiff, width=width, prtreat=prtreat, tauy=tauy, sigma2y=sigma2y, totalvar=totalvar, iccy=iccy, r2between = r2between, r2within = r2within, numpredictor = numpredictor, assurance=assurance, conf.level=conf.level, diffsize=diffsize) cost <- mapply(.costCRD, nclus=nclus, nindiv=nindiv, MoreArgs=list(cluscost=cluscost, indivcost=indivcost, diffsize=diffsize), SIMPLIFY=TRUE) posmin <- which(cost == min(cost)) if(length(posmin) > 1) posmin <- posmin[1] return(c(nclus[posmin], nindiv[posmin], cost[posmin])) } else if (posmin == length(cost)) { start <- nclus[length(nclus) - 1] repeat { nclus <- seq(start, start + 1100, 100) nindiv <- sapply(nclus, .findNindivCRDDiff, width=width, prtreat=prtreat, tauy=tauy, sigma2y=sigma2y, totalvar=totalvar, iccy=iccy, r2between = r2between, r2within = r2within, numpredictor = numpredictor, assurance=assurance, conf.level=conf.level, diffsize=diffsize) cost <- mapply(.costCRD, nclus=nclus, nindiv=nindiv, MoreArgs=list(cluscost=cluscost, indivcost=indivcost, diffsize=diffsize), SIMPLIFY=TRUE) posmin <- which(cost == min(cost)) if(length(posmin) > 1) posmin <- posmin[1] if(posmin == 1) { return(c(nclus[posmin], nindiv[posmin], cost[posmin])) } else if (posmin == length(cost)) { start <- start + 1000 } else { minval <- nclus[posmin - 1] maxval <- nclus[posmin + 1] nclus <- seq(minval, maxval, 1) nindiv <- sapply(nclus, .findNindivCRDDiff, width=width, prtreat=prtreat, tauy=tauy, sigma2y=sigma2y, totalvar=totalvar, iccy=iccy, r2between = r2between, r2within = r2within, numpredictor = numpredictor, assurance=assurance, conf.level=conf.level, diffsize=diffsize) cost <- mapply(.costCRD, nclus=nclus, nindiv=nindiv, MoreArgs=list(cluscost=cluscost, indivcost=indivcost, diffsize=diffsize), SIMPLIFY=TRUE) posmin <- which(cost == min(cost)) if(length(posmin) > 1) posmin <- posmin[1] return(c(nclus[posmin], nindiv[posmin], cost[posmin])) } } } else { minval <- nclus[posmin - 1] maxval <- nclus[posmin + 1] nclus <- seq(minval, maxval, 1) nindiv <- sapply(nclus, .findNindivCRDDiff, width=width, prtreat=prtreat, tauy=tauy, sigma2y=sigma2y, totalvar=totalvar, iccy=iccy, r2between = r2between, r2within = r2within, numpredictor = numpredictor, assurance=assurance, conf.level=conf.level, diffsize=diffsize) cost <- mapply(.costCRD, nclus=nclus, nindiv=nindiv, MoreArgs=list(cluscost=cluscost, indivcost=indivcost, diffsize=diffsize), SIMPLIFY=TRUE) posmin <- which(cost == min(cost)) if(length(posmin) > 1) posmin <- posmin[1] return(c(nclus[posmin], nindiv[posmin], cost[posmin])) } } .findNindivCRDBudget <- function(budget, nclus, cluscost, indivcost, diffsize = NULL) { nindiv <- seq(100, 1000, 100) result <- sapply(nindiv, .costCRD, nclus=nclus, cluscost=cluscost, indivcost=indivcost, diffsize=diffsize) if(all(budget < result)) { nindiv <- seq(2, 100, 1) result <- sapply(nindiv, .costCRD, nclus=nclus, cluscost=cluscost, indivcost=indivcost, diffsize=diffsize) if(all(budget < result)) { return(NA) } else if (all(budget > result)) { return(100) } else { index <- which(budget >= result) return(nindiv[index[length(index)]]) } } else if (all(budget > result)) { start <- 1000 repeat { nindiv <- seq(start, start + 1000, 100) result <- sapply(nindiv, .costCRD, nclus=nclus, cluscost=cluscost, indivcost=indivcost, diffsize=diffsize) if(all(budget < result)) { return(start) } else if (all(budget > result)) { start <- start + 1000 } else { minval <- nindiv[which(budget < result)[1] - 1] maxval <- nindiv[which(budget < result)[1]] nindiv <- seq(minval, maxval, 1) result <- sapply(nindiv, .costCRD, nclus=nclus, cluscost=cluscost, indivcost=indivcost, diffsize=diffsize) if(all(budget < result)) { return(minval) } else if (all(budget > result)) { return(maxval) } else { index <- which(budget >= result) return(nindiv[index[length(index)]]) } } } } else { minval <- nindiv[which(budget < result)[1] - 1] maxval <- nindiv[which(budget < result)[1]] nindiv <- seq(minval, maxval, 1) result <- sapply(nindiv, .costCRD, nclus=nclus, cluscost=cluscost, indivcost=indivcost, diffsize=diffsize) if(all(budget < result)) { return(minval) } else if (all(budget > result)) { return(maxval) } else { index <- which(budget >= result) return(nindiv[index[length(index)]]) } } } .findMinWidthCRDDiff <- function(budget, cluscost=0, indivcost=1, prtreat, tauy=NULL, sigma2y=NULL, totalvar=NULL, iccy=NULL, r2between = 0, r2within = 0, numpredictor = 0, assurance=NULL, conf.level = 0.95, diffsize = NULL) { FUN <- function(nclus, nindiv) { .findWidthCRDDiff(nclus=nclus, nindiv=nindiv, prtreat=prtreat, tauy=tauy, sigma2y=sigma2y, totalvar=totalvar, iccy=iccy, r2between = r2between, r2within = r2within, numpredictor = numpredictor, assurance=assurance, conf.level=conf.level, diffsize=diffsize) } nclus <- seq(100, 1100, 100) nindiv <- sapply(nclus, .findNindivCRDBudget, budget=budget, cluscost=cluscost, indivcost=indivcost, diffsize=diffsize) if(all(is.na(nindiv))) { posmin <- 1 } else { resultwidth <- rep(NA, length(nclus)) resultwidth[!is.na(nindiv)] <- mapply(FUN, nclus=nclus[!is.na(nindiv)], nindiv=nindiv[!is.na(nindiv)], SIMPLIFY=TRUE) posmin <- which(resultwidth == min(resultwidth, na.rm=TRUE)) } if(posmin == 1) { nclus <- seq(ceiling(2 * (1/min(prtreat, 1 - prtreat))) + numpredictor, 200, 1) nindiv <- sapply(nclus, .findNindivCRDBudget, budget=budget, cluscost=cluscost, indivcost=indivcost, diffsize=diffsize) resultwidth <- rep(NA, length(nclus)) resultwidth[!is.na(nindiv)] <- mapply(FUN, nclus=nclus[!is.na(nindiv)], nindiv=nindiv[!is.na(nindiv)]) posmin <- which(resultwidth == min(resultwidth, na.rm=TRUE)) return(c(nclus[posmin], nindiv[posmin], resultwidth[posmin])) } else if (posmin == length(resultwidth)) { start <- nclus[length(nclus) - 1] repeat { nclus <- seq(start, start + 1100, 100) nindiv <- sapply(nclus, .findNindivCRDBudget, budget=budget, cluscost=cluscost, indivcost=indivcost, diffsize=diffsize) resultwidth <- rep(NA, length(nclus)) resultwidth[!is.na(nindiv)] <- mapply(FUN, nclus=nclus[!is.na(nindiv)], nindiv=nindiv[!is.na(nindiv)]) posmin <- which(resultwidth == min(resultwidth, na.rm=TRUE)) if(posmin == 1) { return(c(nclus[posmin], nindiv[posmin], resultwidth[posmin])) } else if (posmin == length(resultwidth)) { start <- start + 1000 } else { minval <- nclus[posmin - 1] maxval <- nclus[posmin + 1] nclus <- seq(minval, maxval, 1) nindiv <- sapply(nclus, .findNindivCRDBudget, budget=budget, cluscost=cluscost, indivcost=indivcost, diffsize=diffsize) resultwidth <- rep(NA, length(nclus)) resultwidth[!is.na(nindiv)] <- mapply(FUN, nclus=nclus[!is.na(nindiv)], nindiv=nindiv[!is.na(nindiv)]) posmin <- which(resultwidth == min(resultwidth, na.rm=TRUE)) return(c(nclus[posmin], nindiv[posmin], resultwidth[posmin])) } } } else { minval <- nclus[posmin - 1] maxval <- nclus[posmin + 1] nclus <- seq(minval, maxval, 1) nindiv <- sapply(nclus, .findNindivCRDBudget, budget=budget, cluscost=cluscost, indivcost=indivcost, diffsize=diffsize) resultwidth <- rep(NA, length(nclus)) resultwidth[!is.na(nindiv)] <- mapply(FUN, nclus=nclus[!is.na(nindiv)], nindiv=nindiv[!is.na(nindiv)]) posmin <- which(resultwidth == min(resultwidth, na.rm=TRUE)) return(c(nclus[posmin], nindiv[posmin], resultwidth[posmin])) } } .findNclusCRDBudget <- function(budget, nindiv, cluscost, indivcost, diffsize = NULL) { nclus <- seq(100, 1000, 100) result <- sapply(nclus, .costCRD, nindiv=nindiv, cluscost=cluscost, indivcost=indivcost, diffsize=diffsize) if(all(budget < result)) { nclus <- seq(4, 100, 1) result <- sapply(nclus, .costCRD, nindiv=nindiv, cluscost=cluscost, indivcost=indivcost, diffsize=diffsize) if(all(budget < result)) { return(NA) } else if (all(budget > result)) { return(100) } else { index <- which(budget >= result) return(nclus[index[length(index)]]) } } else if (all(budget > result)) { start <- 1000 repeat { nclus <- seq(start, start + 1000, 100) result <- sapply(nclus, .costCRD, nindiv=nindiv, cluscost=cluscost, indivcost=indivcost, diffsize=diffsize) if(all(budget < result)) { return(start) } else if (all(budget > result)) { start <- start + 1000 } else { minval <- nclus[which(budget < result)[1] - 1] maxval <- nclus[which(budget < result)[1]] nclus <- seq(minval, maxval, 1) result <- sapply(nclus, .costCRD, nindiv=nindiv, cluscost=cluscost, indivcost=indivcost, diffsize=diffsize) if(all(budget < result)) { return(minval) } else if (all(budget > result)) { return(maxval) } else { index <- which(budget >= result) return(nclus[index[length(index)]]) } } } } else { minval <- nclus[which(budget < result)[1] - 1] maxval <- nclus[which(budget < result)[1]] nclus <- seq(minval, maxval, 1) result <- sapply(nclus, .costCRD, nindiv=nindiv, cluscost=cluscost, indivcost=indivcost, diffsize=diffsize) if(all(budget < result)) { return(minval) } else if (all(budget > result)) { return(maxval) } else { index <- which(budget >= result) return(nclus[index[length(index)]]) } } } .reportCRD <- function(nclus, nindiv, width=NULL, cost=NULL, es=FALSE, estype=0, assurance=NULL, diffsize = NULL) { cat(paste("The number of clusters is ", nclus, ".\n", sep="")) if(is.null(diffsize)) { cat(paste("The cluster size is ", nindiv, ".\n", sep="")) } else { cat("The cluster size is as follows:\n") out <- data.frame(table(.findNindivVec(as.numeric(nindiv), diffsize, nclus))) colnames(out) <- c("Cluster Size", "Frequency") print(out) } if(!is.null(width)) { if(es) { eslab <- NULL if(estype == 0) { eslab <- "total" } else if (estype == 1) { eslab <- "individual-level" } else { eslab <- "cluster-level" } if(is.null(assurance)) { cat(paste("The expected width of ", eslab, " effect size is ", round(width, 4), ".\n", sep="")) } else { cat(paste("The width of ", eslab, " effect size with ", round(assurance, 2), " assurance is ", round(width, 4), ".\n", sep="")) } } else { if(is.null(assurance)) { cat(paste("The expected width of unstandardized conditions difference is ", round(width, 4), ".\n", sep="")) } else { cat(paste("The width of unstandardized conditions difference with ", round(assurance, 2), " assurance is ", round(width, 4), ".\n", sep="")) } } } if(!is.null(cost)) cat(paste("The budget is ", cost, ".\n", sep="")) } ss.aipe.crd.nclus.fixedwidth <- function(width, nindiv, prtreat, tauy=NULL, sigma2y=NULL, totalvar=NULL, iccy=NULL, r2between = 0, r2within = 0, numpredictor = 0, assurance=NULL, conf.level = 0.95, cluscost=NULL, indivcost=NULL, diffsize = NULL) { nclus <- .findNclusCRDDiff(width=width, nindiv=nindiv, prtreat=prtreat, tauy=tauy, sigma2y=sigma2y, totalvar=totalvar, iccy=iccy, r2between = r2between, r2within = r2within, numpredictor = numpredictor, assurance=assurance, conf.level = conf.level, diffsize = diffsize) calculatedWidth <- .findWidthCRDDiff(nclus=nclus, nindiv=nindiv, prtreat=prtreat, tauy=tauy, sigma2y=sigma2y, totalvar=totalvar, iccy=iccy, r2between = r2between, r2within = r2within, numpredictor = numpredictor, assurance=assurance, conf.level = conf.level, diffsize = diffsize) calculatedCost <- NULL if(!is.null(cluscost) && !is.null(indivcost)) calculatedCost <- .costCRD(nclus, nindiv, cluscost, indivcost, diffsize = diffsize) .reportCRD(nclus, nindiv, calculatedWidth, cost=calculatedCost, es=FALSE, estype=0, assurance=assurance, diffsize = diffsize) invisible(nclus) } ss.aipe.crd.nindiv.fixedwidth <- function(width, nclus, prtreat, tauy=NULL, sigma2y=NULL, totalvar=NULL, iccy=NULL, r2between = 0, r2within = 0, numpredictor = 0, assurance=NULL, conf.level = 0.95, cluscost=NULL, indivcost=NULL, diffsize = NULL) { nindiv <- .findNindivCRDDiff(width=width, nclus=nclus, prtreat=prtreat, tauy=tauy, sigma2y=sigma2y, totalvar=totalvar, iccy=iccy, r2between = r2between, r2within = r2within, numpredictor = numpredictor, assurance=assurance, conf.level = conf.level, diffsize = diffsize) if(nindiv == "> 100000") stop("With the current number of clusters, it is impossible to achieve the target width. Please increase the number of clusters.") calculatedWidth <- .findWidthCRDDiff(nclus=nclus, nindiv=nindiv, prtreat=prtreat, tauy=tauy, sigma2y=sigma2y, totalvar=totalvar, iccy=iccy, r2between = r2between, r2within = r2within, numpredictor = numpredictor, assurance=assurance, conf.level = conf.level, diffsize = diffsize) calculatedCost <- NULL if(!is.null(cluscost) && !is.null(indivcost)) calculatedCost <- .costCRD(nclus, nindiv, cluscost, indivcost, diffsize = diffsize) .reportCRD(nclus, nindiv, calculatedWidth, cost=calculatedCost, es=FALSE, estype=0, assurance=assurance, diffsize = diffsize) invisible(nindiv) } ss.aipe.crd.nclus.fixedbudget <- function(budget, nindiv, cluscost = 0, indivcost = 1, prtreat = NULL, tauy=NULL, sigma2y=NULL, totalvar=NULL, iccy=NULL, r2between = 0, r2within = 0, numpredictor = 0, assurance=NULL, conf.level = 0.95, diffsize = NULL) { nclus <- .findNclusCRDBudget(budget=budget, nindiv=nindiv, cluscost=cluscost, indivcost=indivcost, diffsize = diffsize) calculatedWidth <- NULL if(!is.null(prtreat)) { calculatedWidth <- .findWidthCRDDiff(nclus=nclus, nindiv=nindiv, prtreat=prtreat, tauy=tauy, sigma2y=sigma2y, totalvar=totalvar, iccy=iccy, r2between = r2between, r2within = r2within, numpredictor = numpredictor, assurance=assurance, conf.level = conf.level, diffsize = diffsize) } calculatedCost <- .costCRD(nclus, nindiv, cluscost=cluscost, indivcost=indivcost, diffsize = diffsize) .reportCRD(nclus, nindiv, calculatedWidth, cost=calculatedCost, es=FALSE, estype=0, assurance=assurance, diffsize = diffsize) invisible(nclus) } ss.aipe.crd.nindiv.fixedbudget <- function(budget, nclus, cluscost = 0, indivcost = 1, prtreat = NULL, tauy=NULL, sigma2y=NULL, totalvar=NULL, iccy=NULL, r2between = 0, r2within = 0, numpredictor = 0, assurance=NULL, conf.level = 0.95, diffsize = NULL) { nindiv <- .findNindivCRDBudget(budget=budget, nclus=nclus, cluscost=cluscost, indivcost=indivcost, diffsize = diffsize) calculatedWidth <- NULL if(!is.null(prtreat)) { calculatedWidth <- .findWidthCRDDiff(nclus=nclus, nindiv=nindiv, prtreat=prtreat, tauy=tauy, sigma2y=sigma2y, totalvar=totalvar, iccy=iccy, r2between = r2between, r2within = r2within, numpredictor = numpredictor, assurance=assurance, conf.level = conf.level, diffsize = diffsize) } calculatedCost <- .costCRD(nclus, nindiv, cluscost=cluscost, indivcost=indivcost, diffsize = diffsize) .reportCRD(nclus, nindiv, calculatedWidth, cost=calculatedCost, es=FALSE, estype=0, assurance=assurance, diffsize = diffsize) invisible(nindiv) } ss.aipe.crd.both.fixedbudget <- function(budget, cluscost=0, indivcost=1, prtreat, tauy=NULL, sigma2y=NULL, totalvar=NULL, iccy=NULL, r2between = 0, r2within = 0, numpredictor = 0, assurance=NULL, conf.level = 0.95, diffsize = NULL) { result <- .findMinWidthCRDDiff(budget=budget, cluscost=cluscost, indivcost=indivcost, prtreat=prtreat, tauy=tauy, sigma2y=sigma2y, totalvar=totalvar, iccy=iccy, r2between = r2between, r2within = r2within, numpredictor = numpredictor, assurance=assurance, conf.level = conf.level, diffsize = diffsize) calculatedCost <- .costCRD(result[1], result[2], cluscost=cluscost, indivcost=indivcost, diffsize = diffsize) .reportCRD(result[1], result[2], result[3], cost=calculatedCost, es=FALSE, estype=0, assurance=assurance, diffsize = diffsize) invisible(result[1:2]) } ss.aipe.crd.both.fixedwidth <- function(width, cluscost=0, indivcost=1, prtreat, tauy=NULL, sigma2y=NULL, totalvar=NULL, iccy=NULL, r2between = 0, r2within = 0, numpredictor = 0, assurance=NULL, conf.level = 0.95, diffsize = NULL) { result <- .findMinCostCRDDiff(width=width, cluscost=cluscost, indivcost=indivcost, prtreat=prtreat, tauy=tauy, sigma2y=sigma2y, totalvar=totalvar, iccy=iccy, r2between = r2between, r2within = r2within, numpredictor = numpredictor, assurance=assurance, conf.level = conf.level, diffsize = diffsize) calculatedWidth <- .findWidthCRDDiff(nclus=result[1], nindiv=result[2], prtreat=prtreat, tauy=tauy, sigma2y=sigma2y, totalvar=totalvar, iccy=iccy, r2between = r2between, r2within = r2within, numpredictor = numpredictor, assurance=assurance, conf.level = conf.level, diffsize = diffsize) .reportCRD(result[1], result[2], calculatedWidth, cost=result[3], es=FALSE, estype=0, assurance=assurance, diffsize = diffsize) invisible(result[1:2]) } .createDataCRD <- function(nclus, ntreatclus, nindiv, iccy, es, estype = 1, totalvar=1, covariate=FALSE, iccz=NULL, r2within=NULL, r2between=NULL, totalvarz = 1, diffsize = NULL) { if(!requireNamespace("MASS", quietly = TRUE)) stop("The package 'MASS' is needed; please install the package and try again.") if(!is.null(diffsize)) { nindiv <- .findNindivVec(nindiv, diffsize, nclus) } else { nindiv <- rep(nindiv, each=nclus) } id <- do.call(c, mapply(rep, 1:nclus, nindiv, SIMPLIFY=FALSE)) x <- c(rep(1, ntreatclus), rep(0, nclus - ntreatclus)) tau <- iccy * totalvar sigma <- (1 - iccy) * totalvar gamma1 <- NULL if(estype == 0) { gamma1 <- es * sqrt(totalvar) } else if (estype == 1) { gamma1 <- es * sqrt(sigma) } else if (estype == 2) { gamma1 <- es * sqrt(tau) } else { stop("'estype' can be 0 (total variance), 1 (level-1 variance), or 2 (level-2 variance) only.") } if(covariate) { if(iccz == 0 && r2between != 0) stop("Because the covariate varies at the level 1 only, the r-square at level 2 must be 0.") if(iccz == 1 && r2within != 0) stop("Because the covariate varies at the level 2 only, the r-square at level 1 must be 0.") tauz <- totalvarz * iccz sigmaz <- totalvarz * (1 - iccz) gammazb <- sqrt(r2between * tau / tauz) gammazw <- sqrt(r2within * sigma / sigmaz) tau <- (1 - r2between) * tau sigma <- (1 - r2within) * sigma } ybetween <- (gamma1 * x) + rnorm(nclus, 0, sqrt(tau)) if(covariate && iccz != 0) { zbetween <- rnorm(nclus, 0, sqrt(tauz)) ybetween <- ybetween + gammazb * zbetween } ybetween <- do.call(c, mapply(rep, ybetween, nindiv, SIMPLIFY=FALSE)) y <- ybetween + rnorm(sum(nindiv), 0, sqrt(sigma)) if(covariate && iccz != 1) { zwithin <- rnorm(sum(nindiv), 0, sqrt(sigmaz)) y <- y + gammazw * zwithin } x <- do.call(c, mapply(rep, x, nindiv, SIMPLIFY=FALSE)) dat <- data.frame(id, y, x) if(covariate) { z <- NULL if(iccz == 0) { z <- zwithin } else if(iccz == 1) { z <- do.call(c, mapply(rep, zbetween, nindiv, SIMPLIFY=FALSE)) } else { z <- do.call(c, mapply(rep, zbetween, nindiv, SIMPLIFY=FALSE)) + zwithin } if(iccz == 0) { zb <- 0 zw <- z } else { zlist <- split(z, id) zb <- do.call(c, mapply(rep, sapply(zlist, mean), nindiv, SIMPLIFY=FALSE)) zw <- do.call(c, lapply(zlist, scale, scale=FALSE)) } z <- data.frame(zw=zw, zb=zb) dat <- data.frame(dat, z) } rownames(dat) <- NULL return(dat) } .wideFormat <- function(data, betweencol, withincol, idcol) { temp <- split(data[,withincol], data[,idcol]) temp <- lapply(temp, function(x) as.vector(as.matrix(x))) dataw <- do.call(rbind, temp) datab <- as.matrix(data[match(unique(data[,idcol]), data[,idcol]), betweencol]) colnames(datab) <- colnames(data)[betweencol] nindiv <- nrow(data) / nrow(datab) colnames(dataw) <- paste(rep(colnames(data)[withincol], each=nindiv), rep(1:nindiv, length(withincol)), sep="") return(data.frame(datab, dataw)) } .wideFormatUnequal <- function(data, betweencol, withincol, idcol) { temp <- split(data[,withincol], data[,idcol]) temp <- lapply(temp, function(x) as.vector(as.matrix(x))) size <- sapply(temp, length)/length(withincol) dataw <- lapply(split(temp, size), function(x) do.call(rbind, x)) datab <- split(data[match(unique(data[,idcol]), data[,idcol]), betweencol], size) resultdat <- mapply(data.frame, datab, dataw) varnamesw <- lapply(sapply(dataw, ncol)/length(withincol), function(x) paste(rep(colnames(data)[withincol], each=x), rep(1:x, length(withincol)), sep="")) varnames <- lapply(varnamesw, function(x) c(colnames(data)[betweencol], x)) resultdat <- mapply(function(x, y) { colnames(x) <- y; x}, x = resultdat, y = varnames) return(resultdat) } .createDataCRDWide <- function(nclus, ntreatclus, nindiv, iccy, es, estype = 1, totalvar=1, covariate=FALSE, iccz=NULL, r2within=NULL, r2between=NULL, totalvarz = 1, diffsize = NULL) { dat <- .createDataCRD(nclus=nclus, ntreatclus=ntreatclus, nindiv=nindiv, iccy=iccy, es=es, estype = estype, totalvar=totalvar, covariate=covariate, iccz=iccz, r2within=r2within, r2between=r2between, totalvarz = totalvarz, diffsize = diffsize) datawide <- NULL if(!is.null(diffsize)) { if(covariate) { if(iccz == 0) { datawide <- .wideFormatUnequal(dat, 3, c(2, 4), 1) } else if(iccz == 1) { datawide <- .wideFormatUnequal(dat, c(3, 5), 2, 1) } else { datawide <- .wideFormatUnequal(dat, c(3, 5), c(2, 4), 1) } } else { datawide <- .wideFormatUnequal(dat, 3, 2, 1) } } else { if(covariate) { if(iccz == 0) { datawide <- .wideFormat(dat, 3, c(2, 4), 1) } else if(iccz == 1) { datawide <- .wideFormat(dat, c(3, 5), 2, 1) } else { datawide <- .wideFormat(dat, c(3, 5), c(2, 4), 1) } } else { datawide <- .wideFormat(dat, 3, 2, 1) } } return(datawide) } .likCIESCRD <- function(datawide, ylab, xlab, zwlab=NULL, zblab=NULL, estype=1, iccy=0.25, es=0.5, totalvar=1, covariate=FALSE, iccz=0.25, r2within=0.5, r2between=0.5, totalvarz = 1, conf.level = 0.95) { tau <- iccy * totalvar sigma <- (1 - iccy) * totalvar gamma1 <- NULL if(estype == 0) { gamma1 <- es * sqrt(totalvar) } else if (estype == 1) { gamma1 <- es * sqrt(sigma) } else if (estype == 2) { gamma1 <- es * sqrt(tau) } else { stop("'estype' can be 0 (total variance), 1 (level-1 variance), or 2 (level-2 variance) only.") } if(covariate) { if(iccz == 0 && r2between != 0) stop("Because the covariate varies at the level 1 only, the r-square at level 2 must be 0.") if(iccz == 1 && r2within != 0) stop("Because the covariate varies at the level 2 only, the r-square at level 1 must be 0.") tauz <- totalvarz * iccz sigmaz <- totalvarz * (1 - iccz) gammazb <- sqrt(r2between * tau / tauz) gammazw <- sqrt(r2within * sigma / sigmaz) tau <- (1 - r2between) * tau sigma <- (1 - r2within) * sigma } probx <- sum(datawide[,xlab])/nrow(datawide) if(!requireNamespace("OpenMx", quietly = TRUE)) stop("The package 'OpenMx' is needed; please install the package and try again.") latentlab <- c("intcept", "slope") if(is.null(zwlab)) latentlab <- "intcept" frowlab <- c(ylab, xlab, zblab) fcollab <- c(frowlab, latentlab) lenrow <- length(frowlab) lencol <- length(fcollab) Alab <- matrix(NA, lencol, lencol) Aval <- matrix(0, lencol, lencol) Afree <- matrix(FALSE, lencol, lencol) colnames(Alab) <- colnames(Aval) <- colnames(Afree) <- rownames(Alab) <- rownames(Aval) <- rownames(Afree) <- fcollab Alab["intcept", xlab] <- "groupdiff" if(!is.null(zblab)) Alab["intcept", zblab] <- "zbeffect" if(!is.null(zwlab)) Alab[ylab, "slope"] <- paste("data.", zwlab, sep="") Aval["intcept", xlab] <- gamma1 if(!is.null(zblab)) Aval["intcept", zblab] <- gammazb Aval[ylab, latentlab] <- 1 Afree["intcept", xlab] <- TRUE if(!is.null(zblab)) Afree["intcept", zblab] <- TRUE Slab <- matrix(NA, lencol, lencol) Sval <- matrix(0, lencol, lencol) Sfree <- matrix(FALSE, lencol, lencol) colnames(Slab) <- colnames(Sval) <- colnames(Sfree) <- rownames(Slab) <- rownames(Sval) <- rownames(Sfree) <- fcollab diag(Slab)[1:length(ylab)] <- "l1error" diag(Sval)[1:length(ylab)] <- sigma diag(Sfree)[1:length(ylab)] <- TRUE Slab["intcept", "intcept"] <- "l2error" Sval["intcept", "intcept"] <- tau Sfree["intcept", "intcept"] <- TRUE Slab[xlab, xlab] <- "varx" Sval[xlab, xlab] <- probx * (1 - probx) Sfree[xlab, xlab] <- TRUE if(!is.null(zblab)) { Slab[c(xlab, zblab), c(xlab, zblab)] <- "covxzb" Slab[xlab, xlab] <- "varx" Slab[zblab, zblab] <- "varzb" Sval[c(xlab, zblab), c(xlab, zblab)] <- 0 Sval[xlab, xlab] <- probx * (1 - probx) Sval[zblab, zblab] <- tauz Sfree[c(xlab, zblab), c(xlab, zblab)] <- TRUE } Fval <- cbind(diag(lenrow), matrix(0, lenrow, length(latentlab))) Flab <- matrix(NA, lenrow, lencol) Ffree <- matrix(FALSE, lenrow, lencol) colnames(Flab) <- colnames(Fval) <- colnames(Ffree) <- fcollab rownames(Flab) <- rownames(Fval) <- rownames(Ffree) <- frowlab Mlab <- c(rep(NA, length(ylab)), "meanX") Mval <- c(rep(0, length(ylab)), probx) Mfree <- c(rep(FALSE, length(ylab)), TRUE) if(!is.null(zblab)) { Mlab <- c(Mlab, "meanzb") Mval <- c(Mval, 0) Mfree <- c(Mfree, TRUE) } Mlab <- c(Mlab, "meanctrl") Mval <- c(Mval, 0) Mfree <- c(Mfree, TRUE) if(!is.null(zwlab)) { Mlab <- c(Mlab, "zweffect") Mval <- c(Mval, gammazw) Mfree <- c(Mfree, TRUE) } Mlab <- matrix(Mlab, 1, lencol) Mval <- matrix(Mval, 1, lencol) Mfree <- matrix(Mfree, 1, lencol) colnames(Mlab) <- colnames(Mval) <- colnames(Mfree) <- fcollab varzw <- 0 if(!is.null(zwlab)) varzw <- var(as.vector(as.matrix(datawide[,zwlab]))) groupdiff <- NULL l1error <- NULL l2error <- NULL zbeffect <- NULL varzb <- NULL zweffect <- NULL constraint <- NULL if(estype == 0) { if(is.null(zwlab)) { if(is.null(zblab)) { constraint <- OpenMx::mxAlgebra(expression = groupdiff/sqrt(l1error + l2error), name = "es") } else { constraint <- OpenMx::mxAlgebra(expression = groupdiff/sqrt(l1error + l2error + (zbeffect^2 * varzb)), name = "es") } } else { if(is.null(zblab)) { constraint <- OpenMx::mxAlgebra(expression = groupdiff/sqrt(l1error + (zweffect^2 * varzw) + l2error), name = "es") } else { constraint <- OpenMx::mxAlgebra(expression = groupdiff/sqrt(l1error + (zweffect^2 * varzw) + l2error + (zbeffect^2 * varzb)), name = "es") } } } else if (estype == 1) { if(is.null(zwlab)) { constraint <- OpenMx::mxAlgebra(expression = groupdiff/sqrt(l1error), name = "es") } else { constraint <- OpenMx::mxAlgebra(expression = groupdiff/sqrt(l1error + (zweffect^2 * varzw)), name = "es") } } else if (estype == 2) { if(is.null(zblab)) { constraint <- OpenMx::mxAlgebra(expression = groupdiff/sqrt(l2error), name = "es") } else { constraint <- OpenMx::mxAlgebra(expression = groupdiff/sqrt(l2error + (zbeffect^2 * varzb)), name = "es") } } else { stop("'estype' can be 0 (total variance), 1 (level-1 variance), or 2 (level-2 variance) only.") } onecov <- OpenMx::mxModel("effect size CRD", type="RAM", OpenMx::mxData(datawide, type="raw"), OpenMx::mxMatrix(type="Full", nrow=lencol, ncol=lencol, values=Aval, free=Afree, labels=Alab, name="A"), OpenMx::mxMatrix(type="Symm", nrow=lencol, ncol=lencol, values=Sval, free=Sfree, labels=Slab, name="S"), OpenMx::mxMatrix(type="Full", nrow=lenrow, ncol=lencol, values=Fval, free=Ffree, labels=Flab, name="F"), OpenMx::mxMatrix(type="Full", nrow=1, ncol=lencol, values=Mval, free=Mfree, labels=Mlab, name="M"), OpenMx::mxMatrix(type="Full", nrow=1, ncol=1, values=varzw, free=FALSE, labels="varzw", name="J"), OpenMx::mxRAMObjective("A","S","F","M", dimnames=fcollab), constraint, OpenMx::mxCI(c("es"), interval = conf.level) ) onecovfit <- OpenMx::mxRun(onecov, intervals=TRUE) return(onecovfit@output$confidenceIntervals) } .likCIESCRDunequal <- function(datawide, ylab, xlab, zwlab=NULL, zblab=NULL, estype=1, iccy=0.25, es=0.5, totalvar=1, covariate=FALSE, iccz=0.25, r2within=0.5, r2between=0.5, totalvarz = 1, conf.level = 0.95) { if(!requireNamespace("OpenMx", quietly = TRUE)) stop("The package 'OpenMx' is needed; please install the package and try again.") tau <- iccy * totalvar sigma <- (1 - iccy) * totalvar gamma1 <- NULL if(estype == 0) { gamma1 <- es * sqrt(totalvar) } else if (estype == 1) { gamma1 <- es * sqrt(sigma) } else if (estype == 2) { gamma1 <- es * sqrt(tau) } else { stop("'estype' can be 0 (total variance), 1 (level-1 variance), or 2 (level-2 variance) only.") } if(covariate) { if(iccz == 0 && r2between != 0) stop("Because the covariate varies at the level 1 only, the r-square at level 2 must be 0.") if(iccz == 1 && r2within != 0) stop("Because the covariate varies at the level 2 only, the r-square at level 1 must be 0.") tauz <- totalvarz * iccz sigmaz <- totalvarz * (1 - iccz) gammazb <- sqrt(r2between * tau / tauz) gammazw <- sqrt(r2within * sigma / sigmaz) tau <- (1 - r2between) * tau sigma <- (1 - r2within) * sigma } ntreat <- sum(sapply(datawide, function(x) sum(x[,xlab]))) totaln <- sum(sapply(datawide, nrow)) probx <- ntreat/totaln FUNgroupsize <- function(dat, y, zw = NULL) { latentlab <- c("intcept", "slope") if(is.null(zw)) latentlab <- "intcept" frowlab <- c(y, xlab, zblab) fcollab <- c(frowlab, latentlab) lenrow <- length(frowlab) lencol <- length(fcollab) Alab <- matrix(NA, lencol, lencol) Aval <- matrix(0, lencol, lencol) Afree <- matrix(FALSE, lencol, lencol) colnames(Alab) <- colnames(Aval) <- colnames(Afree) <- rownames(Alab) <- rownames(Aval) <- rownames(Afree) <- fcollab Alab["intcept", xlab] <- "groupdiff" if(!is.null(zblab)) Alab["intcept", zblab] <- "zbeffect" if(!is.null(zw)) Alab[y, "slope"] <- paste("data.", zw, sep="") Aval["intcept", xlab] <- gamma1 if(!is.null(zblab)) Aval["intcept", zblab] <- gammazb Aval[y, latentlab] <- 1 Afree["intcept", xlab] <- TRUE if(!is.null(zblab)) Afree["intcept", zblab] <- TRUE Slab <- matrix(NA, lencol, lencol) Sval <- matrix(0, lencol, lencol) Sfree <- matrix(FALSE, lencol, lencol) colnames(Slab) <- colnames(Sval) <- colnames(Sfree) <- rownames(Slab) <- rownames(Sval) <- rownames(Sfree) <- fcollab diag(Slab)[1:length(y)] <- "l1error" diag(Sval)[1:length(y)] <- sigma diag(Sfree)[1:length(y)] <- TRUE Slab["intcept", "intcept"] <- "l2error" Sval["intcept", "intcept"] <- tau Sfree["intcept", "intcept"] <- TRUE Slab[xlab, xlab] <- "varx" Sval[xlab, xlab] <- probx * (1 - probx) Sfree[xlab, xlab] <- TRUE if(!is.null(zblab)) { Slab[c(xlab, zblab), c(xlab, zblab)] <- "covxzb" Slab[xlab, xlab] <- "varx" Slab[zblab, zblab] <- "varzb" Sval[c(xlab, zblab), c(xlab, zblab)] <- 0 Sval[xlab, xlab] <- probx * (1 - probx) Sval[zblab, zblab] <- tauz Sfree[c(xlab, zblab), c(xlab, zblab)] <- TRUE } Fval <- cbind(diag(lenrow), matrix(0, lenrow, length(latentlab))) Flab <- matrix(NA, lenrow, lencol) Ffree <- matrix(FALSE, lenrow, lencol) colnames(Flab) <- colnames(Fval) <- colnames(Ffree) <- fcollab rownames(Flab) <- rownames(Fval) <- rownames(Ffree) <- frowlab Mlab <- c(rep(NA, length(y)), "meanX") Mval <- c(rep(0, length(y)), probx) Mfree <- c(rep(FALSE, length(y)), TRUE) if(!is.null(zblab)) { Mlab <- c(Mlab, "meanzb") Mval <- c(Mval, 0) Mfree <- c(Mfree, TRUE) } Mlab <- c(Mlab, "meanctrl") Mval <- c(Mval, 0) Mfree <- c(Mfree, TRUE) if(!is.null(zw)) { Mlab <- c(Mlab, "zweffect") Mval <- c(Mval, gammazw) Mfree <- c(Mfree, TRUE) } Mlab <- matrix(Mlab, 1, lencol) Mval <- matrix(Mval, 1, lencol) Mfree <- matrix(Mfree, 1, lencol) colnames(Mlab) <- colnames(Mval) <- colnames(Mfree) <- fcollab onecov <- OpenMx::mxModel(paste0("group", length(y)), type="RAM", OpenMx::mxData(dat, type="raw"), OpenMx::mxMatrix(type="Full", nrow=lencol, ncol=lencol, values=Aval, free=Afree, labels=Alab, name="A"), OpenMx::mxMatrix(type="Symm", nrow=lencol, ncol=lencol, values=Sval, free=Sfree, labels=Slab, name="S"), OpenMx::mxMatrix(type="Full", nrow=lenrow, ncol=lencol, values=Fval, free=Ffree, labels=Flab, name="F"), OpenMx::mxMatrix(type="Full", nrow=1, ncol=lencol, values=Mval, free=Mfree, labels=Mlab, name="M"), OpenMx::mxMatrix(type="Full", nrow=1, ncol=1, values=varzw, free=FALSE, labels="varzw", name="J"), OpenMx::mxRAMObjective("A","S","F","M", dimnames=fcollab) ) return(onecov) } varzw <- 0 if(!is.null(zwlab)) varzw <- weighted.mean(do.call(c, mapply(function(x, y) var(as.vector(as.matrix(x[,y]))), x = datawide, y = zwlab,SIMPLIFY=FALSE)), as.numeric(names(datawide))) groupdiff <- NULL l1error <- NULL l2error <- NULL zbeffect <- NULL varzb <- NULL zweffect <- NULL constraint <- NULL if(estype == 0) { if(is.null(zwlab)) { if(is.null(zblab)) { constraint <- OpenMx::mxAlgebra(expression = groupdiff/sqrt(l1error + l2error), name = "es") } else { constraint <- OpenMx::mxAlgebra(expression = groupdiff/sqrt(l1error + l2error + (zbeffect^2 * varzb)), name = "es") } } else { if(is.null(zblab)) { constraint <- OpenMx::mxAlgebra(expression = groupdiff/sqrt(l1error + (zweffect^2 * varzw) + l2error), name = "es") } else { constraint <- OpenMx::mxAlgebra(expression = groupdiff/sqrt(l1error + (zweffect^2 * varzw) + l2error + (zbeffect^2 * varzb)), name = "es") } } } else if (estype == 1) { if(is.null(zwlab)) { constraint <- OpenMx::mxAlgebra(expression = groupdiff/sqrt(l1error), name = "es") } else { constraint <- OpenMx::mxAlgebra(expression = groupdiff/sqrt(l1error + (zweffect^2 * varzw)), name = "es") } } else if (estype == 2) { if(is.null(zblab)) { constraint <- OpenMx::mxAlgebra(expression = groupdiff/sqrt(l2error), name = "es") } else { constraint <- OpenMx::mxAlgebra(expression = groupdiff/sqrt(l2error + (zbeffect^2 * varzb)), name = "es") } } else { stop("'estype' can be 0 (total variance), 1 (level-1 variance), or 2 (level-2 variance) only.") } listModel <- NULL if(!is.null(zwlab)) { listModel <- mapply(FUNgroupsize, dat=datawide, y=ylab, zw=zwlab) } else { listModel <- mapply(FUNgroupsize, dat=datawide, y=ylab) } title <- "Effect Size CRD" algebra <- OpenMx::mxAlgebra("", name="allobjective") groupnames <- paste0("group", names(datawide)) groupnames <- paste0(groupnames, ".objective") groupnames <- lapply(groupnames, as.name) algebra@formula <- as.call(c(list(as.name("sum")), groupnames)) objective <- OpenMx::mxAlgebraObjective("allobjective") finalmodel <- OpenMx::mxModel(title, OpenMx::mxMatrix(type="Full", nrow=1, ncol=1, values=varzw, free=FALSE, labels="varzw", name="J"), unlist(listModel), constraint, algebra, objective, OpenMx::mxCI(c("es"), interval = conf.level)) finalmodelfit <- OpenMx::mxRun(finalmodel, intervals=TRUE) return(finalmodelfit@output$confidenceIntervals) } .runrepWidthESCRD <- function(seed, nclus, ntreatclus, nindiv, iccy, es, estype = 1, totalvar=1, covariate=FALSE, iccz=NULL, r2within=NULL, r2between=NULL, totalvarz = 1, conf.level = 0.95, diffsize = NULL) { set.seed(seed) datawide <- .createDataCRDWide(nclus=nclus, ntreatclus=ntreatclus, nindiv=nindiv, iccy=iccy, es=es, estype = estype, totalvar=totalvar, covariate=covariate, iccz=iccz, r2within=r2within, r2between=r2between, totalvarz = totalvarz, diffsize=diffsize) ylab <- NULL if(!is.null(diffsize)) { size <- as.numeric(names(datawide)) ylab <- lapply(size, function(x) paste("y", 1:x, sep="")) } else { ylab <- paste("y", 1:nindiv, sep="") } xlab <- "x" zwlab <- NULL if(covariate && iccz != 1) { if(!is.null(diffsize)) { size <- as.numeric(names(datawide)) zwlab <- lapply(size, function(x) paste("zw", 1:x, sep="")) } else { zwlab <- paste("zw", 1:nindiv, sep="") } } zblab <- NULL if(covariate && iccz != 0) zblab <- "zb" if(!is.null(diffsize)) { screencapture <- capture.output( result <- .likCIESCRDunequal(datawide=datawide, ylab=ylab, xlab=xlab, zwlab=zwlab, zblab=zblab, estype=estype, iccy=iccy, es=es, totalvar=totalvar, covariate=covariate, iccz=iccz, r2within=r2within, r2between=r2between, totalvarz = totalvarz, conf.level = conf.level)) } else { screencapture <- capture.output( result <- .likCIESCRD(datawide=datawide, ylab=ylab, xlab=xlab, zwlab=zwlab, zblab=zblab, estype=estype, iccy=iccy, es=es, totalvar=totalvar, covariate=covariate, iccz=iccz, r2within=r2within, r2between=r2between, totalvarz = totalvarz, conf.level = conf.level) ) } return(result[2] - result[1]) } .findWidthCRDES <- function(nrep, nclus, ntreatclus, nindiv, iccy, es, estype = 1, totalvar=1, covariate=FALSE, iccz=NULL, r2within=NULL, r2between=NULL, totalvarz = 1, assurance=NULL, seed=123321, multicore=FALSE, numProc=NULL, conf.level=0.95, diffsize = NULL) { set.seed(seed) seedList <- as.list(sample(1:999999, nrep)) Result.l <- NULL if (multicore) { if(!requireNamespace("parallel", quietly = TRUE)) stop("The package 'parallel' is needed; please install the package and try again.") sys <- .Platform$OS.type if (is.null(numProc)) numProc <- parallel::detectCores() if (sys == "windows") { cl <- parallel::makeCluster(rep("localhost", numProc), type = "SOCK") Result.l <- parallel::clusterApplyLB(cl, seedList, .runrepWidthESCRD, nclus=nclus, ntreatclus=ntreatclus, nindiv=nindiv, iccy=iccy, es=es, estype = estype, totalvar=totalvar, covariate=covariate, iccz=iccz, r2within=r2within, r2between=r2between, totalvarz = totalvarz, conf.level = conf.level, diffsize=diffsize) parallel::stopCluster(cl) } else { Result.l <- parallel::mclapply(seedList, .runrepWidthESCRD, nclus=nclus, ntreatclus=ntreatclus, nindiv=nindiv, iccy=iccy, es=es, estype = estype, totalvar=totalvar, covariate=covariate, iccz=iccz, r2within=r2within, r2between=r2between, totalvarz = totalvarz, conf.level = conf.level, diffsize=diffsize) } } else { Result.l <- lapply(seedList, .runrepWidthESCRD, nclus=nclus, ntreatclus=ntreatclus, nindiv=nindiv, iccy=iccy, es=es, estype = estype, totalvar=totalvar, covariate=covariate, iccz=iccz, r2within=r2within, r2between=r2between, totalvarz = totalvarz, conf.level=conf.level, diffsize=diffsize) } result <- do.call(c, Result.l) if(is.null(assurance)) { return(mean(result, na.rm=TRUE)) } else { return(quantile(result, assurance, na.rm=TRUE)) } } .findNclusCRDES <- function(width, nindiv, es, estype = 1, iccy, prtreat, r2between = 0, r2within = 0, numpredictor = 0, assurance=NULL, conf.level = 0.95, nrep = 1000, iccz = NULL, seed = 123321, multicore = FALSE, numProc=NULL, diffsize=NULL) { if(numpredictor > 0 & is.null(iccz)) iccz <- iccy if(numpredictor > 1) stop("Only one predictor is allowed.") totalvar <- 1 if(estype == 0) { totalvar <- 1 } else if (estype == 1) { totalvar <- 1/(1 - iccy) } else if (estype == 2) { totalvar <- 1/iccy } else { stop("'estype' can be 0 (total variance), 1 (level-1 variance), or 2 (level-2 variance) only.") } startval <- .findNclusCRDDiff(width=width, nindiv=nindiv, prtreat=prtreat, totalvar=totalvar, iccy=iccy, r2between = r2between, r2within = r2within, numpredictor = numpredictor, assurance=assurance, conf.level = conf.level, diffsize = diffsize) startval <- as.numeric(startval) startwidth <- .findWidthCRDES(nrep, assurance=assurance, nclus=startval, ntreatclus=round(startval * prtreat), nindiv=nindiv, iccy=iccy, es=es, estype = estype, totalvar=totalvar, covariate=as.logical(numpredictor), iccz=iccz, r2within=r2within, r2between=r2between, totalvarz = 1, seed=seed, multicore=multicore, numProc=numProc, conf.level=conf.level, diffsize = diffsize) if(startwidth < width) { repeat { startval <- startval - 1 if(round(startval * prtreat) == 1 | (startval - round(startval * prtreat)) == 1) return(c(startval + 1, startwidth)) savedwidth <- startwidth startwidth <- .findWidthCRDES(nrep, assurance=assurance, nclus=startval, ntreatclus=round(startval * prtreat), nindiv=nindiv, iccy=iccy, es=es, estype = estype, totalvar=totalvar, covariate=as.logical(numpredictor), iccz=iccz, r2within=r2within, r2between=r2between, totalvarz = 1, seed=seed, multicore=multicore, numProc=numProc, conf.level=conf.level, diffsize = diffsize) if(startwidth > width) return(c(startval + 1, savedwidth)) } } else if (startwidth > width) { repeat { startval <- startval + 1 startwidth <- .findWidthCRDES(nrep, assurance=assurance, nclus=startval, ntreatclus=round(startval * prtreat), nindiv=nindiv, iccy=iccy, es=es, estype = estype, totalvar=totalvar, covariate=as.logical(numpredictor), iccz=iccz, r2within=r2within, r2between=r2between, totalvarz = 1, seed=seed, multicore=multicore, numProc=numProc, conf.level=conf.level, diffsize = diffsize) if(startwidth < width) return(c(startval, startwidth)) } } else { return(c(startval, startwidth)) } } .findNindivCRDES <- function(width, nclus, es, estype = 1, iccy, prtreat, r2between = 0, r2within = 0, numpredictor = 0, assurance=NULL, conf.level = 0.95, nrep = 1000, iccz = NULL, seed = 123321, multicore = FALSE, numProc=NULL, diffsize=NULL) { if(numpredictor > 0 & is.null(iccz)) iccz <- iccy if(numpredictor > 1) stop("Only one predictor is allowed.") totalvar <- 1 if(estype == 0) { totalvar <- 1 } else if (estype == 1) { totalvar <- 1/(1 - iccy) } else if (estype == 2) { totalvar <- 1/iccy } else { stop("'estype' can be 0 (total variance), 1 (level-1 variance), or 2 (level-2 variance) only.") } startval <- .findNindivCRDDiff(width=width, nclus=nclus, prtreat=prtreat, totalvar=totalvar, iccy=iccy, r2between = r2between, r2within = r2within, numpredictor = numpredictor, assurance=assurance, conf.level = conf.level, diffsize = diffsize) if(startval == "> 100000") stop("The starting number of individuals is > 100,000. With the specified number of clusters, it seems impossible to get the specified width.") startval <- as.numeric(startval) startwidth <- .findWidthCRDES(nrep, assurance=assurance, nclus=nclus, ntreatclus=round(nclus * prtreat), nindiv=startval, iccy=iccy, es=es, estype = estype, totalvar=totalvar, covariate=as.logical(numpredictor), iccz=iccz, r2within=r2within, r2between=r2between, totalvarz = 1, seed=seed, multicore=multicore, numProc=numProc, conf.level=conf.level, diffsize = diffsize) if(startwidth < width) { repeat { startval <- startval - 1 if(startval == 1) return(c(startval + 1, startwidth)) savedwidth <- startwidth startwidth <- .findWidthCRDES(nrep, assurance=assurance, nclus=nclus, ntreatclus=round(nclus * prtreat), nindiv=startval, iccy=iccy, es=es, estype = estype, totalvar=totalvar, covariate=as.logical(numpredictor), iccz=iccz, r2within=r2within, r2between=r2between, totalvarz = 1, seed=seed, multicore=multicore, numProc=numProc, conf.level=conf.level, diffsize = diffsize) if(startwidth > width) return(c(startval + 1, savedwidth)) } } else if (startwidth > width) { repeat { startval <- startval + 1 startwidth <- .findWidthCRDES(nrep, assurance=assurance, nclus=nclus, ntreatclus=round(nclus * prtreat), nindiv=startval, iccy=iccy, es=es, estype = estype, totalvar=totalvar, covariate=as.logical(numpredictor), iccz=iccz, r2within=r2within, r2between=r2between, totalvarz = 1, seed=seed, multicore=multicore, numProc=numProc, conf.level=conf.level, diffsize = diffsize) if(startwidth < width) return(c(startval, startwidth)) } } else { return(c(startval, startwidth)) } } .findMinCostCRDES <- function(width, cluscost=0, indivcost=1, es, estype = 1, iccy, prtreat, r2between = 0, r2within = 0, numpredictor = 0, assurance=NULL, conf.level = 0.95, nrep = 1000, iccz = NULL, seed = 123321, multicore = FALSE, numProc=NULL, diffsize=NULL) { if(numpredictor > 0 & is.null(iccz)) iccz <- iccy if(numpredictor > 1) stop("Only one predictor is allowed.") totalvar <- 1 if(estype == 0) { totalvar <- 1 } else if (estype == 1) { totalvar <- 1/(1 - iccy) } else if (estype == 2) { totalvar <- 1/iccy } else { stop("'estype' can be 0 (total variance), 1 (level-1 variance), or 2 (level-2 variance) only.") } startval <- .findMinCostCRDDiff(width=width, cluscost=cluscost, indivcost=indivcost, prtreat=prtreat, totalvar=totalvar, iccy=iccy, r2between = r2between, r2within = r2within, numpredictor = numpredictor, assurance=assurance, conf.level = conf.level, diffsize = diffsize) startval <- as.numeric(startval) startnindiv <- c(startval[2] - 1, startval[2], startval[2] + 1) result <- sapply(startnindiv, .findNclusCRDES, width=width, es=es, estype = estype, iccy = iccy, prtreat=prtreat, r2between = r2between, r2within = r2within, numpredictor = numpredictor, assurance = assurance, conf.level = conf.level, nrep = nrep, iccz = iccz, seed = seed, multicore = multicore, numProc = numProc, diffsize = diffsize) resultnclus <- result[1,] resultwidth <- result[2,] startbudget <- mapply(.costCRD, nclus=resultnclus, nindiv=startnindiv, MoreArgs=list(cluscost=cluscost, indivcost=indivcost, diffsize = diffsize)) if(which(startbudget == min(startbudget)) == 1) { repeat { startnindiv <- startnindiv - 1 resultnclus[2:3] <- resultnclus[1:2] startbudget[2:3] <- startbudget[1:2] resultwidth[2:3] <- resultwidth[1:2] result <- .findNclusCRDES(width=width, nindiv=startnindiv[1], es=es, estype = estype, iccy = iccy, prtreat=prtreat, r2between = r2between, r2within = r2within, numpredictor = numpredictor, assurance = assurance, conf.level = conf.level, nrep = nrep, iccz = iccz, seed = seed, multicore = multicore, numProc = numProc, diffsize = diffsize) resultnclus[1] <- result[1] resultwidth[1] <- result[2] startbudget[1] <- .costCRD(nclus=resultnclus[1], nindiv=startnindiv[1], cluscost=cluscost, indivcost=indivcost, diffsize = diffsize) if(which(startbudget == min(startbudget)) != 1) return(c(resultnclus[2], startnindiv[2], startbudget[2], resultwidth[2])) } } else if (which(startbudget == min(startbudget)) == 3) { repeat { startnindiv <- startnindiv + 1 resultnclus[1:2] <- resultnclus[2:3] startbudget[1:2] <- startbudget[2:3] resultwidth[1:2] <- resultwidth[2:3] result <- .findNclusCRDES(width=width, nindiv=startnindiv[3], es=es, estype = estype, iccy = iccy, prtreat=prtreat, r2between = r2between, r2within = r2within, numpredictor = numpredictor, assurance = assurance, conf.level = conf.level, nrep = nrep, iccz = iccz, seed = seed, multicore = multicore, numProc = numProc, diffsize = diffsize) resultnclus[3] <- result[1] resultwidth[3] <- result[2] startbudget[3] <- .costCRD(nclus=resultnclus[3], nindiv=startnindiv[3], cluscost=cluscost, indivcost=indivcost, diffsize = diffsize) if(which(startbudget == min(startbudget)) != 3) return(c(resultnclus[2], startnindiv[2], startbudget[2], resultwidth[2])) } } else { return(c(resultnclus[2], startnindiv[2], startbudget[2], resultwidth[2])) } } .findMinWidthCRDES <- function(budget, cluscost=0, indivcost=1, es, estype = 1, iccy, prtreat, r2between = 0, r2within = 0, numpredictor = 0, assurance=NULL, conf.level = 0.95, nrep = 1000, iccz = NULL, seed = 123321, multicore = FALSE, numProc=NULL, diffsize = NULL) { if(numpredictor > 0 & is.null(iccz)) iccz <- iccy if(numpredictor > 1) stop("Only one predictor is allowed.") totalvar <- 1 if(estype == 0) { totalvar <- 1 } else if (estype == 1) { totalvar <- 1/(1 - iccy) } else if (estype == 2) { totalvar <- 1/iccy } else { stop("'estype' can be 0 (total variance), 1 (level-1 variance), or 2 (level-2 variance) only.") } FUN <- function(nclus, nindiv) { .findWidthCRDES(nrep=nrep, assurance=assurance, nclus=nclus, ntreatclus=round(nclus * prtreat), nindiv=nindiv, iccy=iccy, es=es, estype = estype, totalvar=totalvar, covariate=as.logical(numpredictor), iccz=iccz, r2within=r2within, r2between=r2between, totalvarz = 1, seed=seed, multicore=multicore, numProc=numProc, conf.level=conf.level, diffsize=diffsize) } startval <- .findMinWidthCRDDiff(budget=budget, cluscost=cluscost, indivcost=indivcost, prtreat=prtreat, totalvar=totalvar, iccy=iccy, r2between = r2between, r2within = r2within, numpredictor = numpredictor, assurance=assurance, conf.level = conf.level, diffsize = diffsize) startnclus <- c(startval[1] - 1, startval[1], startval[1] + 1) resultnindiv <- sapply(startnclus, .findNindivCRDBudget, budget=budget, cluscost=cluscost, indivcost=indivcost, diffsize=diffsize) startwidth <- mapply(FUN, nclus = startnclus, nindiv=resultnindiv) if(which(startwidth == min(startwidth)) == 1) { repeat { startnclus <- startnclus - 1 resultnindiv[2:3] <- resultnindiv[1:2] startwidth[2:3] <- startwidth[1:2] resultnindiv[1] <- .findNindivCRDBudget(startnclus[1], budget=budget, cluscost=cluscost, indivcost=indivcost, diffsize=diffsize) startwidth[1] <- FUN(nclus=startnclus[1], nindiv=resultnindiv[1]) if(which(startwidth == min(startwidth)) != 1) return(c(startnclus[2], resultnindiv[2], startwidth[2])) } } else if (which(startwidth == min(startwidth)) == 3) { repeat { startnclus <- startnclus + 1 resultnindiv[1:2] <- resultnindiv[2:3] startwidth[1:2] <- startwidth[2:3] resultnindiv[3] <- .findNindivCRDBudget(startnclus[3], budget=budget, cluscost=cluscost, indivcost=indivcost, diffsize=diffsize) startwidth[3] <- FUN(nclus=startnclus[3], nindiv=resultnindiv[3]) if(which(startwidth == min(startwidth)) != 3) return(c(startnclus[2], resultnindiv[2], startwidth[2])) } } else { return(c(startnclus[2], resultnindiv[2], startwidth[2])) } } ss.aipe.crd.es.nclus.fixedwidth <- function(width, nindiv, es, estype = 1, iccy, prtreat, r2between = 0, r2within = 0, numpredictor = 0, assurance=NULL, conf.level = 0.95, nrep = 1000, iccz = NULL, seed = 123321, multicore = FALSE, numProc=NULL, cluscost=NULL, indivcost=NULL, diffsize=NULL) { suppressWarnings(result <- .findNclusCRDES(width=width, nindiv=nindiv, es=es, estype = estype, iccy=iccy, prtreat=prtreat, r2between = r2between, r2within = r2within, numpredictor = numpredictor, assurance=assurance, conf.level = conf.level, nrep = nrep, iccz = iccz, seed = seed, multicore = multicore, numProc=numProc, diffsize=diffsize)) calculatedCost <- NULL if(!is.null(cluscost) && !is.null(indivcost)) calculatedCost <- .costCRD(result[1], nindiv, cluscost=cluscost, indivcost=indivcost, diffsize=diffsize) .reportCRD(result[1], nindiv, result[2], cost=calculatedCost, es=TRUE, estype=estype, assurance=assurance, diffsize=diffsize) invisible(result[1]) } ss.aipe.crd.es.nindiv.fixedwidth <- function(width, nclus, es, estype = 1, iccy, prtreat, r2between = 0, r2within = 0, numpredictor = 0, assurance=NULL, conf.level = 0.95, nrep = 1000, iccz = NULL, seed = 123321, multicore = FALSE, numProc=NULL, cluscost=NULL, indivcost=NULL, diffsize=NULL) { suppressWarnings(result <- .findNindivCRDES(width=width, nclus=nclus, es=es, estype = estype, iccy=iccy, prtreat=prtreat, r2between = r2between, r2within = r2within, numpredictor = numpredictor, assurance=assurance, conf.level = conf.level, nrep = nrep, iccz = iccz, seed = seed, multicore = multicore, numProc=numProc, diffsize=diffsize)) calculatedCost <- NULL if(!is.null(cluscost) && !is.null(indivcost)) calculatedCost <- .costCRD(nclus, result[1], cluscost=cluscost, indivcost=indivcost, diffsize=diffsize) .reportCRD(nclus, result[1], result[2], cost=calculatedCost, es=TRUE, estype=estype, assurance=assurance, diffsize=diffsize) invisible(result[1]) } ss.aipe.crd.es.nclus.fixedbudget <- function(budget, nindiv, cluscost, indivcost, nrep=NULL, prtreat=NULL, iccy=NULL, es=NULL, estype = 1, numpredictor = 0, iccz=NULL, r2within=NULL, r2between=NULL, assurance=NULL, seed=123321, multicore=FALSE, numProc=NULL, conf.level=0.95, diffsize=NULL) { nclus <- .findNclusCRDBudget(budget=budget, nindiv=nindiv, cluscost=cluscost, indivcost=indivcost, diffsize=diffsize) calculatedWidth <- NULL if(!is.null(nrep) && !is.null(prtreat) && !is.null(nindiv) && !is.null(iccy)) { suppressWarnings(calculatedWidth <- .findWidthCRDES(nrep=nrep, nclus=nclus, ntreatclus=round(nclus * prtreat), nindiv=nindiv, iccy=iccy, es=es, estype = estype, totalvar=1, covariate=as.logical(numpredictor), iccz=iccz, r2within=r2within, r2between=r2between, totalvarz = 1, assurance=assurance, seed=seed, multicore=multicore, numProc=numProc, conf.level=conf.level, diffsize=diffsize)) } calculatedCost <- .costCRD(nclus, nindiv, cluscost=cluscost, indivcost=indivcost, diffsize=diffsize) .reportCRD(nclus, nindiv, calculatedWidth, cost=calculatedCost, es=TRUE, estype=estype, assurance=assurance, diffsize=diffsize) invisible(nclus) } ss.aipe.crd.es.nindiv.fixedbudget <- function(budget, nclus, cluscost, indivcost, nrep=NULL, prtreat=NULL, iccy=NULL, es=NULL, estype = 1, numpredictor = 0, iccz=NULL, r2within=NULL, r2between=NULL, assurance=NULL, seed=123321, multicore=FALSE, numProc=NULL, conf.level=0.95, diffsize=NULL) { nindiv <- .findNindivCRDBudget(budget=budget, nclus=nclus, cluscost=cluscost, indivcost=indivcost, diffsize=diffsize) calculatedWidth <- NULL if(!is.null(nrep) && !is.null(prtreat) && !is.null(nindiv) && !is.null(iccy)) { suppressWarnings(calculatedWidth <- .findWidthCRDES(nrep=nrep, nclus=nclus, ntreatclus=round(nclus * prtreat), nindiv=nindiv, iccy=iccy, es=es, estype = estype, totalvar=1, covariate=as.logical(numpredictor), iccz=iccz, r2within=r2within, r2between=r2between, totalvarz = 1, assurance=assurance, seed=seed, multicore=multicore, numProc=numProc, conf.level=conf.level, diffsize=diffsize)) } calculatedCost <- .costCRD(nclus, nindiv, cluscost=cluscost, indivcost=indivcost, diffsize=diffsize) .reportCRD(nclus, nindiv, calculatedWidth, cost=calculatedCost, es=TRUE, estype=estype, assurance=assurance, diffsize=diffsize) invisible(nindiv) } ss.aipe.crd.es.both.fixedbudget <- function(budget, cluscost=0, indivcost=1, es, estype = 1, iccy, prtreat, r2between = 0, r2within = 0, numpredictor = 0, assurance=NULL, conf.level = 0.95, nrep = 1000, iccz = NULL, seed = 123321, multicore = FALSE, numProc=NULL, diffsize=NULL) { suppressWarnings(result <- .findMinWidthCRDES(budget=budget, cluscost=cluscost, indivcost=indivcost, es=es, estype = estype, iccy=iccy, prtreat=prtreat, r2between = r2between, r2within = r2within, numpredictor = numpredictor, assurance=assurance, conf.level = conf.level, nrep = nrep, iccz = iccz, seed = seed, multicore = multicore, numProc=numProc, diffsize=diffsize)) calculatedCost <- .costCRD(result[1], result[2], cluscost=cluscost, indivcost=indivcost, diffsize=diffsize) .reportCRD(result[1], result[2], result[3], cost=calculatedCost, es=TRUE, estype=estype, assurance=assurance, diffsize=diffsize) invisible(result[1:2]) } ss.aipe.crd.es.both.fixedwidth <- function(width, cluscost=0, indivcost=1, es, estype = 1, iccy, prtreat, r2between = 0, r2within = 0, numpredictor = 0, assurance=NULL, conf.level = 0.95, nrep = 1000, iccz = NULL, seed = 123321, multicore = FALSE, numProc=NULL, diffsize=NULL) { suppressWarnings(result <- .findMinCostCRDES(width=width, cluscost=cluscost, indivcost=indivcost, es=es, estype = estype, iccy=iccy, prtreat=prtreat, r2between = r2between, r2within = r2within, numpredictor = numpredictor, assurance=assurance, conf.level = conf.level, nrep = nrep, iccz = iccz, seed = seed, multicore = multicore, numProc=numProc, diffsize=diffsize)) .reportCRD(result[1], result[2], result[4], cost=result[3], es=TRUE, estype=estype, assurance=assurance, diffsize=diffsize) invisible(result[1:2]) }
LoglikNormalCens <- function(x, data, lowerbound, vdelta){ if(x[2] > 0){ if(length(lowerbound[is.na(lowerbound)==FALSE])!=0){ loglik <- sum(log(dnorm(data[vdelta == 1], mean=x[1], sd=x[2]))) + sum(log(pnorm(data[vdelta == 0 & is.na(lowerbound)==TRUE], mean=x[1], sd=x[2]))) + sum(log(pnorm(data[vdelta == 0 & is.na(lowerbound)==FALSE], mean=x[1], sd=x[2])-pnorm(lowerbound[vdelta == 0 & is.na(lowerbound)==FALSE], mean=x[1], sd=x[2]))) } if(length(lowerbound[is.na(lowerbound)==FALSE])==0){ loglik <- sum(log(dnorm(data[vdelta == 1], mean=x[1], sd=x[2]))) + sum(log(pnorm(data[vdelta == 0], mean=x[1], sd=x[2]))) } } if(x[2] <= 0){ loglik <- -Inf } if(loglik == -Inf){loglik <- -100000} return(loglik) }
Wave <- setClass("Wave", slots = list( metadata = "list", design = "data.frame", samples = "character", sampled_data = "data.frame", data = "data.frame" ))
context("errcheck_stdat") test_that("tests of errcheck_stdat",{ times<-1:10 dat<-"nonnumeric" callfunc<-"notrealfunc" expect_error(errcheck_stdat(times,dat,callfunc), "Error in errcheck_stdat called by notrealfunc: dat must be numeric") dat<-1 expect_error(errcheck_stdat(times,dat,callfunc), "Error in errcheck_stdat called by notrealfunc: dat must be a matrix") dat<-matrix(c(1,2,3),1,3) expect_error(errcheck_stdat(times,dat,callfunc), "Error in errcheck_stdat called by notrealfunc: dat must have at least two rows") dat<-matrix(1,3,9) expect_error(errcheck_stdat(times,dat,callfunc), "Error in errcheck_stdat called by notrealfunc: second dimension of dat must equal length of times") dat<-matrix(1,3,10) dat[1,1]<-NaN expect_error(errcheck_stdat(times,dat,callfunc), "Error in errcheck_stdat called by notrealfunc: dat must not contain NAs, NaNs, Infs") })
LogisticSigmoidLRCFitter <- setRefClass('LogisticSigmoidLRCFitter' , contains = 'LightResponseCurveFitter' ) LogisticSigmoidLRCFitter_predictGPP <- function( Rg , Amax , alpha ) { GPP <- Amax * tanh(alpha * Rg / Amax) } LogisticSigmoidLRCFitter$methods(predictGPP = LogisticSigmoidLRCFitter_predictGPP) LogisticSigmoidLRCFitter_computeGPPGradient <- function( Rg , Amax , alpha ) { .expr1 <- alpha * Rg .expr2 <- .expr1 / Amax .expr3 <- tanh(.expr2) .expr8 <- cosh(.expr2)^2 .value <- Amax * .expr3 .grad <- array(0, c(length(.value), 2L), list(NULL, c("Amax", "alpha"))) .grad[, 1L] <- .expr3 - Amax * (.expr1 / Amax^2 / .expr8) .grad[, 2L] <- Amax * (Rg / Amax / .expr8) .grad } LogisticSigmoidLRCFitter$methods(computeGPPGradient = LogisticSigmoidLRCFitter_computeGPPGradient)
tilt_compensate <- function(x,y,z,pitch,roll,declination = 0,angle = "degree"){ sinp = sin(pitch) sinr = sin(roll) cosp = cos(pitch) cosr = cos(roll) xh = x*cosp + y*sinr*sinp + z*cosr*sinp yh = y*cosr - z*sinr azimuth90 = atan(yh/xh) heading_mag = azimuth90 category = rep(0,length(azimuth90)) for (i in 1:length(x)){ if (xh[i] < 0 ){ heading_mag[i] <- pi - azimuth90[i] category[i] <- 1 } if (xh[i] > 0 & yh[i] < 0 ){ heading_mag[i] <- -azimuth90[i] category[i] <- 2 } if (xh[i] > 0 & yh[i] > 0 ){ heading_mag[i] <- (2*pi) - azimuth90[i] category[i] <- 3 } if (xh[i] == 0 & yh[i] < 0 ){ heading_mag[i] <- pi/2 category[i] <- 4 } if (xh[i] == 0 & yh[i] > 0 ){ heading_mag[i] <- (3*pi)/2 category[i] <- 5 } } if (angle == "degree"){ heading_geo <- (heading_mag + (declination*(pi/180))) %% (2*pi) } if (angle == "radian"){ heading_geo <- (heading_mag + declination) %% (2*pi) } tiltlist <- list("xh" = xh, "yh" = yh, "heading_mag" = heading_mag,"heading_geo" = heading_geo) class(tiltlist) <- "tiltcompensate" return(tiltlist) }
getAutoGridSize <- function(nL) { index10 = floor(log(nL, base=10)) if(nL/(10^index10) < 3) { index10 = index10-1 } grid.size = 10^(1:index10) return(grid.size) } hardthres = function(v, low=0.9, high=1.1){ n = length(v) for (i in 1:n){ if (v[i]>low && v[i]<high) v[i] = 1 } v } comb = function(tau, cns1, cns2, low=0.9, high=1.1){ n = length(cns1) if (n==1) return(tau) code = rep("",n) for (i in 1:n){ if (cns1[i]<low){ code[i] = "0" }else if (cns1[i]>high){ code[i] = "2" }else{ code[i] = "1" } if (cns2[i]<low){ code[i] = paste(code[i],"0",sep="") }else if (cns2[i]>high){ code[i] = paste(code[i],"2",sep="") }else{ code[i] = paste(code[i],"1",sep="") } } removeid = c() for (i in 2:n){ if (code[i]==code[i-1]){ removeid = c(removeid, i) } } if (length(removeid)==0) return(tau) return(tau[-removeid]) } plotCN = function(n, tauhat, ascn, pos=NULL, gaincol="red", losscol="blue", neutralcol="green",xlab=NULL, ylab=NULL, pch=".",...){ tauhat = sort(unique(c(1,tauhat,n))) ascn1 = ascn[1,] ascn2 = ascn[2,] if (is.null(pos)){ pos = 1:n if (is.null(xlab)) xlab = "SNP }else{ tauhat = pos[tauhat] if (is.null(xlab)) xlab = "Position (bp)" } if (is.null(ylab)) ylab = "Allele-specific CN" poscn1 = poscn2 = rep(1,n) K = length(tauhat)-1 m = match(tauhat[1:K], pos) if (K>1){ for (i in 1:(K-1)){ poscn1[m[i]:(m[i+1]-1)] = ascn1[i] poscn2[m[i]:(m[i+1]-1)] = ascn2[i] } } poscn1[m[K]:n] = ascn1[K] poscn2[m[K]:n] = ascn2[K] g1 = l1 = g2 = l2 = c() if (K>1){ for (i in 1:(K-1)){ if (ascn1[i]>1){ g1 = c(g1, m[i]:(m[i+1]-1)) }else if (ascn1[i]<1){ l1 = c(l1, m[i]:(m[i+1]-1)) } if (ascn2[i]>1){ g2 = c(g2, m[i]:(m[i+1]-1)) }else if (ascn2[i]<1){ l2 = c(l2, m[i]:(m[i+1]-1)) } } } plot(pos, poscn1, col=neutralcol, ylim = c(0, max(c(ascn1,ascn2))+0.5),xlab=xlab, ylab=ylab, pch=pch, ...) points(pos, poscn2, col=neutralcol, pch=pch, ...) for (i in 1:K){ if (i==K){ ids = m[K]:n }else{ ids = m[i]:(m[i+1]-1) } nids = length(ids) if (ascn1[i]>1){ points(pos[ids], poscn1[ids], col=gaincol, pch=pch,...) if (i>1 && ascn1[i-1]>1){ a = ascn1[i-1] }else{ a = 1 } points(c(pos[ids[1]], pos[ids[1]]), c(a, ascn1[i]), col=gaincol, type="l") if (i<K-1 && ascn1[i+1]>1){ a = ascn1[i+1] }else{ a = 1 } points(c(pos[ids[nids]], pos[ids[nids]]), c(a, ascn1[i]), col=gaincol, type="l") }else if (ascn1[i]<1){ points(pos[ids], poscn1[ids], col=losscol, pch=pch, ...) if (i>1 && ascn1[i-1]<1){ a = ascn1[i-1] }else{ a = 1 } points(c(pos[ids[1]], pos[ids[1]]), c(a, ascn1[i]), col=losscol, type="l") if (i<K-1 && ascn1[i+1]<1){ a = ascn1[i+1] }else{ a = 1 } points(c(pos[ids[nids]], pos[ids[nids]]), c(a, ascn1[i]), col=losscol, type="l") } if (ascn2[i]>1){ points(pos[ids], poscn2[ids], col=gaincol, pch=pch, ...) if (i>1 && ascn2[i-1]>1){ a = ascn2[i-1] }else{ a = 1 } points(c(pos[ids[1]], pos[ids[1]]), c(a, ascn2[i]), col=gaincol, type="l") if (i<K-1 && ascn2[i+1]>1){ a = ascn2[i+1] }else{ a = 1 } points(c(pos[ids[nids]], pos[ids[nids]]), c(a, ascn2[i]), col=gaincol, type="l") }else if (ascn2[i]<1){ points(pos[ids], poscn2[ids], col=losscol, pch=pch, ...) if (i>1 && ascn2[i-1]<1){ a = ascn2[i-1] }else{ a = 1 } points(c(pos[ids[1]], pos[ids[1]]), c(a, ascn2[i]), col=losscol, type="l") if (i<K-1 && ascn2[i+1]<1){ a = ascn2[i+1] }else{ a = 1 } points(c(pos[ids[nids]], pos[ids[nids]]), c(a, ascn2[i]), col=losscol, type="l") } } }
set.objfn <- function(lprec, obj, indices) { if(missing(indices)) { if(length(obj) != dim(lprec)[2]) stop("the length of ", sQuote("obj"), " is not equal to the number of ", "decision variables in the model") epsel <- .Call(RlpSolve_get_epsel, lprec) indices <- which(abs(obj) > epsel) obj <- obj[indices] } if(length(obj) != length(indices)) stop(sQuote("obj"), " and ", sQuote("indices"), " are not the same length") .Call(RlpSolve_set_obj_fnex, lprec, as.double(obj), as.integer(indices)) invisible() }
linearRegCostFunction <- function(X, y, lambda) { function(theta) { m <- length(y) J <- 0 h = X %*% theta thetas <- theta[-1] J <- 1 / (2 * m) * sum((h - y) ^ 2) + (lambda / (2 * m)) * sum(theta ^ 2) J } } linearRegGradFunction <- function(X, y, lambda) { function(theta) { m <- length(y) grad <- rep(0,length(theta)) grad } }
knitr::opts_chunk$set( collapse = TRUE, comment = " fig.width = 7, fig.asp = 0.7, fig.align = 'center' ) options(tibble.print_min = 5L, tibble.print_max = 5L) library(aba) library(dplyr, warn.conflicts = FALSE) data <- adnimerge %>% dplyr::filter(VISCODE == 'bl') model <- aba_model() %>% set_data(data) %>% set_groups(DX_bl %in% c('MCI','AD')) %>% set_outcomes(ConvertedToAlzheimers, CSF_ABETA_STATUS_bl) %>% set_predictors( PLASMA_PTAU181_bl, PLASMA_NFL_bl, c(PLASMA_PTAU181_bl, PLASMA_NFL_bl) ) %>% set_covariates(AGE, GENDER, EDUCATION) %>% set_stats(stat_glm(std.beta=T)) print(model) model <- model %>% fit() model_summary <- model %>% summary() print(model_summary) model_summary %>% aba_plot_coef(coord_flip=T) model_summary %>% aba_plot_metric() model_summary %>% aba_plot_roc()
p.seqdatebreaks <- function(x,periodicity){ a<-x a<-seq.Date(from=x[[1]],to=x[[length(x)]],by = periodicity) return(a) }
e2dist <- function(x, y=NULL){ if(is.null(dim(x)) && length(x) == 2) x <- matrix(x, nrow=1) if(ncol(x) != 2) stop("Argument 'x' must be a 2-column matrix or data frame, or a length 2 vector.", call.=FALSE) if(is.null(y)) { y <- x } else { if(is.null(dim(y)) && length(y) == 2) y <- matrix(y, nrow=1) if(ncol(y) != 2) stop("Argument 'y' must be a 2-column matrix or data frame, or a length 2 vector.", call.=FALSE) } i <- sort(rep(1:nrow(y), nrow(x))) dvec <- sqrt((x[, 1] - y[i, 1])^2 + (x[, 2] - y[i, 2])^2) matrix(dvec, nrow = nrow(x), ncol = nrow(y), byrow = FALSE) }
pat_createNew <- function( id = NULL, label = NULL, pas = NULL, startdate = NULL, enddate = NULL, timezone = NULL, baseUrl = "https://api.thingspeak.com/channels/", verbose = FALSE ) { MazamaCoreUtils::stopIfNull(baseUrl) MazamaCoreUtils::stopIfNull(pas) if ( is.null(id) && is.null(label) ) { stop(paste0("label or id must be provided")) } else if ( is.null(id) && !is.null(label) ) { if ( is.null(pas) ) stop(paste0("pas must be provided when loading by label")) if ( !label %in% pas$label ) stop(sprintf("label '%s' is not found in the 'pas' object", label)) pattern <- paste0("^", label, "$") deviceDeploymentID <- pas_getDeviceDeploymentIDs(pas, pattern = pattern) if ( length(deviceDeploymentID) > 1 ) stop(sprintf("label '%s' matches more than one sensor", label)) } else { deviceDeploymentID <- id } pas_single <- pas %>% dplyr::filter(is.na(.data$parentID)) %>% dplyr::filter(.data$deviceDeploymentID == !!deviceDeploymentID) if ( nrow(pas_single) > 1 ) { stop(paste0("Multiple sensors share deviceDeploymentID: ", deviceDeploymentID, "'")) } if ( is.null(timezone) ) { timezone <- pas_single %>% dplyr::pull(.data$timezone) } if ( !is.null(startdate) && !is.null(enddate) ) { dateRange <- MazamaCoreUtils::timeRange( starttime = startdate, endtime = enddate, timezone = timezone, unit = "min", ceilingStart = FALSE, ceilingEnd = FALSE ) } else { dateRange <- MazamaCoreUtils::dateRange( startdate = startdate, enddate = enddate, timezone = timezone, unit = "min", ceilingStart = FALSE, ceilingEnd = FALSE, days = 7 ) } dateSeq <- seq(dateRange[1], dateRange[2], by = lubridate::ddays(7)) if ( dateRange[2] > utils::tail(dateSeq, 1) ) { dateSeq <- c(dateSeq, dateRange[2]) } if ( verbose ) { message(sprintf("Requesting data for %s from %s to %s", id, dateSeq[1], dateSeq[2])) } pat_rawList <- pat_downloadParseRawData( id = pas_single$deviceDeploymentID, label = NULL, pas = pas, startdate = dateSeq[1], enddate = dateSeq[2], timezone = timezone, baseUrl = baseUrl ) if ( length(dateSeq) > 2 ) { for ( i in 2:(length(dateSeq) - 1) ) { if ( verbose ) { message(sprintf("Requesting data for %s from %s to %s", id, dateSeq[i], dateSeq[i+1])) } new_pat_rawList <- pat_downloadParseRawData( id = pas_single$deviceDeploymentID, label = NULL, pas = pas, startdate = dateSeq[i], enddate = dateSeq[i + 1], timezone = timezone, baseUrl = baseUrl ) pat_rawList$A_PRIMARY <- dplyr::bind_rows(pat_rawList$A_PRIMARY, new_pat_rawList$A_PRIMARY) %>% dplyr::distinct() pat_rawList$A_SECONDARY <- dplyr::bind_rows(pat_rawList$A_SECONDARY, new_pat_rawList$A_SECONDARY) %>% dplyr::distinct() pat_rawList$B_PRIMARY <- dplyr::bind_rows(pat_rawList$B_PRIMARY, new_pat_rawList$B_PRIMARY) %>% dplyr::distinct() pat_rawList$B_SECONDARY <- dplyr::bind_rows(pat_rawList$B_SECONDARY, new_pat_rawList$B_SECONDARY) %>% dplyr::distinct() } } if ( verbose ) { message(sprintf("Download completed, merging/harmonizing data ...")) } pat <- pat_createPATimeseriesObject(pat_rawList) pat <- pat %>% pat_distinct() %>% pat_filterDatetime( startdate = dateRange[1], enddate = dateRange[2], timezone = timezone ) return(pat) } if ( FALSE ) { library(AirSensor) setArchiveBaseUrl("http://data.mazamascience.com/PurpleAir/v1") pas <- pas_load() id <- "0bf2ba90b55e7ce6_2025" label <- NULL startdate <- 20170930 enddate <- 20171102 timezone <- NULL baseUrl <- "https://api.thingspeak.com/channels/" verbose <- TRUE pat <- pat_createNew( id, label, pas, startdate, enddate, timezone, baseUrl, verbose ) id = NULL label = NULL pas = example_pas startdate = NULL enddate = NULL timezone = NULL baseUrl = "https://api.thingspeak.com/channels/" verbose = FALSE label = "Seattle" pas = example_pas startdate = 20180701 enddate = 20180901 }
LKGridFindNmax<- function(n1, max.points, mean.neighbor, delta, gridList){ info<- summary( gridList) deltaScaled<- delta/info$dx if( !is.null( mean.neighbor) ){ max.points <- mean.neighbor*n1 } if (is.null(max.points)) { max.points <- n1 * ceiling(prod(deltaScaled*2 + 1 ) ) } return( max.points ) }
library(fields) library(gganimate) library(tidyverse) piChar <- read.table("data/PI_og_100000.txt", stringsAsFactors=F, colClasses = c("character"))[1,1] piVec <- as.numeric(strsplit(piChar, "")[[1]]) x <- y <- rep(NULL, length(piVec)) x[1] <- 0 y[1] <- 0 for (i in 2:length(piVec)){ x[i] <- x[(i-1)] + sin((pi*2)*(piVec[i]/10)) y[i] <- y[(i-1)] + cos((pi*2)*(piVec[i]/10)) } rainbowColDark <- c(" rainbowColDark <- designer.colors(n=10, col=rainbowColDark) Pi.frame <- data.frame(PI=piVec[-1], x=x[-length(x)], y=y[-length(y)], ID=1:(length(x)-1), stringsAsFactors=F) ggplot(Pi.frame[1:8000,], aes(x=x, y=y, group = "1")) + geom_path(aes(color = ID), size=0.7) + scale_colour_gradientn(colours = rainbowColDark) + coord_fixed(ratio = 1) + theme_bw() + theme(panel.grid = element_blank(), axis.ticks = element_blank(), text = element_blank(), title = element_blank(), legend.position="none", panel.border = element_blank(), panel.background = element_blank()) piPlot <- ggplot(Pi.frame[1:1000,], aes(x=x, y=y, group = "1")) + geom_path(aes(color = ID), size=0.7) + scale_colour_gradientn(colours = rainbowColDark) + coord_fixed(ratio = 1) + theme_bw() + theme(panel.grid = element_blank(), axis.ticks = element_blank(), text = element_blank(), title = element_blank(), legend.position="none", panel.border = element_blank(), panel.background = element_blank()) + transition_reveal(id = "1", along = ID) + view_follow() animate(piPlot, nframes = 200, fps = 10, type = "cairo", rewind = TRUE) times <- rep(100, nrow(Pi.frame)) times[1:24] <- c(50000, 40000, 30000, 30000, 30000, 30000, 20000, 20000, 20000, 10000, 10000, 10000, 10000, 10000, 5000, 5000, 5000, 5000, 1000, 1000, 1000, 500, 500, 500) pi_slowdown <- Pi.frame %>% mutate(show_time = ifelse(ID %in% 1:100, times, 1), reveal_time = cumsum(show_time)) pi_pause <- Pi.frame %>% mutate(show_time = ifelse(ID %in% c(500, 2000, 5000, 7000), 500, 1)) %>% uncount(show_time) %>% mutate(reveal_time = row_number()) pi_slow <- ggplot(pi_slowdown[1:nrow(pi_slowdown),], aes(x=x, y=y, group = "1")) + geom_path(aes(color = ID), size=0.7) + scale_colour_gradientn(colours = rainbowColDark) + coord_fixed(ratio = 1) + theme_bw() + theme(panel.grid = element_blank(), axis.ticks = element_blank(), text = element_blank(), title = element_blank(), legend.position="none", panel.border = element_blank(), panel.background = element_blank()) + transition_reveal(id = "1", along = reveal_time) + view_follow() animate(pi_slow, nframes = 200, fps = 10, type = "cairo", renderer = av_renderer()) anim_save("pi_slow.mp4") pi_stop <- ggplot(pi_pause[1:nrow(pi_pause),], aes(x=x, y=y, group = "1")) + geom_path(aes(color = ID), size=0.7) + scale_colour_gradientn(colours = rainbowColDark) + coord_fixed(ratio = 1) + theme_bw() + theme(panel.grid = element_blank(), axis.ticks = element_blank(), text = element_blank(), title = element_blank(), legend.position="none", panel.border = element_blank(), panel.background = element_blank()) + transition_reveal(id = "1", along = reveal_time) + view_follow() animate(pi_stop, nframes = 400, fps = 10, type = "cairo", renderer = av_renderer()) anim_save("pi_pause.mp4")
add_probs.glmerMod <- function(df, fit, q, name = NULL, yhatName = "pred", comparison = "<", type = "boot", includeRanef = TRUE, nSims = 10000, ...){ if (!is.null(fit@optinfo$conv$lme4$code)) warning ("Coverage probabilities may be inaccurate if the model failed to converge") if(fit@resp$family$family == "binomial") stop("Prediction Intervals are not useful if the response is Bernoulli") if (is.null(name) & (comparison == "<")) name <- paste("prob_less_than", q, sep="") if (is.null(name) & (comparison == ">")) name <- paste("prob_greater_than", q, sep="") if (is.null(name) & (comparison == "<=")) name <- paste("prob_less_than_or_equal_to", q, sep="") if (is.null(name) & (comparison == ">=")) name <- paste("prob_greater_than_or_equal_to", q, sep="") if (is.null(name) & (comparison == "=")) name <- paste("prob_equal_to", q, sep="") if ((name %in% colnames(df))) { warning ("These probabilitiess may have already been appended to your dataframe. Overwriting.") } if (type == "boot") bootstrap_probs_glmermod(df, fit, q, name, includeRanef, nSims, yhatName, comparison) else stop("Incorrect type specified!") } bootstrap_probs_glmermod <- function(df, fit, q, name, includeRanef, nSims, yhatName, comparison) { if (includeRanef) { rform = NULL } else { rform = NA } gg <- simulate(fit, newdata = df, re.form = rform, nsim = nSims) gg <- as.matrix(gg) probs <- apply(gg, 1, FUN = calc_prob, quant = q, comparison = comparison) out <- predict(fit, df, re.form = rform, type = "response") if(is.null(df[[yhatName]])) df[[yhatName]] <- out df[[name]] <- probs data.frame(df) }
negint2<-function(ux=0.5,fixedfu=1,type=2,u=c(0.5,0.5,1),ut=c(0.5,1.0,1.5),tfix=ut[length(ut)]+0.5,maxfu=10.0,tchange=c(0,0.5,1),ratec=c(0.15,0.15,0.15),eps=1.0e-03){ if (type==2){ amax=max(ux,ratec,fixedfu)+1 aseq=seq(0,fixedfu,by=1/amax*eps) bseq=c(aseq,0) cseq=unique(bseq[bseq<=fixedfu]) nc=length(cseq) cseq0=c(0,cseq[-nc]) dseq=c((cseq+cseq0)/2,fixedfu) nd=length(dseq) ss=pwe(t=dseq,rate=ratec,tchange=tchange)$surv temp=ux/(1+ux*dseq)^2 dtemp=cseq-cseq0 mt=sum(temp[-nd]*ss[-nd]*dtemp) tt=sum(ss[-nd]*dtemp) vt=2*sum(dseq[-nd]*ss[-nd]*dtemp)-tt^2 } else if (type==3){ amax=max(ux,u,ut,tfix,maxfu)+1 aseq=seq(0,maxfu,by=1/amax*eps) bseq=c(aseq,0) cseq=unique(bseq[bseq<=maxfu]) nc=length(cseq) cseq0=c(0,cseq[-nc]) dseq=c((cseq+cseq0)/2,maxfu) nd=length(dseq) ss=pwu(t=tfix-dseq,u=u,ut=ut)$dist temp=ux/(1+ux*dseq)^2 dtemp=cseq-cseq0 mt=sum(temp[-nd]*ss[-nd]*dtemp) tt=sum(ss[-nd]*dtemp) vt=2*sum(dseq[-nd]*ss[-nd]*dtemp)-tt^2 } else if (type==4){ amax=max(ux,u,ut,tfix,maxfu,ratec)+1 aseq=seq(0,maxfu,by=1/amax*eps) bseq=c(aseq,0) cseq=unique(bseq[bseq<=maxfu]) nc=length(cseq) cseq0=c(0,cseq[-nc]) dseq=c((cseq+cseq0)/2,maxfu) nd=length(dseq) ss=pwu(t=tfix-dseq,u=u,ut=ut)$dist*pwe(t=dseq,rate=ratec,tchange=tchange)$surv temp=ux/(1+ux*dseq)^2 dtemp=cseq-cseq0 mt=sum(temp[-nd]*ss[-nd]*dtemp) tt=sum(ss[-nd]*dtemp) vt=2*sum(dseq[-nd]*ss[-nd]*dtemp)-tt^2 } list(mt=mt,tt=tt,vt=pmax(vt,0)) }
context("sentensize") o <- sapply(c('', 'neonira wrote package \twyz.code.rdoc'), sentensize, USE.NAMES = FALSE) test_that("sentensize", { expect_length(o[1], 1L) expect_equal(o[1], '') expect_length(o[2], 1L) expect_equal(o[2], 'Neonira wrote package wyz.code.rdoc.') expect_equal(sentensize('a simple', ' question\t', punctuationCharacter_s_1 = '?'), "A simple question?") })
plotLinReg <- function(dat,indepVarLst=NULL,dependVar=NULL,cusTxt=NULL,regrLty=1,regrLwd=1,regrCol=1,confInt=0.95, confCol=NULL,xLab=NULL,yLab=NULL,xLim=NULL,yLim=NULL,tit=NULL,nSignif=3,col=1,pch=1,silent=FALSE,callFrom=NULL) { argNa <- c(deparse(substitute(dat)),deparse(substitute(indepVarLst)),deparse(substitute(dependVar))) fxNa <- wrMisc::.composeCallName(callFrom,newNa="plotLinReg") opar <- graphics::par(no.readonly=TRUE) asNumDf <- function(x, colNa=c("x","y")) { if(!is.data.frame(x)) x <- as.data.frame(x[,1:2], stringsAsFactors=FALSE) if(length(colNa) !=2) stop(" argument 'colNa' must be of length=2") chNum <- c(is.numeric(x[,1]), is.numeric(x[,2])) if(any(!chNum)) for(i in which(!chNum)) { num <- try(wrMisc::convToNum(x[,i], spaceRemove=TRUE, remove=NULL,silent=silent,callFrom=fxNa)) if("character" %in% class(num)) { num <- as.numeric(as.character(as.factor(x[,i]))) warning(" Trouble converting column no ",i," to numeric (",wrMisc::pasteC(utils::head(x[,i])),", interpreted as ",wrMisc::pasteC(utils::head(num)),")") } x[,i] <- num } colnames(x) <- colNa x } extrFromList <- function(x,yy,zz,colNa=c("x","y")) { if(all(is.integer(c(yy[1],zz[1])))) { if(any(c(yy[1],zz[1]) <1) | length(x) < max(c(yy[1],zz[1]))) stop(" index values for list-elements of 'x' out of range") } else { msg <- "both arguments 'yy' and 'zz' must correspond to list-elements of 'x'" if(length(yy) <1) stop(msg) if(length(zz) <1) { isBad <- TRUE if(length(dim(x[[yy]])) >1) if(ncol(x[[yy]]) >1) { isBad <- FALSE x <- as.data.frame(x[[yy]][,1:2],stringsAsFactors=FALSE) } if(isBad) stop(msg) } else { chNa1 <- c(yy[1],zz[1]) %in% names(x) if(!all(chNa1)) stop("Cannot find ",wrMisc::pasteC(c(yy[1],zz[1])[which(!chNa1)],quoteC="'")," in list 'x'") x <- data.frame(x[[yy]], x[[zz]], stringsAsFactors=FALSE)} } colnames(x) <- colNa x } extrFromMatr <- function(x,yy,zz,name1=c("y","ordinate","dat","measure","pred","depend"),name2=c("x","abscissa","grp","grp2","dat2","obs","indep"), colNa=c("x","y"),silent=silent,fxNa=fxNa) { chColNa1 <- wrMisc::extrColsDeX(x,extrCol=list(if(is.null(zz)) name1 else zz), doExtractCols=FALSE,callFrom=fxNa,silent=silent) chColNa2 <- wrMisc::extrColsDeX(x,extrCol=list(if(is.null(yy)) name2 else yy), doExtractCols=FALSE,callFrom=fxNa,silent=silent) if(!all(chColNa1,chColNa2)) stop("Cannot find column-names to use from 'x'") x <- data.frame(x[,if(length(chColNa2) >0) chColNa2[1] else { if(chColNa1[1]==2) 1 else chColNa1[1]+1}],x[,chColNa1[2]],stringsAsFactors=FALSE) colnames(x) <- colNa x } msg <- df0<- NULL if(length(dat) <1) { msg <- c(" incomplete data, nothing to do") } else { if(all(!is.list(dat), length(dat) >2,length(indepVarLst) >2, length(dim(dat)) <1, length(dim(indepVarLst)) <1 )) { if(length(dat)!=length(indepVarLst)) stop("length of 'dat' and 'indepVarLst' don't match !") df0 <- data.frame(x=indepVarLst,y=dat,stringsAsFactors=FALSE) argNa[4:5] <- argNa[2:1] } else { if(is.list(dat)) { df0 <- extrFromList(dat,indepVarLst,dependVar) argNa[4:5] <- argNa[2:3] } else { if(length(dim(dat)) >1) { if(ncol(dat) >1) { df0 <- extrFromMatr(dat,indepVarLst,dependVar,silent,fxNa) } else { df0 <- data.frame(x=if(length(dim(indepVarLst)) >1) indepVarLst[,1] else indepVarLst, y=dat, stringsAsFactors=FALSE) } argNa[4:5] <- argNa[2:3] } else msg <- "unknown format of 'dat'" }}} if(length(msg) >0 | length(df0) <1) message(fxNa,"can't plot",msg) else { df0 <- asNumDf(df0) lm0 <- stats::lm(y ~ x, data=df0) if(length(lm0$coefficients) >2) message(fxNa," Bizzare : The regression model was expected as 2 coefficients, but has ", length(lm0$coefficients)," coefficients ",wrMisc::pasteC(names(lm0$coefficients),quoteC="'")) argNa[4:5] <- gsub("\"","",argNa[4:5]) if(is.null(xLab)) xLab <- if(argNa[4]=="NULL") "x" else argNa[4] if(is.null(yLab)) yLab <- if(argNa[5]=="NULL" | argNa[5]==xLab) "y" else argNa[5] graphics::plot(y ~ x, data=df0, las=1, xlab=xLab, ylab=yLab, pch=pch,col=col, main=tit) graphics::abline(lm0, lty=regrLty, lwd=regrLwd, col=regrCol) suplTx <- paste(c("; ",if(length(cusTxt) <1) paste("p.slope =",signif(stats::coef(summary(lm0))[2,"Pr(>|t|)"],2)) else cusTxt), collapse=" ") graphics::mtext(paste("regression (rounded): y =",signif(stats::coef(lm0)[2],nSignif)," x +",signif(stats::coef(lm0)[1],nSignif),suplTx, ", r2=",signif(stats::cor(df0$y,df0$x)^2,nSignif)),cex=0.75,line=0.15) if(length(confInt) >0) { ra <- c(range(df0$x,na.rm=TRUE), abs(mean(df0$x,na.rm=TRUE))) newx <- seq(ra[1]-0.05*ra[3],ra[2]+0.05*ra[3],length.out=200) if(length(confCol) <1) confCol <- grDevices::rgb(0.3,0.3,0.3,0.07) confInterval <- stats::predict(lm0, newdata=data.frame(x=newx), interval="confidence", level=confInt) graphics::polygon(cbind(x=c(newx,rev(newx)),y=c(confInterval[,"lwr"],confInterval[length(newx):1,"upr"])),col=confCol,border=NA) graphics::points(y ~ x, df0, col=col) graphics::mtext(paste(" confidence interval at ",100*confInt,"% shown"), line=-1.05,cex=0.65,adj=0,col=wrMisc::convColorToTransp(confCol,alph=240)) } } invisible(list(data=df0,linRegr=lm0,if(length(confInt) >0) confInterval=confInterval)) }
testthat::test_that("two_way_interaction_plot: lm model", { model <- lm_model( data = iris[1:4], response_variable = "Sepal.Length", predictor_variable = c(Sepal.Width, Petal.Width), two_way_interaction_factor = c(Sepal.Width, Petal.Width) ) plot <- two_way_interaction_plot(model) testthat::expect_false(is.null(plot)) }) testthat::test_that("two_way_interaction_plot: lme4 model", { model <- lme_model( data = popular, response_variable = popular, random_effect_factors = sex, non_random_effect_factors = c(extrav, sex, texp), two_way_interaction_factor = c(sex, extrav), id = class, use_package = "lme4", quite = TRUE ) plot <- two_way_interaction_plot(model) testthat::expect_false(is.null(plot)) }) testthat::test_that("two_way_interaction_plot: lmerTest model", { model <- lme_model( data = popular, response_variable = popular, random_effect_factors = sex, non_random_effect_factors = c(extrav, sex, texp), two_way_interaction_factor = c(sex, extrav), id = class, use_package = "lmerTest", quite = TRUE ) plot <- two_way_interaction_plot(model) testthat::expect_false(is.null(plot)) }) testthat::test_that("two_way_interaction_plot: nlme model", { model <- lme_model( data = popular, response_variable = popular, random_effect_factors = sex, non_random_effect_factors = c(extrav, sex, texp), two_way_interaction_factor = c(sex, extrav), id = class, use_package = "nlme", opt_control = "optim", quite = TRUE ) plot <- two_way_interaction_plot(model) testthat::expect_false(is.null(plot)) })
context("Test the otp_connect function") skip_if_no_otp <- function() { if(!identical(Sys.getenv("OTP_ON_LOCALHOST"), "TRUE")) skip("Not running test as the environment variable OTP_ON_LOCALHOST is not set to TRUE") } test_that("default object is created and make_url method works correctly", { skip_if_no_otp() otpcon <- otp_connect() expect_s3_class(otpcon, "otpconnect") expect_match(make_url(otpcon)$router, "http://localhost:8080/otp/routers/default") expect_match(make_url(otpcon)$otp, "http://localhost:8080/otp") }) test_that("correct message when /otp endpoint exists", { skip_if_no_otp() expect_message(otp_connect(), "http://localhost:8080/otp is running OTPv1") }) test_that("correct error when /otp endpoint does not exist", { skip_if_no_otp() expect_error(otp_connect(hostname = "test"), "Unable to connect to OTP. Does http://test:8080/otp even exist?") }) test_that("correct message when router exists", { skip_if_no_otp() expect_message(otp_connect(), "Router http://localhost:8080/otp/routers/default exists") }) test_that("correct error when router does not exist", { skip_if_no_otp() expect_error(otp_connect(router = "test"), "Router http://localhost:8080/otp/routers/test does not exist") })
std.data <- function(datain, cols){ dataout <- datain changecols <- colnames(dataout) %in% cols leavecols <- !changecols options(warn = -1) means <- sapply(dataout, mean, na.rm = TRUE) sds <- sapply(dataout, sd, na.rm = TRUE) options(warn = 1) changed <- 0 for(i in 1:ncol(dataout)){ if(changecols[i]){ if(is.na(means[i]) | is.na(sds[i])){ str <- paste("Missing mean or sd for variable ", colnames(dataout)[i], ", it is not standardized.", sep="") warning(str, call.=FALSE) } else{ dataout[[i]] <- (dataout[[i]] - means[i])/sds[i] changed <- changed + 1 } } } options(warn = 0) cat("\nNumber of standardized columns: ", changed, "\n") means <- means[changecols] sds <- sds[changecols] tab <- rbind(means, sds) rownames(tab) <- c("mean","sd") cat("\nUsed means and sd's: \n") print(tab) return(dataout) }
unitizer_sect("Basic Tests", { library(utzflm, lib.loc=getOption('unitizer.tmp.lib.loc')) x <- 1:10 y <- x ^ 2 res <- fastlm(x, y) get_slope(res) }) unitizer_sect("Advanced Tests", { get_rsq(res) })
str_contains <- function(x, pattern, ignore.case = FALSE, logic = NULL, switch = FALSE) { if (switch && length(x) > 1) { warning("`x` must be of length 1 when `switch = TRUE`. First element will be used.", call. = FALSE) x <- x[1] } cnt <- c() if (ignore.case) { x <- tolower(x) pattern <- tolower(pattern) } for (k in pattern) { if (switch) cnt <- c(cnt, !sjmisc::is_empty(grep(x, k, fixed = TRUE))) else cnt <- c(cnt, !sjmisc::is_empty(grep(k, x, fixed = TRUE))) } if (is.null(logic)) return(cnt) else if (logic %in% c("or", "OR", "|")) return(any(cnt)) else if (logic %in% c("and", "AND", "&")) return(all(cnt)) else if (logic %in% c("not", "NOT", "!")) return(!any(cnt)) return(cnt) }
.FCC <- function(hwsd) { hwsd$PHASE <- as.integer(hwsd$PHASE) hwsd$T_TEXTURE <- as.integer(hwsd$T_TEXTURE) left <- substr(hwsd$SU_SYM74, 1, 1) right <- substr(hwsd$SU_SYM74, 2, 1) soil <- hwsd$SU_SYM74 fcc <- matrix(FALSE, nrow=length(soil), ncol=18) colnames(fcc) <- c('g', 'd', 'e', 'a', 'h', 'i', 'x', 'v', 'k', 'b', 's', 'n', 'c', "'", '', '', '', '') fcc[left == 'G' | left == 'W' | left=='O' | soil == 'Jt' | soil == 'Gt' | right == 'g' , 1] <- TRUE fcc[left == 'X' | left == 'Y', 2] <- TRUE fcc[left == 'Q'] <- TRUE fcc[left == 'F' & right != 'h' & hwsd$T_TEXTURE == 1, 3] <- TRUE fcc[hwsd$T_CEC_SOIL < 4] <- TRUE fcc[soil == 'Gd' | soil == 'Bd' | soil == 'Wd' | soil == 'Fh' | soil == 'Ah', 4] <- TRUE fcc[hwsd$T_PH_H2O < 5, 4] <- TRUE fcc[grep(soil, 'Rd_Nd_Od_Jd_Gh_Th_Fh_Nh_Ah_Wh') == 1 | left == 'P' | left == 'U', 5] <- TRUE fcc[(left == 'L' | left == 'B') & (right != 'k' & right != 'e' & right != 'v'), 5] <- TRUE fcc[(left == 'F' | left == 'A') & hwsd$T_TEXTURE == 3, 6] <- TRUE fcc[left == 'T', 7] <- TRUE fcc[left == 'V' | (right == 'v' & soil != 'Tv'), 8] <- TRUE fcc[soil == 'Qa' | soil == 'Qf' | left == 'F' | left == 'A' | left == 'N', 9] <- TRUE fcc[hwsd$PHASE == 4 | hwsd$PHASE == 5, 10] <- TRUE fcc[left == 'C' | left == 'E' | ((left=='X' | left=='Y') & right != 'l'), 10] <- TRUE fcc[soil == "Bk" & hwsd$T_TEXTURE != 1, 10] <- TRUE fcc[hwsd$T_PH_H2O > 7.3, 6] <- TRUE fcc[left == "Z" | hwsd$PHASE == 10, 11] <- TRUE fcc[hwsd$T_ECE > 4, 11] <- TRUE fcc[left == "S" | right == "s" | hwsd$PHASE == 11, 12] <- TRUE fcc[hwsd$T_ESP > 15, 12] <- TRUE fcc[soil == "Jt" | soil == "Gt" | soil == "Hj" , 13] <- TRUE fcc[hwsd$PHASE == 1, 16] <- TRUE fcc[hwsd$T_GRAVEL > 15, 16] <- TRUE fcc[left == "O" , 17] <- TRUE fcc[hwsd$T_TEXTURE == 1, 18] <- TRUE return(fcc) } .FCCagg <- function(hwsd) { fcc <- .FCC(hwsd) fcc <- hwsd$SHARE * fcc fccagg <- vector() for (i in 1:dim(fcc)[2]) { j <- tapply( fcc[,i], INDEX=hwsd$MU_GLOBAL, FUN=sum ) fccagg <- cbind(fccagg, j) } return(fccagg) }
"HSImetadata"
context("error_analysis") test_that("fcuk::error_analysis works", { expect_match(error_analysis("iri"),"iris") expect_match(error_analysis("dplir"),"dplyr") })
library(tibble) smiths <- frame_data( ~subject, ~time, ~age, ~weight, ~height, "John Smith", 1, 33, 90, 1.87, "Mary Smith", 1, NA, NA, 1.54 ) devtools::use_data(smiths, overwrite = TRUE)
get.dp.meta=function(dp.id){ dp.meta=rjson::fromJSON(file=paste0("http://data.neonscience.org/api/v0/products/", dp.id))$data names(dp.meta)=unlist(lapply(names(dp.meta), function(x) .camel.to.dot(x))) return(dp.meta) }
f_mactivate <- function (U, W) { d <- ncol(U) m <- ncol(W) N <- nrow(U) Xout <- matrix(0, N, m) Cout <- .C("mactivate_a", as.integer(N), as.integer(d), as.integer(m), as.double(as.vector(U)), as.double(as.vector(W)), Xout = as.double(as.vector(Xout))) Xout <- Cout[["Xout"]] dim(Xout) <- c(N, m) colnames(Xout) <- colnames(W) return(Xout) }
exp2flux <- function(model,expression,organism=NULL,typeID=NULL,missing="mean",scale=FALSE){ if(!is.null(organism) && !is.null(typeID)){ data <- try(kegg.gsets(species = organism, id.type = typeID)) data <- matrix(gsub("[[:digit:]]+$","",names(unlist(data$kg.sets))),dimnames = list(as.vector(unlist(data$kg.sets)),c())) } gpr.expression <- function(gpr,expression,missing){ gpr <- gsub("[()]","",gpr) gpr <- gsub("[[:space:]]","",gpr) complex <- lapply(gpr, function(gpr){unlist(strsplit(gpr,"or"))}) genes <- lapply(complex, function(complex){strsplit(complex,"and")}) genes[lengths(genes) == 0] <- NA min.complex <- lapply(genes, function(gene){ lapply(gene, function(gene){ gene <- unlist(gene) if(!is.null(organism) && !is.null(typeID)){ if(!all(gene%in%rownames(data))){ gene <- gene[gene%in%rownames(data)] }} else { gene <- gene[gene%in%rownames(expression@assayData$exprs)] } if (length(gene)==0){ minComplex <- 0 } else { if(any(gene%in%rownames(expression@assayData$exprs))){ minComplex <- min(rowMeans(expression@assayData$exprs,na.rm = TRUE)[gene],na.rm = TRUE) } else { if(!is.null(organism) && !is.null(typeID)){ minComplex <- summary(rowMeans(expression@assayData$exprs,na.rm = TRUE)[names(data[data[,1]%in%names(sort(table(data[gene,]))[1]),])])[[match(missing,c("min","1q","median","mean","3q","max"))]] } else { minComplex <- 0 } } } return(minComplex) }) }) exp <- unlist(lapply(min.complex, function(min.complex){sum(unlist(min.complex),na.rm = TRUE)})) exp[exp==0] <- summary(rowMeans(expression@assayData$exprs,na.rm = TRUE))[[match(missing,c("min","1q","median","mean","3q","max"))]] return(exp) } exp <- gpr.expression(gpr = model@gpr, expression = expression, missing=missing) if(scale==TRUE){ exp <- round((exp/max(exp,na.rm = TRUE)),6)*1000 } lb <- model@lowbnd ub <- model@uppbnd model@lowbnd <- -1*exp model@lowbnd[!model@react_rev] <- 0 model@uppbnd <- exp model@lowbnd[model@react_id%in%findExchReact(model)@react_id] <- lb[model@react_id%in%findExchReact(model)@react_id] model@uppbnd[model@react_id%in%findExchReact(model)@react_id] <- ub[model@react_id%in%findExchReact(model)@react_id] return(model) }
"VSS.sim" <- function(ncases=1000,nvariables=16,nfactors=4,meanloading=.5,dichot=FALSE,cut=0) { weight=sqrt(1-meanloading*meanloading) theta=matrix(rnorm(ncases*nfactors),nrow=ncases,ncol=nvariables) error=matrix(rnorm(ncases*nvariables),nrow=ncases,ncol=nvariables) items=meanloading*theta+weight*error if(dichot) {items <- (items[,1:nvariables] >= cut) items <- items + 0} return(items) } "VSS.simulate" <- function(ncases=1000,nvariables=16,nfactors=4,meanloading=.5,dichot=FALSE,cut=0) { weight=sqrt(1-meanloading*meanloading) theta=matrix(rnorm(ncases*nfactors),nrow=ncases,ncol=nvariables) error=matrix(rnorm(ncases*nvariables),nrow=ncases,ncol=nvariables) items=meanloading*theta+weight*error if(dichot) {items <- (items[,1:nvariables] >= cut) items <- items + 0} return(items) }
getbynames <- function (x, e) { x <- x [e] if (length (x) > 0) { if (is.character (e)) names (x) <- e x [sapply (x, is.null)] <- NA x } else { list () } }
getliststate <- function(lrank, socket = autosocket()){ request <- paste("getliststate&lrank=", lrank) writeLines(request, socket, sep = "\n") answerFromServer <- readLines(socket, n = 1) if(length(answerFromServer) == 0){ warning("Empty answer from server") return(NA) } resitem <- parser.socket(answerFromServer) if(resitem[1] != "0"){ warning(paste("error code returned by server :", resitem[1])) return(NA) } return(list(type = resitem[2], name = substr(x = resitem[3], start = 2, stop = nchar(resitem[3]) - 1), count = as.numeric(resitem[4]), locus = as.logical(resitem[5]))) } gls <- getliststate gln <- function(lrank, ...) getliststate(lrank, ...)$name
source_addin = function(file) in_root(sys.source( pkg_file('scripts', file), envir = new.env(parent = globalenv()), keep.source = FALSE )) new_post_addin = function() source_addin('new_post.R') update_meta_addin = function() source_addin('update_meta.R') insert_image_addin = function() source_addin('insert_image.R') touch_file_rstudio = function() { ctx = rstudioapi::getSourceEditorContext() if (!file.exists(ctx$path)) stop('The current document has not been saved yet.') p = normalizePath(ctx$path); mtime = function() file.info(p)[, 'mtime'] m = mtime() on.exit(if (!identical(m, m2 <- mtime())) message( 'The modification time of "', p, '" has been updated from ', m, ' to ', m2 ), add = TRUE) touch_file(p) } touch_file = function(path, time = Sys.time()) Sys.setFileTime(path, time) quote_poem = function(x) { x = paste(x, collapse = '\n') if (grepl('^\\s*$', x)) return(x) x = gsub(' *\n', ' \n', x) x = gsub('( *\n){2,}', '\n\n> ', x) paste('>', gsub(' *(\n*) *$', '\\1', x)) } quote_poem_addin = function() { ctx = rstudioapi::getSourceEditorContext() sel = ctx$selection[[1]] if (sel$text == '') { message('Please select some text in the editor first.') return() } rstudioapi::modifyRange(sel$range, quote_poem(sel$text)) }
DataStringBinary <- function(dataString, qrInfo) { .Deprecated("qr_code") if (qrInfo$mode == "0100") { tempBin <- intToBin(utf8ToInt(dataString)) tempBin <- unlist( lapply(tempBin, str_pad, width = 8, side = "left", pad = "0") ) tempBin <- paste(tempBin, collapse = "") } else if (qrInfo$mode == "0010") { map <- c(0:9, LETTERS, " ", "$", "%", "*", "+", "-", ".", "/", ":") key <- seq_along(map) - 1 alpanumericTable <- data.frame(key, map) dataStringTemp <- unlist(strsplit(dataString, split = "")) dataStringValue <- sapply( dataStringTemp, function(x) { alpanumericTable[map == x, 1] } ) index <- seq(1, nchar(dataString), 2) if (nchar(dataString) %% 2 == 0) { tempBin <- sapply( index, function(x) { str_pad( intToBin(dataStringValue[x] * 45 + dataStringValue[x + 1]), 11, side = "left", pad = "0" ) } ) } else { tempBin <- c( sapply( index[1:(length(index) - 1)], function(x) { str_pad( intToBin(dataStringValue[x] * 45 + dataStringValue[x + 1]), 11, side = "left", pad = "0" ) } ), str_pad( intToBin(dataStringValue[index[length(index)]]), 6, side = "left", pad = "0" ) ) } tempBin <- paste(tempBin, collapse = "") } charCount <- 0 if (qrInfo$Version <= 9) { charCount <- ifelse( qrInfo$mode == "0001", 10, ifelse(qrInfo$mode == "0010", 9, 8) ) } else if (qrInfo$Version >= 27) { charCount <- ifelse( qrInfo$mode == "0001", 14, ifelse(qrInfo$mode == "0010", 13, 16) ) } else { charCount <- ifelse( qrInfo$mode == "0001", 12, ifelse(qrInfo$mode == "0010", 11, 16) ) } tempBin <- paste0( qrInfo$mode, str_pad(intToBin(nchar(dataString)), charCount, side = "left", pad = "0"), tempBin, collapse = "" ) if (qrInfo$Dcword * 8 - nchar(tempBin) > 4) { tempBin <- paste0(tempBin, paste(rep("0", 4), collapse = "")) } else { tempBin <- paste0( tempBin, paste( rep("0", qrInfo$Dcword * 8 - nchar(tempBin)), collapse = "" ) ) } padCount <- 8 - nchar(tempBin) %% 8 tempBin <- paste0(tempBin, paste(rep("0", padCount), collapse = "")) padByte <- c("11101100", "00010001") byteCount <- (qrInfo$Dcword * 8 - nchar(tempBin)) / 8 if (byteCount > 0) { if (byteCount == 1) { bytearray <- suppressWarnings(cbind(1, padByte[1])) bytearray <- paste(bytearray[, 2], collapse = "") } else { bytearray <- suppressWarnings(cbind(c(1:byteCount), padByte)) bytearray <- paste(bytearray[, 2], collapse = "") } tempBin <- paste0(tempBin, bytearray, collapse = "") } index <- seq(1, nchar(tempBin), 8) dataPoly <- sapply( index, function(x) { strtoi(substr(tempBin, x, x + 7), base = 2) } ) return(dataPoly) }
.file.cnt <- 0 .prefix <- 'test' if (exists('.test.mode') && .test.mode == 'regression') { context("Regression Tests") test_that_ref <- function(prefix, desc, code) { .prefix <<- prefix .file.cnt <<- 0 test_that(desc, code) } eq_ref <- function(x) { filename <- sprintf('%s_%d.rds', .prefix, .file.cnt) .file.cnt <<- .file.cnt + 1 expect_equal_to_reference(x, filename) } } else { test_that_ref <- function(prefix, desc, code) { cat(sprintf('*** %s ***\n', desc)) code } if (exists('.test.mode') && .test.mode == 'demo') { eq_ref <- function(x) { print(x) l <- readline(prompt="Hit <RETURN> to continue, anything else to quit: ") if (nchar(l) > 0) { stop('', call.=FALSE, domain=NA) } } } else { eq_ref <- function(x) { print(x); expect_true(TRUE) } } } data(iris) if (!requireNamespace('ggplot2movies', quietly=TRUE)) { install.packages('ggplot2movies') } data(movies, package='ggplot2movies') data(Titanic) data(occupationalStatus) data(diamonds, package='ggplot2') test_that_ref("1d_density", "1D density plot", { eq_ref(plotluck(iris, Petal.Length~1)) }) test_that_ref("1d_scatter", "1D scatter num/fact", { eq_ref(plotluck(iris, Petal.Length~1, opts=plotluck.options(min.points.density=1E20))) eq_ref(plotluck(iris, Petal.Length~1, opts=plotluck.options(min.points.density=1E20, dedupe.scatter='jitter'))) }) test_that_ref("1d_bar", "1D bar", { eq_ref(plotluck(movies, mpaa~1)) }) test_that_ref("1d_scaling", "log scaling", { set.seed(0) n <- 1000 m <- 100 df <- data.frame(a=rnorm(n, mean=m, sd=5), b=c(10*m, rnorm(n-1, mean=m, sd=5)), c=m*c(-2*m, rexp(n-1, 1)), d=-m*rexp(n, 1)) eq_ref(plotluck(df, a~1)) eq_ref(plotluck(df, b~1)) eq_ref(plotluck(df, c~1)) eq_ref(plotluck(df, d~1)) }) test_that_ref("2d_scatter", "2D scatter", { eq_ref(plotluck(iris, Petal.Length~Petal.Width)) eq_ref(plotluck(movies, votes~rating)) eq_ref(plotluck(movies, rating~votes, opts=plotluck.options(min.points.hex=1E20))) eq_ref(plotluck(movies, rating~votes, opts=plotluck.options(min.points.hex=1E20, trans.log.thresh=100))) }) test_that_ref("2d_density", "2D density", { eq_ref(plotluck(movies, rating~1|mpaa)) eq_ref(plotluck(iris, Petal.Length~1|Species)) eq_ref(plotluck(iris, Petal.Length~Species, opts=plotluck.options(min.points.violin=1E20))) i2 <- iris i2$Species <- as.ordered(i2$Species) eq_ref(plotluck(i2, Petal.Length~1|Species)) eq_ref(plotluck(diamonds, price~cut)) }) test_that_ref("2d_box", "2D box/violin plot", { eq_ref(plotluck(movies, rating~mpaa)) eq_ref(plotluck(movies, rating~mpaa, opts=plotluck.options(geom='box'))) eq_ref(plotluck(movies, rating~mpaa, opts=plotluck.options(min.points.violin=1E20))) eq_ref(plotluck(movies, rating~mpaa, opts=plotluck.options(min.points.violin=1E20, dedupe.scatter='jitter'))) eq_ref(plotluck(movies, budget~Documentary)) }) test_that_ref("2d_id", "2D identity bar", { df <- data.frame(f=factor(c('aaaaaaa','bbbbbbbbb','ccccccccc','dddddddd')), val=c(5,6,2,8)) eq_ref(plotluck(df, val~f)) }) test_that_ref("2d_spine", "2D spine", { eq_ref(plotluck(as.data.frame(Titanic), Survived~Class, weights=Freq)) df <- as.data.frame(occupationalStatus) df$origin <- ordered(df$origin) df$destination <- ordered(df$destination) eq_ref(plotluck(df, destination~origin, weights=Freq)) }) test_that_ref("3d_identity", "3D identity", { df <- data.frame(f=factor(c('aaaaaaa','bbbbbbbbb','ccccccccc','dddddddd')), f2=factor(c(1,1,2,2)), val=c(5,6,2,8)) eq_ref(plotluck(df, val~f|f2)) eq_ref(plotluck(df, val~f|f2, opts=plotluck.options(max.factor.levels.color=0))) }) test_that_ref("3d_heat", "3D heat map", { eq_ref(plotluck(diamonds, price~cut+color)) }) test_that_ref("3d_spine", "3D spine", { eq_ref(plotluck(as.data.frame(Titanic), Survived~Class+Sex, weights=Freq)) }) test_that_ref("3d_scatter", "3D scatter", { eq_ref(plotluck(movies, rating~length|mpaa)) eq_ref(plotluck(movies, rating~length|mpaa, opts=plotluck.options(min.points.hex=1E20))) eq_ref(plotluck(iris, Petal.Width~Petal.Length|Species)) }) test_that_ref("3d_density", "3D density", { eq_ref(plotluck(diamonds, price~1|cut+color)) eq_ref(plotluck(diamonds, price~1|cut+color, opts=plotluck.options(min.points.density=1E20))) eq_ref(plotluck(diamonds, price~1|cut, opts=plotluck.options(max.factor.levels.color=1E20))) }) test_that_ref("3d_violin", "3D violin", { eq_ref(plotluck(movies, rating~mpaa|Action)) eq_ref(plotluck(movies, rating~mpaa|Action, opts=plotluck.options(max.factor.levels.color=0))) eq_ref(plotluck(movies, rating~mpaa|Action, opts=plotluck.options(min.points.violin=1E20))) eq_ref(plotluck(movies, rating~mpaa|Action, opts=plotluck.options(min.points.violin=1E20, dedupe.scatter='jitter'))) eq_ref(plotluck(movies, rating~mpaa|Action, opts=plotluck.options(min.points.violin=1E20, max.factor.levels.color=0))) }) test_that_ref("3d_spine", "3D spine", { eq_ref(plotluck(as.data.frame(Titanic), Survived~Class+Sex, weights=Freq)) }) test_that_ref("missing", "missing values", { set.seed(0) df<-data.frame(f=factor(sample(c(letters[1:3], NA), 20, replace=TRUE)), f2=factor(sample(c(1,2,3,NA), 20, replace=TRUE)), v=runif(20), v2=runif(20)) df$v2[c(1,5,6)] <- NA eq_ref(plotluck(df, v~f)) eq_ref(plotluck(df, v~f, opts=plotluck.options(na.rm=TRUE))) eq_ref(plotluck(df, v~f, opts=plotluck.options(min.points.violin=0))) eq_ref(plotluck(df, v~f, opts=plotluck.options(min.points.violin=0, na.rm=TRUE))) eq_ref(plotluck(df, f~v)) eq_ref(plotluck(df, v2~v|f)) eq_ref(plotluck(df, f2~f)) eq_ref(plotluck(df, f2~f, opts=plotluck.options(na.rm=TRUE))) }) test_that_ref("2d_weight", "instance weights", { set.seed(0) df<-data.frame(f=factor(sample(letters[1:3], 20, replace=TRUE), exclude=FALSE), v1=runif(20), v2=runif(20)) df$w<-runif(20) + ifelse(df$v1>0.6, 3 * runif(20), ifelse(df$v1>0.3, 2*runif(20), 0)) eq_ref(plotluck(df, v1~v2)) eq_ref(plotluck(df, v1~v2, weights=w)) eq_ref(plotluck(df, v1~f, opts=plotluck.options(geom='violin'))) eq_ref(plotluck(df, v1~f, weights=w, opts=plotluck.options(geom='violin'))) eq_ref(plotluck(df, v1~f, opts=plotluck.options(geom='box'))) eq_ref(plotluck(df, v1~f, weights=w, opts=plotluck.options(geom='box'))) eq_ref(plotluck(df, v1~1, opts=plotluck.options(min.points.density=0))) eq_ref(plotluck(df, v1~1, weights=w, opts=plotluck.options(min.points.density=0))) eq_ref(plotluck(df, v1~1, opts=plotluck.options(geom='histogram'))) eq_ref(plotluck(df, v1~1, weights=w, opts=plotluck.options(geom='histogram'))) df<-expand.grid(1:5, 1:5) df <- rbind(df, df, df) df$v <- runif(75) df$w<-runif(75) + ifelse(df$v>0.6, 10 * runif(75), ifelse(df$v>0.3, 5*runif(75), 0)) eq_ref(plotluck(df, v~Var1+Var2, opts=plotluck.options(geom='spine'))) eq_ref(plotluck(df, v~Var1+Var2, weights=w, opts=plotluck.options(geom='spine'))) }) test_that_ref("multi", "multiple plots", { if (identical(Sys.getenv("NOT_CRAN"), "true")) { eq_ref(plotluck(diamonds, .~1)) eq_ref(plotluck(diamonds, price~.)) eq_ref(plotluck(diamonds, .~price)) } })
t_choose <- function(genes,exp,group_list,up_only = FALSE,down_only = FALSE,pvalue_cutoff = 0.05){ if(up_only&down_only)stop("please change neither up_only or down_only to FALSE") genes = genes[genes %in% rownames(exp)] exp_small = exp[genes,] dat = data.frame(t(exp_small),check.names = FALSE) dat$group_list = group_list p_v <- sapply(1:(ncol(dat)-1), function(i){ stats::t.test(dat[,i] ~group_list)$p.value }) names(p_v) = colnames(dat)[-ncol(dat)] exp_genes = names(p_v[p_v < pvalue_cutoff]) if(up_only){ es_up <- sapply(1:(ncol(dat)-1), function(i){ tmp = stats::t.test(dat[,i] ~group_list) k = tmp$estimate[2]-tmp$estimate[1] >0 return(k) }) up_genes = names(p_v)[p_v < pvalue_cutoff & es_up] return(up_genes) }else if(down_only){ es_down <- sapply(1:(ncol(dat)-1), function(i){ tmp = stats::t.test(dat[,i] ~group_list) k = tmp$estimate[2]-tmp$estimate[1] <0 return(k) }) down_genes = names(p_v)[p_v <pvalue_cutoff & es_down] return(down_genes) }else{ return(exp_genes) } } cor.full <- function(x){ ss = list() p = list() ss1 = utils::combn(colnames(x),2) ss2 = apply(ss1, 2, paste,collapse =":") for(i in (1:ncol(ss1))){ bt = x[,ss1[1,i]] kt = x[,ss1[2,i]] cot = stats::cor.test(bt,kt) p[[i]] = c(cot$p.value,cot$estimate) names(p[[i]]) = c("p.value","cor") } re = do.call(cbind,p) colnames(re) = apply(ss1, 2, paste,collapse =":") return(as.data.frame(t(re))) } cor.one <- function(x,var){ if(!(var %in% colnames(x))) stop(paste0(var," is not a colname of ",x,",please check it.")) if(!all(!duplicated(colnames(x)))) stop("unique colnames is required") ss = list() p = list() ss1 = matrix(c(rep(var,times = (ncol(x)-1)), setdiff(colnames(x),var)), nrow = 2,byrow = TRUE) ss2 = setdiff(colnames(x),var) for(i in (1:ncol(ss1))){ bt = x[,ss1[1,i]] kt = x[,ss1[2,i]] cot = stats::cor.test(bt,kt) p[[i]] = c(cot$p.value,cot$estimate) names(p[[i]]) = c("p.value","cor") } re = do.call(cbind,p) colnames(re) = ss2 return(as.data.frame(t(re))) }
result.extract.mask <- function(mask.grid, values){ germany.mask <- which(is.na(mask.grid$alt)==FALSE) values.id.to.substitute <- germany.mask[which(is.na(values[germany.mask])==TRUE)] values[values.id.to.substitute] <- rep(-9999, length(values[values.id.to.substitute])) return(values) }
read_survey <- function(file_name, strip_html = TRUE, import_id = FALSE, time_zone = NULL, legacy = FALSE, add_column_map = TRUE, add_var_labels = TRUE, col_types = NULL) { if (import_id & legacy) { rlang::warn(c("Using import IDs as column names is not supported for legacy response files.", "Defaulting to user-defined variable names", "Set import_id = FALSE in future.")) import_id = FALSE } assert_surveyFile_exists(file_name) if(is.null(time_zone)){ time_zone <- "UTC" } if(legacy){ header_rows <- 1 } else { header_rows <- 1:2 } rawdata <- suppressMessages( readr::read_csv( file = file_name, col_types = readr::cols(.default = readr::col_character()), na = c("") )) if (grepl(",$", readLines(file_name, n = 1))) { rawdata <- rawdata[, 1:(ncol(rawdata) - 1)] } responsedata <- dplyr::slice(rawdata, -header_rows) responsedata <- readr::type_convert( responsedata, locale = readr::locale(tz = time_zone), col_types = col_types, na = character() ) colmapdata <- dplyr::slice(rawdata, header_rows) if(!legacy){ colmapdata <- dplyr::mutate(colmapdata, metadata_type = c("description", "JSON")) col_map <- tidyr::pivot_longer(colmapdata, -metadata_type, names_to = "qname") col_map <- tidyr::pivot_wider(col_map, names_from = "metadata_type", values_from = "value") col_map <- dplyr::mutate(col_map, purrr::map_dfr(JSON, jsonlite::fromJSON), .keep = "unused") if(!assertthat::has_name(col_map, "choiceId")){ col_map$choiceId <- NA } } else { col_map <- pivot_longer(colmapdata, tidyr::everything(), names_to = "qname", values_to = "description") } if (strip_html) { col_map$description <- remove_html(col_map$description) } col_map <- dplyr::mutate(col_map, tibble::as_tibble( stringr::str_split_fixed(description, "\\s-\\s", n = 2), .name_repair = ~c("main", "sub") ), .after = description ) if (import_id) { qid_names <- tidyr::unite(col_map, col = qidnames, c(ImportId, choiceId), sep = "_", na.rm = TRUE)[["qidnames"]] names(responsedata) <- qid_names col_map$qname <- qid_names } if(add_var_labels){ responsedata <- sjlabelled::set_label(responsedata, col_map$description) } if(add_column_map){ attr(responsedata, "column_map") <- col_map } return(responsedata) }
importSBML <- function(filename, times, meas_input) { if (!base::require('rsbml', character.only = TRUE)) { message('Please install rsbml from the Bioconducture repository') stop('Bioconductor package rsbml not found.') } else { requireNamespace("rsbml") model <- rsbml::rsbml_read(filename = filename, dom = TRUE) if (missing(meas_input)) { warning("No measurements given. Returned model can't directly be used with the algorithms. Use method 'setMeas' for adding them to the model.") } states <- model@model@species parameter <- model@model@parameters rules <- model@model@rules reactions <- model@model@reactions reacList <- list() for (i in 1:length(reactions)) { reacList[[i]] <- gsub(pattern = "expression", replacement = '', deparse(model@model@reactions[[i]]@kineticLaw@math, width.cutoff = 300)) } stoichM <- rsbml::stoichiometryMatrix(object = model@model) react <- c() combieReact <- function(reactStrs, stMatrix) { for (i in 1:nrow(stMatrix)) { m <- which(stMatrix[i,] != 0) if (length(m) > 0) { react <- c(react, paste0(stMatrix[i, m], '*', reactStrs[m], collapse = ' + ')) } } return(react) } react <- combieReact(reacList, stoichM) meas <- c() if (length(rules) != 0) { for (i in 1:length(rules)) { meas[i] <- gsub(pattern = "expression", replacement = '', x = rules[[i]]@math) } } reformatEqs <- function(reactions, states, measureRules) { xStates <- paste('x', 1:length(states), sep = '') for (i in 1:length(states)) { regState <- paste0('\\b', states[i], '\\b') reactions = unlist(lapply(X = reactions, FUN = function(x) gsub(pattern = regState, replacement = xStates[i], x = x))) if (length(measureRules) != 0) { measureRules = unlist(lapply(X = measureRules, FUN = function(x) gsub(pattern = regState, replacement = xStates[i], x = x))) } else { measureRules = paste0('x', 1:length(reactions)) warning('No measurement function found. Set it yourself. Model will use the identity of every state.') } } res = list('reac' = reactions, 'meas' = measureRules) return(res) } reactNames = rownames(stoichM[rowSums(abs(stoichM)) != 0,]) eqList <- reformatEqs(reactions = react, states = reactNames, measureRules = meas) eqFuncList = writeDummy(eqList) if (length(parameter) != 0) { v <- c() n <- c() for (i in 1:length(parameter)) { v[i] <- parameter[[i]]@value n[i] <- parameter[[i]]@name } namedParaVec <- v names(namedParaVec) <- tolower(n) } initToPara <- function(model, namedParaV) { const <- c() for (i in 1:length(model@model@species)) { const[i] = model@model@species[[i]]@constant } constSpec <- model@model@species[[which(const, TRUE)]] nV <- c() namesV <- c() for (i in 1:length(constSpec)) { nV[i] = constSpec@initialAmount namesV[i] = constSpec@id } names(nV) <- tolower(namesV) namedParaV = c(namedParaV, nV) return(namedParaV) } if (length(parameter) != 0) { namedParaVec = initToPara(model, namedParaVec) } else { reactionsList <- model@model@reactions reaction_anno <- c() for (i in 1:length(reactionsList)) { reaction <- reactionsList[[i]] parametersList <- reaction@kineticLaw@parameters values_vec <- c() names_vec <- c() for (j in 1:length(parametersList)) { values_vec[j] = parametersList[[j]]@value names_vec[j] = parametersList[[j]]@id } names(values_vec) <- names_vec reaction_anno <- append(reaction_anno, values_vec) } parameters_vec <- reaction_anno[order(names(reaction_anno))] namedParaVec <- parameters_vec[!duplicated(names(parameters_vec))] constants <- model@model@species const_idx <- which(rowSums(abs(stoichM)) == 0) vec <- c() names <- c() for (i in 1:length(const_idx)) { names[i] = tolower(constants[[const_idx[i]]]@id) vec[i] = constants[[const_idx[i]]]@initialAmount } names(vec) <- names namedParaVec <- append(namedParaVec,vec) } initVec <- model@model@species if (length(initVec) != 0) { v <- c() n <- c() for (i in 1:length(initVec)) { v[i] <- initVec[[i]]@initialAmount } initState <- v initState = initState[rowSums(abs(stoichM)) != 0] } if (missing(meas_input)) { model <- odeModel(func = eqFuncList$reac, parms = namedParaVec, measFunc = eqFuncList$meas, y = initState, times = times) } else { model <- odeModel(func = eqFuncList$reac, parms = namedParaVec, measFunc = eqFuncList$meas, y = initState, times = times, meas = meas_input) } } unloadNamespace('rsbml') return(model) }
broyden <- function(Ffun, x0, J0 = NULL, ..., maxiter = 100, tol = .Machine$double.eps^(1/2)) { if (!is.numeric(x0)) stop("Argument 'x0' must be a numeric (row or column) vector.") fun <- match.fun(Ffun) F <- function(x) fun(x, ...) y0 <- F(x0) if (length(x0) != length(y0)) stop("Function 'F' must be 'square', i.e. from R^n to R^n .") if (length(x0) == 1) stop("Function 'F' must not be a univariate function.") if (is.null(J0)) { A0 <- jacobian(F, x0) } else { A0 <- J0 } B0 <- inv(A0) if (any(is.infinite(B0))) B0 <- diag(length(x0)) xnew <- x0 - B0 %*% y0 ynew <- F(xnew) k <- 1 while (k < maxiter) { s <- xnew - x0 d <- ynew - y0 if (norm(s, "F") < tol || norm(as.matrix(ynew), "F") < tol) break B0 <- B0 + (s - B0 %*% d) %*% t(s) %*% B0 / c(t(s) %*% B0 %*% d) x0 <- xnew xnew <- xnew - B0 %*% ynew y0 <- ynew ynew <- F(xnew) k <- k + 1 } if (k >= maxiter) warning(paste("Not converged: Max number of iterations reached.")) fnew <- sqrt(sum(ynew^2)) return(list(zero = c(xnew), fnorm = fnew, niter = k)) }
tcplRun <- function(asid = NULL, slvl, elvl, id = NULL, type = "mc", mc.cores = NULL, outfile = NULL, runname = NULL) { owarn <- getOption("warn") options(warn = 1) on.exit(options(warn = owarn)) user <- paste(Sys.info()[c("login", "user", "effective_user")], collapse = ".") stime <- Sys.time() if (Sys.info()["sysname"] == "Windows") mc.cores <- 1 if (length(slvl) > 1 | !is.numeric(slvl)) { stop("Invalid slvl - must be integer of length 1.") } if (is.null(elvl) | elvl < slvl) elvl <- slvl if (length(elvl) > 1 | !is.numeric(elvl)) { stop("Invalid elvl - must be integer of length 1.") } if (length(type) > 1 | !type %in% c("mc", "sc")) { stop ("Invalid 'type' value.") } if (!is.null(asid)) id <- tcplLoadAcid("asid", asid)$acid if (length(id) == 0) stop("No asid or id given.") id <- unique(id) if (!is.null(outfile)) { cat("Writing output to:", outfile, "\n") logcon <- file(outfile, open = "a") sink(logcon, append = TRUE) sink(logcon, append = TRUE, type="message") on.exit(sink.reset(), add = TRUE) on.exit(close.connection(logcon), add = TRUE) on.exit(cat("Output appended to log file:", outfile, "\n"), add = TRUE) cat("\n\n\n") cat("RUNDATE -- ", format(stime, "%y%m%d; %H:%M"), "\n", "USER -- ", user, "\n", "TYPE -- ", type, "\n", "LEVEL ", slvl, " TO ", "LEVEL ", elvl, "\n", "RUN -- ", runname, "\n", sep = "") cat("\n\n") } if (is.null(mc.cores)) { ncores <- min(length(id), detectCores() - 1) } else { ncores <- mc.cores } names(id) <- paste0("ACID", id) res <- list() if (type == "mc") { if (slvl <= 1L) { res$l1 <- .multProc(id = id, lvl = 1L, type = "mc", ncores = ncores) res$l1_failed <- names(which(res$l1 != TRUE)) id <- id[which(res$l1[names(id)] == TRUE)] if (length(id) == 0) { warning("Pipeline stopped early at level 1; processing errors ", "occured with all given acids by level 1.") ttime <- round(difftime(Sys.time(), stime, units = "min"), 2) ttime <- paste(unclass(ttime), units(ttime)) cat("\n\nTotal processing time:", ttime, "\n\n") return(res) } if (length(res$l1_failed) > 0) { warning(length(res$l1_failed), " ids failed at level 1.") } } if (elvl <= 1L) { ttime <- round(difftime(Sys.time(), stime, units = "min"), 2) ttime <- paste(unclass(ttime), units(ttime)) cat("\n\nTotal processing time:", ttime, "\n\n") return(res) } if (slvl <= 2L) { res$l2 <- .multProc(id = id, lvl = 2L, type = "mc", ncores = ncores) res$l2_failed <- names(which(res$l2 != TRUE)) id <- id[which(res$l2[names(id)] == TRUE)] if (length(id) == 0) { warning("Pipeline stopped early at level 2; processing errors ", "occured with all given acids by level 2.") ttime <- round(difftime(Sys.time(), stime, units = "min"), 2) ttime <- paste(unclass(ttime), units(ttime)) cat("\n\nTotal processing time:", ttime, "\n\n") return(res) } if (length(res$l2_failed) > 0) { warning(length(res$l2_failed), " ids failed at level 2.") } } if (elvl == 2L) { ttime <- round(difftime(Sys.time(), stime, units = "min"), 2) ttime <- paste(unclass(ttime), units(ttime)) cat("\n\nTotal processing time:", ttime, "\n\n") return(res) } if (slvl <= 3L) { res$l3 <- .multProc(id = id, lvl = 3L, type = "mc", ncores = ncores) res$l3_failed <- names(which(res$l3 != TRUE)) id <- id[which(res$l3[names(id)] == TRUE)] if (length(id) == 0) { warning("Pipeline stopped early at level 3; processing errors ", "occured with all given acids by level 3.") ttime <- round(difftime(Sys.time(), stime, units = "min"), 2) ttime <- paste(unclass(ttime), units(ttime)) cat("\n\nTotal processing time:", ttime, "\n\n") return(res) } if (length(res$l3_failed) > 0) { warning(length(res$l3_failed), " ids failed at level 3.") } } if (elvl == 3L) { ttime <- round(difftime(Sys.time(), stime, units = "min"), 2) ttime <- paste(unclass(ttime), units(ttime)) cat("\n\nTotal processing time:", ttime, "\n\n") return(res) } if (slvl < 4L | !is.null(asid)) id <- tcplLoadAeid("acid", id)$aeid names(id) <- paste0("AEID", id) if (is.null(mc.cores)) ncores <- min(length(id), detectCores() - 1) if (slvl <= 4L) { res$l4 <- .multProc(id = id, lvl = 4L, type = "mc", ncores = ncores) res$l4_failed <- names(which(res$l4 != TRUE)) id <- id[which(res$l4[names(id)] == TRUE)] if (length(id) == 0) { warning("Pipeline stopped early at level 4; processing errors ", "occured with all given acids by level 4.") ttime <- round(difftime(Sys.time(), stime, units = "min"), 2) ttime <- paste(unclass(ttime), units(ttime)) cat("\n\nTotal processing time:", ttime, "\n\n") return(res) } if (length(res$l4_failed) > 0) { warning(length(res$l4_failed), " ids failed at level 4.") } } if (elvl == 4L) { ttime <- round(difftime(Sys.time(), stime, units = "min"), 2) ttime <- paste(unclass(ttime), units(ttime)) cat("\n\nTotal processing time:", ttime, "\n\n") return(res) } if (slvl <= 5L) { res$l5 <- .multProc(id = id, lvl = 5L, type = "mc", ncores = ncores) res$l5_failed <- names(which(res$l5 != TRUE)) id <- id[which(res$l5[names(id)] == TRUE)] if (length(id) == 0) { warning("Pipeline stopped early at level 5; processing errors ", "occured with all given acids by level 5.") ttime <- round(difftime(Sys.time(), stime, units = "min"), 2) ttime <- paste(unclass(ttime), units(ttime)) cat("\n\nTotal processing time:", ttime, "\n\n") return(res) } if (length(res$l5_failed) > 0) { warning(length(res$l5_failed), " ids failed at level 5.") } } if (elvl == 5L) { ttime <- round(difftime(Sys.time(), stime, units = "min"), 2) ttime <- paste(unclass(ttime), units(ttime)) cat("\n\nTotal processing time:", ttime, "\n\n") return(res) } if (slvl <= 6L) { res$l6 <- .multProc(id = id, lvl = 6L, type = "mc", ncores = ncores) res$l6_failed <- names(which(res$l6 != TRUE)) id <- id[which(res$l6[names(id)] == TRUE)] if (length(id) == 0) { warning("Pipeline stopped early at level 6; processing errors ", "occured with all given acids by level 6.") ttime <- round(difftime(Sys.time(), stime, units = "min"), 2) ttime <- paste(unclass(ttime), units(ttime)) cat("\n\nTotal processing time:", ttime, "\n\n") return(res) } if (length(res$l6_failed) > 0) { warning(length(res$l6_failed), " ids failed at level 6.") } } if (elvl == 6L) { ttime <- round(difftime(Sys.time(), stime, units = "min"), 2) ttime <- paste(unclass(ttime), units(ttime)) cat("\n\nTotal processing time:", ttime, "\n\n") return(res) } ttime <- round(difftime(Sys.time(), stime, units = "min"), 2) ttime <- paste(unclass(ttime), units(ttime)) cat("\n\nTotal processing time:", ttime, "\n\n") return(res) } if (type == "sc") { if (slvl <= 1L) { res$l1 <- .multProc(id = id, lvl = 1L, type = "sc", ncores = ncores) res$l1_failed <- names(which(res$l1 != TRUE)) id <- id[which(res$l1[names(id)] == TRUE)] if (length(id) == 0) { warning("Pipeline stopped early at level 1; processing errors ", "occured with all given acids by level 1.") ttime <- round(difftime(Sys.time(), stime, units = "min"), 2) ttime <- paste(unclass(ttime), units(ttime)) cat("\n\nTotal processing time:", ttime, "\n\n") return(res) } if (length(res$l1_failed) > 0) { warning(length(res$l1_failed), " ids failed at level 1.") } } if (elvl <= 1L) { ttime <- round(difftime(Sys.time(), stime, units = "min"), 2) ttime <- paste(unclass(ttime), units(ttime)) cat("\n\nTotal processing time:", ttime, "\n\n") return(res) } if (slvl < 2L | !is.null(asid)) id <- tcplLoadAeid("acid", id)$aeid names(id) <- paste0("AEID", id) if (is.null(mc.cores)) ncores <- min(length(id), detectCores() - 1) if (slvl <= 2L) { res$l2 <- .multProc(id = id, lvl = 2L, type = "sc", ncores = ncores) res$l2_failed <- names(which(res$l2 != TRUE)) id <- id[which(res$l2[names(id)] == TRUE)] if (length(id) == 0) { warning("Pipeline stopped early at level 2; processing errors ", "occured with all given acids by level 2.") ttime <- round(difftime(Sys.time(), stime, units = "min"), 2) ttime <- paste(unclass(ttime), units(ttime)) cat("\n\nTotal processing time:", ttime, "\n\n") return(res) } if (length(res$l2_failed) > 0) { warning(length(res$l2_failed), " ids failed at level 2.") } } if (elvl == 2L) { ttime <- round(difftime(Sys.time(), stime, units = "min"), 2) ttime <- paste(unclass(ttime), units(ttime)) cat("\n\nTotal processing time:", ttime, "\n\n") return(res) } ttime <- round(difftime(Sys.time(), stime, units = "min"), 2) ttime <- paste(unclass(ttime), units(ttime)) cat("\n\nTotal processing time:", ttime, "\n\n") return(res) } }
.construct_s <- function(spikes, ids, time_interval, beg, end, corr_breaks, layout, filename) { spikes_range <- range(unlist(spikes)) if (is.null(end)) { end <- spikes_range[2] } else { spikes <- lapply(spikes, function(x, max) { x_high <- which(x > max) if (any(x_high)) x[1:x_high[1] - 1] else x }, max = end) } if (is.null(beg)) { beg <- spikes_range[1] } else { spikes <- lapply(spikes, function(x, min) { x_low <- which(x < min) if (any(x_low)) x <- x[- x_low] x }, min = beg) } empty_index <- which(sapply(spikes, length) == 0) if (any(empty_index)) { spikes <- spikes[- empty_index] } if (!is.null(ids)) { spikes <- .filter_channel_names(spikes, ids) } channels <- names(spikes) keep <- match(channels, rownames(layout$pos)) layout$pos <- layout$pos[keep, ] rec_time <- c(beg, end) nspikes <- sapply(spikes, length) if (length(nspikes) == 0) { meanfiringrate <- nspikes } else { meanfiringrate <- nspikes / (end - beg) } rates <- .make_spikes_to_frate(spikes, time_interval = time_interval, beg = beg, end = end) unit_offsets <- NULL .check_spikes_monotonic(spikes) res <- list(channels = names(spikes), spikes = spikes, nspikes = nspikes, NCells = length(spikes), meanfiringrate = meanfiringrate, file = filename, layout = layout, rates = rates, unit_offsets = unit_offsets, rec_time = rec_time) class(res) <- "spike.list" if (length(corr_breaks) == 1) { res$corr <- NULL } else { res$corr <- .corr_index(res, corr_breaks) } res } calculate_isis <- function(s) { s$isis <- lapply(s$spikes, diff) s$mean_isis <- lapply(s$isis, mean) s$sd_isis <- lapply(s$isis, sd) return(s) } .plot_isis_by_plate <- function(s) { isis_all <- unlist(s$isis) hist(isis_all, main = "Histogram of ISIs by Plate", xlab = "ISI length") hist(log10(isis_all), main = "Histogram of log(ISIs) by Plate", xlab = "log10(ISI length)") } .spike_summary_by_electrode <- function(s) { s <- calculate_isis(s) electrodes <- .get_all_electrodes(s) sum <- matrix(data = NA, nrow = length(electrodes), ncol = 4) colnames(sum) <- c("nspikes", "meanfiringrate", "meanisis", "sdisis") rownames(sum) <- electrodes df <- cbind(s$nspikes, s$meanfiringrate, s$mean_isis, s$sd_isis) active_electrodes <- rownames(df) for (i in active_electrodes) { sum[i, ] <- unlist(df[i, ]) } sum } .spike_summary_by_well <- function(s) { plate <- get_plateinfo(s$layout$array) wells <- sort(plate$wells) s$isis <- lapply(s$spikes, diff) start_pos <- 1 sum <- matrix(data = NA, nrow = length(wells), ncol = start_pos + 11) colnames(sum) <- c("treatment", "nae", "nspikes_by_well", "meanfiringrate_by_well", "meanfiringrate_by_all_electrodes", "meanfiringrate_by_active_electordes", "sdfiringrate_by_active_electordes", "meanisis", "sdisis","mutual_info","entropy","STTC") rownames(sum) <- wells nelectrodes <- plate$n_elec_r * plate$n_elec_c if (!is.null(s$goodwells)) { for (j in 1:length(s$goodwells)) { icurrentwell <- (s$goodwells[j] == s$cw) incurrentwell <- which(icurrentwell) treatment <- s$treatment[s$goodwells[j]] if (length(incurrentwell) > 0) { well <- strsplit(s$channels[incurrentwell], "_")[[1]][1] treatment <- s$treatment[well][[1]] } sum[s$goodwells[j], start_pos] <- treatment sum[s$goodwells[j], start_pos + 1] <- length(incurrentwell) sum[s$goodwells[j], start_pos + 2] <- sum(s$nspikes[icurrentwell]) sum[s$goodwells[j], start_pos + 3] <- sum(s$meanfiringrate[icurrentwell]) sum[s$goodwells[j], start_pos + 4] <- sum(s$meanfiringrate[icurrentwell]) / nelectrodes sum[s$goodwells[j], start_pos + 5] <- mean(s$meanfiringrate[icurrentwell]) sum[s$goodwells[j], start_pos + 6] <- sd(s$meanfiringrate[icurrentwell]) isis_all <- unlist(s$isis[icurrentwell]) sum[s$goodwells[j], start_pos + 7] <- mean(isis_all) sum[s$goodwells[j], start_pos + 8] <- sd(isis_all) sum[s$goodwells[j], start_pos + 9] <- Reduce(c,s$mutual_inf)[well] sum[s$goodwells[j], start_pos + 10] <- Reduce(c,s$entropy)[well] sum[s$goodwells[j], start_pos + 11] <- unlist(s$mean_sttc)[well] } } sum } .get_div <- function(s) { div <- NA if(length(s$div>0)){ div<-s$div } else { t1 <- strsplit(s$file, split = "_", fixed = TRUE) for (i in t1[[1]]) { i <- toupper(i) if (nchar(i) > 2 && substr(i, 1, 3) == "DIV") { if (nchar(i) > 5) { i <- unlist(strsplit(i, split = ".", fixed = T))[1] } div <- as.numeric(substr(i, 4, nchar(i))) } } } if (is.na(div)){ div <- 1} div } compute_mean_firingrate_by_well <- function(s) { df1 <- aggregate(s$meanfiringrate, by = list(s$cw), FUN = mean, na.rm = T) df2 <- aggregate(s$meanfiringrate, by = list(s$cw), FUN = sum, na.rm = T) df <- cbind(df1, df2[, 2], .get_div(s)) names(df) <- c("well", "meanfiringrate", "meanfiringrate_per_well", "div") rownames(df) <- t(df["well"]) df } .plot_isis_by_electrode <- function(s) { wells <- unique(s$cw) if (length(wells) > 0) { for (well in wells) { active_electrodes <- which(s$cw == well & as.vector(unlist(lapply(s$isis, length))) > 0) if (length(active_electrodes) > 0) { df <- list() for (i in 1:length(active_electrodes)) { df[[i]] <- cbind(s$isis[[active_electrodes[i]]], names(s$isis)[active_electrodes[i]]) } df <- do.call("rbind", df) colnames(df) <- c("isis", "electrode") plateinfo <- get_plateinfo(s$layout$array) d1 <- expand.grid(col = 1:plateinfo$n_elec_c, row = 1:plateinfo$n_elec_r) all_electrodes <- sort(paste(well, "_", d1[, "row"], d1[, "col"], sep = "")) layout_electrodes <- c(plateinfo$n_elec_r, plateinfo$n_elec_c) df <- data.frame(df) df$isis <- as.numeric(as.vector(df$isis)) df$electrode <- as.character(as.vector(df$electrode)) p1 <- histogram(~ isis | factor(electrode, levels = all_electrodes), data = df, breaks = 10, main = paste("ISIs histogram plot for ", well, sep = ""), layout = layout_electrodes, drop.unused.levels = FALSE) print(p1) p2 <- histogram(~ log(isis) | factor(electrode, levels = all_electrodes), data = df, breaks = 10, main = paste("log(ISIs) histogram plot for ", well, sep = ""), layout = layout_electrodes, drop.unused.levels = FALSE) print(p2) } } p2 } } .plot_mean_firingrate_by_electrode <- function(s) { wells <- unique(s$cw) if (length(wells) > 0) { for (well in wells) { active_electrodes <- which(s$cw == well) df <- list() for (i in active_electrodes) { df[[i]] <- cbind(s$rates$times, s$rates$rates[, i], names(s$nspikes)[i]) } df <- do.call("rbind", df) maxy <- max(df[, 2]) colnames(df) <- c("time", "meanfiringrate", "electrode") plateinfo <- get_plateinfo(s$layout$array) if (any(grep("^Axion", s$layout$array))) { d1 <- expand.grid(col = 1:plateinfo$n_elec_c, row = 1:plateinfo$n_elec_r) all_electrodes <- sort(paste(well, "_", d1[, "row"], d1[, "col"], sep = "")) layout_electrodes <- c(plateinfo$n_elec_r, plateinfo$n_elec_c) } else { all_electrodes <- as.factor(names(s$spikes)[active_electrodes]) layout_electrodes <- c(0, length(all_electrodes)) } df <- data.frame(df) p1 <- xyplot(meanfiringrate ~ time | factor(electrode, levels = all_electrodes), data = df, main = paste("Mean Firing Rate per Second for Well ", well, ". Maximum firing rate:", maxy, " Hz", sep = ""), layout = layout_electrodes, type = "h", scales = list( x = list(draw = FALSE), y = list(draw = FALSE)), drop.unused.levels = FALSE) print(p1) } p1 } } plot_mean_firingrate_by_eletrode_by_div <- function(s) { electrode_stats <- lapply(s, function(d) { cbind(d$meanfiringrate, d$cw, .get_div(d)) }) electrode_stats_all <- do.call("rbind", electrode_stats) electrode_names <- row.names(electrode_stats_all) electrode_stats_all <- suppressWarnings(data.frame(cbind(electrode_names, electrode_stats_all[, 1:3]))) names(electrode_stats_all) <- c("electrode", "meanfiringrate", "well", "div") electrode_stats_all$div <- as.numeric(as.vector(electrode_stats_all$div)) electrode_stats_all$meanfiringrate <- as.numeric( as.vector(electrode_stats_all$meanfiringrate)) electrode_stats_all$electrode <- as.character( as.vector(electrode_stats_all$electrode)) wells <- unique(electrode_stats_all$well) if (length(wells) > 0) { for (active_well in wells) { df <- electrode_stats_all[which(electrode_stats_all$well == active_well), ] layout_info <- .get_electrode_layout(s[[1]], active_well) maxy <- max(df$meanfiringrate) p1 <- xyplot(meanfiringrate ~ div | factor(electrode, levels = layout_info$electrodes), data = df, main = paste("Mean Firing Rate across DIV's for ", active_well, ". Maximum firing rate:", round(maxy, 2), " Hz", sep = ""), layout = layout_info$layout, drop.unused.levels = FALSE) print(p1) } } } plot_mean_firingrate_by_well_by_div <- function(s) { well_stats <- lapply(s, function(d) { d$well_stats }) well_stats_all <- do.call("rbind", well_stats) plateinfo <- get_plateinfo(s[[1]]$layout$array) wells <- plateinfo$wells names(wells) <- wells wells_layout <- plateinfo$layout p1 <- xyplot(meanfiringrate ~ div | factor(well, levels = wells), data = well_stats_all, main = "Mean Firing Rate across DIV's (Hz/electrode)", layout = wells_layout, drop.unused.levels = FALSE) print(p1) p2 <- xyplot(meanfiringrate_per_well ~ div | factor(well, levels = wells), data = well_stats_all, main = "Mean Firing Rate across DIV's (Hz/well)", layout = wells_layout, drop.unused.levels = FALSE) print(p2) } plot_plate_summary_for_spikes <- function(s, outputdir) { for (i in 1:length(s)) { basename <- get_file_basename(s[[i]]$file) spike_plot_path <- paste(outputdir, "/", basename, "_spike_plot.pdf", sep = "") pdf(file = spike_plot_path) p <- .plot_mealayout(s[[i]]$layout, use_names = T, cex = 0.48) title(main = paste(paste("Electrode Layout"), paste("file= ", strsplit(basename(s[[i]]$file), ".RData")[[1]][1], sep = ""), sep = "\n")) p <- .plot_meanfiringrate(s[[i]], main = "Mean Firing Rate by Plate (Hz)") p <- .plot_isis_by_plate(s[[i]]) p <- .channel_plot_by_well(s[[i]], resp = "meanfiringrate", resp_label = "Mean Firing Rate (Hz)") p <- .plot_mean_firingrate_by_electrode(s[[i]]) p <- .plot_isis_by_electrode(s[[i]]) dev.off() } } write_plate_summary_for_spikes <- function(s, outputdir) { csvwell <- paste(outputdir, "/", get_project_plate_name(s[[1]]$file), "_well_spikes.csv", sep = "") for (i in 1:length(s)) { div <- .get_div(s[[i]]) basename <- get_file_basename(s[[i]]$file) csvfile <- paste(outputdir, "/", basename, "_spikes.csv", sep = "") df <- .spike_summary_by_electrode(s[[i]]) df2 <- .spike_summary_by_well(s[[i]]) write.table(paste("recording time (s): [", paste(s[[i]]$rec_time[1], round(s[[i]]$rec_time[2]), sep = " ,"), "]", sep = ""), csvfile, sep = ",", append = FALSE, row.names = FALSE, col.names = FALSE) write.table(" ", csvfile, sep = ",", append = TRUE, row.names = FALSE, col.names = FALSE) write.table("Spike statistics for wells", csvfile, sep = ",", append = TRUE, row.names = FALSE, col.names = FALSE) df2 <- cbind(rownames(df2), df2) suppressWarnings(write.table(df2, csvfile, sep = ",", append = TRUE, row.names = FALSE, col.names = TRUE)) suppressWarnings(write.table(cbind(df2, div), csvwell, sep = ",", append = TRUE, row.names = FALSE, col.names = FALSE)) write.table(" ", csvfile, sep = ",", append = TRUE, row.names = FALSE, col.names = FALSE) write.table("Spike statistics for electrodes", csvfile, sep = ",", append = TRUE, row.names = FALSE, col.names = FALSE) df <- cbind(rownames(df), df) colnames(df)[1] <- "electrode" suppressWarnings(write.table(df, csvfile, sep = ",", append = TRUE, row.names = FALSE, col.names = TRUE)) } } .check_spikes_monotonic <- function(spikes) { results <- sapply(spikes, function(x) { any(diff(x) < 0) }) if (any(results)) { stop(paste("Spikes are not ordered in increasing time", paste(which(results), collapse = " "), "\n")) } } .make_spikes_to_frate <- function(spikes, time_interval=1, frate_min=0, frate_max=20, clip=FALSE, beg=NULL, end=NULL ) { nspikes <- lapply(spikes, length) nelectrodes <- length(nspikes) spikes_range <- range(unlist(spikes)) if (is.null(beg)) beg <- spikes_range[1] if (is.null(end)) end <- spikes_range[2] time_breaks <- seq(from = beg, to = end, by = time_interval) if (time_breaks[length(time_breaks)] <= end) { time_breaks <- c(time_breaks, time_breaks[length(time_breaks)] + time_interval) } nbins <- length(time_breaks) - 1 rates = frate_counts(spikes, time_breaks[1], time_breaks[nbins], time_interval, nbins) if (nelectrodes > 0) { if (clip) rates <- pmin(pmax(rates, frate_min), frate_max) av_rate <- apply(rates, 1, mean) } else { av_rate <- rep(NA, nbins) } res <- list(rates = rates, times = time_breaks[- length(time_breaks)], av_rate = av_rate, time_interval = time_interval) res } .plot_meanfiringrate <- function(s, beg, end, main=NULL, lwd=0.2, ...) { if (missing(beg)) beg <- s$rates$times[1] if (missing(end)) end <- s$rates$times[length(s$rates$times)] if (is.null(main)) main <- basename(s$file) plot(s$rates$times, s$rates$av_rate, type = "h", xlab = "time (s)", xlim = c(beg, end), bty = "n", lwd = lwd, ylab = "mean firing rate (Hz)", main = main, ...) } .plot_mealayout <- function(x, use_names=TRUE, ...) { plateinfo = get_plateinfo(x$array) rows <- plateinfo$n_well_r columns <- plateinfo$n_well_c row_names <- chartr("123456789", "ABCDEFGHI", 1:rows) pos <- x$pos electrodes_only <- sub('^[^_]+_', '', rownames(x$pos)) p<-plot(NA, xaxs="i", asp=1, xlim = x$xlim, ylim = x$ylim, bty = "n", xlab = "Plate layout", ylab = "", type = "n",xaxt="n",yaxt="n",cex.lab=1.4) if (use_names) text(pos[, 1], pos[, 2], electrodes_only, ...) else text(pos[, 1], pos[, 2], ...) axis(3,at=seq( x$xlim[1]+x$xlim[2]/(columns*4), x$xlim[2]-x$xlim[2]/(columns*1.5),length.out = columns),labels=c(1:columns),cex.axis=1.4,line=-2,tick = F) axis(2,at=seq( x$ylim[2]-x$ylim[2]/(rows*1.5), x$ylim[1]+x$ylim[2]/(rows*3),length.out = rows),labels=chartr("123456789", "ABCDEFGHI", 1:rows),las=1,cex.axis=1.4,tick = F) if (any(grep('^Axion', x$array))) { abline(h=seq( max(x$pos[,"y"])+200, x$ylim[1]-200,length.out = rows+1), v=seq( x$xlim[2]-100, x$xlim[1]-100,length.out = columns+1), col=c("grey")) } } .summary_spike_list <- function(object, ...) { cat(paste("Spike data:", object$file, "\n")) cat(paste("NCells", object$NCells, "\n")) cat(sprintf("Time (s) [%.3f %.3f]\n", object$rec_time[1], object$rec_time[2])) } .print_spike_list <- function(x) { cat("MEA spikes\n") cat(basename(x$file), "\n") cat("nchannels ", x$NCells, "\n") } isi <- function(train) { isi <- NA if (length(train) > 1) { isi <- diff(train) } isi } .spike_simulation <- function(s1, elec_min_rate= (1 / 60), elec_max_rate=25, well_min_rate=15) { dt <- 1 current_electrode_rate <- s1$meanfiringrate rec_start <- s1$rec_time[1] rec_end <- s1$rec_time[2] spikes <- list() for (electrode in 1:length(s1$spikes)) { rate <- current_electrode_rate[electrode] * dt / 1000.0 timepoints <- seq(rec_start, rec_end, by = 0.001) spikes[[electrode]] <- timepoints[which(rate > runif(length(timepoints)))] } names(spikes) <- names(s1$spikes) temp_s <- .construct_s(spikes, NULL, time_interval = 1, beg = NULL, end = NULL, corr_breaks = 0, s1$layout, filename = s1$file) low <- which(temp_s$meanfiringrate < elec_min_rate) high <- which(temp_s$meanfiringrate > elec_max_rate) extremes <- c(low, high) bad_ids <- names(extremes) bad_ids <- c("-", bad_ids) s2 <- remove_spikes(temp_s, bad_ids) s2$treatment <- s1$treatment s2$size <- s1$size s2$units <- s1$units s2$dose <- s1$dose s2$well <- s1$well s2 <- get_num_ae(s2) low <- which(s2$nae < well_min_rate) bad_wells <- names(low) bad_wells <- c("-", bad_wells) s <- remove_spikes(s2, bad_wells) s$goodwells <- names(which(s2$nae >= well_min_rate)) s$treatment <- s1$treatment names(s$treatment) <- s1$well s$size <- s1$size names(s$size) <- s1$well s$units <- s1$units names(s$units) <- s1$well s$dose <- s1$dose names(s$dose) <- s1$well s$well <- s1$well s <- get_num_ae(s) s$timepoint <- s1$timepoint if (s$nspikes[1] > 0) { s$allb <- lapply(s$spikes, mi_find_bursts, s$parameters$mi_par) s$bs <- calc_burst_summary(s) } s <- calculate_isis(s) s$well_stats <- compute_mean_firingrate_by_well(s) s }
TileBM <- function(BestMatches, Lines, Columns){ BestMatches=as.matrix(unname(BestMatches)) if(ncol(as.matrix(BestMatches))==3){ BestMatches=cbind(as.numeric(BestMatches[,1]),as.numeric(BestMatches[,2]),as.numeric(BestMatches[,3])) TiledBestMatches <- rbind(BestMatches, cbind(BestMatches[,1], (BestMatches[,2]+Lines), BestMatches[,3]), cbind(BestMatches[,1:2],(BestMatches[,3]+Columns)), cbind(BestMatches[,1],(BestMatches[,2]+Lines),(BestMatches[,3]+Columns))) }else{ if (ncol(as.matrix(BestMatches))==2){ BestMatches=cbind(1:length(BestMatches[,1]),BestMatches) BestMatches=cbind(as.numeric(BestMatches[,1]),as.numeric(BestMatches[,2]),as.numeric(BestMatches[,3])) TiledBestMatches <- rbind(BestMatches, cbind(BestMatches[,1], (BestMatches[,2]+Lines), BestMatches[,3]), cbind(BestMatches[,1:2],(BestMatches[,3]+Columns)), cbind(BestMatches[,1],(BestMatches[,2]+Lines),(BestMatches[,3]+Columns))) } else{ stop('Error: Number of Rows is not 2 or 3, nothing could be done') } } return(TiledBestMatches = TiledBestMatches) }
`print.check` <- function(x, ...) { print(x$n) }
design_array<-function(Xrow=NULL,Xcol=NULL,Xdyad=NULL,intercept=TRUE,n=NULL) { if(is.null(n)) { if(is.matrix(Xrow)){ n<-nrow(Xrow) } if(is.matrix(Xcol)){ n<-nrow(Xcol) } if(is.matrix(Xdyad)){ n<-nrow(Xdyad) } if(is.array(Xdyad)){ n<-dim(Xdyad)[1] } if(is.null(n)){ cat("Error: n must be specified") } } pr<-length(Xrow)/n pc<-length(Xcol)/n pd<-length(Xdyad)/n^2 X<-array(dim=c(n,n,pr+pc+pd)) dnX<-NULL if(pr>0) { Xrow<-as.matrix(Xrow) Xrowa<-array(dim=c(n,n,pr)) for( j in 1:pr ){ Xrowa[,,j]<-matrix( Xrow[,j], n,n) } X[,,1:pr]<- Xrowa dnX<-c(dnX,paste0(colnames(Xrow),rep(".row" ,pr))) } if(pc>0) { Xcol<-as.matrix(Xcol) Xcola<-array(dim=c(n,n,pc)) for( j in 1:pc ){ Xcola[,,j]<-t(matrix( Xcol[,j], n,n)) } X[,,pr+1:pc]<- Xcola dnX<-c(dnX,paste0(colnames(Xcol),rep(".col" ,pc))) } if(pd>0) { if(pd==1){ Xdyad<-array(Xdyad,dim=c(n,n,pd)) } X[,,pr+pc+1:pd]<-Xdyad dnX<-c(dnX,paste0(dimnames(Xdyad)[[3]],rep(".dyad",pd))) } if(!any(apply(X,3,function(x){var(c(x),na.rm=TRUE)})==0) & intercept) { X1<-array(dim=c(0,0,1)+dim(X)) X1[,,1]<-1 ; X1[,,-1]<-X X<-X1 dnX<-c("intercept",dnX) } if(dim(X)[[3]]>1) { dimnames(X)[[3]]<- dnX } if(dim(X)[[3]]==1){ dimnames(X)[[3]]<- list(dnX) } if( sum(is.na(X)) > sum( is.na(apply(X,3,diag)) ) ) { cat("WARNING: replacing NAs in design matrix with zeros","\n") } X[is.na(X)]<-0 X<-precomputeX(X) X }
row_waerden <- function(x, g) { force(x) force(g) if(is.vector(x)) x <- matrix(x, nrow=1) if(is.data.frame(x) && all(sapply(x, is.numeric))) x <- data.matrix(x) assert_numeric_mat_or_vec(x) assert_vec_length(g, ncol(x)) bad <- is.na(g) if(any(bad)) { warning(sum(bad), ' columns dropped due to missing group information') x <- x[,!bad, drop=FALSE] g <- g[!bad] } g <- as.character(g) r <- matrixStats::rowRanks(x, ties.method="average") n <- rep.int(ncol(x), nrow(x)) - matrixStats::rowCounts(is.na(x)) z <- stats::qnorm(r/(n+1)) z <- matrix(z, nrow=nrow(x), ncol=ncol(x)) nPerGroup <- matrix(numeric(), nrow=nrow(z), ncol=length(unique(g))) sPerGroup <- nPerGroup for(i in seq_along(unique(g))) { tmpx <- z[,g==unique(g)[i], drop=FALSE] nPerGroup[,i] <- rep.int(ncol(tmpx), nrow(tmpx)) - matrixStats::rowCounts(is.na(tmpx)) sPerGroup[,i] <- rowSums(tmpx, na.rm=TRUE) } nGroups <- matrixStats::rowCounts(nPerGroup!=0) s2 <- rowSums(z^2, na.rm=TRUE) / (n - 1) stat <- rowSums(sPerGroup^2 / nPerGroup) / s2 df <- nGroups - 1 p <- stats::pchisq(stat, df, lower.tail = FALSE) w1 <- n < 2 showWarning(w1, 'had less than 2 total observations') w2 <- !w1 & nGroups < 2 showWarning(w2, 'had less than 2 groups with enough observations') w3 <- !w1 & !w2 & s2==0 showWarning(w3, 'were essentially constant') stat[w1 | w2 | w3] <- NA p[w1 | w2 | w3] <- NA rnames <- rownames(x) if(!is.null(rnames)) rnames <- make.unique(rnames) data.frame(obs.tot=n, obs.groups=nGroups, df=df, statistic=stat, pvalue=p, row.names=rnames ) } col_waerden <- function(x, g) { row_waerden(t(x), g) }
context("Features: MISC - Basic") test_that("Non-Cellmapping Objects", { set.seed(2015*03*26) X = t(replicate(n = 2000, expr = runif(n = 5, min = -10, max = 10))) y = apply(X, 1, function(x) sum(x^2)) feat.object = createFeatureObject(X = X, y = y) features = calculateFeatureSet(feat.object, "basic") expect_identical(length(features), 15L) expect_list(features) expect_identical(as.character(sapply(features, class)), c("integer", "integer", rep("numeric", 6L), rep("integer", 4L), "logical", "integer", "numeric")) expect_identical(features$basic.dim, 5L) expect_identical(features$basic.observations, 2000L) expect_true(features$basic.lower_min >= -10) expect_true(features$basic.lower_max >= -10) expect_true(features$basic.lower_min <= features$basic.lower_max) expect_true(features$basic.upper_min <= 10) expect_true(features$basic.upper_max <= 10) expect_true(features$basic.upper_min <= features$basic.upper_max) expect_true(features$basic.lower_min <= features$basic.upper_min) expect_true(features$basic.lower_max <= features$basic.upper_max) expect_identical(features$basic.blocks_min, 1L) expect_identical(features$basic.blocks_max, 1L) expect_identical(features$basic.cells_total, 1L) expect_identical(features$basic.cells_filled, 1L) expect_identical(features$basic.minimize_fun, TRUE) expect_identical(features$basic.costs_fun_evals, 0L) expect_true( testNumber(features$basic.costs_runtime, lower = 0) ) }) test_that("Cellmapping Objects", { set.seed(2015*03*26) X = t(replicate(n = 2000, expr = runif(n = 5, min = -10, max = 10))) y = apply(X, 1, function(x) sum(x^2)) feat.object = createFeatureObject(X = X, y = y, blocks = c(2, 3, 4, 3, 5)) features = calculateFeatureSet(feat.object, "basic") expect_equal(length(features), 15L) expect_list(features) expect_equal(as.character(sapply(features, class)), c("integer", "integer", rep("numeric", 6L), rep("integer", 4L), "logical", "integer", "numeric")) expect_identical(features$basic.dim, 5L) expect_identical(features$basic.observations, 2000L) expect_true(features$basic.lower_min >= -10) expect_true(features$basic.lower_max >= -10) expect_true(features$basic.lower_min <= features$basic.lower_max) expect_true(features$basic.upper_min <= 10) expect_true(features$basic.upper_max <= 10) expect_true(features$basic.upper_min <= features$basic.upper_max) expect_true(features$basic.lower_min <= features$basic.upper_min) expect_true(features$basic.lower_max <= features$basic.upper_max) expect_identical(features$basic.blocks_min, 2L) expect_identical(features$basic.blocks_max, 5L) expect_identical(features$basic.cells_total, as.integer(2 * 3 * 4 * 3 * 5)) expect_true( testNumber(features$basic.cells_filled, lower = 1, upper = features$basic.cells_total) ) }) test_that("Test Basic Features", { set.seed(2015*03*26) X = t(replicate(n = 2000, expr = runif(n = 5L, min = -10, max = 10))) y = apply(X, 1, function(x) sum(x^2)) feat.object1 = createFeatureObject(X = X, y = y) feat.object2 = createFeatureObject(X = X, y = y, minimize = FALSE) feat.object3 = createFeatureObject(X = X, y = y, blocks = 3L) feat.object4 = createFeatureObject(X = X, y = y, blocks = 3L, minimize = FALSE) features1 = calculateFeatureSet(feat.object1, "basic") features2 = calculateFeatureSet(feat.object2, "basic") features3 = calculateFeatureSet(feat.object3, "basic") features4 = calculateFeatureSet(feat.object4, "basic") expect_equal(length(features1), 15L) expect_equal(length(features2), 15L) expect_equal(length(features3), 15L) expect_equal(length(features4), 15L) expect_list(features1) expect_list(features2) expect_list(features3) expect_list(features4) expect_equal(as.character(sapply(features1, class)), c("integer", "integer", rep("numeric", 6L), rep("integer", 4L), "logical", "integer", "numeric")) expect_equal(as.character(sapply(features2, class)), c("integer", "integer", rep("numeric", 6L), rep("integer", 4L), "logical", "integer", "numeric")) expect_equal(as.character(sapply(features3, class)), c("integer", "integer", rep("numeric", 6L), rep("integer", 4L), "logical", "integer", "numeric")) expect_equal(as.character(sapply(features4, class)), c("integer", "integer", rep("numeric", 6L), rep("integer", 4L), "logical", "integer", "numeric")) expect_true(features1$basic.minimize_fun) expect_true(!features2$basic.minimize_fun) expect_true(features3$basic.minimize_fun) expect_true(!features4$basic.minimize_fun) })
ipwCoxInd<-function(data,indA,indX,indStatus,indTime,ties="breslow",confidence=0.95){ dat=data n=nrow(dat) dat$id=1:n dat$A=dat[,indA] dat$time=dat[,indTime] dat$status=dat[,indStatus] nX=length(indX)+1 covX0=dat[,indX] A=dat$A psmd=glm(A~.,family="binomial",data=as.data.frame(cbind(A,covX0))) psfit=predict(psmd, type = "response") dat$wt=dat$A/psfit+(1-dat$A)/(1-psfit) prevA=mean(dat$A) dat$swt=prevA*dat$A/psfit+(1-prevA)*(1-dat$A)/(1-psfit) fit <- coxph(Surv(time, status) ~ A+cluster(id), weights=dat$wt,data=dat, ties=ties) logHR=fit$coefficients fits <- coxph(Surv(time, status) ~ A+cluster(id), weights=dat$swt,data=dat, ties=ties) logHRs=fits$coefficients eventid=which(dat$status==1) covX=as.matrix(cbind(rep(1,n),covX0)) dgvec=-dat$A*(1-psfit)/psfit+(1-dat$A)*psfit/(1-psfit) dgvecS=-prevA*dat$A*(1-psfit)/psfit+(1-prevA)*(1-dat$A)*psfit/(1-psfit) WdevR=t(diag(dgvec)%*%covX) WdevRS=t(diag(dgvecS)%*%covX) WfS=dat$A/psfit-(1-dat$A)/(1-psfit) A11x=rep(0,n) A12x=matrix(0,nX,n) A11xS=rep(0,n) A12xS=matrix(0,nX,n) A13xS=rep(0,n) for (x in eventid){ idrs=which(dat$time>=dat$time[x]) s0x=sum(dat$wt[idrs]*exp(dat$A[idrs]*logHR)) s1x=sum(dat$wt[idrs]*exp(dat$A[idrs]*logHR)*dat$A[idrs]) A11x[x]=dat$wt[x]*(s1x/s0x-s1x^2/(s0x^2)) A12a=(dat$A[x]-s1x/s0x)*WdevR[,x] s0xS=sum(dat$swt[idrs]*exp(dat$A[idrs]*logHRs)) s1xS=sum(dat$swt[idrs]*exp(dat$A[idrs]*logHRs)*dat$A[idrs]) A11xS[x]=dat$swt[x]*(s1xS/s0xS-s1xS^2/(s0xS^2)) A12aS=(dat$A[x]-s1xS/s0xS)*WdevRS[,x] A13aS=(dat$A[x]-s1xS/s0xS)*WfS[x] if (length(idrs)==1){ A12c=(WdevR[,idrs]*exp(dat$A[idrs]*logHR))*s1x A12d=WdevR[,idrs]*(exp(dat$A[idrs]*logHR)*dat$A[idrs]) A12cS=(WdevRS[,idrs]*exp(dat$A[idrs]*logHRs))*s1xS A12dS=WdevRS[,idrs]*(exp(dat$A[idrs]*logHRs)*dat$A[idrs]) A13cS=(WfS[idrs]*exp(dat$A[idrs]*logHRs))*s1xS A13dS=WfS[idrs]*(exp(dat$A[idrs]*logHRs)*dat$A[idrs]) } else{ A12c=(WdevR[,idrs]%*%exp(dat$A[idrs]*logHR))*s1x A12d=WdevR[,idrs]%*%(exp(dat$A[idrs]*logHR)*dat$A[idrs]) A12cS=(WdevRS[,idrs]%*%exp(dat$A[idrs]*logHRs))*s1xS A12dS=WdevRS[,idrs]%*%(exp(dat$A[idrs]*logHRs)*dat$A[idrs]) A13cS=(WfS[idrs]%*%exp(dat$A[idrs]*logHRs))*s1xS A13dS=WfS[idrs]%*%(exp(dat$A[idrs]*logHRs)*dat$A[idrs]) } A12b=dat$wt[x]*(A12d/s0x-A12c/(s0x^2)) A12x[,x]=-(A12a-A12b) A12bS=dat$swt[x]*(A12dS/s0xS-A12cS/(s0xS^2)) A12xS[,x]=-(A12aS-A12bS) A13bS=dat$swt[x]*(A13dS/s0xS-A13cS/(s0xS^2)) A13xS[x]=-(A13aS-A13bS) } A11A12=c(sum(A11x),apply(A12x,1,sum)) A11A12A13s=c(sum(A11xS),apply(A12xS,1,sum),sum(A13xS)) sumsquare<-function(u){ u%*%t(u) } A22mat=apply(covX,1,sumsquare)%*%(psfit*(1-psfit)) A22=matrix(apply(A22mat,1,sum),nX,nX) AA=as.matrix(rbind(A11A12,cbind(0,A22))) invAA=solve(AA) AAs=as.matrix(rbind(A11A12A13s,cbind(0,A22,0),c(rep(0,nX+1),n))) invAAs=solve(AAs) eventPa=subset(dat,dat$status==1) eventimes=unique(eventPa$time) RScol5=eventimes RScol3=rep(0,length(eventimes)) RScol4=RScol3 RScol1=RScol3 RScol2=RScol3 RScol5s=eventimes RScol3s=rep(0,length(eventimes)) RScol4s=RScol3s RScol1s=RScol3s RScol2s=RScol3s for (i in 1:length(eventimes)){ idc=which(dat$time==eventimes[i]&dat$status==1) RD1=dat[idc,] RScol1[i]=sum(RD1$wt*RD1$A) RScol2[i]=sum(RD1$wt) RSind=which(dat$time>=eventimes[i]) RS1=dat[RSind,] RScol3[i]=sum(RS1$wt*RS1$A) RScol4[i]=sum(RS1$wt*(1-RS1$A)) RScol1s[i]=sum(RD1$swt*RD1$A) RScol2s[i]=sum(RD1$swt) RScol3s[i]=sum(RS1$swt*RS1$A) RScol4s[i]=sum(RS1$swt*(1-RS1$A)) } risksetFull=data.frame(sumAiWi=RScol1,sumWi=RScol2,sumW1=RScol3,sumW0=RScol4,time=RScol5) risksetFulls=data.frame(sumAiWi=RScol1s,sumWi=RScol2s,sumW1=RScol3s,sumW0=RScol4s,time=RScol5s) indevent=which(dat$status==1) gg=rep(0,nrow(dat)) ggS=gg HRest=exp(logHR) HRests=exp(logHRs) for (i in indevent){ ind1=which(risksetFull$time==dat$time[i]) vv=(risksetFull$sumW1*HRest)/(risksetFull$sumW1*HRest+risksetFull$sumW0) gg[i]=dat$wt[i]*(dat$A[i]- vv[ind1]) ind1=which(risksetFulls$time==dat$time[i]) vv=(risksetFulls$sumW1*HRests)/(risksetFulls$sumW1*HRests+risksetFulls$sumW0) ggS[i]=dat$swt[i]*(dat$A[i]- vv[ind1]) } rs11=rep(0,nrow(dat)) rs12=rs11 rs11s=rep(0,nrow(dat)) rs12s=rs11s for (i in 1:nrow(dat)){ ind2=which(risksetFull$time<=dat$time[i]) rsred=risksetFull[ind2,] rs11[i]=dat$wt[i]*dat$A[i]*exp(log(HRest)*dat$A[i])*sum(rsred$sumWi/(rsred$sumW1*HRest+rsred$sumW0)) rs12[i]=dat$wt[i]*exp(log(HRest)*dat$A[i])*sum(rsred$sumWi*(rsred$sumW1*HRest)/((rsred$sumW1*HRest+rsred$sumW0)^2)) ind2=which(risksetFulls$time<=dat$time[i]) rsred=risksetFulls[ind2,] rs11s[i]=dat$swt[i]*dat$A[i]*exp(log(HRests)*dat$A[i])*sum(rsred$sumWi/(rsred$sumW1*HRests+rsred$sumW0)) rs12s[i]=dat$swt[i]*exp(log(HRests)*dat$A[i])*sum(rsred$sumWi*(rsred$sumW1*HRests)/((rsred$sumW1*HRests+rsred$sumW0)^2)) } eta=gg-rs11+rs12 etaS=ggS-rs11s+rs12s covX=as.matrix(cbind(rep(1,n),covX0)) matpi=diag(dat$A-psfit)%*%covX bbmat=cbind(eta,matpi) bbmatS=cbind(etaS,matpi,dat$A-prevA) sumsquare<-function(u){ u%*%t(u) } oot=apply(bbmat,1,sumsquare) BB=matrix(apply(oot,1,sum),nX+1,nX+1) propVar=invAA%*%BB%*%t(invAA) proposeStdErr=(diag(propVar)^0.5)[1] ootS=apply(bbmatS,1,sumsquare) BBs=matrix(apply(ootS,1,sum),nX+2,nX+2) propVarS=invAAs%*%BBs%*%t(invAAs) proposeStdErrS=(diag(propVarS)^0.5)[1] lowProp=logHR-qnorm(1-(1-confidence)/2)*proposeStdErr upProp=logHR+qnorm(1-(1-confidence)/2)*proposeStdErr lowPropS=logHRs-qnorm(1-(1-confidence)/2)*proposeStdErrS upPropS=logHRs+qnorm(1-(1-confidence)/2)*proposeStdErrS mtd=c("conventional weights","stabilized weights") est=c(logHR,logHRs) hrest=exp(est) se=c(proposeStdErr,proposeStdErrS) low=exp(c(lowProp,lowPropS)) up=exp(c(upProp,upPropS)) output=cbind(est,se,hrest,low,up) colnames(output)=c("log HR Estimate","Standard Error","HR Estimate", paste("HR ", confidence*100,"% CI", "-low", sep =""), paste("HR ", confidence*100,"% CI", "-up", sep ="")) rownames(output)=mtd output }
fit.mpt.old <- function(data, model.filename, restrictions.filename = NULL, n.optim = 5, fia = NULL, ci = 95, starting.values = NULL, output = c("standard", "fia", "full"), reparam.ineq = TRUE, sort.param = TRUE, model.type = c("easy", "eqn", "eqn2"), multicore = c("none", "individual", "n.optim"), sfInit = FALSE, nCPU = 2){ if (multicore[1] != "none" & sfInit) { eval(call("require", package = "snowfall", character.only = TRUE)) sfInit( parallel=TRUE, cpus=nCPU ) } else if (multicore[1] != "none") { if (!eval(call("require", package = "snowfall", character.only = TRUE))) stop("multicore needs snowfall") } llk.tree <- function(Q, unlist.tree, data, param.names, length.param.names){ Q[Q > 1] <- 1 Q[Q < 0] <- 0 for (i in 1:length.param.names) assign(param.names[i],Q[i], envir = tmpllk.env) tree.eval <- vapply(unlist.tree, eval, envir = tmpllk.env, 0) if (any(tree.eval < 0)) stop(paste("Model not constructed well. Branch (i.e., line) ", which(tree.eval < 0), " produces probabilities < 0!", sep = "")) llk <- data * log(tree.eval) llk[data == 0] <- 0 llk <- sum(llk) if (is.na(llk)) llk <- -1e10 if (llk == -Inf) llk <- -1e10 return(-llk) } sat_model <- function(tree, data){ temp.branch <- sapply(tree,length) NNN <- rep(.DF.N.get(data,tree)[[2]], temp.branch) temp <- data * log(data/NNN) temp[data == 0] <- 0 llk <- sum(temp) return(-llk) } optim.tree <- function(data, tree, llk.tree, param.names, n.params, n.optim, method = "L-BFGS-B", start.params) { mpt.optim <- function(x, start.params, llk.tree, tree, data, param.names, n.params, method) { if (is.null(start.params)) start.params <- c(0.05, 0.95) if (length(start.params) == 2) start.params <- runif(n.params, start.params[1], start.params[2]) optim(start.params, llk.tree, unlist.tree = tree, data = data, param.names = param.names, length.param.names = n.params, method = method, lower = 0, upper = 1, hessian = TRUE) } if (multicore[1] == "n.optim") { out <- snowfall::sfLapply(1:n.optim, mpt.optim, start.params = start.params, llk.tree = llk.tree, tree = tree, data = data, param.names = param.names, n.params = n.params, method = method) } else out <- lapply(1:n.optim, mpt.optim, start.params = start.params, llk.tree = llk.tree, tree = tree, data = data, param.names = param.names, n.params = n.params, method = method) return(out) } optim.mpt <- function(data, n.data, tree, llk.tree, param.names, n.params, n.optim, start.params) { minim <- vector("list", n.data) data.new <- lapply(1:n.data, function(x, data) data[x,], data = data) llks <- array(NA, dim=c(n.data, n.optim)) if (multicore[1] == "individual") { optim.runs <- snowfall::sfLapply(data.new, optim.tree, tree = unlist(tree), llk.tree = llk.tree, param.names = param.names, n.params = n.params, n.optim = n.optim, start.params = start.params) } else optim.runs <- lapply(data.new, optim.tree, tree = unlist(tree), llk.tree = llk.tree, param.names = param.names, n.params = n.params, n.optim = n.optim, start.params = start.params) for (c.outer in 1:n.data) { least.llk <- 1e10 for (c in 1: n.optim) { llks[c.outer, c] <- -(optim.runs[[c.outer]][[c]][["value"]]) if (optim.runs[[c.outer]][[c]]["value"] < least.llk) { minim[[c.outer]] <- optim.runs[[c.outer]][[c]] least.llk <- optim.runs[[c.outer]][[c]][["value"]] } } } return(list(minim = minim, optim.runs = optim.runs, llks = llks)) } get.goodness.of.fit <- function(minim, tree, data, dgf, n.params, n.data) { Log.Likelihood <- sapply(minim, function(x) x$value) G.Squared <- sapply(1:n.data, function(x, data, Log.Likelihood) as.numeric(2*(Log.Likelihood[x]-sat_model(tree, data[x,]))), data = data, Log.Likelihood = Log.Likelihood) df <- dgf - n.params p.value <- pchisq(G.Squared,df,lower.tail=FALSE) data.frame(Log.Likelihood = -Log.Likelihood, G.Squared, df, p.value) } get.information.criteria <- function(minim, G.Squared, n.params, n_items, fia = NULL) { AIC <- G.Squared + 2*n.params BIC <- G.Squared + n.params*log(n_items) if (!is.null(fia)) { FIA <- (G.Squared/2) + fia[,1] ic <- data.frame(FIA, AIC, BIC) } else ic <- data.frame(AIC, BIC) rownames(ic) <- NULL ic } get.model.info <- function(minim, n.params, dgf) { rank_hessian <- sapply(minim, function(x) qr(x$hessian)$rank) return(data.frame(rank.hessian = rank_hessian, n.parameters = n.params, n.independent.categories = dgf)) } get.parameter.table.multi <- function(minim, param.names, n.params, n.data, use.restrictions, inv.hess.list, ci, orig.params){ var.params <- sapply(inv.hess.list, function(x) tryCatch(diag(x), error = function(e) rep(NA, n.params))) rownames(var.params) <- param.names confidence.interval <- qnorm(1-((100-ci)/2)/100)*sqrt(var.params) estimates <- sapply(minim, function(x) x$par) upper.conf <- estimates + confidence.interval lower.conf <- estimates - confidence.interval if(!use.restrictions) { params <- 1:n.params names(params) <- param.names tmp.values <- NULL for (counter.n in 1:n.data) { tmp.values <- c(tmp.values, estimates[, counter.n], lower.conf[, counter.n], upper.conf[, counter.n]) } parameter_array <- array(tmp.values, dim = c(n.params, 3, n.data)) dimnames(parameter_array) <- list(param.names, c("estimates", "lower.conf", "upper.conf"), paste("dataset:", 1:n.data)) mean.df = data.frame(estimates = apply(parameter_array, c(1,2), mean)[,1], lower.conf = NA, upper.conf = NA) rownames(mean.df) <- param.names } if(use.restrictions) { used.rows <- param.names %in% orig.params params <- 1:length(orig.params) parameter.names.all <- param.names[used.rows] restricted <- rep("", sum(used.rows)) for (c in 1:length(restrictions)) { parameter.names.all <- c(parameter.names.all, restrictions[[c]][1]) restricted <- c(restricted, restrictions[[c]][3]) } names(params) <- parameter.names.all pnames <- parameter.names.all tmp.values <- NULL for (counter.n in 1:n.data) { parameter_table.indiv.tmp <- data.frame(param.names, estimates = estimates[, counter.n], lower.conf =lower.conf[, counter.n], upper.conf = upper.conf[, counter.n], restricted.parameter = 0) parameter_table <- parameter_table.indiv.tmp[parameter_table.indiv.tmp$param.names %in% orig.params,] for (c in 1:length(restrictions)) { if (restrictions[[c]][3] == "=" & sum(grepl("[[:alpha:]]", restrictions[[c]][2]))) { parameter_table <- rbind(parameter_table, data.frame(param.names = restrictions[[c]][1], parameter_table[parameter_table$param.names == restrictions[[c]][2], 2:4], restricted.parameter = 1)) } if (restrictions[[c]][3] == "=" & sum(grepl("^[[:digit:]]\\.?[[:digit:]]*", restrictions[[c]][2]))) { parameter_table <- rbind(parameter_table, data.frame(param.names = restrictions[[c]][1], estimates = as.numeric(restrictions[[c]][2]), lower.conf = NA, upper.conf = NA, restricted.parameter = 1)) } if (restrictions[[c]][3] == "<") { tmp.vars <- .find.MPT.params(parse(text = restrictions[[c]][2])[1]) new.param <- prod(parameter_table.indiv.tmp[parameter_table.indiv.tmp$param.names %in% tmp.vars,2]) var.tmp <- var.params[rownames(var.params) %in% tmp.vars, counter.n] length.var.tmp <- length(var.tmp) var.bound.tmp <- rep(NA,length.var.tmp) for (j in 1:length.var.tmp) var.bound.tmp[j] <- 2*var.tmp[j] + sum(2^(length.var.tmp-1)*(var.tmp[-j])) ineq.ci <- qnorm(1-((100-ci)/2)/100)*sqrt(min(var.bound.tmp)) parameter_table <- rbind(parameter_table, data.frame(param.names = restrictions[[c]][1], estimates = new.param, lower.conf = new.param - ineq.ci, upper.conf = new.param + ineq.ci, restricted.parameter = 2)) } } rownames(parameter_table) <- parameter_table$param.names parameter_table <- parameter_table[,-1] if (sort.param) parameter_table <- parameter_table[order(names(params)),] tmp.values <- c(tmp.values, as.vector(as.matrix(parameter_table))) } if (sort.param) { order.new <- order(pnames) pnames <- pnames[order.new] restricted <- restricted[order.new] } parameter_array <- array(tmp.values, dim = c(length(orig.params), 4, n.data)) dimnames(parameter_array) <- list(pnames, c("estimates", "lower.conf", "upper.conf", "restricted.parameter"), paste("dataset:", 1:n.data)) mean.df = data.frame(apply(parameter_array, c(1,2), mean)[,1], lower.conf = NA, upper.conf = NA, restricted = restricted) rownames(mean.df) <- pnames colnames(mean.df) <- c("estimates", "lower.conf", "upper.conf", "restricted.parameter") } return(list(individual = parameter_array, mean = mean.df)) } get.parameter.table.single <- function(minim, parameter.names, n.params, use.restrictions, inv.hess, ci, sort.param, orig.params){ var.params <- tryCatch(diag(inv.hess), error = function(e) rep(NA, n.params)) names(var.params) <- parameter.names confidence.interval <- tryCatch(qnorm(1-((100-ci)/2)/100)*sqrt(var.params), error = function(e) rep(NA, n.params)) estimates <- minim$par upper.conf <- estimates + confidence.interval lower.conf <- estimates - confidence.interval param.names <- parameter.names if(!use.restrictions) parameter_table <- data.frame(estimates, lower.conf, upper.conf) if(use.restrictions) { parameter_table.tmp <- data.frame(parameter.names, estimates, lower.conf, upper.conf, restricted.parameter = "") parameter_table <- parameter_table.tmp[parameter_table.tmp$parameter.names %in% orig.params,] for (c in 1:length(restrictions)) { if (restrictions[[c]][3] == "=" & sum(grepl("[[:alpha:]]", restrictions[[c]][2]))) { parameter_table <- rbind(parameter_table, data.frame(parameter.names = restrictions[[c]][1], parameter_table[parameter_table$parameter.names == restrictions[[c]][2], 2:4], restricted.parameter = restrictions[[c]][2])) } if (restrictions[[c]][3] == "=" & sum(grepl("^[[:digit:]]\\.?[[:digit:]]*", restrictions[[c]][2]))) { parameter_table <- rbind(parameter_table, data.frame(parameter.names = restrictions[[c]][1], estimates = as.numeric(restrictions[[c]][2]), lower.conf = NA, upper.conf = NA, restricted.parameter = restrictions[[c]][2])) } if (restrictions[[c]][3] == "<") { tmp.vars <- .find.MPT.params(parse(text = restrictions[[c]][2])[1]) new.param <- prod(parameter_table.tmp[parameter_table.tmp$parameter.names %in% tmp.vars,2]) var.tmp <- var.params[names(var.params) %in% tmp.vars] length.var.tmp <- length(var.tmp) var.bound.tmp <- rep(NA,length.var.tmp) for (j in 1:length.var.tmp) var.bound.tmp[j] <- 2*var.tmp[j] + sum(2^(length.var.tmp-1)*(var.tmp[-j])) ineq.ci <- qnorm(1-((100-ci)/2)/100)*sqrt(min(var.bound.tmp)) parameter_table <- rbind(parameter_table, data.frame(parameter.names = restrictions[[c]][1], estimates = new.param, lower.conf = new.param - ineq.ci, upper.conf = new.param + ineq.ci, restricted.parameter = "<")) } } param.names <- as.character(parameter_table[,1]) parameter_table <- parameter_table[,2:5] } if (sort.param) { parameter_table <- parameter_table[order(param.names),] param.names <- param.names[order(param.names)] } rownames(parameter_table) <- param.names return(parameter_table) } get.predicted.values <- function (minim, tree, data, df.n, param.names, length.param.names, n.data) { predictions <- matrix(NA, n.data, length(data[1,])) predict.env <- new.env() temp.branch <- sapply(tree,length) for (c in 1:n.data){ for (i in 1:length.param.names) assign(param.names[i],minim[[c]][["par"]][i], envir = predict.env) tree.eval <- sapply(unlist(tree), eval, envir = predict.env) frequencies <- rep(df.n[[c]][[2]], temp.branch) predictions[c,] <- tree.eval * frequencies } return(predictions) } tree <- .get.mpt.model(model.filename, model.type) if(is.null(data)) stop("Model seems to be constructed well (i.e., all probabilities sum to 1), but data is NULL.") if(is.vector(data)) { data <- array(data, dim = c(1, length(data))) multiFit <- FALSE } else if(dim(data)[1] == 1) { if (is.data.frame(data)) data <- as.matrix(data) data <- array(data, dim = c(1,length(data))) multiFit <- FALSE } else if(is.matrix(data) | is.data.frame(data)) { if (is.data.frame(data)) data <- as.matrix(data) multiFit <- TRUE } else stop("data is neither vector, nor matrix, nor data.frame!") if (sum(sapply(tree, length)) != length(data[1,])) stop(paste("Size of data does not correspond to size of model (i.e., model needs ", sum(sapply(tree, length)), " datapoints, data gives ", length(data[1,]), " datapoints).", sep = "")) if (ci != 95) message(paste("Confidence intervals represent ", ci, "% intervals.", sep = "")) orig.params <- NULL use.restrictions <- FALSE if (!is.null(restrictions.filename)) { use.restrictions <- TRUE restrictions <- .read.MPT.restrictions(restrictions.filename) orig.tree <- tree orig.params <- .find.MPT.params(tree) if (!reparam.ineq) { res.no.ineq <- restrictions for (res in 1:length(restrictions)) if (restrictions[[res]][3] == "<") res.no.ineq[[1]] <- NULL if (length(res.no.ineq) == 0) use.restrictions <- FALSE else restrictions <- res.no.ineq } if (use.restrictions) tree <- .apply.MPT.restrictions(tree, restrictions) } param.names <- .find.MPT.params(tree) n.params <- length(param.names) if (!is.null(starting.values)) { if (length(starting.values) != 2) { n.optim <- 1 if (length(starting.values) != n.params) stop("length(starting.values) does not match number of parameters.\nUse check.mpt() to find number and order of parameters!") } } if (n.optim != 1) message(paste("Presenting the best result out of ", n.optim, " minimization runs.", sep ="")) df.n <- apply(data, 1, .DF.N.get, tree = tree) n_items <- sapply(df.n, function (x) sum(x[[2]])) dgf <- df.n[[1]][[1]] n.data <- dim(data)[1] data.smaller.5 <- t(apply(data, 1, function(x) x < 5)) if (any(data.smaller.5)) warning(paste("Categories have n < 5! Do NOT trust these CIs. Dataset:", paste((1:n.data)[apply(data.smaller.5, 1, any)], collapse = " "), sep = "")) tmpllk.env <- new.env() t0 <- Sys.time() print(paste("Model fitting begins at ", t0, sep = "")) flush.console() res.optim <- optim.mpt(data, n.data, tree, llk.tree, param.names, n.params, n.optim, starting.values) t1 <- Sys.time() print(paste("Model fitting stopped at ", t1, sep = "")) print(t1-t0) minim <- res.optim$minim optim.runs <- res.optim$optim.runs llks <- res.optim$llks if (!is.null(fia)) { if (multiFit) { data.new <- rbind(data, apply(data,2,sum)) fia.tmp <- get.mpt.fia(data.new, model.filename, restrictions.filename, fia, model.type) fia.df <- fia.tmp[-dim(fia.tmp)[1],] fia.agg.tmp <- fia.tmp[dim(fia.tmp)[1],] } else { fia.df <- get.mpt.fia(data, model.filename, restrictions.filename, fia, model.type) } } inv.hess.list <- lapply(minim, function(x) tryCatch(solve(x$hessian), error = function(e) NA)) goodness.of.fit <- get.goodness.of.fit(minim,tree, data, dgf, n.params, n.data) if (is.null(fia)) information.criteria <- get.information.criteria(minim, goodness.of.fit$G.Squared, n.params, n_items) else information.criteria <- get.information.criteria(minim, goodness.of.fit$G.Squared, n.params, n_items, fia.df) model.info <- get.model.info(minim, n.params, dgf) if (n.optim > 1) summary.llks <- t(apply(llks, 1, summary)) if (multiFit) { fia.agg <- NULL data.pooled <- apply(data,2,sum) data.pooled <- matrix(data.pooled, 1, length(data.pooled)) res.optim.pooled <- optim.mpt(data.pooled, 1, tree, llk.tree, param.names, n.params, n.optim, starting.values) inv.hessian <- tryCatch(solve(res.optim.pooled[["minim"]][[1]][["hessian"]]), error = function(e) NA) if (!is.null(fia)) fia.agg <- fia.agg.tmp summed.goodness.of.fit <- data.frame(t(apply(goodness.of.fit, 2, sum))) summed.goodness.of.fit[1,4] <- pchisq(summed.goodness.of.fit[1,2], summed.goodness.of.fit[1,3], lower.tail = FALSE) goodness.of.fit <- list(individual = goodness.of.fit, sum = summed.goodness.of.fit, aggregated = get.goodness.of.fit(res.optim.pooled[["minim"]], tree, data.pooled, dgf, n.params, 1)) information.criteria <- list(individual = information.criteria, sum = data.frame(t(apply(information.criteria, 2, sum))), aggregated = get.information.criteria(res.optim.pooled$minim, goodness.of.fit[["aggregated"]][["G.Squared"]], n.params, sum(n_items), fia.agg)) model.info <- list(individual = model.info, aggregated = get.model.info(res.optim.pooled$minim, n.params, dgf)) parameters <- c(get.parameter.table.multi(minim, param.names, n.params, n.data, use.restrictions, inv.hess.list, ci, orig.params), aggregated = list(get.parameter.table.single(res.optim.pooled[["minim"]][[1]], param.names, n.params, use.restrictions, inv.hessian, ci, sort.param = sort.param, orig.params))) if (n.optim > 1) summary.llks <- list(individual = summary.llks, aggregated = summary(res.optim.pooled[["llks"]][[1]])) if (output[1] == "full") optim.runs <- c(individual = list(optim.runs), aggregated = res.optim.pooled$optim.runs) for (c.n in 1:n.data) { if (minim[[c.n]][["counts"]][1] < 10) warning(paste("Number of iterations run by the optimization routine for individual ", c.n, " is low (i.e., < 10) indicating local minima. Try n.optim >= 5.", sep = "")) if (minim[[c.n]][["convergence"]] != 0) warning(paste("Optimization routine for individual ", c.n, " did not converge succesfully. Error code: ", minim[[c.n]][["convergence"]], ". Use output = 'full' for more information.", sep ="")) } } else { parameters <- get.parameter.table.single(minim[[1]], param.names, n.params, use.restrictions, inv.hess.list[[1]], ci, sort.param = sort.param, orig.params) if (minim[[1]][["counts"]][1] < 10) warning("Number of iterations run by the optimization routine is low (i.e., < 10) indicating local minima. Try n.optim >= 5.") if (minim[[1]][["convergence"]] != 0) warning(paste("Optimization routine did not converge succesfully. Error code is, ", minim[[1]][["convergence"]], ". Use output = 'full' for more information.", sep ="")) } predictions <- get.predicted.values(minim, tree, data, df.n, param.names, n.params, n.data) data <- list(observed = data, predicted = predictions) if (multiFit) if (!is.null(fia.agg)) fia.df <- list(individual = fia.df, aggregated = fia.agg) outlist <- list(goodness.of.fit = goodness.of.fit, information.criteria = information.criteria, model.info = model.info, parameters = parameters, data = data) if (n.optim > 1) outlist <- c(outlist, summary.llks = list(summary.llks)) if (output[1] == "fia" | (output[1] == "full" & !is.null(fia))) outlist <- c(outlist, FIA = list(fia.df)) if (output[1] == "full") outlist <- c(outlist, optim.runs = list(optim.runs)) if (multicore[1] != "none" & sfInit) snowfall::sfStop() return(outlist) }
test_that("check length of output",{ skip_on_cran() local_edition(3) expect_equal(length(RLumModel:::.set_pars("Bailey2001")), 12) expect_equal(length(RLumModel:::.set_pars("Bailey2002")), 12) expect_equal(length(RLumModel:::.set_pars("Bailey2004")), 12) expect_equal(length(RLumModel:::.set_pars("Pagonis2007")), 12) expect_equal(length(RLumModel:::.set_pars("Pagonis2008")), 12) expect_equal(length(RLumModel:::.set_pars("Friedrich2017")), 12) expect_equal(length(RLumModel:::.set_pars("customized")), 5) }) test_that("check class of output",{ skip_on_cran() local_edition(3) expect_equal(class(RLumModel:::.set_pars("Bailey2001")), "list") expect_equal(class(RLumModel:::.set_pars("Bailey2002")), "list") expect_equal(class(RLumModel:::.set_pars("Bailey2004")), "list") expect_equal(class(RLumModel:::.set_pars("Pagonis2007")), "list") expect_equal(class(RLumModel:::.set_pars("Pagonis2008")), "list") expect_equal(class(RLumModel:::.set_pars("Friedrich2017")), "list") expect_equal(class(RLumModel:::.set_pars("customized")), "list") })
epval_Chen2014 <- function(sam1, sam2, eq.cov = TRUE, n.iter = 1000, cov1.est, cov2.est, bandwidth1, bandwidth2, cv.fold = 5, norm = "F", seeds){ if(missing(seeds)){ seeds <- NULL }else{ if(length(seeds) != n.iter){ seeds <- NULL cat("The length of seeds does not match the specified n.iter.\n") cat("Seeds for each permutation/resampling iteration are assigned randomly.\n") } } if(eq.cov){ out <- epval_Chen2014_samecov(sam1, sam2, n.iter, seeds) }else{ sam.cov1 <- cov(sam1) sam.cov2 <- cov(sam2) p <- dim(sam1)[2] if(missing(bandwidth1)) bandwidth1 <- seq(from = 0, to = p, by = floor(p/50)) if(missing(bandwidth2)) bandwidth2 <- seq(from = 0, to = p, by = floor(p/50)) if(any(bandwidth1 < 0)){ cat("Negative values specified in bandwidth1 are removed.\n") bandwidth1 <- bandwidth1[bandwidth1 < 0] } if(any(bandwidth2 < 0)){ cat("Negative values specified in bandwidth2 are removed.\n") bandwidth2 <- bandwidth2[bandwidth2 < 0] } if(any(bandwidth1 != floor(bandwidth1))){ cat("Non-integers specified in bandwidth1 are converted to their integer parts.") bandwidth1 <- floor(bandwidth1) } if(any(bandwidth2 != floor(bandwidth2))){ cat("Non-integers specified in bandwidth2 are converted to their integer parts.") bandwidth2 <- floor(bandwidth2) } if(missing(cov1.est)){ output.opt.bw1 <- TRUE if(length(bandwidth1) > 1){ optim.bandwidth1 <- best.band(sam1, bandwidth1, cv.fold, norm) } if(length(bandwidth1) == 1){ optim.bandwidth1 <- bandwidth1 } if(optim.bandwidth1 > 0){ cov1.est <- sam.cov1 cov1.est[abs(row(cov1.est) - col(cov1.est)) > optim.bandwidth1] <- 0 } if(optim.bandwidth1 == 0){ cov1.est <- diag(diag(sam.cov1)) } eigen1 <- eigen(cov1.est) eigen1.vectors <- eigen1$vectors eigen1.values <- eigen1$values eigen1.values[eigen1.values <= 0] <- 0.001 cov1.est <- eigen1.vectors %*% diag(eigen1.values) %*% t(eigen1.vectors) }else{ output.opt.bw1 <- FALSE } if(missing(cov2.est)){ output.opt.bw2 <- TRUE if(length(bandwidth2) > 1){ optim.bandwidth2 <- best.band(sam2, bandwidth2, cv.fold, norm) } if(length(bandwidth2) == 1){ optim.bandwidth2 <- bandwidth2 } if(optim.bandwidth2 > 0){ cov2.est <- sam.cov2 cov2.est[abs(row(cov2.est) - col(cov2.est)) > optim.bandwidth2] <- 0 } if(optim.bandwidth2 == 0){ cov2.est <- diag(diag(sam.cov2)) } eigen2 <- eigen(cov2.est) eigen2.vectors <- eigen2$vectors eigen2.values <- eigen2$values eigen2.values[eigen2.values <= 0] <- 0.001 cov2.est <- eigen2.vectors %*% diag(eigen2.values) %*% t(eigen2.vectors) }else{ output.opt.bw2 <- FALSE } out <- epval_Chen2014_diffcov(sam1, sam2, n.iter, sam.cov1, sam.cov2, cov1.est, cov2.est, cv.fold, norm, seeds, optim.bandwidth1, optim.bandwidth2, output.opt.bw1, output.opt.bw2) } return(out) }
column_result <- function(x) { structure(x, class = unique(c("rhub_column_result", class(x)))) } `[.rhub_column_result` <- function(x, i) { column_result(NextMethod("[")) } pillar_shaft.rhub_column_result <- function(x, ...) { cx <- lapply(x, color_column_result) new_pillar_shaft_simple(cx, ...) } color_column_result <- function(x) { if (is.null(x)) return("in-progress") E <- if (n <- length(x$errors)) status_style_error(strrep("E", n)) W <- if (n <- length(x$warnings)) status_style_error(strrep("W", n)) N <- if (n <- length(x$notes)) status_style_note(strrep("N", n)) switch( x$status, "parseerror" = status_style_error("parseerror"), "preperror" = status_style_error("preperror"), "aborted" = status_style_aborted("aborted"), "ok" = status_style_ok("ok"), paste0(E, W, N)) } type_sum.rhub_column_result <- function(x) { "rhub::result" }
eqearth_get_ext <- function(ext, npoints=15) { if(base::missing(ext)) ext bckg <- sp::Polygons(list(sp::Polygon(cbind(c(rep(ext[1], npoints), rep(ext[2], npoints)), c(seq(ext[3], ext[4], length.out=npoints), seq(ext[4], ext[3], length.out=npoints))))), ID = as.character(1)) Sl1 <- sp::SpatialPolygons(list(bckg)) raster::crs(Sl1) <- sp::CRS("+init=epsg:4326") PROJ <- sp::CRS(paste0("+proj=eqearth +lon_0=", mean(c(ext[2], ext[1])), " +x_0=", mean(c(ext[2], ext[1])), " +ellps=WGS84 +datum=WGS84 +units=m +no_defs") ) bckg.eqearth <- sp::spTransform(Sl1, PROJ) ext <- raster::extent(bckg.eqearth) ext[1:2] <- ext[1:2] + c(-0.1, 0.02)*diff(ext[1:2]) ext[3:4] <- ext[3:4] + c(-0.1, 0.02)*diff(ext[3:4]) ext } plot_map_eqearth <- function(dat, ext=raster::extent(dat), zlim=range(raster::values(dat), na.rm=TRUE), col=viridis::viridis(20), brks.pos=c(0,1), brks.lab=brks.pos, npoints=15, nlines=9, title='', colour_scale=TRUE, top_layer=NA, top_layer.col='ghostwhite', site_xy=NA, dim=NA) { if(base::missing(dat)) dat slss <- rgdal::projInfo(type = "proj") p1 = rgeos::readWKT("POLYGON((0 0,3 0,3 3,0 3,0 0))") utils::data(M1, package='crestr', envir = environment()) M1 <- raster::crop(M1, ext) PROJ <- sp::CRS(paste0("+proj=eqearth +lon_0=",mean(ext[1:2]), " +x_0=",mean(ext[1:2]), " +ellps=WGS84 +datum=WGS84 +units=m +no_defs") ) M2 <- sp::spTransform(M1, PROJ) if (class(dat) == 'RasterLayer') dat <- raster::projectRaster(from=dat, crs=PROJ) if ('Raster' %in% methods::is(top_layer)) top_layer <- raster::projectRaster(from=top_layer, crs=PROJ) ll=list() idx=1 for(i in seq(ext[1], ext[2], length.out=nlines)){ ll[[idx]] <- sp::Lines(list(sp::Line(cbind(rep(i,npoints), seq(ext[3], ext[4], length.out=npoints)))), ID = as.character(i)) idx = idx +1 } Sl1 <- sp::SpatialLines(ll) raster::crs(Sl1) <- sp::CRS("+init=epsg:4326") verticals.eqearth <- sp::spTransform(Sl1, raster::crs(PROJ)) verticals.eqearth.x <- unlist(lapply(sp::coordinates(verticals.eqearth), function(x) return(x[[1]][1,1]))) ll=list() idx=1 for(i in seq(ext[3], ext[4], length.out=nlines)){ ll[[idx]] <- sp::Lines(list(sp::Line(cbind(seq(ext[1], ext[2], length.out=npoints), rep(i, npoints)))), ID = as.character(i)) idx = idx +1 } Sl1 <- sp::SpatialLines(ll) raster::crs(Sl1) <- sp::CRS("+init=epsg:4326") horizontals.eqearth <- sp::spTransform(Sl1, raster::crs(PROJ)) horizontals.eqearth.xy <- t(data.frame(lapply(sp::coordinates(horizontals.eqearth), function(x) return(x[[1]][1,])))) horizontals.eqearth.y <- unlist(lapply(sp::coordinates(horizontals.eqearth), function(x) return(x[[1]][1,2]))) if (length(site_xy) == 2) { Sl1 <- sp::SpatialPoints(matrix(site_xy, ncol=2)) raster::crs(Sl1) <- sp::CRS("+init=epsg:4326") XY <- sp::spTransform(Sl1, raster::crs(PROJ)) } bckg <- sp::Polygons(list(sp::Polygon(cbind(c(rep(ext[1], npoints), rep(ext[2], npoints)), c(seq(ext[3], ext[4], length.out=npoints), seq(ext[4], ext[3], length.out=npoints))))), ID = as.character(1)) Sl1 <- sp::SpatialPolygons(list(bckg)) raster::crs(Sl1) <- sp::CRS("+init=epsg:4326") bckg.eqearth <- sp::spTransform(Sl1, raster::crs(PROJ)) if (class(dat) == 'RasterLayer') dat <- raster::mask(dat, bckg.eqearth) ext <- raster::extent(bckg.eqearth) ext_factor_x <- max(graphics::strwidth(paste0(' ', round(as.numeric(names(horizontals.eqearth)),2)), units='inches', cex=6/8)) ext_factor_y <- max(graphics::strheight(paste0('\n', round(as.numeric(names(verticals.eqearth)),2)), units='inches', cex=6/8)) if(is.na(dim)[1]) dim <- grDevices::dev.size('in') ext[1:2] <- ext[1:2] + (ext[2]-ext[1])/dim[1] * c(-ext_factor_x, 0.05) ext[3:4] <- ext[3:4] + (ext[4]-ext[3])/dim[2] * c(-ext_factor_y, 0.05) if(colour_scale) { xlab <- c(-0.2,1.2) xlab <- xlab + diff(xlab)/dim[1] * c(-ext_factor_x, 0.05) plot(NA, NA, type='n', xlab='', ylab='', main='', axes=FALSE, frame=FALSE, xlim=xlab, ylim=c(-0.05,1), xaxs='i', yaxs='i') brks2 <- (brks.pos - brks.pos[1]) / diff(range(brks.pos)) for(i in 1:length(col)) { graphics::rect((i-1)/length(col), 0, i/length(col), 0.3, lwd=0.3, border=col[i], col=col[i]) } cex <- 1 while(graphics::strwidth(title, font=2, cex=cex) >= 1.4) cex <- cex - 0.05 cont <- TRUE res <- 1 while(cont) { brks2.pos <- brks.pos[c(TRUE, rep(FALSE, res-1))] brks2.lab <- brks.lab[c(TRUE, rep(FALSE, res-1))] sizes <- graphics::strwidth(paste(' ',brks2.lab,' ', sep=''), cex=min(cex, 6/8)) x1 = (brks2.pos - brks.pos[1]) / diff(range(brks.pos)) + sizes/2 ; x1 = x1[1:(length(x1)-1)] x2 = (brks2.pos - brks.pos[1]) / diff(range(brks.pos)) - sizes/2 ; x2 = x2[2:length(x2)] if(min(x2-x1) <= 0) { res <- res + 1 } else { cont <- FALSE } } for(i in 1:length(brks2.pos)) { graphics::text((brks2.pos[i] - brks2.pos[1])/diff(range(brks.pos)), 0.35, brks2.lab[i] , cex=min(cex, 6/8), adj=c(0.5,0)) } graphics::rect(0,0,1,0.3, lwd=0.5) graphics::text(0.5, 0.85, title, font=2, cex=cex, adj=c(0.5,1)) } plot(0, 0, type='n', xlim=c(ext[1], ext[2]), ylim=c(ext[3], ext[4]), main='', ylab='', xlab='', xaxs='i', yaxs='i', asp=1, frame=FALSE, axes=FALSE) ; { sp::plot(bckg.eqearth, col='grey80', border=NA, cex=0.2, add=TRUE) sp::plot(horizontals.eqearth,col='white',lwd=0.5, add=TRUE ) sp::plot(verticals.eqearth,col='white',lwd=0.5, add=TRUE ) sp::plot(M2, col='black', border=NA, add=TRUE) if (class(dat) == 'RasterLayer') { raster::image(dat, colNa='black', add=TRUE, interpolate=FALSE, zlim=zlim, col=col) sp::plot(M2, border='black', lwd=0.5, add=TRUE) } if ('Raster' %in% methods::is(top_layer)) { raster::image(top_layer, add=TRUE, col=top_layer.col) } if(length(site_xy) == 2) { sp::plot(XY, col='white', bg='red', cex=2, lwd=2, pch=23, add=TRUE) } labels.lon <- rep(FALSE, length(verticals.eqearth.x)) for(v in 1:length(verticals.eqearth.x)) { overlap <- FALSE if(v > 1 ) { if (labels.lon[v-1]) { d1 <- graphics::strwidth(paste0('\n ', round(as.numeric(names(verticals.eqearth))[v-1],2), ' '), cex=6/8) d2 <- graphics::strwidth(paste0('\n ', round(as.numeric(names(verticals.eqearth))[v],2), ' '), cex=6/8) if (verticals.eqearth.x[v-1] + d1 / 2 >= verticals.eqearth.x[v] - d2 / 2) { overlap <- TRUE } } } if (!overlap){ graphics::text(verticals.eqearth.x[v], min(horizontals.eqearth.xy[,2]), paste0('\n', round(as.numeric(names(verticals.eqearth))[v],2)), cex=6/8, adj=c(0.5,0.7) ) labels.lon[v] <- TRUE } } labels.lat <- rep(FALSE, length(horizontals.eqearth.xy)) for(h in nrow(horizontals.eqearth.xy):1) { overlap <- FALSE if(h < nrow(horizontals.eqearth.xy)) { if (labels.lat[h+1]) { d1 <- graphics::strheight(paste0('', round(as.numeric(names(horizontals.eqearth))[h+1],2), ' '), cex=6/8) d2 <- graphics::strheight(paste0('', round(as.numeric(names(horizontals.eqearth))[h],2), ' '), cex=6/8) if (horizontals.eqearth.y[h+1] - d1 / 2 <= horizontals.eqearth.y[h] + d2 / 2) { overlap <- TRUE } } } if (!overlap){ graphics::text(horizontals.eqearth.xy[h, 1], horizontals.eqearth.xy[h, 2], paste0(round(as.numeric(names(horizontals.eqearth))[h], 2),' '), cex=6/8, adj=c(1,0.4) ) labels.lat[h] <- TRUE } } sp::plot(bckg.eqearth, col=NA, border='black', cex=0.2, add=TRUE) } invisible(ext) }
convert <- function(in_file, out_file, in_opts=list(), out_opts=list()) { if (missing(out_file)) { stop("'outfile' is missing with no default") } invisible(do.call("export", c(list(file = out_file, x = do.call("import", c(list(file=in_file), in_opts))), out_opts))) }
make_legend_ggplot <- function(dat, legend_pos) { legend_just <- NULL legend_dir <- NULL n_lines <- num_lines(dat) if (n_lines == 1) { legend_pos <- "none" } else if (any(is.na(legend_pos))) { legend_pos <- "none" } else if (is.logical(legend_pos)) { if (isTRUE(legend_pos)) { legend_pos <- "bottom" } else { legend_pos <- c(1, 0) legend_just <- legend_pos } } else if (is.character(legend_pos)) { pos_choices <- c("left", "right", "bottom", "top") legend_pos <- pos_choices[pmatch(legend_pos, pos_choices)] legend_just <- "center" } else if (is.numeric(legend_pos) & length(legend_pos) == 2) { legend_just <- legend_pos } else { legend_pos <- c(1, 0) legend_just <- legend_pos } list(legend.direction = legend_dir, legend.justification = legend_just, legend.position = legend_pos) }
require(OpenMx) v <- 1:3 omxCheckError(mxFactor(v, levels=1:3, exclude=3), "Factor levels and exclude vector are not disjoint; both contain '3'") v <- 1:4 omxCheckError(mxFactor(v, levels=1:3), "The following values are not mapped to factor levels and not excluded: '4'") cf <- omxCheckError(mxFactor(sample(1:2, 10, replace=TRUE), levels=1:2, labels=c("incorrect", "incorrect")), "Duplicate labels and collapse=TRUE not specified: 'incorrect'") cf <- mxFactor(sample(1:2, 10, replace=TRUE), levels=1:2, labels=c("incorrect", "incorrect"), collapse=TRUE) omxCheckEquals(length(levels(cf)), 1) omxCheckEquals(levels(cf), 'incorrect') omxCheckTrue(all(cf == "incorrect")) foo <- data.frame(x=c(1:3),y=c(4:6),z=c(7:9)) foo <- mxFactor(foo, c(1:9), labels=c(1,1,1,2,2,2,3,3,3), collapse=TRUE) omxCheckTrue(all(foo == matrix(kronecker(1:3, rep(1,3)),3,3))) v <- sample.int(50, 200, replace=TRUE) vl <- v %% 11 mask <- !duplicated(v) v2 <- mxFactor(v, levels=v[mask], labels=vl[mask], collapse = TRUE) omxCheckTrue(all(v2 == vl)) nthresh1 <- 1 nthresh2 <- 12 cnames <- c("t1neur1", "t1mddd4l", "t2neur1", "t2mddd4l") data <- suppressWarnings(try(read.table("data/mddndzf.dat", na.string=".", col.names=cnames))) if (is(data, "try-error")) data <- read.table("models/passing/data/mddndzf.dat", na.string=".", col.names=cnames) data[,c(1,3)] <- mxFactor(data[,c(1,3)], c(0 : nthresh2)) data[,c(2,4)] <- mxFactor(data[,c(2,4)], c(0 : nthresh1)) diff <- nthresh2 - nthresh1 nvar <- 4 Mx1Threshold <- rbind( c(-1.9209, 0.3935, -1.9209, 0.3935), c(-0.5880, 0 , -0.5880, 0 ), c(-0.0612, 0 , -0.0612, 0 ), c( 0.3239, 0 , 0.3239, 0 ), c( 0.6936, 0 , 0.6936, 0 ), c( 0.8856, 0 , 0.8856, 0 ), c( 1.0995, 0 , 1.0995, 0 ), c( 1.3637, 0 , 1.3637, 0 ), c( 1.5031, 0 , 1.5031, 0 ), c( 1.7498, 0 , 1.7498, 0 ), c( 2.0733, 0 , 2.0733, 0 ), c( 2.3768, 0 , 2.3768, 0 )) Mx1R <- rbind( c(1.0000, 0.2955, 0.1268, 0.0760), c(0.2955, 1.0000, -0.0011, 0.1869), c(0.1268, -0.0011, 1.0000, 0.4377), c(0.0760, 0.1869, 0.4377, 1.0000)) nameList <- names(data) model <- mxModel() model <- mxModel(model, mxMatrix("Stand", name = "R", nrow = nvar, ncol = nvar, free=TRUE)) model <- mxModel(model, mxMatrix("Zero", name = "M", nrow = 1, ncol = nvar, free=FALSE)) model <- mxModel(model, mxMatrix("Full", name="thresh", values=cbind( seq(-1.9, 1.9, length.out=nthresh2), c(rep(1, nthresh1), rep(0, diff)), seq(-1.9, 1.9, length.out=nthresh2), c(rep(1, nthresh1), rep(0, diff)) ), free = c(rep(c( rep(TRUE, nthresh2), rep(TRUE, nthresh1), rep(FALSE, diff) ), 2)), labels = rep(c(paste("neur", 1:nthresh2, sep=""), paste("mddd4l", 1:nthresh1, sep=""), rep(NA, diff)) ))) objective <- mxExpectationNormal(covariance="R", means="M", dimnames=nameList, thresholds="thresh") dataMatrix <- mxData(data, type='raw') model <- mxModel(model, objective, dataMatrix, mxFitFunctionML()) modelOut <- mxRun(model) estimates <- modelOut$output$estimate omxCheckCloseEnough(mxEval(thresh, modelOut)[,1], Mx1Threshold[,1], 0.03) omxCheckCloseEnough(mxEval(thresh, modelOut)[1,2], Mx1Threshold[1,2], 0.01) omxCheckCloseEnough(mxEval(R, modelOut), Mx1R, 0.01) omxCheckCloseEnough(modelOut$output$Minus2LogLikelihood, 4081.48, 0.08)
sample <- function(x, size, replace = FALSE, prob = NULL) { if(length(x) == 1L && is.numeric(x) && is.finite(x) && x >= 1) { if(missing(size)) size <- x sample.int(x, size, replace, prob) } else { if(missing(size)) size <- length(x) x[sample.int(length(x), size, replace, prob)] } } sample.int <- function(n, size = n, replace = FALSE, prob = NULL) { if (!replace && is.null(prob) && n > 1e7 && size <= n/2) .Internal(sample2(n, size)) else .Internal(sample(n, size, replace, prob)) }