code
stringlengths
1
13.8M
phyloglmstep <- function(formula, starting.formula = NULL, data=list(), phy, method = c("logistic_MPLE","logistic_IG10"), direction = c("both", "backward", "forward"), trace = 2, btol = 10, log.alpha.bound = 4, start.beta=NULL, start.alpha=NULL, boot = 0, full.matrix = TRUE, k=2, ...) { method = match.arg(method) direction = match.arg(direction) fit.full = phyloglm(formula, data, phy, method, btol, log.alpha.bound, start.beta, start.alpha, boot, full.matrix, ...) response = fit.full$formula[[2]] covariates = attr(terms(formula), "term.labels") p = length(covariates) if (p==0) stop("Your full model only has intercept. Model selection is not needed.") plm.full = rep(1,p) create.formula <- function(plm) { on = which(plm==1) str = paste(response," ~ 1",sep="") if (length(on) > 0) for (i in 1:length(on)) str = paste(str," + ",covariates[on[i]],sep="") return(str) } fit <- function(plm) { return(phyloglm(create.formula(plm), data, phy, method, btol, log.alpha.bound, start.beta, start.alpha, boot, full.matrix, ...)) } if (direction == "forward") { plm.current = rep(0,p) fit.current = fit(plm.current) } else { plm.current = plm.full fit.current = fit.full } if (!is.null(starting.formula)) { fit.current = phylolm(starting.formula, data, phy, method, btol, log.alpha.bound, start.beta, start.alpha, boot, full.matrix, ...) covariates.current = attr(terms(starting.formula), "term.labels") plm.current = rep(0,p) position = match(covariates.current,covariates) if (any(is.na(position))) stop("The starting model is not a submodel of the full model.") plm.current[position] = 1 } if (trace>0) { cat("----------\n") cat(paste("Starting model: ",create.formula(plm.current),"\n",sep="")) cat(paste("Direction: ",direction,"\n",sep="")) cat(paste("AIC(k=",k,"): ",AIC(fit.current,k),"\n",sep="")) } flag = 0 count = 1 while (flag == 0) { flag = 1 plm.best = plm.current fit.best = fit.current terms.add = add.scope(formula(create.formula(plm.current)), formula(create.formula(plm.full))) terms.drop = drop.scope(formula(create.formula(plm.current))) for (i in 1:p) { plm.propose = plm.current do.update = FALSE if ((plm.current[i]==1)&&(direction %in% c("both", "backward")) &&(covariates[i] %in% terms.drop)) { plm.propose[i] = 0 do.update = TRUE } if ((plm.current[i]==0)&&(direction %in% c("both", "forward")) &&(covariates[i] %in% terms.add)) { plm.propose[i] = 1 do.update = TRUE } if (do.update){ fit.propose = fit(plm.propose) if (trace>1) { cat(paste0("\tProposed: ",create.formula(plm.propose),"\n")) cat(paste0("\tAIC(k=",k,"): ",AIC(fit.propose,k),"\n")) } if (AIC(fit.propose,k) < AIC(fit.best,k)) { plm.best = plm.propose fit.best = fit.propose flag = 0 } } } plm.current = plm.best fit.current = fit.best if (trace>0) { cat("----------\nStep ",count,"\n",sep="") cat(paste("Current model: ",create.formula(plm.current),"\n",sep="")) cat(paste("AIC(k=",k,"): ",AIC(fit.current,k),"\n",sep="")) } count = count + 1 } if (trace>0) cat("---END\n") return(fit.current) }
plotClass.result<-function(true.classified, cross.method, class.method, flag.feature, feat.num) { if((cross.method=="sub-sampling")||(cross.method=="fold-crossval")) { if(flag.feature) { if(length(class.method)==1) { vrem=matrix(1:ncol(true.classified),ncol(true.classified),1) } else { vrem=sapply(class.method,function(z) which(colnames(true.classified)==z)) } par(mfrow=c(length(class.method),1)) for(i in 1:length(class.method)) { if(feat.num==1) { values=true.classified[,vrem[i],drop=FALSE] } else { values=true.classified[,vrem[,i],drop=FALSE] } colnames(values)=seq(feat.num,1,-1) box=boxplot(values,main = paste("Cross validation",class.method[i]),ylab = "Classification accuracy",xlab="n of features",col=i+1) } } else { box=boxplot(true.classified,main = "Cross validation",ylab = "Classification accuracy",xlab="Classifiers",col=3) } } if(cross.method=="leaveOneOut") { if(flag.feature) { dim(true.classified)=c(length(class.method),feat.num) barplot (true.classified, beside=TRUE, col=(1:length(class.method))+1, border='white' , xlab="n of features", ylab="Accuracy", names.arg=as.character(seq(feat.num,1,-1)) , ylim=c(0,1), main="Classification with n of features") legend("bottomright", col=(1:length(class.method))+1, class.method, bg="white", lwd=1, pch=1:length(class.method)) } else { barplot (true.classified, col=(1:length(class.method))+1, border='white' , space=0.2, xlab="Classifiers", ylab="Accuracy", names.arg=class.method , ylim=c(0,1), main="Classification results") legend("bottomright", col=(1:length(class.method))+1, paste(class.method,format(true.classified,digits=3)),bg="white", lwd=1, pch=1:length(class.method)) } } }
hires <- function( yini = NULL, times = seq(0, 321.8122, by = 321.8122/500), parms = list(), printmescd = TRUE, method = mebdfi, atol = 1e-6, rtol = 1e-6, ...) { hires <- function(t,y,parms) { with (as.list(c(y,parms)),{ dPr <- -k1*Pr + k2*Pfr + k6*PrX + Oks dPfr <- k1*Pr - (k2+k3)*Pfr dPrX <- -(k6+k1)*PrX + k2*PfrX + k5*PrX2 dPfrX <- k3*Pfr + k1*PrX -(k4+k2)*PfrX dPrX2 <- -(k5+k1)*PrX2 + k2*(PfrX2+PfrX2E) dPfrX2 <- -k7*PfrX2*E + k8*PfrX + k1*PrX2 - k2*PfrX2+ k8*PfrX2E dPfrX2E <- k7*PfrX2*E - (k2+k8+k9)*PfrX2E dE <- -k7*PfrX2*E + (k2+k8+k9)*PfrX2E list(c(dPr, dPfr, dPrX, dPfrX, dPrX2, dPfrX2, dPfrX2E, dE)) }) } parameter <- c(k1 = 1.71, k2 = 0.43, k3 = 8.32, k4 = 0.69, k5 = 0.035, k6 = 8.32, k7 = 280, k8 = 0.69, k9 = 0.69, Oks = 0.0007) parameter <- overrulepar(parameter, parms, 10) prob <- hiresprob() if (is.null(yini)) yini <- hiresinit() checkini(prob$neqn, yini) useres <- FALSE if (is.character(method)) { if (method %in% c("mebdfi", "daspk")) useres <- TRUE } else if("res" %in% names(formals(method))) useres <- TRUE if (useres){ out <- ode(func = "hiresfun", dllname = "deTestSet", initfunc = "hirespar", method = method, atol=atol,rtol=rtol,parms = parameter, y = yini, times = times, ...) }else{ if (prob$numjac) out <- ode(func = "hiresfun", dllname = "deTestSet", initfunc = "hirespar", method = method, atol=atol,rtol=rtol,parms = parameter, y = yini, times = times, ...) else{ fulljac = (prob$mujac == prob$neqn & prob$mljac == prob$neqn) if (fulljac) jactype <- "fullusr" else jactype <- "bandusr" out <- ode(func = "hiresfun", dllname = "deTestSet", initfunc = "hirespar", method = method, atol=atol,rtol=rtol, parms = parameter, y = yini, times = times,jacfunc ="hiresjac", jactype = jactype,...) }} if(printmescd) out <- printpr (out, prob, "hires", rtol, atol) return(out) } hiresprob <- function(){ fullnm <- 'Problem HIRES' problm <- 'hires' type <- 'ODE' neqn <- 8 ndisc <- 500 t <- matrix(1,2) t[1] <- 0 t[2] <- 321.8122 numjac <- FALSE mljac <- neqn mujac <- neqn return(list(fullnm=fullnm, problm=problm,type=type,neqn=neqn,ndisc=ndisc, t=t,numjac=numjac,mljac=mljac,mujac=mujac)) } hiresinit <- function( ){ yini= c(Pr=1, Pfr=0, PrX=0, PfrX=0, PrX2=0, PfrX2=0, PfrX2E=0, E=0.0057) return(yini) }
context("cache_options_get") test_that("cache_options_get - onload conditions", { skip_on_cran() aa <- cache_options_get() expect_is(aa, "list") expect_named(aa, c('cache', 'backend', 'path', 'overwrite')) expect_is(aa$cache, 'logical') expect_is(aa$backend, 'character') expect_is(aa$path, 'character') expect_is(aa$overwrite, 'logical') expect_false(aa$overwrite) expect_match(aa$path, 'R/fulltext') expect_identical(cache_options_set(), aa) }) context("cache_options_set") test_that("cache_options_set - onload conditions", { skip_on_cran() aa <- cache_options_set(path = "foobar") expect_is(aa, "list") expect_named(aa, c('cache', 'backend', 'path', 'overwrite')) expect_match(aa$path, 'R/foobar') bb <- cache_options_set(overwrite = TRUE) expect_true(bb$overwrite) skip_on_os("windows") mypath <- tempdir() cache_options_set(full_path = mypath) cc <- cache_options_get() expect_match(cc$path, mypath) }) test_that("cache_options_set fails well", { skip_on_cran() expect_error(cache_options_set(5), "class character") expect_error(cache_options_set(overwrite = "afd"), "class logical") expect_error(cache_options_set(full_path = 5), "class character") expect_message(cache_options_set("foo", full_path = "bar"), "ignoring") }) invisible(cache_options_set())
getCMCm = function(tree, C) { k = (nrow(tree$edge) + 2)/2 s.cna = nrow(C) CM = matrix(nrow = s.cna, ncol = k, data = 1) rownames(CM) = rownames(C) colnames(CM) = paste("clone", 1:k, sep = "") Cm = CM clonal.cna = vector("list", k) for (tip in 2:k) { child.node = tip parent.node = tree$edge[which(tree$edge[, 2] == child.node), 1] while (parent.node >= (k + 1)) { cnatemp = intersect(which(tree$cna[, 2] == parent.node), which(tree$cna[, 3] == child.node)) if (length(cnatemp) > 0) { clonal.cna[[tip]] = c(clonal.cna[[tip]], cnatemp) } child.node = parent.node if (child.node == (k + 1)) break parent.node = tree$edge[which(tree$edge[, 2] == child.node), 1] } } clonal.cna[[1]] = 0 if(all(apply(C,1,sum)==1)){ Z = matrix(nrow = nrow(tree$cna), ncol = k, data = 0) for (ki in 2:k) { Z[clonal.cna[[ki]], ki] = 1 } CM.temp=as.matrix(tree$cna.copy[1,])%*%rep(1,ncol(Z))*Z Cm.temp=as.matrix(tree$cna.copy[2,])%*%rep(1,ncol(Z))*Z CM[Z==1]=CM.temp[Z==1] Cm[Z==1]=Cm.temp[Z==1] } else{ for (i in 1:nrow(C)) { cnai = which(C[i, ] == 1) cnai = cnai[rank(tree$cna[cnai, 2], ties.method = "random")] for (s in cnai) { for (t in 2:k) { if (is.element(s, clonal.cna[[t]])) { CM[i, t] = tree$cna.copy[1, s] Cm[i, t] = tree$cna.copy[2, s] } } } } } return(list(CM, Cm)) }
library(testthat) library(ggalt) test_check("ggalt")
library(MASS) all_n = 1000 * 10**(0:3) all_rep = 1:10 a = 1 b = 0.05 base_all = array(data.frame(), dim = c(length(all_n), length(all_rep))) for(i in 1:length(all_n)){ cat("i =", i) n = all_n[i] dum_all = list() nb_dum = c(n/20, floor(sqrt(n)), floor(n**.33)) N = nb_dum**3 dum_all[[1]] = sample(nb_dum[1], n, TRUE) dum_all[[2]] = sample(nb_dum[2], n, TRUE) dum_all[[3]] = sample(nb_dum[3], n, TRUE) for(r in all_rep){ cat(".") X1 = rnorm(n) X2 = X1**2 mu = a*X1 + b*X2 for(m in 1:3){ coef_dum = rnorm(nb_dum[m]) mu = mu + coef_dum[dum_all[[m]]] } mu = exp(mu) y = rnegbin(mu, theta = 0.5) base = data.frame(y, X1, ln_y = log(y + 1)) for(m in 1:3){ base[[paste0("dum_", m)]] = dum_all[[m]] } base_all[i, r][[1]] = base } cat("\n") } save(base_all, file = "DATA/base_all_simulations.Rdata") n = 1e7 dum_all = list() nb_dum = c(n/20, floor(sqrt(n)), floor(n**.33)) N = nb_dum**3 dum_all[[1]] = sample(nb_dum[1], n, TRUE) dum_all[[2]] = sample(nb_dum[2], n, TRUE) dum_all[[3]] = sample(nb_dum[3], n, TRUE) X1 = rnorm(n) X2 = X1**2 mu = a*X1 + b*X2 for(m in 1:3){ coef_dum = rnorm(nb_dum[m]) mu = mu + coef_dum[dum_all[[m]]] } mu = exp(mu) y = rnegbin(mu, theta = 0.5) base = data.frame(ln_y = log(y + 1), X1) for(m in 1:3){ base[[paste0("dum_", m)]] = dum_all[[m]] } fwrite(base, "DATA/base_10M.csv") load( "DATA/base_all_simulations.Rdata") library(haven) for(size in 1:4){ for(replication in 1:10){ cat(".") stata_name = paste0("_STATA/base_s", size, "_r", replication, ".dta") write_dta(as.data.frame(base_all[size, replication]), stata_name) } } set.seed(1) base_all_diff = list() for(pow in 4:7){ cat(".") n = 10**pow nb_indiv = n/20 nb_firm = round(n/160) nb_year = round(n**.3) id_indiv = sample(1:nb_indiv, n, TRUE) id_firm = pmin(sample(0:20, n, TRUE) + pmax(1, id_indiv %/% 8 - 10), nb_firm) id_year = sample(nb_year, n, TRUE) x1 = 5 * cos(id_indiv) + 5 * sin(id_firm) + 5 * sin(id_year) + runif(n) x2 = cos(id_indiv) + sin(id_firm) + sin(id_year) + rnorm(n) y= 3 * x1 + 5 * x2 + cos(id_indiv) + cos(id_firm)^2 + sin(id_year) + rnorm(n) df = data.frame(id_indiv = id_indiv, id_firm = id_firm, id_year = id_year, x1 = x1, x2 = x2, y = y) base_all_diff[[length(base_all_diff) + 1]] = df if(pow < 7){ stata_name = paste0("_STATA/base_diff_e", pow, ".dta") haven::write_dta(df, stata_name) } } save(base_all_diff, file = "DATA/base_all_diff.Rdata")
test.MA <- function() { x <- rnorm(100L); myMA <- numeric(length(x)); order <- 5L for (i in order:length(x)) myMA[i] <- sum(x[(i - order + 1):i])/order checkEquals(MA(x, order = order)[-(1:(order-1))], myMA[-(1:(order-1))]) x <- rnorm(100L); myMA <- numeric(length(x)); order <- 1L checkEquals(x, MA(x, order = order)) checkEquals(x, MA(x, order = order, pad = NA)) }
extremophileDis<-function() { angz<-c(0, 9.0, 18.0, 27.0, 36.0, 45.0, 54.0, 63.0, 72.0, 81.0, 90.0) sDis<-0 pi180<-pi/180.0 extremophileLAD<-function(LeafAngle) { 2*(1-cos(4*LeafAngle))/pi } for(i in 1:(length(angz)-1)) { fraction<-integrate(extremophileLAD, lower=angz[i]*pi180, upper=angz[i+1]*pi180) sDis[i]<-fraction[[1]] } sDis }
test_that("bind_dimensions_n.mcmcarray", { expect_identical(bind_dimensions_n(mcmcr_example$beta), mcmcr_example$beta) expect_identical( pdims(bind_dimensions_n(mcmcr_example$beta, mcmcr_example$beta, mcmcr_example$beta)), c(2L, 2L, 3L) ) }) test_that("bind_dimensions_n.mcmcr", { expect_identical(bind_dimensions_n(mcmcr_example), mcmcr_example) expect_identical( pdims(bind_dimensions_n(mcmcr_example, mcmcr_example, mcmcr_example)), list(alpha = c(2L, 3L), beta = c(2L, 2L, 3L), sigma = c(1L, 3L)) ) })
print.pstest <- function(x, ...){ if(x$argu$w == "ind") ww <- "Indicator function: w(q,u) = 1(q<=u)" if(x$argu$w == "exp") ww <- "Exponential function: w(q,u) = exp(qu)" if(x$argu$w == "logistic") ww <- "Logistic function: w(q,u) = 1/[1+exp(-qu)]" if(x$argu$w == "sin") ww <- "Sine function: w(q,u) = sin(qu)" if(x$argu$w == "sincos") ww <- "Sine and cosine function: w(q,u) = sin(qu)+ cos(qu)" distt <- x$argu$dist if(distt == "Mammen") distt <- "Mammen's" header <- c("", "Test statistic", "Bootstrapped P-value") body <- cbind(c("Kolmogorov-Smirnov", "Cramer-von Mises"), c(round(x$kstest, digits = 4), round(x$cvmtest, digits = 4)), c(round(x$pvks, digits = 4), round(x$pvcvm, digits = 4))) colnames(body) <- header cat(" Call:\n") print(x$call) cat("\n Sant'Anna and Song (2016) specification tests for the propensity score:\n") print.matrix1(rbind(header, body)) cat(" -------------------------------------------------------------------------") cat("\n Weight function:", "\t \t", ww) cat("\n Number of boostrap draws:", "\t", x$argu$nboot) cat("\n Boostrap draws from", distt, 'distribution') }
test_that("KP - Get foul trouble", { skip_on_cran() x <- kp_foul_trouble(min_year = 2020, max_year = 2020) cols <- c( "team", "conf", "two_foul_particpation_pct", "two_foul_particpation_pct_rk", "adj2fp", "adj2fp_rk", "two_foul_total_time", "two_foul_total_time_rk", "two_foul_time_on", "two_foul_time_on_rk", "bench_pct", "bench_pct_rk", "ncaa_seed", "year" ) expect_equal(colnames(x), cols) expect_s3_class(x, 'data.frame') })
ranges_espace <- function(..., add_occurrences = TRUE, variables, do_pca = FALSE, max_background = 10000, occurrence_color = "blue", range_colors = NULL, alpha = 0.6, legend = TRUE, verbose = TRUE) { if (missing(...)) { stop("Argument '...' is necessary to perform the analysis.") } else { ranges <- list(...) if (length(ranges) < 1) { stop("At least one sp_range* object is needed to produce plots.") } if (length(ranges) > 5) { stop("Only 5 sp_range* objects can be plotted at the time.") } cls <- sapply(ranges, function(x) {class(x)[1]}) if (any(!cls %in% c("sp_range", "sp_range_iucn", "sp_range_iucnextra"))) { stop("All objects to be plotted must be of class sp_range*.") } } if (missing(variables)) { stop("Argument 'variables' must be defined. See function's help for details.") } else { if (raster::nlayers(variables) < 3) { stop("At least three 'variables' are required.") } } WGS84 <- ranges[[1]]@species_range@proj4string sp_ranges <- lapply(ranges, function(x) {x@species_range}) rnames <- sapply(ranges, function(x) {x@name}) if (add_occurrences == TRUE) { if (any(cls %in% c("sp_range_iucn", "sp_range_iucnextra"))){ wh <- which(cls %in% c("sp_range_iucn", "sp_range_iucnextra"))[1] sp_records <- ranges[[wh]]@species_unique_records pdata <- na.omit(cbind(sp_records@data[, 2:3], raster::extract(variables, sp_records))) } else { add_occurrences <- FALSE sp_records <- NULL if (verbose == TRUE) { message("None of the objects contain occurrences.") } } } else { sp_records <- NULL } variables <- raster::projectRaster(variables, crs = WGS84@projargs) vdata <- raster::rasterToPoints(variables) if (nrow(vdata) > max_background) { vdata <- vdata[sample(nrow(vdata), max_background), ] } nr <- nrow(vdata) nc <- ncol(vdata) if (add_occurrences == TRUE) { colnames(vdata)[1:2] <- colnames(pdata)[1:2] vdata <- rbind(vdata, pdata) } else { vdata <- vdata } if (do_pca == TRUE) { vdata <- data.frame(vdata[, 1:2], prcomp(vdata[, 3:nc], center = TRUE, scale = TRUE)$x[, 1:3]) vnam <- c("PC 1", "PC 2", "PC 3") } else { if (verbose == TRUE) { if ((nc - 2) > 3) { message("Using only the three first variables\n") } } vnam <- gsub("_", " ", colnames(vdata)[3:5]) } nc <- 5 if (add_occurrences == TRUE) { pc_occ <- vdata[(nr - nrow(pdata) + 1):nrow(vdata), 3:nc] } vdata <- sp::SpatialPointsDataFrame(coords = vdata[, 1:2], data = as.data.frame(vdata[, 1:nc]), proj4string = WGS84) if (verbose == TRUE) { message("Getting environmental conditions inside ranges, please wait...") } env_ranges <- lapply(sp_ranges, function(x) {vdata[x, ]@data}) if (is.null(range_colors)) { colors <- c("black", "green", "red", "blue", "purple") }else { colors <- range_colors } if (verbose == TRUE) { message("\nCreating interactive visualization...\n") } if (add_occurrences == TRUE) { rgl::plot3d(pc_occ[, 1:3], col = occurrence_color, size = 6, xlab = vnam[1], ylab = vnam[2], zlab = vnam[3]) ad <- TRUE }else { ad <- FALSE } ellipsoides <- lapply(1:length(env_ranges), function(x) { centroid <- apply(env_ranges[[x]][, 3:nc], 2, mean) cov_mat <- cov(env_ranges[[x]][, 3:nc]) ell <- rgl::ellipse3d(cov_mat, centre = centroid, level = 0.99) adt <- ifelse(x == 1, ad, TRUE) rgl::wire3d(ell, col = colors[x], alpha = alpha, xlab = vnam[1], ylab = vnam[2], zlab = vnam[3], add = adt) if (x == 1 & add_occurrences == FALSE) { rgl::axes3d(box = T) rgl::title3d(xlab = vnam[1], ylab = vnam[2], zlab = vnam[3]) } }) if (legend == TRUE) { rgl::legend3d("topright", legend = rnames, lty = 1, inset = 0.02, col = colors[1:length(ranges)], bty = "n") } rgl::aspect3d(1, 1, 1) }
make.partial.C = function(rows, cols, index){ x=matrix(0, nrow = rows, ncol = cols) for(i in index){ x[i-1, i] = 1 } return(x) }
context("'collect' on CrunchDataset") test_that("transfer groups between datasets", { grouped_df <- group_by(mtcars, cyl, wt) df2 <- mtcars %>% select(-gear) %>% transfer_groups(grouped_df) expect_identical(group_vars(df2), group_vars(grouped_df)) }) with_mock_crunch({ ds <- loadDataset("test ds") test_that("collect generates expected POST request", { expect_POST( ds %>% select(gender, birthyr) %>% collect(), 'https://app.crunch.io/api/datasets/1/export/csv/', '{"filter":null,"where":{"function":"select","args":[{"map":{"66ae9881e3524f7db84970d556c34552":{"variable":"https://app.crunch.io/api/datasets/1/variables/gender/"},"f78ca47313144b57adfb495893968e70":{"variable":"https://app.crunch.io/api/datasets/1/variables/birthyr/"}}}]},"options":{"use_category_ids":true}}' ) }) test_that("collect on grouped dataset", { expect_POST( ds %>% select(gender, birthyr) %>% group_by(gender) %>% collect(), 'https://app.crunch.io/api/datasets/1/export/csv/', '{"filter":null,"where":{"function":"select","args":[{"map":{"66ae9881e3524f7db84970d556c34552":{"variable":"https://app.crunch.io/api/datasets/1/variables/gender/"},"f78ca47313144b57adfb495893968e70":{"variable":"https://app.crunch.io/api/datasets/1/variables/birthyr/"}}}]},"options":{"use_category_ids":true}}' ) }) ds3 <- loadDataset("ECON.sav") test_that("collect can pull hidden variables", { expect_POST( ds3 %>% select(gender, birthyr) %>% collect(), 'https://app.crunch.io/api/datasets/3/export/csv/', '{"filter":null,"where":{"function":"select","args":[{"map":{"66ae9881e3524f7db84970d556c34552":{"variable":"https://app.crunch.io/api/datasets/3/variables/gender/"},"f78ca47313144b57adfb495893968e70":{"variable":"https://app.crunch.io/api/datasets/3/variables/birthyr/"}}}]},"options":{"use_category_ids":true}}' ) }) test_that("collect doesn't affect dplyr methods", { expect_identical(mtcars, collect(mtcars)) }) })
`bsjktest.formula` <- function(x, data, index=NULL, listw, test=c("C.1","C.2","C.3","J"), ...){ if("listw" %in% class(listw)) { w <- listw2mat(listw) } else { w <- listw } if(!("pdata.frame" %in% class(data))) { data <- pdata.frame(data, index) } gindex <- dimnames(data)[[2]][1] tindex <- dimnames(data)[[2]][2] switch(match.arg(test), C.1 = { bsjk = pbsjkSDtest(formula=x, data=data, w=w, index=index, ...) }, C.2 = { bsjk = pbsjkARtest(formula=x, data=data, w=w, index=index, ...) }, C.3 = { bsjk = pbsjkREtest(formula=x, data=data, w=w, index=index, ...) }, J = { bsjk = pbsjkJtest(formula=x, data=data, w=w, index=index, ...) }) return(bsjk) }
source("ESEUR_config.r") rt=read.csv(paste0(ESEUR_dir, "economics/SSRN-id1028592.csv.xz"), as.is=TRUE) rt20=subset(rt, basemultiple < 15) plot(density(rt20$basemultiple, na.rm=TRUE, from=0), xlab="ROI", ylab="Density\n")
read.dsm.matrix <- function (file, format=c("word2vec"), encoding="UTF-8", batchsize=1e6, verbose=FALSE) { format <- match.arg(format) if (is.character(file)) { file <- file(file, "r", encoding=encoding) on.exit(close(file)) } else { if (!inherits(file, "connection")) stop("'file' must be a character string or connection") if (!isOpen(file, "r")) { open(file, "r") on.exit(close(file)) } } if (format == "word2vec") { info <- read.table(file, header=FALSE, quote="", comment.char="", colClasses="integer", col.names=c("nR", "nC"), nrows=1) if (!(info$nR > 0 && info$nC > 0)) stop("format error in 'word2vec' file") if (as.double(info$nR) * info$nC > 2147483647) stop(sprintf("%d x %d matrix is too large for R", info$nR, info$nC)) batch.lines <- max(round(batchsize / info$nC), 10) col.classes <- c("character", rep("double", info$nC)) M <- matrix(0, info$nR, info$nC) row.names <- character(info$nR) n.total <- 0 if (verbose) { pb <- txtProgressBar(0, info$nR, style=3) on.exit(close(pb), add=TRUE) } while (n.total < info$nR) { A <- as.matrix(read.table(file, header=FALSE, quote="", comment.char="", na.strings=c(), colClasses=col.classes, row.names=1, nrows=batch.lines)) if (ncol(A) != info$nC) stop(sprintf("format error in 'word2vec' file -- expected %d-dim vector, but got %d columns", info$nC, ncol(A))) nR <- nrow(A) if (nR < 1) stop(sprintf("read error in 'word2vec' file -- expecting to read %d further rows", info$nR - n.total)) if (n.total + nR > info$nR) stop("format error in 'word2vec' file -- too many rows") idx <- seq(n.total + 1, n.total + nR) M[idx, ] <- A row.names[idx] <- rownames(A) n.total <- n.total + nR if (verbose) setTxtProgressBar(pb, n.total) } structure(M, dimnames=list(row.names, NULL)) } else stop(sprintf("internal error -- unsupported format '%s'", format)) }
'Objects in R' 'R allows to save the data by storing it inside an R object.' 'What’s an object? It is just a name that you can use to call up stored data. For example, you can save data into an object like a or b.' a <- 5 a 'How to create an Object in R?' 'To create an R object, choose a name and then use the less-than symbol, <, followed by a minus sign, -, to save data into it. This combination looks like an arrow, <-. R will make an object, give it your name, and store in it whatever follows the arrow.' 'When you ask R what’s in a, it tells you on the next line. For example:' die <- 1:6 die 'You can name an object in R almost anything you want, but there are a few rules. First, a name cannot start with a number. Second, a name cannot use some special symbols, like ^, !, $, @, +, -, /, or *:' 'R also understands capitalization (or is case-sensitive), so name and Name will refer to different objects. You can see which object names you have already used with the function ls().'
tabPanel('RFM', value = 'tab_rfm', icon = icon('sitemap'), navlistPanel(id = 'navlist_rfm', well = FALSE, widths = c(2, 10), source('ui/ui_rfm_score_transaction.R', local = TRUE)[[1]], source('ui/ui_rfm_customer_1.R', local = TRUE)[[1]], source('ui/ui_rfm_customer_2.R', local = TRUE)[[1]], source('ui/ui_rfm_heat_map.R', local = TRUE)[[1]], source('ui/ui_rfm_bar_chart.R', local = TRUE)[[1]], source('ui/ui_rfm_histogram.R', local = TRUE)[[1]], source('ui/ui_rfm_scatter_plot.R', local = TRUE)[[1]] ) )
NULL is_tabular <- function(x) { if (is.matrix(x) | is.data.frame(x)) { TRUE } else FALSE } is_numeric_tabular <- function(x) { if (is_numeric_matrix(x) | is_numeric_dataframe(x)) { TRUE } else FALSE } is_string_tabular <- function(x) { if (is_string_matrix(x) | is_string_dataframe(x)) { TRUE } else FALSE } is_not_tabular <- function(x) { !is_tabular(x) }
library("netregR") data("wolf") vlist <- list(wolf$wolf_age_diff, wolf$wolf_same_sex, Y=wolf$wolf) r <- inputs_lmnet(vlist) X <- r$X ; colnames(X) <- c("Intercept", "age_diff", "same_sex") fit <- lmnet(r$Y, X) summary(fit) plot(fit) summary(lm(r$Y ~ X - 1)) range(vnet(e=resid(fit), X=model.matrix(fit))$vhat - vcov(fit)) range(vnet(fit=fit)$vhat - vcov(fit)) fitgls <- lmnet(r$Y, X, reweight=T) cat("Converged?:", fitgls$converged, "\nNumber of iterations:", fitgls$nit) coeftable <- cbind(coef(lm(r$Y ~ X - 1)), coef(fitgls)) colnames(coeftable) <- c("OLS", "GLS") knitr::kable(round(coeftable, 4), caption="Coefficients for OLS and GLS fits of complete, directed data.") see <- sqrt(diag( vcov(fitgls) )) sedc <- sqrt(diag( vnet(fit=fitgls, type="dyadic clustering")$vhat )) setable <- data.frame( "exchangeable"=see, "dyadic_clustering"=sedc ) knitr::kable(round(setable, 4), caption="Standard errors of GLS coefficient estimates based on complete, directed data.") wolf_undir <- .5*(wolf$wolf + t(wolf$wolf)) vlist <- list(abs(wolf$wolf_age_diff), wolf$wolf_same_sex, Y=wolf_undir) ru <- inputs_lmnet(vlist, directed=F) X <- ru$X ; colnames(X) <- c("Intercept", "abs_age_diff", "same_sex") fit <- lmnet(ru$Y, X, directed=F, reweight=T) summary(fit) Y <- wolf$wolf Y[which(wolf_undir == 0)] <- NA r <- inputs_lmnet(list(wolf$wolf_age_diff, wolf$wolf_same_sex, Y=Y)) X <- r$X ; colnames(X) <- c("Intercept", "abs_age_diff", "same_sex") scramble <- sample(1:nrow(X)) fit <- lmnet(r$Y, X, nodes=r$nodes, reweight=T) fit1 <- lmnet(r$Y[scramble], X[scramble,], nodes=r$nodes[scramble,], reweight=T) range(coef(fit) - coef(fit1)) summary(fit) data("interactions") temp <- inputs_lmnet(Xlist=list(Y=interactions$interactions, X1=interactions$xbinary, X2=interactions$xabs), directed = TRUE, add_intercept=TRUE, time_intercept = TRUE) fit1 <- lmnet(temp$Y, temp$X, directed=TRUE, tmax=5, nodes=temp$nodes, reweight=FALSE, type="ind") fit2 <- lmnet(temp$Y, temp$X, directed=TRUE, tmax=5, nodes=temp$nodes, reweight=FALSE, type="exch") fit3 <- lmnet(temp$Y, temp$X, directed=TRUE, tmax=5, nodes=temp$nodes, reweight=TRUE, type="ind") fit4 <- lmnet(temp$Y, temp$X, directed=TRUE, tmax=5, nodes=temp$nodes, reweight=TRUE, type="exch") timetable <- round(cbind(coef(fit1), coef(fit2), coef(fit3), coef(fit4)), 4) signifs <- cbind( summary(fit1)$coef[,4] < .05, summary(fit2)$coef[,4] < .05, summary(fit3)$coef[,4] < .05, summary(fit4)$coef[,4] < .05) signif_coefs <- rep("*", length(signifs)) signif_coefs[!signifs] <- "" esttable <- matrix(paste0(timetable, signif_coefs), ncol=ncol(timetable)) rownames(esttable) <- c(paste0("intercept ", c("school", "friends", "family", "significant others", "popular culture")), "xbinary", "xabs") colnames(esttable) <- c("OLS/ind", "OLS/exch", "GLS/ind", "GLS/exch") knitr::kable(esttable, caption="Estimated coefficients for the multiple network observation. `*' indicates a p-value less than 0.05.") n <- 10 phi1 <- rphi(n, seed=1) phi2 <- rphi(n, seed=1, phi6=T) O1 <- build_exchangeable_matrix(n, phi1) min(eigen(O1)$values) > 0 p1 <- invert_exchangeable_matrix(n, phi1) p2 <- invert_exchangeable_matrix(n, phi2) I1 <- O1 %*% build_exchangeable_matrix(n, p1) range(I1 - diag(nrow(I1))) I2 <- build_exchangeable_matrix(n, phi2) %*% build_exchangeable_matrix(n, p2) range(I2 - diag(nrow(I2)))
library(gridGraphics) pairs1 <- function() { pairs(iris[1:4], main = "Anderson's Iris Data -- 3 species", pch = 21, bg = c("red", "green3", "blue")[unclass(iris$Species)]) } pairs2 <- function() { pairs(~ Fertility + Education + Catholic, data = swiss, subset = Education < 20, main = "Swiss data, Education < 20") } pairs3 <- function() { pairs(USJudgeRatings) } pairs4 <- function() { pairs(USJudgeRatings, text.panel = NULL, upper.panel = NULL) } pairs5 <- function() { panel.hist <- function(x, ...) { usr <- par("usr"); on.exit(par(usr)) par(usr = c(usr[1:2], 0, 1.5) ) h <- hist(x, plot = FALSE) breaks <- h$breaks; nB <- length(breaks) y <- h$counts; y <- y/max(y) rect(breaks[-nB], 0, breaks[-1], y, col = "cyan", ...) } pairs(USJudgeRatings[1:5], panel = panel.smooth, cex = 1.5, pch = 24, bg = "light blue", diag.panel = panel.hist, cex.labels = 2, font.labels = 2) } pairs6 <- function() { panel.cor <- function(x, y, digits = 2, prefix = "", cex.cor, ...) { usr <- par("usr"); on.exit(par(usr)) par(usr = c(0, 1, 0, 1)) r <- abs(cor(x, y)) txt <- format(c(r, 0.123456789), digits = digits)[1] txt <- paste0(prefix, txt) if(missing(cex.cor)) cex.cor <- 0.8/strwidth(txt) text(0.5, 0.5, txt, cex = cex.cor * r) } pairs(USJudgeRatings, lower.panel = panel.smooth, upper.panel = panel.cor) } pairs7 <- function() { pairs(iris[-5], log = "xy") } pairs8 <- function() { pairs(iris, log = 1:4, main = "Lengths and Widths in [log]", line.main=1.5, oma=c(2,2,3,2)) } plotdiff(expression(pairs1()), "pairs-1", width=10, height=10) plotdiff(expression(pairs2()), "pairs-2") plotdiff(expression(pairs3()), "pairs-3", width=15, height=15) plotdiff(expression(pairs4()), "pairs-4", width=15, height=15) plotdiff(expression(pairs5()), "pairs-5") plotdiff(expression(pairs6()), "pairs-6", width=15, height=15, antialias=FALSE) plotdiff(expression(pairs7()), "pairs-7", width=10, height=10) plotdiff(expression(pairs8()), "pairs-8", width=12, height=12) plotdiffResult()
ql <- function(x, ...) { UseMethod("ql", x) } ql.ql <- function(x, ...) { pipe_autoexec(toggle = FALSE) make_query(x) } ql.character <- function(x, ..., flags = jq_flags()) { query <- query_from_dots(...) structure(jqr(x, query, flags), class = c("jqson", "character")) } ql.default <- function(x, ...) { stop(sprintf("ql method not implemented for ", class(x)), call. = FALSE) } print.ql <- function(x, ...) { cat(jsonlite::prettify(combine(x))) } query_from_dots <- function(...) { dots <- list(...) if (!all(vapply(dots, is.character, logical(1)))) stop("jq query specification must be character.", call. = FALSE) paste(unlist(dots), collapse = " | ") } make_query <- function(x) { paste0(pop(x), collapse = " | ") }
library(fracdiff) if(FALSE) { data(npext, package = "urca") realgnp2 <- npext[50:129, "realgnp"] } else { realgnp2 <- c(4.7604631, 4.7883247, 4.8138091, 4.8690717, 4.8782461, 4.8331023, 4.8243057, 4.9000761, 4.9067552, 5.0225639, 4.9863426, 4.9416424, 4.8504665, 4.9972123, 5.1113852, 5.1089712, 5.1896179, 5.2470241, 5.2459709, 5.2517497, 5.3161573, 5.2122147, 5.1316723, 4.9712012, 4.9522997, 5.0388988, 5.1328529, 5.2626902, 5.3141907, 5.2621719, 5.3442463, 5.4258307, 5.5748121, 5.6964221, 5.8203796, 5.8897086, 5.872681, 5.7449244, 5.7362497, 5.7798172, 5.7810521, 5.8729625, 5.9490788, 5.9791389, 6.0229632, 6.0088132, 6.0822189, 6.1005431, 6.1147878, 6.1032295, 6.1652077, 6.1897005, 6.2089924, 6.2724996, 6.3117348, 6.3649229, 6.4261648, 6.4893569, 6.5150089, 6.5604647, 6.5857578, 6.5792512, 6.6067, 6.6552832, 6.705961, 6.700553, 6.687906, 6.7356178, 6.781224, 6.8328012, 6.8572808, 6.8556192, 6.8747935, 6.8489768, 6.8840768, 6.9496707, 6.9826227, 7.0096668, 7.0455416, 7.0888837) } fr1 <- fracdiff(realgnp2, nar = 0, nma = 0, M = 100) fr1 summary(fr1)
test_that("cusum_single works", { test_vec <- c(0.175, 0.152, 0.15, 0.207, 0.136, 0.212, 0.166) expected_res <- c(0.1750000, 0.1558571, 0.1347143, 0.1705714, 0.1354286, 0.1762857, 0.1711429) expected_res <- round(expected_res,6) func_res <- cusum_single(test_vec) func_res <- round(func_res,6) expect_equal(func_res, expected_res) }) test_that("target replaces mean and gives expected results", { test_vec2 <- c(0.175, 0.152, 0.15, 0.207, 0.136, 0.212, 0.166) expected_res2 <- c(0.175, 0.167, 0.157, 0.204, 0.180, 0.232, 0.238) func_res2 <- cusum_single(test_vec2, target = 0.16) expect_equal(func_res2, expected_res2) }) test_that("non numeric vector fails", { test_vec3 <- as.character(c(0.175, 0.152, 0.15, 0.207, 0.136, 0.212, 0.166)) expect_error(cusum_single(test_vec3, target = 0.16)) }) test_that("na elements fail", { test_vec3 <- c(0.175, NA, 0.15, 0.207, 0.136, NA, 0.166) expect_error(cusum_single(test_vec3, target = 0.16)) })
base2Geno <- function (baseData = NULL, allele.matrix = NULL) { if (nrow(baseData) == ncol(allele.matrix)) allele.matrix <- t(allele.matrix) if (nrow(baseData) != nrow(allele.matrix)) stop("nrow(baseData)!=nrow(allele.matrix), allele.matrix error!!!") genoData <- baseData genoData[baseData == allele.matrix[, 1]] <- 1 genoData[baseData == allele.matrix[, 2]] <- -1 genoData[is.na(genoData)] <- 0 genoData <- matrix(as.numeric(genoData), ncol = ncol(genoData)) dimnames(genoData) <- dimnames(baseData) genoData }
context("apa_print() for MANOVA") test_that( "Two-way MANOVA: apa_print.manova and apa_print.summary.manova" , { set.seed(42) data <- npk data$yield2 <- as.integer(data$N) * 2 + rnorm(n = nrow(data), sd = 2) x1 <- manova(formula = cbind(yield, yield2) ~ N * P, data = data) x2 <- summary(x1, test = "Wilks") out1 <- apa_print(x1) out3 <- apa_print(x1, test = "H") out4 <- apa_print(x1, test = "R", in_paren = TRUE) expect_identical( object = out1$statistic$N , expected = "$V = 0.25$, $F(2, 19) = 3.22$, $p = .062$" ) expect_identical( object = out3$full_result$P , expected = "$T = 0.02$, $F(2, 19) = 0.20$, $p = .821$" ) expect_identical( object = out4$statistic$N , expected = "$\\theta = 0.34$, $F[2, 19] = 3.22$, $p = .062$" ) expect_identical( object = variable_labels(out3$table) , expected = list( Effect = "Effect" , hl = "$T$" , `F` = "$F$" , df1 = "$\\mathit{df}_1$" , df2 = "$\\mathit{df}_2$" , p = "$p$" ) ) expect_identical( object = class(out1$table) , expected = c("apa_results_table", "data.frame") ) } ) test_that( "Anova.mlm from MANOVA not supported" , { set.seed(42) data <- npk data$yield2 <- as.integer(data$N) * 2 + rnorm(n = nrow(data), sd = 2) expect_error( apa_print(car::Manova(manova(formula = cbind(yield, yield2) ~ N * P, data = data), type = 3)) , fixed = TRUE , regexp = "Anova.mlm objects from car::Manova are not supported, yet. Visit https://github.com/crsh/papaja/issues to request support for this class. You can try using stats::manova instead if Type I oder Type II sums of squares are adequate for your analysis." ) } )
context("maps tidiers") skip_on_cran() skip_if_not_installed("modeltests") library(modeltests) skip_if_not_installed("maps") ca <- maps::map("county", "ca", plot = FALSE, fill = TRUE) test_that("tidy.map", { check_arguments(tidy.map) td <- tidy(ca) check_tidy_output(td, strict = FALSE) check_dims(td, expected_cols = 7) })
gibsDependency <- function() { list( htmltools::htmlDependency( "lfx-gibs", version = "1.0.0", src = system.file("htmlwidgets/lfx-gibs", package = "leaflet.extras2"), script = c( "GIBSLayer.js", "GIBSMetadata.js", "gibs-bindings.js") ) ) } addGIBS <- function(map, layers = NULL, group = NULL, dates = NULL, opacity = 0.5, transparent = TRUE) { if (is.null(layers)) stop("You must define one or multiple `layers`.\n", "See `gibs_layers` for a list of all available layers and their attributes.") if (is.null(dates)) stop("You must define one or multiple `dates` for each layer.") if (!all(layers %in% gibs_layers$title)) { stop("The layer is not valid. Did you mean: `", gibs_layers$title[which.min(adist(layers, gibs_layers$title))], "`?\n", "If not, please see `gibs_layers` for a list of all available layers and their attributes.") } lenlay = length(layers) if (lenlay > 1) { seqlen <- seq.int(lenlay) if (lenlay != length(group)) { group <- rep(group, lenlay)[seqlen] } if (lenlay != length(dates)) { dates <- rep(dates, lenlay)[seqlen] } if (lenlay != length(opacity)) { opacity <- rep(opacity, lenlay)[seqlen] } if (lenlay != length(transparent)) { transparent <- rep(transparent, lenlay)[seqlen] } } map$dependencies <- c(map$dependencies, gibsDependency()) invokeMethod(map, getMapData(map), "addGIBS", layers, group, dates, opacity, transparent) } setDate <- function(map, layers = NULL, dates = NULL) { if (is.null(layers)) stop("You must define one or multiple `layers`.\n", "See `gibs_layers` for a list of all available layers and their attributes.") if (is.null(dates)) stop("You must define one or multiple `dates`.") invokeMethod(map, NULL, "setDate", layers, dates) } setTransparent <- function(map, layers = NULL, transparent = TRUE) { if (is.null(layers)) stop("You must define one or multiple `layers`.\n", "See `gibs_layers` for a list of all available layers and their attributes.") invokeMethod(map, NULL, "setTransparent", layers, transparent) }
mmpcbackphase <- function(target, dataset, max_k = 3, threshold = 0.05, test = NULL, wei = NULL, R = 1 ) { d <- NCOL(dataset) met <- 1:d counter <- 0 if (R == 1) { threshold = log(threshold) if (d == 1) { tes <- test(target, dataset, 1, 0, wei = wei) pv <- tes$pvalue counter <- 1 if ( pv > threshold ) met <- 0 pvalue <- pv } else if ( d == 2 ) { tes1 <- test(target, dataset, 1, 2, wei = wei) tes2 <- test(target, dataset, 2, 1, wei = wei) pv1 <- tes1$pvalue pv2 <- tes2$pvalue counter <- 2 if ( pv1 > threshold ) met[1] <- 0 if ( pv2 > threshold ) met[2] <- 0 pvalue <- c(pv1, pv2) } else { pvalue <- 0 for (i in 1:d) { k <- 0 pval <- -5 b <- 0 while ( k < d - 1 & k < max_k & pval < threshold ) { k <- k + 1 ze <- combn(d, k) rem <- which(ze == i,arr.ind = TRUE)[, 2] ze <- ze[, -rem, drop = FALSE] j <- 0 while ( j < dim(ze)[2] & pval < threshold ) { j <- j + 1 tes <- test(target, dataset, i, ze[, j], wei = wei) pval <- tes$pvalue b[j] <- pval counter <- counter + 1 } } if ( pval > threshold ) met[i] <- 0 pvalue[i] <- max(b) } } } else { if (d == 1) { tes <- test(target, dataset, 1, 2, wei = wei, threshold = threshold, R = R) pv <- tes$pvalue counter <- 1 if ( pv > threshold ) met <- 0 pvalue <- pv } else if ( d == 2 ) { tes1 <- test(target, dataset, 1, 2, wei = wei, threshold = threshold, R = R) tes2 <- test(target, dataset, 2, 1, wei = wei, threshold = threshold, R = R) pv1 <- tes1$pvalue pv2 <- tes2$pvalue counter <- 2 if ( pv1 > threshold ) met[1] <- 0 if ( pv2 > threshold ) met[2] <- 0 pvalue <- c(pv1, pv2) } else { pvalue <- 0 for (i in 1:d) { k <- 0 pval <- 0 b <- 0 while ( k < d - 1 & k < max_k & pval < threshold ) { k <- k + 1 ze <- combn(d, k) rem <- which(ze == i,arr.ind = TRUE)[, 2] ze <- ze[, -rem, drop = FALSE] j <- 0 while ( j < dim(ze)[2] & pval < threshold ) { j <- j + 1 tes <- test(target, dataset, i, ze[, j], wei = wei, threshold = threshold, R = R) pval <- tes$pvalue b[j] <- pval counter <- counter + 1 } } if ( pval > threshold ) met[i] <- 0 pvalue[i] <- max(b) } } } list(met = met, counter = counter, pvalues = pvalue) }
WeakRankNorm<-function(K){ if(missing(K)) stop("Need to specify the number K of best instances.") Family( ngradient=function(y,f) NULL, loss=function(y,f){ if(missing(f)|missing(y)) stop("Need two vectors.") if(length(y)!=length(f)) stop("Objects lengths must be identical.") if(K!=round(K)) stop("K must be an integer.") if(K<=0) stop("K must be positive.") if(K>length(y)) stop("K must not be higher than the length of the vectors.") if(K==length(y)) warning("You are using K=n. The weak ranking loss will not produce a reasonable result.") indy<-order(y,decreasing=TRUE) indf<-order(f,decreasing=TRUE) s<-sum(indf[1:K]%in%indy[1:K]) return((K-s)/K) }, offset=function(y,f) NULL, name="Weak ranking family" )}
criteria.after.split.calculator <- function(x.node = data.frame(), y.new.node = c(), split.record = kidids_split(), entropy = TRUE){ ent.status <- entropy criteria.x.node <- criteria.calculator(x.node, y.new.node, ent.status)$criteria unique.length.split.record <- length(unique(split.record)) if(!(dim(x.node)[1] > 1) || !(dim(x.node)[2] >= 1) || is.null(dim(x.node))){ stop("Invalid dimension for x.node") } if(!(length(y.new.node) > 1) || is.null(y.new.node)){ stop("Invalid length for the y.new.node") } if(!(dim(x.node)[1] == length(y.new.node))){ stop("The number of observations in x.node and y.new.node do not match") } if(is.null(split.record)){ stop("'split.record' (kikids_split object) has to be provided as a parameter") } if(!is.boolean(entropy)){ stop("The parameter 'entropy' has to be either TRUE or FALSE") } if(!(unique.length.split.record == 1 || unique.length.split.record == 2)){ stop("Error in 'split.record': the number of splits is not 1 or 2") } if(unique.length.split.record == 2){ length.split.record <- length(split.record) split.record.level <- levels(as.factor(split.record)) length.split.record.level <- length(split.record.level) criteria.vec <- rep(0, length.split.record.level) n.vec <- rep(0, length.split.record.level) for (z in 1:length.split.record.level){ n.vec[z] <- length(which(split.record %in% as.numeric(c(split.record.level[z])))) y.new.split.record <- y.new.node[which(split.record %in% as.numeric(c(split.record.level[z])))] vec.levels <- unique(y.new.split.record) vec2 <- rep(0, length(unique(y.new.split.record))) for (p in 1:(length(unique(y.new.split.record)))){ vec2[p] <- sum(y.new.split.record %in% vec.levels[p]) } prop <- vec2/n.vec[z] if (ent.status == TRUE){ criteria <- 0 for (y in 1:(length(prop))){ criteria2<- -prop[y] * ifelse(prop[y] > 0, log2(prop[y]), 0) criteria <- criteria + criteria2 } criteria.vec[z] <- criteria } else {criteria.vec[z] <- 1-sum((prop)^2)} } criteria.after.split <- criteria.vec[1] * n.vec[1] / (sum(n.vec)) + criteria.vec[2] * n.vec[2] / (sum(n.vec)) } else {criteria.after.split <- criteria.x.node} criteria.after.split }
ewspecHaarNonPer <- function (x, filter.number = 1, family = "DaubExPhase", UseLocalSpec = TRUE, DoSWT = TRUE, WPsmooth = TRUE, verbose = FALSE, smooth.filter.number = 10, smooth.family = "DaubLeAsymm", smooth.levels = 3:WPwst$nlevels - 1, smooth.dev = madmad, smooth.policy = "LSuniversal", smooth.value = 0, smooth.by.level = FALSE, smooth.type = "soft", smooth.verbose = FALSE, smooth.cvtol = 0.01, smooth.cvnorm = l2norm, smooth.transform = I, smooth.inverse = I) { coarser <- 0 if (verbose) cat("Smoothing then inversion\n") if (DoSWT == TRUE) { if (verbose) cat("Computing nondecimated wavelet transform of data\n") xwdS <- HwdS(x) } else xwdS <- x if (UseLocalSpec == TRUE) { if (verbose) cat("Computing raw wavelet periodogram\n") xwdWP <- LocalSpec(xwdS, lsmooth = "none", nlsmooth = FALSE) } else xwdWP <- x J <- xwdWP$nlevels if (verbose) cat("Computing A matrix\n") rm <- ipndacw(-J, filter.number = filter.number, family = family) if (verbose) cat("Computing inverse of A\n") irm <- solve(rm) if (verbose) cat("Putting wavelet periodogram into a matrix\n") WavPer <- matrix(0, nrow = (J - coarser), ncol = 2^J) for (j in 1:(J - coarser)) { WavPer[j, ] <- accessD(xwdWP, lev = J - j) } if (WPsmooth == TRUE) { if (verbose) { cat("Smoothing the wavelet periodogram\n") cat("Smoothing level: ") } for (j in 1:(J - coarser)) { if (verbose) cat(J - j) WP <- WavPer[j, ] WP <- smooth.transform(WP) WPwst <- wst(WP, filter.number = smooth.filter.number, family = smooth.family) if (verbose == TRUE) cat(".w") WPwstT <- threshold.wst(WPwst, levels = smooth.levels, dev = smooth.dev, policy = smooth.policy, value = smooth.value, by.level = smooth.by.level, type = smooth.type, verbose = smooth.verbose, cvtol = smooth.cvtol, cvnorm = smooth.cvnorm) if (verbose == TRUE) cat(".t") WPwsrR <- AvBasis(WPwstT) if (verbose == TRUE) cat(".i") WavPer[j, ] <- smooth.inverse(WPwsrR) } if (verbose == TRUE) cat("\n") } irm <- irm[1:(J - coarser), 1:(J - coarser)] S <- irm %*% WavPer xwdS <- xwdWP for (j in 1:(J - coarser)) { xwdS <- putD(xwdS, lev = J - j, v = S[j, ]) } if (coarser > 0) for (j in (J - coarser + 1):J) xwdS <- putD(xwdS, lev = J - j, v = rep(0, 2^J)) list(S = xwdS, WavPer = xwdWP, rm = rm, irm = irm) }
library(testthat) library(rly) context("Literals as a string") Lexer <- R6::R6Class("Lexer", public = list( tokens = c('NUMBER'), literals = "+-*", t_NUMBER = function(re='\\d+', t) { return(t) }, t_error = function(t) {} ) ) test_that("literals as a string", { expect_output(rly::lex(Lexer), NA) })
mice.impute.rfpred.norm <- function( y, ry, x, wy = NULL, num.trees.cont = 10, norm.err.cont = TRUE, alpha.oob = 0.0, pre.boot = TRUE, num.threads = NULL, ...) { if (is.null(wy)) wy <- !ry yMisNum <- sum(wy) if (isTRUE(pre.boot)) { bootIdx <- sample(sum(ry), replace = TRUE) yObs <- y[ry][bootIdx] xObs <- x[ry, , drop = FALSE][bootIdx, , drop = FALSE] } else { yObs <- y[ry] xObs <- x[ry, , drop = FALSE] } xMis <- x[wy, , drop = FALSE] rfObj <- rangerCallerSafe( x = xObs, y = yObs, oob.error = TRUE, num.trees = num.trees.cont, num.threads = num.threads, ...) misPredVal <- predictions(predict(rfObj, xMis)) if (norm.err.cont) { oobMse <- NULL if (isTRUE(alpha.oob > 0 && alpha.oob < 1)) { oobErr <- yObs - rfObj[["predictions"]] oobErrAbs <- abs(oobErr[!is.na(oobErr)]) oobErrorAbsHi <- quantile( oobErrAbs, probs = (1 - alpha.oob), na.rm = TRUE, names = FALSE ) oobErrAbs <- oobErrAbs[oobErrAbs < oobErrorAbsHi] oobMse <- mean(oobErrAbs * oobErrAbs) } else { oobMse <- rfObj[["prediction.error"]] } impVal <- rnorm(length(misPredVal), mean = misPredVal, sd = sqrt(rfObj[["prediction.error"]])) return(impVal) } else { return(misPredVal) } }
MapXform <- function(boxdata,xformInfo,table=NA,defaultValue=NA,mapMissingTo=NA,...) { newrow <- NULL colnamesGiven <- FALSE j <- 0 origFieldName <- NULL derivedFieldName <- NA sampleMin <- NA sampleMax<- NA xformedMin <- NA xformedMax <- NA centers <- NA scales <- NA missingValue <- NA functionXform <- NA dataMatrix <- NULL default <- NA newBoxData <- Initialize(boxdata) if(!is.list(xformInfo)) { minf <- as.character(xformInfo) split0 <- strsplit(minf,"]\\[")[[1]] split0[1] <- gsub("\\[","",split0[1]) given <- length(split0) if(given == 2) { mapVal <- split0[1] split0[2] <- gsub("]","",split0[2]) datType <- split0[2] } else { split0[1] <- gsub("]","",split0[1]) mapVal <- split0[1] datType <- NA } mapVal <- gsub("^[ ]*","",mapVal) mapVal <- gsub("[ $]*","",mapVal) if(grepl("[^-]->",mapVal)) { st <- "->" } else { st <- "-->" } val <- strsplit(mapVal,st)[[1]] inVal <- val[1] valsplit <- strsplit(inVal,",")[[1]] inVals <- valsplit for(i in 1:length(inVals)) { inVals[i] <- gsub("^[ ]*","",inVals[i]) inVals[i] <- gsub("[ $]*","",inVals[i]) } outVal <- val[2] outVal <- gsub("^[ ]*","",outVal) outVal <- gsub("[ $]*","",outVal) inDats <- NULL outDat <- NULL if(!is.na(datType)) { if(grepl("[^-]->",datType)) { st <- "->" } else { st <- "-->" } datsplit <- strsplit(datType,st)[[1]] inDat <- datsplit[1] inDats <- strsplit(inDat,",")[[1]] for(i in 1:length(inDats)) { inDats[i] <- gsub("^[ ]*","",inDats[i]) inDats[i] <- gsub("[ $]*","",inDats[i]) } outDat <- datsplit[2] outDat <- gsub("^[ ]*","",outDat) outDat <- gsub("[ $]*","",outDat) } if(!is.null(outDat)) { if((outDat == "double") || (outDat == "integer")) { outDat <- "numeric" } } else { outDat <- "string" } vnames <- NULL vdtype <- NULL for(i in 1:length(inVals)) { vnames <- c(vnames,inVals[i]) if(is.null(inDats[i])) { vdtype <- c(vdtype,"string") } else { vdtype <- c(vdtype,inDats[i]) } } vnames <- c(vnames,outVal) if(is.na(outDat)) { vdtype <- c(vdtype,"string") } else { vdtype <- c(vdtype,outDat) } tabl <- as.character(table) file <- scan(tabl,what=character(0),sep=",",quiet=T) ndat <- length(file) nrows <- length(scan(tabl,what=character(0),sep="\n",quiet=T)) numcols <- ndat/nrows dataMatrix <- matrix(file,nrow=nrows,byrow=TRUE) if(!is.na(defaultValue)) { default <- as.character(defaultValue) } if(!is.na(mapMissingTo)) { missingValue <- as.character(mapMissingTo) } top <- rbind(vnames,vdtype) dataMatrix <- rbind(top,dataMatrix) rownames(dataMatrix) <- NULL type <- "derived" origFieldName <- paste(inVals,collapse=",") if(is.null(outDat)) { dataType <- "string" } else { dataType <- outDat } fieldsMap <- list(dataMatrix) transform <- "MapValues" derivedFieldName <- outVal suppressWarnings(newrow <- data.frame(type,dataType,I(origFieldName),sampleMin,sampleMax,xformedMin,xformedMax,centers,scales,I(fieldsMap),transform,default,missingValue,functionXform,row.names=derivedFieldName,check.names=FALSE)) suppressWarnings(newBoxData$fieldData <- rbind(newBoxData$fieldData,newrow)) newcol <- NULL newmatrixcol <- NULL if(!is.na(default)) { if(outDat == "numeric") { newcol <- rep(as.numeric(default),nrow(newBoxData$data)) newmatrixcol <- rep(as.numeric(default),nrow(newBoxData$data)) } else if(outDat == "boolean"){ newcol <- rep(as.logical(default),nrow(newBoxData$data)) } else { newcol <- rep(default,nrow(newBoxData$data)) newmatrixcol <- rep(default,nrow(newBoxData$data)) } } else { newcol <- rep(NA,nrow(newBoxData$data)) newmatrixcol <- rep(NA,nrow(newBoxData$data)) } if(!is.na(missingValue)) { for(i in 1:length(inVals)) { na <- which(is.na(newBoxData$data[,inVals[i]])) for(j in na) { if(outDat == "numeric") { newcol[j] <- rep(as.numeric(missingValue),nrow(newBoxData$data)) newmatrixcol[j] <- rep(as.numeric(missingValue),nrow(newBoxData$data)) } else if(outDat == "boolean") { newcol[j] <- rep(as.logical(missingValue),nrow(newBoxData$data)) newmatrixcol[j] <- rep(as.logical(missingValue),nrow(newBoxData$data)) } else { newcol[j] <- rep(missingValue,nrow(newBoxData$data)) newmatrixcol[j] <- rep(missingValue,nrow(newBoxData$data)) } } } } for( j in 3:nrow(dataMatrix)) { if(outDat == "numeric") { newcol[apply(as.matrix(newBoxData$data[,dataMatrix[1,1:(ncol(dataMatrix)-1)]]==matrix(rep(dataMatrix[j,1:(ncol(dataMatrix)-1)],nrow(newBoxData$data)),nrow=nrow(newBoxData$data),byrow=T)),1,all)]<-as.numeric(dataMatrix[j,ncol(dataMatrix)]) newmatrixcol[apply(as.matrix(newBoxData$data[,dataMatrix[1,1:(ncol(dataMatrix)-1)]]==matrix(rep(dataMatrix[j,1:(ncol(dataMatrix)-1)],nrow(newBoxData$data)),nrow=nrow(newBoxData$data),byrow=T)),1,all)]<-as.numeric(dataMatrix[j,ncol(dataMatrix)]) } else if(outDat == "boolean"){ newcol[apply(as.matrix(newBoxData$data[,dataMatrix[1,1:(ncol(dataMatrix)-1)]]==matrix(rep(dataMatrix[j,1:(ncol(dataMatrix)-1)],nrow(newBoxData$data)),nrow=nrow(newBoxData$data),byrow=T)),1,all)]<-as.logical(dataMatrix[j,ncol(dataMatrix)]) newmatrixcol[apply(as.matrix(newBoxData$data[,dataMatrix[1,1:(ncol(dataMatrix)-1)]]==matrix(rep(dataMatrix[j,1:(ncol(dataMatrix)-1)],nrow(newBoxData$data)),nrow=nrow(newBoxData$data),byrow=T)),1,all)]<-as.logical(dataMatrix[j,ncol(dataMatrix)]) } else { newcol[apply(as.matrix(newBoxData$data[,dataMatrix[1,1:(ncol(dataMatrix)-1)]]==matrix(rep(dataMatrix[j,1:(ncol(dataMatrix)-1)],nrow(newBoxData$data)),nrow=nrow(newBoxData$data),byrow=T)),1,all)]<-dataMatrix[j,ncol(dataMatrix)] newmatrixcol[apply(as.matrix(newBoxData$data[,dataMatrix[1,1:(ncol(dataMatrix)-1)]]==matrix(rep(dataMatrix[j,1:(ncol(dataMatrix)-1)],nrow(newBoxData$data)),nrow=nrow(newBoxData$data),byrow=T)),1,all)]<-dataMatrix[j,ncol(dataMatrix)] } } col <- as.matrix(newcol) newBoxData$data <- data.frame(newBoxData$data,col,check.names=FALSE) if(outDat=="string") newBoxData$data[,ncol(newBoxData$data)] <- as.factor(newBoxData$data[,ncol(newBoxData$data)]) colnames(newBoxData$data)[ncol(newBoxData$data)] <- dataMatrix[1,ncol(dataMatrix)] rownames(newBoxData$data) <- NULL if(!is.null(newBoxData$matrixData)) { matrixcol <- as.matrix(newmatrixcol) newBoxData$matrixData <- cbind(newBoxData$matrixData,matrixcol) colnames(newBoxData$matrixData) <- colnames(newBoxData$data) rownames(newBoxData$matrixData) <- NULL } } else { for(k in 1:length(xformInfo)) { ifelse(is.list(xformInfo),xform<-xformInfo[[k]],xform<-table[[k]]) datatypes<-c("string","String","double","Double","boolean","Boolean","integer","Integer","float","Float") if(!(xform[2,ncol(xform)] %in% datatypes)) { datype<-rep("string",ncol(xform)) for(l in 1:ncol(xform)){xform[[l]]<-as.character(xform[[l]])} xform <- rbind(xform[1,],datype,xform[-1,]) } orig <- as.matrix(xform[1,-ncol(xform)]) colnames(orig) <- NULL rownames(orig) <- NULL origFieldName <- list(orig) derivedFieldName <- as.character(xform[1,ncol(xform)]) default <- defaultValue[k] missingValue <- mapMissingTo[k] if((as.character(xform[2,ncol(xform)]) == "double") || (as.character(xform[2,ncol(xform)]) == "integer")) { outDat <- "numeric" } else if(as.character(xform[2,ncol(xform)]) == "double") { outDat <- "boolean" } else { outDat <- "string" } if(derivedFieldName %in% rownames(newBoxData$fieldData)[newBoxData$fieldData[,"type"]=="derived"]) { newBoxData$fieldData <- newBoxData$fieldData[-which(rownames(newBoxData$fieldData)==derivedFieldName),] } suppressWarnings(newrow <- data.frame("derived",outDat,I(origFieldName),sampleMin,sampleMax,xformedMin,xformedMax,centers,scales,I(list(as.matrix(xform))),"MapValues",defaultValue[k],mapMissingTo[k],functionXform,row.names=derivedFieldName,check.names=FALSE)) colnames(newrow)<-c("type","dataType","origFieldName","sampleMin","sampleMax","xformedMin","xformedMax","centers","scales","fieldsMap","transform","default","missingValue","functionXform") suppressWarnings(newBoxData$fieldData <- rbind(newBoxData$fieldData,newrow)) dataMatrix <- as.matrix(xform) newcol <- NULL newmatrixcol <- NULL if(!is.na(default)) { if(outDat == "numeric") { newcol <- rep(as.numeric(default),nrow(newBoxData$data)) newmatrixcol <- rep(as.numeric(default),nrow(newBoxData$data)) } else if(outDat == "boolean"){ newcol <- rep(as.logical(default),nrow(newBoxData$data)) } else { newcol <- rep(default,nrow(newBoxData$data)) newmatrixcol <- rep(default,nrow(newBoxData$data)) } } if(!is.na(missingValue)) { for(i in 1:length(orig[1,])) { na <- which(is.na(newBoxData$data[,orig[1,i]])) for(j in na) { if(outDat == "numeric") { newcol[j] <- rep(as.numeric(missingValue),nrow(newBoxData$data)) newmatrixcol[j] <- rep(as.numeric(missingValue),nrow(newBoxData$data)) } else if(outDat == "boolean"){ newcol[j] <- rep(as.logical(missingValue),nrow(newBoxData$data)) newmatrixcol[j] <- rep(as.logical(missingValue),nrow(newBoxData$data)) } else { newcol[j] <- rep(missingValue,nrow(newBoxData$data)) newmatrixcol[j] <- rep(missingValue,nrow(newBoxData$data)) } } } } for( j in 3:nrow(dataMatrix)) { if(outDat == "numeric") { newcol[apply(as.matrix(newBoxData$data[,dataMatrix[1,1:(ncol(dataMatrix)-1)]]==matrix(rep(dataMatrix[j,1:(ncol(dataMatrix)-1)],nrow(newBoxData$data)),nrow=nrow(newBoxData$data),byrow=T)),1,all)]<-as.numeric(dataMatrix[j,ncol(dataMatrix)]) newmatrixcol[apply(as.matrix(newBoxData$data[,dataMatrix[1,1:(ncol(dataMatrix)-1)]]==matrix(rep(dataMatrix[j,1:(ncol(dataMatrix)-1)],nrow(newBoxData$data)),nrow=nrow(newBoxData$data),byrow=T)),1,all)]<-as.numeric(dataMatrix[j,ncol(dataMatrix)]) } else if(outDat == "boolean"){ newcol[apply(as.matrix(newBoxData$data[,dataMatrix[1,1:(ncol(dataMatrix)-1)]]==matrix(rep(dataMatrix[j,1:(ncol(dataMatrix)-1)],nrow(newBoxData$data)),nrow=nrow(newBoxData$data),byrow=T)),1,all)]<-as.logical(dataMatrix[j,ncol(dataMatrix)]) newmatrixcol[apply(as.matrix(newBoxData$data[,dataMatrix[1,1:(ncol(dataMatrix)-1)]]==matrix(rep(dataMatrix[j,1:(ncol(dataMatrix)-1)],nrow(newBoxData$data)),nrow=nrow(newBoxData$data),byrow=T)),1,all)]<-as.logical(dataMatrix[j,ncol(dataMatrix)]) } else { newcol[apply(as.matrix(newBoxData$data[,dataMatrix[1,1:(ncol(dataMatrix)-1)]]==matrix(rep(dataMatrix[j,1:(ncol(dataMatrix)-1)],nrow(newBoxData$data)),nrow=nrow(newBoxData$data),byrow=T)),1,all)]<-dataMatrix[j,ncol(dataMatrix)] newmatrixcol[apply(as.matrix(newBoxData$data[,dataMatrix[1,1:(ncol(dataMatrix)-1)]]==matrix(rep(dataMatrix[j,1:(ncol(dataMatrix)-1)],nrow(newBoxData$data)),nrow=nrow(newBoxData$data),byrow=T)),1,all)]<-dataMatrix[j,ncol(dataMatrix)] } } col <- as.matrix(newcol) matrixcol <- as.matrix(newmatrixcol) newBoxData$data <- data.frame(newBoxData$data,col,check.names=FALSE) colnames(newBoxData$data)[ncol(newBoxData$data)] <- dataMatrix[1,ncol(dataMatrix)] rownames(newBoxData$data) <- NULL if(!is.null(newBoxData$matrixData)) { newBoxData$matrixData <- cbind(newBoxData$matrixData,matrixcol) colnames(newBoxData$matrixData) <- colnames(newBoxData$data) rownames(newBoxData$matrixData) <- NULL } } } return(newBoxData) }
filing_funds <- function(x) { UseMethod("filing_funds") } filing_funds.character <- function(x) { filing_funds(charToDoc(x)) } filing_funds.xml_node <- function(x) { entries_xpath <- "//td[@class='classContract']" info_pieces <- list( "cik" = "preceding::td[@class='CIKname']/a", "cik_href" = "preceding::td[@class='CIKname']/a/@href", "series" = "preceding::td[@class='seriesName'][1]/a", "series_href" = "preceding::td[@class='seriesName'][1]/a/@href", "series_name" = "preceding::td[@class='seriesName'][1]/following-sibling::td[2]/text()", "contract" = "a/text()", "contract_href" = "a/@href", "contract_name" = "following-sibling::td[2]/text()", "ticker" = "following-sibling::td[3]/text()" ) res <- map_xml(x, entries_xpath, info_pieces) return(res) }
context("AnnotateIDVCF") test_that("AnnotateIDVCF function with hg19", { skip_if("" == system.file(package = "BSgenome.Hsapiens.1000genomes.hs37d5")) stopifnot(requireNamespace("BSgenome.Hsapiens.1000genomes.hs37d5")) load("testdata/test_AnnotateIDVCF.Rdata") id.vcf <- ReadStrelkaIDVCF("testdata/Strelka-ID-GRCh37/Strelka.ID.GRCh37.s1.vcf") list <- AnnotateIDVCF(id.vcf, ref.genome = BSgenome.Hsapiens.1000genomes.hs37d5::BSgenome.Hsapiens.1000genomes.hs37d5) list1 <- AnnotateIDVCF(id.vcf, ref.genome = "GRCh37") list2 <- AnnotateIDVCF(id.vcf, ref.genome = "hg19") expect_equal(list$annotated.vcf, strelka.ID.vcf.GRCh37) expect_equal(list$annotated.vcf, list1$annotated.vcf) expect_equal(list$annotated.vcf, list2$annotated.vcf) }) test_that("AnnotateIDVCF with hg38", { skip_if("" == system.file(package = "BSgenome.Hsapiens.UCSC.hg38")) stopifnot(requireNamespace("BSgenome.Hsapiens.UCSC.hg38")) load("testdata/test_AnnotateIDVCF.Rdata") id.vcf <- ReadStrelkaIDVCF("testdata/Strelka.ID.GRCh38.vcf") list3 <- AnnotateIDVCF(id.vcf, ref.genome = BSgenome.Hsapiens.UCSC.hg38::BSgenome.Hsapiens.UCSC.hg38) list4 <- AnnotateIDVCF(id.vcf, ref.genome = "GRCh38") list5 <- AnnotateIDVCF(id.vcf, ref.genome = "hg38") expect_equal(list3$annotated.vcf, strelka.ID.vcf.GRCh38) expect_equal(list3$annotated.vcf, list4$annotated.vcf) expect_equal(list3$annotated.vcf, list5$annotated.vcf) })
matching <- function(z, score, replace=FALSE){ n <- length(score) nt <- sum(z) nc <- sum(1-z) ind.t <- c(1:n)[z==1] ind.c <- c(1:n)[z==0] cnts <- rep(0, n) cnts[z==1] = rep(1,nt) scorec <- score[z == 0] scoret <- score[z == 1] if (replace){ dist = abs(outer(scoret,scorec,FUN="-")) mins = apply(dist,1,min) matches = dist - mins matches[matches!=0] = 1 matches = 1 - matches if(sum(matches)>nt){ for(i in c(1:nt)[apply(matches,1,sum)>1]){ matches_i <- c(1:nc)[matches[i,]==1] nmi <- length(matches_i) matches[i,matches_i] <- sample(c(1,rep(0,nmi-1)),nmi,replace=FALSE) } } ind.cm <- matches %*% ind.c cnts[z==0] <- apply(matches,2,sum) match.ind <- c(ind.t, ind.cm) out <- list(match.ind = match.ind, cnts = cnts, matches = matches) } if (!replace){ pairs = rep(NA,n) match.ind <- rep(0, n) tally <- 0 for (i in ind.t) { available <- (1:n)[(z == 0) & (match.ind == 0)] j <- available[order(abs(score[available] - score[i]))[1]] cnts[j] <- 1 match.ind[i] <- j match.ind[j] <- i tally <- tally + 1 pairs[c(i, j)] <- tally } out <- list(match.ind = match.ind, cnts = cnts, pairs = pairs) } return(out) }
registerISOMetadataSchema <- function(xsdFile){ schemas <- tryCatch( XML::xmlParse( xsdFile, isSchema = TRUE, xinclude = TRUE, error = function (msg, code, domain, line, col, level, filename, class = "XMLError"){} ) ) .geometa.iso$schemas <- schemas } setISOMetadataSchemas <- function(){ packageStartupMessage("Loading ISO 19139 XML schemas...") schemaPath <- "extdata/schemas" namespace <- "gmd" defaultXsdFile <- system.file(paste(schemaPath, namespace, sep="/"), paste0(namespace,".xsd"), package = "geometa", mustWork = TRUE) registerISOMetadataSchema(defaultXsdFile) } getISOMetadataSchemas <- function(){ return(.geometa.iso$schemas) }
mdp_LP <- function(P, R, discount) { start<-as.POSIXlt(Sys.time()) if ( discount <= 0 | discount > 1 ) { print('--------------------------------------------------------') print('MDP Toolbox ERROR: Discount rate must be in ]0; 1]') print('--------------------------------------------------------') } else if (is.list(P)) { print('--------------------------------------------------------') print('MDPR ERROR: mdp_LP cannot be used with sparse matrices') print('--------------------------------------------------------') } else { if (is.list(P)) { S <- dim(P[[1]])[1] A <- length(P) } else { S <- dim(P)[1] A <- dim(P)[3] } PR <- mdp_computePR(P,R) f <- rep(1,S) M <- NULL if (is.list(P)) { for (a in 1:A) { M <- rbind2(M, discount*P[[a]] - Diagonal(S)) } } else { for (a in 1:A) { M <- rbind(M, as.matrix(discount*P[,,a] - Diagonal(S))) } } V <- as.numeric(solveLP(f,as.vector(-PR),M)$solution) bellman <- mdp_bellman_operator(P,PR,discount,V) V <- bellman[[1]] policy <- bellman[[2]] end <-as.POSIXlt(Sys.time()) return(list("V"=V, "policy"=policy, "time"=end-start)) } }
predict.filter.NULL <- function (object, newdata, ...) { return(newdata) } predict.filter.PCA <- function (object, newdata, ...) { res = predict(object$mod, newdata)[,1:object$nbreVarX] return(res) } predict.filter.RegressionTreeFilter <- function (object, newdata, ...) { if(is.matrix(newdata)) nbreDExempleMax=dim(newdata)[1] else nbreDExempleMax=1 resFinal=c() for(nbreDExemple in 1:nbreDExempleMax) { Nmax = object$nbreVarX a = newdata resume = TRUE shortResume = TRUE D = list() L = list() t = c(1:length(a)) D[[1]] = t[1] D[[2]] = t[length(t)] L[[1]] = struct(g = integer(), d = integer()) L[[1]]$g = t[1] L[[1]]$d = t[length(t)] ac = rep(mean(a), (t[length(t)])) Np = 1 while (Np != Nmax) { if (is.struct(L[[1]])) { max = (L[[1]]$d - L[[1]]$g) * var(a[c(L[[1]]$g:L[[1]]$d)]) ti = L[[1]]$g tj = L[[1]]$d LIndex = 1 if (length(L) != 1) { for (i in 2:length(L)) { if (is.struct(L[[i]])) { tmp = (L[[i]]$d - L[[i]]$g) * var(a[c(L[[i]]$g:L[[i]]$d)]) if (tmp > max) { max = tmp ti = L[[i]]$g tj = L[[i]]$d LIndex = i } } } } L[[LIndex]] = NA } max = 0 maxE = -1 vartitj = (tj - ti) * var(a[which(t == ti):which(t == tj)]) for (e in which(t == ti):which(t == tj)) { varIE = var(a[ti:t[e]]) if (is.na(varIE)) { varIE = 0 } varEJ = var(a[t[e]:tj]) if (is.na(varEJ)) { varEJ = 0 } tmp = vartitj - (t[e] - ti) * varIE - (tj - t[e]) * varEJ if (tmp > max) { max = tmp maxE = e } } e = maxE te = t[e] distIE = length(which(t == ti):which(t == te)) distEJ = length(which(t == te):which(t == tj)) ac[ti:te] = rep(mean(a[ti:te]), distIE) ac[te:tj] = rep(mean(a[te:tj]), distEJ) Np = Np + 1 trouve = FALSE trouveI = -1 for (i in 1:length(L)) { if (!is.struct(L[[i]]) && !trouve) { trouve = TRUE trouveI = i } } if (!trouve) { trouveI = length(L) + 1 } L[[trouveI]] = struct(g = integer(), d = integer()) L[[trouveI]]$g = ti L[[trouveI]]$d = te trouve = FALSE trouveI = -1 for (i in 1:length(L)) { if (!is.struct(L[[i]]) && !trouve) { trouve = TRUE trouveI = i } } if (!trouve) { trouveI = length(L) + 1 } L[[trouveI]] = struct(g = integer(), d = integer()) L[[trouveI]]$g = te L[[trouveI]]$d = tj D[[length(D) + 1]] = te } if (!resume) { resFinal = rbind(ac) } else { if (shortResume) { resFinal = rbind(unique(ac)) } else { resTmp = unique(ac) res = resTmp for (i in resTmp) { res = c(res, length(which(ac == i))) } resFinal = rbind(res) } } } return(resFinal) } predict.filter.mRMR <- function (object, newdata, ...) { return(newdata[, object$filter]) } predict.filter.MAX <- function (object, newdata, ...) { if(is.matrix(newdata)) nbreDExempleMax=dim(newdata)[1] else nbreDExempleMax=1 res=c() for(nbreDExemple in 1:nbreDExempleMax) { res = rbind(res,sort(newdata[nbreDExemple,])[(dim(newdata)[2]-object$nbreVarX+1):(dim(newdata)[2])]) } return(res) }
print.userContribsClass <-function(x, maxprint = 10,...) { if(class(x)!="userContribsClass") stop("The argument Object must be a class userContribsClass") cl <- x$call if (!is.null(cl)){ cat("Call:\n") dput(cl) cat("\n") } if(any(names(x)=="user")) { cat("User name:", x$user[1],"\n") cat("User id:", x$user[2],"\n") cat("Domain:", x$user[3],"\n") cat("\n") if(any(names(x)=="contribs")) { cat("Total number of contributions:",nrow(x$contribs)) cat("\n") cat("List of contributions :","\n") nbprint <- min(maxprint,nrow(x$contribs)) print(x$contribs[1:nbprint,]) if(nbprint <nrow(x$contribs) ) {cat("... last",nrow(x$contribs) -maxprint,"contributions not printed")} } else{cat("0 contribution")} cat("\n") } }
NMixPredDensJoint2.NMixMCMC <- function(x, grid, lgrid=50, scaled=FALSE, ...) { if (scaled) scale <- list(shift=0, scale=1) else scale <- x$scale if (x$nx_w == 1){ if (missing(grid)){ grid <- list() if (scaled){ if (x$dim == 1){ rangeGrid <- x$summ.z.Mean["Median"] + c(-3.5, 3.5)*x$summ.z.SDCorr["Median"] grid[[1]] <- seq(rangeGrid[1], rangeGrid[2], length=lgrid) }else{ for (i in 1:x$dim){ rangeGrid <- x$summ.z.Mean["Median", i] + c(-3.5, 3.5)*x$summ.Z.SDCorr["Median", (i-1)*(2*x$dim - i + 2)/2 + 1] grid[[i]] <- seq(rangeGrid[1], rangeGrid[2], length=lgrid) } } }else{ if (x$dim == 1){ rangeGrid <- x$summ.y.Mean["Median"] + c(-3.5, 3.5)*x$summ.y.SDCorr["Median"] grid[[1]] <- seq(rangeGrid[1], rangeGrid[2], length=lgrid) }else{ for (i in 1:x$dim){ rangeGrid <- x$summ.y.Mean["Median", i] + c(-3.5, 3.5)*x$summ.y.SDCorr["Median", (i-1)*(2*x$dim - i + 2)/2 + 1] grid[[i]] <- seq(rangeGrid[1], rangeGrid[2], length=lgrid) } } } names(grid) <- paste("x", 1:x$dim, sep="") } if (x$dim == 1) if (is.numeric(grid)) grid <- list(x1=grid) if (!is.list(grid)) stop("grid must be a list") if (x$prior$priorK == "fixed"){ dns <- NMixPredDensJoint2.default(x=grid, scale=scale, K=x$K, w=as.numeric(t(x$w)), mu=as.numeric(t(x$mu)), Li=as.numeric(t(x$Li)), Krandom=FALSE) }else{ dns <- NMixPredDensJoint2.default(x=grid, scale=scale, K=x$K, w=x$w, mu=x$mu, Li=x$Li, Krandom=TRUE) } dns$nx_w <- 1 dns$lx_w <- "" return(dns) }else{ if (missing(grid)){ grid <- list() if (scaled){ for (ixw in 1:x$nx_w){ for (i in 1:x$dim){ naamM <- paste("z.Mean.", i, "-", x$lx_w[ixw], sep = "") naamS <- paste("z.SD.", i, "-", x$lx_w[ixw], sep = "") rangeGrid <- x$summ.z.Mean["Median", naamM] + c(-3.5, 3.5) * x$summ.z.SDCorr["Median", naamS] grid[[(ixw - 1)*x$dim + i]] <- seq(rangeGrid[1], rangeGrid[2], length = lgrid) } } }else{ for (ixw in 1:x$nx_w){ for (i in 1:x$dim){ naamM <- paste("y.Mean.", i, "-", x$lx_w[ixw], sep = "") naamS <- paste("y.SD.", i, "-", x$lx_w[ixw], sep = "") rangeGrid <- x$summ.y.Mean["Median", naamM] + c(-3.5, 3.5) * x$summ.y.SDCorr["Median", naamS] grid[[(ixw - 1)*x$dim + i]] <- seq(rangeGrid[1], rangeGrid[2], length = lgrid) } } } names(grid) <- paste("x", rep(1:x$dim, x$nx_w), "-", rep(x$lx_w, each = x$dim), sep="") } if (!is.list(grid)) stop("grid must be a list") dns <- list() for (ixw in 1:x$nx_w){ gridixw <- list() for (i in 1:x$dim){ gridixw[[i]] <- grid[[(ixw - 1)*x$dim + i]] } names(gridixw) <- paste("x", 1:x$dim, sep = "") dns[[ixw]] <- NMixPredDensJoint2.default(x = gridixw, scale = scale, K=x$K, w = as.numeric(t(x$w[, (ixw - 1)*x$K[1] + 1:x$K[1]])), mu = as.numeric(t(x$mu)), Li = as.numeric(t(x$Li)), Krandom = FALSE) } names(dns) <- x$lx_w dns$nx_w <- x$nx_w dns$lx_w <- x$lx_w class(dns) <- "NMixPredDensJoint2" return(dns) } }
`covAxis` <- function(X, na.action = na.fail) { X<-na.action(X) X<-as.matrix(X) n <- dim(X)[1] p <- dim(X)[2] if (p<2) stop("'X' must be at least bivariate") Xmeans <- colMeans(X) di<-sqrt(mahalanobis(X,Xmeans,cov(X))) X.centered <- sweep(X, 2, Xmeans) Y<-sweep(X.centered,1,di,FUN="/") v.tilde <- p*crossprod(Y) / n return(v.tilde) }
effectContinuousmod7 <- function(object, x1x2, level, nboot, IQReffect, effectsOutRange) { betaCI <- betaCIContinuousExactTrans(object = object, level = level) effect <- t(apply(x1x2, 1, FUN = function(x) exp((x[2] - x[1]) * betaCI))) effect <- cbind(x1x2, effect) names(effect)[3:5] <- c("OR", paste(c("lower", "upper"), 100 * level, "%", sep = "")) if (IQReffect) { info <- paste("Adjusted odds ratio of the response variable when the explanatory\nvariable changes from the 1st to the 3rd quartile", sep = "") } else { info <- paste("Adjusted odds ratio of the response variable when the explanatory\nvariable changes from x1 to x2", sep = "") } if (effectsOutRange) info <- paste("WARNING: computing effects out of the observed range of X.\n\n", info, sep = "") info <- paste(info, ":\n\n", sep = "") res <- list(effect = effect, info = info) res }
NULL NULL NULL NULL NULL release_questions <- function() { c( "Have you updated the inst/NEWS file?", "Have you changed the version+dates in DESCRIPTION and NEWS.md?", "Have you added all new files to GIT?", "Have you clean the vignettes file (source)?" ) } NULL .onLoad <- function(libname, pkgname) { options( aphylo_informative = FALSE, aphylo_reduce_pseq = TRUE ) }
context('ab_test') test_that("basic ab_test works", { library(truncnorm) H0int <- function(beta, data, prior_par) { p <- plogis(beta) p^(data$y1 + data$y2) * (1 - p)^(data$n1 + data$n2 - data$y1 - data$y2) * dnorm(beta, prior_par$mu_beta, prior_par$sigma_beta) } inner_integrand <- function(beta, psi, data, prior_par) { p1 <- plogis(beta - psi / 2) p2 <- plogis(beta + psi / 2) p1^data$y1 * (1 - p1)^(data$n1 - data$y1) * p2^data$y2 * (1 - p2)^(data$n2 - data$y2) * dnorm(beta, prior_par$mu_beta, prior_par$sigma_beta) } Haltint <- function(psi, data, prior_par, hypothesis) { bounds <- switch(hypothesis, "H1" = c(-Inf, Inf), "H+" = c(0, Inf), "H-" = c(-Inf, 0)) vapply(psi, FUN = function(x) { integrate(inner_integrand, lower = -Inf, upper = Inf, psi = x, data = data, prior_par = prior_par)$value }, FUN.VALUE = 0) * dtruncnorm(psi, a = bounds[1], b = bounds[2], mean = prior_par$mu_psi, sd = prior_par$sigma_psi) } mean_psi_int <- function(psi, data, prior_par, hypothesis) { bounds <- switch(hypothesis, "H1" = c(-Inf, Inf), "H+" = c(0, Inf), "H-" = c(-Inf, 0)) vapply(psi, FUN = function(x) { integrate(inner_integrand, lower = -Inf, upper = Inf, psi = x, data = data, prior_par = prior_par)$value }, FUN.VALUE = 0) * psi * dtruncnorm(psi, a = bounds[1], b = bounds[2], mean = prior_par$mu_psi, sd = prior_par$sigma_psi) } var_psi_int <- function(psi, m, data, prior_par, hypothesis) { bounds <- switch(hypothesis, "H1" = c(-Inf, Inf), "H+" = c(0, Inf), "H-" = c(-Inf, 0)) vapply(psi, FUN = function(x) { integrate(inner_integrand, lower = -Inf, upper = Inf, psi = x, data = data, prior_par = prior_par)$value }, FUN.VALUE = 0) * (psi - m)^2 * dtruncnorm(psi, a = bounds[1], b = bounds[2], mean = prior_par$mu_psi, sd = prior_par$sigma_psi) } mean_beta_int <- function(beta, data, prior_par, hypothesis) { bounds <- switch(hypothesis, "H1" = c(-Inf, Inf), "H+" = c(0, Inf), "H-" = c(-Inf, 0)) vapply(beta, FUN = function(x) { integrate(function(psi, beta, data, prior_par, hypothesis, bounds) { p1 <- plogis(beta - psi / 2) p2 <- plogis(beta + psi / 2) p1^data$y1 * (1 - p1)^(data$n1 - data$y1) * p2^data$y2 * (1 - p2)^(data$n2 - data$y2) * dtruncnorm(psi, a = bounds[1], b = bounds[2], mean = prior_par$mu_psi, sd = prior_par$sigma_psi) }, lower = -Inf, upper = Inf, beta = x, data = data, prior_par = prior_par, hypothesis = hypothesis, bounds = bounds)$value }, FUN.VALUE = 0) * beta * dnorm(beta, prior_par$mu_beta, prior_par$sigma_beta) } var_beta_int <- function(beta, m, data, prior_par, hypothesis) { bounds <- switch(hypothesis, "H1" = c(-Inf, Inf), "H+" = c(0, Inf), "H-" = c(-Inf, 0)) vapply(beta, FUN = function(x) { integrate(function(psi, beta, data, prior_par, hypothesis, bounds) { p1 <- plogis(beta - psi / 2) p2 <- plogis(beta + psi / 2) p1^data$y1 * (1 - p1)^(data$n1 - data$y1) * p2^data$y2 * (1 - p2)^(data$n2 - data$y2) * dtruncnorm(psi, a = bounds[1], b = bounds[2], mean = prior_par$mu_psi, sd = prior_par$sigma_psi) }, lower = -Inf, upper = Inf, beta = x, data = data, prior_par = prior_par, hypothesis = hypothesis, bounds = bounds)$value }, FUN.VALUE = 0) * (beta - m)^2 * dnorm(beta, prior_par$mu_beta, prior_par$sigma_beta) } set.seed(1) data <- list(y1 = 11, n1 = 15, y2 = 5, n2 = 13) prior_par <- list(mu_psi = -0.4, sigma_psi = 1.2, mu_beta = 0.2, sigma_beta = 0.6) ab <- ab_test(data = data, prior_par = prior_par) mlH0 <- integrate(H0int, lower = -Inf, upper = Inf, data = data, prior_par = prior_par)$value mlH1 <- integrate(Haltint, lower = -Inf, upper = Inf, data = data, prior_par = prior_par, hypothesis = "H1")$value mlHplus <- integrate(Haltint, lower = 0, upper = Inf, data = data, prior_par = prior_par, hypothesis = "H+")$value mlHminus <- integrate(Haltint, lower = -Inf, upper = 0, data = data, prior_par = prior_par, hypothesis = "H-")$value BF10 <- mlH1 / mlH0 BFplus0 <- mlHplus / mlH0 BFminus0 <- mlHminus / mlH0 expect_equal(ab$bf$bf10, expected = BF10, tolerance = 0.1) expect_equal(ab$bf$bfplus0, expected = BFplus0, tolerance = 0.1) expect_equal(ab$bf$bfminus0, expected = BFminus0, tolerance = 0.1) prior_prob <- ab$input$prior_prob mls <- c(mlH1, mlHplus, mlHminus, mlH0) post_prob <- mls * prior_prob / sum(mls * prior_prob) expect_equal(ab$post_prob, expected = post_prob, tolerance = 0.05) prior_prob2 <- c(0.1, 0.3, 0.2, 0.4) names(prior_prob2) <- names(prior_prob) ab2 <- ab_test(data = data, prior_par = prior_par, prior_prob = prior_prob2) post_prob2 <- mls * prior_prob2 / sum(mls * prior_prob2) expect_equal(ab2$post_prob, expected = post_prob2, tolerance = 0.05) ab3 <- ab_test(data = data, prior_par = prior_par, posterior = TRUE) ml <- list("H1" = mlH1, "H+" = mlHplus, "H-" = mlHminus) for (hypothesis in c("H1", "H+", "H-")) { bounds <- switch(hypothesis, "H1" = c(-Inf, Inf), "H+" = c(0, Inf), "H-" = c(-Inf, 0)) hypothesis2 <- switch(hypothesis, "H1" = "H1", "H+" = "Hplus", "H-" = "Hminus") mnum <- integrate(mean_psi_int, lower = bounds[1], upper = bounds[2], data = data, prior_par = prior_par, hypothesis = hypothesis)$value / ml[[hypothesis]] expect_equal(mean(ab3$post[[hypothesis2]]$psi), expected = mnum, tolerance = 0.05) vnum <- integrate(var_psi_int, lower = bounds[1], upper = bounds[2], m = mnum, data = data, prior_par = prior_par, hypothesis = hypothesis)$value / ml[[hypothesis]] expect_equal(var(ab3$post[[hypothesis2]]$psi), expected = vnum, tolerance = 0.05) mnum <- integrate(mean_beta_int, lower = -Inf, upper = Inf, data = data, prior_par = prior_par, hypothesis = hypothesis)$value / ml[[hypothesis]] expect_equal(mean(ab3$post[[hypothesis2]]$beta), expected = mnum, tolerance = 0.05) vnum <- integrate(var_beta_int, lower = -Inf, upper = Inf, m = mnum, data = data, prior_par = prior_par, hypothesis = hypothesis)$value / ml[[hypothesis]] expect_equal(var(ab3$post[[hypothesis2]]$beta), expected = vnum, tolerance = 0.05) } }) test_that("different sequential data formats yield same result", { set.seed(1) data <- list(y1 = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3, 4, 4), n1 = c(1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10), y2 = c(0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9), n2 = c(0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10)) data_seq <- data.frame(outcome = c(1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0), group = rep(c(1, 2), 10)) data_seq_mat <- as.matrix(data_seq) ab <- ab_test(data) ab_seq <- ab_test(data_seq) ab_seq_mat <- ab_test(data_seq_mat) expect_equal(ab_seq$bf$bf10, expected = ab$bf$bf10) expect_equal(ab_seq_mat$bf$bf10, expected = ab$bf$bf10) }) test_that("y and n alternative data specification works", { set.seed(1) data <- list(y1 = 11, n1 = 15, y2 = 5, n2 = 13) ab <- ab_test(data) ab2 <- ab_test(y = c(11, 5), n = c(15, 13)) expect_equal(ab2$bf$bf10, expected = ab$bf$bf10) })
context("epinow") if (!testthat:::on_cran()) { generation_time <- get_generation_time(disease = "SARS-CoV-2", source = "ganyani", max_value = 15) incubation_period <- get_incubation_period(disease = "SARS-CoV-2", source = "lauer", max_value = 15) reporting_delay <- list(mean = convert_to_logmean(3,1), mean_sd = 0.1, sd = convert_to_logsd(3,1), sd_sd = 0.1, max = 10) reported_cases <- EpiNow2::example_confirmed[1:30] futile.logger::flog.threshold("FATAL") df_non_zero <- function(df) { expect_true(nrow(df) > 0) } expected_out <- c("estimates", "estimated_reported_cases", "summary", "plots", "timing") } test_that("epinow produces expected output when run with default settings", { skip_on_cran() out <- suppressWarnings(epinow(reported_cases = reported_cases, generation_time = generation_time, delays = delay_opts(incubation_period, reporting_delay), stan = stan_opts(samples = 25, warmup = 25, cores = 1, chains = 2, control = list(adapt_delta = 0.8)), logs = NULL)) expect_equal(names(out), expected_out) df_non_zero(out$estimates$samples) df_non_zero(out$estimates$summarised) df_non_zero(out$estimated_reported_cases$samples) df_non_zero(out$estimated_reported_cases$summarised) df_non_zero(out$summary) expect_equal(names(out$plots), c("infections", "reports", "R", "growth_rate","summary")) }) test_that("epinow runs without error when saving to disk", { skip_on_cran() expect_null(suppressWarnings(epinow(reported_cases = reported_cases, generation_time = generation_time, delays = delay_opts(incubation_period, reporting_delay), stan = stan_opts(samples = 25, warmup = 25, cores = 1, chains = 2, control = list(adapt_delta = 0.8)), target_folder = tempdir(check = TRUE), logs = NULL, ))) }) test_that("epinow can produce partial output as specified", { skip_on_cran() out <- suppressWarnings(epinow(reported_cases = reported_cases, generation_time = generation_time, delays = delay_opts(incubation_period, reporting_delay), stan = stan_opts(samples = 25, warmup = 25, cores = 1, chains = 2, control = list(adapt_delta = 0.8)), output = c(), logs = NULL)) expect_equal(names(out), c("estimates", "estimated_reported_cases", "summary")) expect_null(out$estimates$samples) df_non_zero(out$estimates$summarised) expect_null(out$estimated_reported_cases$samples) df_non_zero(out$estimated_reported_cases$summarised) df_non_zero(out$summary) }) test_that("epinow fails as expected when given a short timeout", { skip_on_cran() expect_error(suppressWarnings(epinow(reported_cases = reported_cases, generation_time = generation_time, delays = delay_opts(incubation_period, reporting_delay), stan = stan_opts(samples = 100, warmup = 100, cores = 1, chains = 2, control = list(adapt_delta = 0.8), max_execution_time = 10), logs = NULL))) }) test_that("epinow fails if given NUTs arguments when using variational inference", { skip_on_cran() expect_error(suppressWarnings(epinow(reported_cases = reported_cases, generation_time = generation_time, delays = delay_opts(incubation_period, reporting_delay), stan = delay_opts(samples = 100, warmup = 100, cores = 1, chains = 2, method = "vb"), logs = NULL))) }) test_that("epinow fails if given variational inference arguments when using NUTs", { skip_on_cran() expect_error(suppressWarnings(epinow(reported_cases = reported_cases, generation_time = generation_time, delays = delay_opts(incubation_period, reporting_delay), stan = stan_opts(method = "sampling", tol_rel_obj = 1), logs = NULL))) })
repeat_anticlustering <- function(x, K, objective, categories, method, repetitions) { N <- nrow(x) clusters <- list(initialize_clusters(N, K, categories)) if (argument_exists(repetitions) && repetitions > 1) { if (argument_exists(categories)) { if (length(K) > 1 && sum(K) != N) { stop("If `K` is of length `nrow(x)` and `repetitions` is given, you cannot use `preclustering = TRUE` or `categories`, sorry.") } clusters_repetitions <- as.list(data.frame(as.matrix( replicate(repetitions - 1, categorical_sampling(categories, K)) ))) } else { clusters_repetitions <- as.list(data.frame(as.matrix( replicate(repetitions - 1, sample(clusters[[1]])) ))) } clusters_repetitions <- unname(clusters_repetitions) clusters <- merge_lists(list(clusters, clusters_repetitions)) } if (inherits(objective, "function")) { obj_function <- objective } else if (objective == "variance") { obj_function <- variance_objective } else if (objective == "diversity" || objective == "distance") { obj_function <- diversity_objective } else if (objective == "dispersion") { obj_function <- dispersion_objective } if (method == "local-maximum") { candidate_solutions <- lapply( clusters, local_maximum_anticlustering, data = x, objective = objective, obj_function = obj_function, categories = categories ) } else if (method == "exchange") { candidate_solutions <- lapply( clusters, anticlustering_, data = x, objective = objective, categories = categories ) candidate_solutions } obj_function_ <- function(clusters, x) { obj_function(x, clusters) } objs <- lapply( candidate_solutions, obj_function_, x = x ) candidate_solutions[[which.max(objs)]] } local_maximum_anticlustering <- function( clusters, data, objective, obj_function, categories) { old_obj <- obj_function(data, clusters) has_improved <- TRUE while (has_improved) { new_clusters <- anticlustering( x = data, K = clusters, objective = objective, categories = categories, repetitions = NULL, method = "exchange", preclustering = FALSE ) new_obj <- obj_function(data, new_clusters) if (new_obj > old_obj) { clusters <- new_clusters old_obj <- new_obj } else { has_improved <- FALSE } } clusters } anticlustering_ <- function(clusters, data, objective, categories) { anticlustering( data, K = clusters, objective = objective, method = "exchange", categories = categories, repetitions = NULL, preclustering = FALSE ) }
sim_bmat <- function(n_items, k, ncat = 2, xi_dist = list(runif, min = -1, max = 1), omega_dist = list(runif, min = -1, max = 1), alpha_dist = list(runif, min = -1, max = .5), tau_dist = list(runif, min = -3, max = 0)) { maxk <- max(k) maxncat <- max(ncat) bmat <- matrix(0, nrow = n_items, ncol = 2 * maxk + maxncat) if (length(k) == 1) k <- rep(k, n_items) if (length(k) != n_items) stop("k must either have 1 or n_items elements") if (length(ncat) == 1) ncat <- rep(ncat, n_items) if (length(ncat) != n_items) stop("ncat must either have 1 or n_items elements") xi <- matrix(do.call(xi_dist[[1]], c(list(n = n_items * (maxncat - 1)), xi_dist[-1])), ncol = maxncat - 1) omega <- do.call(omega_dist[[1]], c(list(n = n_items), omega_dist[-1])) alpha <- matrix(0, nrow = n_items, ncol = maxk) tau <- matrix(-Inf, nrow = n_items, ncol = maxk) for (i in 1:n_items) { if (ncat[i] < maxncat) xi[i, ncat[i]:ncol(xi)] <- NA xi[i, 1:(ncat[i] - 1)] <- sort(xi[i, 1:(ncat[i] - 1)], decreasing = TRUE) if (k[i] != 0) { alpha[i, 1:k[i]] <- do.call(alpha_dist[[1]], c(list(n = k[i]), alpha_dist[-1])) tau[i, 1:k[i]] <- do.call(tau_dist[[1]], c(list(n = k[i]), tau_dist[-1])) bmat[i, ] <- greek2b(xi = xi[i, ], omega = omega[i], alpha = alpha[i, ], tau = tau[i, ]) } else bmat[i, 1:maxncat] <- greek2b(xi = xi[i, ], omega = omega[i]) } greekmat <- matrix(rbind(alpha, tau), nrow = n_items) greekmat <- cbind(xi, omega, greekmat) if (maxk == 0) colnames(greekmat) <- c(paste0("xi", 1:(maxncat - 1)), "omega") else colnames(greekmat) <- c(paste0("xi", 1:(maxncat - 1)), "omega", paste0(rep(c("alpha", "tau"), maxk), rep(1:maxk, each = 2))) if (maxncat > 2) colnames(bmat) <- c(paste0("b0_", 1:(maxncat - 1)), paste0("b", 1:(2 * maxk + 1))) else colnames(bmat) <- paste0("b", 0:(ncol(bmat) - 1)) list(bmat = bmat, greekmat = greekmat) }
applytopup = function( infile, datain, index, topup_files, out = NULL, method = c("lsr", "jac"), interp = c("spline", "trilinear"), verbose = TRUE ){ warning("This function has not been tested") index = paste(index, collapse = ",") topup_files = checkimg(topup_files) topup_files = unname(topup_files) method = match.arg(method) interp = match.arg(interp) parse_num_args = function(x){ x = paste0(names(x), '=', x) x = paste(x, collapse = " ") x } if (is.null(out)) { out = tempfile() } L = list(out = out, inindex = index, topup = topup_files, interp = interp, method = method ) nulls = sapply(L, is.null) L = L[!nulls] names(L) = paste0("--", names(L)) opts = parse_num_args(L) if (verbose) { opts = paste(opts, "--verbose") } cmd = get.fsl() cmd = paste0(cmd, "applytopup") infile = checkimg(infile) infile = unname(infile) infile = normalizePath(infile) infile = paste(infile, collapse = ",") datain = normalizePath(datain) datain = unname(datain) args = paste0("--imain=", infile, " --datain=", datain) cmd = paste(cmd, args, opts) if (verbose) { message(cmd, "\n") } res = system(cmd) return(res) } apply_topup = function(...){ res = applytopup(...) return(res) } fsl_applytopup = function(...){ res = applytopup(...) return(res) }
check_tf_version <- function(alert = c("none", "error", "warn", "message", "startup")) { ac_flag <- Sys.getenv("RETICULATE_AUTOCONFIGURE") on.exit( Sys.setenv( RETICULATE_AUTOCONFIGURE = ac_flag ) ) Sys.setenv(RETICULATE_AUTOCONFIGURE = FALSE) alert <- match.arg(alert) if (is_mac_arm64()) { msg <- cli::format_error( c( "{.pkg greta} does not currently work with Apple Silicon (M1)", "We are working on getting this resolved ASAP, see {.url https://github.com/greta-dev/greta/issues/458} for current progress." ) ) stop( msg, call. = FALSE ) } if (!greta_stash$python_has_been_initialised) { cli_process_start( msg = "Initialising python and checking dependencies, this may take a \\ moment." ) } requirements_valid <- c( python_exists = have_python(), correct_tf = have_tf(), correct_tfp = have_tfp() ) if ((all(requirements_valid))) { if (!greta_stash$python_has_been_initialised) { cli_process_done( msg_done = "Initialising python and checking dependencies ... done!") cat("\n") greta_stash$python_has_been_initialised <- TRUE } } if (!all(requirements_valid)) { cli_process_failed() cli_msg <- c( "We have detected that you do not have the expected python packages \\ setup.", "You can set these up by running this R code in the console:", "{.code install_greta_deps()}", "Then, restart R and run:", "{.code library(greta)}", "({.strong Note}: Your R session should not have initialised \\ Tensorflow yet.)", "For more information, see {.code ?install_greta_deps}" ) message_text <- cli::format_message(cli_msg) warning_text <- cli::format_warning(cli_msg) error_text <- cli::format_error(cli_msg) switch( alert, error = stop(error_text, call. = FALSE), warn = warning(warning_text, call. = FALSE), message = message(message_text), startup = packageStartupMessage(message_text), none = NULL ) } invisible(all(requirements_valid)) } check_dims <- function(..., target_dim = NULL) { elem_list <- list(...) elem_list <- lapply(elem_list, as.greta_array) dim_list <- lapply(elem_list, dim) dims_paste <- vapply(dim_list, paste, "", collapse = "x") dims_text <- paste(dims_paste, collapse = ", ") scalars <- vapply(elem_list, is_scalar, FALSE) if (sum(!scalars) > 1) { match_first <- vapply(dim_list[!scalars], identical, FUN.VALUE = FALSE, dim_list[!scalars][[1]] ) if (!all(match_first)) { msg <- cli::format_error( "incompatible dimensions: {dims_text}" ) stop(msg, call. = FALSE) } } if (!is.null(target_dim)) { if (length(target_dim) == 1) { target_dim <- c(target_dim, 1) } target_dim <- as.integer(target_dim) if (!all(scalars)) { matches_target <- vapply(dim_list[!scalars], identical, FUN.VALUE = FALSE, target_dim ) if (!all(matches_target)) { msg <- cli::format_error( c( "incorrect array dimensions", "x" = "array dimensions should be \\ {paste(target_dim, collapse = 'x')},", "but input dimensions were {dims_text}." ) ) stop( msg, call. = FALSE ) } } output_dim <- target_dim } else { dim_lengths <- vapply(dim_list, length, numeric(1)) dim_list <- lapply(dim_list, pad_vector, to_length = max(dim_lengths)) output_dim <- do.call(pmax, dim_list) } output_dim } check_2d <- function(x) { if (length(dim(x)) != 2L) { msg <- cli::format_error( c( "Dimensions of parameters not compatible with multivariate \\ distribution parameters of multivariate distributions cannot have \\ more than two dimensions", "object {.var x} has dimensions: {paste(dim(x), collapse = 'x')}" ) ) stop( msg, call. = FALSE ) } } check_square <- function(x) { dim <- dim(x) ndim <- length(dim) is_square <- ndim == 2 && dim[1] == dim[2] if (!is_square) { msg <- cli::format_error( c( "Not 2D square greta array", "x" = "expected a 2D square greta array, but object {.var x} had \\ dimension: {paste(dim, collapse = 'x')}" ) ) stop( msg, call. = FALSE ) } } check_n_realisations <- function(vectors = list(), scalars = list(), target = NULL) { nrows <- lapply(c(vectors, scalars), nrow) single_rows <- unlist(nrows) == 1 if (sum(!single_rows) > 1) { match_first <- vapply(nrows[!single_rows], identical, FUN.VALUE = FALSE, nrows[!single_rows][[1]] ) if (!all(match_first)) { msg <- cli::format_error( c( "incompatible number of rows", x = "{paste(nrows, collapse = ' vs ')}" ) ) stop( msg, call. = FALSE ) } } if (!is.null(target)) { if (length(target) != 1 || target < 1) { msg <- cli::format_error( c( "{.code n_realisations is not a positive scalar interger}", "{.code n_realisations} must be a positive scalar integer giving \\ the number of rows of the output", "x" = "We see {.code n_realisations} = {.code {n_realisations}} \\ having class: \\ {.cls {class(n_realisations)}} and length \\ {.var {length(n_realisations)}}" ) ) stop( msg, call. = FALSE ) } target <- as.integer(target) if (!all(single_rows)) { matches_target <- vapply(nrows[!single_rows], identical, FUN.VALUE = FALSE, target ) if (!all(matches_target)) { msg <- cli::format_error( c( "Realisations do not match rows", "number of realisations should be {target},", "but arguments had {paste(nrows, collapse = ', ')} rows" ) ) stop( msg, call. = FALSE ) } } n_realisations <- target } else { n_realisations <- max(unlist(nrows)) } n_realisations } check_dimension <- function(vectors = list(), squares = list(), target = NULL, min_dimension = 2L) { ncols <- lapply(c(vectors, squares), ncol) if (!is.null(target)) { if (length(target) != 1 || target < 1 || !is.finite(target)) { msg <- cli::format_error( c( "{.var dimension} must be a positive scalar integer giving the \\ dimension of the distribution", "{.code dim(target)} returns: {dim(target)}" ) ) stop( msg, call. = FALSE ) } dimension <- as.integer(target) } else { dimension <- ncols[[1]] } if (dimension < min_dimension) { msg <- cli::format_error( c( "the dimension of this distribution must be at least \\ {min_dimension}, but was {dimension}", "multivariate distributions treat each {.emph row} as a separate \\ realisation - perhaps you need to transpose something?" ) ) stop( msg, call. = FALSE ) } match_dimension <- vapply(ncols, identical, dimension, FUN.VALUE = FALSE ) if (!all(match_dimension)) { msg <- cli::format_error( c( "distribution dimensions do not match implied dimensions", "The distribution dimension should be {dimension}, but parameters \\ implied dimensions: {paste(ncols, collapse = ' vs ')}", "Multivariate distributions treat each {.emph row} as a separate \\ realisation - perhaps you need to transpose something?" ) ) stop( msg, call. = FALSE) } dimension } check_multivariate_dims <- function(vectors = list(), scalars = list(), squares = list(), n_realisations = NULL, dimension = NULL, min_dimension = 2L) { vectors <- lapply(vectors, as.greta_array) scalars <- lapply(scalars, as.greta_array) squares <- lapply(squares, as.greta_array) lapply(c(vectors, scalars, squares), check_2d) lapply(squares, check_square) n_realisations <- check_n_realisations( vectors, scalars, n_realisations ) dimension <- check_dimension( vectors, squares, dimension, min_dimension ) c(n_realisations, dimension) } check_positive <- function(truncation) { if (truncation[1] < 0) { msg <- cli::format_error( c( "lower bound must be 0 or higher", "lower bound is: {.val {truncation[1]}}" ) ) stop( msg, call. = FALSE ) } } check_unit <- function(truncation) { if (truncation[1] < 0 | truncation[2] > 1) { msg <- cli::format_error( c( "lower and upper bounds must be between 0 and 1", "lower bound is: {.val {truncation[1]}}", "upper bound is: {.val {truncation[2]}}" ) ) stop( msg, call. = FALSE ) } } check_in_family <- function(function_name, arg) { if (missing(arg)) { arg_is_link <- TRUE } else { links <- c( "logit", "probit", "cloglog", "cauchit", "log", "identity", "sqrt" ) arg_is_link <- inherits(arg, "character") && length(arg) == 1 && arg %in% links } greta_function <- get(function_name, envir = asNamespace("greta")) family <- parent.frame(2)$family function_is_family <- !is.null(family) && identical(family, greta_function) if (arg_is_link | function_is_family) { msg <- cli::format_error( c( "Wrong function name provided in another model", "It looks like you're using {.pkg greta}'s {.fun {function_name}} \\ function in the family argument of another model.", "Maybe you want to use {.code family = stats::{function_name}},instead?" ) ) stop(msg, call. = FALSE) } } check_future_plan <- function() { plan_info <- future::plan() plan_is <- list( parallel = !inherits(plan_info, "sequential"), cluster = inherits(plan_info, "cluster"), multiprocess = inherits(plan_info, "multiprocess"), multisession = inherits(plan_info, "multisession"), local = TRUE ) if (plan_is$parallel) { if (plan_is$cluster) { test_if_forked_cluster() f <- future::future(NULL, laze = FALSE) workers <- f$workers if (inherits(workers, "cluster")) { worker <- workers[[1]] } if (!is.null(worker$host)) { localhosts <- c("localhost", "127.0.0.1", Sys.info()[["nodename"]]) plan_is$local <- worker$host %in% localhosts } } else { if (plan_is$multiprocess && !plan_is$multisession) { msg <- cli::format_error( "parallel mcmc samplers cannot be run with \\ {.code plan(multiprocess)} or {.code plan(multicore)}" ) stop( msg, call. = FALSE ) } } } plan_is } check_greta_arrays <- function(greta_array_list, fun_name, hint = NULL) { are_greta_arrays <- vapply(greta_array_list, inherits, "greta_array", FUN.VALUE = FALSE ) msg <- NULL if (length(greta_array_list) == 0) { msg <- cli::format_error( c( "could not find any non-data {.cls greta_array}s" ) ) } if (!all(are_greta_arrays)) { unexpected_items <- names(greta_array_list)[!are_greta_arrays] msg <- cli::format_error( c( "{.fun {fun_name}} arguments must be {.cls greta_array}s", "The following {cli::qty(length(unexpected_items))} object{?s} passed \\ to {.fun {fun_name}} {cli::qty(length(unexpected_items))} \\ {?is not a/are not} {.cls greta array}{?s}:", "{.val {unexpected_items}}", "{hint}" ) ) } if (!is.null(msg)) { stop( msg, call. = FALSE ) } greta_array_list } check_values_list <- function(values, env) { names <- names(values) stopifnot(length(names) == length(values)) fixed_greta_arrays <- lapply(names, get, envir = env) are_greta_arrays <- vapply(fixed_greta_arrays, inherits, "greta_array", FUN.VALUE = FALSE ) if (!all(are_greta_arrays)) { msg <- cli::format_error( "the names of arguments to values must all correspond to named \\ {.cls greta_array}s" ) stop( msg, call. = FALSE ) } assign_dim <- function(value, greta_array) { array <- unclass(get_node(greta_array)$value()) if (length(array) != length(value)) { msg <- cli::format_error( "a provided value has different number of elements than the \\ {.cls greta_array}" ) stop( msg, call. = FALSE ) } array[] <- value array } values <- mapply(assign_dim, values, fixed_greta_arrays, SIMPLIFY = FALSE ) list( fixed_greta_arrays = fixed_greta_arrays, values = values ) } check_dependencies_satisfied <- function(target, fixed_greta_arrays, dag, env) { dependency_names <- function(x) { get_node(x)$parent_names(recursive = TRUE) } dependencies <- dependency_names(target) complete_dependencies <- unlist( lapply( fixed_greta_arrays, dependency_names ) ) unmet <- !dependencies %in% complete_dependencies unmet_dependencies <- dependencies[unmet] unmet_nodes <- dag$node_list[unmet_dependencies] unmet_node_types <- vapply(unmet_nodes, node_type, FUN.VALUE = "") is_variable <- unmet_node_types == "variable" if (any(is_variable)) { greta_arrays <- all_greta_arrays(env, include_data = FALSE) greta_array_node_names <- vapply(greta_arrays, function(x) get_node(x)$unique_name, FUN.VALUE = "" ) unmet_variables <- unmet_nodes[is_variable] matches <- names(unmet_variables) %in% greta_array_node_names unmet_names_idx <- greta_array_node_names %in% names(unmet_variables) unmet_names <- names(greta_array_node_names)[unmet_names_idx] if (any(matches)) { names_text <- paste(unmet_names, collapse = ", ") msg <- cli::format_error( c( "Please provide values for the following {length(names_text)} \\ {.cls greta_array}{?s}:", "{.var {names_text}}" ) ) } else { msg <- cli::format_error( "The names of the missing {.cls greta_array}s could not be detected" ) } final_msg <- cli::format_error( c( "greta array(s) do not have values", "values have not been provided for all {.cls greta_array}s on which the \\ target depends, and {.var nsim} has not been set.", "{msg}" ) ) stop( msg, call. = FALSE ) } } check_cum_op <- function(x) { dims <- dim(x) if (length(dims) > 2 | dims[2] != 1) { msg <- cli::format_error( c( "{.var x} must be a column vector", "but {.var x} has dimensions {paste(dims, collapse = 'x')}" ) ) stop( msg, call. = FALSE ) } } check_n_cores <- function(n_cores, samplers, plan_is) { if (is.null(n_cores) & !plan_is$local) { return(NULL) } n_cores_detected <- future::availableCores() allowed_n_cores <- seq_len(n_cores_detected) if (!is.null(n_cores) && !n_cores %in% allowed_n_cores) { check_positive_integer(n_cores, "n_cores") msg <- cli::format_warning( "{n_cores} cores were requested, but only {n_cores_detected} \\ are available." ) warning( msg, call. = FALSE ) n_cores <- NULL } if (is.null(n_cores)) { n_cores <- floor(n_cores_detected / samplers) } n_cores <- max(n_cores, 1) as.integer(n_cores) } check_positive_integer <- function(x, name = "") { suppressWarnings(x <- as.integer(x)) if (length(x) != 1 | is.na(x) | x < 1) { msg <- cli::format_error( c( "{name} must be a positive integer", "However the value provided was: {.val {x}}" ) ) stop( msg, call. = FALSE ) } x } check_trace_batch_size <- function(x) { valid <- is.numeric(x) && length(x) == 1 && x >= 1 if (!valid) { msg <- cli::format_error( "{.var trace_batch_size} must be a single numeric value greater than or \\ equal to 1" ) stop( msg, call. = FALSE ) } x } complex_error <- function(z) { msg <- cli::format_error( "{.pkg greta} does not yet support complex numbers" ) stop( msg, call. = FALSE ) } Im.greta_array <- complex_error Re.greta_array <- complex_error Arg.greta_array <- complex_error Conj.greta_array <- complex_error Mod.greta_array <- complex_error checks_module <- module( check_tf_version, check_dims, check_unit, check_positive, check_in_family, check_future_plan, check_greta_arrays, check_values_list, check_dependencies_satisfied, check_cum_op, check_future_plan, check_n_cores, check_positive_integer, complex_error )
binom.test <- function(x, n, p = 0.5, alternative = c("two.sided", "less", "greater"), conf.level = 0.95) { DNAME <- deparse(substitute(x)) xr <- round(x) if(any(is.na(x) | (x < 0)) || max(abs(x-xr)) > 1e-7) stop("'x' must be nonnegative and integer") x <- xr if(length(x) == 2L) { n <- sum(x) x <- x[1L] } else if(length(x) == 1L) { nr <- round(n) if((length(n) > 1L) || is.na(n) || (n < 1) || abs(n-nr) > 1e-7 || (x > nr)) stop("'n' must be a positive integer >= 'x'") DNAME <- paste(DNAME, "and", deparse(substitute(n))) n <- nr } else stop("incorrect length of 'x'") if(!missing(p) && (length(p) > 1L || is.na(p) || p < 0 || p > 1)) stop ("'p' must be a single number between 0 and 1") alternative <- match.arg(alternative) if(!((length(conf.level) == 1L) && is.finite(conf.level) && (conf.level > 0) && (conf.level < 1))) stop("'conf.level' must be a single number between 0 and 1") PVAL <- switch(alternative, less = pbinom(x, n, p), greater = pbinom(x - 1, n, p, lower.tail = FALSE), two.sided = { if(p == 0) (x == 0) else if(p == 1) (x == n) else { relErr <- 1 + 1e-7 d <- dbinom(x, n, p) m <- n * p if (x == m) 1 else if (x < m) { i <- seq.int(from = ceiling(m), to = n) y <- sum(dbinom(i, n, p) <= d * relErr) pbinom(x, n, p) + pbinom(n - y, n, p, lower.tail = FALSE) } else { i <- seq.int(from = 0, to = floor(m)) y <- sum(dbinom(i, n, p) <= d * relErr) pbinom(y - 1, n, p) + pbinom(x - 1, n, p, lower.tail = FALSE) } } }) p.L <- function(x, alpha) { if(x == 0) 0 else qbeta(alpha, x, n - x + 1) } p.U <- function(x, alpha) { if(x == n) 1 else qbeta(1 - alpha, x + 1, n - x) } CINT <- switch(alternative, less = c(0, p.U(x, 1 - conf.level)), greater = c(p.L(x, 1 - conf.level), 1), two.sided = { alpha <- (1 - conf.level) / 2 c(p.L(x, alpha), p.U(x, alpha)) }) attr(CINT, "conf.level") <- conf.level ESTIMATE <- x / n names(x) <- "number of successes" names(n) <- "number of trials" names(ESTIMATE) <- names(p) <- "probability of success" structure(list(statistic = x, parameter = n, p.value = PVAL, conf.int = CINT, estimate = ESTIMATE, null.value = p, alternative = alternative, method = "Exact binomial test", data.name = DNAME), class = "htest") }
graycode2 <- function(a) { rows <- 2^floor(a/2) cols <- 2^(a - floor(a/2)) dec <- grays(a) dim(dec) <- c(cols, rows) dec <- t(dec) nrow_dec <- nrow(dec) if (nrow_dec == 1) { return(list(rows, cols, dec)) } else if (nrow_dec == 2) { dec[2, ] <- rev(dec[2, ]) return(list(rows, cols, dec)) } else { dec[seq(2, nrow_dec, 2), ] <- t(apply(dec[seq(2, nrow_dec, 2), ], 1, rev)) return(list(rows, cols, dec)) } }
table_scrap <- function(link, choose = 1, header = TRUE, fill = FALSE, askRobot = FALSE) { if(missing(link)) { stop("'link' is a mandatory parameter") } if(!is.character(link)) { stop("'link' parameter must be provided as a character string") } if(!is.numeric(choose)){ stop(paste0("the 'choose' parameter must be provided as numeric not as "), typeof(choose)) } if (askRobot) { if (paths_allowed(link) == TRUE) { message(green("the robot.txt doesn't prohibit scraping this web page")) } else { message(bgRed( "WARNING: the robot.txt doesn't allow scraping this web page" )) } } tryCatch( expr = { table <- link %>% read_html() %>% html_table(header, fill = fill) chosen_table <- table[[choose]] return(chosen_table) }, error = function(cond){ if(!has_internet()){ message(paste0("Please check your internet connexion: ", cond)) return(NA) } else if (grepl("current working directory", cond) || grepl("HTTP error 404", cond)) { message(paste0("The URL doesn't seem to be a valid one: ", link)) message(paste0("Here the original error message: ", cond)) return(NA) } else if(grepl("subscript out of bounds", cond)) { message( "Are you sure that your web page contains more than one HTML table ?" ) message(paste0("Here the original error message: ", cond)) return(NA) } else { message(paste0("Undefined Error: ", cond)) return(NA) } } )}
library(ggplot2) library(ggiraph) set.seed(4393) dsmall <- diamonds[sample(nrow(diamonds), 1000),] p <- ggplot(dsmall, aes(x, y)) + stat_density_2d(aes( fill = stat(nlevel), tooltip = paste("nlevel:", stat(nlevel)) ), geom = "interactive_polygon") + facet_grid(. ~ cut) p1 <- p + scale_fill_viridis_c_interactive(data_id = "nlevel", tooltip = "nlevel") x <- girafe(ggobj = p1) if (interactive()) print(x) p2 <- p + scale_fill_viridis_c_interactive(data_id = "nlevel", tooltip = "nlevel", guide = "legend") x <- girafe(ggobj = p2) if (interactive()) print(x) p3 <- p + scale_fill_viridis_c_interactive( data_id = function(breaks) { as.character(breaks) }, tooltip = function(breaks) { as.character(breaks) }, guide = "legend" ) x <- girafe(ggobj = p3) if (interactive()) print(x) p4 <- p + scale_fill_viridis_c_interactive( data_id = function(breaks) { as.character(breaks) }, tooltip = function(breaks) { as.character(breaks) }, guide = "legend", name = label_interactive("nlevel", data_id = "nlevel", tooltip = "nlevel"), labels = function(breaks) { label_interactive( as.character(breaks), data_id = as.character(breaks), onclick = paste0("alert(\"", as.character(breaks), "\")"), tooltip = as.character(breaks) ) } ) x <- girafe(ggobj = p4) x <- girafe_options(x, opts_hover_key(girafe_css("stroke:red", text="stroke:none;fill:red"))) if (interactive()) print(x)
CRI <- function(level){ x <- NULL if(level==1){ x1 <- github.cssegisanddata.covid19(country = "Costa Rica") x2 <- ourworldindata.org(id = "CRI") x <- full_join(x1, x2, by = "date") } return(x) }
calcul_part_ens <- function(data,var) { msg_error1<-msg_error2 <- NULL if(any(class(data)!="data.frame")) msg_error1 <- "Les donnees doivent etre dans un data.frame / " if(!any(names(data) %in% var)) msg_error2 <- "La variable identifiant les donnees n'existe pas dans la table des donnees / " if(any(!is.null(msg_error1),!is.null(msg_error2))) { stop(simpleError(paste0(msg_error1,msg_error2))) } if(sum(data[,var],na.rm = TRUE)==0) { data[data[,var] %in% 0,var] <- 0.0001 } data$PART <- (data[,var]/sum(data[,var],na.rm = TRUE))*100 return(data) }
"pew_energy_2018"
viz_type <- c( "Distribution" = "dist", "Density" = "density", "Scatter" = "scatter", "Surface" = "surface", "Line" = "line", "Bar" = "bar", "Box-plot" = "box" ) viz_check <- c("Line" = "line", "Loess" = "loess", "Jitter" = "jitter", "Interpolate" = "interpolate") viz_axes <- c( "Flip" = "flip", "Log X" = "log_x", "Log Y" = "log_y", "Scale-y" = "scale_y", "Density" = "density", "Sort" = "sort" ) viz_theme <- c( "Gray" = "theme_gray", "Black and White" = "theme_bw", "Light" = "theme_light", "Dark" = "theme_dark", "Minimal" = "theme_minimal", "Classic" = "theme_classic" ) os_type = Sys.info()["sysname"] if (os_type == "Windows") { fnt <- names(windowsFonts()) names(fnt) <- tools::toTitleCase(fnt) viz_base_family <- c("Theme default" = "", fnt) } else { viz_base_family = c( "Theme default" = "", "Helvetica" = "Helvetica", "Serif" = "serif", "Sans" = "sans", "Mono" = "mono", "Courier" = "Courier", "Times" = "Times" ) } viz_labs <- c("title", "subtitle", "caption", "x", "y") viz_add_labs <- function() { lab_list <- list() for(l in viz_labs) { inp <- input[[paste0("viz_labs_", l)]] if(!radiant.data::is_empty(inp)) lab_list[[l]] <- inp } lab_list } viz_args <- as.list(formals(visualize)) viz_inputs <- reactive({ viz_args$data_filter <- if (isTRUE(input$show_filter)) input$data_filter else "" viz_args$dataset <- input$dataset viz_args$shiny <- input$shiny viz_args$labs <- viz_add_labs() for (i in r_drop(names(viz_args), drop = c("dataset", "data_filter", "labs"))) viz_args[[i]] <- input[[paste0("viz_", i)]] viz_args }) output$ui_viz_type <- renderUI({ selectInput( inputId = "viz_type", label = "Plot-type:", choices = viz_type, selected = state_single("viz_type", viz_type), multiple = FALSE ) }) output$ui_viz_nrobs <- renderUI({ req(input$viz_type == "scatter") nrobs <- nrow(.get_data()) choices <- c("1,000" = 1000, "5,000" = 5000, "10,000" = 10000, "All" = -1) %>% .[. < nrobs] selectInput( "viz_nrobs", "Number of data points plotted:", choices = choices, selected = state_single("viz_nrobs", choices, 1000) ) }) output$ui_viz_yvar <- renderUI({ req(input$viz_type) vars <- varying_vars() req(available(vars)) vars <- vars["date" != .get_class()[vars]] if (input$viz_type %in% c("line", "bar", "scatter", "surface", "box")) { vars <- vars["character" != .get_class()[vars]] } if (input$viz_type %in% c("line", "scatter", "box")) { vars <- vars["factor" != .get_class()[vars]] } selectInput( inputId = "viz_yvar", label = "Y-variable:", choices = vars, selected = state_multiple("viz_yvar", vars, isolate(input$viz_yvar)), multiple = TRUE, size = min(3, length(vars)), selectize = FALSE ) }) output$ui_viz_xvar <- renderUI({ req(input$viz_type) vars <- varying_vars() req(available(vars)) if (input$viz_type == "dist") vars <- vars["date" != .get_class()[vars]] if (input$viz_type == "density") vars <- vars["factor" != .get_class()[vars]] if (input$viz_type %in% c("box", "bar")) vars <- groupable_vars_nonum() selectInput( inputId = "viz_xvar", label = "X-variable:", choices = vars, selected = state_multiple("viz_xvar", vars, isolate(input$viz_xvar)), multiple = TRUE, size = min(3, length(vars)), selectize = FALSE ) }) output$ui_viz_comby <- renderUI({ checkboxInput( "viz_comby", "Combine Y-variables in one plot", state_init("viz_comby", FALSE) ) }) output$ui_viz_combx <- renderUI({ checkboxInput( "viz_combx", "Combine X-variables in one plot", state_init("viz_combx", FALSE) ) }) observeEvent(length(input$viz_xvar) < 2, { updateCheckboxInput(session, "viz_combx", value = FALSE) }) observeEvent(length(input$viz_yvar) < 2, { updateCheckboxInput(session, "viz_comby", value = FALSE) }) observeEvent(input$viz_type, { if (input$viz_type %in% c("dist", "density")) { updateCheckboxInput(session, "viz_comby", value = FALSE) } else { updateCheckboxInput(session, "viz_combx", value = FALSE) } }) observeEvent(input$viz_check, { if (!"loess" %in% input$viz_check && input$viz_smooth != 1) { updateSliderInput(session, "viz_smooth", value = 1) } }) output$ui_viz_facet_row <- renderUI({ vars <- c("None" = ".", groupable_vars_nonum()) selectizeInput( "viz_facet_row", "Facet row:", vars, selected = state_single("viz_facet_row", vars, init = "."), multiple = FALSE ) }) output$ui_viz_facet_col <- renderUI({ vars <- c("None" = ".", groupable_vars_nonum()) selectizeInput( "viz_facet_col", "Facet column:", vars, selected = state_single("viz_facet_col", vars, init = "."), multiple = FALSE ) }) output$ui_viz_color <- renderUI({ req(input$viz_type) if (input$viz_type == "line") { vars <- c("None" = "none", groupable_vars()) } else { vars <- c("None" = "none", varnames()) } if (isTRUE(input$viz_comby) && length(input$viz_yvar) > 1) vars <- c("None" = "none") selectizeInput( "viz_color", "Color:", vars, multiple = FALSE, selected = state_single("viz_color", vars, init = "none") ) }) output$ui_viz_fill <- renderUI({ vars <- c("None" = "none", groupable_vars()) if (isTRUE(input$viz_combx) && length(input$viz_xvar) > 1) vars <- vars[1] selectizeInput( "viz_fill", "Fill:", vars, multiple = FALSE, selected = state_single("viz_fill", vars, init = "none") ) }) output$ui_viz_size <- renderUI({ req(input$viz_type) isNum <- .get_class() %in% c("integer", "numeric", "ts") vars <- c("None" = "none", varnames()[isNum]) if (isTRUE(input$viz_comby) && length(input$viz_yvar) > 1) vars <- c("None" = "none") selectizeInput( "viz_size", "Size:", vars, multiple = FALSE, selected = state_single("viz_size", vars, init = "none") ) }) output$ui_viz_axes <- renderUI({ req(input$viz_type) ind <- 1 if (input$viz_type %in% c("line", "scatter", "surface")) { ind <- 1:3 } else if (input$viz_type == "dist") { ind <- c(1:2, 5) } else if (input$viz_type == "density") { ind <- 1:2 } else if (input$viz_type %in% c("bar", "box")) { ind <- c(1, 3) } if (!radiant.data::is_empty(input$viz_facet_row, ".") || !radiant.data::is_empty(input$viz_facet_col, ".")) ind <- c(ind, 4) if (input$viz_type == "bar") ind <- c(ind, 6) checkboxGroupInput( "viz_axes", NULL, viz_axes[ind], selected = state_group("viz_axes", ""), inline = TRUE ) }) output$ui_viz_check <- renderUI({ req(input$viz_type) if (input$viz_type == "scatter") { ind <- 1:3 } else if (input$viz_type == "box") { ind <- 3 } else if (input$viz_type == "surface") { ind <- 4 } else { ind <- c() } if (!input$viz_type %in% c("scatter", "box")) { r_state$viz_check <<- gsub("jitter", "", r_state$viz_check) } if (input$viz_type != "scatter") { r_state$viz_check <<- gsub("line", "", r_state$viz_check) r_state$viz_check <<- gsub("loess", "", r_state$viz_check) } checkboxGroupInput( "viz_check", NULL, viz_check[ind], selected = state_group("viz_check", ""), inline = TRUE ) }) output$ui_viz_run <- renderUI({ req(input$dataset) actionButton("viz_run", "Create plot", width = "100%", icon = icon("play"), class = "btn-success") }) output$ui_viz_labs <- renderUI({ req(input$dataset) wellPanel( textAreaInput("viz_labs_title", NULL, "", placeholder = "Title", rows = 1), textAreaInput("viz_labs_subtitle", NULL, "", placeholder = "Subtitle", rows = 1), textAreaInput("viz_labs_caption", NULL, "", placeholder = "Caption", rows = 1), textAreaInput("viz_labs_y", NULL, "", placeholder = "Y-label", rows = 1), textAreaInput("viz_labs_x", NULL, "", placeholder = "X-label", rows = 1) ) }) output$ui_viz_colors <- renderUI({ tagList( conditionalPanel( condition = "input.viz_type == 'bar' || input.viz_type == 'dist' || input.viz_type == 'box' || input.viz_type == 'density'", selectInput( "viz_fillcol", "Fill color:", choices = colors(), selected = state_single("viz_fillcol", colors(), "blue") ) ), conditionalPanel( condition = "input.viz_type == 'dist' || input.viz_type == 'density' || input.viz_type == 'box' || input.viz_type == 'scatter' || input.viz_type == 'line'", selectInput( "viz_linecol", "Line color:", choices = colors(), selected = state_single("viz_linecol", colors(), "black") ) ), conditionalPanel( condition = "input.viz_type == 'scatter' || input.viz_type == 'line' || input.viz_type == 'box'", selectInput( "viz_pointcol", "Point color:", choices = colors(), selected = state_single("viz_pointcol", colors(), "black") ) ) ) }) run_refresh( viz_args, "viz", init = "xvar", label = "Create plot", relabel = "Update plot", inputs = c("labs_title", "labs_subtitle", "labs_caption", "labs_y", "labs_x") ) output$ui_Visualize <- renderUI({ tagList( wellPanel( uiOutput("ui_viz_run") ), checkboxInput("viz_details_main", "Main", state_init("viz_details_main", TRUE)), conditionalPanel("input.viz_details_main == true", wellPanel( uiOutput("ui_viz_type"), conditionalPanel("input.viz_type == 'scatter'", uiOutput("ui_viz_nrobs") ), conditionalPanel( condition = "input.viz_type != 'dist' && input.viz_type != 'density'", uiOutput("ui_viz_yvar"), conditionalPanel( "input.viz_yvar != undefined && input.viz_yvar != null && input.viz_yvar.length > 1", uiOutput("ui_viz_comby") ) ), uiOutput("ui_viz_xvar"), conditionalPanel( "input.viz_type == 'dist' || input.viz_type == 'density'", conditionalPanel( "input.viz_xvar != undefined && input.viz_xvar != null && input.viz_xvar.length > 1", uiOutput("ui_viz_combx") ) ), uiOutput("ui_viz_facet_row"), uiOutput("ui_viz_facet_col"), conditionalPanel( condition = "input.viz_type == 'bar' || input.viz_type == 'dist' || input.viz_type == 'density' || input.viz_type == 'surface'", uiOutput("ui_viz_fill") ), conditionalPanel( condition = "input.viz_type == 'scatter' || input.viz_type == 'line' || input.viz_type == 'box'", uiOutput("ui_viz_color") ), conditionalPanel( condition = "input.viz_type == 'scatter'", uiOutput("ui_viz_size") ), conditionalPanel( condition = "input.viz_type == 'bar' || input.viz_type == 'scatter' || input.viz_type == 'line'", selectInput( "viz_fun", "Function:", choices = getOption("radiant.functions"), selected = state_single("viz_fun", getOption("radiant.functions"), "mean") ) ), conditionalPanel( condition = "input.viz_type == 'scatter' || input.viz_type == 'line' || input.viz_type == 'surface' || input.viz_type == 'box'", uiOutput("ui_viz_check") ), uiOutput("ui_viz_axes"), conditionalPanel( condition = "input.viz_type == 'dist'", sliderInput( "viz_bins", label = "Number of bins:", value = state_init("viz_bins", 10), min = 2, max = 50, step = 1 ) ), conditionalPanel( "input.viz_type == 'density' || input.viz_type == 'dist' && (input.viz_axes && input.viz_axes.indexOf('density')) >= 0 || (input.viz_type == 'scatter' && (input.viz_check && input.viz_check.indexOf('loess') >= 0))", sliderInput( "viz_smooth", label = "Smooth:", value = state_init("viz_smooth", 1), min = 0.1, max = 3, step = .1 ) ) ) ), checkboxInput("viz_details_labels", "Labels", state_init("viz_details_labels", FALSE)), conditionalPanel("input.viz_details_labels == true", uiOutput("ui_viz_labs") ), checkboxInput("viz_details_style", "Style", state_init("viz_details_style", FALSE)), conditionalPanel("input.viz_details_style == true", wellPanel( selectInput( "viz_theme", "Plot theme:", choices = viz_theme, selected = state_single("viz_theme", viz_theme, "theme_gray") ), numericInput( "viz_base_size", "Base font size:", value = state_init("viz_base_size", 11) ), selectInput( "viz_base_family", "Font family:", choices = viz_base_family, selected = state_single("viz_base_family", viz_base_family, "helvetica") ), uiOutput("ui_viz_colors"), sliderInput( "viz_alpha", label = "Opacity:", value = state_init("viz_alpha", .5), min = 0, max = 1, step = .01 ), tags$table( tags$td( numericInput( "viz_plot_height", label = "Plot height:", min = 100, max = 2000, step = 50, value = state_init("viz_plot_height", r_info[["plot_height"]]), width = "117px" ) ), tags$td( numericInput( "viz_plot_width", label = "Plot width:", min = 100, max = 2000, step = 50, value = state_init("viz_plot_width", r_info[["plot_width"]]), width = "117px" ), width = "100%" ) ) ) ), help_and_report( modal_title = "Visualize", fun_name = "visualize", help_file = inclRmd(file.path(getOption("radiant.path.data"), "app/tools/help/visualize.md")), lic = "by-sa" ) ) }) viz_plot_width <- reactive({ if (radiant.data::is_empty(input$viz_plot_width)) r_info[["plot_width"]] else input$viz_plot_width }) viz_plot_height <- eventReactive({ input$viz_run input$viz_plot_height input$viz_plot_width }, { if (radiant.data::is_empty(input$viz_plot_height)) { r_info[["plot_height"]] } else { lx <- ifelse(not_available(input$viz_xvar) || isTRUE(input$viz_combx), 1, length(input$viz_xvar)) ly <- ifelse(not_available(input$viz_yvar) || input$viz_type %in% c("dist", "density") || isTRUE(input$viz_comby), 1, length(input$viz_yvar)) nr <- lx * ly if (nr > 1) { (input$viz_plot_height / 2) * ceiling(nr / 2) } else { input$viz_plot_height } } }) output$visualize <- renderPlot({ req(input$viz_type) if (not_available(input$viz_xvar)) { if (input$viz_type != "box") { return( plot( x = 1, type = "n", main = "\nPlease select variables from the dropdown menus to create a plot", axes = FALSE, xlab = "", ylab = "", cex.main = .9 ) ) } } .visualize() %>% { if (is.character(.)) { plot(x = 1, type = "n", main = paste0("\n", .), axes = FALSE, xlab = "", ylab = "", cex.main = .9) } else if (length(.) > 0) { print(.) } } }, width = viz_plot_width, height = viz_plot_height, res = 96) .visualize <- eventReactive(input$viz_run, { req(input$viz_type) if (input$viz_type == "scatter") req(input$viz_nrobs) req(input$viz_plot_height && input$viz_plot_width) if (not_available(input$viz_xvar) && input$viz_type != "box") return() if (input$viz_type %in% c("scatter", "line", "box", "bar", "surface") && not_available(input$viz_yvar)) { return("No Y-variable provided for a plot that requires one") } if (input$viz_type == "box" && !all(input$viz_xvar %in% groupable_vars())) return() if (input$viz_type %in% c("dist", "density")) { if (isTRUE(input$viz_comby)) return() if (length(input$viz_xvar) > 1 && is.null(input$viz_combx)) return() } else { if (isTRUE(input$viz_combx)) return() if (length(input$viz_yvar) > 1 && is.null(input$viz_comby)) return() } req(!is.null(input$viz_color) || !is.null(input$viz_fill)) vizi <- viz_inputs() vizi$shiny <- TRUE vizi$envir <- r_data withProgress(message = "Making plot", value = 1, { do.call(visualize, vizi) }) }) observeEvent(input$visualize_report, { vi <- viz_inputs() if (input$viz_type != "dist") { vi$bins <- viz_args$bins } if (input$viz_type %in% c("dist", "density")) { vi$yvar <- viz_args$yvar } if (!input$viz_type %in% c("density", "scatter", "dist") || !("loess" %in% input$viz_check || "density" %in% input$viz_axes || input$viz_type == "density")) { vi$smooth <- viz_args$smooth } if (!input$viz_type %in% c("scatter", "box") && "jitter" %in% input$viz_check) { vi$check <- base::setdiff(vi$check, "jitter") } if (input$viz_type != "scatter") { vi$size <- "none" vi$nrobs <- NULL } else { vi$nrobs <- as_integer(vi$nrobs) } if (!input$viz_type %in% c("scatter", "line", "box")) { vi$color <- NULL } if (!input$viz_type %in% c("bar", "dist", "density", "surface")) { vi$fill <- NULL } if (!input$viz_type %in% c("bar", "dist", "box", "density")) { vi$fillcol <- "blue" } if (!input$viz_type %in% c("dist", "density", "box", "scatter", "line")) { vi$linecol <- "black" } if (!input$viz_type %in% c("box", "scatter", "line")) { vi$pointcol <- "black" } if (!input$viz_type %in% c("bar", "line", "scatter")) { vi$fun <- "mean" } inp_main <- c(clean_args(vi, viz_args), custom = FALSE) update_report( inp_main = inp_main, fun_name = "visualize", outputs = character(0), pre_cmd = "", figs = TRUE, fig.width = viz_plot_width(), fig.height = viz_plot_height() ) }) download_handler( id = "dlp_visualize", fun = download_handler_plot, fn = function() paste0(input$dataset, "_visualize"), type = "png", caption = "Save visualize plot", plot = .visualize, width = viz_plot_width, height = viz_plot_height )
if (require("testthat") && require("effectsize")) { test_that("sd_pooled", { expect_equal(sd_pooled(1:4, 1:3 * 5), 3.316625, tolerance = 0.001) expect_equal(mad_pooled(1:4, 1:3 * 5), 3.297154, tolerance = 0.001) expect_equal(sd_pooled(c(1:3, 40), 1:3 * 5), 15.06652, tolerance = 0.001) expect_equal(mad_pooled(c(1:3, 40), 1:3 * 5), 3.297154, tolerance = 0.001) }) }
quit() pdf(file.path(tempdir(), "segmentation.pdf")) library("AntMAN") set.seed(123) LoadAndGenerate <- function(img_path) { library(jpeg) img <- readJPEG(img_path) plot(1:2, type='n') rasterImage(img, 1.01, 1.01, 1.99, 1.99) imgDm <- dim(img) imgRGB <- data.frame( x = rep(1:imgDm[2], each = imgDm[1]), y = rep(imgDm[1]:1, imgDm[2]), R = as.vector(img[,,1]), G = as.vector(img[,,2]), B = as.vector(img[,,3]) ) x <- imgRGB[,c(3,4,5)] return (list(pic = x, dim = imgDm)) } DrawMat <- function(pic,imgDm) { img_seg <- array(dim=imgDm) img_seg[,,1] <- matrix(pic[,1],nrow=imgDm[1],ncol=imgDm[2]) img_seg[,,2] <- matrix(pic[,2],nrow=imgDm[1],ncol=imgDm[2]) img_seg[,,3] <- matrix(pic[,3],nrow=imgDm[1],ncol=imgDm[2]) plot(1:2, type='n') rasterImage(img_seg, 1.01, 1.01, 1.99, 1.99) } DrawResult <- function(mat,imgDm,clusters) { clusters = clusters / max(clusters) img_seg <- array(dim=imgDm) img_seg[,,1] <- matrix(clusters,nrow=imgDm[1],ncol=imgDm[2]) img_seg[,,2] <- matrix(clusters,nrow=imgDm[1],ncol=imgDm[2]) img_seg[,,3] <- matrix(clusters,nrow=imgDm[1],ncol=imgDm[2]) plot(1:2, type='n') rasterImage(img_seg, 1.01, 1.01, 1.99, 1.99) } data(brain) imgDm <- brain$dim x = brain$pic bn <- imgDm[1] * imgDm[2] mat <- matrix(0,bn,3) mat[,1 ] <-x$R mat[,2 ] <-x$G mat[,3 ] <-x$B DrawMat(mat,imgDm) mixture_mvn_params = AM_mix_hyperparams_multinorm (mu0=c(0,0,0),ka0=.1,nu0=5,Lam0=0.1*diag(3)) mcmc_params = AM_mcmc_parameters(niter=10000, burnin=5000, thin=5, verbose=0, output = c("CI","K","M")) components_prior = AM_mix_components_prior_pois (init=5,a=10,b=2) weights_prior = AM_mix_weights_prior_gamma(init=2, a=1, b=1) set.seed(523) fit <- AM_mcmc_fit( init_K = 1, y = mat, mix_kernel_hyperparams = mixture_mvn_params, mix_components_prior =components_prior, mix_weight_prior = weights_prior, mcmc_parameters = mcmc_params) summary (fit)
stopifnot(require(testthat)) context("issue library(naturalsort) test_that("Produces an error when all elements are empty character", { text <- "" expected <- "" actual <- naturalsort(text) expect_that(actual, equals(expected)) })
.tmp_dir <- function(dir_out, action = 2, change_raster_tmp = F, tmp_orig = NULL) { tmp_dir <- file.path(dir_out, "tmp") if (dir.exists(tmp_dir) && action == 2) { unlink(tmp_dir, recursive = T) } if (action == 1) { dir.create(tmp_dir) } if (isTRUE(change_raster_tmp)) { if (action == 1) { rasterOptions(tmpdir = tmp_dir) } else { rasterOptions(tmpdir = tmp_orig) } } return(tmp_dir) } .delete_tmp_files <- function(dir, patterns = c(".gri", ".grd")) { patterns <- paste0(patterns, "$") files <- unlist(sapply(patterns, function(p) list.files(dir, pattern = p))) paths_del <- file.path(dir, files) del <- sapply(paths_del, function(path) { try <- try(unlink(path)) }) } .column_summary <- function(records, records.names, download_success = F) { gSD.cols <- grep("gSD", colnames(records)) if (length(gSD.cols > 0)) records <- records[, -gSD.cols] diff.cols <- setdiff(colnames(records), records.names) if (length(diff.cols) > 0) out(paste0("Columns added to records: '", paste0(diff.cols, collapse = "', '"), "'")) if (isTRUE(download_success)) { if (!is.null(records$download_success)) { if (any(!records$download_success)) { out(paste0("Some downloads have not been succesfull after ", max(records$download_attempts), " attempt(s) (see column 'download_success'). Please retry later."), type = 2) } else { out(paste0("All downloads have been succesfull after ", max(records$download_attempts), " attempt(s)."), msg = T) } } } return(records) } .translate_records <- function(records, product_name, simplify_cols = TRUE) { records.names <- colnames(records) <- gsub("[.]", "", tolower(colnames(records))) dict <- getOption("gSD.clients_dict") dict$clients <- gsub("[.]", "", tolower(dict$clients)) pos.names <- match(dict$clients, colnames(records)) records.tr <- records[, as.numeric(na.omit(pos.names))] colnames(records.tr) <- dict$gSD[!is.na(pos.names)] if (isTRUE(simplify_cols)) { records <- records.tr } else { records <- cbind(records.tr, records[, -as.numeric(na.omit(pos.names))]) } products <- get_products(grouped = T, update_online = F) records$product_group <- product_group <- names(products)[sapply(products, function(x) any(grepl(product_name, x)))] records$product <- product_name if (unique(records$product_group) == "sentinel") { records$date_acquisition <- sapply(strsplit(records$start_time, "T"), "[", 1) records$md5_url <- paste0(records$md5_url, "Checksum/Value/$value") } if (unique(records$product == "sentinel-2")) { records$tile_id[is.na(records$tile_id)] <- sapply(strsplit(records$record_id[is.na(records$tile_id)], "_"), function(x) { gsub("T", "", x[nchar(x) == 6 & substr(x, 1, 1) == "T"]) }) } records$record_id <- gsub("[.]", "_", gsub(":", "_", records$record_id)) if (product_group == "sentinel") { records$start_time <- as.POSIXct(strptime(records$start_time, "%Y-%m-%dT%T", tz = "UTC")) records$stop_time <- as.POSIXct(strptime(records$stop_time, "%Y-%m-%dT%T", tz = "UTC")) records$date_acquisition <- as.Date(records$date_acquisition) } if (product_group == "landsat") { records$start_time <- as.POSIXct(strptime(records$start_time, "%Y:%j:%T", tz = "UTC")) records$stop_time <- as.POSIXct(strptime(records$stop_time, "%Y:%j:%T", tz = "UTC")) records$date_acquisition <- as.Date(records$start_time) records$start_date <- records$stop_date <- NULL } if (product_group == "modis") { records$start_time <- as.POSIXct(strptime(records$start_date, "%Y-%m-%d %T", tz = "UTC")) records$stop_time <- as.POSIXct(strptime(records$stop_date, "%Y-%m-%d %T", tz = "UTC")) records$date_acquisition <- as.Date(records$date_acquisition) records$start_date <- records$stop_date <- NULL } if (product_group == "srtm") { records$start_time <- as.POSIXct(strptime(records$start_time, "%Y-%m-%dT%T", tz = "UTC")) records$stop_time <- as.POSIXct(strptime(records$stop_time, "%Y-%m-%dT%T", tz = "UTC")) records$date_acquisition <- as.Date(records$start_time) } return(records) } .unlist_df <- function(records) { for (i in 1:NCOL(records)) { column <- records[, i] not_matrix <- ifelse(inherits(records, SF()), !is.matrix(column[[1]][[1]]), !is.matrix(column[[1]][[1]][[1]])) if (inherits(column, LIST())) { if (not_matrix) { column <- unlist(column) if (!is.matrix(column) && length(column) == NROW(records)) { records[, i] <- unlist(column) } } } } return(records) } rbind.different <- function(x) { if (.is_empty_array(x)) { return(x) } else { x.bind <- x[[1]] for (i in 2:length(x)) { x.diff <- setdiff(colnames(x.bind), colnames(x[[i]])) y.diff <- setdiff(colnames(x[[i]]), colnames(x.bind)) x.bind[, c(as.character(y.diff))] <- NA x[[i]][, c(as.character(x.diff))] <- NA x.bind <- rbind(x.bind, x[[i]]) } return(x.bind) } } .calc_aoi_area <- function(aoi) { if (!.is_sf(aoi)) { aoi <- st_as_sf(aoi) } aoi_area <- st_area(aoi) if (length(aoi_area) > 1) { aoi_area <- sum(aoi_area) } return(as.numeric(aoi_area) / 1000) } .calc_aoi_coverage <- function(x, aoi, aoi_ncell = NULL) { if (is.null(aoi_ncell)) aoi_ncell <- .calc_aoi_corr_vals(aoi, x) x_vals <- getValues(x) x_valid <- length(x_vals[!is.na(x_vals)]) percent <- (x_valid / aoi_ncell) * 100 return(percent) } .calc_aoi_corr_vals <- function(aoi, x) { e <- as.vector(st_bbox(aoi)) r <- raster(xmn = e[1], xmx = e[3], ymn = e[2], ymx = e[4], crs = crs(x), resolution = res(x)) values(r) <- as.integer(1) r <- .mask_raster_by_polygon(r, aoi) r_vals <- getValues(r) aoi_npixels <- length(which(r_vals == 1)) return(aoi_npixels) } .has_SAR <- function(products) { sentinel1 <- name_product_sentinel1() if (sentinel1 %in% products) { has_SAR <- ifelse(all(products == sentinel1), 100, 1) } else { has_SAR <- 0 } } .make_tileid <- function(records) { if (is.null(getElement(records, name_tile_id()))) records[name_tile_id()] <- NA_character_ has_tileid <- !is.na(getElement(records, name_tile_id())) has_vertical <- if (!is.null(getElement(records, name_tile_number_vertical()))) !is.na(getElement(records, name_tile_number_vertical())) else rep(FALSE, nrow(records)) has_horizontal <- if (!is.null(getElement(records, name_tile_number_horizontal()))) !is.na(getElement(records, name_tile_number_horizontal())) else rep(FALSE, nrow(records)) sub <- !has_tileid & has_vertical & has_horizontal if (any(sub)) { horizontal <- getElement(records[sub, ], name_tile_number_horizontal()) vertical <- getElement(records[sub, ], name_tile_number_vertical()) records[sub, name_tile_id()] <- paste0(horizontal, vertical) } records <- .make_tileid_sentinel1(records) records <- .make_tileid_sentinel2(records) records <- .make_tileid_sentinel3(records) records <- .make_tileid_landsat(records) records <- .make_tileid_modis(records) return(records) } .make_tileid_sentinel1 <- function(records) { TILEID <- name_tile_id() RECORD_ID <- name_record_id() FOOTPRINT <- name_footprint() SENTINEL1 <- "S1" POINT_SEP <- "\\." record_ids <- records[[RECORD_ID]] is_sentinel1 <- intersect(which(!is.na(record_ids)), which(startsWith(record_ids, SENTINEL1))) if (!.is_empty_array(is_sentinel1)) { no_tileid <- is_sentinel1[is.na(records[is_sentinel1, TILEID])] footprints <- records[is_sentinel1, FOOTPRINT] if (!is.na(no_tileid) && !.is_empty_array(no_tileid) && !.is_empty_array(footprints)) { tileids <- sapply(footprints, function(footprint) { tryCatch( { footprint <- footprint[[1]] horizontal <- strsplit(as.character(mean(footprint[, 1][1:4])), POINT_SEP)[[1]] vertical <- strsplit(as.character(mean(footprint[, 2][1:4])), POINT_SEP)[[1]] id <- paste0( "h", horizontal[1], ".", substr(horizontal[2], 1, 1), "v", vertical[1], ".", substr(vertical[2], 1, 1) ) }, error = function(err) { return(NA) } ) }) records[no_tileid, TILEID] <- tileids } } return(records) } .make_tileid_sentinel2 <- function(records) { RECORD_ID <- name_record_id() TILEID <- name_tile_id() SENTINEL2 <- "S2" record_ids <- records[[RECORD_ID]] is_sentinel2 <- intersect(which(!is.na(record_ids)), which(startsWith(record_ids, SENTINEL2))) if (!.is_empty_array(is_sentinel2)) { no_tileid <- is_sentinel2[is.na(records[is_sentinel2, TILEID])] if (!is.na(no_tileid) && !.is_empty_array(no_tileid)) { tileids <- sapply(records[no_tileid, RECORD_ID], function(x) { id <- strsplit(x, "_")[[1]][6] }) records[no_tileid, TILEID] <- tileids } } return(records) } .make_tileid_sentinel3 <- function(records) { RECORD_ID <- name_record_id() TILEID <- name_tile_id() SENTINEL3 <- "S3" record_ids <- records[[RECORD_ID]] is_sentinel3 <- intersect(which(!is.na(record_ids)), which(startsWith(record_ids, SENTINEL3))) if (!.is_empty_array(is_sentinel3)) { no_tileid <- is_sentinel3[is.na(records[is_sentinel3, TILEID])] if (!is.na(no_tileid) && !.is_empty_array(no_tileid)) { tileids <- sapply(records[no_tileid, RECORD_ID], function(x) { tryCatch( { sep <- "______" if (grepl(sep, x)) { splitted <- strsplit(x, sep)[[1]][1] splitted1 <- strsplit(splitted, "_")[[1]] len <- length(splitted1) last <- tail(splitted1, 1) if (grepl("[^0-9]", last)) { id <- last } else { id <- paste0(splitted1[len - 1], splitted1[len]) } } else { splitted <- strsplit(x, "_LN1")[[1]] splitted1 <- strsplit(splitted, "_")[[1]] len <- length(splitted1) if (len == 18) { id <- paste0(splitted1[len - 6], splitted1[len - 5]) } else { id <- paste0(splitted1[len - 2], splitted1[len - 1]) } } }, error = function(err) { return(NA) } ) }) records[no_tileid, TILEID] <- tileids } } return(records) } .make_tileid_landsat <- function(records) { RECORD_ID <- name_record_id() TILEID <- name_tile_id() landsat <- name_product_group_landsat() record_ids <- records[[RECORD_ID]] is_landsat <- intersect(which(!is.na(record_ids)), which(startsWith(record_ids, landsat))) if (!.is_empty_array(is_landsat)) { no_tileid <- is_landsat[is.na(records[is_landsat, TILEID])] if (!is.na(no_tileid) && !.is_empty_array(no_tileid)) { tileids <- sapply(records[no_tileid, RECORD_ID], function(x) { splitted <- strsplit(x, "_")[[1]][3] id <- paste0(substr(splitted, 1, 3), substr(splitted, 4, 7)) }) records[no_tileid, TILEID] <- tileids } } return(records) } .make_tileid_modis <- function(records) { RECORD_ID <- name_record_id() PRODUCT <- name_product() TILEID <- name_tile_id() modis <- name_product_group_modis() POINT_SEP <- "\\." h <- "h" v <- "v" product_names <- records[[PRODUCT]] is_modis <- intersect(which(!is.na(product_names)), which(startsWith(product_names, modis))) if (!.is_empty_array(is_modis)) { no_tileid <- is_modis[is.na(records[is_modis, TILEID])] if (!is.na(no_tileid) && !.is_empty_array(no_tileid)) { tileids <- sapply(records[no_tileid, RECORD_ID], function(x) { tryCatch( { splitted <- strsplit(x, POINT_SEP)[[1]] splitted1 <- splitted[which(grepl(v, splitted) * grepl(h, splitted) == 1)] splitted2 <- strsplit(splitted1, v)[[1]] is_horizontal <- grepl(h, splitted2) id <- paste0(h, strsplit(splitted2[is_horizontal], h)[[1]][2], v, splitted2[!is_horizontal]) }, error = function(err) { return(NA) } ) }) records[no_tileid, TILEID] <- tileids } } return(records) } .identify_period <- function(dates) { dates_sorted <- sort(dates) period <- c(dates_sorted[1], tail(dates_sorted, 1)) return(period) } .period_days <- function(period) { days <- as.integer(unclass(as.Date(period[2])) - unclass(as.Date(period[1]))) return(days) } .landsat_preview_mask_edges <- function(preview) { polygons <- "polygons" COORDS_SLOT <- "coords" ext <- try(extent(preview)) if (inherits(ext, TRY_ERROR())) { return(preview) } poly <- as(ext, SPATIAL_POLYGONS()) crs(poly) <- crs(preview) coords <- slot(slot(slot(poly, polygons)[[1]], "Polygons")[[1]], COORDS_SLOT) coords[1, 1] <- coords[1, 1] + 0.08 coords[2, 1] <- coords[2, 1] + 0.42 coords[3, 1] <- coords[3, 1] - 0.08 coords[4, 1] <- coords[4, 1] - 0.42 coords[5, 1] <- coords[5, 1] + 0.08 coords[1, 2] <- coords[1, 2] + 0.38 coords[2, 2] <- coords[2, 2] - 0.06 coords[3, 2] <- coords[3, 2] - 0.38 coords[4, 2] <- coords[4, 2] + 0.05 coords[5, 2] <- coords[5, 2] + 0.38 slot(slot(slot(poly, polygons)[[1]], "Polygons")[[1]], COORDS_SLOT) <- coords preview_masked <- .mask_raster_by_polygon(preview, poly) extent(preview_masked) <- extent(c(coords[1, 1], coords[3, 1], coords[4, 2], coords[2, 2])) return(preview_masked) } .sentinel2_preview_mask_edges <- function(preview) { polygons <- "polygons" COORDS_SLOT <- "coords" ext <- try(extent(preview)) if (inherits(ext, TRY_ERROR())) { return(preview) } poly <- as(ext, SPATIAL_POLYGONS()) crs(poly) <- crs(preview) coords <- slot(slot(slot(poly, polygons)[[1]], "Polygons")[[1]], COORDS_SLOT) val <- 0.005 coords[1, 1] <- coords[1, 1] + val coords[2, 1] <- coords[2, 1] + val coords[3, 1] <- coords[3, 1] - val coords[4, 1] <- coords[4, 1] - val coords[5, 1] <- coords[5, 1] + val coords[1, 2] <- coords[1, 2] + val coords[2, 2] <- coords[2, 2] - val coords[3, 2] <- coords[3, 2] - val coords[4, 2] <- coords[4, 2] + val coords[5, 2] <- coords[5, 2] + val slot(slot(slot(poly, polygons)[[1]], "Polygons")[[1]], COORDS_SLOT) <- coords preview_masked <- .mask_raster_by_polygon(preview, poly) extent(preview_masked) <- extent(c(coords[1, 1], coords[3, 1], coords[4, 2], coords[2, 2])) return(preview_masked) } .ensure_minmax <- function(x) { max <- 255 min_below_zero <- which(minValue(x) < 0) max_above_255 <- which(maxValue(x) > max) if (!.is_empty_array(min_below_zero)) { } if (!.is_empty_array(min_below_zero)) { for (i in min_below_zero) { x[[i]][x[[i]] < min] <- min } } if (!.is_empty_array(max_above_255)) { for (i in max_above_255) { x[[i]][x[[i]] > max] <- max } } return(x) } .raster_percent <- function(x, mode = "na", custom = c(), aoi = NULL, aoi_ncell = NULL) { if (mode == "na") { na_mask <- is.na(x) x <- .mask_raster_by_polygon(na_mask, aoi) x_mat <- as.integer(as.matrix(x)) percent <- (length(which(x_mat == 1)) / length(which(!is.na(x_mat)))) * 100 } else if (mode == "custom") { x_mat <- as.integer(as.matrix(x)) val1 <- length(which(x_mat == custom[[1]])) val2 <- length(which(x_mat == custom[[2]])) percent <- (val1 / sum(val1, val2)) * 100 } else if (mode == "aoi") { percent <- .calc_aoi_coverage(x, aoi, aoi_ncell) } percent <- ifelse(percent > 100, 100, percent) } .aggr_rasters <- function(x, x_names, aoi, factor = 750000, dir_out) { aoi_area <- .calc_aoi_area(aoi) adj <- aoi_area / factor res_ref <- mean(res(raster(x[[1]]))) target_res <- 0.0019 * adj if (target_res > 0.0042) target_res <- 0.004 adj <- target_res / res_ref adj <- ifelse(adj < 2 && adj > 1, 2, adj) if (adj > 1) { x_adj <- sapply(1:length(x), function(i) { r_save_path <- file.path(dir_out, paste0(x_names[i], "_aggr.tif")) if (file.exists(r_save_path)) { return(r_save_path) } r_load <- stack(x[[i]]) r_aggr <- aggregate(r_load, adj) writeRaster(r_aggr, r_save_path, overwrite = T, datatype = dataType(r_load)) return(r_save_path) }) } else { return(x) } return(x_adj) } .make_mosaic <- function(x, save_path, mode = "mask", srcnodata = NULL, datatype = NULL) { write_mos <- try(gdalbuildvrt(x, save_path, resolution = "highest", srcnodata = as.character(srcnodata), vrtnodata = "0", seperate = F, overwrite = T, datatype = datatype )) if (inherits(write_mos, TRY_ERROR())) { return(NA) } else { mos <- raster(save_path) if (mode == "rgb") { return(mos) } else { mos <- mos == 1 } } } .mask_raster_by_polygon <- function(x, polygon) { if (!inherits(polygon, SPATIAL_POLYGONS())) { polygon <- as_Spatial(st_zm(polygon)) } return(mask(x, polygon)) } .crop_raster_by_polygon <- function(x, polygon) { if (!inherits(polygon, SPATIAL_POLYGONS())) { polygon <- as_Spatial(polygon) } return(crop(x, polygon)) } .normalized_difference <- function(x, y) { a <- x - y b <- x + y norm_diff <- a / b return(norm_diff) } .rescale_raster <- function(x) { return((x - minValue(x)) / (maxValue(x) - minValue(x)) * 100) } .create_preview_na_mask <- function(preview, record) { product_group <- record[[name_product_group()]] is_olci <- .record_is_olci(record) is_landsat_or_sentinel2 <- product_group %in% c(name_product_group_landsat(), name_product_group_sentinel()) is_continental_s3 <- .record_is_s3_continental(record) if (any(is_olci, is_landsat_or_sentinel2, is_continental_s3)) { MIN_DN <- ifelse(is_landsat_or_sentinel2, 3, 0) NA_mask <- ((preview[[1]] > MIN_DN) + (preview[[2]] > MIN_DN) + (preview[[3]] > MIN_DN)) >= 1 } else { NA_mask <- preview[[1]] > -100 } return(NA_mask) } .add_aoi <- function(map = NULL, aoi_colour, homebutton = F) { if (isFALSE(getOption("gSD.aoi_set"))) { out("No AOI is displayed, since no AOI has been set yet (use 'set_aoi()' to define an AOI).", type = 2) } else { aoi.sf <- getOption("gSD.aoi") map.aoi <- mapview(aoi.sf, layer.name = "AOI", label = "AOI", lwd = 6, color = aoi_colour, legend = F, homebutton = homebutton) if (!is.null(map)) { return(map + map.aoi) } else { return(map.aoi) } } } .gsd_compact <- function(x) { if (inherits(x, LIST()) || length(x) > 1) { not_na <- sapply(x, function(y) { return((!is.na(y) && !is.null(y))) }) if (length(x) > 0) { x <- x[not_na] } } return(x) } .is_empty_array <- function(x) { all_null <- sapply(x, function(element) { return(ifelse(inherits(element, LIST()), FALSE, is.null(element))) }) all_na <- sapply(x, function(element) { return(ifelse(inherits(element, LIST()), FALSE, is.na(element))) }) return(length(x) == 0 || is.null(x) || is.na(x) || all_null || all_na) } .char_can_be_int <- function(x) { return(!grepl("[^0-9]", x)) } .eval_records_footprints <- function(records, as_sf = TRUE) { name_footprint <- name_footprint() footprints <- list() for (i in 1:NROW(records)) { record <- records[i, ] f <- record[[name_footprint]][[1]] is_sfg <- inherits(f, "sfg") is_sfc <- inherits(f, "sfc") if (is_sfg) { footprints[[i]] <- f } else if (is_sfc) { footprints[[i]] <- f[[1]] } else { footprint_eval <- try(unlist(eval(parse(text = f)))) if (inherits(footprint_eval, "try-error")) { out("Could not create footprint", type = 2) footprints[[i]] <- f } else { ncol <- 2 nrow <- length(footprint_eval) / ncol m <- matrix(data = footprint_eval, nrow = nrow, ncol = ncol) footprints[[i]] <- st_multipolygon(list(list(m))) } } } records[[name_footprint]] <- st_sfc(footprints, crs = 4326) return(.check_records(records, as_sf = as_sf)) } .generate_datetime_filename <- function(name, extension = "", sep = "_") { return(paste(Sys.Date(), format(Sys.time(), "%Hh%Mm%Ss"), paste0(name, extension), sep = "_")) } .generate_records_filename <- function(file_name = NULL, dir_out = NULL, driver = NULL) { if (is.null(driver)) driver <- "GeoJSON" ext <- get_records_drivers()[[driver]] if (is.null(file_name)) { file_name <- .generate_datetime_filename("records", extension = ext) } else { file_name <- paste0(file_name, ext) } file <- file.path(dir_out, file_name) return(file) } .set_verbose <- function(verbose) { options("gSD.verbose" = verbose) } .uncharacter_dataframe <- function(df) { if (inherits(df, "data.frame")) { for (i in 1:NCOL(df)) { column <- df[[i]] column_new <- c() if (inherits(column, "character")) { for (j in 1:length(column)) { element <- column[j] if (is.null(element)) { column_new[j] <- element } else if (is.na(element)) { column_new[j] <- element } else if (is.na(suppressWarnings(try(as.numeric(element))))) { char <- as.character(element) if (char == "NA") char <- NA column_new[j] <- char } else { column_new[j] <- as.numeric(element) } } df[[i]] <- column_new } } } return(df) } .create_datetime_string <- function() { return(gsub(":", "_", gsub(" ", "_", as.character(Sys.time())))) } .retry <- function(fun, ..., fail, ini = NULL, retry = NULL, final = NULL, n = 3, delay = 0, value = TRUE, verbose = T) { extras <- list(...) if (!is.null(ini)) eval(ini) while (n != 0) { x <- try(fun(...), silent = T) if (inherits(x, "try-error")) { if (grepl("aborted", as.character(attributes(x)$condition))) out("Operation was aborted by an application callback.", type = 3) else eval(retry) n <- n - 1 if (n == 0) x <- eval(fail) } else { n <- 0 } Sys.sleep(delay) } eval(final) if (isTRUE(value)) { return(x) } } .lapply <- function(X, FUN, ..., verbose = FALSE) { if (isTRUE(verbose)) pblapply(X, FUN, ...) else lapply(X, FUN, ...) } .sapply <- function(X, FUN, ..., verbose = FALSE) { if (isTRUE(verbose)) pbsapply(X, FUN, ...) else sapply(X, FUN, ...) } .apply <- function(X, MARGIN, FUN, ..., verbose = FALSE) { if (isTRUE(verbose)) pbapply(X, MARGIN, FUN, ...) else apply(X, MARGIN, FUN, ...) } .onLoad <- function(libname, pkgname) { pboptions(type = "timer", char = "=", txt.width = getOption("width") - 30) dict <- rbind.data.frame( c("summary", "product_group"), c("summary", "product"), c("title", "record_id"), c("displayId", "record_id"), c("uuid", "entity_id"), c("entityId", "entity_id"), c("id", "entity_id"), c("summary", "summary"), c("dataset_id", "summary"), c("localgranuleid", "summary"), c("beginposition", "start_time"), c("StartTime", "start_time"), c("time_start", "start_time"), c("temporalcoveragestartdate", "start_date"), c("endposition", "stop_time"), c("StopTime", "stop_time"), c("temporalcoverageenddate", "stop_date"), c("time_end", "stop_time"), c("beginposition", "date_acquisition"), c("acquisitionDate", "date_acquisition"), c("AcquisitionStartDate", "date_acquisition"), c("daynightindicator", "day_or_night"), c("ingestiondate", "date_ingestion"), c("publishdate", "date_publish"), c("dateentered", "date_ingestion"), c("dateupdated", "date_modified"), c("modifiedDate", "date_modified"), c("updated", "date_modified"), c("creationdate", "date_creation"), c("footprint", "footprint"), c("boxes", "footprint"), c("tileid", "tile_id"), c("wrspath", "tile_number_horizontal"), c("wrsrow", "tile_number_vertical"), c("HorizontalTileNumber", "tile_number_horizontal"), c("VerticalTileNumber", "tile_number_vertical"), c("url.alt", "md5_url"), c("browseUrl", "preview_url"), c("url.icon", "preview_url"), c("preview_url", "preview_url"), c("metadataUrl", "meta_url"), c("fgdcMetadataUrl", "meta_url_fgdc"), c("slicenumber", "slice_number"), c("orbitnumber", "orbit_number"), c("orbitdirection", "orbit_direction"), c("lastorbitnumber", "lastorbit_number"), c("relativeorbitnumber", "relativeorbit_number"), c("lastrelativeorbitnumber", "lastrelativeorbit_number"), c("passnumber", "pass_number"), c("passdirection", "pass_direction"), c("relorbitdir", "relativeorbit_direction"), c("relpassnumber", "relativepass_number"), c("relpassdirection", "relativepass_direction"), c("lastorbitdirection", "lastorbit_direction"), c("lastpassnumber", "lastpass_number"), c("lastpassdirection", "lastpass_direction"), c("lastrelorbitdirection", "lastrelativeorbit_direction"), c("lastrelpassnumber", "lastrelativepass_number"), c("lastrelpassdirection", "lastrelativepass_direction"), c("swathidentifier", "swath_id"), c("producttype", "product_type"), c("productclass", "product_class"), c("productconsolidation", "product_consolidation"), c("timeliness", "timeliness"), c("platformname", "platform"), c("Platform", "platform"), c("platformidentifier", "platform_id"), c("platformserialidentifier", "platform_serial"), c("instrumentname", "sensor"), c("Sensor", "sensor"), c("instrumentshortname", "sensor_id"), c("SensorIdentifier", "sensor_id"), c("sensoroperationalmode", "sensor_mode"), c("polarisationmode", "polarisation_mode"), c("acquisitiontype", "acquistion_type"), c("size", "size"), c("is_gnss", "is_gnss"), c("landcloudcover", "cloudcov_land"), c("scenecloudcover", "cloudcov"), c("cloudcover", "cloudcov"), c("cloudcoverpercentage", "cloudcov"), c("highprobacloudspercentage", "cloudcov_highprob"), c("mediumprobacloudspercentage", "cloudcov_mediumprob"), c("notvegetatedpercentage", "cloudcov_notvegetated"), c("snowicepercentage", "snowice"), c("unclassifiedpercentage", "unclassified"), c("vegetationpercentage", "vegetation"), c("waterpercentage", "water"), c("processinglevel", "level"), c("versionnumber", "version_product"), c("productgenerationalgorithm", "version_algorithm"), c("level", "level"), c("AutoQualityFlag", "flag_autoquality"), c("AutoQualityFlagExplanation", "flag_autoquality_expl"), c("ScienceQualityFlag", "flag_sciencequality"), c("ScienceQualityFlagExpln", "flag_sciencequality_expl"), c("MissingDataPercentage", "missingdata"), c("collectionnumber", "collection"), c("collectioncategory", "collection_category"), c("collection_concept_id", "product_id"), c("product", "product"), stringsAsFactors = F ) colnames(dict) <- c("clients", "gSD") op <- options() op.gSD <- list( gSD.api = list( dhus = "https://scihub.copernicus.eu/dhus/", codede = list(auth = "https://auth.cloud.code-de.org/auth/realms/code-de/protocol/openid-connect/token"), s5p = "https://s5phub.copernicus.eu/", gnss = "https://scihub.copernicus.eu/gnss/", espa = "https://espa.cr.usgs.gov/api/v1/", ee = "https://m2m.cr.usgs.gov/api/api/json/stable/", aws.l8 = "https://landsat-pds.s3.amazonaws.com/c1/L8/", aws.l8.sl = "https://landsat-pds.s3.amazonaws.com/c1/L8/scene_list.gz", laads = "https://ladsweb.modaps.eosdis.nasa.gov/archive/allData/" ), gSD.api.names = list( dhus = "ESA Copernicus Open Hub", codede = "CODE-DE", s5p = "ESA Copernicus S5P Hub", gnss = "ESA Copernicus GNSS Hub", espa = "USGS-EROS ESPA", ee = "USGS EarthExplorer", aws.l8 = "AWS Landsat 8", laads = "NASA DAAC LAADS" ), gSD.copnames = data.frame( name = c("sentinel-1", "sentinel-2", "sentinel-3", "sentinel-5p", "gnss"), api = c("dhus", "dhus", "dhus", "s5p", "gnss"), stringsAsFactors = F ), gSD.sen2cor = list( win = "http://step.esa.int/thirdparties/sen2cor/2.5.5/Sen2Cor-02.05.05-win64.zip", linux = "http://step.esa.int/thirdparties/sen2cor/2.5.5/Sen2Cor-02.05.05-Linux64.run", mac = "http://step.esa.int/thirdparties/sen2cor/2.5.5/Sen2Cor-02.05.05-Darwin64.run" ), gSD.verbose = FALSE, gSD.dhus_session = NULL, gSD.dhus_user = FALSE, gSD.dhus_pass = FALSE, gSD.dhus_set = FALSE, gSD.dhus_time = NULL, gSD.codede_token = NULL, gSD.codede_user = NULL, gSD.codede_pass = NULL, gSD.codede_set = FALSE, gSD.codede_time = NULL, gSD.usgs_user = FALSE, gSD.usgs_pass = FALSE, gSD.usgs_set = FALSE, gSD.usgs_time = NULL, gSD.usgs_refresh = 60, gSD.usgs_apikey = FALSE, gSD.ed_user = FALSE, gSD.ed_pass = FALSE, gSD.ed_set = FALSE, gSD.ed_time = NULL, gSD.ed_refresh = 60, gSD.archive = FALSE, gSD.archive_set = FALSE, gSD.aoi = FALSE, gSD.aoi_set = FALSE, gSD.products = NULL, gSD.clients_dict = dict ) toset <- !(names(op.gSD) %in% names(op)) if (any(toset)) options(op.gSD[toset]) invisible() } .onUnload <- function(libname, pkgname) { if (isTRUE(getOption("gSD.usgs_set"))) .ERS_logout(getOption("gSD.usgs_apikey")) }
setClass( "doubleEntry", representation( meta = "list", scale = "list", coupled = "logical", elements = "list", constructs = "list", elicitation = "list", ratings = "array", calcs = "list", plotdata = "data.frame"))
library(googleCloudRunner) bs <- c( cr_buildstep_gitsetup("github-ssh"), cr_buildstep_git(c("clone","[email protected]:MarkEdmondson1234/googleCloudRunner",".")), cr_buildstep_docker("gcr.io/gcer-public/packagetools", dir = "inst/docker/packages/") ) build <- cr_build_yaml(bs, timeout = 2400) cr_build_write(build, "inst/docker/packages/cloudbuild.yml") s_me <- cr_build_schedule_http(build) cr_schedule("packagetest-build2", schedule = "15 9 * * 1", httpTarget = s_me)
MaxentIC <- function(csvfile, grdfile, lambdasfile) { nparams = 0 probsum = 0 loglikelihood = 0 AICcscore = 0 AICscore = 0 BICscore = 0 lambdases <- read.csv(lambdasfile, header=FALSE) nparams <- nrow(lambdases[lambdases$V2 != 0, ]) nparams = nparams - 4 layerRaw <- raster::raster(grdfile) probsum <- raster::cellStats(layerRaw, sum) points <- read.csv(csvfile) npoints <- nrow(points) layerValues <- raster::extract(layerRaw, points[, c("longitude", "latitude")]) loglikelihood <- sum(log(layerValues / probsum)) if (nparams >= npoints - 1) { AICcscore <- "x" AICscore <- "x" BICscore <- "x" } else { AICcscore = (2 * nparams - 2 * loglikelihood) + (2 * (nparams) * (nparams + 1) / (npoints - nparams - 1)) AICscore = 2 * nparams - 2 * loglikelihood BICscore = nparams * log(npoints) - 2 * loglikelihood } ICs <- c(npoints, nparams, loglikelihood, AICscore, AICcscore, BICscore) return(ICs) }
require("TSsdmx") ilo <- TSconnect("sdmx", dbname="ILO") z <- TSget("DF_YI_ALL_EMP_TEMP_SEX_AGE_NB/YI.MEX.A.463.EMP_TEMP_NB.SEX_F.AGE_10YRBANDS_TOTAL", ilo) if (! all(c(1988,1) == start(z))) stop("ILO test 1 start date changed.") z <- TSget("DF_YI_ALL_EMP_TEMP_SEX_AGE_NB/YI.MEX.A.463.EMP_TEMP_NB.SEX_F.AGE_10YRBANDS_TOTAL", start=c(1995,1), end=c(2012,1), ilo) if (! all(c(1995,1) == start(z))) stop("ILO test 2 start date error.") z <- TSget("DF_YI_ALL_EMP_TEMP_SEX_AGE_NB/YI.MEX.A.463.EMP_TEMP_NB.SEX_F.AGE_10YRBANDS_TOTAL", start="1995-01-01", end="2012-12-31", ilo) if (!all(c(2012,1) == end(z))) stop("ILO test 2 end date error.") z <- TSget( "DF_YI_ALL_EMP_TEMP_SEX_AGE_NB/YI.DEU+FRA+GBR+ITA.A..EMP_TEMP_NB.SEX_T.AGE_AGGREGATE_TOTAL", ilo) if (10 != tframe::nseries(z)) stop("ILO test 3 number of series changed (again).") if (! all(c(1969,1) == start(z))) stop("ILO test 3 start date error.") tframe::seriesNames(z)
post1PYO=function(canc,brks=c(0,2,5),binIndx=1,Trt="rad",PYLong=FALSE,yearEnd,firstS,secondS) { surv=yrdx=age=casenum=cancer=trt=yrdx1=seqnum=yrdiff=mn=NULL age=NULL yrdx2=yrdiffn=cancer1=cancer2=py=year=ageL=ageR=age1=age2=ageM=sem=NULL if(sum(canc$trt==Trt,na.rm=T)==0) stop(paste0("canc must have a trt column containing",Trt)) binS=levels(cut(brks+0.1,breaks=c(brks,100))) bin=binS[binIndx] LL=getBinInfo(bin,binS)["LL"] print(bin) D0=canc%>%filter(seqnum==0,surv<200,surv>LL,trt==Trt,cancer%in%firstS) D0$cancer=factor(D0$cancer,levels=firstS) D1=canc%>%filter(seqnum==1,trt==Trt,cancer%in%firstS)%>%select(casenum,cancer,yrdx,age,trt) D1$cancer=factor(D1$cancer,levels=firstS) D2=canc%>%filter(seqnum==2) D1=D1%>%filter(casenum%in%D2$casenum) names(D1)[2:5]=c("cancer1","yrdx1","age1","trt1") D2=D2%>%select(casenum,cancer2=cancer,yrdx2=yrdx,age2=age) D12=left_join(D2,D1,by="casenum") D12=D12%>%filter(!is.na(yrdx1)) D12=D12%>%mutate(yrdiffn=yrdx2-yrdx1) D12$yrdiffn[D12$yrdiffn==0]=0.33/12 D12py=D12 D12=D12%>%mutate(yrdiff=cut(yrdiffn,breaks=c(-1,brks,100),include.lowest = TRUE)) D12=D12%>%filter(yrdiff==bin) PY0=D0%>%mutate(py=getPY(surv,bin,binS,brks)) PY0=PY0%>%filter(py>0) PY0=PY0%>%mutate(ageL=age+LL) PY0$year=floor(PY0$yrdx+LL) PY0$cancer2="none" PY0=PY0%>%select(cancer1=cancer,cancer2,py,ageL,year) PY12=D12py%>%mutate(py=getPY(yrdiffn,bin,binS,brks)) PY12=PY12%>%filter(py>0) PY12=PY12%>%mutate(ageL=age1+LL) PY12$year=floor(PY12$yrdx1+LL) PY12=PY12%>%select(cancer1,cancer2,py,ageL,year) PYL=rbind(PY0,PY12) N=dim(PYL)[1] binMidPnt=LL+sum(PYL$py)/N/2 PYL=PYL%>%mutate(ageM=ageL+py/2) PYA=PYL%>%group_by(cancer1)%>%summarize(n=n(),py=sum(py),age=mean(ageM),sig2=var(ageM))%>%mutate(t=LL + py/n/2) AgeO=D12%>%filter(cancer2%in%secondS)%>%group_by(cancer1,cancer2)%>% summarize(age=mean(age2),sig2=var(age2),n=n()) PYin=PYL%>%select(-cancer1,-cancer2,-ageM) LPYin=split(PYin,PYL$cancer1) LPYinM=lapply(LPYin,as.matrix) LPYM=NULL yrs=1975:yearEnd nyears=length(yrs) ages=0.5:125.5 Zs=matrix(0,ncol=nyears,nrow=length(ages)) colnames(Zs)=yrs rownames(Zs)=ages for (i in firstS) { PYMat=Zs+0 LPYM[[i]]=fillPYM(LPYinM[[i]],PYMat) } LD12=split(D12,D12$cancer1) O=t(sapply(LD12,function(x) table(x$cancer2))) rownames(O)=names(LD12) colnames(O)=levels(D12$cancer2) L1=list(LPYM=LPYM,O=O,binMidPnt=binMidPnt,AgeO=AgeO,PYA=PYA) if (PYLong) L1$PYL=PYL L1 }
mod <- function(x, minMI = 10) { if ((x$means == TRUE | x$diff == TRUE) & packageVersion("lavaan") <= "0.5.15") { stop("Modification indices do not work when mean structure or delta method are used. If you upgrade to lavaan 0.5.16 (or later), you can get MI for these models as well.") } MI <- modindices(x$fit, standardized=TRUE) MI <- MI[order(MI$mi, decreasing=TRUE), ] if (max(MI$mi, na.rm=TRUE) < minMI) { print(paste0("No modification index is larger then ", minMI, ".")) invisible(NULL) } MI2 <- MI[!is.na(MI$mi) & MI$mi>minMI, ] if (nrow(MI2)>0) { return(MI2) } else { invisible(NULL) } }
missingdata <- function(data, unk=0 ){ pedigree.data<-data data <- c() if( ncol(pedigree.data) != 3 ){ print("Data with more than 3 columns, please verify") return() } ind.data <- as.vector(c(unk,as.character(pedigree.data[,1]))) sire.data <- as.vector(pedigree.data[,2]) dire.data <- as.vector(pedigree.data[,3]) sire <- match(sire.data, ind.data) dire <- match(dire.data, ind.data) ind <- as.vector(c(1:length(ind.data))) missing <- c() missing$conflict <- c(which( sire == ind[-1]),which( dire == ind[-1] )) missing$sire.na <- c( which(is.na(sire))) missing$dire.na <- c( which(is.na(dire))) missing$sire <- as.matrix(summary(as.factor(pedigree.data[which(is.na(sire)),2]))) missing$dire <- as.matrix(summary(as.factor(pedigree.data[which(is.na(dire)),3]))) names <- unique(c(rownames(missing$sire),rownames(missing$dire))) pos.sire <- match(rownames(missing$sire),names) pos.dire <- match(rownames(missing$dire),names) missing$parent <- rep(0,length(names)) missing$parent[pos.dire] <- missing$dire missing$parent[pos.sire] <- missing$parent[pos.sire]+missing$sire missing$parent <- as.matrix(missing$parent) rownames(missing$parent) <- names missing <- list(conflict=missing$conflict,missing.sire=missing$sire.na,missing.dire=missing$dire.na,summary.missing=missing$parent) return(missing) }
print.loglik_dglars <- function (x, digits = max(3, getOption("digits") - 3), ...){ model <- x$object$control$method fml <- x$object$family tbl <- data.frame(g = x$g, df = x$df, loglik = x$loglik) cat("Sequence of log-likelihood values for the estimated", sQuote(model),"models.") cat("\n\nDetails:\n") cat("\t", sQuote(fml$family) ,"family with link function", sQuote(fml$link),"\n") if(!fml$family %in% c("binomial", "poisson")) cat("\t (dispersion parameter estimated by", sQuote(x$phi), ")\n\n") else cat("\t (dispersion parameter for", fml$family, "family taken to be 1)\n\n") print.data.frame(tbl, print.gap = 2, quote = FALSE, row.names = FALSE, ...) invisible(tbl) }
AUCRFcv <- function(x,nCV=5,M=20){ AUC.votes <- function(votes,y=NULL,clase=1){ if(missing(y) || is.null(y)) y <- votes$y r <- rank(votes[,as.character(clase)]) rd <- mean(r[y==clase]) nd <- sum(y==clase) nnd <- length(y)-nd return((rd-nd/2-0.5)/nnd) } cl <- match.call() switch(class(x), "AUCRF" = { callRF <- x$call data <- x$data callRF$data <- as.name("newData") yname <- as.character(eval(x$call$formula)[[2]]) }, stop("x must be a AUCRF object.") ) cvAUC <- NULL varnames <- colnames(data)[colnames(data)!=yname] nSelect <- rep(0,length(varnames)) names(nSelect) <- varnames for(m in 1:M){ CV <- list() mpredict <- NULL indPermuted <- matrix(c(sample(rownames(data)),rep(NA,nCV-nrow(data)%%nCV)),ncol=nCV,byrow=TRUE) for(k in 1:nCV){ indTest <- indPermuted[,k] indTest <- indTest[!is.na(indTest)] indTrain <- rownames(data)[!(rownames(data) %in% indTest)] newData <- data[indTrain,] kaucRF <- eval(callRF) mpredict <- rbind(mpredict, predict(kaucRF$RFopt,newdata=data[indTest,],type="vote")) nSelect[kaucRF$Xopt] <- nSelect[kaucRF$Xopt]+1 } mvotes <- data.frame(y=data[,yname],mpredict[rownames(data),]) class(mvotes) <- c("votes","data.frame") colnames(mvotes) <- c("y","0","1") cvAUC <- c(cvAUC, AUC.votes(mvotes)) } if(class(x)=="AUCRF") objectList <- x else objectList <- list() objectList$cvAUC <- mean(cvAUC) objectList$Psel <- nSelect/(M*nCV) objectList$callcv <- cl class(objectList) <- c("AUCRFcv","AUCRF") return(objectList) }
test_that("padding with interactions", { skip_if_not_installed("insight", minimum_version = "0.14.4.1") dat <- read.csv("https://vincentarelbundock.github.io/Rdatasets/csv/ggplot2movies/movies.csv") dat$style <- ifelse(dat$Action == 1, "Action", "Other") dat$style <- ifelse(dat$Comedy == 1, "Comedy", dat$style) dat$style <- ifelse(dat$Drama == 1, "Drama", dat$style) dat$style <- factor(dat$style) dat$certified_fresh <- dat$rating >= 8 dat <- dat[dat$length < 240,] mod <- glm(certified_fresh ~ length * style, data = dat, family = binomial) res <- predictions(mod, type = c("response", "link")) expect_predictions(res, n_row = nrow(dat) * 2) })
print.summary.spsur <- function(x, digits = max(3L, getOption("digits") - 3L), ...) { G <- x$G cat("Call:\n") print(x$call) cat("\n","\n") cat("Spatial SUR model type: ",x$type,"\n\n") for (i in 1:G){ cat("Equation ",i,"\n") printCoefmat(x$coef_table[[i]], P.values = TRUE, has.Pvalue = TRUE) cat("R-squared: ", formatC(x$R2[i+1], digits = 4), " ", sep = "") cat("\n"," ") } cat("\n") if (x$Tm>1 | x$G>1){ cat("Variance-Covariance Matrix of inter-equation residuals:") prmatrix(x$Sigma,digits=4, rowlab=rep("", nrow(x$Sigma)), collab = rep("", ncol(x$Sigma))) } else { cat("Residual standard error:",formatC(sqrt(x$Sigma), digits = 4, width = 6)) } if (x$Tm>1 | x$G>1){ cat("Correlation Matrix of inter-equation residuals:") prmatrix(x$Sigma_corr,digits=3, rowlab=rep("",nrow(x$Sigma)), collab = rep("",ncol(x$Sigma))) } if (x$Tm>1 | x$G>1){ cat("\n R-sq. pooled: ", formatC(x$R2[1], digits = 4)," ", sep = "") if(!is.null(x$llsur)){ cat("\n Log-Likelihood: ",formatC(x$llsur, digits = 6, width = 6)) } } if (x$Tm>1 | x$G>1){ if(!is.null(x$BP)){ cat("\n Breusch-Pagan: ",formatC(x$BP, digits = 4), " p-value: (",formatC(pchisq(x$BP, df = G*(G - 1)/2, lower.tail = FALSE), digits = 3, width = 4),") ", sep = "") } } if(!is.null(x$LMM)){ if (x$Tm==1 & x$G==1){ df= 1} else {df= G*(G - 1)/2 } cat("\n LMM: ",formatC(x$LMM, digits = 5), " p-value: (",formatC(pchisq(x$LMM, df = df, lower.tail = FALSE), digits = 3, width = 4),")\n", sep = "") } invisible(x) }
Yule04<- function (X,YY,levX,nameYY,tri=0,alpha=0.05) { T4 <- Yule03(X, YY, levX,nameYY,tri=tri) T4<-na.omit(T4) couleur<-rep(1,nrow(T4)) couleur[T4[,4]<alpha]<-2 L <- nrow(T4) MIN <- min(-1, T4[, 2] - 1.96 * T4[, 3]) MAX <- max(1, T4[, 2] + 1.96 * T4[, 3]) dotchart(T4[, 2], labels = rownames(T4), xlim = c(MIN, MAX), main = levX,color=couleur,xlab="Yule's Q") abline(v = 0, lty = 2) segments(T4[, 2] - 1.96 * T4[, 3], 1:L, T4[, 2] + 1.96 * T4[, 3], 1:L,col=couleur) }
test_that("scent_select() selects the correct columns", { gene1 <- c(0,0,0,0,1,2,3) gene2 <- c(5,5,3,2,0,0,0) gene3 <- c(2,0,2,1,3,0,1) gene4 <- c(3,3,3,3,3,3,3) gene5 <- c(0,0,0,0,5,0,0) gene_counts <- matrix(c(gene1,gene2,gene3,gene4,gene5), ncol = 5) rownames(gene_counts) <- paste0("cell",1:7) colnames(gene_counts) <- paste0("gene",1:5) expect_equal( scent_select(gene_counts, bit_threshold = 0.85), gene_counts[,c(1,2,5)] ) expect_equal( scent_select(gene_counts, count_threshold = 2), gene_counts[,c(1,5)] ) expect_equal( scent_select(gene_counts, perc_threshold = 0.25), gene_counts[,c(1,2,3,5)] ) }) test_that("scent_select_tidy() selects the correct columns", { library(tibble) gene1 <- c(0,0,0,0,1,2,3) gene2 <- c(5,5,3,2,0,0,0) gene3 <- c(2,0,2,1,3,0,1) gene4 <- c(3,3,3,3,3,3,3) gene5 <- c(0,0,0,0,5,0,0) gene_counts <- matrix(c(gene1,gene2,gene3,gene4,gene5), ncol = 5) rownames(gene_counts) <- paste0("cell",1:7) colnames(gene_counts) <- paste0("gene",1:5) gene_counts <- as_tibble(gene_counts) expect_equal( scent_select_tidy(gene_counts, bit_threshold = 0.85), gene_counts[,c(1,2,5)] ) expect_equal( scent_select_tidy(gene_counts, count_threshold = 2), gene_counts[,c(1,5)] ) expect_equal( scent_select_tidy(gene_counts, perc_threshold = 0.25), gene_counts[,c(1,2,3,5)] ) })
table2office=function(x=NULL,target="Report",append=FALSE,title="",vanilla=FALSE,echo=FALSE, preprocessing="",type="pptx",landscape=FALSE,left=1,top=1){ doc<-open_doc(target=target,type=type,append=append) target=attr(doc,"name") if(title!=""){ doc <- doc %>% add_text(title=title) } else { if(type=="pptx") doc <- doc %>% add_slide(layout="Blank") } pos=top if(title!="") pos=pos+0.5 if(echo & is.character(x)) { codeft=Rcode2flextable(x,preprocessing=preprocessing,format="pptx",eval=FALSE) doc<-doc %>% ph_with(value=codeft, location = ph_location(left=1,top=pos)) pos=pos+0.5 } if("character" %in% class(x)){ x<-eval(parse(text=x)) } if("mytable" %in% class(x)){ ft<-mytable2flextable(x,vanilla=vanilla) } else if(class(x)[1] %in% c("matrix","lm","fitdistr","nls","aov","anova","glm","coxph","prcomp","summary.prcomp")){ ft<-ztable2flextable(ztable(x),vanilla=vanilla) } else if(class(x)[1]=="data.frame"){ ft<-df2flextable(x,vanilla=vanilla) } else if(class(x)[1]=="flextable"){ ft<-x } if(class(doc)=="rpptx"){ doc<-doc %>% ph_with(value=ft,location = ph_location(left=left,top=pos)) } else { if(landscape) doc <- body_end_section_portrait(doc) doc<-doc %>% body_add_flextable(ft) if(landscape) doc <- body_end_section_landscape(doc) } message(paste0("Exported table as ", target)) doc %>% print(target=target) } table2pptx=function(...){ table2office(...,type="pptx") } table2docx=function(...){ table2office(...,type="docx") }
context("test running dtw") goal <- function(h, x, ws, dm, sp){ nx <- length(x) nh <- length(h) hscale <- IncDTW::scale(h, type = "01") sapply(1:(nx-nh+1), function(i){ y <- IncDTW::scale(x[i:(i+nh-1)], type = "01") IncDTW::dtw2vec(y, hscale, dist_method = dm, step_pattern = sp, ws = ws)$dist }) } noise <- function(i) cumsum(rnorm(i)) test_that("no variance for a sequence", { dm <- "norm1" sp <- "symmetric1" WS <- 10 h <- rep(rnorm(1), 20) hscale <- IncDTW::scale(h, type="01") x <- c(noise(10), rep(rnorm(1), 20), noise(10)) ret <- rundtw(Q = h, C = x, dist_method = dm, step_pattern = sp, ws = WS, scale = "01", threshold = NULL, lower_bound = F) ist <- ret$dist[11] soll <- 0 expect_equal(ist, soll) ret <- rundtw(Q = h, C = x, dist_method = dm, step_pattern = sp, ws = WS, scale = "z", threshold = NULL, lower_bound = F) ist <- ret$dist[11] soll <- 0 expect_equal(ist, soll) }) test_that("equal sapply univariate norm1", { dm <- "norm1" sp <- "symmetric1" WS <- 10 h <- noise(10) hscale <- IncDTW::scale(h, type="01") x <- c(noise(10), h, noise(10)) ist <- rundtw(Q = h, C = x, dist_method = dm, step_pattern = sp, ws = WS, scale = "01", threshold = NULL, lower_bound = F) soll <- goal(h, x, WS, dm, sp) expect_equal(ist$dist, soll) }) test_that("equal sapply univariate sym2", { dm <- "norm1" sp <- "symmetric2" WS <- 10 h <- noise(10) hscale <- IncDTW::scale(h, type="01") x <- c(noise(10), h, noise(10)) ist <- rundtw(Q = h, C = x, dist_method = dm, step_pattern = sp, ws = WS, scale = "01", threshold = NULL, lower_bound = F) soll <- goal(h, x, WS, dm, sp) expect_equal(ist$dist, soll) }) test_that("expected result, univariate", { dm <- "norm1" sp <- "symmetric1" WS <- NULL deform <- function(x) (x + rnorm(1, 0, 100)) * abs(rnorm(1, 0, 100)) h <- noise(10) hscale <- IncDTW::scale(h, type="01") x <- c(noise(10), h, noise(10), deform(h), noise(10), deform(h)) soll <- c(11, 31, 51) ist <- rundtw(Q = hscale, C = x, dist_method = dm, step_pattern = sp, scale = "01", threshold = NULL, lower_bound = FALSE) ist <- which(ist$dist < 10^(-10)) expect_equal(ist, soll) ist <- rundtw(Q = hscale, C = x, dist_method = dm, step_pattern = sp, scale = "01", threshold = Inf, lower_bound = TRUE) ist <- which(ist$dist < 10^(-10)) expect_equal(ist, soll) }) test_that("rundtw and find_peaks", { noise <- function(nr) cumsum(rnorm(nr)) nx <- 500 nh <- 30 nfits <- 5 nn <- nx - nfits * nh nn <- nn/nfits h <- noise(nh) hscale <- IncDTW::scale( h , type="01") x <- noise(0) for(i in 1:nfits){ x <- c(x, noise(nn), h) } result <- rundtw(h, x, scale = "01", ws = 10, threshold = Inf, lower_bound = TRUE) soll_indices <- c(71, 171, 271, 371, 471) minima <- find_peaks(result$dist, w = nh) ist <- sum(soll_indices %in% minima) soll = length(soll_indices) expect_equal(ist, soll) }) test_that("kNN rundtw", { noise <- function(nr) cumsum(rnorm(nr)) nx <- 500 nh <- 30 nfits <- 5 nn <- nx - nfits * nh nn <- nn/nfits h <- noise(nh) hscale <- IncDTW::scale( h , type="01") x <- noise(0) for(i in 1:nfits){ x <- c(x, noise(nn), h) } k <- 10 result <- rundtw(h, x, scale = "01", ws = 10, threshold = Inf, k = k, lower_bound = TRUE) soll <- c(71, 171, 271, 371, 471) ord <- order(result$knn_values, decreasing = F) ist <- sort(result$knn_indices[ord[1:5]]) expect_equal(ist, soll) }) test_that("kNN rundtw", { for(i in 1:1){ myseed <- sample(i + as.numeric(Sys.time())/10^5, size=1) print(myseed) set.seed(myseed) nx <- 500 nh <- sample(20:50, size=1) WS <- sample(nh, size=1) dm <- "norm1" sp <- "symmetric1" noise <- function(nr) cumsum(rnorm(nr)) goal_knn <- function(hscale, x, sp, ws, kNNk){ allv <- rundtw(h, x, dist_method = dm, step_pattern = sp, ws = ws, threshold = NULL, k = 0, lower_bound = FALSE, scale = "01") dd <- allv$dist best_i <- integer() for(i in 1:kNNk){ ix <- which.min(dd) if(dd[ix] < Inf){ best_i <- c(best_i, ix) dd[max(1, (1 + ix - nh)):min((ix + nh - 1), length(dd))] <- Inf } } return(list(indices=best_i, all_values = allv$dist)) } nfits <- sample(10, size=1) nn <- nx - nfits * nh nn <- nn/nfits h <- noise(nh) hscale <- IncDTW::scale( h , type="01") x <- noise(0) for(i in 1:nfits){ x <- c(x, noise(nn), h) } k <- nfits + 2 a <- rundtw(h, x, dist_method = dm, step_pattern = sp, ws = WS, threshold = Inf, k = k, lower_bound = TRUE, scale = "01") ist <- sort(a$knn_indices) b <- goal_knn(hscale, x, sp, ws=WS, kNNk = k) soll <- sort( b$indices ) expect_equal(ist, soll) } }) test_that("bug go to end",{ skip("") load("build_ignore/bug_data01.Rda") zz <- file("build_ignore/mySink.Rout", open = "wt"); sink(zz); sink(zz, type = "message") tmp <- rundtw( Q = Q, C = C, scale = "01", dist_method = "norm1", ws = 20, threshold = 5, lower_bound = T, k = 5 ) sink();close(zz); closeAllConnections() tmp }) test_that("bug counter", { skip(" there is no bug!") rw <- function(m) cumsum(rnorm(m)) noise <- function(x) rnorm(length(x)) deform <- function(x, p) { ( simulate_timewarp(x, p, preserve_length = T) + rnorm(1, 0, 10) ) * abs(rnorm(1, 0, 10)) + noise(x) } infix <- function(x, y, i) { if(length(i) == 1){ new_x <- c(x[1:(i-1)], deform(y, 0.1), x[i:length(x)]) }else{ new_x <- infix(infix(x, y, i[1]), y,i[-1]) } return(new_x) } nQ <- 100 nC <- 1000 Q <- rw(nQ) C0 <- rw(nC) ii <- c(30, 550,700) C <- infix(C0, Q, ii) tmp <- rundtw( Q = Q, C = C, dist_method = "norm1", ws = 10, threshold = NULL, lower_bound = F, k = 0 ) plot(C, type="l") C2 <- C C2[-as.vector(sapply(ii, function(i){i:(i+nQ)}))] <- NA lines(C2, col="red") plot(tmp$dist) }) test_that("figure", { skip("") dm <- "norm1" sp <- "symmetric1" WS <- NULL noise <- function(nr) cumsum(rnorm(nr)) nx <- 500 nh <- 100 nfits <- 2 nn <- nx - nfits * nh nn <- nn/nfits h <- noise(nh) hscale <- IncDTW::scale( h , type="01") x <- noise(0) for(i in 1:nfits){ x <- c(x, noise(nn), h) } a <- rundtw(h, x, k = NULL) b <- rundtw(h, x, k = 3) par(mfrow=c(1,1)) plot(a$dist) points(b$dist, col="red") a <- rundtw(h, x, k = 10) c0 <- rundtw(h, x, k = 10, overlap_tol = round(nh/2)) plot(a$dist) points(c0$dist, col="red") }) test_that("run time univ kNN", { skip("runtime comparison") dm <- "norm1" sp <- "symmetric1" noise <- function(i) cumsum(rnorm(i)) foo_2vec <- function(h, x, ws, k){ hscale <- IncDTW::scale( h , type="01") dis <- sapply(1:(length(x)-length(hscale)+1), function(i){ y <- IncDTW::scale(x[i:(i+length(hscale)-1)], type = "01") IncDTW::dtw2vec(y, hscale, dist_method = dm, step_pattern = sp, ws = ws)$dist }) nh <- length(hscale) dd <- dis best_i <- integer() for(i in 1:k){ ix <- which.min(dd) if(dd[ix] < Inf){ best_i <- c(best_i, ix) dd[max(1, (1 + ix - nh)):min((ix + nh - 1), length(dd))] <- Inf } } return(list(all_values = dis, indices=best_i)) } foo_cm <- function(h, x, ws, k){ hscale <- IncDTW::scale( h , type="01") dis <- sapply(1:(length(x)-length(hscale)+1), function(i){ y <- IncDTW::scale(x[i:(i+length(hscale)-1)], type = "01") cm_tmp <- IncDTW::cm(y, hscale, dist_method = dm, ws = ws) IncDTW::dtw2vec(cm_tmp, C = "cm", step_pattern = sp, ws = ws)$dist }) nh <- length(hscale) dd <- dis best_i <- integer() for(i in 1:k){ ix <- which.min(dd) if(dd[ix] < Inf){ best_i <- c(best_i, ix) dd[max(1, (1 + ix - nh)):min((ix + nh - 1), length(dd))] <- Inf } } return(list(all_values = dis, indices=best_i)) } foo_run <- function(h, x, ws, k){ dis <- rundtw(h, x, dm, sp, k=0, scale = "01", WS, Inf, T)$dist dis[is.nan(dis)] <- Inf nh <- length(hscale) dd <- dis best_i <- integer() for(i in 1:k){ ix <- which.min(dd) if(dd[ix] < Inf){ best_i <- c(best_i, ix) dd[max(1, (1 + ix - nh)):min((ix + nh - 1), length(dd))] <- Inf } } return(list(all_values = dis, indices=best_i)) } nx <- 1000 nh <- 50 nfits0 <- 3 nfits1 <- min(nfits0, floor(nx/nh)) nfits <- sample(nfits1, size = 1) nn <- nx - nfits * nh nn <- nn/nfits h <- noise(nh) x <- c() for(i in 1:nfits){ x <- c(x, noise(nn), h) } WS <- 30 k <- 5 mic <- microbenchmark::microbenchmark(foo_cm(h, x, WS,k=k), foo_2vec(h, x, WS, k=k), foo_run(h, x, WS, k=k), rundtw(h, x, dm, sp, k, "01", WS, Inf, T), times = 30) df0 <- maxaR::rel_microbenchmark(mic, cols = c("expr", "min", "mean", "median", "max", "neval"), rel_expr = "rundtw(h, x, dm, sp, k, '01', WS, Inf, T)")$df df0 }) test_that("run time univ", { skip("runtime comparison") dm <- "norm1" sp <- "symmetric1" nc <- 1 WS <- NULL noise <- function(i) matrix(cumsum(rnorm(i*nc)), nrow =i, ncol=nc) foo_2vec <- function(hscale, x, ws){ sapply(1:(length(x)-length(hscale)+1), function(i){ y <- IncDTW::scale(x[i:(i+length(hscale)-1)], type = "01") IncDTW::dtw2vec(y, hscale, dist_method = dm, step_pattern = sp, ws = ws)$dist }) } foo_cm <- function(hscale, x, ws){ sapply(1:(length(x)-length(hscale)+1), function(i){ y <- IncDTW::scale(x[i:(i+length(hscale)-1)], type = "01") cm_tmp <- IncDTW::cm(y, hscale, dist_method = dm, ws = ws) IncDTW::dtw2vec(cm_tmp, C = "cm", step_pattern = sp, ws = ws)$dist }) } NH <- c(0.05, 0.1, 0.15, 0.2) NX <- c(100, 200) NH <- seq(0.1, 0.5, 0.1) NX <- c(100, 200, 300, 500, 1000) df <- data.frame(expr = character(), min = numeric(), mean = numeric(), median = numeric(), max = numeric(), neval = integer(), rel = numeric(), nh = integer(), nx = integer(), nfits = integer() ) nhh <- NH[1] nx <- NX[5] data.table::fwrite(df, file = "build_ignore/comp_time_test_univ.txt") tic <- Sys.time() for(nhh in NH){ print(c(nhh)) print(Sys.time()) for(nx in NX){ print(c(nhh, nx)) print(Sys.time()) nh <- nhh*nx nfits0 <- 10 nfits1 <- min(nfits0, floor(nx/nh)) nfits <- sample(nfits1, size = 1) nn <- nx - nfits * nh nn <- nn/nfits h <- cumsum(rnorm(nh)) hscale <- IncDTW::scale( h , type="01") x <- c() for(i in 1:nfits){ x <- c(x, cumsum(rnorm(nn)), h) } mic <- microbenchmark::microbenchmark(foo_cm(hscale, x, WS), foo_2vec(hscale, x, WS), rundtw(hscale, x, dm, sp, 0, '01', WS, NULL), rundtw(hscale, x, dm, sp, 0, '01', WS, Inf), rundtw(hscale, x, dm, sp, 0, "z", WS, NULL), rundtw(hscale, x, dm, sp, 0, "z", WS, Inf), rundtw(hscale, x, dm, sp, 0, "none", WS, NULL), rundtw(hscale, x, dm, sp, 0, "none", WS, Inf), times = 30) df0 <- maxaR::rel_microbenchmark(mic, cols = c("expr", "min", "mean", "median", "max", "neval"), rel_expr = "rundtw(hscale, x, dm, sp, 0, \"01\", WS, Inf)")$df df0$nh <- nh df0$nx <- nx df0$nfits <- nfits data.table::fwrite(df0, file = "build_ignore/comp_time_test_univ.txt", append = T, row.names = F, col.names = F) df <- rbind(df, df0) } } print(Sys.time()) require(ggplot2) df <- data.table::fread(file = "build_ignore/comp_time_test_univ.txt") df <- df[grep("foo_",df$expr, invert = TRUE), ] df <- df[grep("none",df$expr, invert = TRUE), ] ggplot(df) + geom_line(aes(x = nh/nx, y = rel, group = expr, col = expr), size = 2)+ facet_grid(~nx) x <- matrix(cumsum(rnorm(3 * 1000)), ncol = 3) hscale <- matrix(cumsum(rnorm(3 * 100)), ncol = 3) mic <- microbenchmark::microbenchmark(rundtw(hscale, x, step_pattern = "symmetric1", scale = '01' , dist_method = "norm2_square", k = 0, ws = NULL, threshold = NULL, lower_bound = FALSE ), rundtw(hscale, x, step_pattern = "symmetric1", scale = 'z' , dist_method = "norm2_square", k = 0, ws = NULL, threshold = NULL, lower_bound = FALSE ), rundtw(hscale, x, step_pattern = "symmetric1", scale = 'none', dist_method = "norm2_square", k = 0, ws = NULL, threshold = NULL, lower_bound = FALSE ), times = 5) levels(mic$expr) <- c("f(01)", "f(z)", "f(none)") mic }) test_that("knn 01-scale vs. knn z-scale", { skip("comparison 01-z") dm <- "norm1" sp <- "symmetric1" WS <- 10 noise <- function(i) cumsum(rnorm(i)) h <- c(20, noise(10)) hscale01 <- IncDTW::scale(h, type="01") hscalez <- IncDTW::scale(h, type="z") par(mfrow=c(3,1)) plot(h, type="l") plot(hscale01, type="l") plot(hscalez, type="l") par(mfrow=c(1,1)) x <- c(noise(10), h, noise(10), h, noise(10), h, noise(10), h, noise(10)) ret01 <- rundtw(Q = h, C = x, dist_method = dm, step_pattern = sp, ws = WS, scale = "01", threshold = NULL, k = 10) retz <- rundtw(Q = h, C = x, dist_method = dm, step_pattern = sp, ws = WS, scale = "z", threshold = NULL, k = 10) ret01$knn_indices retz$knn_indices })
library("testthat") s <- "{DEFAULT @a = '123'} SELECT * FROM table WHERE x = @a AND {@b == 'blaat'}?{y = 1234}:{x = 1};" test_that("Parameter substitution works", { sql <- render(s, a = "abc") expect_equal(sql, "SELECT * FROM table WHERE x = abc AND x = 1;") }) test_that("Empty parameter does not cause trouble", { sql <- render(s, a = "abc", b = "") expect_equal(sql, "SELECT * FROM table WHERE x = abc AND x = 1;") }) test_that("Default works", { sql <- render(s, b = "1") expect_equal(sql, "SELECT * FROM table WHERE x = 123 AND x = 1;") }) test_that("If-then-else: then works", { sql <- render(s, b = "blaat") expect_equal(sql, "SELECT * FROM table WHERE x = 123 AND y = 1234;") }) test_that("If-then-else: else works", { sql <- render(s, b = "bla") expect_equal(sql, "SELECT * FROM table WHERE x = 123 AND x = 1;") }) test_that("If-then-else: boolean parameter interpreted as character", { sql <- render("SELECT * FROM table {@a}?{WHERE x = 1}", a = FALSE) expect_equal(sql, "SELECT * FROM table ") sql <- render("SELECT * FROM table {@a}?{WHERE x = 1}", a = TRUE) expect_equal(sql, "SELECT * FROM table WHERE x = 1") }) s <- "{1 IN (@a)}?{SELECT * FROM table}" test_that("If-then-else: IN pattern works if value is in", { sql <- render(s, a = c(1, 2, 3, 4)) expect_equal(sql, "SELECT * FROM table") }) test_that("If-then-else: IN pattern works if value is not in", { sql <- render(s, a = c(2, 3, 4)) expect_equal(sql, "") }) test_that("If-then-else: IN pattern works with space at start", { sql <- render("{ 1 IN (@a)}?{SELECT * FROM table}", a = c(2, 3, 4)) expect_equal(sql, "") sql <- render("{ 1 IN (@a)}?{SELECT * FROM table}", a = c(1, 2, 3, 4)) expect_equal(sql, "SELECT * FROM table") }) test_that("If-then-else: AND operator", { sql <- render("{true & true}?{true}:{false}") expect_equal(sql, "true") }) test_that("If-then-else: AND operator", { sql <- render("{true & false}?{true}:{false}") expect_equal(sql, "false") }) test_that("If-then-else: OR operator", { sql <- render("{true | false}?{true}:{false}") expect_equal(sql, "true") }) test_that("If-then-else: OR operator", { sql <- render("{true | true}?{true}:{false}") expect_equal(sql, "true") }) test_that("If-then-else: OR operator", { sql <- render("{false | false}?{true}:{false}") expect_equal(sql, "false") }) test_that("If-then-else: IN pattern nested in boolean condition", { sql <- render("{true & (true & (true & 4 IN (@a)))}?{true}:{false}", a = c(1, 2, 3)) expect_equal(sql, "false") }) test_that("If-then-else: nested if-then-else where nest in firing expression", { sql <- render("{true}?{{true} ? {double true} : {true false}} : {false}") expect_equal(sql, "double true") }) test_that("If-then-else: nested if-then-else where nest in non-firing expression", { sql <- render("{false}?{{true} ? {double true} : {true false}} : {false}") expect_equal(sql, "false") }) test_that("If-then-else: simple negation", { sql <- render("{!false}?{true}:{false}") expect_equal(sql, "true") }) test_that("If-then-else: negation of parameter", { sql <- render("{!@a}?{true}:{false}", a = "true") expect_equal(sql, "false") }) test_that("If-then-else: negation of parameter", { sql <- render("{!@a}?{true}:{false}", a = "true") expect_equal(sql, "false") }) test_that("If-then-else: does not equals pattern 1", { sql <- render("{123 != 123}?{true}:{false}") expect_equal(sql, "false") }) test_that("If-then-else: does not equals pattern 1", { sql <- render("{123 != 234}?{true}:{false}") expect_equal(sql, "true") }) test_that("If-then-else: does not equals pattern 2", { sql <- render("{123 <> 123}?{true}:{false}") expect_equal(sql, "false") }) test_that("If-then-else: does not equals pattern 2", { sql <- render("{123 <> 234}?{true}:{false}") expect_equal(sql, "true") }) test_that("If-then-else: Nested IN evaluates to true", { sql <- render("{TRUE & (FALSE | 1 IN (1,2,3))} ? {true} : {false}") expect_equal(sql, "true") }) test_that("If-then-else: Nested IN evaluates to false", { sql <- render("{TRUE & (FALSE | 4 IN (1,2,3))} ? {true} : {false}") expect_equal(sql, "false") }) test_that("Backslash in parameter is handled correctly", { sql <- render("SELECT * FROM table WHERE name = '@name';", name = "NA\\joe") expect_equal(sql, "SELECT * FROM table WHERE name = 'NA\\joe';") }) test_that("Dollar in parameter is handled correctly", { sql <- render("SELECT * FROM table WHERE name = '@name';", name = "NA$joe") expect_equal(sql, "SELECT * FROM table WHERE name = 'NA$joe';") }) test_that("If-then-else: error on bad boolean logic syntax", { expect_error(render("{true = true} ? {true} : {false}")) }) test_that("rendering: warning on parameter name mismatch", { expect_warning(render("SELECT * FROM @my_table", a_table = "x")) }) test_that("rendering: no problem when not providing parameters", { expect_equal(render("SELECT * FROM @my_table"), "SELECT * FROM @my_table") }) test_that("rendering: warning when using old function", { expect_warning(renderSql("SELECT * FROM @my_table")) })
check_netmhc2pan_installation <- function( netmhc2pan_folder_name = get_default_netmhc2pan_folder() ) { if (!is_netmhc2pan_bin_installed( netmhc2pan_folder_name = netmhc2pan_folder_name) ) { bin_file_path <- file.path( netmhc2pan_folder_name, basename(get_default_netmhc2pan_subfolder()), basename(get_default_netmhc2pan_bin_path()) ) netmhc2pan_version <- stringr::str_match( bin_file_path, "[:digit:]\\.[:digit:]" )[1, 1] stop( "NetMHCIIpan binary not found at\n", bin_file_path, "\n", "\n", "Tip 1: from R, run 'netmhc2pan::install_netmhc2pan()'\n", " with a (non-expired) download URL\n", "Tip 2: request a download URL at the NetMHCIIpan download page at\n", "\n", paste0( "https://services.healthtech.dtu.dk/service.php?NetMHCIIpan-", netmhc2pan_version, "\n" ) ) } if (!is_netmhc2pan_data_installed(netmhc2pan_folder_name)) { data_file_path <- file.path( netmhc2pan_folder_name, basename(get_default_netmhc2pan_subfolder()), "data" ) stop( "NetMHCIIpan data not found at\n", data_file_path, "\n", "\n", "Tip: from R, run 'netmhc2pan::install_netmhc2pan()'\n" ) } if (!is_netmhc2pan_set_up(netmhc2pan_folder_name)) { stop( "NetMHCIIpan not set up completely\n", "\n", "Tip: from R, run 'nethmhc2pan::install_netmhc2pan()'\n" ) } if (!is_tcsh_installed()) { stop( "Debian package 'tcsh' not found\n", "\n", "Tip: from the terminal, run 'sudo apt install tcsh'" ) } }
impute <- function(x, ...) UseMethod("impute") impute.default <- function(x, fun=median, ...) { m <- is.na(x) k <- sum(m) if(k==0) return(x) nam <- names(x) if(!length(nam)) { nam <- as.character(1:length(x)); names(x) <- nam } if(!is.function(fun)) { fill <- fun if(is.character(fill) && length(fill)==1 && fill=="random") fill <- sample(x[!is.na(x)], sum(is.na(x)), replace=TRUE) } else if(is.factor(x)) { freq <- table(x) fill <- names(freq)[freq==max(freq)][1] } else fill <- if(missing(fun) && is.logical(x)) (if(sum(x[!m]) >= sum(!m)/2) TRUE else FALSE) else fun(x[!m]) if(length(fill)>1 && length(fill)!=k) stop("length of vector of imputed values != no. NAs in x") if(is.factor(x)) { newlev <- sort(unique(fill)) if(any(!(z <- newlev %in% levels(x)))) { xc <- as.character(x) xc[m] <- fill x <- factor(xc, c(levels(x), newlev[!z])) } else x[m] <- fill } else x[m] <- fill structure(x, imputed=(1:length(x))[m], class=c('impute', attr(x, 'class'))) } print.impute <- function(x, ...) { i <- attr(x,"imputed") if(!length(i)) { print.default(x); return(invisible()) } if(is.factor(x)) w <- as.character(x) else w <- format(x) names(w) <- names(x) w[i] <- paste(w[i], "*", sep="") attr(w, "label") <- attr(w,"imputed") <- attr(w, "class") <- NULL print.default(w, quote=FALSE) invisible() } summary.impute <- function(object, ...) { i <- attr(object, "imputed") oi <- object attr(oi,'class') <- attr(oi,'class')[attr(oi,'class')!="impute"] oi <- oi[i] if(all(oi==oi[1])) cat("\n",length(i),"values imputed to", if(is.numeric(oi)) format(oi[1]) else as.character(oi[1]), "\n\n") else { cat("\nImputed Values:\n\n") if(length(i)<20) print(oi) else print(describe(oi, descript=as.character(sys.call())[2])) cat("\n") } NextMethod("summary") } "[.impute" <- function(x, ..., drop=FALSE) { ats <- attributes(x) ats$dimnames <- NULL ats$dim <- NULL ats$names <- NULL attr(x,'class') <- NULL y <- x[..., drop = drop] if(length(y)==0) return(y) k <- 1:length(x); names(k) <- names(x) k <- k[...] attributes(y) <- c(attributes(y), ats) imp <- attr(y, "imputed") attr(y, "imputed") <- j <- (1:length(k))[k %in% imp] if(length(j)==0) { cy <- attr(y,'class')[attr(y,'class')!='impute'] y <- structure(y, imputed=NULL, class=if(length(cy)) cy else NULL) } y } is.imputed <- function(x) { w <- rep(FALSE, if(is.matrix(x))nrow(x) else length(x)) if(length(z <- attr(x,"imputed"))) w[z] <- TRUE w } as.data.frame.impute <- function(x, row.names = NULL, optional = FALSE, ...) { nrows <- length(x) if(!length(row.names)) { if(length(row.names <- names(x)) == nrows && !anyDuplicated(row.names)) { } else if(optional) row.names <- character(nrows) else row.names <- as.character(1:nrows) } value <- list(x) if(!optional) names(value) <- deparse(substitute(x))[[1]] structure(value, row.names=row.names, class='data.frame') }
pns <- function(subnational_shares, method = 'Jones-Mainwaring') { if (class(subnational_shares) != 'numeric') { stop('Input vector must be numeric') } if (is.na(sum(subnational_shares))) { stop('NA not allowed in input') } if (!method %in% c('Jones-Mainwaring', 'Golosov')) { stop('Not a valid method') } if (method == 'Jones-Mainwaring') { pns <- 1 - Gini(subnational_shares) } else if (method == 'Golosov') { n_sub <- length(subnational_shares) pns <- 1- (n_sub - sum(subnational_shares)^2/sum(subnational_shares^2))/(n_sub - 1) } pns }
library(testthat) library(shiny.router) test_check("shiny.router")
rrpexpow = function(n, lambda = 1, mu= 0, sigma = 1, k = 0){ n = runif(n) x = qrpexpow(n, lambda, mu, sigma, k) return(x) }
setMethodS3("addFinalizerToLast", "default", function(...) { if (exists(".Last", mode="function")) { .Last <- get(".Last", mode="function") if (identical(attr(.Last, "finalizeSession"), TRUE)) { ver <- attr(.Last, "finalizeSessionVersion") if (!is.null(ver) && compareVersion(ver, "0.8.5") >= 0) { return(invisible(FALSE)) } } else { env <- globalenv(); assign(".LastOriginal", .Last, envir=env) } .Last <- function(...) { tryCatch({ if (exists("finalizeSession", mode="function")) finalizeSession() if (exists(".LastOriginal", mode="function")) { .LastOriginal <- get(".LastOriginal", mode="function") .LastOriginal() } }, error = function(ex) { message("Ignoring error occured in .Last(): ", as.character(ex)) }) } } else { .Last <- function(...) { tryCatch({ if (exists("finalizeSession", mode="function")) finalizeSession() }, error = function(ex) { message("Ignoring error occured in .Last(): ", as.character(ex)) }) } } attr(.Last, "finalizeSession") <- TRUE attr(.Last, "finalizeSessionVersion") <- packageDescription("R.utils")$Version environment(.Last) <- globalenv() env <- globalenv(); assign(".Last", .Last, envir=env) invisible(FALSE) }, private=TRUE)
context("currencies") test_that("it should get currency data from BCB", { skip_on_cran() x <- get_currency("USD", "2017-03-01", "2017-03-02", as = "text") expect_is(x, "character") expect_equal(x, "01032017;220;A;USD;3,0970;3,0976;1,0000;1,0000\n02032017;220;A;USD;3,1132;3,1138;1,0000;1,0000\n") }) test_that("it should get a time series of a currency from bcb", { skip_on_cran() x <- get_currency("USD", "2017-03-01", "2017-03-14") expect_is(x, "data.frame") expect_equal(dim(x), c(10, 3)) expect_error( get_currency("BRL", "2017-03-01", "2017-03-14") ) }) test_that("it should get currency code", { skip_on_cran() x <- get_currency_id("BRL") expect_equal(x, 177) }) test_that("it should get MXN and ARS data", { skip_on_cran() x <- get_currency("MXN", "2018-05-28", "2018-05-30") expect_is(x, "data.frame") expect_equal(dim(x), c(3, 3)) x <- get_currency("ARS", "2018-05-28", "2018-05-30") expect_is(x, "data.frame") expect_equal(dim(x), c(3, 3)) }) test_that("it should get a time series with a symbol attribute", { skip_on_cran() x <- get_currency("USD", "2017-03-01", "2017-03-14") expect_is(x, "data.frame") expect_equal(attr(x, "symbol"), "USD") x <- get_currency("USD", "2017-03-01", "2017-03-14", as = "xts") expect_is(x, "xts") expect_equal(attr(x, "symbol"), "USD") }) test_that("it should get ask/bid time series named with symbol", { skip_on_cran() x <- get_currency("USD", "2017-03-01", "2017-03-14") x_ask <- Ask(x) expect_equal(colnames(x_ask), c("date", "USD")) x_bid <- Bid(x) expect_equal(colnames(x_bid), c("date", "USD")) x <- get_currency("USD", "2017-03-01", "2017-03-14", as = "xts") x_ask <- Ask(x) expect_equal(colnames(x_ask), "USD") x_bid <- Bid(x) expect_equal(colnames(x_bid), "USD") })
message("\nTesting get_body_part_names") test_that("Structure of body parts value", { skip_on_cran() bp_names_all <- get_body_part_names() expect_equal(length(bp_names_all), 3) expect_true(length(bp_names_all$body_parts) > 20) expect_true(length(bp_names_all$content) > 20) expect_equal(class(bp_names_all$response), "response") }) test_that("Body part values for TCGA-BRCA", { skip_on_cran() bp_names_tcga <- get_body_part_names(collection = "TCGA-BRCA") expect_identical(bp_names_tcga$body_parts, c("BREAST")) }) test_that("Body part values for MR", { skip_on_cran() bp_names_mr <- get_body_part_names(modality = "MR") expect_true(length(bp_names_mr$body_parts) > 10) expect_true("BREAST" %in% bp_names_mr$body_parts) }) test_that("Body part values for TCGA-BRCA and MR", { skip_on_cran() bp_names_tcga_mr <- get_body_part_names(collection = "TCGA-BRCA", modality = "MR") expect_identical(bp_names_tcga_mr$body_parts, c("BREAST")) }) test_that("Nonexistent collection and modality combination", { skip_on_cran() expect_warning(bp <- get_body_part_names(collection = "TCGA-BRCA", modality = "RTSTRUCT")) suppressWarnings(bp <- get_body_part_names(collection = "TCGA-BRCA", modality = "RTSTRUCT")) expect_equal(length(bp$body_parts), 0) }) test_that("Invalid collection name", { skip_on_cran() expect_warning(bp <- get_body_part_names(collection = "fake_collection")) suppressWarnings(bp <- get_body_part_names(collection = "fake_collection")) expect_equal(length(bp$body_parts), 0) }) test_that("Invalid modality", { skip_on_cran() expect_warning(bp <- get_body_part_names(modality = "fake_modality")) suppressWarnings(bp <- get_body_part_names(modality = "fake_modality")) expect_equal(length(bp$body_parts), 0) })
intermediate.corr.BC <- function(n.P, n.B, n.C, lambda.vec=NULL, prop.vec=NULL, coef.mat=NULL, corr.vec = NULL, corr.mat=NULL) { validation.bin(n.B, prop.vec) if(is.null(corr.mat) && !is.null(corr.vec)) { d=ceiling(uniroot(function(d) d^2-d-2*length(corr.vec), interval=c(0,1000))$root) corr.mat=diag(1,d) corr.mat[lower.tri(corr.mat)]=corr.vec corr.mat=corr.mat+t(corr.mat)-diag(1,d) } if((n.P+n.B+n.C) !=ncol(corr.mat)) stop("Dimension of the correlation matrix is misspecied!") correlation.bound.check(n.P, n.B, n.C, lambda.vec, prop.vec, coef.mat, corr.vec = NULL, corr.mat=corr.mat) cor.bn=apply(as.matrix(prop.vec,length(prop.vec),1),1,function(x) dnorm(qnorm(x))/sqrt(x*(1-x))) bicor.mat=t(sapply(1:n.B, function(ii) sapply(1:n.C, function(i) (corr.mat[(ii+n.P),(i+n.B+n.P)]/cor.bn[ii])/(coef.mat[2,i]+3*coef.mat[4,i])))) return(bicor.mat) }
knitr::opts_chunk$set( collapse = TRUE, comment = " ) library(dplyr) library(ggplot2) library(survival) library(survParamSim) set.seed(12345) colon2 <- as_tibble(colon) %>% filter(rx != "Lev", etype == 1) %>% mutate(rx = factor(rx, levels = c("Obs", "Lev+5FU")), depth = as.numeric(extent <= 2)) survfit.colon <- survfit(Surv(time, status) ~ rx, data = colon2) survminer::ggsurvplot(survfit.colon) survfit.colon.censor <- survfit(Surv(time, 1-status) ~ rx, data = colon2) survminer::ggsurvplot(survfit.colon.censor) fit.colon <- survreg(Surv(time, status) ~ rx + node4 + depth, data = colon2, dist = "lognormal") summary(fit.colon) sim <- surv_param_sim(object = fit.colon, newdata = colon2, censor.dur = c(1800, 3000), n.rep = 100) sim km.pi <- calc_km_pi(sim, trt = "rx") km.pi plot_km_pi(km.pi) + theme(legend.position = "bottom") + labs(y = "Recurrence free rate") + expand_limits(y = 0) extract_medsurv_pi(km.pi) km.pi <- calc_km_pi(sim, trt = "rx", group = c("node4", "depth")) plot_km_pi(km.pi) + theme(legend.position = "bottom") + labs(y = "Recurrence free rate") + expand_limits(y = 0) hr.pi <- calc_hr_pi(sim, trt = "rx", group = c("depth")) hr.pi plot_hr_pi(hr.pi) extract_hr_pi(hr.pi)
analysis.sensitivity <- function(Y, plan, nbcomp=2, sigma.car=NULL, analysis.args=list( keep.outputs=FALSE ) ) { a.args=analysis.args if(is.null(a.args$keep.outputs)){ a.args$keep.outputs=FALSE; } outputkept=NULL; if(a.args$keep.outputs) outputkept=vector("list",nbcomp) PC.names <- colnames(Y)[1:nbcomp]; indic.fact <- diag(1,nrow=ncol(plan$X)) rownames(indic.fact) <- colnames(plan$X) colnames(indic.fact) <- colnames(plan$X) indices <- as.data.frame(matrix(NA,ncol(plan$X),nbcomp)) rownames(indices) <-colnames(plan$X) colnames(indices) <- PC.names indices.tot <- indices indices.inter <- indices.tot indices.main <- indices.tot if(class(plan)=="morris"){ cat("Be careful : morris method used, changes in outputs : SI contains mu, mSI contains mu.star, tSI contains sigma.\n") }else { if(class(plan)=="sobolroalhs"){ cat("Be careful : sobolroalhs method used, changes in outputs : SI contains Seff for the Janon-Monod estimator, mSI contains S for the standard estimator, tSI and iSI contain nothing.\n") } } for(k in 1:nbcomp){ xtemp=plan tell(xtemp,Y[,k]) if(class(plan)=="fast99"){ xtemp$S=matrix(xtemp$D1/xtemp$V,ncol(plan$X),1) xtemp$T=matrix(1 - xtemp$Dt / xtemp$V,ncol(plan$X),1) }else{if(class(plan)=="morris"){ indices[,k] <- matrix(colMeans(xtemp$ee),ncol(plan$X),1) xtemp$S <- matrix(colMeans(abs(xtemp$ee)),ncol(plan$X),1) xtemp$T <- matrix(apply(xtemp$ee, 2, sd),ncol(plan$X),1) }} indices.main[,k]=xtemp$S[1:nrow(indices.main),1] if(!is.null(xtemp$T)){ indices.tot[,k]=xtemp$T[,1] }else{if(class(plan)=="sobolroalhs"){ indices[,k] <- xtemp$S[seq(from=1+nrow(indices.main),to=2*nrow(indices.main),by=1),1] }} if(a.args$keep.outputs){ outputkept[[k]]=xtemp names(outputkept)[[k]]=paste(class(plan),k,sep="_") } } if(!is.null(sigma.car) && class(plan)!="morris"){ VarH=apply(Y[,1:nbcomp,drop=FALSE],2,var) GSI=rowSums(indices.main*t(matrix(rep(VarH,nrow(indices.main)),nbcomp,nrow(indices.main))),na.rm=TRUE)/sum(VarH) indices.main=cbind(indices.main,GSI) if(!is.null(xtemp$T)){ GSI=rowSums(indices.tot*t(matrix(rep(VarH,nrow(indices.tot)),nbcomp,nrow(indices.tot))),na.rm=TRUE)/sum(VarH) indices.tot=cbind(indices.tot,GSI) }else{ indices.tot=cbind(indices.tot,NA) colnames(indices.tot)[ncol(indices.tot)]="GSI" } } indices.inter <- indices.tot- indices.main call.info=list(analysis="sensitivity",fct=class(plan)) return(list(SI=indices, mSI=indices.main, tSI=indices.tot, iSI=indices.inter, inertia=rep(NA,nbcomp), indic.fact=indic.fact, Hpredict=NULL, outputkept=outputkept, call.info=call.info)) }
NULL adj_object <- function(x, cluster = NULL, use_vcov = TRUE, ...) { find_methods_fn <- function(i) as.vector(utils::methods(class = class(x)[i])) all_methods <- unlist(sapply(1:length(class(x)), find_methods_fn)) has_logLikVec_method <- paste0("logLikVec.", class(x)) %in% all_methods if (!any(has_logLikVec_method)) { stop("A logLikVec method must be available for x") } loglik_fn <- function(pars, fitted_object, ...) { return(logLikVec(fitted_object, pars = pars)) } if (!use_vcov) { H <- NULL } else { has_vcov_method <- paste0("vcov.", class(x)) %in% all_methods if (any(has_vcov_method)) { H <- -solve(vcov(x)) } else { H <- NULL } } mle <- coef(x) n_obs <- nobs(x) if (is.null(cluster)) { V <- sandwich::meat(x, fitted_object = x, loglik_fn = loglik_fn, ...) * n_obs } else { V <- sandwich::meatCL(x, cluster = cluster, fitted_object = x, loglik_fn = loglik_fn, ...) * n_obs } res <- chandwich::adjust_loglik(loglik = loglik_fn, fitted_object = x, p = length(mle), par_names = names(mle), name = paste(class(x), collapse = "_"), mle = mle, H = H, V = V) class(res) <- c("lax", "chandwich") return(res) } ismev_ppp <- function (a, npy) { u <- a[4] la <- 1 - exp(-(1 + (a[3] * (u - a[1]))/a[2])^(-1/a[3])/npy) sc <- a[2] + a[3] * (u - a[1]) xi <- a[3] c(la, sc, xi) } return_level_gev <- function(x, m, level, npy, prof, inc, type) { rl_sym <- gev_rl_CI(x, m, level, npy, type) rl_se <- rl_sym["se"] rl_sym <- rl_sym[c("lower", "mle", "upper")] if (!prof) { return(list(rl_sym = rl_sym, rl_prof = NULL, rl_se = rl_se)) } temp <- gev_rl_prof(x, m, level, npy, inc, type, rl_sym) return(list(rl_sym = rl_sym, rl_prof = temp$rl_prof, rl_se = rl_se, max_loglik = logLik(x), crit = temp$crit, for_plot = temp$for_plot)) } gev_rl_prof <- function(x, m, level, npy, inc, type, rl_sym) { if (is.null(inc)) { inc <- (rl_sym["upper"] - rl_sym["lower"]) / 100 } p <- 1 / (m * npy) gev_neg_prof_loglik <- function(a, xp) { if (a[1] <= 0) { return(10 ^ 10) } mu <- xp - revdbayes::qgev(1 - p, loc = 0, scale = a[1], shape = a[2]) gev_pars <- c(mu, a[1:2]) return(-x(gev_pars)) } rl_mle <- rl_sym["mle"] max_loglik <- attr(x, "max_loglik") conf_line <- max_loglik - 0.5 * stats::qchisq(level, 1) v1 <- v2 <- x1 <- x2 <- NULL x2[1] <- x1[1] <- rl_mle v2[1] <- v1[1] <- max_loglik xp <- rl_mle my_val <- max_loglik ii <- 1 sol <- attr(x, "MLE")[2:3] while (my_val > conf_line){ xp <- xp + inc opt <- stats::optim(sol, gev_neg_prof_loglik, method = "BFGS", xp = xp) sol <- opt$par ii <- ii + 1 x2[ii] <- xp v2[ii] <- -opt$value my_val <- v2[ii] } sol_up <- sol xp <- rl_mle my_val <- max_loglik ii <- 1 sol <- attr(x, "MLE")[2:3] while (my_val > conf_line){ xp <- xp - inc opt <- stats::optim(sol, gev_neg_prof_loglik, method = "BFGS", xp = xp) sol <- opt$par ii <- ii + 1 x1[ii] <- xp v1[ii] <- -opt$value my_val <- v1[ii] } sol_low <- sol prof_lik <- c(rev(v1), v2) ret_levs <- c(rev(x1), x2) temp <- diff(prof_lik - conf_line > 0) loc <- which(temp == -1) x1 <- ret_levs[loc] x2 <- ret_levs[loc + 1] y1 <- prof_lik[loc] y2 <- prof_lik[loc + 1] up_lim <- x1 + (conf_line - y1) * (x2 - x1) / (y2 - y1) loc <- which(temp == 1) x1 <- ret_levs[loc] x2 <- ret_levs[loc+1] y1 <- prof_lik[loc] y2 <- prof_lik[loc+1] low_lim <- x1 + (conf_line - y1) * (x2 - x1) / (y2 - y1) rl_prof <- c(lower = low_lim, rl_mle, upper = up_lim) return(list(rl_prof = rl_prof, crit = conf_line, for_plot = cbind(ret_levs = ret_levs, prof_loglik = prof_lik))) } gev_rl_CI <- function (x, m, level, npy, type){ mle <- attr(x, "MLE") mu <- mle[1] sigma <- mle[2] xi <- mle[3] if (type == "none") { mat <- attr(x, "VC") } else { mat <- attr(x, "adjVC") } p <- 1 / (m * npy) rl_mle <- revdbayes::qgev(p, loc = mu, scale = sigma, shape = xi, lower.tail = FALSE) yp <- -log(1 - p) delta <- matrix(0, 3, 1) delta[1,] <- 1 delta[2,] <- revdbayes::qgev(p, loc = 0, scale = 1, shape = xi, lower.tail = FALSE) delta[3,] <- sigma * box_cox_deriv(yp, lambda = -xi) rl_var <- t(delta) %*% mat %*% delta rl_se <- sqrt(rl_var) z_val <- stats::qnorm(1 - (1 - level) / 2) rl_lower <- rl_mle - z_val * rl_se rl_upper <- rl_mle + z_val * rl_se res <- c(lower = rl_lower, mle = rl_mle, upper = rl_upper, se = rl_se) return(res) } box_cox_deriv <- function(x, lambda = 1, lambda_tol = 1 / 50, poly_order = 3) { lnx <- log(x) if (abs(lambda) > lambda_tol) { retval <- (lambda * x ^ lambda * lnx - x ^ lambda + 1) / lambda ^ 2 } else { i <- 0:poly_order retval <- sum(lnx ^ (i + 2) * lambda ^ i / ((i + 2) * factorial(i))) } return(retval) }
bq_projects <- function(page_size = 100, max_pages = 1, warn = TRUE) { pages <- bq_get_paginated( "projects", query = list(fields = "projects(projectReference(projectId))"), page_size = page_size, max_pages = max_pages ) projects <- unlist(lapply(pages, function(x) x$projects), recursive = FALSE) map_chr(projects, function(x) x$projectReference$projectId) }
SpellCheck = function(file) { if (interactive()) { for (ThisFile in file) { cat(paste0(ThisFile, ": ")) if (file.exists(ThisFile)) { file.copy(ThisFile, paste0(ThisFile, ".bak"), overwrite = FALSE) cat("\n", file = ThisFile, append = TRUE) OldText <- readLines(con = ThisFile) Mistakes = SpellCheckFiles(file = ThisFile) for (i in names(Mistakes[[1]])) { Lines = gsub(",", ", ", Mistakes[[1]][i]) LineNos = as.numeric(unlist(strsplit(Lines, ", "))) UserPref = 6 while (UserPref > 4) { UserPref = menu( list( "Ignore this word", "add this word to the global list of words to ignore", "add this word to the list of words to ignore when checking this file", "change it to...", paste0("read the word '", i, "' in context")), title = paste0( "\n", i, " appears to be misspelled on ", ifelse(length(LineNos) > 1, "lines", "line"), Lines)) if (UserPref == "5") { cat(paste0(OldText[LineNos], "\n")) } } if (UserPref == "2") { cat(paste0(i, "\n"), file = paste0(getOption("BrailleR.Folder"), "words.ignore.txt"), append = TRUE) } if (UserPref == "3") { cat(paste0(i, "\n"), file = paste0(ThisFile, ".ignore.txt"), append = TRUE) } if (UserPref == "4") { cat("Enter replacement text: ") Replace = readLines(n = 1) OldText = gsub(i, Replace, OldText) } } NoLines = length(OldText) if (NoLines > 2) { if (all(OldText[c(NoLines - 1, NoLines)] == "\n")) { NoLines = NoLines - 1 } } writeLines(OldText[1:NoLines], con = ThisFile) message("Done.") } else { warning("The specified file does not exist.\n") } } } else { warning("This function is meant for use in interactive mode only.\n") } return(invisible(NULL)) }
pb_download_url <- function(file = NULL, repo = guess_repo(), tag = "latest", .token = get_token()) { df <- pb_info(repo, tag, .token) if (is.null(file)) { return(df$browser_download_url) } else if (file %in% df$file_name) { return(df[file == df$file_name, "browser_download_url"]) } else { stop(paste("file", file, "not found in release", tag, "for repo", repo)) } }
tts_speak_engine = function(options) { if (!options$eval) { return(knitr::engine_output(options, options$code, "")) } output_format = options$output_format service = options$service voice = options$voice if (is.null(service)) { service = "google" } if (is.null(voice)) { voice = tts_default_voice(service = service) } if (is.null(output_format)) { output_format = "mp3" } out_path = dirname(options$fig.path) dir.create(out_path, showWarnings = FALSE, recursive = TRUE) output = file.path( out_path, paste0(options$label, ".", output_format)) if (!file.exists(output)) { options$cache = FALSE } key_or_json_file = options$key_or_json_file if (!is.null(key_or_json_file)) { text2speech::tts_auth(service = service, key_or_json_file = key_or_json_file) } text = paste0(options$code, collapse = " ") result = text2speech::tts( text = text, output_format = output_format, service = service, voice = voice ) file.copy(result$file, output, overwrite = TRUE) out = utils::capture.output(output) if (knitr::is_html_output()) { if (options$results != "hide") { options$results = "asis" out = c("<audio controls>", paste0('<source src="', output, '">'), "</audio>", "") } else { out = "" } } print(out) knitr::engine_output(options, options$code, out) }
dist2d <- function(a,b,c) { v1 <- b - c v2 <- a - b m <- cbind(v1,v2) abs(det(m))/sqrt(sum(v1*v1)) } distMat <- function(x,y,theta) { ncomp <- length(theta) n <- length(x) dM <- matrix(nrow=n,ncol=ncomp) for(j in 1:ncomp) { beta <- theta[[j]][["beta"]] b0 <- if(length(beta)==2) beta[1] else 0 b1 <- if(length(beta)==2) beta[2] else beta[1] for(i in 1:n) { x1 <- (b1*y[i] + x[i] - b0*b1)/(1+b1^2) y1 <- b0+b1*x1 dM[i,j] <- (x[i] - x1)^2 + (y[i] - y1)^2 } } sqrt(dM) }
testthat_examples <- function() { system.file("examples", package = "testthat") } testthat_example <- function(filename) { system.file( "examples", paste0("test-", filename, ".R"), package = "testthat", mustWork = TRUE ) }