code
stringlengths
1
13.8M
.runThisTest <- Sys.getenv("RunAllparametersTests") == "yes" if (.runThisTest && requiet("testthat") && requiet("parameters") && requiet("tripack") && requiet("insight") && requiet("quantreg")) { data("CobarOre") set.seed(123) CobarOre$w <- rnorm(nrow(CobarOre)) m1 <- rqss(z ~ w + qss(cbind(x, y), lambda = .08), data = CobarOre) mp <- suppressWarnings(model_parameters(m1)) test_that("mp_rqss", { expect_identical(mp$Parameter, c("(Intercept)", "w", "cbind(x, y)")) expect_equal(mp$Coefficient, c(17.63057, 1.12506, NA), tolerance = 1e-3) expect_equal(mp$df_error, c(15, 15, NA), tolerance = 1e-3) expect_equal(mp[["df"]], c(NA, NA, 70), tolerance = 1e-3) }) data(stackloss) m1 <- rq(stack.loss ~ Air.Flow + Water.Temp, data = stackloss, tau = .25) mp <- suppressWarnings(model_parameters(m1)) test_that("mp_rq", { expect_identical(mp$Parameter, c("(Intercept)", "Air.Flow", "Water.Temp")) expect_equal(mp$Coefficient, c(-36, 0.5, 1), tolerance = 1e-3) }) set.seed(123) data("engel") m1 <- rq(foodexp ~ income, data = engel, tau = 1:9 / 10) mp <- suppressWarnings(model_parameters(m1)) test_that("mp_rqs", { expect_identical(mp$Parameter, c( "(Intercept)", "income", "(Intercept)", "income", "(Intercept)", "income", "(Intercept)", "income", "(Intercept)", "income", "(Intercept)", "income", "(Intercept)", "income", "(Intercept)", "income", "(Intercept)", "income" )) expect_equal(mp$Coefficient, c( 110.14157, 0.40177, 102.31388, 0.4469, 99.11058, 0.48124, 101.95988, 0.5099, 81.48225, 0.56018, 79.70227, 0.58585, 79.28362, 0.60885, 58.00666, 0.65951, 67.35087, 0.6863 ), tolerance = 1e-3) expect_equal(mp$SE, c( 29.39768, 0.04024, 21.42836, 0.02997, 22.18115, 0.02987, 22.06032, 0.02936, 19.25066, 0.02828, 17.61762, 0.02506, 14.25039, 0.02176, 19.21719, 0.02635, 22.39538, 0.02849 ), tolerance = 1e-3) }) set.seed(123) n <- 200 x <- rnorm(n) y <- 5 + x + rnorm(n) c <- 4 + x + rnorm(n) d <- (y > c) dat <- data.frame(y, x, c, d) m1 <- crq(survival::Surv(pmax(y, c), d, type = "left") ~ x, method = "Portnoy", data = dat) mp <- model_parameters(m1) test_that("mp_rq", { expect_identical(mp$Parameter, c("(Intercept)", "x", "(Intercept)", "x", "(Intercept)", "x", "(Intercept)", "x")) expect_equal(mp$Coefficient, c(4.26724, 0.97534, 4.84961, 0.92638, 5.21843, 0.98038, 5.91301, 0.97382), tolerance = 1e-3) }) }
extractPSSMAcc <- function(pssmmat, lag) { mat <- 1 / (1 + exp(pssmmat)) accpssm <- function(mat, lag) { p <- nrow(mat) n <- ncol(mat) if (lag > n) { stop("lag must be smaller than the amino acids in the sequence") } acc1 <- matrix(0, nrow = p, ncol = lag) for (j in 1:p) { for (i in 1:lag) { acc1[j, i] <- sum(mat[j, 1:(n - i)] * mat[j, ((1:(n - i)) + i)]) / (n - i) } } acc1 <- as.vector(acc1) AADict <- c( "A", "R", "N", "D", "C", "Q", "E", "G", "H", "I", "L", "K", "M", "F", "P", "S", "T", "W", "Y", "V" ) names(acc1) <- as.vector(outer( AADict, paste0("lag", 1:lag), paste, sep = "." )) acc2 <- matrix(0, nrow = p^2 - p, ncol = lag) idx <- cbind(combn(1:p, 2), combn(1:p, 2)[2:1, ]) for (j in 1:ncol(idx)) { for (i in 1:lag) { acc2[j, i] <- sum(mat[idx[1, j], 1:(n - i)] * mat[idx[2, j], ((1:(n - i)) + i)]) / (n - i) } } acc2 <- as.vector(acc2) names(acc2) <- as.vector(outer( paste(AADict[idx[1, ]], AADict[idx[2, ]], sep = "."), paste0("lag", 1:lag), paste, sep = "." )) ACC <- c(acc1, acc2) ACC } res <- accpssm(mat, lag) res }
library(PAFit) net <- generate_net(N = 50, m = 10, mode = 1, s = 100, no_new_node_step = 1, m_no_new_node_step = 1) net$graph
setClass("bmerHorseshoeDist", representation(beta.0 = "numeric", tau.sq = "numeric"), contains = "bmerDist") toString.bmerHorseshoeDist <- function(x, digits = getOption("digits"), ...) { meanString <- "" beta.0 <- [email protected] if (length(beta.0) > 4L) { meanString <- paste0("mean = c(", toString(round(beta.0[seq_len(4L)], digits)), ", ...)") } else if (length(beta.0) == 1L) { meanString <- paste0("mean = ", toString(round(beta.0[1L], digits))) } else { meanString <- paste0("mean = c(", toString(round(beta.0, digits)), ")") } paste0("horseshoe(", meanString, ", ", "global.shrinkage = ", round(sqrt([email protected]), digits), ", ", "common.scale = ", x@commonScale, ")") } setMethod("getDFAdjustment", "bmerHorseshoeDist", function(object) { if (object@commonScale == TRUE) length([email protected]) else 0 } ) setMethod("getConstantTerm", "bmerHorseshoeDist", function(object) { d <- length([email protected]) d * (3 * log(pi) + log(2) + log([email protected])) } ) setMethod("getExponentialTerm", "bmerHorseshoeDist", function(object, beta, sigma = NULL) { beta.0 <- [email protected] tau.sq <- [email protected] dist <- 0.5 * (beta - beta.0)^2 / tau.sq if (object@commonScale == TRUE && !is.null(sigma)) dist <- dist / sigma^2 temp <- suppressWarnings(sapply(dist, expint::expint_E1, scale = TRUE)) temp[is.nan(temp)] <- .Machine$double.xmax * .Machine$double.eps result <- -2 * sum(log(temp)) c(0, result) } )
hullEFA <- function(X, maxQ, extr = "ULS", index_hull = "CAF", display = TRUE, graph = TRUE, details = TRUE){ if (missing(X)){ stop("The argument X is not optional, please provide a valid raw sample scores") } if (extr!="ML" && extr!="ULS"){ stop("extr argument has to be ML or ULS") } if (index_hull!="CAF" && index_hull!="CFI" && index_hull!="RMSEA"){ stop("index_hull argument has to be one of the availables indices (see documentation)") } if (display!=0 && display!=1){ stop("display argument has to be logical (TRUE or FALSE, 0 or 1)") } if (graph!=0 && graph!=1){ stop("graph argument has to be logical (TRUE or FALSE, 0 or 1)") } corr_char = 'Pearson correlation matrices' N<-dim(X)[1] p<-dim(X)[2] x<-as.matrix(X) SIGMA<-cor(X) if (missing(maxQ)){ realevals<-eigen(SIGMA)$values evals<-matrix(0,p,500) for (a in 1:500){ evals[,a]<- svd(cor(matrix(x[round(matrix(runif(N*p),N,p)*(N-1)+1)],N,p)))$d } means <- apply(evals,1,mean) for (root in 1:p){ if (realevals[root] < means[root]){ maxQ <- root - 1 break } } } else { if (is.numeric(maxQ)){ if (maxQ>p){ stop('The maxQ value has to be equal or lower than the number of variables') } maxQ = maxQ - 1 } else { stop("The maxQ argument has to be a numeric one, indicating the maximum number of factors to be retained.") } } q<-0 f_CAF <- 1-psych::KMO(SIGMA)$MSA f_CFI <- 0 f_NNFI <- 0 f_GFI <- 0 f_AGFI <- 0 t<-0 for (i in 1:(p-1)){ for (j in (i+1):p){ t <- t + SIGMA[i,j]^2 } } if (Re(t) > (-1)){ RMSEA <- fitchi_zero(SIGMA,N,t) f_RMSEA <- 1-Re(RMSEA) } else { r_CAF<-(-1) r_CFI<-(-1) r_RMSEA<-(-1) stop("Convergence was not possible, the analysis was stopped.") } g <- (1 / 2 * ((p - q) * (p - q + 1)) - p) again<-1 q<-1 while (again==1){ if (extr=='ML'){ out <- tryCatch( { out<-ml77(SIGMA,q,0.001) }, error=function(cond) { out<-NA cat(sprintf('The maximum number of factors available for extraction were %.0f \n\n',q-1)) return(out) } ) t<-out$t A<-out$A SIGMAREP <- A%*%t(A) if (Re(t) > 0){ SIGMA_ERROR <- SIGMA - SIGMAREP CAF <- 1 - psych::KMO(SIGMA_ERROR - diag(diag(SIGMA_ERROR)) + diag(p))$MSA f_CAF <- rbind(f_CAF,CAF) OUT<-fitchi(SIGMA,A,N,t) CFI<-OUT$CFI RMSEA <- 1 - Re(OUT$RMSEA) } else { r_CAF<-(-1) r_CFI<-(-1) r_RMSEA<-(-1) stop("Convergence was not possible, the analysis was stopped.") } } else { out_eigen<-eigen(SIGMA) VV<-out_eigen$vectors[,1:q] LL<-diag(out_eigen$values[1:q]) if (q==1){ VV<-transpose(VV) LL<-out_eigen$values[1] } A<-VV%*%sqrt(LL) A <-psych::fa(X, fm="minres",nfactors = q, rotate = "none", min.err = 0.000001)$loadings SIGMAREP <- A%*%t(A) RES <- SIGMA - SIGMAREP t<-0 for (i in 1:(p-1)){ for (j in (i+1):p){ t <- t + RES[i,j]^2 } } if (Re(t) > 0){ SIGMA_ERROR <- SIGMA - SIGMAREP CAF <- 1 - psych::KMO(SIGMA_ERROR - diag(diag(SIGMA_ERROR)) + diag(p))$MSA f_CAF <- rbind(f_CAF,CAF) OUT<-fitchi(SIGMA,A,N,t) CFI<-OUT$CFI RMSEA <- 1 - Re(OUT$RMSEA) } else { r_CAF<-(-1) r_CFI<-(-1) r_RMSEA<-(-1) stop("Convergence was not possible, the analysis was stopped.") } } f_CFI <- rbind(f_CFI, CFI) f_RMSEA <- rbind(f_RMSEA, RMSEA) g<- rbind(g,g <- (1 / 2 * ((p - q) * (p - q + 1)) - p)) q<-q+1 if ((q>maxQ+1)){ again<-0 } if (q>p){ again<-0 } } maxQ<-q-1 if (index_hull == "CAF"){ f_ <- f_CAF } if (index_hull == "CFI"){ f_ <- f_CFI } if (index_hull == "RMSEA"){ f_ <- f_RMSEA } out<-cbind(c(0:maxQ),f_,g) out_best<-out[1,] for (i in 2:(maxQ+1)){ if (i==2){ if (max(out_best[2]) < out[i,2]){ out_best <- rbind(out_best, out[i,]) } } else { if (max(out_best[,2]) < out[i,2]){ out_best <- rbind(out_best, out[i,]) } } } out_c <- out out <- out_best tmp4<-dim(out)[1] i<-2 while (i < tmp4-1){ f1 <- out[i-1,2] f2 <- out[i,2] f3 <- out[i+1,2] fp1 <- out[i-1,3] fp2 <- out[i,3] fp3 <- out[i+1,3] if (LineCon(f1,f2,f3,fp1,fp2,fp3)==FALSE){ out <- rbind(out[1:(i-1),],out[(i+1):tmp4,]) tmp4 <- dim(out)[1] i<-1 } i<-i+1 } tmp4<-dim(out)[1] st<-c(matrix(0,tmp4,1)) for (i in 2:(tmp4-1)){ fi <- out[i,2] fi_p <- out[i-1,2] fi_n <- out[i+1,2] pi <- out[i,3] pi_p <- out[i-1,3] pi_n <- out[i+1,3] st[i] <- ((fi - fi_p) / (pi - pi_p)) / ((fi_n - fi) / (pi_n - pi)) } out <- cbind(out,st) j<-which(out[,4]==max(out[,4])) if (index_hull == "CAF"){ r_CAF<-out[j,1] } if (index_hull == "CFI"){ r_CFI<-out[j,1] } if (index_hull == "RMSEA"){ r_RMSEA<-out[j,1] } r<-out[j,1] dif<-(dim(out_c)[1])-(dim(out)[1]) out_red <- matrix(0,dif,3) j<-2 h<-1 k2<-dim(out)[1] for (i in 2:maxQ){ if (j<=k2){ if (out_c[i,1]==out[j,1]){ j=j+1 } else { out_red[h,] <- out_c[i,] h<-h+1 } } else { if (out_c[i,1]==out[j-1,1]){ } else { out_red[h,] <- out_c[i,] h<-h+1 } } } if (dif>1 && (out_red[dif,1]==0)){ out_red[dif,] <- out_c[(dim(out_c)[1]),] } if (index_hull == "CAF"){ t_CAF_red <- out_red t_CAF<-out colnames(t_CAF)<-c('q','f','g','st') rownames(t_CAF)<-NULL colnames(t_CAF_red)<-c('q','f','g') rownames(t_CAF_red)<-NULL OUT<-list('Matrix'=t_CAF,'n_factors'=r_CAF) } if (index_hull == "CFI"){ t_CFI_red <- out_red t_CFI<-out colnames(t_CFI)<-c('q','f','g','st') rownames(t_CFI)<-NULL colnames(t_CFI_red)<-c('q','f','g') rownames(t_CFI_red)<-NULL OUT<-list('Matrix'=t_CFI,'n_factors'=r_CFI) } if (index_hull == "RMSEA"){ t_RMSEA_red <- out_red t_RMSEA<-out colnames(t_RMSEA)<-c('q','f','g','st') rownames(t_RMSEA)<-NULL colnames(t_RMSEA_red)<-c('q','f','g') rownames(t_RMSEA_red)<-NULL OUT<-list('Matrix'=t_RMSEA,'n_factors'=r_RMSEA) } if (display==T){ if (index_hull=="CAF"){ cat('HULL METHOD - CAF INDEX\n') cat('\n') cat(' q f g st\n') if (details==FALSE){ f1<-dim(t_CAF)[1] for (i in 1:f1){ cat(sprintf(' %2.0f %.4f %4.0f %6.4f \n',t_CAF[i,1],t_CAF[i,2],t_CAF[i,3],t_CAF[i,4])) } } else { f1<-dim(out_c)[1] g1<-dim(t_CAF)[1] j <- 1 h <- 0 for (i in 1:f1){ if ((i-h)<=g1){ if (t_CAF[i-h,1] == (i-j+h)){ cat(sprintf(' %2.0f %.4f %4.0f %6.4f \n',t_CAF[i-h,1],t_CAF[i-h,2],t_CAF[i-h,3],t_CAF[i-h,4])) } else { cat(sprintf(' %2.0f* %.4f %4.0f \n',t_CAF_red[j,1],t_CAF_red[j,2],t_CAF_red[j,3])) j <- j+1 h <- h+1 } } else { cat(sprintf(' %2.0f* %.4f %4.0f \n',t_CAF_red[j,1],t_CAF_red[j,2],t_CAF_red[j,3])) j <- j+1 h <- h+1 } } } cat('\n') cat(sprintf('Number of advised dimensions: %.0f \n',r_CAF)) if (details==TRUE){ if (g1!=f1){ cat(sprintf('* Value outside the convex Hull \n')) } } cat('\n') cat('-----------------------------------------------\n') cat('\n') } if (index_hull == "CFI"){ cat('HULL METHOD - CFI INDEX\n') cat('\n') cat(' q f g st\n') if (details==FALSE){ f1<-dim(t_CFI)[1] for (i in 1:f1){ cat(sprintf(' %2.0f %.4f %4.0f %6.4f \n',t_CFI[i,1],t_CFI[i,2],t_CFI[i,3],t_CFI[i,4])) } } else { f1<-dim(out_c)[1] g1<-dim(t_CFI)[1] j <- 1 h <- 0 for (i in 1:f1){ if ((i-h)<=g1){ if (t_CFI[i-h,1] == (i-j+h)){ cat(sprintf(' %2.0f %.4f %4.0f %6.4f \n',t_CFI[i-h,1],t_CFI[i-h,2],t_CFI[i-h,3],t_CFI[i-h,4])) } else { cat(sprintf(' %2.0f* %.4f %4.0f \n',t_CAF_red[j,1],t_CAF_red[j,2],t_CAF_red[j,3])) j <- j+1 h <- h+1 } } else { cat(sprintf(' %2.0f* %.4f %4.0f \n',t_CFI_red[j,1],t_CFI_red[j,2],t_CFI_red[j,3])) j <- j+1 h <- h+1 } } } cat('\n') cat(sprintf('Number of advised dimensions: %.0f \n',r_CFI)) if (details==TRUE){ if (g1!=f1){ cat(sprintf('* Value outside the convex Hull \n')) } } cat('\n') cat('-----------------------------------------------\n') cat('\n') } if (index_hull == "RMSEA"){ cat('HULL METHOD - RMSEA INDEX\n') cat('\n') cat(' q f g st\n') if (details==FALSE){ f1<-dim(t_RMSEA)[1] for (i in 1:f1){ cat(sprintf(' %2.0f %.4f %4.0f %6.4f \n',t_RMSEA[i,1],t_RMSEA[i,2],t_RMSEA[i,3],t_RMSEA[i,4])) } } else { f1<-dim(out_c)[1] g1<-dim(t_RMSEA)[1] j <- 1 h <- 0 for (i in 1:f1){ if ((i-h)<=g1){ if (t_RMSEA[i-h,1] == (i-j+h)){ cat(sprintf(' %2.0f %.4f %4.0f %6.4f \n',t_RMSEA[i-h,1],t_RMSEA[i-h,2],t_RMSEA[i-h,3],t_RMSEA[i-h,4])) } else { cat(sprintf(' %2.0f* %.4f %4.0f \n',t_RMSEA_red[j,1],t_RMSEA_red[j,2],t_RMSEA_red[j,3])) j <- j+1 h <- h+1 } } else { cat(sprintf(' %2.0f* %.4f %4.0f \n',t_RMSEA_red[j,1],t_RMSEA_red[j,2],t_RMSEA_red[j,3])) j <- j+1 h <- h+1 } } } cat('\n') cat(sprintf('Number of advised dimensions: %.0f \n',r_RMSEA)) if (details==TRUE){ if (g1!=f1){ cat(sprintf('* Value outside the convex Hull \n')) } } cat('\n') cat('-----------------------------------------------\n') cat('\n') } invisible(OUT) } if (graph==T){ title<-sprintf('Hull Method: %s Index',index_hull) f1<-dim(out_c)[1] g1<-dim(out)[1] out_c<-as.data.frame(out_c) buff<-character(length = f1) buff[]<-"f1" out_c2<-cbind(out_c,buff) colnames(out_c)<-c('Factors','f','g') out<-as.data.frame(out) buff<-character(length = g1) buff[]<-"g1" out2<-cbind(out[,1:3],buff) colnames(out)<-c('Factors','f','g','st') out_final<-rbind(out_c2,out2) colnames(out_final)<-c('Factors','f','g','buff') Factors=f=NULL p<-ggplot2::ggplot(data=out_final, ggplot2::aes(x=Factors, y=f, colour=buff)) + ggplot2::geom_line(data=out) + ggplot2::geom_point() + ggplot2::ggtitle(title) + ggplot2::geom_vline(xintercept = r, linetype="dashed") + ggplot2::scale_x_continuous(breaks=scales::pretty_breaks(n=f1)) + ggplot2::theme(legend.position="none") print(p) } if (display==F){ invisible(OUT) } }
data(dataADaMCDISCP01) labelVars <- attr(dataADaMCDISCP01, "labelVars") dataAE <- dataADaMCDISCP01$ADAE subjectsSafety <- subset(dataADaMCDISCP01$ADSL, SAFFL == "Y")$USUBJID tableAE <- stats::aggregate( formula = USUBJID ~ AESOC:AEDECOD, data = dataAE, FUN = function(usubjid) length(unique(usubjid)) ) colnames(tableAE)[colnames(tableAE) == "USUBJID"] <- "N" tableAE$perc <- round(tableAE$N/length(subjectsSafety)*100, 3) tableAE <- tableAE[order(tableAE$perc, decreasing = TRUE), ] tableAELabels <- getLabelVar( var = colnames(tableAE), labelVars = labelVars, label = c(N = ' ) tableAELabelsDT <- setNames(names(tableAELabels), tableAELabels) getClinDT( data = tableAE, barVar = "perc", colnames = tableAELabelsDT ) getClinDT( data = tableAE, filter = "none", barVar = "perc", barRange = c(0, 100), colnames = tableAELabelsDT ) getClinDT( data = tableAE, filter = "none", barVar = "perc", barColorThr = seq(from = 0, to = 100, by = 25), colnames = tableAELabelsDT ) tableAESOC <- aggregate(formula = N ~ AESOC, data = tableAE, FUN = sum) tableAE$AESOC <- factor(tableAE$AESOC, levels = tableAESOC[order(tableAESOC$N, decreasing = FALSE), "AESOC"] ) tableAE <- tableAE[order(tableAE$AESOC, tableAE$perc, decreasing = TRUE), ] getClinDT( data = tableAE, filter = "none", barVar = "perc", barRange = c(0, 100), colnames = tableAELabelsDT, rowGroupVar = "AESOC", pageLength = Inf ) getClinDT( data = tableAE, barVar = "perc", colnames = tableAELabelsDT, expandVar = "USUBJID", escape = grep("USUBJID", colnames(tableAE))-1 ) getClinDT( data = tableAE, colnames = tableAELabelsDT, fixedColumns = list(leftColumns = 1), columnsWidth = c(0.1, 0.7, 0.1, 0.1), width = "350px" ) getClinDT( data = tableAE, colnames = tableAELabelsDT, filter = "none", buttons = getClinDTButtons(type = c("csv", "excel", "pdf")) ) getClinDT( data = tableAE, colnames = tableAELabelsDT, buttons = getClinDTButtons(typeExtra = "colvis") ) buttons <- getClinDTButtons( opts = list(pdf = list(orientation = "landscape")) ) getClinDT( data = tableAE, colnames = tableAELabelsDT, buttons = buttons ) getClinDT( data = tableAE, nonVisibleVar = "AESOC" ) library(htmltools) caption <- tags$caption( "Number of subjects with adverse events grouped by system organ class.", br(), paste( "Percentages are based on the total number of patients having", "received a first study treatment." ) ) getClinDT( data = tableAE, filter = "none", barVar = "perc", barRange = c(0, 100), pageLength = Inf, colnames = tableAELabelsDT, rowGroupVar = "AESOC", caption = caption )
context("Basic function") test_that("graticule creation is successful", { expect_that(graticule(seq(100, 240, by = 15), seq(-85, -30, by = 15)), is_a("SpatialLinesDataFrame")) expect_that(graticule(seq(100, 240, by = 15), seq(-85, -30, by = 15), nverts = 20), is_a("SpatialLinesDataFrame")) expect_that(graticule(seq(100, 240, by = 15), seq(-85, -30, by = 15), nverts = 100, xlim = c(-180, 180), ylim = c(-60, -30)), is_a("SpatialLinesDataFrame")) }) test_that("labels work", { expect_that(graticule_labels(seq(100, 240, by = 15), seq(-85, -30, by = 15)), is_a("SpatialPointsDataFrame")) })
isNegativeNumberOrNaOrNanOrInfScalarOrNull <- function(argument, default = NULL, stopIfNot = FALSE, message = NULL, argumentName = NULL) { checkarg(argument, "N", default = default, stopIfNot = stopIfNot, nullAllowed = TRUE, n = 1, zeroAllowed = TRUE, negativeAllowed = TRUE, positiveAllowed = FALSE, nonIntegerAllowed = TRUE, naAllowed = TRUE, nanAllowed = TRUE, infAllowed = TRUE, message = message, argumentName = argumentName) }
M13p <- function(RR, alpha=c(0.333,0.333, 0.333),r=0.1) { x.m <- RR[1:3] x.f <- RR[4:6] AA <- expand.grid(seq(r/2,1-r/2,by=r), seq(r/2,1-r/2,by=r)) paa.m <- AA[,1] pab.m <- AA[,2] pp <- cbind(paa.m,pab.m) matriu <- pp[paa.m < 1 -r/2 -pab.m, ] ddir <- function (x, alpha, log = T) { x <- as.vector(x) alpha <- as.vector(alpha) if (!identical(length(x), length(alpha))) stop("x and alpha differ in length.") dens <- lgamma(sum(alpha)) + sum((alpha-1)*log(x)) - sum(lgamma(alpha)) if (log == FALSE) dens <- exp(dens) return(dens) } ff3 <- apply(matriu, 1, function(el){ pAA.m <- el[1] pAB.m <- el[2] pBB.m <- 1-pAA.m-pAB.m pAA.f <- ((2*pAA.m+pAB.m)/2)^2 pAB.f <- 2*((2*pAA.m+pAB.m)/2)*(1-(2*pAA.m+pAB.m)/2) pBB.f <- 1-pAA.f - pAB.f aux3 <- dmultinom(x.f, size=sum(x.f), prob=c(pAA.f,pAB.f,pBB.f),log=T) + dmultinom(x.m, size=sum(x.m), prob=c(pAA.m,pAB.m,pBB.m),log=T) + ddir(x=c(pAA.m,pAB.m,pBB.m),alpha,log=T) return(exp(aux3)) }) dens <- sum(ff3)*r*r return(dens) }
sliceSampler_N <- function(c, m, alpha, z, hyperG0, U_mu, U_Sigma, diagVar){ maxCl <- length(m) ind <- which(m!=0) w <- numeric(maxCl) temp <- stats::rgamma(n=(length(ind)+1), shape=c(m[ind], alpha), scale = 1) temp_norm <- temp/sum(temp) w[ind] <- temp_norm[-length(temp_norm)] R <- temp_norm[length(temp_norm)] u <- stats::runif(length(c))*w[c] u_star <- min(u) ind_new <- which(m==0) if(length(ind_new)>0){ t <- 0 while(R>u_star && (t<length(ind_new))){ t <- t+1 beta_temp <- stats::rbeta(n=1, shape1=1, shape2=alpha) w[ind_new[t]] <- R*beta_temp R <- R * (1-beta_temp) } ind_new <- ind_new[1:t] for (i in 1:t){ NiW <- rNiW(hyperG0, diagVar) U_mu[, ind_new[i]] <- NiW[["mu"]] U_Sigma[, , ind_new[i]] <- NiW[["S"]] } } fullCl_ind <- which(w != 0) if(length(fullCl_ind)>1){ U_mu_full <- sapply(fullCl_ind, function(j) U_mu[, j]) U_Sigma_list <- lapply(fullCl_ind, function(j) U_Sigma[, ,j]) l <- mmvnpdfC(z, mean=U_mu_full, varcovM=U_Sigma_list, Log = TRUE) u_mat <- t(sapply(w[fullCl_ind], function(x){as.numeric(u < x)})) prob_mat_log <- log(u_mat) + l c <- fullCl_ind[sampleClassC(probMat = prob_mat_log, Log = TRUE)] }else{ c <- rep(fullCl_ind, maxCl) } m_new <- numeric(maxCl) m_new[unique(c)] <- table(c)[as.character(unique(c))] return(list("c"=c, "m"=m_new, "weights"=w,"U_mu"=U_mu,"U_Sigma"=U_Sigma)) }
calcENT <- function(rawmat) { lnrawmat<-log(rawmat) size<-dim(lnrawmat)[1] for(i in 1:size) { for(a in 1:size) { if(lnrawmat[a,i]=="-Inf") { lnrawmat[a,i]<-0 } } } return(sum(rawmat*lnrawmat)) }
plot.sparsenet=function(x, xvar=c("rsq","lambda","norm"),which.gamma=NULL,label=FALSE,...){ oldpar=par(mar=c(4,4,4,1)) on.exit(par(oldpar)) xvar=match.arg(xvar) switch(xvar, rsq={iname="Fraction Training Variance Explained";xvar="dev"}, lambda={iname=expression(log (lambda))}, norm={iname="L1 Norm"} ) lamax=x$max.lambda coeflist=x$coefficients ngamma=length(coeflist) if(is.null(which.gamma))which.gamma=1:ngamma coeflistseq=seq(along=coeflist) which.gamma=coeflistseq[match(which.gamma,coeflistseq,0)] rsq=x$rsq ylims=range(sapply(coeflist[which.gamma],function(x)range(x$beta))) for(i in which.gamma){ x=coeflist[[i]] beta=x$beta p=nrow(beta) beta=cbind2(rep(0,p),beta) plotCoef(beta,lambda=c(lamax,x$lambda),df=c(0,x$df),dev=c(0,rsq[i,]),label=label,xvar=xvar,xlab=iname,ylim=ylims,...) if(x$gamma> 1000)mlab="Lasso" else if (x$gamma<1.001)mlab="Subset" else mlab=paste("Gamma =",format(round(x$gamma,1))) mtext(mlab,3,2) } invisible() }
adrop3d.last <- function(x, d, keepColNames = FALSE) { if (!is.array(x)) { x } else { if (d > 1) { x[,,1:d, drop = FALSE] } else { if (dim(x)[1] == 1) { rbind(x[,,1, drop = TRUE]) } else { if (dim(x)[2] == 1) { if (keepColNames) { xnew <- cbind(x[,,1, drop = TRUE]) colnames(xnew) <- colnames(x) xnew } else { cbind(x[,,1, drop = TRUE]) } } else { x[,,1, drop = TRUE] } } } } } adrop2d.first <- function(x, d, keepColNames = FALSE) { if (!is.array(x)) { x } else { if (d > 1) { x[1:d,, drop = FALSE] } else { x[1, , drop = TRUE] } } } adrop2d.last <- function(x, d, keepColNames = FALSE) { if (!is.array(x)) { x } else { if (d > 1) { x[,1:d, drop = FALSE] } else { x[,1, drop = TRUE] } } } amatrix <- function(x, d, names) { x <- matrix(x, d, dimnames = names) if (ncol(x) > 1) { x } else { c(x) } } amatrix.remove.names <- function(x) { if (!is.null(dim(x)) && ncol(x) == 1) { unlist(c(x), use.names = FALSE) } else { x } } atmatrix <- function(x, d, names, keep.names = FALSE) { x <- t(matrix(x, ncol = d, dimnames = names)) if (ncol(x) > 1) { x } else { if (keep.names == FALSE) { c(x) } else { x.names <- rownames(x) x <- c(x) names(x) <- x.names x } } } avector <- function(x, name = FALSE) { if (!is.null(dim(x)) && nrow(x) > 1 && ncol(x) == 1) { x.names <- rownames(x) x <- unlist(c(x)) if (name) names(x) <- x.names else names(x) <- NULL x } else if (!is.null(dim(x)) && nrow(x) == 1 && ncol(x) > 1) { x.names <- colnames(x) x <- unlist(c(x)) if (name) names(x) <- x.names else names(x) <- NULL x } else if (!is.null(dim(x)) && nrow(x) == 1 && ncol(x) == 1) { unlist(c(x)) } else { x } } available <- function (package, lib.loc = NULL, quietly = TRUE) { package <- as.character(substitute(package)) installed <- find.package(package, quiet = TRUE) if (length(installed) > 0) { require(package, quietly = TRUE, character.only = TRUE) } else { return(invisible(FALSE)) } } cv.folds <- function (n, folds = 10) { split(resample(1:n), rep(1:folds, length = n)) } data.matrix <- function(x) { as.data.frame(lapply(x, function(xi) { if (is.integer(xi) || is.numeric(xi)) { xi } else if (is.logical(xi) || is.factor(xi)) { as.integer(xi) } else { as.numeric(xi) } })) } family.pretty <- function(x) { fmly <- x$family if (!is.null(x$forest$rfq) && x$forest$rfq) { fmly <- "rfq" } switch(fmly, "surv" = "RSF", "surv-CR" = "RSF", "regr" = "RF-R", "class" = "RF-C", "unsupv" = "RF-U", "regr+" = "mRF-R", "class+" = "mRF-C", "mix+" = "mRF-RC", "rfq" = "RFQ" ) } finalizeFormula <- function(formula.obj, data) { yvar.names <- formula.obj$yvar.names all.names <- formula.obj$all.names index <- length(yvar.names) fmly <- formula.obj$family ytry <- formula.obj$ytry if (length(all.names) <= index) { stop("formula is misspecified: total number of variables does not exceed total number of y-variables") } if (all.names[index + 1] == ".") { if(index == 0) { xvar.names <- names(data) } else { xvar.names <- names(data)[!is.element(names(data), all.names[1:index])] } } else { if(index == 0) { xvar.names <- all.names } else { xvar.names <- all.names[-c(1:index)] } not.specified <- !is.element(xvar.names, names(data)) if (sum(not.specified) > 0) { stop("formula is misspecified, object ", xvar.names[not.specified], " not found") } } return (list(family=fmly, yvar.names=yvar.names, xvar.names=xvar.names, ytry=ytry)) } finalizeData <- function(fnames, data, na.action, miss.flag = TRUE) { data <- data[ , is.element(names(data), fnames), drop = FALSE] factor.names <- unlist(lapply(data, is.factor)) if (sum(factor.names) > 0) { data[, factor.names] <- data.matrix(data[, factor.names, drop = FALSE]) } if (miss.flag == TRUE && na.action == "na.omit") { if (any(is.na(data))) { data <- na.omit(data) } } if (miss.flag == TRUE && na.action != "na.omit") { nan.names <- sapply(data, function(x){any(is.nan(x))}) if (sum(nan.names) > 0) { data[, nan.names] <- data.frame(lapply(which(nan.names), function(j) { x <- data[, j] x[is.nan(x)] <- NA x })) } } if (nrow(data) == 0) { stop("no records in the NA-processed data: consider using 'na.action=na.impute'") } logical.names <- unlist(lapply(data, is.logical)) if (sum(logical.names) > 0) { data[, logical.names] <- 1 * data[, logical.names, drop = FALSE] } character.names <- unlist(lapply(data, is.character)) if (sum(character.names) > 0) { stop("data types cannot be character: please convert all characters to factors") } return (data) } get.auc.workhorse <- function(roc.data) { x <- roc.data[, 1][roc.data[, 2] == 1] y <- roc.data[, 1][roc.data[, 2] == 0] if (length(x) > 1 & length(y) > 1) { AUC <- tryCatch({wilcox.test(x, y, exact=F)$stat/(length(x)*length(y))}, error=function(ex){NA}) } else { AUC <- NA } AUC } get.auc <- function(y, prob) { if (is.factor(y)) { y.uniq <- levels(y) } else { y.uniq <- sort(unique(y)) } nclass <- length(y.uniq) AUC <- NULL for (i in 1:(nclass - 1)) { for (j in (i + 1):nclass) { pt.ij <- (y == y.uniq[i] | y == y.uniq[j]) if (sum(pt.ij) > 1) { y.ij <- y[pt.ij] pij <- prob[pt.ij, j] pji <- prob[pt.ij, i] Aij <- get.auc.workhorse(cbind(pij, 1 * (y.ij == y.uniq[j]))) Aji <- get.auc.workhorse(cbind(pji, 1 * (y.ij == y.uniq[i]))) AUC <- c(AUC, (Aij + Aji)/2) } } } if (is.null(AUC)) { NA } else { mean(AUC, na.rm = TRUE) } } get.bayes.rule <- function(prob, pi.hat = NULL) { class.labels <- colnames(prob) if (is.null(pi.hat)) { factor(class.labels[apply(prob, 1, function(x) { if (!all(is.na(x))) { resample(which(x == max(x, na.rm = TRUE)), 1) } else { NA } })], levels = class.labels) } else { minority <- which.min(pi.hat) majority <- setdiff(1:2, minority) rfq.rule <- rep(majority, nrow(prob)) rfq.rule[prob[, minority] >= min(pi.hat, na.rm = TRUE)] <- minority factor(class.labels[rfq.rule], levels = class.labels) } } get.brier.error <- function(y, prob) { if (is.null(colnames(prob))) { colnames(prob) <- levels(y) } cl <- colnames(prob) J <- length(cl) bs <- rep(NA, J) nullO <- sapply(1:J, function(j) { bs[j] <<- mean((1 * (y == cl[j]) - prob[, j]) ^ 2, na.rm = TRUE) NULL }) norm.const <- (J / (J - 1)) sum(bs * norm.const, na.rm = TRUE) } get.misclass.error <- function(y, yhat) { cl <- sort(unique(y)) err <- rep(NA, length(cl)) for (k in 1:length(cl)) { cl.pt <- (y == cl[k]) if (sum(cl.pt) > 0) { err[k] <- mean(y[cl.pt] != yhat[cl.pt]) } } err } get.confusion <- function(y, class.or.prob) { if (is.factor(class.or.prob)) { confusion <- table(y, class.or.prob) } else { if (is.null(colnames(class.or.prob))) { colnames(class.or.prob) <- levels(y) } confusion <- table(y, get.bayes.rule(class.or.prob)) } class.error <- 1 - diag(confusion) / rowSums(confusion, na.rm = TRUE) cbind(confusion, class.error = round(class.error, 4)) } get.cindex <- function (time, censoring, predicted, do.trace = FALSE) { size <- length(time) if (size != length(time) | size != length(censoring) | size != length(predicted)) { stop("time, censoring, and predicted must have the same length") } miss <- is.na(time) | is.na(censoring) | is.na(predicted) nmiss <- sum(miss) if (nmiss == size) { stop("no valid pairs found, too much missing data") } denom <- sapply(miss, function(x) if (x) 0 else 1) nativeOutput <- .Call("rfsrcCIndex", as.integer(do.trace), as.integer(size), as.double(time), as.double(censoring), as.double(predicted), as.integer(denom)) if (is.null(nativeOutput)) { stop("An error has occurred in rfsrcCIndex. Please turn trace on for further analysis.") } return (nativeOutput$err) } get.coerced.survival.fmly <- function(fmly, event.type, splitrule = NULL) { if (grepl("surv", fmly)) { coerced.fmly <- "surv" if (!is.null(splitrule)) { if ((length(event.type) > 1) && (splitrule != "l2.impute") && (splitrule != "logrankscore")) { coerced.fmly <- "surv-CR" } } else { if (length(event.type) > 1) { coerced.fmly <- "surv-CR" } } } else { stop("attempt to coerce a non-survival family") } coerced.fmly } get.event.info <- function(obj, subset = NULL) { if (grepl("surv", obj$family)) { if (!is.null(obj$yvar)) { if (is.null(subset)) { subset <- (1:nrow(cbind(obj$yvar))) } r.dim <- 2 time <- obj$yvar[subset, 1] cens <- obj$yvar[subset, 2] if (!all(floor(cens) == abs(cens), na.rm = TRUE)) { stop("for survival families censoring variable must be coded as a non-negative integer") } event <- na.omit(cens)[na.omit(cens) > 0] event.type <- sort(unique(event)) } else { r.dim <- 0 event <- event.type <- cens <- cens <- time <- NULL } time.interest <- obj$time.interest } else { if ((obj$family == "regr+") | (obj$family == "class+")) { r.dim <- dim(obj$yvar)[2] } else { r.dim <- 1 } event <- event.type <- cens <- time.interest <- cens <- time <- NULL } return(list(event = event, event.type = event.type, cens = cens, time.interest = time.interest, time = time, r.dim = r.dim)) } get.gmean <- function(y, prob, rfq = FALSE, robust = FALSE) { frq <- table(y) if (length(frq) > 2) { return(NULL) } if (rfq) { threshold <- min(frq, na.rm = TRUE) / sum(frq, na.rm = TRUE) } else { threshold <- 0.5 } minority <- which.min(frq) majority <- setdiff(1:2, minority) yhat <- factor(1 * (prob[, minority] >= threshold), levels = c(0,1)) confusion.matrix <- table(y, yhat) if (nrow(confusion.matrix) > 1) { TN <- confusion.matrix[minority, 2] FP <- confusion.matrix[minority, 1] FN <- confusion.matrix[majority, 2] TP <- confusion.matrix[majority, 1] if (robust) { sensitivity <- (1 + TP) / (1 + TP + FN) specificity <- (1 + TN) / (1 + TN + FP) } else { sensitivity <- TP / (TP + FN) specificity <- TN / (TN + FP) } sqrt(sensitivity * specificity) } else { NA } } get.grow.event.info <- function(yvar, fmly, need.deaths = TRUE, ntime) { if (grepl("surv", fmly)) { r.dim <- 2 time <- yvar[, 1] cens <- yvar[, 2] if (!all(floor(cens) == abs(cens), na.rm = TRUE)) { stop("for survival families censoring variable must be coded as a non-negative integer (perhaps the formula is set incorrectly?)") } if (need.deaths && (all(na.omit(cens) == 0))) { stop("no deaths in data!") } event.type <- unique(na.omit(cens)) if (sum(event.type >= 0) != length(event.type)) { stop("censoring variable must be coded as NA, 0, or greater than 0.") } event <- na.omit(cens)[na.omit(cens) > 0] event.type <- unique(event) nonMissingOutcome <- which(!is.na(cens) & !is.na(time)) nonMissingDeathFlag <- (cens[nonMissingOutcome] != 0) time.interest <- sort(unique(time[nonMissingOutcome[nonMissingDeathFlag]])) if (!missing(ntime)) { if (length(ntime) == 1 && length(time.interest) > ntime) { time.interest <- time.interest[ unique(round(seq.int(1, length(time.interest), length.out = ntime)))] } if (length(ntime) > 1) { time.interest <- unique(sapply(ntime, function(tt) { time.interest[max(1, sum(tt >= time.interest, na.rm = TRUE))] })) } } } else { if ((fmly == "regr+") | (fmly == "class+") | (fmly == "mix+")) { r.dim <- dim(yvar)[2] } else { if (fmly == "unsupv") { r.dim <- 0 } else { r.dim <- 1 } } event <- event.type <- cens <- time.interest <- cens <- time <- NULL } return(list(event = event, event.type = event.type, cens = cens, time.interest = time.interest, time = time, r.dim = r.dim)) } get.grow.mtry <- function (mtry = NULL, n.xvar, fmly) { if (!is.null(mtry)) { mtry <- round(mtry) if (mtry < 1 | mtry > n.xvar) mtry <- max(1, min(mtry, n.xvar)) } else { if (grepl("regr", fmly)) { mtry <- max(ceiling(n.xvar/3), 1) } else { mtry <- max(ceiling(sqrt(n.xvar)), 1) } } return (mtry) } get.grow.nodesize <- function(fmly, nodesize) { if (fmly == "surv"){ if (is.null(nodesize)) { nodesize <- 15 } } else if (fmly == "surv-CR"){ if (is.null(nodesize)) { nodesize <- 15 } } else if (fmly == "class" | fmly == "class+") { if (is.null(nodesize)) { nodesize <- 1 } } else if (fmly == "regr" | fmly == "regr+") { if (is.null(nodesize)) { nodesize <- 5 } } else if (fmly == "mix+") { if (is.null(nodesize)) { nodesize <- 3 } } else if (fmly == "unsupv") { if (is.null(nodesize)) { nodesize <- 3 } } else if (is.null(nodesize)) { stop("family is misspecified") } nodesize <- round(nodesize) } get.grow.splitinfo <- function (formula.detail, splitrule, hdim, nsplit, event.type) { splitrule.names <- c("logrank", "logrankscore", "logrankCR", "random", "mse", "gini", "unsupv", "mv.mse", "mv.gini", "mv.mix", "custom", "quantile.regr", "la.quantile.regr", "bs.gradient", "auc", "entropy", "sg.regr", "sg.class", "sg.surv") fmly <- formula.detail$family if (hdim > 0) { if(!is.null(nsplit)) { nsplit <- round(nsplit) if (nsplit < 0) { stop("Invalid nsplit value. Set nsplit >= 0.") } } else { nsplit = 1 } } else { if(!is.null(nsplit)) { nsplit <- round(nsplit) if (nsplit < 0) { stop("Invalid nsplit value. Set nsplit >= 0.") } } else { nsplit = 0 } } cust.idx <- NULL splitpass <- FALSE if (!is.null(splitrule)) { if(grepl("custom", splitrule)) { splitrule.idx <- which(splitrule.names == "custom") cust.idx <- as.integer(sub("custom", "", splitrule)) if (is.na(cust.idx)) cust.idx <- 1 splitpass <- TRUE } else if (splitrule == "random") { splitrule.idx <- which(splitrule.names == "random") nsplit <- 1 splitpass <- TRUE } } if (!splitpass) { if (grepl("surv", fmly)) { if (is.null(splitrule)) { if (length(event.type) == 1) { splitrule.idx <- which(splitrule.names == "logrank") } else { splitrule.idx <- which(splitrule.names == "logrankCR") } splitrule <- splitrule.names[splitrule.idx] } else { splitrule.idx <- which(splitrule.names == splitrule) if (length(splitrule.idx) != 1) { stop("Invalid split rule specified: ", splitrule) } if ((length(event.type) == 1) & (splitrule.idx == which(splitrule.names == "logrankCR"))) { stop("Cannot specify logrankCR splitting for right-censored data") } if ((length(event.type) > 1) & (splitrule.idx == which(splitrule.names == "logrank"))) { splitrule.idx <- which(splitrule.names == "logrankCR") } } } if (fmly == "class") { if (is.null(splitrule)) { splitrule.idx <- which(splitrule.names == "gini") splitrule <- splitrule.names[splitrule.idx] } else { if ((splitrule != "rps") & (splitrule != "auc") & (splitrule != "entropy") & (splitrule != "gini") & (splitrule != "sg.class")) { stop("Invalid split rule specified: ", splitrule) } splitrule.idx <- which(splitrule.names == splitrule) } } if (fmly == "regr") { if (is.null(splitrule)) { splitrule.idx <- which(splitrule.names == "mse") splitrule <- splitrule.names[splitrule.idx] } else { if ((splitrule != "mse") & (splitrule != "sg.regr") & (splitrule != "la.quantile.regr") & (splitrule != "quantile.regr")) { stop("Invalid split rule specified: ", splitrule) } splitrule.idx <- which(splitrule.names == splitrule) } } if (fmly == "regr+") { if (is.null(splitrule)) { splitrule.idx <- which(splitrule.names == "mv.mse") splitrule <- splitrule.names[splitrule.idx] } else { if ((splitrule != "mv.mse")) { stop("Invalid split rule specified: ", splitrule) } splitrule.idx <- which(splitrule.names == splitrule) } } if (fmly == "class+") { if (is.null(splitrule)) { splitrule.idx <- which(splitrule.names == "mv.gini") splitrule <- splitrule.names[splitrule.idx] } else { if ((splitrule != "mv.gini")) { stop("Invalid split rule specified: ", splitrule) } splitrule.idx <- which(splitrule.names == splitrule) } } if (fmly == "mix+") { if (is.null(splitrule)) { splitrule.idx <- which(splitrule.names == "mv.mse") splitrule <- "mv.mix" } else { if ((splitrule != "mv.mix")) { stop("Invalid split rule specified: ", splitrule) } splitrule.idx <- which(splitrule.names == splitrule) } } if (fmly == "unsupv") { if (is.null(splitrule)) { splitrule.idx <- which(splitrule.names == "unsupv") splitrule <- splitrule.names[splitrule.idx] } else { if ((splitrule != "unsupv")) { stop("Invalid split rule specified: ", splitrule) } splitrule.idx <- which(splitrule.names == splitrule) } } } splitinfo <- list(name = splitrule, index = splitrule.idx, cust = cust.idx, nsplit = nsplit) return (splitinfo) } get.importance.xvar <- function(importance.xvar, importance, object) { if (!is.null(importance)) { if (missing(importance.xvar) || is.null(importance.xvar)) { importance.xvar <- object$xvar.names } else { importance.xvar <- unique(importance.xvar) importance.xvar <- intersect(importance.xvar, object$xvar.names) } if (length(importance.xvar) == 0) { stop("xvar names do not match object xvar matrix") } } else { importance.xvar <- NULL } return (importance.xvar) } get.mv.error <- function(obj, standardize = FALSE, pretty = TRUE, block = FALSE) { nms <- NULL ynms <- obj$yvar.names if (obj$family == "surv" || obj$family == "surv-CR") { ynms <- ynms[1] } if (block) { pretty <- FALSE } err <- lapply(ynms, function(nn) { o.coerce <- coerce.multivariate(obj, nn) if (!block) { er <- o.coerce$err.rate } else { er <- o.coerce$err.block.rate } if (!is.null(er)) { if (o.coerce$family != "regr" || !standardize) { if (pretty && o.coerce$family == "class") { er <- utils::tail(cbind(er)[, 1], 1) } else { if (!block) { er <- utils::tail(er, 1) rownames(er) <- NULL } } } else { if (!block) { er <- utils::tail(er, 1) / var(o.coerce$yvar, na.rm = TRUE) } else { er <- er / var(o.coerce$yvar, na.rm = TRUE) } } } if (is.null(dim(er))) { nms <<- c(nms, paste(nn)) } else { nms <<- c(nms, colnames(er)) } er }) if (is.null(err[[1]])) { err <- NULL } if (!is.null(err)) { if (pretty) { err <- unlist(err) names(err) <- nms } else { names(err) <- ynms } } err } get.mv.error.block <- function(obj, standardize = FALSE) { get.mv.error(obj, standardize = standardize, block = TRUE) } get.mv.formula <- function(ynames) { as.formula(paste("Multivar(", paste(ynames, collapse = ","),paste(") ~ ."), sep = "")) } get.mv.predicted <- function(obj, oob = TRUE) { nms <- NULL ynms <- obj$yvar.names if (obj$family == "surv" || obj$family == "surv-CR") { ynms <- ynms[1] } pred <- do.call(cbind, lapply(ynms, function(nn) { o.coerce <- coerce.multivariate(obj, nn) if (o.coerce$family == "class" || o.coerce$family == "surv-CR") { if (!is.null(o.coerce$predicted.oob)) { nms <<- c(nms, paste(nn, ".", colnames(o.coerce$predicted.oob), sep = "")) } else { nms <<- c(nms, paste(nn, ".", colnames(o.coerce$predicted), sep = "")) } } else { nms <<- c(nms, paste(nn)) } if (oob && !is.null(o.coerce$predicted.oob)) { o.coerce$predicted.oob } else { o.coerce$predicted } })) colnames(pred) <- nms pred } get.mv.vimp <- function(obj, standardize = FALSE, pretty = TRUE) { ynms <- obj$yvar.names if (obj$family == "surv" || obj$family == "surv-CR") { ynms <- ynms[1] } vmp <- lapply(ynms, function(nn) { o.coerce <- coerce.multivariate(obj, nn) v <- o.coerce$importance if (!is.null(v)) { if (o.coerce$family != "regr" || !standardize) { if (pretty && o.coerce$family == "class") { v <- v[, 1] } } else { v <- v / var(o.coerce$yvar, na.rm = TRUE) } if (is.null(dim(v))) { v <- cbind(v) colnames(v) <- nn } } v }) if (is.null(vmp[[1]])) { vmp <- NULL } if (!is.null(vmp)) { if (pretty) { vmp <- do.call(cbind, vmp) } else { names(vmp) <- ynms } } vmp } get.nmiss <- function(xvar, yvar = NULL) { if (!is.null(yvar)) { sum(apply(yvar, 1, function(x){any(is.na(x))}) | apply(xvar, 1, function(x){any(is.na(x))})) } else { sum(apply(xvar, 1, function(x){any(is.na(x))})) } } get.outcome.target <- function(family, yvar.names, outcome.target) { if (family == "regr" | family == "regr+" | family == "class" | family == "class+" | family == "mix+") { if (is.null(outcome.target)) { outcome.target <- yvar.names } outcome.target <- unique(outcome.target) outcome.target <- intersect(outcome.target, yvar.names) if (length(outcome.target) == 0) { stop("yvar target names do not match object yvar names") } outcome.target <- match(outcome.target, yvar.names) } else { outcome.target <- 0 } } get.univariate.target <- function(x, outcome.target = NULL) { if (x$family == "regr+" | x$family == "class+" | x$family == "mix+") { if (is.null(outcome.target)) { target <- match(c("regrOutput", "classOutput"), names(x)) target <- target[!is.na(target)] if(length(target) > 0) { do.break <- FALSE for (i in target) { for (j in 1:length(x[[i]])) { if (length(x[[i]][[j]]) > 0) { outcome.target <- names(x[[i]][j]) do.break <- TRUE break } } if (do.break == TRUE) { break } } } else { stop("No outcomes found in object. Please contact technical support.") } } else { if (sum(is.element(outcome.target, x$yvar.names)) != 1) { stop("Specified target was not found or too many target outcomes were supplied (only one is allowed).") } target <- match(c("regrOutput", "classOutput"), names(x)) target <- target[!is.na(target)] found = FALSE if(length(target) > 0) { do.break <- FALSE for (i in target) { for (j in 1:length(x[[i]])) { if (length(x[[i]][[j]]) > 0) { if (outcome.target == names(x[[i]][j])) { found = TRUE do.break <- TRUE break } } } if (do.break == TRUE) { break } } } if (!found) { stop("Target outcome has been correctly specified but it did not contain outcome statistics.") } } } outcome.target } get.weight <- function(weight, n) { if (!is.null(weight)) { if (any(weight < 0) || all(weight == 0) || length(weight) != n || any(is.na(weight))) { stop("Invalid weight vector specified.") } } else { weight <- rep(1, n) } return (weight) } get.ytry <- function(f) { } get.xvar.type <- function(generic.types, xvar.names, coerce.factor = NULL) { xvar.type <- generic.types if (!is.null(coerce.factor$xvar.names)) { xvar.type[is.element(xvar.names, coerce.factor$xvar.names)] <- "C" } xvar.type } get.xvar.nlevels <- function(nlevels, xvar.names, xvar, coerce.factor = NULL) { xvar.nlevels <- nlevels if (!is.null(coerce.factor$xvar.names)) { pt <- is.element(xvar.names, coerce.factor$xvar.names) xvar.nlevels[pt] <- sapply(coerce.factor$xvar.names, function(nn) {max(xvar[, nn])}) } xvar.nlevels } get.yvar.type <- function(fmly, generic.types, yvar.names, coerce.factor = NULL) { if (fmly == "unsupv") { yvar.type <- NULL } else { if (grepl("surv", fmly)) { yvar.type <- c("T", "S") } else { yvar.type <- generic.types if (!is.null(coerce.factor$yvar.names)) { yvar.type[is.element(yvar.names, coerce.factor$yvar.names)] <- "C" } } } yvar.type } get.yvar.nlevels <- function(fmly, nlevels, yvar.names, yvar, coerce.factor = NULL) { if (fmly == "unsupv") { yvar.nlevels <- NULL } else { yvar.nlevels <- nlevels if (!is.null(coerce.factor$yvar.names)) { pt <- is.element(yvar.names, coerce.factor$yvar.names) yvar.nlevels[pt] <- sapply(coerce.factor$yvar.names, function(nn) {max(yvar[, nn])}) } } yvar.nlevels } global.prob.assign <- function(prob, prob.epsilon, gk.quantile, quantile.regr, splitrule, n) { prob.default <- (1:99) / 100 prob.epsilon.default <- .005 prob.bs.default <- .9 if (quantile.regr || grepl("quantile.regr", splitrule) || gk.quantile) { if (gk.quantile) { if (is.null(prob) && is.null(prob.epsilon)) { n <- max(n, 1) prob <- (1 : (2 * n)) / (2 * n + 1) prob.epsilon <- diff(prob)[1] * .99 } else if (is.null(prob) && !is.null(prob.epsilon)) { prob <- prob.default } else if (!is.null(prob) && is.null(prob.epsilon)) { prob.epsilon <- mean(diff(sort(prob)), na.rm = TRUE) * .99 } else { } } else { prob.epsilon <- prob.epsilon.default if (is.null(prob)) { prob <- prob.default } } if (sum(prob > 0 & prob < 1) == 0) { stop("parameter 'prob' is not between (0,1)", prob) } prob <- sort(prob[prob>0 & prob<1]) } if (splitrule == "bs.gradient") { if (is.null(prob)) { prob <- prob.bs.default } if (sum(prob > 0 & prob < 1) == 0) { stop("parameter 'prob' is not between (0,1)", prob) } prob <- prob[prob>0 & prob<1][1] } return(list(prob = prob, prob.epsilon = prob.epsilon)) } make.samplesize.function <- function(fraction = 1) { f <- paste("x * ", paste(eval(fraction))) expr <- parse(text = f) function(x) eval(expr, list(x = x)) } make.holdout.array <- function(vtry = 0, p, ntree, ntree.allvars = NULL) { if (vtry == 0) { return(NULL) } if (vtry < 0 || vtry >= p) { stop("vtry must be positive and less than the feature dimension") } holdout <- do.call(cbind, lapply(1:ntree, function(b) { ho <- rep(0, p) ho[sample(1:p, size = vtry, replace = FALSE)] <- 1 ho })) if (is.null(ntree.allvars)) { holdout } else { cbind(matrix(0, p, ntree.allvars), holdout) } } make.imbalanced.sample <- function(ntree, ratio = 0.5, y, replace = FALSE) { if (ratio < 0 | ratio > 1) { stop("undersampling ratio must be between 0 and 1:", ratio) } frq <- table(y) class.labels <- names(frq) minority <- which.min(frq) majority <- setdiff(1:2, minority) n.minority <- min(frq, na.rm = TRUE) n.majority <- max(frq, na.rm = TRUE) samp.size <- length(y) ratio <- max((2 + n.minority) / length(y), ratio) rbind(sapply(1:ntree, function(bb){ inb <- rep(0, samp.size) smp.min <- sample(which(y == class.labels[minority]), size = n.minority, replace = TRUE) smp.maj <- sample(which(y == class.labels[majority]), size = ratio * n.majority, replace = replace) smp <- c(smp.min, smp.maj) inb.frq <- tapply(smp, smp, length) idx <- as.numeric(names(inb.frq)) inb[idx] <- inb.frq inb })) } make.sample <- function(ntree, samp.size, boot.size = NULL, replace = FALSE) { if (samp.size < 0) { stop("samp.size cannot be negative:", samp.size) } if (is.null(boot.size)) { if (replace == TRUE) { boot.size <- samp.size } else { boot.size <- .632 * samp.size } } rbind(sapply(1:ntree, function(bb){ inb <- rep(0, samp.size) smp <- sample(1:samp.size, size = boot.size, replace = replace) frq <- tapply(smp, smp, length) idx <- as.numeric(names(frq)) inb[idx] <- frq inb })) } make.size <- function(y) { frq <- table(y) min(length(y), min(frq, na.rm = TRUE) * length(frq)) } make.wt <- function(y) { frq <- table(y) class.labels <- names(frq) wt <- rep(1, length(y)) nullO <- sapply(1:length(frq), function(j) { wt[y == class.labels[j]] <<- prod(frq[-j], na.rm = TRUE) NULL }) wt / max(wt, na.rm = TRUE) } parseFormula <- function(f, data, ytry = NULL, coerce.factor = NULL) { if (!inherits(f, "formula")) { stop("'formula' is not a formula object.") } if (is.null(data)) { stop("'data' is missing.") } if (!is.data.frame(data)) { stop("'data' must be a data frame.") } fmly <- all.names(f, max.names = 1e7)[2] all.names <- all.vars(f, max.names = 1e7) yvar.names <- all.vars(formula(paste(as.character(f)[2], "~ .")), max.names = 1e7) yvar.names <- yvar.names[-length(yvar.names)] coerce.factor.org <- coerce.factor coerce.factor <- vector("list", 2) names(coerce.factor) <- c("xvar.names", "yvar.names") if (!is.null(coerce.factor.org)) { coerce.factor$yvar.names <- intersect(yvar.names, coerce.factor.org) if (length(coerce.factor$yvar.names) == 0) { coerce.factor$yvar.names <- NULL } coerce.factor$xvar.names <- intersect(setdiff(colnames(data), yvar.names), coerce.factor.org) } if ((fmly == "Surv")) { if (sum(is.element(yvar.names, names(data))) != 2) { stop("Survival formula incorrectly specified.") } family <- "surv" ytry <- 2 } else if ((fmly == "Multivar" || fmly == "cbind") && length(yvar.names) > 1) { if (sum(is.element(yvar.names, names(data))) < length(yvar.names)) { stop("Multivariate formula incorrectly specified: y's listed in formula are not in data.") } Y <- data[, yvar.names, drop = FALSE] logical.names <- unlist(lapply(Y, is.logical)) if (sum(logical.names) > 0) { Y[, logical.names] <- 1 * Y[, logical.names, drop = FALSE] } if ((sum(unlist(lapply(Y, is.factor))) + length(coerce.factor$yvar.names)) == length(yvar.names)) { family <- "class+" } else if ((sum(unlist(lapply(Y, is.factor))) + length(coerce.factor$yvar.names)) == 0) { family <- "regr+" } else if (((sum(unlist(lapply(Y, is.factor))) + length(coerce.factor$yvar.names)) > 0) && ((sum(unlist(lapply(Y, is.factor))) + length(coerce.factor$yvar.names)) < length(yvar.names))) { family <- "mix+" } else { stop("y-outcomes must be either real or factors in multivariate forests.") } if (!is.null(ytry)) { if ((ytry < 1) || (ytry > length(yvar.names))) { stop("invalid value for ytry: ", ytry) } } else { ytry <- length(yvar.names) } } else if (fmly == "Unsupervised") { if (length(yvar.names) != 0) { stop("Unsupervised forests require no y-responses") } family <- "unsupv" yvar.names <- NULL temp <- gsub(fmly, "", as.character(f)[2]) temp <- gsub("\\(|\\)", "", temp) ytry <- as.integer(temp) if (is.na(ytry)) { ytry <- 1 } else { if (ytry <= 0) { stop("Unsupervised forests require positive ytry value") } } } else { if (sum(is.element(yvar.names, names(data))) != 1) { stop("formula is incorrectly specified.") } Y <- data[, yvar.names] if (is.logical(Y)) { Y <- as.numeric(Y) } if (!(is.factor(Y) | is.numeric(Y))) { stop("the y-outcome must be either real or a factor.") } if (is.factor(Y) || length(coerce.factor$yvar.names) == 1) { family <- "class" } else { family <- "regr" } ytry <- 1 } return (list(all.names=all.names, family=family, yvar.names=yvar.names, ytry=ytry, coerce.factor = coerce.factor)) } is.all.na <- function(x) {all(is.na(x))} parseMissingData <- function(formula.obj, data) { yvar.names <- formula.obj$yvar.names if (length(yvar.names) > 0) { resp <- data[, yvar.names, drop = FALSE] col.resp.na <- unlist(lapply(data[, yvar.names, drop = FALSE], is.all.na)) if (any(col.resp.na)) { stop("All records are missing for one (or more) yvar(s)") } } colPt <- unlist(lapply(data, is.all.na)) if (sum(colPt) > 0 && sum(colPt) >= (ncol(data) - length(yvar.names))) { stop("All x-variables have all missing data: analysis not meaningful.") } data <- data[, !colPt, drop = FALSE] rowPt <- apply(data, 1, is.all.na) if (sum(rowPt) == nrow(data)) { stop("Rows of the data have all missing data: analysis not meaningful.") } data <- data[!rowPt,, drop = FALSE] return(data) } resample <- function(x, size, ...) { if (length(x) <= 1) { if (!missing(size) && size == 0) x[FALSE] else x } else { sample(x, size, ...) } } row.col.deleted <- function(dat, r.n, c.n) { which.r <- setdiff(r.n, rownames(dat)) if (length(which.r) > 0) { which.r <- match(which.r, r.n) } else { which.r <- NULL } which.c <- setdiff(c.n, colnames(dat)) if (length(which.c) > 0) { which.c <- match(which.c, c.n) } else { which.c <- NULL } return(list(row = which.r, col = which.c)) } sid.perf.metric <- function(truth,cluster,mode=c("entropy", "gini")){ mode <- match.arg(mode, c("entropy", "gini")) k=length(unique(truth)) tab=table(truth,cluster) clustersizes=colSums(tab) clustersizesnorm=clustersizes/sum(clustersizes) tabprop=tab lapply(1:(dim(tab)[2]),function(i){ tabprop[,i]<<-tabprop[,i]/clustersizes[i] NULL }) if(mode=="entropy"){ measure=0 maxmeasure=0 lapply(1:(dim(tabprop)[2]),function(i){ clustermeasure=0 maxclustermeasure=0 lapply(1:(dim(tabprop)[1]),function(j){ if(tabprop[j,i]!=0){ clustermeasure<<-clustermeasure+-tabprop[j,i]*log2(tabprop[j,i]) } maxclustermeasure<<-maxclustermeasure+-1/k*log2(1/k) NULL }) measure<<-measure+clustersizesnorm[i]*clustermeasure maxmeasure<<-maxmeasure+clustersizesnorm[i]*maxclustermeasure }) } if(mode=="gini"){ measure=0 maxmeasure=0 lapply(1:(dim(tabprop)[2]),function(i){ clustermeasure=1 maxclustermeasure=1 lapply(1:(dim(tabprop)[1]),function(j){ if(tabprop[j,i]!=0){ clustermeasure<<-clustermeasure+(-tabprop[j,i]^2) } maxclustermeasure<<-maxclustermeasure+(-1/k^2) NULL }) measure<<-measure+clustersizesnorm[i]*clustermeasure maxmeasure<<-maxmeasure+clustersizesnorm[i]*maxclustermeasure NULL }) } list(result=measure,measure=mode,normalized_measure=measure/maxmeasure) }
knitr::opts_chunk$set( collapse = TRUE, comment = " ) library(geneExpressionFromGEO)
calculate_FSSwind <- function (findex1, findex2, nvector) { if (ncol(findex1) != ncol(findex2) || nrow(findex1) != nrow(findex2)) { stop("The two input wind class index fields don't have the same dimensions !!!") } max_index = max(max(findex1), max(findex2)) min_value = min(min(findex1), min(findex2)) if (identical(findex1, round(findex1)) == FALSE || identical(findex2, round(findex2)) == FALSE || min_value < 1) { stop("At least one of the two index fields contains non-integer or non-positive values. Only positive integer values that represent wind classes are allowed in the input index fields! The smallest allowed windclass index is 1 and not 0.") } if (identical(nvector, round(nvector)) == FALSE || length(which(nvector%%2 != 1)) > 0) { stop("nvector can only contain odd positive integer values representing the neigberhood size!") } fsum1enl_list = list() fsum2enl_list = list() d = max(ncol(findex1), nrow(findex1)) for (iclass in 1:max_index) { ftemp = findex1 ftemp[ftemp != iclass] <- 0 ftemp[ftemp == iclass] <- 1 ftemp2 = enlarge_matrix(ftemp, d) fsum1enl_list[[iclass]] <- calculate_summed_field(ftemp2) ftemp = findex2 ftemp[ftemp != iclass] <- 0 ftemp[ftemp == iclass] <- 1 ftemp2 = enlarge_matrix(ftemp, d) fsum2enl_list[[iclass]] <- calculate_summed_field(ftemp2) } FSSwind = nvector for (inn in 1:length(nvector)) { numerator = 0 denominator = 0 for (iclass in 1:max_index) { ffrac1 <- calculate_fractions_from_enlarged_summed_field(fsum1enl_list[[iclass]], nvector[inn], d) ffrac2 <- calculate_fractions_from_enlarged_summed_field(fsum2enl_list[[iclass]], nvector[inn], d) numerator = numerator + sum((ffrac1 - ffrac2)^2) denominator = denominator + sum(ffrac1^2 + ffrac2^2) } FSSwind[inn] = 1 - numerator/denominator } return(FSSwind) }
NULL get_elasticities <- function( blp_data, share_info, theta_lin, variable, products , market, printLevel = 1){ if(class(blp_data) != "blp_data") stop("blp_data has wrong class. Call BLP_data() first.") if(class(share_info) != "shareInfo") stop("share_info has wrong class. Call getShareInfo() first.") if( missing(variable )) stop("Specify variable for which elasticities should be calculated for.") if( length(variable) != 1) stop("Only one variable can be specified.") if( missing(market )) stop("Specify mkt in which elasticities should be calculated.") if( length(market) != 1) stop("Only one market can be specified.") X_rand_colNames <- colnames(blp_data$data$X_rand) X_lin_colNames <- colnames(blp_data$data$X_lin) if ( !( variable %in% c(X_lin_colNames, X_rand_colNames ) ) ){ stop( paste( "Provided variable", variable , "is not in the set of variables. Constants must be named (Intercept).") ) } original_market_id <- blp_data$parameters$market_id_char_in market <- as.character(market) if( !any(market %in% original_market_id) ) stop("Market is not available in provided dataset.") relevant_Obs_Mkt <- which( market == original_market_id) relevant_Mkt <- which( market == unique(original_market_id)) nobs <- nrow( blp_data$data$X_lin ) amountDraws <- blp_data$integration$amountDraws K <- blp_data$parameters$K totalDemographics <- blp_data$parameters$total_demogr nprod_Mkt <- length( relevant_Obs_Mkt ) implShare_Mkt <- share_info$shares[ relevant_Obs_Mkt ] product_id_Mkt <- blp_data$parameters$product_id[ relevant_Obs_Mkt ] if( missing(products) ){ product_selector <- 1:nprod_Mkt }else{ product_selector <- products } if( any(!(product_selector %in% product_id_Mkt ))){ if(printLevel >0) cat("At least one specified product is not available in the market... selecting all.\n") product_selector <- 1:nprod_Mkt } if( length(theta_lin)!=1 || !is.numeric(theta_lin) || is.na( theta_lin ) ) stop( "Provide a valid linear parameter theta_lin. If the variable does not enter linerarly, provide zero.") if ( !( variable %in% colnames(blp_data$data$X_rand)) ) { changingVariable_Mkt <- blp_data$data$X_lin[ relevant_Obs_Mkt , variable, drop = F ] EtaMkt <- - matrix( changingVariable_Mkt * theta_lin * implShare_Mkt , nrow = nprod_Mkt, ncol = nprod_Mkt, byrow = TRUE) diag(EtaMkt) <- theta_lin * changingVariable_Mkt * (1 - implShare_Mkt) } else { changingVariable_Mkt <- blp_data$data$X_rand[ relevant_Obs_Mkt , variable, drop = F ] drawsRCMktShape_Mkt <- blp_data$integration$drawsRcMktShape[ relevant_Mkt , , drop = FALSE] drawsRC_tableform_Mkt <- matrix(drawsRCMktShape_Mkt, nrow = amountDraws, ncol = K ) colnames(drawsRC_tableform_Mkt) <- X_rand_colNames if ( totalDemographics > 0 ) { drawsDemMktShape_Mkt <- blp_data$integration$drawsDemMktShape[ relevant_Mkt, , drop = FALSE] demographicReshape_Mkt <- matrix( drawsDemMktShape_Mkt , ncol = totalDemographics , nrow = amountDraws ) } else { drawsDemMktShape_Mkt <- matrix( NA ) demographicReshape_Mkt <- matrix( NA ) } sij_Mkt <- share_info$sij[ relevant_Obs_Mkt , ,drop=FALSE] weights <- blp_data$integration$weights theta2Mat <- share_info$theta2 sigma <- theta2Mat[ variable , "unobs_sd" ] unobserved_part <- theta_lin + sigma * drawsRC_tableform_Mkt[ , variable ] if ( totalDemographics > 0 ) { demographic_effects <- matrix( theta2Mat[ variable, -1], ncol = totalDemographics, nrow = amountDraws, byrow = TRUE ) observed_part <- rowSums( demographic_effects * demographicReshape_Mkt ) } else { observed_part <- 0 } beta_i <- observed_part + unobserved_part Omega <- matrix( NA_real_ , nrow = nprod_Mkt, ncol = nprod_Mkt) scalar <- - matrix( 1/implShare_Mkt ) %*% matrix( changingVariable_Mkt , nrow = 1) diag( scalar ) <- - diag( scalar ) Omega[, ] <- ( t( beta_i )[ rep(1, nprod_Mkt) , ] * t( weights )[ rep( 1 , nprod_Mkt), ] * sij_Mkt ) %*% t( sij_Mkt ) diag( Omega ) <- c( ( t( beta_i )[rep( 1, nprod_Mkt ), ] * sij_Mkt * (1 - sij_Mkt) ) %*% weights ) EtaMkt <- Omega * scalar } rownames( EtaMkt ) <- colnames( EtaMkt ) <- product_id_Mkt return( EtaMkt[product_selector,product_selector] ) }
mdes.bird2f1 <- function(score = NULL, dists = "normal", k1 = -6, k2 = 6, order = 1, interaction = FALSE, treat.lower = TRUE, cutoff = 0, p = NULL, power = .80, alpha = .05, two.tailed = TRUE, df = n2 * (n1 - 2) - g1 - order * (1 + interaction), r21 = 0, g1 = 0, rate.tp = 1, rate.cc = 0, n1, n2 = 1) { user.parms <- as.list(match.call()) .error.handler(user.parms) if(df < 1) stop("Insufficient degrees of freedom", call. = FALSE) if(!is.null(score) & order == 0) warning("Ignoring information from the 'score' object \n", call. = FALSE) if(order == 0) { d <- 1 if(is.null(p)) stop("'p' cannot be NULL in random assignment designs", call. = FALSE) idx.score <- intersect(c("dists", "k1", "k2", "interaction", "treat.lower", "cutoff"), names(user.parms)) if(length(idx.score) > 0) cat("\nCAUTION: Ignoring argument(s):", sQuote(names(user.parms[idx.score])), "\n") ifelse(treat.lower, cutoff <- p, cutoff <- 1 - p) interaction <- FALSE dists <- "uniform" k1 <- 0 k2 <- 1 } else if(order %in% 1:8) { if(is.null(score)) { score <- inspect.score(order = order, interaction = interaction, treat.lower = treat.lower, cutoff = cutoff, p = p, k1 = k1, k2 = k2, dists = dists) } else { if("p" %in% names(user.parms)) warning("Using 'p' from the 'score' object, ignoring 'p' in the function call", call. = FALSE) if(!inherits(score, "score")) { score <- inspect.score(score = score, order = order, interaction = interaction, treat.lower = treat.lower, cutoff = cutoff, p = p, k1 = k1, k2 = k2, dists = dists) } else { idx.score <- intersect(c("dists", "k1", "k2", "order", "interaction", "treat.lower", "p", "cutoff"), names(user.parms)) if(length(idx.score) > 0) cat("\nCAUTION: 'score' object overwrites argument(s):", sQuote(names(user.parms[idx.score])), "\n") } } d <- score$rdde p <- score$p cutoff <- score$cutoff treat.lower <- score$treat.lower order <- score$order interaction <- score$interaction dists <- score$parms$dists k1 <- score$parms$k1 k2 <- score$parms$k2 } else if(order > 8) { stop("'order' > 8 is not allowed", call. = FALSE) } sse <- (1/(rate.tp - rate.cc)) * sqrt(d * (1 - r21) / (p * (1 - p) * n1 * n2)) mdes <- .mdes(power, alpha, sse, df, two.tailed) colnames(mdes) <- c("mdes", paste0(100 * (1 - round(alpha, 2)), "%lcl"), paste0(100 * (1 - round(alpha, 2)), "%ucl")) mdes.out <- list(parms = list(dists = dists, k1 = k1, k2 = k2, order = order, interaction = interaction, treat.lower = treat.lower, p = p, cutoff = cutoff, power = power, alpha = alpha, two.tailed = two.tailed, r21 = r21, g1 = g1, rate.tp = rate.tp, rate.cc = rate.cc, n1 = n1, n2 = n2), df = df, sse = sse, mdes = mdes) class(mdes.out) <- c("mdes", "bird2f1") .summary.mdes(mdes.out) return(invisible(mdes.out)) } power.bird2f1 <- function(score = NULL, dists = "normal", k1 = -6, k2 = 6, order = 1, interaction = FALSE, treat.lower = TRUE, cutoff = 0, p = NULL, es = .25, alpha = .05, two.tailed = TRUE, df = n2 * (n1 - 2) - g1 - order * (1 + interaction), r21 = 0, g1 = 0, rate.tp = 1, rate.cc = 0, n1, n2 = 1) { user.parms <- as.list(match.call()) .error.handler(user.parms) if(df < 1) stop("Insufficient degrees of freedom", call. = FALSE) if(!is.null(score) & order == 0) warning("Ignoring information from the 'score' object \n", call. = FALSE) if(order == 0) { d <- 1 if(is.null(p)) stop("'p' cannot be NULL in random assignment designs", call. = FALSE) idx.score <- intersect(c("dists", "k1", "k2", "interaction", "treat.lower", "cutoff"), names(user.parms)) if(length(idx.score) > 0) cat("\nCAUTION: Ignoring argument(s):", sQuote(names(user.parms[idx.score])), "\n") ifelse(treat.lower, cutoff <- p, cutoff <- 1 - p) interaction <- FALSE dists <- "uniform" k1 <- 0 k2 <- 1 } else if(order %in% 1:8) { if(is.null(score)) { score <- inspect.score(order = order, interaction = interaction, treat.lower = treat.lower, cutoff = cutoff, p = p, k1 = k1, k2 = k2, dists = dists) } else { if("p" %in% names(user.parms)) warning("Using 'p' from the 'score' object, ignoring 'p' in the function call", call. = FALSE) if(!inherits(score, "score")) { score <- inspect.score(score = score, order = order, interaction = interaction, treat.lower = treat.lower, cutoff = cutoff, p = p, k1 = k1, k2 = k2, dists = dists) } else { idx.score <- intersect(c("dists", "k1", "k2", "order", "interaction", "treat.lower", "p", "cutoff"), names(user.parms)) if(length(idx.score) > 0) cat("\nCAUTION: 'score' object overwrites argument(s):", sQuote(names(user.parms[idx.score])), "\n") } } d <- score$rdde p <- score$p cutoff <- score$cutoff treat.lower <- score$treat.lower order <- score$order interaction <- score$interaction dists <- score$parms$dists k1 <- score$parms$k1 k2 <- score$parms$k2 } else if(order > 8) { stop("'order' > 8 is not allowed", call. = FALSE) } sse <- (1/(rate.tp - rate.cc)) * sqrt(d * (1 - r21) / (p * (1 - p) * n1 * n2)) power <- .power(es, alpha, sse, df, two.tailed) power.out <- list(parms = list(dists = dists, k1 = k1, k2 = k2, order = order, interaction = interaction, treat.lower = treat.lower, p = p, cutoff = cutoff, es = es, alpha = alpha, two.tailed = two.tailed, r21 = r21, g1 = g1, rate.tp = rate.tp, rate.cc = rate.cc, n1 = n1, n2 = n2), df = df, sse = sse, power = power) class(power.out) <- c("power", "bird2f1") .summary.power(power.out) return(invisible(power.out)) } cosa.bird2f1 <- function(score = NULL, dists = "normal", k1 = -6, k2 = 6, rhots = NULL, order = 1, interaction = FALSE, treat.lower = TRUE, cutoff = 0, p = NULL, cn1 = 0, cn2 = 0, cost = NULL, n1 = NULL, n2 = NULL, n0 = c(400, 5), p0 = .499, constrain = "power", round = TRUE, max.power = FALSE, local.solver = c("LBFGS", "SLSQP"), power = .80, es = .25, alpha = .05, two.tailed = TRUE, g1 = 0, r21 = 0) { user.parms <- as.list(match.call()) .error.handler(user.parms, fun = "cosa") if(!is.null(rhots)) { if(rhots == 0) { if(order != 0) { order <- 0 warning("'order' argument is ignored, forcing 'order = 0' because 'rhots = 0'", call. = FALSE) } } else { stop("'rhots' argument will be removed in the future, arbitrary correlations are not allowed, use inspect.score() function instead", call. = FALSE) } } if(!is.null(score) & order == 0) warning("Ignoring information from the 'score' object \n", call. = FALSE) if(order == 0) { d <- 1 idx.score <- intersect(c("dists", "k1", "k2", "interaction", "treat.lower", "cutoff"), names(user.parms)) if(length(idx.score) > 0) cat("\nCAUTION: Ignoring argument(s):", sQuote(names(user.parms[idx.score])), "\n") cutoff <- NA interaction <- FALSE dists <- "uniform" k1 <- 0 k2 <- 1 } else if(order %in% 1:8) { if(is.null(score)) { score <- inspect.score(order = order, interaction = interaction, treat.lower = treat.lower, cutoff = cutoff, p = p, k1 = k1, k2 = k2, dists = dists) } else { if("p" %in% names(user.parms)) warning("Using 'p' from the 'score' object, ignoring 'p' in the function call", call. = FALSE) if(!inherits(score, "score")) { score <- inspect.score(score = score, order = order, interaction = interaction, treat.lower = treat.lower, cutoff = cutoff, p = p, k1 = k1, k2 = k2, dists = dists) } else { idx.score <- intersect(c("dists", "k1", "k2", "order", "interaction", "treat.lower", "p", "cutoff"), names(user.parms)) if(length(idx.score) > 0) cat("\nCAUTION: 'score' object overwrites argument(s):", sQuote(names(user.parms[idx.score])), "\n") } } d <- score$rdde p <- score$p cutoff <- score$cutoff treat.lower <- score$treat.lower order <- score$order interaction <- score$interaction dists <- score$parms$dists k1 <- score$parms$k1 k2 <- score$parms$k2 } else if(order > 8) { stop("'order' > 8 is not allowed", call. = FALSE) } fun <- "cosa.bird2f1" lb <- c(g1 + order * (1 + interaction) + 3, 1) if(!is.null(n1)) { if(n1[1] < lb[1]) warning("Lower bound for 'n1' may violate minimum degrees of freedom requirement", call. = FALSE) } .df <- quote(n2 * (n1 - 2) - g1 - order * (1 + interaction)) .sse <- quote(sqrt(d * (1 - r21) / (p * (1 - p) * n2 * n1))) .cost <- quote(n2 * cn2 + n2 * n1 * (cn1[2] + p * (cn1[1] - cn1[2]))) .var.jacob <- expression( c( -d * (1 - r21) / (p * (1 - p) * n2 * n1^2), -d * (1 - r21) / (p * (1 - p) * n2^2 * n1), -(1 - 2 * p) * d * (1 - r21) / ((1 - p)^2 * p^2 * n2 * n1) ) ) .cost.jacob <- expression( c( n2 * (p * cn1[1] + (1 - p) * cn1[2]), cn2 + n1 * (p * cn1[1] + (1 - p) * cn1[2]), n2 * n1 * (cn1[1] - cn1[2]) ) ) if(all(cn1 == 0) & is.null(p)) p <- .50 cosa <- .cosa(order = order, interaction = interaction, cn1 = cn1, cn2 = cn2, cost = cost, constrain = constrain, round = round, max.power = max.power, local.solver = local.solver, power = power, es = es, alpha = alpha, two.tailed = two.tailed, r21 = r21, g1 = g1, p0 = p0, p = p, n0 = n0, n1 = n1, n2 = n2) cosa.out <- list(parms = list(dists = dists, k1 = k1, k2 = k2, order = order, interaction = interaction, treat.lower = treat.lower, cutoff = cutoff, cn1 = cn1, cn2 = cn2, cost = cost, constrain = constrain, round = round, max.power = max.power, local.solver = local.solver, power = power, es = es, alpha = alpha, two.tailed = two.tailed, r21 = r21, g1 = g1, p0 = p0, p = p, n0 = n0, n1 = n1, n2 = n2), cosa = cosa) class(cosa.out) <- c("cosa", "bird2f1") .summary.cosa(cosa.out) return(invisible(cosa.out)) }
context("cytominer integration test") test_that("cytominer can process dataset with a normalized schema", { skip_on_os("windows") futile.logger::flog.threshold(futile.logger::WARN) fixture <- system.file( "extdata", "fixture_intensities_shapes.sqlite", package = "cytominer" ) db <- DBI::dbConnect(RSQLite::SQLite(), fixture) ext_metadata <- readr::read_csv(system.file( "extdata", "metadata.csv", package = "cytominer" )) %>% dplyr::rename(g_well = Well) ext_metadata <- dplyr::copy_to(db, ext_metadata) futile.logger::flog.info("Creating temp table for intensities") intensities <- dplyr::tbl(src = db, "view_intensities") %>% dplyr::compute() futile.logger::flog.info("Created temp table for intensities") measurements <- intensities %>% dplyr::filter(g_well %in% c("A01", "A02", "A10", "A11")) qualities <- c("q_debris") groupings <- c( "g_plate", "g_well", "g_image", "g_pattern", "g_channel" ) testthat::expect_true(all(groupings %in% ( colnames(measurements) %>% stringr::str_subset("^g_") ))) testthat::expect_true(all(qualities %in% ( colnames(measurements) %>% stringr::str_subset("^q_") ))) variables <- colnames(measurements) %>% stringr::str_subset("^m_") measurements %<>% dplyr::select(c(groupings, qualities, variables)) debris_removed <- measurements %>% dplyr::filter(q_debris == 0) na_rows_removed <- drop_na_rows( population = debris_removed, variables = variables ) %>% dplyr::compute() futile.logger::flog.info("Normalizing") normalized <- normalize( population = na_rows_removed, variables = variables, strata = c("g_plate", "g_pattern", "g_channel"), sample = na_rows_removed %>% dplyr::inner_join( ext_metadata %>% dplyr::filter(Type == "ctrl") %>% dplyr::select(g_well) ) ) futile.logger::flog.info("Normalized") normalized %<>% dplyr::collect() na_frequency <- count_na_rows( population = normalized, variables = variables ) cleaned <- variable_select( population = normalized, variables = variables, operation = "drop_na_columns" ) transformed <- transform( population = cleaned, variables = variables ) transformed_whiten <- transform( population = cleaned, sample = cleaned, variables = variables, operation = "whiten" ) expect_error( transform( population = transformed, variables = variables, operation = "dummy" ), paste0("undefined operation 'dummy'") ) aggregated <- aggregate( population = transformed, variables = variables, strata = groupings ) %>% dplyr::collect() variables <- colnames(aggregated) %>% stringr::str_subset("^m_") selected <- variable_select( population = transformed, variables = variables, operation = "correlation_threshold", sample = aggregated ) %>% dplyr::collect() selected <- variable_select( population = transformed, variables = variables, operation = "variance_threshold", sample = aggregated ) %>% dplyr::collect() expect_error( variable_select( population = transformed, variables = variables, sample = aggregated, operation = "dummy" ), paste0("undefined operation 'dummy'") ) expect_error( variable_importance( sample = transformed, variables = variables, operation = "dummy" ), paste0("undefined operation 'dummy'") ) DBI::dbDisconnect(db) }) test_that("cytominer can process dataset with a CellProfiler schema", { skip_on_os("windows") set.seed(123) futile.logger::flog.threshold(futile.logger::WARN) fixture <- system.file( "extdata", "fixture_htqc.sqlite", package = "cytominer" ) db <- DBI::dbConnect(RSQLite::SQLite(), fixture) ext_metadata <- readr::read_csv(system.file( "extdata", "metadata.csv", package = "cytominer" )) %>% dplyr::rename(g_well = Well) ext_metadata <- dplyr::copy_to(db, ext_metadata) futile.logger::flog.info("Creating table for objects") image <- dplyr::tbl(src = db, "image") object <- dplyr::tbl(src = db, "cells") %>% dplyr::inner_join( dplyr::tbl(src = db, "cytoplasm"), by = c("TableNumber", "ImageNumber", "ObjectNumber") ) %>% dplyr::inner_join( dplyr::tbl(src = db, "nuclei"), by = c("TableNumber", "ImageNumber", "ObjectNumber") ) object %<>% dplyr::inner_join( image %>% dplyr::select( "TableNumber", "ImageNumber", "image_Metadata_Barcode", "image_Metadata_Well", "image_Metadata_isDebris" ), by = c("TableNumber", "ImageNumber") ) object %<>% dplyr::rename(g_plate = "image_Metadata_Barcode") object %<>% dplyr::rename(g_well = "image_Metadata_Well") object %<>% dplyr::rename(g_table = "TableNumber") object %<>% dplyr::rename(g_image = "ImageNumber") object %<>% dplyr::rename(q_debris = "image_Metadata_isDebris") futile.logger::flog.info("Created table for objects") measurements <- object %>% dplyr::filter(g_well %in% c("A01", "A02", "A10", "A11")) qualities <- c("q_debris") groupings <- c( "g_plate", "g_well", "g_table", "g_image" ) variables <- colnames(measurements) %>% stringr::str_subset("^Nuclei_|^Cells_|^Cytoplasm_") testthat::expect_true(all(groupings %in% ( colnames(measurements) %>% stringr::str_subset("^g_") ))) testthat::expect_true(all(qualities %in% ( colnames(measurements) %>% stringr::str_subset("^q_") ))) variables <- colnames(measurements) %>% stringr::str_subset("^Nuclei_|^Cells_|^Cytoplasm_") variables <- sample(variables, 10) measurements %<>% dplyr::select(c(groupings, qualities, variables)) debris_removed <- measurements %>% dplyr::filter(q_debris == 0) na_rows_removed <- debris_removed futile.logger::flog.info("Normalizing") normalized <- normalize( population = na_rows_removed %>% dplyr::collect(), variables = variables, strata = c("g_plate"), sample = na_rows_removed %>% dplyr::inner_join( ext_metadata %>% dplyr::filter(Type == "ctrl") %>% dplyr::select(g_well) ) %>% dplyr::collect() ) futile.logger::flog.info("Normalized") na_frequency <- count_na_rows( population = normalized, variables = variables ) cleaned <- variable_select( population = normalized, variables = variables, operation = "drop_na_columns" ) variables <- colnames(cleaned) %>% stringr::str_subset("^Nuclei_|^Cells_|^Cytoplasm_") transformed <- transform( population = cleaned, variables = variables ) aggregated <- aggregate( population = transformed, variables = variables, strata = groupings ) %>% dplyr::collect() variables <- colnames(aggregated) %>% stringr::str_subset("^m_") selected <- variable_select( population = transformed, variables = variables, sample = aggregated, operation = "correlation_threshold" ) %>% dplyr::collect() selected <- variable_select( population = transformed, variables = variables, sample = aggregated, operation = "variance_threshold" ) %>% dplyr::collect() DBI::dbDisconnect(db) })
modelDisplay <- function(model, ...) { funcName <- paste(model$type, "Display", sep="") if(exists(funcName, mode="function")) { func <- get(funcName, mode="function") func(model, ...) } }
.garchRnlminb <- function(.params, .series, .garchLLH, trace) { if(trace) cat("\nR coded nlminb Solver: \n\n") INDEX = .params$index parscale = rep(1, length = length(INDEX)) names(parscale) = names(.params$params[INDEX]) parscale["omega"] = var(.series$x)^(.params$delta/2) parscale["mu"] = abs(mean(.series$x)) TOL1 = .params$control$tol1 fit <- nlminb( start = .params$params[INDEX], objective = .garchLLH, lower = .params$U[INDEX], upper = .params$V[INDEX], scale = 1/parscale, control = list( eval.max = 2000, iter.max = 1500, rel.tol = 1.0e-14 * TOL1, x.tol = 1.0e-14 * TOL1, trace = as.integer(trace)), fGarchEnv = FALSE) fit$value <- fit.llh <- fit$objective names(fit$par) = names(.params$params[INDEX]) .garchLLH(fit$par, trace = FALSE, fGarchEnv = TRUE) fit$coef <- fit$par fit$llh <- fit$objective fit } .garchRlbfgsb <- function(.params, .series, .garchLLH, trace) { if(trace) cat("\nR coded optim[L-BFGS-B] Solver: \n\n") INDEX = .params$index parscale = rep(1, length = length(INDEX)) names(parscale) = names(.params$params[INDEX]) parscale["omega"] = var(.series$x)^((.params$params["delta"])/2) TOL1 = .params$control$tol1 fit <- optim( par = .params$params[INDEX], fn = .garchLLH, lower = .params$U[INDEX], upper = .params$V[INDEX], method = "L-BFGS-B", control = list( parscale = parscale, lmm = 20, pgtol = 1.0e-11 * TOL1, factr = 1.0 * TOL1, trace = as.integer(trace)), fGarchEnv = FALSE) names(fit$par) = names(.params$params[INDEX]) .garchLLH(fit$par, trace = FALSE, fGarchEnv = TRUE) fit$coef = fit$par fit$llh = fit$value fit } .garchRnm <- function(.params, .series, .garchLLH, trace) { if(trace) cat("\nR coded Nelder-Mead Hybrid Solver: \n\n") INDEX = .params$index fnscale = abs(.params$llh) parscale = abs(.params$params[INDEX]) TOL2 = .params$control$tol2 fit = optim( par = .params$params[INDEX], fn = .garchLLH, method = "Nelder-Mead", control = list( ndeps = rep(1e-14*TOL2, length = length(INDEX)), maxit = 10000, reltol = 1.0e-11 * TOL2, fnscale = fnscale, parscale = c(1, abs((.params$params[INDEX])[-1])), trace = as.integer(trace)), hessian = TRUE, fGarchEnv = FALSE) names(fit$par) = names(.params$params[INDEX]) .garchLLH(fit$par, trace = FALSE, fGarchEnv = TRUE) fit$coef = fit$par fit$llh = fit$value fit }
test_that("ctype() errors for unanticipated inputs", { expect_error(ctype(NULL)) expect_error(ctype(data.frame(cell = "cell"))) }) test_that("ctype() works on a SHEET_CELL, when it should", { expect_identical( ctype(structure(1, class = c("wut", "SHEETS_CELL"))), NA_character_ ) expect_identical( ctype(structure(1, class = c("CELL_NUMERIC", "SHEETS_CELL"))), "CELL_NUMERIC" ) }) test_that("ctype() works on shortcodes, when it should", { expect_equal( unname(ctype(c("?", "-", "n", "z", "D"))), c("COL_GUESS", "COL_SKIP", "CELL_NUMERIC", NA, "CELL_DATE") ) }) test_that("ctype() works on lists, when it should", { list_of_cells <- list( structure(1, class = c("CELL_NUMERIC", "SHEETS_CELL")), "nope", NULL, structure(1, class = c("wut", "SHEETS_CELL")), structure(1, class = c("CELL_TEXT", "SHEETS_CELL")) ) expect_equal( ctype(list_of_cells), c("CELL_NUMERIC", NA, NA, NA, "CELL_TEXT") ) }) test_that("effective_cell_type() doesn't just pass ctype through", { expect_equal(unname(effective_cell_type("CELL_INTEGER")), "CELL_NUMERIC") expect_equal(unname(effective_cell_type("CELL_DATE")), "CELL_DATETIME") expect_equal(unname(effective_cell_type("CELL_TIME")), "CELL_DATETIME") }) test_that("consensus_col_type() implements our type coercion DAG", { expect_identical( consensus_col_type(c("CELL_TEXT", "CELL_TEXT")), "CELL_TEXT" ) expect_identical( consensus_col_type(c("CELL_LOGICAL", "CELL_NUMERIC")), "CELL_NUMERIC" ) expect_identical( consensus_col_type(c("CELL_LOGICAL", "CELL_DATE")), "COL_LIST" ) expect_identical( consensus_col_type(c("CELL_DATE", "CELL_DATETIME")), "CELL_DATETIME" ) expect_identical( consensus_col_type(c("CELL_TEXT", "CELL_BLANK")), "CELL_TEXT" ) expect_identical(consensus_col_type("CELL_TEXT"), "CELL_TEXT") expect_identical(consensus_col_type("CELL_BLANK"), "CELL_LOGICAL") })
tidyverse_update <- function(recursive = FALSE, repos = getOption("repos")) { deps <- tidyverse_deps(recursive, repos) behind <- dplyr::filter(deps, behind) if (nrow(behind) == 0) { cli::cat_line("All tidyverse packages up-to-date") return(invisible()) } cli::cat_line(cli::pluralize( "The following {cli::qty(nrow(behind))}package{?s} {?is/are} out of date:" )) cli::cat_line() cli::cat_bullet(format(behind$package), " (", behind$local, " -> ", behind$cran, ")") cli::cat_line() cli::cat_line("Start a clean R session then run:") pkg_str <- paste0(deparse(behind$package), collapse = "\n") cli::cat_line("install.packages(", pkg_str, ")") invisible() } tidyverse_sitrep <- function() { cli::cat_rule("R & RStudio") if (rstudioapi::isAvailable()) { cli::cat_bullet("RStudio: ", rstudioapi::getVersion()) } cli::cat_bullet("R: ", getRversion()) deps <- tidyverse_deps() package_pad <- format(deps$package) packages <- ifelse( deps$behind, paste0(cli::col_yellow(cli::style_bold(package_pad)), " (", deps$local, " < ", deps$cran, ")"), paste0(package_pad, " (", deps$cran, ")") ) cli::cat_rule("Core packages") cli::cat_bullet(packages[deps$package %in% core]) cli::cat_rule("Non-core packages") cli::cat_bullet(packages[!deps$package %in% core]) } tidyverse_deps <- function(recursive = FALSE, repos = getOption("repos")) { pkgs <- utils::available.packages(repos = repos) deps <- tools::package_dependencies("tidyverse", pkgs, recursive = recursive) pkg_deps <- unique(sort(unlist(deps))) base_pkgs <- c( "base", "compiler", "datasets", "graphics", "grDevices", "grid", "methods", "parallel", "splines", "stats", "stats4", "tools", "tcltk", "utils" ) pkg_deps <- setdiff(pkg_deps, base_pkgs) tool_pkgs <- c("cli", "crayon", "rstudioapi") pkg_deps <- setdiff(pkg_deps, tool_pkgs) cran_version <- lapply(pkgs[pkg_deps, "Version"], base::package_version) local_version <- lapply(pkg_deps, packageVersion) behind <- purrr::map2_lgl(cran_version, local_version, `>`) tibble::tibble( package = pkg_deps, cran = cran_version %>% purrr::map_chr(as.character), local = local_version %>% purrr::map_chr(as.character), behind = behind ) } packageVersion <- function(pkg) { if (rlang::is_installed(pkg)) { utils::packageVersion(pkg) } else { 0 } }
knitr::opts_chunk$set( echo = TRUE, python.reticulate = FALSE )
formInput <- function(..., id, inline = FALSE) { assert_id() dep_attach({ tags$form( class = str_collate( "yonder-form", if (inline) "form-inline" ), id = id, ... ) }) } formSubmit <- function(label, value = label, ...) { dep_attach({ tags$button( class = "yonder-form-submit btn btn-blue", value = value, label, ... ) }) } updateFormInput <- function(id, submit = FALSE, session = getDefaultReactiveDomain()) { assert_id() assert_session() if (!(is.logical(submit) || is.character(submit)) || (is.character(submit) && length(submit) > 1)) { stop( "invalid argument in `updateFormInput()`, `submit` must be one of ", "TRUE or FALSE or a character string", call. = FALSE ) } submit <- coerce_submit(submit) session$sendInputMessage(id, list( submit = submit )) }
ScaleDiscreteIdentity <- getFromNamespace("ScaleDiscreteIdentity", "ggplot2") binned_scale <- getFromNamespace("binned_scale", "ggplot2") discrete_scale <- getFromNamespace("discrete_scale", "ggplot2") datetime_scale <- getFromNamespace("datetime_scale", "ggplot2") manual_scale <- getFromNamespace("manual_scale", "ggplot2") mid_rescaler <- getFromNamespace("mid_rescaler", "ggplot2") continuous_scale <- getFromNamespace("continuous_scale", "ggplot2") waiver <- getFromNamespace("waiver", "ggplot2") muted <- getFromNamespace("muted", "scales") binned_pal <- getFromNamespace("binned_pal", "ggplot2") scale_shadowcolour_hue <- function(..., h = c(0, 360) + 15, c = 100, l = 65, h.start = 0, direction = 1, na.value = "grey50", aesthetics = "shadowcolour") { discrete_scale(aesthetics, "hue", scales::hue_pal(h, c, l, h.start, direction), na.value = na.value, ...) } scale_shadowcolour_discrete <- scale_shadowcolour_hue scale_shadowcolour_brewer <- function(..., type = "seq", palette = 1, direction = 1, aesthetics = "shadowcolour") { discrete_scale(aesthetics, "brewer", scales::brewer_pal(type, palette, direction), ...) } scale_shadowcolour_distiller <- function(..., type = "seq", palette = 1, direction = -1, values = NULL, space = "Lab", na.value = "grey50", guide = "colourbar", aesthetics = "shadowcolour") { type <- match.arg(type, c("seq", "div", "qual")) if (type == "qual") { warn("Using a discrete colour palette in a continuous scale.\n Consider using type = \"seq\" or type = \"div\" instead") } continuous_scale(aesthetics, "distiller", scales::gradient_n_pal(scales::brewer_pal(type, palette, direction)(7), values, space), na.value = na.value, guide = guide, ...) } scale_shadowcolour_fermenter <- function(..., type = "seq", palette = 1, direction = -1, na.value = "grey50", guide = "coloursteps", aesthetics = "shadowcolour") { type <- match.arg(type, c("seq", "div", "qual")) if (type == "qual") { warn("Using a discrete colour palette in a binned scale.\n Consider using type = \"seq\" or type = \"div\" instead") } binned_scale(aesthetics, "fermenter", binned_pal(scales::brewer_pal(type, palette, direction)), na.value = na.value, guide = guide, ...) } scale_shadowcolour_identity <- function(..., guide = "none", aesthetics = "shadowcolour") { sc <- discrete_scale(aesthetics, "identity", scales::identity_pal(), ..., guide = guide, super = ScaleDiscreteIdentity) sc } scale_shadowcolour_continuous <- function(..., type = getOption("ggplot2.continuous.colour", default = "gradient")) { if (is.function(type)) { type(...) } else if (identical(type, "gradient")) { scale_shadowcolour_gradient(...) } else if (identical(type, "viridis")) { scale_shadowcolour_viridis_c(...) } else { abort("Unknown scale type") } } scale_shadowcolour_binned <- function(..., type = getOption("ggplot2.binned.colour", default = getOption("ggplot2.continuous.colour", default = "gradient"))) { if (is.function(type)) { type(...) } else if (identical(type, "gradient")) { scale_shadowcolour_steps(...) } else if (identical(type, "viridis")) { scale_shadowcolour_viridis_b(...) } else { abort("Unknown scale type") } } scale_shadowcolour_steps <- function(..., low = " na.value = "grey50", guide = "coloursteps", aesthetics = "shadowcolour") { binned_scale(aesthetics, "steps", scales::seq_gradient_pal(low, high, space), na.value = na.value, guide = guide, ...) } scale_shadowcolour_steps2 <- function(..., low = muted("red"), mid = "white", high = muted("blue"), midpoint = 0, space = "Lab", na.value = "grey50", guide = "coloursteps", aesthetics = "shadowcolour") { binned_scale(aesthetics, "steps2", scales::div_gradient_pal(low, mid, high, space), na.value = na.value, guide = guide, rescaler = mid_rescaler(mid = midpoint), ...) } scale_shadowcolour_stepsn <- function(..., colours, values = NULL, space = "Lab", na.value = "grey50", guide = "coloursteps", aesthetics = "shadowcolour", colors) { colours <- if (missing(colours)) colors else colours binned_scale(aesthetics, "stepsn", scales::gradient_n_pal(colours, values, space), na.value = na.value, guide = guide, ...) } scale_shadowcolour_gradient <- function(..., low = " na.value = "grey50", guide = "colourbar", aesthetics = "shadowcolour") { continuous_scale(aesthetics, "gradient", scales::seq_gradient_pal(low, high, space), na.value = na.value, guide = guide, ...) } scale_shadowcolour_gradient2 <- function(..., low = muted("red"), mid = "white", high = muted("blue"), midpoint = 0, space = "Lab", na.value = "grey50", guide = "colourbar", aesthetics = "shadowcolour") { continuous_scale(aesthetics, "gradient2", scales::div_gradient_pal(low, mid, high, space), na.value = na.value, guide = guide, ..., rescaler = mid_rescaler(mid = midpoint)) } scale_shadowcolour_gradientn <- function(..., colours, values = NULL, space = "Lab", na.value = "grey50", guide = "colourbar", aesthetics = "shadowcolour", colors) { colours <- if (missing(colours)) colors else colours continuous_scale(aesthetics, "gradientn", scales::gradient_n_pal(colours, values, space), na.value = na.value, guide = guide, ...) } scale_shadowcolour_datetime <- function(..., low = " high = " space = "Lab", na.value = "grey50", guide = "colourbar") { datetime_scale( "shadowcolour", "time", palette = scales::seq_gradient_pal(low, high, space), na.value = na.value, guide = guide, ... ) } scale_shadowcolour_date <- function(..., low = " high = " space = "Lab", na.value = "grey50", guide = "colourbar") { datetime_scale( "shadowcolour", "date", palette = scales::seq_gradient_pal(low, high, space), na.value = na.value, guide = guide, ... ) } scale_shadowcolour_grey <- function(..., start = 0.2, end = 0.8, na.value = "red", aesthetics = "shadowcolour") { discrete_scale(aesthetics, "grey", scales::grey_pal(start, end), na.value = na.value, ...) } scale_shadowcolour_viridis_d <- function(..., alpha = 1, begin = 0, end = 1, direction = 1, option = "D", aesthetics = "shadowcolour") { discrete_scale( aesthetics, "viridis_d", scales::viridis_pal(alpha, begin, end, direction, option), ... ) } scale_shadowcolour_viridis_c <- function(..., alpha = 1, begin = 0, end = 1, direction = 1, option = "D", values = NULL, space = "Lab", na.value = "grey50", guide = "colourbar", aesthetics = "shadowcolour") { continuous_scale( aesthetics, "viridis_c", scales::gradient_n_pal( scales::viridis_pal(alpha, begin, end, direction, option)(6), values, space ), na.value = na.value, guide = guide, ... ) } scale_shadowcolour_viridis_b <- function(..., alpha = 1, begin = 0, end = 1, direction = 1, option = "D", values = NULL, space = "Lab", na.value = "grey50", guide = "coloursteps", aesthetics = "shadowcolour") { binned_scale( aesthetics, "viridis_b", scales::gradient_n_pal( scales::viridis_pal(alpha, begin, end, direction, option)(6), values, space ), na.value = na.value, guide = guide, ... ) } scale_shadowcolour_ordinal <- scale_shadowcolour_viridis_d scale_shadowcolour_manual <- function(..., values, aesthetics = "shadowcolour", breaks = waiver()) { manual_scale(aesthetics, values, breaks, ...) }
expected <- eval(parse(text="numeric(0)")); test(id=0, code={ argv <- eval(parse(text="list(logical(0))")); do.call(`cos`, argv); }, o=expected);
if(interactive()){ data(mstData) data(crtData) outputSRT <- srtFREQ(Posttest~ Intervention + Prettest, intervention = "Intervention",data = mstData) print(outputSRT) outputSRTB <- srtBayes(Posttest~ Intervention + Prettest, intervention = "Intervention", data = mstData) print(outputSRTB) outputMST <- mstFREQ(Posttest~ Intervention + Prettest, random = "School", intervention = "Intervention", data = mstData) print(outputMST) outputCRT <- crtFREQ(Posttest~ Intervention + Prettest, random = "School", intervention = "Intervention", data = crtData) print(outputCRT) }
print.earth <- function(x, digits=getOption("digits"), fixed.point=TRUE, ...) { form <- function(x, pad) { sprint("%-*s", digits+pad, format(if(abs(x) < 1e-20) 0 else x, digits=digits)) } check.classname(x, substitute(x), "earth") warn.if.dots(...) remind.user.bpairs.expansion <- !is.null(x$glm.bpairs) && !is.null(x$ncases.after.expanding.bpairs) if(!is.null(x$glm.list)) { if(remind.user.bpairs.expansion) printf("The following stats are for the binomial pairs without expansion (%g cases):\n", NROW(x$residuals)) print_earth_glm(x, digits, fixed.point, prefix.space=remind.user.bpairs.expansion) } nresp <- NCOL(x$coefficients) is.cv <- !is.null(x$cv.list) nselected <- length(x$selected.terms) if(is.null(x$glm.list)) { if(remind.user.bpairs.expansion) printf(" ") cat("Selected ") } else { if(remind.user.bpairs.expansion) printf("The following stats are for the binomial pairs after expansion (%g cases):\n ", x$ncases.after.expanding.bpairs) cat("Earth selected ") } cat(length(x$selected.terms), "of", nrow(x$dirs), "terms, and", get.nused.preds.per.subset(x$dirs, x$selected.terms), "of", ncol(x$dirs), "predictors") if(x$pmethod != "backward") printf(" (pmethod=\"%s\")", x$pmethod) if(!is.null(x$nprune)) printf(" (nprune=%g)", x$nprune) cat("\n") print_termcond(x, remind.user.bpairs.expansion) print_one_line_evimp(x, remind.user.bpairs.expansion) try(print_offset(x, digits, remind.user.bpairs.expansion)) try(print_weights(x, digits, remind.user.bpairs.expansion)) nterms.per.degree <- get.nterms.per.degree(x, x$selected.terms) cat0(if(remind.user.bpairs.expansion) " " else "") cat("Number of terms at each degree of interaction:", nterms.per.degree) cat0(switch(length(nterms.per.degree), " (intercept only model)", " (additive model)"), "\n") if(nresp > 1) print_earth_multiple_response(x, digits, fixed.point) else print_earth_single_response(x, digits, fixed.point, remind.user.bpairs.expansion) if(x$pmethod == "cv") { print_would_have(x, if(nresp > 1) digits+1 else digits) } invisible(x) } print_earth_single_response <- function(x, digits, fixed.point, prefix.space) { is.cv <- !is.null(x$cv.list) spacer <- if(is.cv) " " else " " nselected <- length(x$selected.terms) if(prefix.space) printf(" ") if(!is.null(x$glm.list)) cat0("Earth ") if(x$pmethod == "cv") { ilast <- nrow(x$cv.oof.rsq.tab) cat0("GRSq ", format(x$grsq, digits=digits), spacer, "RSq ", format(x$rsq, digits=digits), spacer, "mean.oof.RSq ", format(x$cv.oof.rsq.tab[ilast,nselected], digits=digits), " (sd ", format(sd(x$cv.oof.rsq.tab[-ilast,nselected], na.rm=TRUE), digits=3), ")\n") } else { ilast <- nrow(x$cv.rsq.tab) cat0("GCV ", format(x$gcv, digits=digits), spacer, "RSS ", format(x$rss, digits=digits), spacer, "GRSq ", format(x$grsq, digits=digits), spacer, "RSq ", format(x$rsq, digits=digits)) if(is.cv) cat0(spacer, "CVRSq ", format(x$cv.rsq.tab[ilast,ncol(x$cv.rsq.tab)], digits=digits)) cat("\n") } } print_earth_multiple_response <- function(x, digits, fixed.point) { nresp <- NCOL(x$coefficients) stopifnot(nresp > 1) is.cv <- !is.null(x$cv.list) nselected <- length(x$selected.terms) mat <- matrix(nrow=nresp+1, ncol=4 + is.cv + (x$pmethod == "cv")) rownames(mat) <- c(colnames(x$fitted.values), "All") colnames <- c("GCV", "RSS", "GRSq", "RSq") if(is.cv) colnames <- c(colnames, if(x$pmethod=="cv") c(" mean.oof.RSq", "sd(mean.oof.RSq)") else "CVRSq") colnames(mat) <- colnames for(iresp in seq_len(nresp)) { mat[iresp,1:4] <- c(x$gcv.per.response[iresp], x$rss.per.response[iresp], x$grsq.per.response[iresp], x$rsq.per.response[iresp]) if(is.cv) { if(x$pmethod == "cv") { ilast <- nrow(x$cv.oof.rsq.tab) mat[iresp,5] <- NA mat[iresp,6] <- NA } else { ilast <- nrow(x$cv.rsq.tab) mat[iresp,5] <- x$cv.rsq.tab[ilast,iresp] } } } mat[nresp+1,1:4] <- c(x$gcv, x$rss, x$grsq, x$rsq) if(is.cv) { if(x$pmethod == "cv") { mat[nresp+1,5] <- signif(x$cv.oof.rsq.tab[ilast,nselected], digits=digits) mat[nresp+1,6] <- signif(sd(x$cv.oof.rsq.tab[-ilast,nselected], na.rm=TRUE), digits=digits) } else mat[nresp+1,5] <- x$cv.rsq.tab[ilast,ncol(x$cv.rsq.tab)] } cat("\n") if(!is.null(x$glm.list)) cat("Earth\n") if(fixed.point) mat <- my.fixed.point(mat, digits) df <- as.data.frame(mat) df[is.na(df)] <- "" print(df, digits=digits) } print_termcond <- function(object, prefix.space) { if(prefix.space) printf(" ") printf("Termination condition: ") if(is.null(object$termcond)) { printf("Unknown\n") return() } termcond <- object$termcond check.numeric.scalar(termcond) nk <- object$nk check.numeric.scalar(nk) nterms.before.pruning <- nrow(object$dirs) check.numeric.scalar(nterms.before.pruning) thresh <- object$thresh check.numeric.scalar(thresh) terms.string = if(nterms.before.pruning == 1) "term" else "terms" if(termcond == 1) printf("Reached nk %d\n", nk) else if(termcond == 2) printf("GRSq -Inf at %d %s\n", nterms.before.pruning, terms.string) else if(termcond == 3) printf("GRSq -10 at %d %s\n", nterms.before.pruning, terms.string) else if(termcond == 4) printf("RSq changed by less than %g at %d %s\n", thresh, nterms.before.pruning, terms.string) else if(termcond == 5) printf("Reached maximum RSq %.4f at %d %s\n", 1-thresh, nterms.before.pruning, terms.string) else if(termcond == 6) printf("No new term increases RSq at %d %s\n", nterms.before.pruning, terms.string) else if(termcond == 7) printf("Reached nk %d\n", nk) else printf("Unknown (termcond %d)\n", termcond) } print.summary.earth <- function( x = stop("no 'x' argument"), details = x$details, decomp = x$decomp, digits = x$digits, fixed.point = x$fixed.point, newdata = x$newdata, ...) { nresp <- NCOL(x$coefficients) warn.if.dots(...) if(!is.null(newdata)) { printf("RSq %.3f on newdata (%d cases)\n", x$newrsq, NROW(newdata)) if(!is.null(x$varmod)) { printf("\n") print.varmod(x$varmod, newdata=newdata, digits=digits) } return(invisible(x)) } printcall("Call: ", x$call) cat("\n") new.order <- reorder.earth(x, decomp=decomp) if(is.null(x$glm.stats) || details) print_earth_coefficients(x, digits, fixed.point, new.order) if(!is.null(x$glm.stats)) print_summary_earth_glm(x, details, digits, fixed.point, new.order) print.earth(x, digits) if(!is.null(x$cv.list) && x$pmethod != "cv") print_cv(x) if(!is.null(x$varmod)) { printf("\nvarmod: ") x$varmod <- print.varmod(x$varmod, digits=digits) } invisible(x) } print_offset <- function(object, digits, prefix.space) { terms <- object$terms if(is.null(terms)) return() offset.index <- attr(terms, "offset") if(is.null(offset.index) || is.null(object$offset)) return() varnames <- rownames(attr(terms, "factors")) if(is.null(varnames) || offset.index < 1 || offset.index > length(varnames)) return() offset.term <- varnames[offset.index] offset.term.name <- substring(offset.term, 8, nchar(offset.term)-1) if(prefix.space) printf(" ") print_values("Offset", offset.term.name, object$offset, digits) } print_weights <- function(object, digits, prefix.space) { if(is.null(object$weights)) return() if(prefix.space) printf(" ") print_values("Weights", NULL, object$weights, digits) } print_values <- function(name, term.name, values, digits) { s <- if(is.null(term.name)) paste0(name, ": ") else paste0(name, ": ", strip.space.collapse(term.name), " with values ") cat0(s) n <- min(30, length(values)) stopifnot(n > 0) svalues <- character(n) maxlen <- max(25, getOption("width") - nchar(s) - 5) s <- if(!is.null(term.name) && substring(term.name, 1, 4) == "log(") { for(i in seq_along(svalues)) svalues[i] <- strip.space(format(exp(values[i]), digits=digits)) paste.trunc("log(", svalues, ")", sep="", collapse=", ", maxlen=maxlen) } else { for(i in seq_along(svalues)) svalues[i] <- strip.space(format(values[i], digits=digits)) paste.trunc(svalues, sep="", collapse=", ", maxlen=maxlen) } cat0(s, "\n") } print_would_have <- function(x, digits) { form <- function(x) format(x, digits=digits) nselected <- length(x$backward.selected.terms) ilast <- nrow(x$cv.oof.rsq.tab) cat0("\npmethod=\"backward\" would have selected", if(nselected == length(x$selected.terms)) " the same model" else "", ":\n ", nselected, " terms ", get.nused.preds.per.subset(x$dirs, x$backward.selected.terms), " preds, GRSq ", form(get.rsq(x$gcv.per.subset[nselected], x$gcv.per.subset[1])), " RSq ", form(get.rsq(x$rss.per.subset[nselected], x$rss.per.subset[1])), " mean.oof.RSq ", form(x$cv.oof.rsq.tab[ilast, nselected]), "\n") if(anyNA(x$cv.oof.rsq.tab[ilast, nselected])) printf( " (mean.oof.RSq is NA because most fold models have less than %g terms)\n", nselected) } print_earth_coefficients <- function(x, digits, fixed.point, new.order) { nresp <- NCOL(x$coefficients) if(!is.null(x$strings)) { resp.names <- colnames(x$fitted.values) for(iresp in seq_len(nresp)) { cat0(resp.names[iresp], " =\n") cat(x$strings[iresp]) cat("\n") } } else { rownames(x$coefficients) <- spaceout(rownames(x$coefficients)) coef <- x$coefficients[new.order, , drop=FALSE] if(fixed.point) coef <- my.fixed.point(coef, digits) if(!is.null(x$glm.list)) cat("Earth coefficients\n") else if(nresp == 1) colnames(coef) = "coefficients" print(coef, digits=digits) cat("\n") } } print_summary_earth_glm <- function(x, details, digits, fixed.point, new.order) { nresp <- NCOL(x$coefficients) resp.names <- colnames(x$fitted.values) if(!is.null(x$strings)) { for(iresp in seq_len(nresp)) { g <- x$glm.list[[iresp]] cat("GLM ") cat0(resp.names[iresp], " =\n") cat(x$strings[nresp+iresp]) cat("\n") } } else { cat("GLM coefficients\n") rownames(x$glm.coefficients) <- spaceout(rownames(x$glm.coefficients)) coef <- x$glm.coefficients[new.order, , drop=FALSE] if(fixed.point) coef <- my.fixed.point(coef, digits) print(coef, digits=digits) cat("\n") } if(details) for(iresp in seq_len(nresp)) print_glm_details(x$glm.list[[iresp]], nresp, digits, my.fixed.point, resp.names[iresp]) } summary.earth <- function( object = stop("no 'object' argument"), details = FALSE, style = c("h", "pmax", "max", "C", "bf"), decomp = "anova", digits = getOption("digits"), fixed.point = TRUE, newdata = NULL, ...) { check.classname(object, substitute(object), "earth") details <- check.boolean(details) fixed.point <- check.boolean(fixed.point) rval <- object rval$strings <- switch(match.arg1(style, "style"), "h" = { stop.if.dots(...) }, "pmax" = format.earth(x=object, style=style, decomp=decomp, digits=digits, ...), "max" = format.earth(x=object, style=style, decomp=decomp, digits=digits, ...), "C" = format.earth(x=object, style=style, decomp=decomp, digits=digits, ...), "bf" = format.earth(x=object, style=style, decomp=decomp, digits=digits, ...)) rval$details <- details rval$decomp <- decomp rval$digits <- digits rval$fixed.point <- fixed.point if(!is.null(newdata)) { rval$newdata <- newdata rval$newrsq <- plotmo::plotmo_rsq(object, newdata, ...) } is.glm <- !is.null(object$glm.list) class(rval) <- c("summary.earth", "earth") rval } spaceout <- function(rownames.) { rownames. <- gsub("\\*", " * ", rownames.) rownames. <- gsub("--", "- -", rownames.) gsub("`", "", rownames.) } get.nterms.per.degree <- function(object, which.terms = object$selected.terms) { check.classname(object, substitute(object), "earth") check.which.terms(object$dirs, which.terms) degrees.per.term <- get.degrees.per.term(object$dirs[which.terms, , drop=FALSE]) max.degree <- max(degrees.per.term) nterms.per.degree <- repl(0, max.degree+1) for(i in 0:max.degree) nterms.per.degree[i+1] <- sum(degrees.per.term == i) names(nterms.per.degree) <- 0:max.degree nterms.per.degree }
context("polygon") test_that("add_polygon accepts multiple objects", { testthat::skip_on_cran() geo <- '[{"type":"Feature","properties":{"elevation":0,"fill_colour":" poly <- '[{"elevation":0,"fill_colour":" set_token("abc") m <- mapdeck() sf <- spatialwidget::widget_melbourne[ spatialwidget::widget_melbourne$SA2_NAME == "South Yarra - West", ] attr( sf, "class" ) <- c("sf", "data.frame") df <- sfheaders::sf_to_df( spatialwidget::widget_melbourne, fill = T ) df <- df[ df$SA2_NAME == "South Yarra - West", ] sf <- sfheaders::sf_polygon( df, polygon_id = "polygon_id", linestring_id = "linestring_id", x = "x", y = "y") p <- add_polygon(map = m, data = sf, digits = 7) expect_equal( as.character( p$x$calls[[1]]$args[[2]] ), geo ) })
diat_morpho <- function(resultLoad, isRelAb = FALSE){ numcloroplastos.result <- shpcloroplastos.result <- biovol.val.result <- NULL if(missing(resultLoad)) { print("Please run the diat_loadData() function first to enter your species data in the correct format") if (missing(resultLoad)){ stop("Calculations cancelled") } } sampleNames <- resultLoad[[3]] resultsPath <- resultLoad[[4]] taxaIn <- resultLoad[[5]] if (nrow(taxaIn)==0){ print("No species were recognized for morphology calculations") print("Morphology data will not be available") morphoresultTable <- NULL return(morphoresultTable) } lastcol <- which(colnames(taxaIn)=="species") if (isRelAb == FALSE) { taxaInRA <- taxaIn setDT(taxaInRA) setnafill(x = taxaInRA[,1:(lastcol-1)], fill = 0) rel_abu = apply(taxaInRA[,1:(lastcol-1)], 2, function(x) round(x / sum(x) * 100, 2)) taxaInRA = cbind(rel_abu, taxaInRA[, lastcol:ncol(taxaInRA)]) } else { taxaInRA <- taxaIn } taxaInRA_samples = taxaInRA[,1:(lastcol-1)] print("Calculating chloroplasts and biovolume") pb <- txtProgressBar(min = 1, max = 3, style = 3) for (i in 1:3){ lp_var = switch(i, taxaInRA[, "chloroplast_number"], taxaInRA[, "chloroplast_shape"], taxaInRA[, "biovolume"]) prefix_name = switch(i, "chloroplasts -", "shape chloroplasts -", "Total Biovolume") final_name = switch(i, "numcloroplastos.result", "shpcloroplastos.result", "biovol.val.result") if (i == 3){ lp_data = taxaInRA_samples * unlist(lp_var) lp_data = lp_data[, lapply(.SD, sum, na.rm = T), .SDcols = 1:(lastcol-1)] } else { lp_data = taxaInRA_samples[, lapply(.SD, sum, na.rm = T), by = lp_var] } lp_data = data.table::transpose(lp_data) if (i == 3){ names(lp_data) = prefix_name } else { names(lp_data) = paste(prefix_name,unlist(lp_data[1,])) lp_data = lp_data[-1,] } if (i < 3) { lp_data = lp_data[, lapply(.SD, as.numeric)] lp_data = lp_data[, lapply(.SD, round, 4)] } rownames(lp_data) = sampleNames assign(x = final_name, value = lp_data) setTxtProgressBar(pb, i) } close(pb) names(numcloroplastos.result) morphoresultTable <- list(as.data.frame(numcloroplastos.result), as.data.frame(shpcloroplastos.result), as.data.frame(if (exists("biovol.val.result")) { biovol.val.result })) names(morphoresultTable) <- c("numcloroplastos.result", "shpcloroplastos.result", "biovol.val.result") return(morphoresultTable) }
herm_poly_diff_t <- function(t1, t2, pairwise_cors) { rho_bar1 <- mean(pairwise_cors) rho_bar2 <- mean(pairwise_cors^2) rho_bar3 <- mean(pairwise_cors^3) rho_bar4 <- mean(pairwise_cors^4) rho_bar5 <- mean(pairwise_cors^5) rho_bar6 <- mean(pairwise_cors^6) rho_bar7 <- mean(pairwise_cors^7) rho_bar8 <- mean(pairwise_cors^8) rho_bar9 <- mean(pairwise_cors^9) rho_bar10 <- mean(pairwise_cors^10) He1 <- (t1) * (t2) He3 <- (t1^3 - 3*t1) * (t2^3 - 3*t2) He5 <- (t1^5 - 10*t1^3 + 15*t1) * (t2^5 - 10*t2^3 + 15*t2) He7 <- (t1^7 - 21*t1^5 + 105*t1^3 - 105*t1) * (t2^7 - 21*t2^5 + 105*t2^3 - 105*t2) He9 <- (t1^9 - 36*t1^7 + 378*t1^5 - 1260*t1^3 + 945*t1) * (t2^9 - 36*t2^7 + 378*t2^5 - 1260*t2^3 + 945*t2) He0 <- 1 He2 <- (t1^2 - 1) * (t2^2 - 1) He4 <- (t1^4 - 6*t1^2 + 3) * (t2^4 - 6*t2^2 + 3) He6 <- (t1^6 - 15*t1^4 + 45*t1^2 - 15) * (t2^6 - 15*t2^4 + 45*t2^2 - 15) He8 <- (t1^8 - 28*t1^6 + 210*t1^4 - 420*t1^2 + 105) * (t2^8 - 28*t2^6 + 210*t2^4 - 420*t2^2 + 105) odds <- ( He1*rho_bar2/2 + He3*rho_bar4/24 + He5*rho_bar6/720 + He7*rho_bar8/40320 + He9*rho_bar10/3628800 ) evens <- ( He0*rho_bar1/1 + He2*rho_bar3/6 + He4*rho_bar5/120 + He6*rho_bar7/5040 + He8*rho_bar9/362880 ) sum_term <- odds + evens return(sum_term) }
topo <- function(nm, simplify = TRUE) { out <- nm[["topology"]] if (simplify && length(unique(out)) == 1) { return(unique(out)[[1]]) } return(out) } prop_family <- function(nm, quiet = FALSE) { z <- attr(nm, "prop_family") if (!quiet) { describe_z_eta("eta", z) } z } size_family <- function(nm, quiet = FALSE) { z <- attr(nm, "size_family") if (!quiet) { describe_z_eta("zeta", z) } z } groups.networkModel <- function(x) { nm_get_groups(x, error = FALSE) } priors <- function(nm, fix_set_params = FALSE, quiet = FALSE) { if (fix_set_params) { set_params <- attr(nm, "parameterValues") if (!is.null(set_params)) { for (i in seq_len(nrow(set_params))) { myPrior <- constant_p(value = set_params[["value"]][i]) nm <- set_prior(nm, myPrior, param = set_params[["parameter"]][i], use_regexp = FALSE, quiet = quiet) } } } out <- attr(nm, "priors") return(out) } missing_priors <- function(nm) { p <- priors(nm) p <- p[sapply(p$prior, is.null), ] return(p) } params <- function(nm, simplify = FALSE) { stopifnot("parameters" %in% colnames(nm)) params <- dplyr::bind_rows(nm[["parameters"]]) if (simplify) { return(sort(unique(params[["in_model"]]))) } if (!"value" %in% colnames(params)) { params[["value"]] <- as.numeric(rep(NA, nrow(params))) } params <- unique(params[, c("in_model", "value")]) params <- params[order(params[["in_model"]]), ] if (!all(table(params[["in_model"]]) == 1)) { stop("Some parameters have two different values assigned to them.") } return(params) } comps <- function(nm) { comps <- nm[, "topology"] comps$compartments <- lapply(comps$topology, colnames) return(comps[["compartments"]]) }
sigmoid <- function(z) { z <- as.matrix(z) g <- matrix(0,dim(z)[1],dim(z)[2]) g }
source("ESEUR_config.r") library("VGAM") plot_layout(3, 2, max_width=6, max_height=11.0) par(mar=c(1.0, 1.0, 1, 0.5)) pal_col=rainbow(2) NUM_REPLICATE=4000 plot_sample=function(sample_size, samp_mean, dist_mean, dist_str) { samp_den=density(samp_mean) actual_sd=dist_mean/sqrt(sample_size) x_bounds=c(dist_mean-4*actual_sd, dist_mean+4*actual_sd) xpoints=seq(0, max(x_bounds), by=0.01) norm_sd=dist_mean/sqrt(sample_size) ypoints=dnorm(xpoints, mean=dist_mean, sd=norm_sd) y_bounds=range(c(samp_den$y, ypoints)) plot(samp_den, col=pal_col[1], fg="grey", col.axis="grey", yaxt="n", bty="n", yaxt="n", main="", xlab="", ylab="", xlim=x_bounds, ylim=y_bounds) q=quantile(samp_mean, c(0.025, 0.975)) lines(c(q[1], q[1]), c(0, max(y_bounds)/3), col=pal_col[1]) lines(c(q[2], q[2]), c(0, max(y_bounds)/3), col=pal_col[1]) lines(xpoints, ypoints, col=pal_col[2], fg="grey") q=c(dist_mean-norm_sd*1.96, dist_mean+norm_sd*1.96) lines(c(q[1], q[1]), c(0, max(y_bounds)/3), col=pal_col[2]) lines(c(q[2], q[2]), c(0, max(y_bounds)/3), col=pal_col[2]) legend(x="topright", legend=c(paste0("size=", sample_size)), title=dist_str, bty="n", cex=1.3) } exp_samp_dis=function(sample_size) { samp_mean=replicate(NUM_REPLICATE, mean(rexp(sample_size))) dist_mean=1 plot_sample(sample_size, samp_mean, dist_mean, "Exponential") } lnorm_samp_dis=function(sample_size) { samp_mean=replicate(NUM_REPLICATE, mean(rlnorm(sample_size))) dist_mean=exp(0.5) plot_sample(sample_size, samp_mean, dist_mean, "Lognormal") } pareto_samp_dis=function(sample_size) { p_shape=2 samp_mean=replicate(NUM_REPLICATE, mean(rpareto(sample_size, scale=1, shape=p_shape))) dist_mean=1*p_shape/(p_shape-1) plot_sample(sample_size, samp_mean, dist_mean, "Pareto") } exp_samp_dis(10) lnorm_samp_dis(10) pareto_samp_dis(20) exp_samp_dis(20) lnorm_samp_dis(20) pareto_samp_dis(200)
priormul <- function(alpha, PHI, nquad, df, ls){ n<-size(alpha)[1] mvari <- 0 resi <- matrix(0,n,1) for (i in 1:n){ tmp <- alpha[i,] tmp2 <-1 - tmp%*%PHI%*%transpose(tmp) tmp3 <- tmp%*%transpose(tmp) resi[i] <- tmp2/tmp3 } tmpmin <- min(resi) mvari <- tmpmin resi <- resi - (mvari*matrix(1,n,1)) if (missing(df)==TRUE || missing(ls)==TRUE){ df <- 5 ls <- round(mvari*3) if (ls == 0){ ls <- 1 } } nodth <- creanodos(-4,4,nquad) nodichi<- creanchi(0.02,4,nquad,df,ls) if (df == 5){ var_nodos <- 0.4159 } if (df == 6){ var_nodos <- 0.3832 } if (df == 10){ var_nodos <- 0.2631 } OUT<-list("mvari" = mvari, "resi" = resi, "nodth" = nodth, "nodichi" = nodichi, "var_nodos" = var_nodos) return(OUT) }
txt <- " abline acf approx arrows axis box browseURL capture.output col2rgb colorRamp colors contour contourLines cor demo density dev.cur dev.new dev.off extendrange fix frame grey hist legend lines make.packages.html median mtext nlm nlminb optim pairs par plot plot.new points polygon qnorm rect rgb rnorm runif segments str strwidth symbols text update vignette " txt = gsub("\\n"," ",txt) imports_for_undefined_globals <- function(txt, lst, selective = TRUE) { if(!missing(txt)) lst <- scan(what = character(), text = txt, quiet = TRUE) nms <- lapply(lst, find) ind <- sapply(nms, length) > 0L imp <- split(lst[ind], substring(unlist(nms[ind]), 9L)) if(selective) { sprintf("importFrom(%s)", vapply(Map(c, names(imp), imp), function(e) paste0("\"", e, "\"", collapse = ", "), "")) } else { sprintf("import(\"%s\")", names(imp)) } }
dd_hyperbolic <- hBayesDM_model( task_name = "dd", model_name = "hyperbolic", model_type = "", data_columns = c("subjID", "delay_later", "amount_later", "delay_sooner", "amount_sooner", "choice"), parameters = list( "k" = c(0, 0.1, 1), "beta" = c(0, 1, 5) ), regressors = NULL, postpreds = c("y_pred"), preprocess_func = dd_preprocess_func)
globalVariables(c("grp", "for.split", ".", "pos", "prob", "pos2", "allele","parents.homologs", "progeny.homologs", "homolog")) globalVariables(c("V1", "V2", "V3", "V4", "H1_P1", "H1_P2", "H2_P1", "H2_P2", "P1_H1", "P1_H2", "P2_H1", "P2_H2")) parents_haplotypes <- function(..., group_names=NULL){ input <- list(...) if(length(input) == 0) stop("argument '...' missing, with no default") if(is(input[[1]], "sequence")) input.map <- input else input.map <- unlist(input, recursive = FALSE) if(!all(sapply(input.map, function(x) is(x, "sequence")))) stop(paste("Input objects must be of 'sequence' class. \n")) if(is.null(group_names)) group_names <- paste("Group",seq(input.map), sep = " - ") if(all(sapply(input, function(x) is(x, "sequence")))){ n <- length(sapply(input, function(x) is(x, "sequence"))) } else n <- 1 input_temp <- input out_dat <- data.frame() for(z in 1:n){ if(all(sapply(input_temp, function(x) is(x, "sequence")))) input <- input_temp[[z]] marnames <- colnames(input$data.name$geno)[input$seq.num] if(length(input$seq.rf) == 1 && input$seq.rf == -1) { warning("\nParameters not estimated.\n\n") } else { link.phases <- matrix(NA,length(input$seq.num),2) link.phases[1,] <- rep(1,2) for (i in 1:length(input$seq.phases)) { switch(EXPR=input$seq.phases[i], link.phases[i+1,] <- link.phases[i,]*c(1,1), link.phases[i+1,] <- link.phases[i,]*c(1,-1), link.phases[i+1,] <- link.phases[i,]*c(-1,1), link.phases[i+1,] <- link.phases[i,]*c(-1,-1), ) } marnumbers <- input$seq.num distances <- c(0,cumsum(get(get(".map.fun", envir=.onemapEnv))(input$seq.rf))) if(is(input$data.name, c("outcross", "f2"))){ link.phases <- apply(link.phases,1,function(x) paste(as.character(x),collapse=".")) parents <- matrix("",length(input$seq.num),4) for (i in 1:length(input$seq.num)) parents[i,] <- return_geno(input$data.name$segr.type[input$seq.num[i]],link.phases[i]) out_dat_temp <- data.frame(group= group_names[z], mk.number = marnumbers, mk.names = marnames, dist = as.numeric(distances), P1_1 = parents[,1], P1_2 = parents[,2], P2_1 = parents[,3], P2_2 = parents[,4]) out_dat <- rbind(out_dat, out_dat_temp) } else if(is(input$data.name, c("backcross", "riself", "risib"))){ warning("There is only a possible phase for this cross type\n") } else warning("invalid cross type") } } return(out_dat) } progeny_haplotypes <- function(..., ind = 1, group_names=NULL, most_likely = FALSE){ input <- list(...) if(length(input) == 0) stop("argument '...' missing, with no default") if(is(input[[1]], "sequence")) input.map <- input else input.map <- unlist(input, recursive = FALSE) if(!all(sapply(input.map, function(x) is(x, "sequence")))) stop(paste("Input objects must be of 'sequence' class. \n")) if(is.null(group_names)) group_names <- paste("Group",seq(input.map), sep = " - ") n.mar <- sapply(input.map, function(x) length(x$seq.num)) n.ind <- sapply(input.map, function(x) ncol(x$probs))/n.mar ind.names <- lapply(input.map, function(x) rownames(x$data.name$geno)) ind.names <- unique(unlist(ind.names)) if(length(unique(n.ind)) != 1) stop("At least one of the sequences have different number of individuals in dataset.") n.ind <- unique(n.ind) if(is.null(ind.names)) ind.names <- 1:n.ind if(ind[1] == "all"){ ind <- 1:n.ind } probs <- lapply(1:length(input.map), function(x) cbind(ind = rep(1:n.ind, each = n.mar[x]), grp = group_names[x], marker = input.map[[x]]$seq.num, pos = c(0,cumsum(kosambi(input.map[[x]]$seq.rf))), as.data.frame(t(input.map[[x]]$probs)))) probs <- lapply(probs, function(x) split.data.frame(x, x$ind)[ind]) if(is(input.map[[1]]$data.name, "outcross") | is(input.map[[1]]$data.name, "f2")){ phase <- list('1' = c(1,2,3,4), '2' = c(2,1,4,3), '3' = c(3,4,1,2), "4" = c(4,3,2,1)) seq.phase <- lapply(input.map, function(x) c(1,x$seq.phases)) for(g in seq_along(input.map)){ for(i in seq_along(ind)){ for(m in seq(n.mar[g])){ probs[[g]][[i]][m:n.mar[g],5:8] <- probs[[g]][[i]][m:n.mar[g],phase[[seq.phase[[g]][m]]]+4] } } } probs <- do.call(rbind,lapply(probs, function(x) do.call(rbind, x))) if(most_likely){ probs[,5:8] <- t(apply(probs[,5:8], 1, function(x) as.numeric(x == max(x))/sum(x == max(x)))) } if(is(input.map[[1]]$data.name, "outcross")){ probs <- probs %>% mutate(P1_H1 = V1 + V2, P1_H2 = V3 + V4, P2_H1 = V1 + V3, P2_H2 = V2 + V4) %>% select(ind, marker, grp, pos, P1_H1, P1_H2, P2_H1, P2_H2) %>% gather(parents, prob, P1_H1, P1_H2, P2_H1, P2_H2) new.col <- t(sapply(strsplit(probs$parents, "_"), "[", 1:2)) colnames(new.col) <- c("parents", "parents.homologs") cross <- "outcross" } else { probs <- probs %>% mutate(H1_P1 = V1 + V2, H1_P2 = V3 + V4, H2_P1 = V1 + V3, H2_P2 = V2 + V4) %>% select(ind, marker, grp, pos, H1_P1, H1_P2, H2_P1, H2_P2) %>% gather(parents, prob, H1_P1, H1_P2, H2_P1, H2_P2) new.col <- t(sapply(strsplit(probs$parents, "_"), "[", 1:2)) colnames(new.col) <- c("progeny.homologs", "parents") cross <- "f2" } } else { probs <- do.call(rbind,lapply(probs, function(x) do.call(rbind, x))) if(most_likely){ probs[,5:6] <- t(apply(probs[,5:6], 1, function(x) as.numeric(x == max(x))/sum(x == max(x)))) } if (is(input.map[[1]]$data.name, c("backcross")) | is(input.map[[1]]$data.name, c("riself", "risib"))){ if(is(input.map[[1]]$data.name, c("backcross"))){ cross <- "backcross" probs <- probs %>% mutate(H1_P1 = V1 + V2, H1_P2 = 0, H2_P1 = V2, H2_P2 = V1) } else if (is(input.map[[1]]$data.name, c("riself", "risib"))){ cross <- "rils" probs <- probs %>% mutate(H1_P1 = V1, H1_P2 = V2, H2_P1 = V1, H2_P2 = V2) } probs <- probs %>% select(ind, marker, grp, pos, H1_P1, H1_P2, H2_P1, H2_P2) %>% gather(parents, prob, H1_P1, H1_P2, H2_P1, H2_P2) new.col <- t(sapply(strsplit(probs$parents, "_"), "[", 1:2)) colnames(new.col) <- c("progeny.homologs", "parents") } } probs <- cbind(probs, new.col) probs <- cbind(probs[,-5], allele = probs[,5]) probs <- as.data.frame(probs) probs$marker = colnames(input.map[[1]]$data.name$geno)[probs$marker] probs$ind <- ind.names[probs$ind] if(most_likely) flag <- "most.likely" else flag <- "by.probs" class(probs) <- c("onemap_progeny_haplotypes", cross, "data.frame", flag) return(probs) } plot.onemap_progeny_haplotypes <- function(x, col = NULL, position = "stack", show_markers = TRUE, main = "Genotypes", ncol=4, ...){ if(is(x, "outcross")){ n <- c("H1" = "P1", "H2" = "P2") progeny.homologs <- names(n)[match(x$parents, n)] probs <- cbind(x, progeny.homologs) } else { probs <- x } probs <- probs %>% group_by(ind, grp, allele) %>% do(rbind(.,.[nrow(.),])) %>% do(mutate(., pos2 = c(0,pos[-1]-diff(pos)/2), pos = c(pos[-nrow(.)], NA))) if(is(x, "outcross")){ p <- ggplot(probs, aes(x = pos, col=allele, alpha = prob)) + ggtitle(main) } else { p <- ggplot(probs, aes(x = pos, col=parents, alpha = prob)) + ggtitle(main) } p <- p + facet_wrap(~ ind + grp , ncol = ncol) + scale_alpha_continuous(range = c(0,1)) + guides(fill = guide_legend(reverse = TRUE)) + labs(alpha = "Prob", col = "Allele", x = "position (cM)") if(is.null(col)) p <- p + scale_color_brewer(palette="Set1") else p <- p + scale_color_manual(values = rev(col)) if(position == "stack"){ p <- p + geom_line(aes(x = pos2, y = progeny.homologs), size = ifelse(show_markers, 4, 5)) + labs(y = "progeny homologs") if(show_markers) p <- p + geom_point(aes(y = progeny.homologs), size = 5, stroke = 2, na.rm = T, shape = "|") } if(position == "split"){ p <- p + geom_line(aes(x = pos2, y = allele), size = ifelse(show_markers, 4, 5)) if(show_markers) p <- p + geom_point(aes(y = allele), size = 5, stroke = 2, na.rm = T, shape = "|") } return(p) } progeny_haplotypes_counts <- function(x){ if(!is(x, "onemap_progeny_haplotypes")) stop("Input need is not of class onemap_progeny_haplotyes") if(!is(x, "most.likely")) stop("The most likely genotypes must receive maximum probability (1)") cross <- class(x)[2] doubt <- x[which(x$prob == 0.5),] if(dim(doubt)[1] > 0){ repl <- x[which(x$prob == 0.5)-1,"prob"] x[which(x$prob == 0.5),"prob"] <- repl } x <- x[which(x$prob == 1),] x <- x[order(x$ind, x$grp, x$prob, x$parents,x$pos),] if(is(x, "outcross")){ counts <- x %>% group_by(ind, grp, parents.homologs) %>% mutate(seq = sequence(rle(as.character(parents))$length) == 1) %>% summarise(counts = sum(seq) -1) %>% ungroup() } else { counts <- x %>% group_by(ind, grp, progeny.homologs) %>% mutate(seq = sequence(rle(as.character(parents))$length) == 1) %>% summarise(counts = sum(seq) -1) %>% ungroup() } colnames(counts)[3] <- "homolog" class(counts) <- c("onemap_progeny_haplotypes_counts", cross, "data.frame") return(counts) } globalVariables(c("counts", "colorRampPalette", "alleles")) plot.onemap_progeny_haplotypes_counts <- function(x, by_homolog = FALSE, n.graphics =NULL, ncol=NULL, ...){ if(!is(x, "onemap_progeny_haplotypes_counts")) stop("Input need is not of class onemap_progeny_haplotyes_counts") p <- list() n.ind <- length(unique(x$ind)) nb.cols <- n.ind mycolors <- colorRampPalette(brewer.pal(12, "Paired"))(nb.cols) set.seed(20) mycolors <- sample(mycolors) if(by_homolog){ if(is.null(n.graphics) & is.null(ncol)){ n.ind <- dim(x)[1]/2 if(n.ind/25 <= 1) { n.graphics = 1 ncol=1 }else { n.graphics = round(n.ind/25,0) ncol=round(n.ind/25,0) } } size <- dim(x)[1] if(size%%n.graphics == 0){ div.n.graphics <- rep(1:n.graphics, each= size/n.graphics) } else { div.n.graphics <- c(rep(1:n.graphics, each = round(size/n.graphics,0)), rep(n.graphics, size%%n.graphics)) } y_lim_counts <- max(x$counts) div.n.graphics <- div.n.graphics[1:size] p <- x %>% mutate(div.n.graphics = div.n.graphics) %>% split(., .$div.n.graphics) %>% lapply(., function(x) ggplot(x, aes(x=homolog, y=counts)) + geom_bar(stat="identity", aes(fill=grp)) + theme_minimal() + coord_flip() + scale_fill_manual(values=mycolors) + facet_grid(ind ~ ., switch = "y") + theme(axis.title.y = element_blank(), axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1), strip.text.y.left = element_text(angle = 0)) + labs(fill="groups") + ylim(0,y_lim_counts) ) } else { x <- x %>% ungroup %>% group_by(ind, grp) %>% summarise(counts = sum(counts)) if(is.null(n.graphics) & is.null(ncol)){ if(n.ind/25 <= 1) { n.graphics = 1 ncol=1 }else { n.graphics = round(n.ind/25,0) ncol=round(n.ind/25,0) } } size <-n.ind if(size%%n.graphics == 0){ div.n.graphics <- rep(1:n.graphics, each= size/n.graphics) } else { div.n.graphics <- c(rep(1:n.graphics, each = round(size/n.graphics,0)),rep(n.graphics, size%%n.graphics)) } div.n.graphics <- div.n.graphics[1:n.ind] div.n.graphics <- rep(div.n.graphics, each = length(unique(x$grp))) x$ind <- factor(as.character(x$ind), levels = sort(as.character(unique(x$ind)))) temp <- x %>% ungroup() %>% group_by(ind) %>% summarise(total = sum(counts)) y_lim_counts <- max(temp$total) p <- x %>% ungroup() %>% mutate(div.n.graphics = div.n.graphics) %>% split(., .$div.n.graphics) %>% lapply(., function(x) ggplot(x, aes(x=ind, y=counts, fill=grp)) + geom_bar(stat="identity") + coord_flip() + scale_fill_manual(values=mycolors) + theme(axis.title.y = element_blank(), axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + labs(fill="groups") + ylim(0,y_lim_counts) ) } p <- ggarrange(plotlist = p, common.legend = T, label.x = 1, ncol = ncol, nrow = round(n.graphics/ncol,0)) return(p) }
setClass( "system_equilibrium", contains = "system_base", representation( delta = "numeric", mu_P = "matrix", var_P = "numeric", sigma_P = "numeric", h_P = "matrix", mu_Q = "matrix", var_Q = "numeric", sigma_Q = "numeric", h_Q = "matrix", rho_QP = "numeric", rho_1QP = "numeric", rho_2QP = "numeric", z_QP = "matrix", z_PQ = "matrix", llh = "matrix" ), prototype( llh = matrix(NA_real_) ) ) setMethod( "initialize", "system_equilibrium", function( .Object, specification, data, correlated_shocks, demand_initializer = NULL, supply_initializer = NULL) { .Object <- callNextMethod( .Object, specification, data, correlated_shocks, ifelse(is.null(demand_initializer), function(...) new("equation_basic", ...), demand_initializer ), ifelse(is.null(supply_initializer), function(...) new("equation_basic", ...), supply_initializer ) ) } ) setMethod( "show_implementation", signature(object = "system_equilibrium"), function(object) { callNextMethod(object) cat(sprintf( " %-18s: %s\n", "Market Clearing", paste0( quantity_variable(object@demand), " = ", prefixed_quantity_variable(object@demand), " = ", prefixed_quantity_variable(object@supply) ) )) } ) setMethod("set_parameters", signature(object = "system_equilibrium"), function(object, parameters) { object <- callNextMethod(object, parameters) object@delta <- object@supply@alpha - object@demand@alpha object <- calculate_system_moments(object) object@llh <- calculate_system_loglikelihood(object) object })
gjamPoints2Grid <- function(specs, xy, nxy = NULL, dxy = NULL, predGrid = NULL, effortOnly = TRUE){ dx <- dy <- nx <- ny <- NULL wna <- which(is.na(xy),arr.ind=T) if(length(wna) > 0){ wna <- unique(wna[,1]) } wna <- c(wna,which(is.na(specs))) if(length(wna) > 0){ specs <- specs[-wna] xy <- xy[-wna,] } if(length(nxy) == 1) nx <- ny <- nxy if(length(dxy) == 1) dx <- dy <- dxy if(is.null(nxy) & is.null(dxy) & is.null(predGrid)){ stop('must supply nxy or dxy or predGrid') } if(length(nxy) == 2) nx <- nxy[1]; ny <- nxy[2] if(length(dxy) == 2) dx <- dxy[1]; dy <- dxy[2] if(length(specs) != nrow(xy))stop('specs must have length = nrow(xy)') mr <- apply( apply(xy,2,range, na.rm=T), 2, diff ) if(!is.null(dxy)){ if(mr[1] < (3*dx) | mr[2] < (3*dy))stop('dxy too small') } .incidence2Grid(specs, lonLat = xy, nx, ny, dx, dy, predGrid, effortOnly) }
appendToCSV <- function(existing.csv, row.frame, append = TRUE, sep=",", row.names=FALSE, col.names=FALSE) { if (is.null(existing.csv) || file.exists(existing.csv) == FALSE) { warning("The file was not found or path was wrong, \"file.name=" + existing.csv+ "\"") return(FALSE) } row.names(row.frame) <- NULL write.table(row.frame, file = existing.csv, append=append, sep=sep, row.names=FALSE, col.names = FALSE) return(TRUE) }
yuima.PhamBreton.Alg<-function(a){ p<-length(a) gamma<-a[p:1] if(p>2){ gamma[p]<-a[1] alpha<-matrix(NA,p,p) for(j in 1:p){ if(is.integer(as.integer(j)/2)){ alpha[p,j]<-0 alpha[p-1,j]<-0 }else{ alpha[p,j]<-a[j] alpha[p-1,j]<-a[j+1]/gamma[p] } } for(n in (p-1):1){ gamma[n]<-alpha[n+1,2]-alpha[n,2] for(j in 1:n-1){ alpha[n-1,j]<-(alpha[n+1,j+2]-alpha[n,j+2])/gamma[n] } alpha[n-1,n-1]<-alpha[n+1,n+1]/gamma[n] } gamma[1]<-alpha[2,2] } return(gamma) } Diagnostic.Carma<-function(carma){ if(!is(carma@model,"yuima.carma")) yuima.stop("model is not a carma") if(!is(carma,"mle")) yuima.stop("object does not belong to yuima.qmle-class or yuima.carma.qmle-class ") param<-coef(carma) info <- carma@model@info numb.ar<-info@p name.ar<-paste([email protected],c(numb.ar:1),sep="") ar.par<-param[name.ar] statCond<-FALSE if(min(yuima.PhamBreton.Alg(ar.par[numb.ar:1]))>=0) statCond<-TRUE return(statCond) }
expected <- eval(parse(text="structure(integer(0), .Dim = c(0L, 2L))")); test(id=0, code={ argv <- eval(parse(text="list(structure(integer(0), .Dim = c(0L, 2L), .Dimnames = list(NULL, c(\"row\", \"col\"))), 0, 2, FALSE, NULL, FALSE, FALSE)")); .Internal(matrix(argv[[1]], argv[[2]], argv[[3]], argv[[4]], argv[[5]], argv[[6]], argv[[7]])); }, o=expected);
print.vandeWielTest <- function(x,eps=0.0001,pdigits=4,...){ cat("\nvan de Wiel test based on ",x$B," data splits\n") cat("\nTraining sample size: ",x$M,"\n") cat("\nTest sample size: ",x$N-x$M,"\n") if (length(x$testIBS)==2){ cat("\nP-values based on integrated Brier score residuals:") cat("\nRange of integration: [",x$testIBS[1],"--",x$testIBS[2],"]\n\n") ibsP <- sapply(x$Comparisons,function(x)x$pValueIBS) ibsP <- format.pval(ibsP,digits=pdigits,eps=eps) ibsMat <- matrix(ibsP,ncol=1) rownames(ibsMat) <- names(x$Comparisons) colnames(ibsMat) <- "p-value (IBS)" print(ibsMat,quote=FALSE,...) } NT <- length(x$testTimes) if (NT>0){ cat("\nMatrix of time point wise p-values:\n\n") if (NT>5){ showTimes <- sort(sample(x$testTimes)) showTimePos <- prodlim::sindex(jump.times=x$testTimes,eval.times=showTimes) } else{ showTimes <- x$testTimes showTimePos <- 1:NT } mat <- do.call("rbind",lapply(x$Comparisons,function(comp){ format.pval(comp$pValueTimes[showTimePos],digits=pdigits,eps=eps) })) colnames(mat) <- paste("t=",showTimes) print(mat,quote=FALSE,...) } invisible(mat) }
sampleOccurrences <- function(x, n, type = "presence only", extract.probability = FALSE, sampling.area = NULL, detection.probability = 1, correct.by.suitability = FALSE, error.probability = 0, bias = "no.bias", bias.strength = 50, bias.area = NULL, weights = NULL, sample.prevalence = NULL, replacement = FALSE, plot = TRUE) { results <- list(type = type, detection.probability = list( detection.probability = detection.probability, correct.by.suitability = correct.by.suitability), error.probability = error.probability, bias = NULL, replacement = replacement, original.distribution.raster = NULL, sample.plot = NULL) if(is.null(.Random.seed)) {stats::runif(1)} attr(results, "RNGkind") <- RNGkind() attr(results, "seed") <- .Random.seed if(inherits(x, "virtualspecies")) { if(inherits(x$occupied.area, "RasterLayer")) { sp.raster <- x$occupied.area } else if(inherits(x$pa.raster, "RasterLayer")) { sp.raster <- x$pa.raster } else stop("x must be:\n- a raster layer object\nor\n- the output list from functions generateRandomSp(), convertToPA() or limitDistribution()") } else if (inherits(x, "RasterLayer")) { sp.raster <- x if(extract.probability) { stop("Cannot extract probability when x is not a virtualspecies object. Set extract.probability = FALSE") } } else stop("x must be:\n- a raster layer object\nor\n- the output list from functions generateRandomSp(), convertToPA() or limitDistribution()") if(sp.raster@data@max > 1 | sp.raster@data@min < 0) { stop("There are values above 1 or below 0 in your presence/absence raster. Please make sure that the provided raster is a correct P/A raster and not a suitability raster.") } results$original.distribution.raster <- original.raster <- sp.raster if(!is.null(sample.prevalence)) { if(sample.prevalence < 0 | sample.prevalence > 1) { stop("Sample prevalence must be a numeric between 0 and 1") } } if(!is.null(sampling.area)) { if(is.character(sampling.area)) { worldmap <- rworldmap::getMap() if (any(!(sampling.area %in% c(levels(worldmap@data$SOVEREIGNT), levels(worldmap@data$REGION), levels(worldmap@data$continent))))) { stop("The choosen sampling.area is incorrectly spelled.\n Type 'levels(getMap()@data$SOVEREIGNT)', 'levels(worldmap@data$REGION)' and levels(worldmap@data$continent) to obtain valid names.") } sampling.area <- worldmap[which( worldmap@data$SOVEREIGNT %in% sampling.area | worldmap@data$REGION %in% sampling.area | worldmap@data$continent %in% sampling.area), ] } else if(!(inherits(sampling.area, c("SpatialPolygons", "SpatialPolygonsDataFrame", "Extent")))) { stop("Please provide to sampling.area either \n - the names of countries, region and/or continents in which to sample\n - a SpatialPolygons or SpatialPolygonsDataFrame\n - an extent\n in which the sampling will take place") } sample.area.raster1 <- rasterize(sampling.area, sp.raster, field = 1, background = NA, silent = TRUE) sp.raster <- sp.raster * sample.area.raster1 } if(correct.by.suitability) { if(!(inherits(x, "virtualspecies")) | !("suitab.raster" %in% names(x))) { stop("If you choose to weight the probability of detection by the suitability of the species (i.e., correct.by.suitability = TRUE), then you need to provide an appropriate virtual species containing a suitability raster to x.") } } if(!is.numeric(detection.probability) | detection.probability > 1 | detection.probability < 0) { stop("detection.probability must be a numeric value between 0 and 1") } if(!is.numeric(error.probability) | error.probability > 1 | error.probability < 0) { stop("error.probability must be a numeric value between 0 and 1") } if(length(bias) > 1) { stop('Only one bias can be applied at a time') } if (!(bias %in% c("no.bias", "country", "region", "continent", "extent", "polygon", "manual"))) { stop('Argument bias must be one of : "no.bias", "country", "region", "continent", "extent", "polygon", "manual"') } if(!is.numeric(bias.strength) & bias != "no.bias") { stop("Please provide a numeric value for bias.strength") } if (bias %in% c("country", "region", "continent")) { if(!("rworldmap" %in% rownames(installed.packages()))) { stop('You need to install the package "rworldmap" in order to use bias = "region" or bias = "country"') } worldmap <- rworldmap::getMap() if(bias == "country") { if (any(!(bias.area %in% levels(worldmap@data$SOVEREIGNT)))) { stop("country name(s) must be correctly spelled. Type 'levels(getMap()@data$SOVEREIGNT)' to obtain valid names.") } results$bias <- list(bias = bias, bias.strength = bias.strength, bias.area = bias.area) } else if (bias == "region") { if (any(!(bias.area %in% levels(worldmap@data$REGION)))) { stop(paste("region name(s) must be correctly spelled, according to one of the following : ", paste(levels(worldmap@data$REGION), collapse = ", "), sep = "\n")) } results$bias <- list(bias = bias, bias.strength = bias.strength, bias.area = bias.area) } else if (bias == "continent") { if (any(!(bias.area %in% levels(worldmap@data$continent)))) { stop(paste("region name(s) must be correctly spelled, according to one of the following : ", paste(levels(worldmap@data$continent), collapse = ", "), sep = "\n")) } results$bias <- list(bias = bias, bias.strength = bias.strength, bias.area = bias.area) } } if (bias == "polygon") { if(!(inherits(bias.area, c("SpatialPolygons", "SpatialPolygonsDataFrame")))) { stop("If you choose bias = 'polygon', please provide a polygon of class SpatialPolygons or SpatialPolygonsDataFrame to argument bias.area") } warning("Polygon projection is not checked. Please make sure you have the same projections between your polygon and your presence-absence raster") results$bias <- list(bias = bias, bias.strength = bias.strength, bias.area = bias.area) } if (bias == "extent") { results$bias <- list(bias = bias, bias.strength = bias.strength, bias.area = bias.area) } if(type == "presence-absence") { sample.raster <- sp.raster sample.raster[!is.na(sample.raster)] <- 1 } else if (type == "presence only") { sample.raster <- sp.raster } else stop("type must either be 'presence only' or 'presence-absence'") if (bias == "manual") { if(!(inherits(weights, "RasterLayer"))) { stop("You must provide a raster layer of weights (to argument weights) if you choose bias == 'manual'") } bias.raster <- weights results$bias <- list(bias = bias, bias.strength = "Defined by raster weights", weights = weights) } else { bias.raster <- sample.raster } if(bias == "country") { bias.raster1 <- rasterize( worldmap[which(worldmap@data$SOVEREIGNT %in% bias.area), ], bias.raster, field = bias.strength, background = 1, silent = TRUE) bias.raster <- bias.raster * bias.raster1 } else if(bias == "region") { bias.raster1 <- rasterize( worldmap[which(worldmap@data$REGION %in% bias.area), ], bias.raster, field = bias.strength, background = 1, silent = TRUE) bias.raster <- bias.raster * bias.raster1 } else if(bias == "continent") { bias.raster1 <- rasterize( worldmap[which(levels(worldmap@data$continent) %in% bias.area), ], bias.raster, field = bias.strength, background = 1, silent = TRUE) bias.raster <- bias.raster * bias.raster1 } else if(bias == "extent") { if(!(inherits(bias.area, "Extent"))) { message("No object of class extent provided: click twice on the map to draw the extent in which presence points will be sampled") plot(sp.raster) bias.area <- drawExtent(show = TRUE) } bias.raster <- bias.raster * rasterize(bias.area, sp.raster, field = bias.strength, background = 1) results$bias <- list(bias = bias, bias.strength = bias.strength, bias.area = bias.area) } else if(bias == "polygon") { bias.raster1 <- rasterize(bias.area, bias.raster, field = bias.strength, background = 1, silent = TRUE) bias.raster <- bias.raster * bias.raster1 } if(bias != "no.bias") { if(type == "presence only") { number.errors <- stats::rbinom(n = 1, size = 50, prob = error.probability) sample.points <- .randomPoints(sample.raster * bias.raster, n = number.errors, prob = TRUE, tryf = 1, replaceCells = replacement) sample.points <- rbind(sample.points, .randomPoints(sample.raster * bias.raster, n = n - number.errors, prob = TRUE, tryf = 1, replaceCells = replacement)) } else { if(is.null(sample.prevalence)) { sample.points <- .randomPoints(sample.raster * bias.raster, n = n, prob = TRUE, tryf = 1, replaceCells = replacement) } else { if(replacement) { message("Argument replacement = TRUE implies that sample prevalence may not necessarily be respected in geographical space. Sample prevalence will be respected, but multiple samples can occur in the same cell so that spatial prevalence will be different. ") } tmp1 <- sample.raster tmp1[sp.raster != 1] <- NA sample.points <- .randomPoints(tmp1 * bias.raster, n = sample.prevalence * n, prob = TRUE, tryf = 1, replaceCells = replacement) tmp1 <- sample.raster tmp1[sp.raster != 0] <- NA sample.points <- rbind(sample.points, .randomPoints(tmp1 * bias.raster, n = (1 - sample.prevalence) * n, prob = TRUE, tryf = 1, replaceCells = replacement)) rm(tmp1) } } } else { if(type == "presence only") { number.errors <- stats::rbinom(n = 1, size = n, prob = error.probability) sample.points <- .randomPoints(sample.raster, n = number.errors, prob = TRUE, tryf = 1, replaceCells = replacement) sample.points <- rbind(sample.points, .randomPoints(sample.raster, n = n - number.errors, prob = TRUE, tryf = 1, replaceCells = replacement)) } else { if(is.null(sample.prevalence)) { sample.points <- .randomPoints(sample.raster, n = n, prob = TRUE, tryf = 1, replaceCells = replacement) } else { tmp1 <- sample.raster tmp1[sp.raster != 1] <- NA sample.points <- .randomPoints(tmp1, n = sample.prevalence * n, prob = TRUE, tryf = 1, replaceCells = replacement) tmp1 <- sample.raster tmp1[sp.raster != 0] <- NA sample.points <- rbind(sample.points, .randomPoints(tmp1, n = (1 - sample.prevalence) * n, prob = TRUE, tryf = 1, replaceCells = replacement)) rm(tmp1) } } } if(type == "presence only") { sample.points <- data.frame(sample.points, Real = extract(sp.raster, sample.points), Observed = sample( c(NA, 1), size = nrow(sample.points), prob = c(1 - detection.probability, detection.probability), replace = TRUE)) } else if(type == "presence-absence") { sample.points <- data.frame(sample.points, Real = extract(sp.raster, sample.points)) if(correct.by.suitability) { suitabs <- extract(x$suitab.raster, sample.points[, c("x", "y")]) } else { suitabs <- rep(1, nrow(sample.points)) } sample.points$Observed <- NA if(correct.by.suitability) { sample.points$Observed[which(sample.points$Real == 1)] <- sapply(detection.probability * suitabs[ which(sample.points$Real == 1) ], function(y) { sample(c(0, 1), size = 1, prob = c(1 - y, y)) }) } else { sample.points$Observed[which(sample.points$Real == 1)] <- sample(c(0, 1), size = length(which(sample.points$Real == 1)), prob = c(1 - detection.probability, detection.probability), replace = TRUE) } sample.points$Observed[which(sample.points$Real == 0 | sample.points$Observed == 0)] <- sample(c(0, 1), size = length(which(sample.points$Real == 0 | sample.points$Observed == 0)), prob = c(1 - error.probability, error.probability), replace = TRUE) } if(plot) { plot(original.raster) if(type == "presence only") { points(sample.points[, c("x", "y")], pch = 16, cex = .5) } else { points(sample.points[sample.points$Observed == 1, c("x", "y")], pch = 16, cex = .8) points(sample.points[sample.points$Observed == 0, c("x", "y")], pch = 1, cex = .8) } results$sample.plot <- grDevices::recordPlot() } if(extract.probability) { sample.points <- data.frame(sample.points, true.probability = extract(x$probability.of.occurrence, sample.points[, c("x", "y")])) } results$sample.points <- sample.points if(type == "presence-absence") { true.prev <- length(sample.points$Real[which( sample.points$Real == 1)]) / nrow(sample.points) obs.prev <- length(sample.points$Real[which( sample.points$Observed == 1)]) / nrow(sample.points) results$sample.prevalence <- c(true.sample.prevalence = true.prev, observed.sample.prevalence = obs.prev) } class(results) <- append("VSSampledPoints", class(results)) return(results) }
useWaitress <- function(color = " dep <- htmltools::htmlDependency( name = "waitress", version = utils::packageVersion("waiter"), src = "packer", package = "waiter", script = "waitress.js" ) singleton( tags$head( tags$style( paste0(".progressjs-theme-blue .progressjs-inner{background-color:", color, ";}"), paste0(".progressjs-theme-blueOverlay .progressjs-inner{background-color:", color, ";}"), paste0(".progressjs-theme-blueOverlayRadius .progressjs-inner{background-color:", color, ";}"), paste0(".progressjs-theme-blueOverlayRadiusHalfOpacity .progressjs-inner{background-color:", color, ";}"), paste0(".progressjs-theme-blueOverlayRadiusWithPercentBar .progressjs-inner{background-color:", color, ";}"), paste0(".progressjs-percent{color:", percent_color, ";}") ), dep ) ) } use_waitress <- function(color = " useWaitress(color, percent_color) } Waitress <- R6::R6Class( "waitress", public = list( initialize = function(selector = NULL, theme = c("line", "overlay", "overlay-radius", "overlay-opacity", "overlay-percent"), min = 0, max = 100, infinite = FALSE, hide_on_render = FALSE){ name <- .random_name() theme <- match.arg(theme) overlay <- ifelse(grepl("overlay", theme), TRUE, FALSE) theme <- themes_to_js(theme) if(infinite){ min <- 0 max <- 100 } if(!is.null(selector)) if(!grepl("^ stop("`hide_on_render` will only work if the `selector` is an private$.hide_on_render <- hide_on_render private$.name <- name private$.theme <- theme private$.overlay <- overlay private$.dom <- selector private$.min <- min private$.max <- max private$.infinite <- infinite invisible(self) }, start = function(html = NULL, background_color = "transparent", text_color = "black"){ id <- private$.dom if(!private$.initialised) private$.initialised <- private$init() if(!is.null(html)){ if(!is.null(id)) if(!grepl("^ stop("`html` will only work when the `selector` is an if(is.character(html)) html <- span(html) html <- as.character(html) } id <- gsub("^ private$.started <- TRUE opts <- list( name = private$.name, infinite = private$.infinite, id = id, html = html, hideOnRender = private$.hide_on_render, backgroundColor = background_color, textColor = text_color, isNotification = FALSE ) private$get_session() private$.session$sendCustomMessage("waitress-start", opts) invisible(self) }, notify = function(html = NULL, background_color = "white", text_color = "black", position = c("br", "tr", "bl", "tl")){ id <- private$.dom private$.is_notification <- TRUE if(!is.null(html)){ if(is.character(html)) html <- p(html) } else { html <- p(style = "width:200px;") } html <- as.character(html) if(!private$.initialised) private$.initialised <- private$init( id = private$.name, html = html, backgroundColor = background_color, textColor = text_color, position = match.arg(position), notify = TRUE ) if(!is.null(id)) if(grepl("^ id <- gsub("^ private$.started <- TRUE opts <- list( name = private$.name, infinite = private$.infinite, id = id, hideOnRender = private$.hide_on_render, isNotification = TRUE ) private$get_session() private$.session$sendCustomMessage("waitress-start", opts) invisible(self) }, set = function(value){ if(missing(value)) stop("Missing `value`", call. = FALSE) private$get_session() private$.value <- value if(!private$.started) self <- self$start() value <- private$rescale(value) opts <- list(name = private$.name, percent = value) private$.session$sendCustomMessage("waitress-set", opts) invisible(self) }, auto = function(value, ms){ private$get_session() private$.value <- value if(!private$.started) self <- self$start() value <- private$rescale(value) opts <- list(name = private$.name, percent = value, ms = ms) private$.session$sendCustomMessage("waitress-auto", opts) invisible(self) }, inc = function(value){ private$get_session() private$.value <- value if(!private$.started) self <- self$start() value <- private$rescale(value) opts <- list(name = private$.name, percent = value) private$.session$sendCustomMessage("waitress-increase", opts) invisible(self) }, close = function(){ opts <- list( name = private$.name, infinite = private$.infinite, is_notification = private$.is_notification ) if(!is.null(private$.dom)) if(grepl("^ opts$id <- gsub("^ private$get_session() private$.session$sendCustomMessage("waitress-end", opts) invisible(self) }, getMin = function(){ private$.min }, getMax = function(){ private$.max }, getValue = function(){ private$.value }, print = function(){ if(!is.null(private$.dom)) cat("A waitress applied to", private$.dom, "\n") else if(!private$.is_notification) cat("A waitress applied to the whole page\n") else if (private$.is_notification) cat("A waitress notification\n") } ), active = list( max = function(value) { if(missing(value)) return(private$.max) private$.max <- value }, min = function(value) { if(missing(value)) return(private$.min) private$.min <- value } ), private = list( .name = NULL, .theme = NULL, .overlay = NULL, .dom = NULL, .session = NULL, .started = FALSE, .initialised = FALSE, .min = 0, .max = 100, .value = 0, .infinite = FALSE, .hide_on_render = FALSE, .is_notification = FALSE, rescale = function(value){ floor(((value-private$.min)/(private$.max - private$.min)) * 100) }, get_session = function(){ private$.session <- shiny::getDefaultReactiveDomain() }, init = function(id = NULL, ...){ if(is.null(id)) id <- private$.dom opts <- list( id = id, name = private$.name, options = list( theme = private$.theme, overlayMode = private$.overlay ) ) additional_options <- list(...) opts <- append(opts, additional_options) private$get_session() private$.session$sendCustomMessage("waitress-init", opts) return(TRUE) } ) )
define_shapefiles <- function(limits) { if(length(limits) == 1) { if(limits >= 30 & limits <= 89) { shapefiles <- "ArcticStereographic" decLimits <- TRUE } else if (limits <= -30 & limits >= -89) { shapefiles <- "AntarcticStereographic" decLimits <- TRUE } else { stop("limits argument has to be between 30 and 89 or -30 and -89 when numeric and length == 1 (polar stereographic maps).") } } else if(length(limits) == 4) { if(is_decimal_limit(limits)) { decLimits <- TRUE if(max(limits[3:4]) > 90) stop("limits[3:4] must be <= 90") if(min(limits[3:4]) < -90) stop("limits[3:4] must be >= -90") if(max(limits[3:4]) >= 60) { if(min(limits[3:4]) < 30) { shapefiles <- "DecimalDegree" } else { shapefiles <- "ArcticStereographic" } } else if(min(limits[3:4]) <= -60) { if(max(limits[3:4]) > 30) { shapefiles <- "DecimalDegree" } else { shapefiles <- "AntarcticStereographic" } } else if(all(limits[3:4] >= 40)) { shapefiles <- "ArcticStereographic" } else if(all(limits[3:4] <= -40)) { shapefiles <- "AntarcticStereographic" } else { shapefiles <- "DecimalDegree" } } else { decLimits <- FALSE shapefiles <- NA } } list(shapefile.name = shapefiles, decimal.degree.limits = decLimits) }
normlog.fsreg_2 <- function(target, dataset, iniset = NULL, wei = NULL, threshold = 0.05, tol = 2, ncores = 1) { dm <- dim(dataset) if ( is.null(dm) ) { n <- length(target) p <- 1 } else { n <- dm[1] p <- dm[2] } devi <- dof <- numeric( p ) moda <- list() k <- 1 tool <- numeric( min(n, p) ) threshold <- log(threshold) pa <- NCOL(iniset) da <- 1:pa dataset <- cbind(iniset, dataset) dataset <- as.data.frame(dataset) runtime <- proc.time() devi <- dof <- phi <- numeric(p) mi <- glm(target ~., data = as.data.frame( iniset ), weights = wei, family = gaussian(link = log), y = FALSE, model = FALSE ) do <- length( mi$coefficients ) ini <- mi$deviance if (ncores <= 1) { for (i in 1:p) { mi <- glm( target ~ . , data = dataset[, c(da, pa + i)], weights = wei, family = gaussian(link = log), y = FALSE, model = FALSE ) devi[i] <- mi$deviance dof[i] <- length( mi$coefficients ) phi[i] <- summary(mi)[[ 14 ]] } stat <- (ini - devi)/(dof - do) / phi pval <- pf( stat, dof - do, n - dof, lower.tail = FALSE, log.p = TRUE ) } else { cl <- makePSOCKcluster(ncores) registerDoParallel(cl) mod <- foreach( i = 1:p, .combine = rbind) %dopar% { ww <- glm( target ~., data = dataset[, c(da, pa + i)], weights = wei, family = gaussian(link = log) ) return( c( ww$deviance, length( ww$coefficients ), summary(ww)[[ 14 ]] ) ) } stopCluster(cl) stat <- (ini - mod[, 1])/(mod[, 2] - do) /mod[, 3] pval <- pf( stat, mod[, 2] - do, n - mod[, 2], lower.tail = FALSE, log.p = TRUE ) } mat <- cbind(1:p, pval, stat) colnames(mat)[1] <- "variables" rownames(mat) <- 1:p sel <- which.min(pval) info <- matrix( c( 1e300, 0, 0 ), ncol = 3 ) sela <- pa + sel if ( mat[sel, 2] < threshold ) { info[k, ] <- mat[sel, ] mat <- mat[-sel, , drop = FALSE] mi <- glm( target ~., data = dataset[, c(da, sela) ], weights = wei, family = gaussian(link = log), y = FALSE, model = FALSE ) tool[k] <- BIC( mi ) moda[[ k ]] <- mi } if ( info[k, 2] < threshold & nrow(mat) > 0 ) { k <- k + 1 pn <- p - k + 1 ini <- 2 * as.numeric( logLik(moda[[ 1 ]]) ) do <- length( coef( moda[[ 1 ]] ) ) devi <- dof <- phi <- numeric( pn ) if ( ncores <= 1 ) { for ( i in 1:pn ) { ww <- glm( target ~., data = dataset[, c(da, sela, pa + mat[i, 1]) ], weights = wei, family = gaussian(link = log), y = FALSE, model = FALSE ) devi[i] <- ww$deviance dof[i] <- length( ww$coefficients ) phi[i] <- summary(ww)[[ 14 ]] } stat <- (ini - devi)/(dof - do) / phi pval <- pf( stat, dof - do, n - dof, lower.tail = FALSE, log.p = TRUE ) } else { cl <- makePSOCKcluster(ncores) registerDoParallel(cl) mod <- foreach( i = 1:pn, .combine = rbind) %dopar% { ww <- glm( target ~., data = dataset[, c(da, sela, pa + mat[i, 1]) ], weights = wei, family = gaussian(link = log) ) return( c( ww$deviance, length( ww$coefficients ), summary(ww)[[ 14 ]] ) ) } stopCluster(cl) stat <- (ini - mod[, 1])/(mod[, 2] - do) / mod[, 3] pval <- pf( stat, mod[, 2] - do, n - mod[, 2], lower.tail = FALSE, log.p = TRUE ) } mat[, 2:3] <- cbind(pval, stat) ina <- which.min(mat[, 2]) sel <- pa + mat[ina, 1] if ( mat[ina, 2] < threshold ) { ma <- glm( target ~., data = dataset[, c(da, sela, sel) ], weights = wei, family = gaussian(link = log), y = FALSE, model = FALSE ) tool[k] <- BIC( ma ) if ( tool[ k - 1 ] - tool[ k ] <= tol ) { info <- info } else { info <- rbind(info, c( mat[ina, ] ) ) sela <- c(sela, sel) mat <- mat[-ina , , drop = FALSE] moda[[ k ]] <- ma } } else info <- info } if ( nrow(info) > 1 & nrow(mat) > 0 ) { while ( info[k, 2] < threshold & k < n - 15 & tool[ k - 1 ] - tool[ k ] > tol & nrow(mat) > 0 ) { ini <- 2 * as.numeric( logLik(moda[[ k ]]) ) do <- length( coef( moda[[ k ]] ) ) k <- k + 1 pn <- p - k + 1 devi <- dof <- phi <- numeric( pn ) if (ncores <= 1) { for ( i in 1:pn ) { ma <- glm( target ~., data = dataset[, c(da, sela, pa + mat[i, 1] ) ], weights = wei, family = gaussian(link = log), y = FALSE, model = FALSE ) devi[i] <- ma$deviance dof[i] <- length( ma$coefficients ) phi[i] <- summary(ma)[[ 14 ]] } stat <- (ini - devi)/(dof - do) /phi pval <- pf( stat, dof - do, n - dof, lower.tail = FALSE, log.p = TRUE ) } else { cl <- makePSOCKcluster(ncores) registerDoParallel(cl) mod <- foreach( i = 1:pn, .combine = rbind) %dopar% { ww <- glm( target ~., data = dataset[, c(da, sela, pa + mat[i, 1]) ], weights = wei, family = gaussian(link = log), y = FALSE, model = FALSE ) return( c( ww$deviance, length( ww$coefficients ), summary(ww)[[ 14 ]] ) ) } stopCluster(cl) stat <- (ini - mod[, 1])/(mod[, 2] - do)/mod[, 3] pval <- pf( stat, mod[, 2] - do, n - mod[, 2], lower.tail = FALSE, log.p = TRUE ) } mat[, 2:3] <- cbind(pval, stat) ina <- which.min(mat[, 2]) sel <- pa + mat[ina, 1] if ( mat[ina, 2] < threshold ) { ma <- glm( target ~., data = dataset[, c(da, sela, sel) ], weights = wei, family = gaussian(link = log), y = FALSE, model = FALSE ) tool[k] <- BIC( ma ) if ( tool[ k - 1 ] - tool[ k ] < tol ) { info <- rbind(info, c( 1e300, 0, 0 ) ) } else { info <- rbind( info, mat[ina, ] ) sela <- c(sela, sel) mat <- mat[-ina, , drop = FALSE] moda[[ k ]] <- ma } } else info <- rbind(info, c( 1e300, 0, 0 ) ) } } runtime <- proc.time() - runtime d <- length(moda) final <- NULL if ( d == 0 ) { final <- glm( target ~., data = as.data.frame( iniset ), weights = wei, family = gaussian(link = log), y = FALSE, model = FALSE ) info <- NULL } else { final <- glm( target ~., data = dataset[, c(da, sela) ], weights = wei, family = gaussian(link = log), y = FALSE, model = FALSE ) info <- info[1:d, , drop = FALSE] info <- cbind( info, tool[ 1:d ] ) colnames(info) <- c( "variables", "log.p-value", "stat", "BIC" ) rownames(info) <- info[, 1] } list( runtime = runtime, mat = t(mat), info = info, ci_test = "testIndNormLog", final = final ) }
scaleByGroup <- function(data , protGroup, plot=FALSE, scale=TRUE, center=TRUE){ reference = data[rownames(data) %in% protGroup,] noReference = data[!rownames(data) %in% protGroup,] referenceScaled = robustscale(reference,scale=scale, center=center) if(center){ noReference = sweep(noReference,2,referenceScaled$medians,"-") } if(scale){ noReference = sweep(noReference,2,referenceScaled$mads,"/") } if(plot){ graphics::par(mfrow=c(1,2)) graphics::boxplot(noReference,main="noReference",ylim=c(-8,6), pch=".", las=2,cex.axis=0.5) abline(h=0,col=2) graphics::boxplot(referenceScaled$data,main="reference",ylim=c(-8,6),las=2,pch=".",cex.axis=0.5) abline(h=0,col=2) } return(list(reference = referenceScaled$data, noReference = noReference)) }
simulate.glm <- function(object, nsim = 1, seed = NULL, newdata=NULL, type = c("coef", "link", "response"), ...){ if (!exists(".Random.seed", envir = .GlobalEnv, inherits = FALSE)) runif(1) if (is.null(seed)){ RNGstate <- get(".Random.seed", envir = .GlobalEnv) } else { R.seed <- get(".Random.seed", envir = .GlobalEnv) set.seed(seed) RNGstate <- structure(seed, kind = as.list(RNGkind())) on.exit(assign(".Random.seed", R.seed, envir = .GlobalEnv)) } cl <- as.list(object[['call']]) if(is.null(newdata)){ if('x' %in% names(object)){ newMat <- object$x } else { if(is.null(cl$data)){ newMat <- model.matrix(cl$formula, data = environment(object), ...) } else { fmla <- eval(cl$formula) dat <- eval(cl$data) newMat <- model.matrix(fmla, data = dat, ...) } } } else newMat <- model.matrix(~., newdata) nobs <- NROW(newdata) vc <- vcov(object) simCoef <- mvtnorm::rmvnorm(nsim, coef(object), vc) rownames(simCoef) <- paste0('sim_', 1:nsim) sims <- tcrossprod(newMat, simCoef) if(any(!is.na(pmatch(type, 'response')))){ fam <- cl$family if(is.character(fam)){ fam <- get(fam, mode = "function", envir = parent.frame()) } if(class(fam) %in% c('call', 'name')) fam <- eval(fam) if(is.function(fam)) fam <- fam() if(is.null(fam$family)) { print(fam) stop("'family' not recognized") } linkinv <- fam$linkinv if(!is.function(linkinv)){ print(fam) stop("linkinv from 'family' is not a function.") } } if(length(type)<1)stop('No "type" requested.') if(length(type)<2){ if(!is.na(pmatch(type, 'coef'))){ out <- data.frame(t(simCoef)) attr(out, 'seed') <- RNGstate return(out) } else if(!is.na(pmatch(type, 'link'))){ out <- data.frame(sims) attr(out, 'seed') <- RNGstate return(out) } else if(is.na(pmatch(type, 'response'))){ stop('Not a recognized type. type = ', type) } else { out <- data.frame(linkinv(sims)) attr(out, 'seed') <- RNGstate return(out) } } out <- vector('list', length(type)) names(out) <- type if(any(!is.na(pmatch(type, 'coef')))){ out[['coef']] <- data.frame(t(simCoef)) } if(any(!is.na(pmatch(type, 'link')))){ out[['link']] <- data.frame(sims) } if(any(!is.na(pmatch(type, 'response')))){ out[['response']] <- data.frame(linkinv(sims)) } attr(out, 'seed') <- RNGstate out }
toucrec<-function(atoms,alkublokki,blokki){ if (dim(t(atoms))[1]==1) m<-1 else m<-length(atoms[,1]) len<-alkublokki links<-matrix(NA,m,len) maara<-matrix(0,m,1) i<-1 while (i<=m){ j<-i+1 while (j<=m){ rec1<-atoms[i,] rec2<-atoms[j,] crit<-touch(rec1,rec2) if (crit){ maari<-maara[i]+1 maarj<-maara[j]+1 if ((maari>len) || (maarj>len)){ links<-blokitus2(links,blokki) len<-len+blokki } links[i,maari]<-j maara[i]<-maari links[j,maarj]<-i maara[j]<-maarj } j<-j+1 } i<-i+1 } return(links) }
process_tags <- function(node, drawing_context) { new <- lapply(seq_along(node), function(i) { dispatch_tag(node[[i]], names(node)[i], drawing_context) }) rbind_dfs(new) } dispatch_tag <- function(node, tag, drawing_context) { if (is.null(tag) || tag == "") return(process_text(node, drawing_context)) call_name <- paste("process_tag", tag, sep = "_") if(!exists(call_name)) { abort(paste0( "The rich-text has a tag that isn't supported (yet): <", tag, ">\n", "Only a very limited number of tags are currently supported." )) } dc <- set_style(drawing_context, attr(node, "style")) call(call_name, node = node, drawing_context = dc) } process_text <- function(node, drawing_context) { cbind(list(unlist(node)), list(drawing_context$gp), list(drawing_context$yoff)) } process_tag_p <- process_tag_span <- function(node, drawing_context) { process_tags(node, drawing_context) } process_tag_b <- process_tag_strong <- function(node, drawing_context) { drawing_context <- set_context_font(drawing_context, 2) process_tags(node, drawing_context) } process_tag_i <- process_tag_em <- function(node, drawing_context) { drawing_context <- set_context_font(drawing_context, 3) process_tags(node, drawing_context) } process_tag_sub <- function(node, drawing_context) { drawing_context <- set_context_size(drawing_context, 0.8) drawing_context <- set_context_offset(drawing_context, -0.5) process_tags(node, drawing_context) } process_tag_sup <- function(node, drawing_context) { drawing_context <- set_context_size(drawing_context, 0.8) drawing_context <- set_context_offset(drawing_context, 0.5) process_tags(node, drawing_context) } setup_context <- function( fontsize = 12, fontfamily = "", fontface = "plain", colour = "black", lineheight = 1.2, gp = NULL ) { if (is.null(gp)) { gp <- gpar( fontsize = fontsize, fontfamily = fontfamily, fontface = fontface, col = colour, cex = 1, lineheight = lineheight ) } gp <- update_gpar(get.gpar(), gp) set_context_gp(list(yoff = 0), gp) } update_gpar <- function(gp, gp_new) { names_new <- names(gp_new) names_old <- names(gp) gp[c(intersect(names_old, names_new), "fontface")] <- NULL gp_new["fontface"] <- NULL do.call(gpar, c(gp, gp_new)) } set_context_gp <- function(drawing_context, gp = NULL) { gp <- update_gpar(drawing_context$gp, gp) update_context(drawing_context, ascent = x_height(gp), gp = gp) } set_context_font <- function(drawing_context, font = 1, overwrite = FALSE) { font_old <- drawing_context$gp$font old_bold <- font_old %in% c(2, 4) new_bold <- font %in% c(2, 4) old_ital <- font_old %in% c(3, 4) new_ital <- font %in% c(3, 4) if (!isTRUE(overwrite)) { if (isTRUE(new_ital) && isTRUE(old_bold)) { font <- 4 } else if (isTRUE(new_bold) && isTRUE(old_ital)) { font <- 4 } } set_context_gp(drawing_context, gpar(font = font)) } set_context_size <- function(drawing_context, size = 1) { fontsize <- size * drawing_context$gp$fontsize set_context_gp(drawing_context, gpar(fontsize = fontsize)) } set_context_offset <- function(drawing_context, offset = 0) { drawing_context$yoff <- drawing_context$yoff + drawing_context$ascent * offset drawing_context } update_context <- function(drawing_context, ...) { dc_new <- list(...) names_new <- names(dc_new) names_old <- names(drawing_context) drawing_context[intersect(names_old, names_new)] <- NULL c(drawing_context, dc_new) } set_style <- function(drawing_context, style = NULL) { if (is.null(style)) return(drawing_context) css <- parse_css(style) if (!is.null(css$`font-size`)) { font_size <- convert_css_unit_pt(css$`font-size`) } else { font_size <- NULL } drawing_context <- set_context_gp( drawing_context, gpar(col = css$color, fontfamily = css$`font-family`, fontsize = font_size) ) } parse_css <- function(text) { lines <- strsplit(text, ";", fixed = TRUE)[[1]] unlist(lapply(lines, parse_css_line), FALSE) } parse_css_line <- function(line) { pattern <- "\\s*(\\S+)\\s*:\\s*(\"(.*)\"|'(.*)'|(\\S*))\\s*" m <- attributes(regexpr(pattern, line, perl = TRUE)) start <- m$capture.start end <- start + m$capture.length - 1 if (start[1] > 0) { key <- substr(line, start[1], end[1]) key <- as_lower(key) } else { key <- NULL } if (start[3] > 0) { value <- substr(line, start[3], end[3]) } else if (start[4] > 0) { value <- substr(line, start[4], end[4]) } else if (start[5] > 0) { value <- substr(line, start[5], end[5]) } else value <- NULL if (is.null(key)) list() else rlang::list2(!!key := value) } parse_css_unit <- function(x) { pattern <- "^((-?\\d+\\.?\\d*)(%|[a-zA-Z]+)|(0))$" m <- attributes(regexpr(pattern, x, perl = TRUE)) start <- m$capture.start end <- start + m$capture.length - 1 if (start[4] > 0) { return(list(value = 0, unit = "pt")) } else { if (start[2] > 0) { value <- as.numeric(substr(x, start[2], end[2])) if (start[3] > 0) { unit <- substr(x, start[3], end[3]) return(list(value = value, unit = unit)) } } } abort(paste0("The string '", x, "' does not represent a valid CSS unit.")) } convert_css_unit_pt <- function(x) { u <- parse_css_unit(x) switch( u$unit, pt = u$value, px = (72 / 96) * u$value, `in` = 72 * u$value, cm = (72 / 2.54) * u$value, mm = (72 / 25.4) * u$value, abort(paste0("Cannot convert ", u$value, u$unit, " to pt.")) ) }
OutputExcelFileDBMH <- function(dataset, method, methodTxt, ReportFileName, covEstMethod, summaryInfo, alpha, FOM, analysisOption, StResult) { I <- dim(dataset$ratings$NL)[1] J <- dim(dataset$ratings$NL)[2] K <- dim(dataset$ratings$NL)[3] K2 <- dim(dataset$ratings$LL)[3] K1 <- K - K2 wb <- createWorkbook() addWorksheet(wb, "Summary") writeData(wb, sheet = "Summary", x = summaryInfo, rowNames = TRUE, colNames = FALSE) modalityID <- data.frame(output = dataset$descriptions$modalityID, input = names(dataset$descriptions$modalityID)) colnames(modalityID) <- c("Modality ID in output file", "Modality ID in input file") writeData(wb, sheet = "Summary", x = modalityID, startRow = 5, colNames = TRUE) readerID <- data.frame(output = dataset$descriptions$readerID, input = names(dataset$descriptions$readerID)) colnames(readerID) <- c("Reader ID in output file", "Reader ID in input file") writeData(wb, sheet = "Summary", x = readerID, startRow = 5, startCol = 3, colNames = TRUE) analysisInfo <- data.frame(info = c(K1, K2, FOM, method, covEstMethod)) rownames(analysisInfo) <- c("Number of non-diseased cases", "Number of diseased cases", "FOM", "Significance testing", "Variability estimation method") writeData(wb, sheet = "Summary", x = analysisInfo, startRow = 7 + max(I, J), startCol = 1, rowNames = TRUE, colNames = FALSE) sty <- createStyle(halign = "center", valign = "center") addStyle(wb, sheet = "Summary", style = sty, rows = seq(1, 11 + max(I, J)), cols = 1:4, gridExpand = TRUE) setColWidths(wb, sheet = "Summary", cols = 1:4, widths = "auto", ignoreMergedCells = TRUE) sheet <- "FOMs" addWorksheet(wb, sheet) setColWidths(wb, sheet = sheet, cols = 1:(J + 3), widths = "auto", ignoreMergedCells = TRUE) setColWidths(wb, sheet = sheet, cols = 1, widths = 10) startRow <- 1 df <- StResult$FOMs$foms hdr <- "FOMs: reader vs. treatment" startRow <- OutputDataFrame (wb, sheet, startRow, df, sty, hdr) df <- StResult$FOMs$trtMeans hdr <- "treatment means" startRow <- OutputDataFrame (wb, sheet, startRow, df, sty, hdr) df <- StResult$FOMs$trtMeanDiffs hdr <- "treatment differences" startRow <- OutputDataFrame (wb, sheet, startRow, df, sty, hdr) sheet <- "ANOVA" addWorksheet(wb, sheet) setColWidths(wb, sheet = sheet, cols = 1:8, widths = "auto", ignoreMergedCells = TRUE) setColWidths(wb, sheet = sheet, cols = 1, widths = 10) startRow <- 1 df <- StResult$ANOVA$TRCanova hdr <- "DBM treatment reader case ANOVA" startRow <- OutputDataFrame (wb, sheet, startRow, df, sty, hdr) df <- StResult$ANOVA$VarCom hdr <- "DBM Variance Components" startRow <- OutputDataFrame (wb, sheet, startRow, df, sty, hdr) df <- UtilDBM2ORVarCom(K, df) hdr <- "OR Variance Components" startRow <- OutputDataFrame (wb, sheet, startRow, df, sty, hdr) df <-StResult$ANOVA$IndividualTrt hdr <- "Reader x Case Anova for each treatment" startRow <- OutputDataFrame (wb, sheet, startRow, df, sty, hdr) df <-StResult$ANOVA$IndividualRdr hdr <- "Treatment x Case Anova for each reader" startRow <- OutputDataFrame (wb, sheet, startRow, df, sty, hdr) sheet <- "RRRC" addWorksheet(wb, sheet) setColWidths(wb, sheet = sheet, cols = 1:8, widths = "auto", ignoreMergedCells = TRUE) setColWidths(wb, sheet = sheet, cols = 1, widths = 10) startRow <- 1 df <- StResult$RRRC$FTests hdr <- "(a) F-Tests of NH" startRow <- OutputDataFrame (wb, sheet, startRow, df, sty, hdr) df <- StResult$RRRC$ciDiffTrt hdr <- "(b) 95% confidence interval for treatment differences" startRow <- OutputDataFrame (wb, sheet, startRow, df, sty, hdr) df <-StResult$RRRC$ciAvgRdrEachTrt hdr <- "(c) 95% confidence interval for each treatment" startRow <- OutputDataFrame (wb, sheet, startRow, df, sty, hdr) sheet <- "FRRC" addWorksheet(wb, sheet) setColWidths(wb, sheet = sheet, cols = 1:8, widths = "auto", ignoreMergedCells = TRUE) setColWidths(wb, sheet = sheet, cols = 1, widths = 10) startRow <- 1 df <- StResult$FRRC$FTests hdr <- "(a) F-Tests of NH" startRow <- OutputDataFrame (wb, sheet, startRow, df, sty, hdr) df <- StResult$FRRC$ciDiffTrt hdr <- "(b) 95% confidence interval for treatment differences" startRow <- OutputDataFrame (wb, sheet, startRow, df, sty, hdr) df <-StResult$FRRC$ciAvgRdrEachTrt hdr <- "(c) 95% confidence interval for each treatment" startRow <- OutputDataFrame (wb, sheet, startRow, df, sty, hdr) df <-StResult$FRRC$ciDiffTrtEachRdr hdr <- "(d) 95% confidence interval treatment differences, each reader" startRow <- OutputDataFrame (wb, sheet, startRow, df, sty, hdr) sheet <- "RRFC" addWorksheet(wb, sheet) setColWidths(wb, sheet = sheet, cols = 1:8, widths = "auto", ignoreMergedCells = TRUE) setColWidths(wb, sheet = sheet, cols = 1, widths = 10) startRow <- 1 df <- StResult$RRFC$FTests hdr <- "(a) F-Tests of NH" startRow <- OutputDataFrame (wb, sheet, startRow, df, sty, hdr) df <- StResult$RRFC$ciDiffTrt hdr <- "(b) 95% confidence interval for treatment differences" startRow <- OutputDataFrame (wb, sheet, startRow, df, sty, hdr) df <-StResult$RRFC$ciAvgRdrEachTrt hdr <- "(c) 95% confidence interval for each treatment" startRow <- OutputDataFrame (wb, sheet, startRow, df, sty, hdr) saveWorkbook(wb, ReportFileName, overwrite = TRUE) sucessfulOutput <- sprintf("The report has been saved to %s.", ReportFileName) return(sucessfulOutput) } OutputDataFrame <- function (wb, sheet, startRow, df, sty, hdr) { addStyle(wb, sheet = sheet, style = sty, rows = startRow:(startRow + nrow(df) + 1), cols = 1:(ncol(df) + 1), gridExpand = TRUE) mergeCells(wb, sheet, rows = startRow, cols = 1:(ncol(df)+1)) writeData(wb, sheet = sheet, startRow = startRow, x = hdr, rowNames = FALSE, colNames = FALSE) startRow <- startRow + 1 writeData(wb, sheet = sheet, startRow = startRow, x = df, rowNames = TRUE, colNames = TRUE) startRow <- startRow + nrow(df) + 2 return(startRow) }
get_split_names = function(tree,data){ paths <- eval(parse(text = "pre:::list.rules(tree, removecomplements = FALSE)")) vnames = names(data) split_names = vnames[sapply(sapply(vnames, FUN = function(var) grep(paste(paste(var,"<="),"|",paste(var,">"),sep=""), paths)), length) > 0] return (split_names) }
expected <- eval(parse(text="\"utils\"")); test(id=0, code={ argv <- eval(parse(text="list(structure(\"/home/lzhao/hg/r-instrumented/library/utils\", .Names = \"Dir\"))")); .Internal(basename(argv[[1]])); }, o=expected);
valcam=function(trat, resp, error = "SE", ylab = "Dependent", xlab = "Independent", theme = theme_classic(), legend.position = "top", r2 = "mean", point = "all", width.bar = NA, scale = "none", textsize = 12, pointsize = 4.5, linesize = 0.8, pointshape = 21, round = NA, yname.formula="y", xname.formula="x", comment = NA, fontfamily="sans") { if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} requireNamespace("ggplot2") ymean=tapply(resp,trat,mean) if(error=="SE"){ysd=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){ysd=tapply(resp,trat,sd)} if(error=="FALSE"){ysd=0} desvio=ysd xmean=tapply(trat,trat,mean) theta.0 <- min(resp) * 0.5 model <- lm(resp ~ trat+I(trat^1.5)+I(trat^2)) coef=summary(model) if(is.na(round)==TRUE){ a=coef$coefficients[,1][1] b=coef$coefficients[,1][2] c=coef$coefficients[,1][3] d=coef$coefficients[,1][4]} if(is.na(round)==FALSE){ a=round(coef$coefficients[,1][1],round) b=round(coef$coefficients[,1][2],round) c=round(coef$coefficients[,1][3],round) d=round(coef$coefficients[,1][4],round)} modm=lm(ymean~xmean+I(xmean^1.5)+I(xmean^2)) if(r2=="all"){r2=round(summary(model)$r.squared,2)} if(r2=="mean"){r2=round(summary(modm)$r.squared,2)} r2=floor(r2*100)/100 equation=sprintf("~~~%s == %e %s %e * %s %s %e * %s^1.5 %s %0.e * %s^2 ~~~~~ italic(R^2) == %0.2f", yname.formula, coef(modm)[1], ifelse(coef(modm)[2] >= 0, "+", "-"), abs(coef(modm)[2]), xname.formula, ifelse(coef(modm)[3] >= 0, "+", "-"), abs(coef(modm)[3]), xname.formula, ifelse(coef(modm)[4] >= 0, "+", "-"), abs(coef(modm)[4]), xname.formula, r2) if(is.na(comment)==FALSE){equation=paste(equation,"~\"",comment,"\"")} xp=seq(min(trat),max(trat),length.out = 1000) preditos=data.frame(x=xp, y=predict(model,newdata = data.frame(trat=xp))) predesp=predict(model) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) x=preditos$x y=preditos$y s=equation data=data.frame(xmean,ymean) data1=data.frame(trat=xmean,resp=ymean) if(point=="mean"){ graph=ggplot(data,aes(x=xmean,y=ymean)) if(error!="FALSE"){graph=graph+geom_errorbar(aes(ymin=ymean-ysd,ymax=ymean+ysd), width=width.bar, size=linesize)} graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill="gray")} if(point=="all"){ graph=ggplot(data.frame(trat,resp),aes(x=trat,y=resp)) graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill="gray")} graph=graph+theme+geom_line(data=preditos,aes(x=x, y=y,color="black"),size=linesize)+ scale_color_manual(name="",values=1,label=parse(text = equation))+ theme(axis.text = element_text(size=textsize,color="black",family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.position = legend.position, legend.text = element_text(size=textsize,family = fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ ylab(ylab)+xlab(xlab) if(scale=="log"){graph=graph+scale_x_log10()} temp1=seq(min(trat),max(trat),length.out=10000) result=predict(model,newdata = data.frame(trat=temp1),type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)] aic=AIC(model) bic=BIC(model) graphs=data.frame("Parameter"=c("X Maximum", "Y Maximum", "X Minimum", "Y Minimum", "AIC", "BIC", "r-squared", "RMSE"), "values"=c(maximo, respmax, minimo, respmin, aic, bic, r2, rmse)) graficos=list("Coefficients"=coef, "values"=graphs, graph) print(graficos) }
get_pairwise_mrcas = function(tree, A, B, check_input=TRUE){ Ntips = length(tree$tip.label); Nnodes = tree$Nnode; if((!is.character(A)) && (!is.numeric(A))) stop("ERROR: List of tips/nodes A must be a character or integer vector") if((!is.character(B)) && (!is.numeric(B))) stop("ERROR: List of tips/nodes B must be a character or integer vector") if(length(A)!=length(B)) stop(sprintf("ERROR: Lists A & B must have equal lengths; instead, A has length %d and B has length %d",length(A),length(B))) if(is.character(A) || is.character(B)){ name2clade = 1:(Ntips+Nnodes); names(name2clade) = c(tree$tip.label,tree$node.label); } if(is.character(A)){ Ai = name2clade[A]; if(check_input && any(is.na(Ai))) stop(sprintf("ERROR: Unknown tip or node name '%s'",A[which(is.na(Ai))[1]])); A = Ai; }else if(check_input){ minA = min(A); maxA = max(A); if(minA<1 || maxA>(Ntips+Nnodes)) stop(sprintf("ERROR: List A must contain values between 1 and Ntips+Nnodes (%d); instead, found values from %d to %d",Ntips+Nnodes,minA,maxA)); } if(is.character(B)){ Bi = name2clade[B]; if(check_input && any(is.na(Bi))) stop(sprintf("ERROR: Unknown tip or node name '%s'",B[which(is.na(Bi))[1]])) B = Bi; }else if(check_input){ minB = min(B); maxB = max(B); if(minB<1 || maxB>(Ntips+Nnodes)) stop(sprintf("ERROR: List B must contain values between 1 and Ntips+Nnodes (%d); instead, found values from %d to %d",Ntips+Nnodes,minB,maxB)) } mrcas = get_most_recent_common_ancestors_CPP(Ntips = Ntips, Nnodes = tree$Nnode, Nedges = nrow(tree$edge), tree_edge = as.vector(t(tree$edge))-1, cladesA = A-1, cladesB = B-1, verbose = FALSE, verbose_prefix = ""); return(as.integer(mrcas+1)); }
if(TRUE) x else y
test_that("illegal initializations are rejected", { k <- 9 theta <- 0.5 expect_silent(GammaDistribution$new(k,theta)) expect_error(GammaDistribution$new("9",theta), class="shape_not_numeric") expect_error(GammaDistribution$new(k,"0.5"), class="scale_not_numeric") expect_error(GammaDistribution$new(-1,theta), class="shape_not_supported") expect_error(GammaDistribution$new(k,0), class="scale_not_supported") }) test_that("distribution name is correct", { k <- 9 theta <- 0.5 g <- GammaDistribution$new(k, theta) expect_identical(g$distribution(), "Ga(9,0.5)") }) test_that("mean, mode, sd and quantiles are returned correctly", { k <- 9 theta <- 0.5 g <- GammaDistribution$new(k, theta) expect_intol(g$mean(), k*theta, 0.01) expect_intol(g$SD(), sqrt(k)*theta, 0.01) expect_intol(g$mode(), (k-1)*theta, 0.01) probs <- c(0.025, 0.975) q <- g$quantile(probs) expect_intol(q[1], 2.06, 0.01) expect_intol(q[2], 7.88, 0.01) }) test_that("quantile function checks inputs and has correct output", { k <- 9 theta <- 0.5 g <- GammaDistribution$new(k, theta) probs <- c(0.1, 0.2, 0.5) expect_silent(g$quantile(probs)) probs <- c(0.1, NA, 0.5) expect_error(g$quantile(probs), class="probs_not_defined") probs <- c(0.1, "boo", 0.5) expect_error(g$quantile(probs), class="probs_not_numeric") probs <- c(0.1, 0.4, 1.5) expect_error(g$quantile(probs), class="probs_out_of_range") probs <- c(0.1, 0.2, 0.5) expect_length(g$quantile(probs),3) }) test_that("random sampling is from a Gamma distribution", { k <- 9 theta <- 0.5 n <- 1000 g <- GammaDistribution$new(k, theta) g$sample(TRUE) expect_equal(g$r(), 4.5) samp <- sapply(1:n, FUN=function(i) { g$sample() rv <- g$r() return(rv) }) expect_length(samp, n) skip_on_cran() ht <- ks.test(samp, stats::rgamma(n,shape=k,scale=theta)) expect_true(ht$p.value > 0.001) })
NULL readPagoda2SelectionFile <- function(filepath) { returnList <- list() con <- file(filepath, "r") while (TRUE) { suppressWarnings(line <- readLines(con, n = 1)) if ( length(line) == 0 ) { break } fields <- unlist(strsplit(line, split=',', fixed=TRUE)) name <- make.names(fields[2]) color <- fields[1] cells <- fields[-c(1:2)] returnList[[name]] <- list(name=fields[2], color = color, cells = cells) } close(con) invisible(returnList) } writePagoda2SelectionFile <- function(sel, filepath) { fileConn <- file(filepath) lines <- c() for (l in names(sel)) { cells <- sel[[l]]$cells cellsString <- paste0(cells,collapse=',') ln <- paste(sel[[l]]$color,as.character(l),cellsString,sep=',') lines <- c(lines,ln) } writeLines(lines, con=fileConn) close(fileConn) } writeGenesAsPagoda2Selection <- function(name, genes, filename) { con <- file(filename, 'w') cat(name, file=con) cat(',',file=con) cat(paste(genes, collapse=','), file=con) cat('\n', file=con) close(con) } calcMulticlassified <- function(sel) { selectionCellsFlat <- unname(unlist(sapply(sel, function(x) x$cells))) multiClassified <- selectionCellsFlat[duplicated(selectionCellsFlat)] sort(sapply(sel, function(x) { sum(x$cells %in% multiClassified) / length(x$cells) })) } factorFromP2Selection <- function (sel, use.internal.name=FALSE, flatten=FALSE){ if (!flatten && !all(calcMulticlassified(sel) == 0)) { stop("The selections provided are not mutually exclusive. Use flatten=TRUE to overwrite") } x <- mapply(function(x,n) { if (length(x$cells) > 0) { data.frame(cellid = x$cells, label = c(x$name), internal.name = c(n)) } }, sel, names(sel), SIMPLIFY = FALSE) d <- do.call(rbind, x) if(flatten) d <- d[!duplicated(d$cell),] if (use.internal.name) { f <- as.factor(d$internal.name) } else { f <- as.factor(d$label) } names(f) <- d$cellid invisible(f) } getColorsFromP2Selection <- function(sel) { unlist(lapply(sel, function(x) { paste0(' } factorToP2selection <- function(cl, col=NULL) { if(!is.factor(cl)) { stop('cl is not a factor'); } if(is.null(col)) { col=substr(rainbow(nlevels(cl)),2,7) names(col) <- levels(cl) } ns <- list() for (l in levels(cl)) { ns[[l]] <- list( name = l, cells = names(cl)[which(cl == l)], color=col[l] ) } invisible(ns) } removeSelectionOverlaps <- function(selections) { selectionsCellsFlat <- unname(unlist(sapply(selections, function(x) x$cells))) multiClassified <- selectionsCellsFlat[duplicated(selectionsCellsFlat)] lapply(selections, function(x) { r <- list() r$name = x$name r$color = x$color r$cells = x$cells[!x$cells %in% multiClassified] r }) } cellsPerSelectionGroup <- function(selection) { unlist(lapply(selection, function(x) length(x$cells))) } validateSelectionsObject <- function(selections) { t <- lapply(selections, function(x) { isvalidentry <- TRUE if (!is.character(x$name)) { isvalidentry <- FALSE } if (!is.character(x$color)) { isvalidentry <- FALSE } if (!is.character(x$cells)) { isvalidentry <- FALSE } isvalidentry }) all(unlist(t)) } getClusterLabelsFromSelection <- function(clustering, selections, multiClassCutoff=0.3, ambiguous.ratio=0.5) { if (!is.factor(clustering)) { stop('clustering is not a factor') } if (!validateSelectionsObject(selections)) { stop('selections is not a valid selection object') } multiClass <- calcMulticlassified(selections) if(!all(multiClass < multiClassCutoff)) { msg <- paste0('The following selections have a very high number of multiclassified cells: ', paste(names(multiClass)[!multiClass < multiClassCutoff], collapse = ', '), '. Please reduce the overlaps and try again. You can use calcMulticlassified() to see more details.') stop(msg) } sel.clean <- removeSelectionOverlaps(selections) sel.clean.vector <- factorFromP2Selection(sel.clean) shared.names <- intersect(names(sel.clean.vector), names(clustering)) confusion.table <- table(data.frame(sel.clean.vector[shared.names],clustering[shared.names])) tmp1 <- plyr::adply(.data = confusion.table, .margins = 2, .fun = function(x) { rv <- NA x.sort <- sort(x, decreasing=TRUE) if((x.sort[1] * ambiguous.ratio) >= x.sort[2]) { rv <- names(x.sort)[1] } rv }) labels <- tmp1[,2] names(labels) <- tmp1[,1] colnames(tmp1) <- c('cluster', 'selection') invisible(tmp1) } generateClassificationAnnotation <- function(clustering, selections) { clAnnotation <- getClusterLabelsFromSelection(clustering, selections) rownames(clAnnotation) <- clAnnotation$cluster r <- as.factor(clAnnotation[as.character(clustering),]$selection) names(r) <- names(clustering) invisible(r) } getCellsInSelections <- function(p2selections, selectionNames) { if(!is.character(selectionNames)) { stop('selectionNames needs to be a character vector of cell names') } if(!validateSelectionsObject(p2selections)) { stop('p2selections is not a valid p2 selection object') } if(any(!selectionNames %in% names(p2selections))) { stop('Some selection names were not found in the pagoda2 selections object') } cells <- unique(unname(unlist(lapply(p2selections[selectionNames], function(x) x$cells)))) invisible(cells) } plotSelectionOverlaps <- function(sel) { if (!requireNamespace("ggplot2", quietly = TRUE)) { stop("Package \"ggplot2\" needed for this function to work. Please install it.", call. = FALSE) } n1s = c() n2s = c() overlaps = c() for (n1 in names(sel)) { for (n2 in names(sel)) { if (n1 != n2) { overlapC = length(which(sel[[n1]]$cells %in% sel[[n2]]$cells)) } else { overlapC = 0 } n1s <- c(n1s, n1) n2s <- c(n2s, n2) overlaps = c(overlaps,overlapC) } } res <- data.frame(cbind(n1s, n2s, overlaps),stringsAsFactors=FALSE) res$overlaps <- as.numeric(res$overlaps) p <- ggplot2::ggplot(res, ggplot2::aes(n1s, n2s)) + ggplot2::geom_tile(ggplot2::aes(fill=log10(overlaps))) + ggplot2::theme(axis.text.x = ggplot2::element_text(angle = 90, hjust = 1)) + ggplot2::geom_text(ggplot2::aes(label=(overlaps))) + ggplot2::scale_fill_gradient(low = "yellow", high = "red") invisible(list(results=res, plot=p)) } plotMulticlassified <- function(sel) { if (!requireNamespace("ggplot2", quietly = TRUE)) { stop("Package \"ggplot2\" needed for this function to work. Please install it.", call. = FALSE) } multiclassified <- calcMulticlassified(sel) tmp1 <- as.data.frame(multiclassified) tmp1$lab <- rownames(tmp1) p <- ggplot2::ggplot(tmp1, ggplot2::aes(x=.data$lab, y= multiclassified)) + ggplot2::geom_bar(stat='identity') + ggplot2::theme_bw() + ggplot2::theme(axis.text.x = ggplot2::element_text(angle = 90, hjust = 1)) + ggplot2::scale_y_continuous(name='% multiclassified') + ggplot2::scale_x_discrete(name='Selection Label') invisible(p) } compareClusterings <- function(cl1, cl2, filename = NA) { if (!requireNamespace("pheatmap", quietly = TRUE)) { stop("Package \"pheatmap\" needed for this function to work. Please install it.", call. = FALSE) } n1 <- names(cl1) n2 <- names(cl2) if(!all(n1 %in% n2) || !all(n2 %in% n1)) { warning('Clusterings do not completely overlap!') ns <- intersect(n1,n2) } else { ns <- n1 } tbl <- table(data.frame(cl1[ns],cl2[ns])) tblNorm <- sweep(tbl, 2, colSums(tbl), FUN=`/`) pheatmap::pheatmap(tblNorm, file=filename) invisible(tblNorm) } diffExprOnP2FromWebSelection <- function(p2, sel, group1name, group2name) { grp1cells <- sel[[group1name]]$cells grp2cells <- sel[[group2name]]$cells t1 <- rep(NA, length(rownames(p2$counts))) names(t1) <- rownames(p2$counts) t1[grp1cells] <- c(group1name) t1[grp2cells] <- c(group2name) p2$getDifferentialGenes(groups=t1) } diffExprOnP2FromWebSelectionOneGroup <- function(p2, sel, groupname) { grp1cells <- sel[[groupname]]$cells t1 <- rep('other', length(rownames(p2$counts))) names(t1) <- rownames(p2$counts) t1[grp1cells] <- c(groupname) p2$getDifferentialGenes(groups=t1) } getIntExtNamesP2Selection <- function(x){ unlist(lapply(x, function(y) {y$name})) } readPagoda2SelectionAsFactor <- function(filepath, use.internal.name=FALSE) { factorFromP2Selection(removeSelectionOverlaps( readPagoda2SelectionFile(filepath) ),use.internal.name=use.internal.name) }
timssg4.var.label <- function(folder=getwd(), name="Variable labels", output=getwd()) { intsvy.var.label(folder=folder, name=name, output=output, config = timss4_conf) }
setClass(Class = "CVInfo2Par", slots = c(value = "matrix"), contains = c("CVInfo")) NULL setMethod(f = ".newCVInfo", signature = c(lambdas = "array", kernel = "MultiRadialKernel"), definition = function(lambdas, kernel, methodObject, cvObject, suppress, ...) { nl <- length(x = lambdas) nk <- length(x = kernel@kparam) valuePairs <- matrix(data = 0.0, nrow = nk, ncol = nl, dimnames = list(round(x = kernel@kparam, digits = 3L), round(x = lambdas, digits = 3L))) for (j in 1L:nk) { methodObject@kernel <- new("RadialKernel", model = kernel@model, kparam = kernel@kparam[j]) methodObject@kernel@X <- kernel@X for (k in 1L:nl) { if (suppress != 0L) { cat("Cross-validation for kparam =", kernel@kparam[j], "lambda =", lambdas[k], "\n") } res <- .newCVStep(cvObject = cvObject, methodObject = methodObject, lambda = lambdas[k], suppress = suppress, ...) if (is.null(x = res)) { valuePairs[j,k] <- NA } else { valuePairs[j,k] <- res } } } if (all(is.na(x = valuePairs)) ) return( NA ) bestKparam <- apply(X = valuePairs, MARGIN = 2L, FUN = function(x) { res <- length(x = x) - which.max(x = rev(x = x)) + 1L return( res ) }) ivl <- which.max(x = apply(X = valuePairs, MARGIN = 2L, FUN = max, na.rm = TRUE)) lambda <- lambdas[ivl] kparam <- kernel@kparam[bestKparam[ivl]] if (suppress != 0L) { cat("Selected parameters\n") cat("lambda =", lambda, "kparam =", kparam, "\n") } optKernel <- as(object = kernel, Class = "Kernel") optKernel@kparam <- kparam optKernel <- as(object = optKernel, Class = "RadialKernel") result <- new(Class = "CVInfo2Par", "value" = valuePairs, "params" = list("lambda" = lambdas, "kparam" = kernel@kparam), "optimal" = list("lambda" = lambda, "kernel" = optKernel)) return( result ) })
new_llr_boolean <- function(value = logical()) { vec_assert(value, logical()) stopifnot(!is.na(value), length(value) == 1) new_vctr(value, class = "llr_boolean", inherit_base_type = TRUE) } methods::setOldClass(c("llr_boolean", "vctrs_vctr")) format.llr_boolean <- function(x, ...) { if (isTRUE(x)) { "true" } else { "false" } } print.llr_boolean <- default_print vec_cast.logical.llr_boolean <- function(x, to, ...) { vec_data(x) } vec_arith.llr_boolean <- function(op, x, y, ...) { UseMethod("vec_arith.llr_boolean", y) } vec_arith.llr_boolean.default <- function(op, x, y, ...) { stop_incompatible_op(op, x, y) } vec_arith.llr_boolean.MISSING <- function(op, x, y, ...) { switch( op, "!" = new_llr_boolean(!vec_data(x)), stop_incompatible_op(op, x, y) ) }
IAT <- function(x) { if(missing(x)) stop("The x argument is required.") if(!is.vector(x)) x <- as.vector(x) dt <- x n <- length(x) mu <- mean(dt) s2 <- var(dt) maxlag <- max(3, floor(n/2)) Ga <- rep(0,2) Ga[1] <- s2 lg <- 1 Ga[1] <- Ga[1] + sum((dt[1:(n-lg)]-mu)*(dt[(lg+1):n]-mu)) / n m <- 1 lg <- 2*m Ga[2] <- sum((dt[1:(n-lg)]-mu)*(dt[(lg+1):n]-mu)) / n lg <- 2*m + 1 Ga[2] <- Ga[2] + sum((dt[1:(n-lg)]-mu)*(dt[(lg+1):n]-mu)) / n IAT <- Ga[1]/s2 while ((Ga[2] > 0.0) & (Ga[2] < Ga[1])) { m <- m + 1 if(2*m + 1 > maxlag) { cat("Not enough data, maxlag=", maxlag, "\n") break} Ga[1] <- Ga[2] lg <- 2*m Ga[2] <- sum((dt[1:(n-lg)]-mu)*(dt[(lg+1):n]-mu)) / n lg <- 2*m + 1 Ga[2] <- Ga[2] + sum((dt[1:(n-lg)]-mu)*(dt[(lg+1):n]-mu)) / n IAT <- IAT + Ga[1] / s2 } IAT <- -1 + 2*IAT return(IAT) }
library(testthat) library(dplyr) library(mrgsim.sa) context("test-lsa") mod <- mrgsolve::house() test_that("lsa", { mod <- mrgsolve::ev(mod, mrgsolve::ev(amt = 100)) out <- lsa(mod, par = "CL,VC", var = "CP") expect_is(out, "lsa") expect_is(out, "tbl_df") expect_equal(names(out), c("time", "dv_name", "dv_value", "p_name", "sens")) expect_equal(unique(out$dv_name), "CP") expect_equal(unique(out$p_name), c("CL", "VC")) }) test_that("lsa input and output errors", { expect_error(lsa(mod, par = "a,b,c"), regex = "invalid parameter") expect_error( lsa(mod, par = "CL", var = "a,b,c"), regex = "invalid output name" ) fun <- function(p, ...) { out <- mrgsim_df(mod) out$time <- NULL out } expect_error( lsa(mod, par = "CL", var = "CP", fun = fun), regex = "output from `fun` must contain" ) }) test_that("lsa plot", { out <- lsa(mod, par = "CL", var = "CP") ans <- lsa_plot(out) expect_is(ans, "gg") })
ORAnalysisFactorial <- function(dataset, FOM, FPFValue, alpha = 0.05, covEstMethod = "jackknife", nBoots = 200, analysisOption = "ALL") { RRRC <- NULL FRRC <- NULL RRFC <- NULL modalityID <- dataset$descriptions$modalityID I <- length(modalityID) foms <- UtilFigureOfMerit(dataset, FOM, FPFValue) ret <- UtilORVarComponentsFactorial(dataset, FOM, FPFValue, covEstMethod, nBoots) TRanova <- ret$TRanova VarCom <- ret$VarCom IndividualTrt <- ret$IndividualTrt IndividualRdr <- ret$IndividualRdr ANOVA <- list() ANOVA$TRanova <- TRanova ANOVA$VarCom <- VarCom ANOVA$IndividualTrt <- IndividualTrt ANOVA$IndividualRdr <- IndividualRdr trtMeans <- rowMeans(foms) trtMeans <- as.data.frame(trtMeans) colnames(trtMeans) <- "Estimate" trtMeanDiffs <- array(dim = choose(I, 2)) diffTRName <- array(dim = choose(I, 2)) ii <- 1 for (i in 1:I) { if (i == I) break for (ip in (i + 1):I) { trtMeanDiffs[ii] <- trtMeans[i,1] - trtMeans[ip,1] diffTRName[ii] <- paste0("trt", modalityID[i], sep = "-", "trt", modalityID[ip]) ii <- ii + 1 } } trtMeanDiffs <- data.frame("Estimate" = trtMeanDiffs, row.names = diffTRName, stringsAsFactors = FALSE) FOMs <- list( foms = foms, trtMeans = trtMeans, trtMeanDiffs = trtMeanDiffs ) if (analysisOption == "RRRC") { RRRC <- ORSummaryRRRC(dataset, FOMs, ANOVA, alpha, diffTRName) return(list( FOMs = FOMs, ANOVA = ANOVA, RRRC = RRRC )) } if (analysisOption == "FRRC") { FRRC <- ORSummaryFRRC(dataset, FOMs, ANOVA, alpha, diffTRName) return(list( FOMs = FOMs, ANOVA = ANOVA, FRRC = FRRC )) } if (analysisOption == "RRFC") { RRFC <- ORSummaryRRFC(dataset, FOMs, ANOVA, alpha, diffTRName) return(list( FOMs = FOMs, ANOVA = ANOVA, RRFC = RRFC )) } if (analysisOption == "ALL") { RRRC <- ORSummaryRRRC(dataset, FOMs, ANOVA, alpha, diffTRName) FRRC <- ORSummaryFRRC(dataset, FOMs, ANOVA, alpha, diffTRName) RRFC <- ORSummaryRRFC(dataset, FOMs, ANOVA, alpha, diffTRName) return(list( FOMs = FOMs, ANOVA = ANOVA, RRRC = RRRC, FRRC = FRRC, RRFC = RRFC )) } else stop("Incorrect analysisOption: must be `RRRC`, `FRRC`, `RRFC` or `ALL`") } FOMijk2VarCov <- function(resampleFOMijk, varInflFactor) { I <- dim(resampleFOMijk)[1] J <- dim(resampleFOMijk)[2] K <- dim(resampleFOMijk)[3] covariances <- array(dim = c(I, I, J, J)) for (i in 1:I) { for (ip in 1:I) { for (j in 1:J) { for (jp in 1:J) { covariances[i, ip, j, jp] <- cov(resampleFOMijk[i, j, ], resampleFOMijk[ip, jp, ]) } } } } Var <- 0 count <- 0 I <- dim(covariances)[1] J <- dim(covariances)[3] for (i in 1:I) { for (j in 1:J) { Var <- Var + covariances[i, i, j, j] count <- count + 1 } } if (count > 0) Var <- Var/count else Var <- 0 Cov1 <- 0 count <- 0 for (i in 1:I) { for (ip in 1:I) { for (j in 1:J) { if (ip != i) { Cov1 <- Cov1 + covariances[i, ip, j, j] count <- count + 1 } } } } if (count > 0) Cov1 <- Cov1/count else Cov1 <- 0 Cov2 <- 0 count <- 0 for (i in 1:I) { for (j in 1:J) { for (jp in 1:J) { if (j != jp) { Cov2 <- Cov2 + covariances[i, i, j, jp] count <- count + 1 } } } } if (count > 0) Cov2 <- Cov2/count else Cov2 <- 0 Cov3 <- 0 count <- 0 for (i in 1:I) { for (ip in 1:I) { if (i != ip) { for (j in 1:J) { for (jp in 1:J) { if (j != jp) { Cov3 <- Cov3 + covariances[i, ip, j, jp] count <- count + 1 } } } } } } if (count > 0) Cov3 <- Cov3/count else Cov3 <- 0 if (varInflFactor) { Var <- Var * (K - 1)^2/K Cov1 <- Cov1 * (K - 1)^2/K Cov2 <- Cov2 * (K - 1)^2/K Cov3 <- Cov3 * (K - 1)^2/K } return(list( Var = Var, Cov1 = Cov1, Cov2 = Cov2, Cov3 = Cov3 )) } FOMijk2VarCovSpA <- function(resampleFOMijk, varInflFactor) { I <- dim(resampleFOMijk)[1] J <- dim(resampleFOMijk)[2] K <- dim(resampleFOMijk)[3] covariances <- array(dim = c(I, I, J, J)) for (i in 1:I) { for (ip in 1:I) { for (j in 1:J) { for (jp in 1:J) { if (any(is.na(resampleFOMijk[i, j, ])) || any(is.na(resampleFOMijk[ip, jp, ]))) next covariances[i, ip, j, jp] <- cov(resampleFOMijk[i, j, ], resampleFOMijk[ip, jp, ]) } } } } Var_i <- rep(0,I) count_i <- rep(0,I) for (i in 1:I) { rdr_i <- which(!is.na(resampleFOMijk[i,,1])) for (j in 1:length(rdr_i)) { if (is.na(covariances[i, i, rdr_i[j], rdr_i[j]])) next Var_i[i] <- Var_i[i] + covariances[i, i, rdr_i[j], rdr_i[j]] count_i[i] <- count_i[i] + 1 } if (count_i[i] > 0) Var_i[i] <- Var_i[i]/count_i[i] else Var_i[i] <- 0 } Cov2_i <- rep(0,I) count_i <- rep(0,I) for (i in 1:I) { rdr_i <- which(!is.na(resampleFOMijk[i,,1])) for (j in 1:length(rdr_i)) { for (jp in 1:length(rdr_i)) { if (rdr_i[j] != rdr_i[jp]) { if (is.na(covariances[i, i, rdr_i[j], rdr_i[jp]])) next Cov2_i[i] <- Cov2_i[i] + covariances[i, i, rdr_i[j], rdr_i[jp]] count_i[i] <- count_i[i] + 1 } } } if (count_i[i] > 0) Cov2_i[i] <- Cov2_i[i]/count_i[i] else Cov2_i[i] <- 0 } Cov3_i <- rep(0,I) count_i <- rep(0,I) for (i in 1:I) { for (ip in 1:I) { rdr_i <- which(!is.na(resampleFOMijk[i,,1])) rdr_ip <- which(!is.na(resampleFOMijk[ip,,1])) if (i != ip) { for (j in 1:length(rdr_i)) { for (jp in 1:length(rdr_ip)) { if (rdr_i[j] != rdr_ip[jp]) { if (is.na(covariances[i, ip, rdr_i[j], rdr_ip[jp]])) next Cov3_i[i] <- Cov3_i[i] + covariances[i, ip, rdr_i[j], rdr_ip[jp]] count_i[i] <- count_i[i] + 1 } } } } } if (count_i[i] > 0) Cov3_i[i] <- Cov3_i[i]/count_i[i] else Cov3_i[i] <- 0 } if (varInflFactor) { Var_i <- Var_i * (K - 1)^2/K Cov2_i <- Cov2_i * (K - 1)^2/K Cov3_i <- Cov3_i * (K - 1)^2/K } return(list(Var_i = Var_i, Cov2_i = Cov2_i, Cov3_i = Cov3_i )) } varComponentsJackknifeFactorial <- function(dataset, FOM, FPFValue) { if (dataset$descriptions$design != "FCTRL") stop("This functions requires a factorial dataset") K <- length(dataset$ratings$NL[1,1,,1]) ret <- UtilPseudoValues(dataset, FOM, FPFValue) CovTemp <- FOMijk2VarCov(ret$jkFomValues, varInflFactor = TRUE) Cov <- list( Var = CovTemp$Var, Cov1 = CovTemp$Cov1, Cov2 = CovTemp$Cov2, Cov3 = CovTemp$Cov3 ) return(Cov) } varComponentsBootstrapFactorial <- function(dataset, FOM, FPFValue, nBoots, seed) { if (dataset$descriptions$design != "FCTRL") stop("This functions requires a factorial dataset") set.seed(seed) NL <- dataset$ratings$NL LL <- dataset$ratings$LL perCase <- dataset$lesions$perCase IDs <- dataset$lesions$IDs weights <- dataset$lesions$weights I <- length(NL[,1,1,1]) J <- length(NL[1,,1,1]) K <- length(NL[1,1,,1]) K2 <- length(LL[1,1,,1]) K1 <- (K - K2) maxNL <- length(NL[1,1,1,]) maxLL <- length(LL[1,1,1,]) if (FOM %in% c("MaxNLF", "ExpTrnsfmSp", "HrSp")) { stop("This needs fixing") fomBsArray <- array(dim = c(I, J, nBoots)) for (b in 1:nBoots) { kBs <- ceiling(runif(K1) * K1) for (i in 1:I) { for (j in 1:J) { NLbs <- NL[i, j, kBs, ] LLbs <- LL[i, j, , ] dim(NLbs) <- c(K1, maxNL) dim(LLbs) <- c(K2, maxLL) fomBsArray[i, j, b] <- MyFom_ij(NLbs, LLbs, perCase, IDs, weights, maxNL, maxLL, K1, K2, FOM, FPFValue) } } } } else if (FOM %in% c("MaxLLF", "HrSe")) { stop("This needs fixing") fomBsArray <- array(dim = c(I, J, nBoots)) for (b in 1:nBoots) { kBs <- ceiling(runif(K2) * K2) for (i in 1:I) { for (j in 1:J) { NLbs <- NL[i, j, c(1:K1, (kBs + K1)), ] LLbs <- LL[i, j, kBs, ] dim(NLbs) <- c(K, maxNL) dim(LLbs) <- c(K2, maxLL) lesionIDBs <- IDs[kBs, ] dim(lesionIDBs) <- c(K2, maxLL) lesionWeightBs <- weights[kBs, ] dim(lesionWeightBs) <- c(K2, maxLL) fomBsArray[i, j, b] <- MyFom_ij(NLbs, LLbs, perCase[kBs], lesionIDBs, lesionWeightBs, maxNL, maxLL, K1, K2, FOM, FPFValue) } } } } else { fomBsArray <- array(dim = c(I, J, nBoots)) for (b in 1:nBoots) { k1bs <- ceiling(runif(K1) * K1) k2bs <- ceiling(runif(K2) * K2) for (i in 1:I) { for (j in 1:J) { NLbs <- NL[i, j, c(k1bs, k2bs + K1), ] lesionVectorbs <- perCase[k2bs] LLbs <- LL[i, j, k2bs,1:max(lesionVectorbs)] dim(NLbs) <- c(K, maxNL) dim(LLbs) <- c(K2, max(lesionVectorbs)) lesionIDBs <- IDs[k2bs, ] dim(lesionIDBs) <- c(K2, maxLL) lesionWeightBs <- weights[k2bs, ] dim(lesionWeightBs) <- c(K2, maxLL) fomBsArray[i, j, b] <- MyFom_ij(NLbs, LLbs, lesionVectorbs, lesionIDBs, lesionWeightBs, maxNL, maxLL, K1, K2, FOM, FPFValue) } } } } Cov <- FOMijk2VarCov(fomBsArray, varInflFactor = FALSE) Var <- Cov$Var Cov1 <- Cov$Cov1 Cov2 <- Cov$Cov2 Cov3 <- Cov$Cov3 return(list( Var = Var, Cov1 = Cov1, Cov2 = Cov2, Cov3 = Cov3 )) } varComponentsDeLongFactorial <- function(dataset, FOM) { if (dataset$descriptions$design != "FCTRL") stop("This functions requires a factorial dataset") UNINITIALIZED <- RJafrocEnv$UNINITIALIZED NL <- dataset$ratings$NL LL <- dataset$ratings$LL perCase <- dataset$lesions$perCase I <- length(NL[,1,1,1]) J <- length(NL[1,,1,1]) K <- length(NL[1,1,,1]) K2 <- length(LL[1,1,,1]) K1 <- (K - K2) maxNL <- length(NL[1,1,1,]) maxLL <- length(LL[1,1,1,]) fomArray <- UtilFigureOfMerit(dataset, FOM) if (!FOM %in% c("Wilcoxon", "HrAuc", "ROI")) stop("DeLong\"s method can only be used for trapezoidal figures of merit.") if (FOM == "ROI") { kI01 <- which(apply((NL[1, 1, , ] != UNINITIALIZED), 1, any)) numKI01 <- rowSums((NL[1, 1, , ] != UNINITIALIZED)) I01 <- length(kI01) I10 <- K2 N <- sum((NL[1, 1, , ] != UNINITIALIZED)) M <- sum(perCase) V01 <- array(dim = c(I, J, I01, maxNL)) V10 <- array(dim = c(I, J, I10, maxLL)) for (i in 1:I) { for (j in 1:J) { for (k in 1:I10) { for (el in 1:perCase[k]) { V10[i, j, k, el] <- (sum(as.vector(NL[i, j, , ][NL[i, j, , ] != UNINITIALIZED]) < LL[i, j, k, el]) + 0.5 * sum(as.vector(NL[i, j, , ][NL[i, j, , ] != UNINITIALIZED]) == LL[i, j, k, el]))/N } } for (k in 1:I01) { for (el in 1:maxNL) { if (NL[i, j, kI01[k], el] == UNINITIALIZED) next V01[i, j, k, el] <- (sum(NL[i, j, kI01[k], el] < as.vector(LL[i, j, , ][LL[i, j, , ] != UNINITIALIZED])) + 0.5 * sum(NL[i, j, kI01[k], el] == as.vector(LL[i, j, , ][LL[i, j, , ] != UNINITIALIZED])))/M } } } } s10 <- array(0, dim = c(I, I, J, J)) s01 <- array(0, dim = c(I, I, J, J)) s11 <- array(0, dim = c(I, I, J, J)) for (i in 1:I) { for (ip in 1:I) { for (j in 1:J) { for (jp in 1:J) { for (k in 1:I10) { s10[i, ip, j, jp] <- (s10[i, ip, j, jp] + (sum(V10[i, j, k, !is.na(V10[i, j, k, ])]) - perCase[k] * fomArray[i, j]) * (sum(V10[ip, jp, k, !is.na(V10[ip, jp, k, ])]) - perCase[k] * fomArray[ip, jp])) } for (k in 1:I01) { s01[i, ip, j, jp] <- (s01[i, ip, j, jp] + (sum(V01[i, j, k, !is.na(V01[i, j, k, ])]) - numKI01[kI01[k]] * fomArray[i, j]) * (sum(V01[ip, jp, k, !is.na(V01[ip, jp, k, ])]) - numKI01[kI01[k]] * fomArray[ip, jp])) } allAbn <- 0 for (k in 1:K2) { if (all(NL[ip, jp, k + K1, ] == UNINITIALIZED)) { allAbn <- allAbn + 1 next } s11[i, ip, j, jp] <- (s11[i, ip, j, jp] + (sum(V10[i, j, k, !is.na(V10[i, j, k, ])]) - perCase[k] * fomArray[i, j]) * (sum(V01[ip, jp, k + K1 - allAbn, !is.na(V01[ip, jp, k + K1 - allAbn, ])]) - numKI01[K1 + k] * fomArray[ip, jp])) } } } } } s10 <- s10 * I10/(I10 - 1)/M s01 <- s01 * I01/(I01 - 1)/N s11 <- s11 * K/(K - 1) S <- array(0, dim = c(I, I, J, J)) for (i in 1:I) { for (ip in 1:I) { for (j in 1:J) { for (jp in 1:J) { S[i, ip, j, jp] <- s10[i, ip, j, jp]/M + s01[i, ip, j, jp]/N + s11[i, ip, j, jp]/(M * N) + s11[ip, i, jp, j]/(M * N) } } } } } else { V10 <- array(dim = c(I, J, K2)) V01 <- array(dim = c(I, J, K1)) for (i in 1:I) { for (j in 1:J) { nl <- NL[i, j, 1:K1, ] ll <- cbind(NL[i, j, (K1 + 1):K, ], LL[i, j, , ]) dim(nl) <- c(K1, maxNL) dim(ll) <- c(K2, maxNL + maxLL) fp <- apply(nl, 1, max) tp <- apply(ll, 1, max) for (k in 1:K2) { V10[i, j, k] <- (sum(fp < tp[k]) + 0.5 * sum(fp == tp[k]))/K1 } for (k in 1:K1) { V01[i, j, k] <- (sum(fp[k] < tp) + 0.5 * sum(fp[k] == tp))/K2 } } } s10 <- array(dim = c(I, I, J, J)) s01 <- array(dim = c(I, I, J, J)) for (i in 1:I) { for (ip in 1:I) { for (j in 1:J) { for (jp in 1:J) { s10[i, ip, j, jp] <- sum((V10[i, j, ] - fomArray[i, j]) * (V10[ip, jp, ] - fomArray[ip, jp]))/(K2 - 1) s01[i, ip, j, jp] <- sum((V01[i, j, ] - fomArray[i, j]) * (V01[ip, jp, ] - fomArray[ip, jp]))/(K1 - 1) } } } } S <- s10/K2 + s01/K1 } covariances <- S Var <- 0 count <- 0 for (i in 1:I) { for (j in 1:J) { Var <- Var + covariances[i, i, j, j] count <- count + 1 } } if (count > 0) Var <- Var/count else Var <- 0 Cov1 <- 0 count <- 0 for (i in 1:I) { for (ip in 1:I) { for (j in 1:J) { if (ip != i) { Cov1 <- Cov1 + covariances[i, ip, j, j] count <- count + 1 } } } } if (count > 0) Cov1 <- Cov1/count else Cov1 <- 0 Cov2 <- 0 count <- 0 for (i in 1:I) { for (j in 1:J) { for (jp in 1:J) { if (j != jp) { Cov2 <- Cov2 + covariances[i, i, j, jp] count <- count + 1 } } } } if (count > 0) Cov2 <- Cov2/count else Cov2 <- 0 Cov3 <- 0 count <- 0 for (i in 1:I) { for (ip in 1:I) { if (i != ip) { for (j in 1:J) { for (jp in 1:J) { if (j != jp) { Cov3 <- Cov3 + covariances[i, ip, j, jp] count <- count + 1 } } } } } } if (count > 0) Cov3 <- Cov3/count else Cov3 <- 0 return(list( Var = Var, Cov1 = Cov1, Cov2 = Cov2, Cov3 = Cov3)) }
start_activities <- function(eventlog, level, append, ...) { UseMethod("start_activities") } start_activities.eventlog <- function(eventlog, level = c("log","case","activity","resource","resource-activity"), append = FALSE, append_column = NULL, sort = TRUE, ...) { level <- match.arg(level) level <- deprecated_level(level, ...) absolute <- NULL if(is.null(append_column)) { append_column <- case_when(level == "activity" ~ "absolute", level == "resource" ~ "absolute", level == "resource-activity" ~ "absolute", level == "case" ~ activity_id(eventlog), T ~ "NA") } FUN <- switch(level, log = start_activities_log, case = start_activities_case, activity = start_activities_activity, resource = start_activities_resource, "resource-activity" = start_activities_resource_activity) output <- FUN(eventlog = eventlog) if(sort && level %in% c("activity", "resource","resource-activity")) { output %>% arrange(-absolute) -> output } return_metric(eventlog, output, level, append, append_column, "start_activities", ifelse(level == "case",1,3)) } start_activities.grouped_eventlog <- function(eventlog, level = c("log","case","activity","resource","resource-activity"), append = FALSE, append_column = NULL, sort = TRUE, ...) { absolute <- NULL level <- match.arg(level) level <- deprecated_level(level, ...) FUN <- switch(level, log = start_activities_log, case = start_activities_case, activity = start_activities_activity, resource = start_activities_resource, "resource-activity" = start_activities_resource_activity) grouped_metric(eventlog, FUN) -> output if(sort && level %in% c("activity", "resource","resource-activity")) { output %>% arrange(-absolute) -> output } return_metric(eventlog, output, level, append,append_column, "start_activities", ifelse(level == "case",1,3)) }
d = read.csv('http://www.nd.edu/~mclark19/learn/data/pisasci2006.csv') library(psych) describe(d)[-1,1:9] library(mgcv) mod_lm <- gam(Overall ~ Income, data=d) summary(mod_lm) mod_gam1 <- gam(Overall ~ s(Income, bs="cr"), data=d) summary(mod_gam1) AIC(mod_lm) summary(mod_lm)$sp.criterion summary(mod_lm)$r.sq anova(mod_lm, mod_gam1, test="Chisq") mod_lm2 <- gam(Overall ~ Income + Edu + Health, data=d) summary(mod_lm2) mod_gam2 <- gam(Overall ~ s(Income) + s(Edu) + s(Health), data=d) summary(mod_gam2) mod_gam2B = update(mod_gam2, .~.-s(Health) + Health) summary(mod_gam2B) mod_gam3 <- gam(Overall ~ te(Income,Edu), data=d) summary(mod_gam3) anova(mod_lm2, mod_gam2, test="Chisq") gam.check(mod_gam2, k.rep=1000) mod_1d = gam(Overall ~ s(Income) + s(Edu), data=d) mod_2d = gam(Overall ~ te(Income,Edu, bs="tp"), data=d) AIC(mod_1d, mod_2d) mod_A = gam(Overall ~ s(Income, bs="cr", k=5) + s(Edu, bs="cr", k=5), data=d) mod_B = gam(Overall ~ s(Income, bs="cr", k=5) + s(Edu, bs="cr", k=5) + te(Income, Edu), data=d) anova(mod_A,mod_B, test="Chi")
get_col_values <- function(lpt, col = 1, start_row = 2, rows_left = 0) { label <- c() table <- c() for (i in seq_along(lpt)) { label <- c(label, lpt[[i]][start_row:(nrow(lpt[[i]]) - rows_left), col]) table <- c(table, rep(i, nrow(lpt[[i]]) - rows_left - start_row + 1)) } data.frame(table, label, stringsAsFactors = FALSE) }
testarggapVIR <- function(z, dimx, grobj, arggrobj, echo=FALSE) { nplayer <- length(dimx) if(!is.function(grobj)) stop("argument grobj must be a function.") if(echo) { print(dimx) print(length(z)) } if(length(z) != sum(dimx)) stop("CER: incompatible dimension for dimx.") if(!missing(arggrobj) && !is.null(arggrobj)) grobjfinal <- grobj else { grobjfinal <- function(z, i, j, ...) grobj(z, i, j) arggrobj <- list() } str <- paste("the call to obj(z, 1, argobj) does not work.", "arguments are", paste(names(formals(grobj)), collapse=","), ".") testfunc(grobjfinal, z, arg=arggrobj, echo=echo, errmess=str) list(grobj=grobjfinal, arggrobj=arggrobj, dimx=dimx, nplayer=nplayer) } testarggradygapVIR <- function(z, dimx, grobj, arggrobj, echo=FALSE) { nplayer <- length(dimx) if(!is.function(grobj)) stop("argument grobj must be a function.") if(echo) { print(dimx) print(length(z)) } if(length(z) != sum(dimx)) stop("CER: incompatible dimension for dimx.") if(!missing(arggrobj) && !is.null(arggrobj)) grobjfinal <- grobj else { grobjfinal <- function(z, i, j, ...) grobj(z, i, j) arggrobj <- list() } str <- paste("the call to grobj(z, 1, 1, arggrobj) does not work.", "arguments are", paste(names(formals(grobj)), collapse=","), ".") testfunc(grobjfinal, z, arg=arggrobj, echo=echo, errmess=str) list(grobj=grobjfinal, arggrobj=arggrobj, dimx=dimx, nplayer=nplayer) } testarggradxgapVIR <- function(z, dimx, grobj, arggrobj, heobj, argheobj, echo=FALSE) { nplayer <- length(dimx) if(!is.function(grobj)) stop("argument grobj must be a function.") if(echo) { print(dimx) print(length(z)) } if(length(z) != sum(dimx)) stop("CER: incompatible dimension for dimx.") if(!missing(arggrobj) && !is.null(arggrobj)) grobjfinal <- grobj else { grobjfinal <- function(z, i, j, ...) grobj(z, i, j) arggrobj <- list() } str <- paste("the call to grobj(z, 1, 1, arggrobj) does not work.", "arguments are", paste(names(formals(grobj)), collapse=","), ".") testfunc(grobjfinal, z, arg=arggrobj, echo=echo, errmess=str) if(!missing(argheobj) && !is.null(argheobj)) heobjfinal <- heobj else { heobjfinal <- function(z, i, j, k, ...) heobj(z, i, j, k) argheobj <- list() } str <- paste("the call to heobj(z, 1, 1, 1, argheobj) does not work.", "arguments are", paste(names(formals(heobj)), collapse=","), ".") testfunc(heobjfinal, z, arg=argheobj, echo=echo, errmess=str) list(grobj=grobjfinal, arggrobj=arggrobj, heobj=heobjfinal, argheobj=argheobj, dimx=dimx, nplayer=nplayer) } testargfpVIR <- function(z, dimx, obj, argobj, joint, argjoint, grobj, arggrobj, jacjoint, argjacjoint, echo=FALSE) { nplayer <- length(dimx) if(!is.function(obj)) stop("argument obj must be a function.") if(missing(joint)) joint <- NULL else if(!is.function(joint) && !is.null(joint)) stop("argument joint must be a function.") if(length(z) != sum(dimx)) stop("incompatible dimension for dimx.") if(missing(grobj)) grobj <- NULL if(missing(jacjoint)) jacjoint <- NULL if(!is.null(jacjoint) && is.null(grobj)) stop("missing grobj argument.") if(!missing(argobj) && !is.null(argobj)) objfinal <- obj else { objfinal <- function(z, i, ...) obj(z, i) argobj <- list() } str <- paste("the call to obj(z, 1, argobj) does not work.", "arguments are", paste(names(formals(obj)), collapse=","), ".") testfunc(objfinal, z, arg=argobj, echo=echo, errmess=str) if(!is.null(joint)) { if(!missing(argjoint) && !is.null(argjoint)) jointfinal <- joint else { jointfinal <- function(z, ...) joint(z) argjoint <- list() } str <- paste("the call to joint(z, argconstr) does not work.", "arguments are", paste(names(formals(joint)), collapse=","), ".") testfunc(jointfinal, z, arg=argjoint, echo=echo, errmess=str) }else jointfinal <- argjoint <- NULL if(!is.null(grobj)) { if(!missing(arggrobj) && !is.null(arggrobj)) grobjfinal <- grobj else { grobjfinal <- function(z, i, j, ...) grobj(z, i, j) arggrobj <- list() } str <- paste("the call to grobj(z, 1, 1, arggrobj) does not work.", "arguments are", paste(names(formals(grobj)), collapse=","), ".") testfunc(grobjfinal, z, arg=arggrobj, echo=echo, errmess=str) }else grobjfinal <- arggrobj <- NULL if(!is.null(jacjoint)) { if(!missing(argjacjoint) && !is.null(argjacjoint)) jacjointfinal <- jacjoint else { jacjointfinal <- function(z, ...) jacjoint(z) argjacjoint <- list() } str <- paste("the call to jacjoint(z, argjacjoint) does not work.", "arguments are", paste(names(formals(jacjoint)), collapse=","), ".") testfunc(jacjointfinal, z, arg=argjacjoint, echo=echo, errmess=str) }else jacjointfinal <- argjacjoint <- NULL list(obj=objfinal, argobj=argobj, grobj=grobjfinal, arggrobj=arggrobj, joint=jointfinal, argjoint=argjoint, jacjoint=jacjointfinal, argjacjoint=argjacjoint, dimx=dimx, nplayer=nplayer) }
archetypoids_funct_multiv <- function(numArchoid, data, huge = 200, ArchObj, PM){ x11 <- t(data[,,1]) x12 <- t(data[,,2]) x1 <- rbind(x11 ,x12) data <- t(x1) N <- dim(data)[1] ai <- archetypes::bestModel(ArchObj[[1]]) if (is.null(archetypes::parameters(ai))) { stop("No archetypes computed") } dime <- dim(archetypes::parameters(ai)) ar <- archetypes::parameters(ai) R <- matrix(0, nrow = dime[1], ncol = N) for (di in 1:dime[1]) { Raux <- matrix(ar[di,], byrow = FALSE, ncol = N, nrow = dime[2]) - t(data) dii <- dim(Raux) R[di,] <- apply(Raux[1:(dii[1]/2),], 2, int_prod_mat_funct, PM = PM) + apply(Raux[(dii[1]/2 + 1):dii[1],], 2, int_prod_mat_funct, PM = PM) } ini_arch <- apply(R, 1, which.min) if (all(ini_arch > numArchoid) == FALSE) { k = 1 neig <- knn(data, archetypes::parameters(ai), 1:N, k = k) indices1 <- attr(neig, "nn.index") ini_arch <- indices1[,k] while (any(duplicated(ini_arch))) { k = k + 1 neig <- knn(data, archetypes::parameters(ai), 1:N, k = k) indicesk <- attr(neig, "nn.index") dupl <- anyDuplicated(indices1[,1]) ini_arch <- c(indices1[-dupl,1],indicesk[dupl,k]) } } n <- ncol(t(data)) x_gvv <- rbind(t(data), rep(huge, n)) zs <- x_gvv[,ini_arch] zs <- as.matrix(zs) alphas <- matrix(0, nrow = numArchoid, ncol = n) for (j in 1:n) { alphas[, j] = coef(nnls(zs, x_gvv[,j])) } resid <- zs[1:(nrow(zs) - 1),] %*% alphas - x_gvv[1:(nrow(x_gvv) - 1),] rss_ini <- frobenius_norm_funct_multiv(resid, PM) / n res_def <- swap_funct_multiv(ini_arch, rss_ini, huge, numArchoid, x_gvv, n, PM) return(res_def) }
success <- c(158, 109) n <- c(444,922)
library(testthat) context('General tests') x <- runif(1000)*10^runif(1000, min=1e-20, max=20) test_that('Zero values are left alone', { expect_equal(0, squeeze_bits(0, 1, method='trim')) expect_equal(0, squeeze_bits(0, 1, method='pad')) }) test_that('Infinite values are left alone', { expect_equal(Inf, squeeze_bits(Inf, 1, method='trim')) expect_equal(Inf, squeeze_bits(Inf, 1, method='pad')) expect_equal(-Inf, squeeze_bits(-Inf, 1, method='trim')) expect_equal(-Inf, squeeze_bits(-Inf, 1, method='pad')) }) test_that('NA values are left alone', { expect_equal(NA_real_, squeeze_bits(NA_real_, 1, method='trim')) expect_equal(NA_real_, squeeze_bits(NA_real_, 1, method='pad')) }) test_that('We ignore trimming when the tolerance is too small', { z <- pi*1e15 expect_equal(z, squeeze_bits(z, 3, method='trim', decimal=TRUE)) expect_equal(x, squeeze_bits(x, 17, method='trim', decimal=FALSE)) }) test_that('Trimmed values biased low and within specified tolerance', { for (i in 1:15) { trimmed <- squeeze_bits(x, i, method='trim', decimal=FALSE) expect_true(all(trimmed <= x)) expect_true(all(abs(trimmed - x)/x < 10^-i)) } }) test_that('Values can be trimmed using a decimal digits tolerance', { for (i in -15:15) { trimmed <- squeeze_bits(x, i, method='trim', decimal=TRUE) expect_true(all(trimmed <= x)) expect_true(all(abs(trimmed - x) < 10^-i)) } }) test_that('Values can be padded using a decimal digits tolerance', { for (i in -15:15) { padded <- squeeze_bits(x, i, method='pad', decimal=TRUE) expect_true(all(padded >= x)) expect_true(all(abs(padded - x) < 10^-i)) } }) test_that('Padded values biased high and within specified tolerance', { for (i in 1:15) { padded <- squeeze_bits(x, i, method='pad', decimal=FALSE) expect_true(all(padded >= x)) expect_true(all(abs(padded-x)/x < 10^-i)) } }) test_that('Groomed values are within specified tolerance', { for (i in 1:15) { groomed <- squeeze_bits(x, i, method='groom', decimal=FALSE) expect_true(all(abs(groomed-x)/x < 10^-i)) } })
args <- commandArgs(TRUE) if("--fresh" %in% args) unlink(reticulate::miniconda_path(), recursive = TRUE) tf_vers <- c("2.1", "2.2", "2.3", "2.4", "2.5", "2.6", "2.7", "nightly") tf_vers <- paste0(tf_vers, "-cpu") py_vers <- c("3.6", "3.6", "3.7", "3.8", "3.8", "3.9", "3.9", "3.9") names(tf_vers) <- paste0("tf-", tf_vers) names(tf_vers) <- sub(".0rc[0-9]+", "", names(tf_vers)) if(!reticulate:::miniconda_exists()) reticulate::install_miniconda() for (i in seq_along(tf_vers)) keras::install_keras( version = tf_vers[i], envname = names(tf_vers)[i], conda_python_version = py_vers[i], pip_ignore_installed = TRUE, method = "conda", restart_session = FALSE)
test_that("a non-function option fails", { expect_error(trajectory() %>% branch(1, TRUE, trajectory())) }) test_that("the wrong number of elements fails, but continue is recycled", { expect_error(trajectory() %>% branch(function() 1, c(TRUE, TRUE), trajectory())) expect_silent(trajectory() %>% branch(function() 1, TRUE, trajectory(), trajectory())) }) test_that("an index equal to 0 skips the branch", { t0 <- trajectory() %>% branch(function() 0, TRUE, trajectory() %>% timeout(1) ) %>% timeout(2) env <- simmer(verbose = TRUE) %>% add_generator("entity", t0, at(0)) %>% run() expect_equal(env %>% now(), 2) }) test_that("an index out of range fails", { t1 <- trajectory() %>% branch(function() 1, TRUE, trajectory() %>% timeout(1) ) t2 <- trajectory() %>% branch(function() 2, TRUE, trajectory() %>% timeout(1) ) env <- simmer(verbose = TRUE) %>% add_generator("entity", t2, at(0)) expect_error(env %>% run()) env <- simmer(verbose = TRUE) %>% add_generator("entity", t1, at(0)) %>% run() expect_equal(env %>% now(), 1) }) test_that("accepts a list of trajectories", { t1 <- trajectory() %>% timeout(1) t2 <- trajectory() %>% branch(function() 1, continue=TRUE, replicate(10, t1)) expect_equal(length(t2), 1) expect_equal(get_n_activities(t2), 11) }) test_that("the continue argument works as expected", { sequential <- function(n) { i <- 0 function() { i <<- i + 1 if (i > n) i <<- 1 i } } t0 <- trajectory() t1 <- trajectory() %>% timeout(1) t <- trajectory() %>% branch( sequential(4), continue=c(FALSE, TRUE, FALSE, TRUE), t0, t0, t1, t1 ) %>% timeout(1) arr <- simmer(verbose = TRUE) %>% add_generator("dummy", t, at(0:3)) %>% run() %>% get_mon_arrivals() expect_equal(arr$start_time, 0:3) expect_equal(arr$activity_time, c(0, 1, 1, 2)) })
NULL scale_x_units <- function(..., position = "bottom", unit = NULL) { if (!requireNamespace("ggplot2", quietly=TRUE)) stop("package 'ggplot2' is required for this functionality", call.=FALSE) sc <- ggplot2::continuous_scale( c("x", "xmin", "xmax", "xend", "xintercept", "xmin_final", "xmax_final", "xlower", "xmiddle", "xupper"), "position_c", identity, ..., position = position, guide = ggplot2::waiver(), super = MakeScaleContinuousPositionUnits() ) sc$units <- as_units(unit) sc } scale_y_units <- function(..., unit = NULL) { if (!requireNamespace("ggplot2", quietly=TRUE)) stop("package 'ggplot2' is required for this functionality", call.=FALSE) sc <- ggplot2::continuous_scale( c("y", "ymin", "ymax", "yend", "yintercept", "ymin_final", "ymax_final", "lower", "middle", "upper"), "position_c", identity, ..., guide = ggplot2::waiver(), super = MakeScaleContinuousPositionUnits() ) sc$units <- as_units(unit) sc } MakeScaleContinuousPositionUnits <- function() { ggplot2::ggproto( "ScaleContinuousPositionUnits", ggplot2::ScaleContinuousPosition, units = NULL, train = function(self, x) { if (length(x) == 0) return() if (!is.null(self$units)) units(x) <- as_units(1, self$units) self$range$train(x) }, map = function(self, x, limits = self$get_limits()) { if (inherits(x, "units")) { if (is.null(self$units)) self$units <- units(x) else units(x) <- as_units(1, self$units) x <- drop_units(x) } ggplot2::ggproto_parent( ggplot2::ScaleContinuousPosition, self)$map(x, limits) }, make_title = function(self, title) { if (!is.null(title)) title <- make_unit_label(title, as_units(1, self$units)) title } ) } scale_type.units <- function(x) { if (!"units" %in% .packages()) stop("Variable of class 'units' found, but 'units' package is not attached.\n", " Please, attach it using 'library(units)' to properly show scales with units.") c("units", "continuous") }
fairProportions <- function (phy, nodeCount=FALSE) { treeMatrix <- caper::clade.matrix(phy) fpEdgeVals <- treeMatrix$edge.length / apply(treeMatrix$clade.matrix, 1, sum) fpTips <- as.matrix(apply(fpEdgeVals * treeMatrix$clade.matrix, 2, sum)) if (nodeCount == TRUE) { nodeCount <- apply(treeMatrix$clade.matrix, 2, sum) - 1 fpTips <- cbind(fpTips, nodeCount) colnames(fpTips) <- c("FP", "NodeCount") rownames(fpTips) <- phy$tip.label } else { rownames(fpTips) <- phy$tip.label } rm(treeMatrix) return(fpTips) }
tableplot_jpg <- function(data, target, nBins = 100, folder = "./autoplots/plot_", ID = FALSE, width = 960, height = 960, pointsize = 12) { data <- tablePrepare(data.frame(target = target, data)) for (i in 2:ncol(data)) { jpeg(filename = paste(folder, ifelse(ID == FALSE, colnames(data)[i], i-1), ".jpg", sep = ""), width = width, height = height, units = "px", pointsize = pointsize) tableplot(dat = data, select = c(1,i), sortCol = target, sample = FALSE, nBins = nBins) dev.off() } }
source("testthat/helper-common.R") pdf(file = "eafplot.pdf", title = "eafplot.pdf", width = 6, height = 6) data(gcp2x2) tabucol <- subset(gcp2x2, alg != "TSinN1") tabucol$alg <- tabucol$alg[drop = TRUE] eafplot(time + best ~ run, data = tabucol, subset = tabucol$inst == "DSJC500.5") eafplot(time + best ~ run | inst, groups = alg, data = gcp2x2) eafplot(time + best ~ run | inst, groups = alg, data = gcp2x2, percentiles = c(0, 50, 100), include.extremes = TRUE, cex = 1.4, lty = c(2, 1, 2), lwd = c(2, 2, 2), col = c("black", "blue", "grey50")) A1 <- read_extdata("ALG_1_dat.xz") A2 <- read_extdata("ALG_2_dat.xz") eafplot(list(A1 = A1, A2 = A2), percentiles = 50) eafplot(A1, type="area", legend.pos="bottomleft") data(HybridGA) data(SPEA2relativeVanzyl) eafplot(SPEA2relativeVanzyl, percentiles = c(25, 50, 75), xlab = expression(C[E]), ylab = "Total switches", xlim = c(320, 400), extra.points = HybridGA$vanzyl, extra.legend = "Hybrid GA") data(SPEA2relativeRichmond) eafplot(SPEA2relativeRichmond, percentiles = c(25, 50, 75), xlab = expression(C[E]), ylab = "Total switches", xlim = c(90, 140), ylim = c(0, 25), extra.points = HybridGA$richmond, extra.lty = "dashed", extra.legend = "Hybrid GA") data(SPEA2minstoptimeRichmond) SPEA2minstoptimeRichmond[, 2] <- SPEA2minstoptimeRichmond[, 2] / 60 eafplot(SPEA2minstoptimeRichmond, xlab = expression(C[E]), ylab = "Minimum idle time (minutes)", las = 1, log = "y", maximise = c(FALSE, TRUE), main = "SPEA2 (Richmond)") dev.off()
assort_rvalues <- reactiveValues( mixmat_message = NULL ) output$assortativity_details_output <- renderText({ assortativityPrelimOutput() }) output$mixing_matrix <- DT::renderDataTable({ DT::datatable(assortativityMMOutput(), options = list(paging = F, searching = F, bInfo = F, ordering = F)) }) output$assortativity_homophily_output <- renderText({ homophilyOutput() }) output$mixing_matrix_details_output <- renderText({ assort_rvalues$mixmat_message }) assortativityPrelimOutput <- reactive({ g <- graphFilters() output <- c() if (!is.null(g)) { CA_sel <- ng_rv$graph_cat_selected if (nchar(CA_sel) && CA_sel != "All") { output <- append(output, paste0("Selected categorical attribute is: ", CA_sel)) output <- append(output, "") } else { return(NULL) } } else { return(NULL) } paste0(output, collapse = '\n') }) assortativityMMOutput <- reactive({ g <- graphFilters() if (!is.null(g)) { CA_sel <- ng_rv$graph_cat_selected if (nchar(CA_sel) && CA_sel != "All") { assort_rvalues$mixmat_message <- NULL df <- VOSONDash::mixmat(g, paste0("vosonCA_", CA_sel), use_density = FALSE) return(df) } else { assort_rvalues$mixmat_message <- "Categorical attribute not present, or not selected." return(NULL) } } else { assort_rvalues$mixmat_message <- "No Data." return(NULL) } }) homophilyOutput <- reactive({ g <- graphFilters() output <- c() if (!is.null(g)) { CA_sel <- ng_rv$graph_cat_selected if (nchar(CA_sel) && CA_sel != "All") { vattr <- paste0('vosonCA_', CA_sel) mm <- VOSONDash::mixmat(g, paste0("vosonCA_", CA_sel), use_density = FALSE) attr_list <- ng_rv$graph_cats[[CA_sel]] if (input$graph_sub_cats_select[1] != "All") { attr_list <- input$graph_sub_cats_select } for (i in attr_list) { output <- append(output, paste0("Category: ", i)) w_i <- length(which(vertex_attr(g, vattr) == i)) / length(V(g)) output <- append(output, paste0(" Population share: ", sprintf("%.3f", w_i))) if (w_i > 0) { H_i <- mm[i, i] / rowSums(mm)[i] output <- append(output, paste0(" Homogeneity index: ", sprintf("%.3f", H_i))) Hstar_i <- (H_i - w_i) / (1 - w_i) output <- append(output, paste0(" Homophily index: ", sprintf("%.3f", Hstar_i))) } output <- append(output, "") } output <- append(output, "") }else{ output <- append(output, paste0("Categorical attribute not present, or not selected.")) } }else{ output <- append(output, paste0("No data.")) } paste0(output, collapse = '\n') })
mark_my_file <- function(tasks = NULL, mark_file=file.choose(), assignment_path = NULL, force_get_tests = FALSE, quiet = FALSE, ...){ checkmate::assert_character(tasks, null.ok = TRUE) checkmate::assert_file_exists(mark_file) checkmate::assert_string(assignment_path, null.ok = TRUE) checkmate::assert_flag(force_get_tests) checkmate::assert_flag(quiet) if(force_get_tests){ .Deprecated("set_assignment()", old = "force_get_tests") } if(!is.null(assignment_path)) { old_warn_opt <- options(warn = 2) set_assgn_result <- try(suppressMessages(set_assignment(assignment_path)), silent = TRUE) options(warn = old_warn_opt$warn) if(methods::is(set_assgn_result, "try-error")) stop(set_assgn_result[1]) } if(quiet){ testthat::capture_output(test_results <- suppressMessages(run_test_suite(caller = "mark_my_file", tasks, mark_file, quiet, ...))) } else { test_results <- run_test_suite(caller = "mark_my_file", tasks, mark_file, quiet, ...) } test_results_df <- as.data.frame(test_results) if(!any(test_results_df$error) & sum(test_results_df$failed) == 0 & is.null(tasks) & !quiet) cheer() if(!is.null(assignment_path)) remove_assignment() return(invisible(test_results)) }
simulateVARX <- function(N = 40, K = 10, p = 1, m = 1, nobs = 250, rho = 0.5, sparsityA1 = 0.05, sparsityA2 = 0.5, sparsityA3 = 0.5, mu = 0, method = "normal", covariance = "Toeplitz", ...) { opt <- list(...) fixedMat <- opt$fixedMat SNR <- opt$SNR out <- list() attr(out, "class") <- "varx" attr(out, "type") <- "simulation" out$A <- list() out$A1 <- list() out$A2 <- list() out$A3 <- list() out$A4 <- list() pX <- max(p, m) for (i in 1:pX) { out$A4[[i]] <- matrix(0, nrow = K, ncol = N) } stable <- FALSE while (!stable) { s <- sample(1:pX, 1) for (i in 1:s) { out$A3[[i]] <- createSparseMatrix(sparsity = sparsityA3, N = K, method = method, stationary = TRUE, p = 1, ...) l <- max(Mod(eigen(out$A3[[i]])$values)) while ((l > 1) | (l == 0)) { out$A3[[i]] <- createSparseMatrix(sparsity = sparsityA3, N = K, method = method, stationary = TRUE, p = 1, ...) l <- max(Mod(eigen(out$A3[[i]])$values)) } } if (s < pX) { for (i in (s + 1):pX) { out$A3[[i]] <- matrix(0, nrow = K, ncol = K) } } for (i in 1:p) { out$A1[[i]] <- createSparseMatrix(sparsity = sparsityA1, N = N, method = method, stationary = TRUE, p = p, ...) l <- max(Mod(eigen(out$A1[[i]])$values)) while ((l > 1) | (l == 0)) { out$A1[[i]] <- createSparseMatrix(sparsity = sparsityA1, N = N, method = method, stationary = TRUE, p = p, ...) l <- max(Mod(eigen(out$A1[[i]])$values)) } } if (p < pX) { for (i in (p + 1):pX) { out$A1[[i]] <- matrix(0, nrow = N, ncol = N) } } for (i in 1:m) { R <- max(K, N) tmp <- createSparseMatrix(sparsity = sparsityA2, N = R, method = method, stationary = TRUE, p = p, ...) out$A2[[i]] <- tmp[1:N, 1:K] } if (m < pX) { for (i in (m + 1):pX) { out$A2[[i]] <- matrix(0, nrow = N, ncol = K) } } for (i in 1:pX) { tmp1 <- cbind(out$A1[[i]], out$A2[[i]]) tmp2 <- cbind(out$A4[[i]], out$A3[[i]]) out$A[[i]] <- rbind(tmp1, tmp2) } cVAR <- as.matrix(companionVAR(out)) if (max(Mod(eigen(cVAR)$values)) < 1) { stable <- TRUE } } N <- N + K if (covariance == "block1") { l <- floor(N / 2) I <- diag(1 - rho, nrow = N) r <- matrix(0, nrow = N, ncol = N) r[1:l, 1:l] <- rho r[(l + 1):N, (l + 1):N] <- diag(rho, nrow = (N - l)) C <- I + r } else if (covariance == "block2") { l <- floor(N / 2) I <- diag(1 - rho, nrow = N) r <- matrix(0, nrow = N, ncol = N) r[1:l, 1:l] <- rho r[(l + 1):N, (l + 1):N] <- rho C <- I + r } else if (covariance == "Toeplitz") { r <- rho^(1:N) C <- Matrix::toeplitz(r) } else if (covariance == "Wishart") { r <- rho^(1:N) S <- Matrix::toeplitz(r) C <- stats::rWishart(1, 2 * N, S) C <- as.matrix(C[, , 1]) } else if (covariance == "diagonal") { C <- diag(x = rho, nrow = N, ncol = N) } else { stop("Unknown covariance matrix type. Possible choices are: toeplitz, block1, block2 or diagonal") } if (!is.null(SNR)) { if (SNR == 0) { stop("Signal to Noise Ratio must be greater than 0.") } s <- max(abs(cVAR)) / opt$SNR C <- diag(s, N, N) %*% C %*% diag(s, N, N) } theta <- matrix(0, N, N) data <- generateVARseries(nobs = nobs, mu, AR = out$A, sigma = C, skip = 200) out$series <- data$series[, 1:(N - K)] out$Xt <- data$series[, (N - K + 1):N] out$noises <- data$noises out$sigma <- C return(out) } generateVARXseries <- function(nobs, mu, AR, sigma, skip = 200) { N <- nrow(sigma) nT <- nobs + skip at <- mvtnorm::rmvnorm(nT, rep(0, N), sigma) p <- length(AR) ist <- p + 1 zt <- matrix(0, nT, N) if (length(mu) == 0) { mu <- rep(0, N) } for (it in ist:nT) { tmp <- matrix(at[it, ], 1, N) for (i in 1:p) { ph <- AR[[i]] ztm <- matrix(zt[it - i, ], 1, N) tmp <- tmp + ztm %*% t(ph) } zt[it, ] <- mu + tmp } zt <- zt[(1 + skip):nT, ] at <- at[(1 + skip):nT, ] out <- list() out$series <- zt out$noises <- at return(out) } checkMatricesX <- function(A) { if (!is.list(A)) { stop("The matrices must be passed in a list") } else { l <- length(A) if (l > 1) { for (i in 1:(l - 1)) { if (sum(1 - (dim(A[[i]]) == dim(A[[i + 1]]))) != 0) { return(FALSE) } } return(TRUE) } else { return(TRUE) } } }
if (packageVersion("FisPro") == "1.0") { setClass("AggregFis", slots = c(fis = "envRefClass", output_index = "numeric")) } else { setClass("AggregFis", slots = c(fis = "Rcpp_Fis", output_index = "numeric")) } .CheckAggregFisRange <- function(type, name, range) { if ((range["min"] < 0) || (range["max"] > 1)) { stop(sprintf("%s '%s' must be in range [0, 1]", type, name)) } } .CheckAggregFisInput <- function(input) { .CheckAggregFisRange("input", input$name, input$range()) } .CheckAggregFisOutput <- function(output) { .CheckAggregFisRange("output", output$name, output$range()) } setGeneric(name = ".CheckAggregFisConclusion", def = function(output, conclusion) { standardGeneric(".CheckAggregFisConclusion") }) setMethod(f = ".CheckAggregFisConclusion", signature = c("Rcpp_FisOutCrisp", "numeric"), definition = function(output, conclusion) { if ((conclusion < 0) || (conclusion > 1)) { stop(sprintf("crisp output '%s' conclusion must be in range [0, 1]", output$name)) } }) setMethod(f = ".CheckAggregFisConclusion", signature = c("Rcpp_FisOutFuzzy", "numeric"), definition = function(output, conclusion) {}) .CheckAggregFisRule <- function(rule, outputs) { output <- conclusion <- NULL foreach(output = outputs, conclusion = rule$conclusions) %do% { .CheckAggregFisConclusion(output, conclusion) } } .CheckAggregFis <- function(fis, output_index) { for (input in fis$get_inputs()) { .CheckAggregFisInput(input) } if (fis$output_size() < output_index) { stop(sprintf("output '%d' not found", output_index)) } for (output in fis$get_outputs()) { .CheckAggregFisOutput(output) } for (rule in fis$get_rules()) { .CheckAggregFisRule(rule, fis$get_outputs()) } } setMethod("initialize", "AggregFis", function(.Object, ...) { .Object <- callNextMethod() if (packageVersion("FisPro") != "1.0") { .CheckAggregFis(.Object@fis, .Object@output_index) } return(.Object) }) NewAggregFis <- function(fis, output_index = 1) { return(new("AggregFis", fis = fis, output_index = output_index)) } setMethod(f = ".CheckAggreg", signature = c("AggregFis", "integer"), definition = function(aggreg, aggregate_length) { if (aggreg@fis$input_size() != aggregate_length) { stop("the Fis must have the same number of inputs as the aggregate nodes") } }) setMethod(f = "Aggreg", signature = "AggregFis", definition = function(object, node, attribute) { return(Aggregate(node, attribute, aggFun = function(x) object@fis$infer_output(x, object@output_index))) }) toString.AggregFis <- function(x, ...) { return(sprintf("fis(\"%s\", %d)", x@fis$name, x@output_index)) }
library(distr) library(RobLox) library(Biobase) rowRoblox1 <- function(x, r, k = 1L){ mean <- rowMedians(x, na.rm = TRUE) sd <- rowMedians(abs(x-mean), na.rm = TRUE)/qnorm(0.75) if(r > 10){ b <- sd*1.618128043 const <- 1.263094656 A2 <- b^2*(1+r^2)/(1+const) A1 <- const*A2 a <- -0.6277527697*A2/sd mse <- A1 + A2 }else{ A1 <- sd^2*RobLox:::.getA1.locsc(r) A2 <- sd^2*RobLox:::.getA2.locsc(r) a <- sd*RobLox:::.geta.locsc(r) b <- sd*RobLox:::.getb.locsc(r) mse <- A1 + A2 } robEst <- .kstep.locsc.matrix(x = x, initial.est = cbind(mean, sd), A1 = A1, A2 = A2, a = a, b = b, k = k) colnames(robEst$est) <- c("mean", "sd") return(robEst$est) } n <- 10 M <- 1e5 eps <- 0.01 D <- 0.1 fun <- function(r, x, n){ RadMinmax <- rowRoblox1(x, r = r) n*(mean(RadMinmax[,1]^2) + mean((RadMinmax[,2]-1)^2)) } r <- rbinom(n*M, prob = eps, size = 1) Mid <- rnorm(n*M) Mcont <- rep(D, n*M) Mre <- matrix((1-r)*Mid + r*Mcont, ncol = n) ind <- rowSums(matrix(r, ncol = n)) >= n/2 while(any(ind)){ M1 <- sum(ind) cat("M1:\t", M1, "\n") r <- rbinom(n*M1, prob = eps, size = 1) Mid <- rnorm(n*M1) Mcont <- r(contD)(n*M1) Mre[ind,] <- (1-r)*Mid + r*Mcont ind[ind] <- rowSums(matrix(r, ncol = n)) >= n/2 } fun(r = 1, x = Mre, n = n) fun1 <- function(D){ Mcont <- rep(D, n*M) Mre <- matrix((1-r)*Mid + r*Mcont, ncol = n) fun(r = 1, x = Mre, n = n) } sapply(c(seq(0.1, 10, length = 20), 20, 50, 100, 1000, 1e4, 1e6), fun1) n <- c(3:50, seq(55, 100, by = 5), seq(110, 200, by = 10), seq(250, 500, by = 50)) eps <- c(seq(0.001, 0.01, by = 0.001), seq(0.02, to = 0.5, by = 0.01)) M <- 1e5 contD <- Dirac(1e6) r.fi <- matrix(NA, nrow = length(eps), ncol = length(n)) colnames(r.fi) <- n rownames(r.fi) <- eps r.as <- r.fi for(j in seq(along = n)){ ptm <- proc.time() cat("aktuelles n:\t", n[j], "\n") i <- 0 repeat{ i <- i + 1 cat("aktuelles eps:\t", eps[i], "\n") r <- rbinom(n[j]*M, prob = eps[i], size = 1) Mid <- rnorm(n[j]*M) Mcont <- r(contD)(n[j]*M) Mre <- matrix((1-r)*Mid + r*Mcont, ncol = n[j]) rm(Mid, Mcont) gc() ind <- rowSums(matrix(r, ncol = n[j])) >= n[j]/2 rm(r) gc() while(any(ind)){ M1 <- sum(ind) cat("M1:\t", M1, "\n") r <- rbinom(n[j]*M1, prob = eps[i], size = 1) Mid <- rnorm(n[j]*M1) Mcont <- r(contD)(n[j]*M1) Mre[ind,] <- (1-r)*Mid + r*Mcont ind[ind] <- rowSums(matrix(r, ncol = n[j])) >= n[j]/2 rm(Mid, Mcont, r) gc() } fun <- function(r, x, n){ RadMinmax <- rowRoblox1(x, r = r) n*(mean(RadMinmax[,1]^2) + mean((RadMinmax[,2]-1)^2)) } r.fi[i,j] <- optimize(fun, interval = c(eps[i], min(max(2, n[j]*eps[i]*25), 10)), x = Mre, n = n[j])$minimum r.as[i,j] <- sqrt(n[j])*eps[i] cat("finit:\t", r.fi[i,j], "\t asympt:\t", r.as[i,j], "\n") rm(Mre) gc() if(round(r.fi[i,j], 2) == 1.74 | i == length(eps)) break } save.image(file = "FiniteSample1.RData") cat("Dauer:\t", proc.time() - ptm, "\n") } r.as <- outer(eps, sqrt(n)) r.fi[is.na(r.fi)] <- 1.74 r.finite <- round(pmax(r.fi, r.as, na.rm = TRUE), 4) finiteSampleCorrection <- function(r, n){ if(r >= 1.74) return(r) eps <- r/sqrt(n) ns <- c(3:50, seq(55, 100, by = 5), seq(110, 200, by = 10), seq(250, 500, by = 50)) epss <- c(seq(0.001, 0.01, by = 0.001), seq(0.02, to = 0.5, by = 0.01)) if(n %in% ns){ ind <- ns == n }else{ ind <- which.min(abs(ns-n)) } return(approx(x = epss, y = finiteSampleRadius[,ind], xout = eps, rule = 2)$y) }
local_unexport_signal_abort() test_that("try_fetch() catches or declines values", { f <- function() g() g <- function() h() h <- function() abort("foo") expect_error(try_fetch(f(), warning = function(cnd) NULL), "foo") expect_error(try_fetch(f(), error = function(cnd) zap()), "foo") expect_null(try_fetch(f(), error = function(cnd) NULL)) fns <- list(error = function(cnd) NULL) expect_null(try_fetch(f(), !!!fns)) }) test_that("try_fetch() checks inputs", { expect_snapshot({ (expect_error(try_fetch(NULL, function(...) NULL))) }) expect_true(try_fetch(TRUE)) }) test_that("can rethrow from `try_fetch()`", { local_options( rlang_trace_top_env = current_env(), rlang_trace_format_srcrefs = FALSE ) f <- function() g() g <- function() h() h <- function() abort("foo") high1 <- function(...) high2(...) high2 <- function(...) high3(...) high3 <- function(..., chain) { if (chain) { try_fetch(f(), error = function(cnd) abort("bar", parent = cnd)) } else { try_fetch(f(), error = function(cnd) abort("bar", parent = NA)) } } expect_snapshot({ err <- catch_error( try_fetch(f(), error = function(cnd) abort("bar", parent = cnd)) ) print(err) print(err, simplify = "none") err <- catch_error(high1(chain = TRUE)) print(err) print(err, simplify = "none") err <- catch_error(high1(chain = FALSE)) print(err) print(err, simplify = "none") }) }) test_that("can catch condition of specific classes", { expect_null(catch_cnd(signal("", "bar"), "foo")) expect_s3_class(catch_cnd(signal("", "bar"), "bar"), "bar") expect_s3_class(catch_cnd(stop(""), "error"), "error") expect_s3_class(catch_cnd(stop("tilt")), "error") expect_error(catch_cnd(stop("tilt"), "foo"), "tilt") classes <- c("foo", "bar") expect_s3_class(catch_cnd(signal("", "bar"), classes), "bar") expect_s3_class(catch_cnd(signal("", "foo"), classes), "foo") }) test_that("cnd_muffle() returns FALSE if the condition is not mufflable", { value <- NULL expect_error(withCallingHandlers( stop("foo"), error = function(cnd) value <<- cnd_muffle(cnd) )) expect_false(value) }) test_that("drop_global_handlers() works and is idempotent", { skip_if_not_installed("base", "4.0.0") code <- '{ library(testthat) globalCallingHandlers(NULL) handler <- function(...) "foo" globalCallingHandlers(foo = handler) rlang:::drop_global_handlers(bar = handler) expect_equal(globalCallingHandlers(), list(foo = handler)) rlang:::drop_global_handlers(foo = handler, bar = function() "bar") expect_equal(globalCallingHandlers(), list()) rlang:::drop_global_handlers(foo = handler, bar = function() "bar") expect_equal(globalCallingHandlers(), list()) }' out <- Rscript(shQuote(c("--vanilla", "-e", code))) expect_equal(out$out, chr()) }) test_that("stackOverflowError are caught", { overflow <- function() signal("", "stackOverflowError") handled <- FALSE try_fetch( overflow(), error = function(cnd) handled <<- TRUE ) expect_true(handled) handled <- FALSE try_fetch( overflow(), warning = identity, error = function(cnd) handled <<- TRUE ) expect_true(handled) handled <- NULL try_fetch( overflow(), error = function(cnd) { handled <<- c(handled, 1) cnd_signal(cnd) }, warning = identity, error = function(cnd) handled <<- c(handled, 2) ) expect_equal(handled, c(1, 2)) })
plot.ltm <- function (x, type = c("ICC", "IIC", "loadings"), items = NULL, zrange = c(-3.8, 3.8), z = seq(zrange[1], zrange[2], length = 100), annot, labels = NULL, legend = FALSE, cx = "topleft", cy = NULL, ncol = 1, bty = "n", col = palette(), lty = 1, pch, xlab, ylab, zlab, main, sub = NULL, cex = par("cex"), cex.lab = par("cex.lab"), cex.main = par("cex.main"), cex.sub = par("cex.sub"), cex.axis = par("cex.axis"), plot = TRUE, ...) { if (!inherits(x, "ltm")) stop("Use only with 'ltm' objects.\n") type <- match.arg(type) if (type == "IIC" && any(x$ltst$factors == 2, x$ltst$inter, x$ltst$quad.z1, x$ltst$quad.z2)) stop("Item Information Curves are currently plotted only for the one-factor model.\n") if (type == "loadings" && x$ltst$factors == 1) stop("type = 'loadings' is only valid for the linear two-factor model.\n") betas <- x$coefficients p <- nrow(betas) itms <- if (!is.null(items)) { if (!is.numeric(items) || length(items) > p) stop("'items' must be a numeric vector of length at most ", p) if (type == "ICC" && any(items < 1 | items > p)) stop("'items' must contain numbers between 1 and ", p, " denoting the items.\n") if (type == "IIC" && any(items < 0 | items > p)) stop("'items' must contain numbers between 0 and ", p) items } else 1:p if (x$ltst$factors == 1){ Z <- if (x$ltst$quad.z1) cbind(1, z, z * z) else cbind(1, z) pr <- if (type == "ICC") { plogis(Z %*% t(betas)) } else { pr <- plogis(Z %*% t(betas)) pqr <- pr * (1 - pr) t(t(pqr) * betas[, 2]^2) } plot.items <- type == "ICC" || (type == "IIC" & (is.null(items) || all(items > 0))) plot.info <- !plot.items col <- if (plot.items) rep(col, length.out = length(itms)) else col[1] lty <- if (plot.items) rep(lty, length.out = length(itms)) else lty[1] if(!missing(pch)) { pch <- if (plot.items) rep(pch, length.out = length(itms)) else pch[1] pch.ind <- round(seq(15, 85, length = 4)) } if (missing(main)) { main <- if (type == "ICC") "Item Characteristic Curves" else { if (plot.items) "Item Information Curves" else "Test Information Function" } } if (missing(xlab)) { xlab <- "Ability" } if (missing(ylab)) { ylab <- if (type == "ICC") "Probability" else "Information" } r <- if (type == "ICC") c(0, 1) else { if (plot.info) range(rowSums(pr)) else range(pr[, itms]) } if (plot) { plot(range(z), r, type = "n", xlab = xlab, ylab = ylab, main = main, sub = sub, cex = cex, cex.lab = cex.lab, cex.main = cex.main, cex.axis = cex.axis, cex.sub = cex.sub, ...) if (missing(annot)) { annot <- !legend } if (legend) { legnd <- if (is.null(labels)) { if (plot.info) "Information" else rownames(betas)[itms] } else { if (length(labels) < length(itms)) warning("the length of 'labels' is smaller than the length of 'items'.\n") labels } legend(cx, cy, legend = legnd, col = col, lty = lty, bty = bty, ncol = ncol, cex = cex, pch = pch, ...) } if (annot) { pos <- round(seq(10, 90, length = length(itms))) nams <- if (is.null(labels)) { nms <- if (rownames(betas)[1] == "Item 1") 1:p else rownames(betas) nms[itms] } else { if (length(labels) < length(itms)) warning("the length of 'labels' is smaller than the length of 'items'.\n") labels } } if (plot.items) { for (it in seq(along = itms)) { lines(z, pr[, itms[it]], lty = lty[it], col = col[it], ...) if (!missing(pch)) points(z[pch.ind], pr[pch.ind, itms[it]], pch = pch[it], col = col[it], cex = cex, ...) if (annot) text(z[pos[it]], pr[pos[it], itms[it]], labels = nams[it], adj = c(0, 2), col = col[it], cex = cex, ...) } } if (plot.info) lines(z, rowSums(pr), lty = lty, col = col, ...) return.value <- if (plot.items) cbind(z = z, pr[, itms]) else cbind(z = z, info = rowSums(pr)) } else { return(if (plot.items) cbind(z = z, pr[, itms]) else cbind(z = z, info = rowSums(pr))) } } if (x$ltst$factors == 2) { nams <- rownames(x$coef) if (type == "loadings") { if (any(unlist(x$ltst[2:4]))) stop("the plot of standardized loadings is produced only for the linear two-factor model.\n") cof <- coef(x, TRUE) z1 <- cof[itms, 3] z2 <- cof[itms, 5] if (plot) { if (missing(xlab)) xlab <- "Factor 1" if (missing(ylab)) ylab <- "Factor 2" if (missing(main)) main <- "Standardized Loadings" plot(z1, z2, type = "n", xlab = xlab, ylab = ylab, main = main, sub = sub, xlim = c(min(z1, -0.1), max(z1, 0.1)), ylim = c(min(z2, -0.1), max(z2, 0.1)), cex = cex, cex.lab = cex.lab, cex.main = cex.main, cex.axis = cex.axis, cex.sub = cex.sub, ...) abline(h = 0, v = 0, lty = 2) text(z1, z2, labels = if (is.null(labels)) nams[itms] else labels, cex = cex, ...) return.value <- cbind("Factor 1" = z1, "Factor 2" = z2) } else { return(cbind("Factor 1" = z1, "Factor 2" = z2)) } } else { z1 <- z2 <- z f <- function (z, betas, strct) { Z <- cbind(1, z[1], z[2]) colnames(Z) <- c("(Intercept)", "z1", "z2") if (strct$inter) Z <- cbind(Z, "z1:z2" = z[1] * z[2]) if (strct$quad.z1) Z <- cbind(Z, "I(z1^2)" = z[1] * z[1]) if (strct$quad.z2) Z <- cbind(Z, "I(z2^2)" = z[2] * z[2]) Z <- Z[, match(names(betas), colnames(Z)), drop = FALSE] pr <- plogis(Z %*% betas) } if (plot) { if (missing(xlab)) xlab <- "Factor 1" if (missing(ylab)) ylab <- "Factor 2" if (missing(zlab)) zlab <- "Probability" if (missing(main)) main <- "Item Characteristic Surfaces" col <- if (missing(col)) rep("white", length.out = length(itms)) else rep(col, length.out = length(itms)) old.par <- par(ask = TRUE) on.exit(par(old.par)) } grid. <- as.matrix(expand.grid(z1, z2)) dimnames(grid.) <- NULL z <- vector("list", length(itms)) for (it in seq(along = itms)) { item <- itms[it] z[[it]] <- apply(grid., 1, f, betas = betas[item, ], strct = x$ltst) dim(z[[it]]) <- c(length(z1), length(z1)) if (plot) { persp(z1, z2, z[[it]], cex = cex, xlab = list(xlab, cex = cex.lab), ylab = list(ylab, cex = cex.lab), zlab = list(zlab, cex = cex.lab), main = list(main, cex = cex.main), sub = list(if (is.null(labels)) nams[item] else labels[it], cex = cex.sub), col = col[it], ...) } } return.value <- list(Factor1 = z1, Factor2 = z2, Prob = z) if (!plot) return(return.value) } } invisible(return.value) }
database_init <- function( path = tempfile(), header = "name", list_columns = character(0) ) { memory <- memory_init() database_new(memory, path, header, list_columns) } database_new <- function( memory = NULL, path = NULL, header = NULL, list_columns = NULL, queue = NULL ) { database_class$new( memory = memory, path = path, header = header, list_columns = list_columns, queue = queue ) } database_class <- R6::R6Class( classname = "tar_database", class = FALSE, portable = FALSE, cloneable = FALSE, public = list( initialize = function( memory = NULL, path = NULL, header = NULL, list_columns = NULL, queue = NULL ) { self$memory <- memory self$path <- path self$header <- header self$list_columns <- list_columns self$queue <- queue }, memory = NULL, path = NULL, header = NULL, list_columns = NULL, queue = NULL, get_row = function(name) { memory_get_object(self$memory, name) }, set_row = function(row) { name <- as.character(row$name) memory_set_object(self$memory, name = name, object = as.list(row)) }, del_rows = function(names) { memory_del_objects(self$memory, names) }, get_data = function() { rows <- self$list_rows() out <- map(rows, ~as_data_frame(self$get_row(.x))) do.call(rbind, out) }, set_data = function(data) { list <- lapply(data, as.list) map(seq_along(list$name), ~self$set_row(lapply(list, `[[`, i = .x))) }, exists_row = function(name) { memory_exists_object(self$memory, name) }, list_rows = function() { self$memory$names }, condense_data = function(data) { data[!duplicated(data$name, fromLast = TRUE), ] }, read_condensed_data = function() { self$condense_data(self$read_data()) }, preprocess = function(write = FALSE) { data <- self$read_condensed_data() self$set_data(data) if (write) { self$ensure_storage() self$overwrite_storage(data) } }, insert_row = function(row) { self$write_row(row) self$set_row(row) }, append_data = function(data) { self$append_storage(data) self$set_data(data) }, select_cols = function(data) { fill <- setdiff(self$header, names(data)) na_col <- rep(NA_character_, length(data$name)) for (col in fill) { data[[col]] <- na_col } as.list(data)[self$header] }, enqueue_row = function(row) { line <- self$produce_line(self$select_cols(row)) self$queue <- c(self$queue, line) }, dequeue_rows = function() { if (length(self$queue)) { on.exit(self$queue <- NULL) self$append_lines(self$queue) } }, write_row = function(row) { line <- self$produce_line(self$select_cols(row)) self$append_lines(line) }, append_lines = function(lines, max_attempts = 500) { attempt <- 0L while (!is.null(try(self$try_append_lines(lines)))) { msg <- paste("Reattempting to append lines to", self$path) cli::cli_alert_info(msg) Sys.sleep(stats::runif(1, 0.2, 0.25)) attempt <- attempt + 1L if (attempt > max_attempts) { tar_throw_run( "timed out after ", max_attempts, " attempts trying to append to ", self$path ) } } }, try_append_lines = function(lines) { write(lines, self$path, ncolumns = 1L, append = TRUE, sep = "") invisible() }, append_storage = function(data) { dir_create(dirname(self$path)) data.table::fwrite( x = data, file = self$path, sep = database_sep_outer, sep2 = c("", database_sep_inner, ""), na = "", append = TRUE ) }, overwrite_storage = function(data) { dir <- dirname(self$path) dir_create(dir) tmp <- tempfile(pattern = "tar_temp_", tmpdir = dir) data.table::fwrite( x = data, file = tmp, sep = database_sep_outer, sep2 = c("", database_sep_inner, ""), na = "", append = FALSE ) file.rename(from = tmp, to = self$path) }, produce_line = function(row) { paste(map_chr(row, self$produce_subline), collapse = database_sep_outer) }, produce_subline = function(element) { element <- replace_na(element, "") if (is.list(element)) { element <- paste(unlist(element), collapse = database_sep_inner) } as.character(element) }, reset_storage = function() { dir_create(dirname(self$path)) write(self$produce_line(self$header), self$path) }, ensure_storage = function() { if (!file.exists(self$path)) { self$reset_storage() } }, ensure_preprocessed = function(write = FALSE) { if (identical(self$memory$count, 0L)) { self$preprocess(write = write) } }, read_data = function() { if_any( file.exists(self$path), self$read_existing_data(), self$produce_mock_data() ) }, read_existing_data = function() { database_read_existing_data(self) }, produce_mock_data = function() { out <- as_data_frame(map(self$header, ~character(0))) colnames(out) <- self$header out }, deduplicate_storage = function() { if (file.exists(self$path)) { data <- self$condense_data(self$read_data()) data <- data[order(data$name),, drop = FALSE] self$overwrite_storage(data) } }, validate_columns = function(header, list_columns) { database_validate_columns(header, list_columns) }, validate_file = function() { database_validate_file(self) }, validate = function() { memory_validate(self$memory) self$validate_columns(self$header, self$list_columns) self$validate_file() tar_assert_chr(self$path) tar_assert_scalar(self$path) tar_assert_chr(self$header) tar_assert_chr(self$list_columns) } ) ) database_read_existing_data <- function(database) { out <- data.table::fread( file = database$path, sep = database_sep_outer, fill = TRUE, na.strings = "" ) out <- as_data_frame(out) if (nrow(out) < 1L) { return(out) } for (id in database$list_columns) { out[[id]] <- strsplit( as.character(out[[id]]), split = database_sep_inner, fixed = TRUE ) } out } database_validate_columns <- function(header, list_columns) { if (!all(list_columns %in% header)) { tar_throw_validate("all list columns must be in the header") } if (!is.null(header) & !("name" %in% header)) { tar_throw_validate("header must have a column called \"name\"") } } database_validate_file <- function(database) { if (!file.exists(database$path)) { return() } line <- readLines(database$path, n = 1L) header <- strsplit(line, split = database_sep_outer, fixed = TRUE)[[1]] if (identical(header, database$header)) { return() } tar_throw_file( "invalid header in ", database$path, "\n", " found: ", paste(header, collapse = database_sep_outer), "\n", " expected: ", paste(database$header, collapse = database_sep_outer), "\nProbably because of a breaking change in the targets package. ", "Before running tar_make() again, ", "either delete the data store with tar_destroy() ", "or downgrade the targets package to an earlier version." ) } database_sep_outer <- "|" database_sep_inner <- "*"
setClass("QuadraticDiscriminantClassifier", representation(means="matrix",sigma="list",prior="matrix"), prototype(name="Quadratic Discriminant Classifier"), contains="NormalBasedClassifier") QuadraticDiscriminantClassifier <- function(X, y, prior=NULL, scale=FALSE, ...) { ModelVariables<-PreProcessing(X,y,scale=scale,intercept=FALSE) X<-ModelVariables$X y<-ModelVariables$y scaling<-ModelVariables$scaling classnames<-ModelVariables$classnames modelform<-ModelVariables$modelform Y <- model.matrix(~as.factor(y)-1) if (is.null(prior)) prior<-matrix(colMeans(Y),2,1) means <- t((t(X) %*% Y))/(colSums(Y)) sigma <- lapply(1:ncol(Y),function(c,X){cov(X[Y[,c]==1,,drop=FALSE])},X) new("QuadraticDiscriminantClassifier", modelform=modelform, prior=prior, means=means, sigma=sigma,classnames=classnames,scaling=scaling) } setMethod("line_coefficients", signature(object="QuadraticDiscriminantClassifier"), function(object) { stop("Not a linear decision boundary.") })
rm(list=ls()) setwd("C:/Users/Tom/Documents/Kaggle/Santander") library(data.table) baseProducts <- c("ahor_fin", "aval_fin", "cco_fin", "cder_fin", "cno_fin", "ctju_fin", "ctma_fin", "ctop_fin", "ctpp_fin", "deco_fin", "deme_fin", "dela_fin", "ecue_fin", "fond_fin", "hip_fin", "plan_fin", "pres_fin", "reca_fin", "tjcr_fin", "valo_fin", "viv_fin", "nomina", "nom_pens", "recibo" ) targetVars <- paste0("ind_", baseProducts, "_ult1") nbTargetVars <- length(targetVars) sampleSubmission <- fread("Data/sample_submission.csv") for(i in 1:nbTargetVars){ dummyTable <- sampleSubmission dummyTable[, added_products := targetVars[i]] write.csv(dummyTable, file.path(getwd(), "Submission", "Leaderboard probing", "Submission files", paste0("all_", baseProducts[i], ".csv")), row.names = FALSE) }
Hajekestimator<-function(y,pik,N=NULL,type=c("total","mean")) { if(any(is.na(pik))) stop("there are missing values in pik") if(any(is.na(y))) stop("there are missing values in y") if(length(y)!=length(pik)) stop("y and pik have different sizes") if(missing(type) | is.null(N)) { if(missing(type)) warning("the type estimator is missing") warning("by default the mean estimator is computed") est<-crossprod(y,1/pik)/sum(1/pik)} else if(type=="total") est<-N*crossprod(y,1/pik)/sum(1/pik) est }
nca.deviation.plot <- function(plotdata, xvar=NULL, devcol=NULL, figlbl=NULL, spread="npi", cunit=NULL, tunit=NULL){ "XVAR" <- "melt" <- "xlab" <- "ylab" <- "theme" <- "element_text" <- "unit" <- "geom_point" <- "facet_wrap" <- "ggplot" <- "aes" <- "labs" <- "na.omit" <- "dist" <- NULL rm(list=c("XVAR","melt","xlab","ylab","theme","element_text","unit","geom_point","facet_wrap","ggplot","aes","labs","na.omit","dist")) if (!is.data.frame(plotdata)) stop("plotdata must be a data frame.") if (is.null(xvar)){ stop("Missing x-variable against which the deviation data will be plotted.") }else{ names(plotdata)[which(names(plotdata)==xvar)] <- "XVAR" } if (is.null(devcol)){ stop("Missing column names/numbers of the data frame containing deviation data.") }else if (!is.null(devcol) && !is.numeric(devcol)){ if (!all(devcol%in%names(plotdata))) stop("All column names given as deviation data column must be present in plotdata") }else if (!is.null(devcol) && is.numeric(devcol)){ if (any(devcol <= 0) | (max(devcol) > ncol(plotdata))) stop("Column number for deviation data out of range of plotdata.") devcol <- names(plotdata)[devcol] } plotdata <- subset(plotdata, select=c("XVAR",devcol)) longdata <- melt(plotdata, measure.vars = devcol) names(longdata)[c((ncol(longdata)-1):ncol(longdata))] <- c("type","dist") longdata <- na.omit(longdata) longdata <- subset(longdata, dist!="NaN") if (nrow(longdata)==0){ ggplt <- NULL }else{ fctNm <- data.frame() npr <- length(devcol) nc <- ifelse(npr<2, 1, ifelse(npr>=2 & npr<=6, 2, 3)) for (p in 1:npr){ if (devcol[p] == "dAUClast" | devcol[p] == "dAUClower_upper" | devcol[p] == "dAUCINF_obs" | devcol[p] == "dAUCINF_pred"){ if(is.null(cunit) | is.null(tunit)){ fctNm <- rbind(fctNm, data.frame(prmNm=devcol[p],prmUnit=gsub("^d", "", devcol)[p])) }else{ fctNm <- rbind(fctNm, data.frame(prmNm=devcol[p],prmUnit=paste0(gsub("^d", "", devcol)[p]," (",cunit,"*",tunit,")"))) } }else if (devcol[p] == "dAUMClast"){ if(is.null(cunit) | is.null(tunit)){ fctNm <- rbind(fctNm, data.frame(prmNm=devcol[p],prmUnit=gsub("^d", "", devcol)[p])) }else{ fctNm <- rbind(fctNm, data.frame(prmNm=devcol[p],prmUnit=paste0(gsub("^d", "", devcol)[p]," (",cunit,"*",tunit,"^2)"))) } }else if (devcol[p] == "dCmax"){ if(is.null(cunit)){ fctNm <- rbind(fctNm, data.frame(prmNm=devcol[p],prmUnit=gsub("^d", "", devcol)[p])) }else{ fctNm <- rbind(fctNm, data.frame(prmNm=devcol[p],prmUnit=paste0(gsub("^d", "", devcol)[p]," (",cunit,")"))) } }else if (devcol[p] == "dTmax" | devcol[p] == "dHL_Lambda_z"){ if(is.null(tunit)){ fctNm <- rbind(fctNm, data.frame(prmNm=devcol[p],prmUnit=gsub("^d", "", devcol)[p])) }else{ fctNm <- rbind(fctNm, data.frame(prmNm=devcol[p],prmUnit=paste0(gsub("^d", "", devcol)[p]," (",tunit,")"))) } }else{ fctNm <- rbind(fctNm, data.frame(prmNm=devcol[p],prmUnit=devcol[p])) } } ggOpt_dev <- list(xlab(paste("\n",xvar,sep="")), ylab("Deviation\n"), theme(axis.text.x = element_text(angle=45,vjust=1,hjust=1,size=10), axis.text.y = element_text(hjust=0,size=10), strip.text.x = element_text(size=10), title = element_text(size=14,face="bold")), geom_point(size=2), facet_wrap(~type, ncol=nc, scales="free")) longdata$type <- factor(longdata$type, levels=fctNm$prmNm, labels=fctNm$prmUnit) if (is.null(figlbl)){ ttl <- ifelse (spread=="ppi", "Deviation = (obs-medianSim)/d\nd = distance between medianSim and 95% parametric prediction\ninterval boundary proximal to the observed value\n", "Deviation = (obs-medianSim)/d\nd = distance between medianSim and 95% nonparametric prediction\ninterval boundary proximal to the observed value\n") }else{ ttl <- ifelse (spread=="ppi", paste0("Deviation = (obs-medianSim)/d\nd = distance between medianSim and 95% parametric prediction\ninterval boundary proximal to the observed value\n",figlbl,"\n"), paste0("Deviation = (obs-medianSim)/d\nd = distance between medianSim and 95% nonparametric prediction\ninterval boundary proximal to the observed value\n",figlbl,"\n")) } ggplt <- ggplot(longdata,aes(as.numeric(as.character(XVAR)),as.numeric(as.character(dist)))) + ggOpt_dev + labs(title = ttl) + theme(plot.title = element_text(size = rel(0.85))) } return(ggplt) }
ggplot_estimate_uncertainties <- function(JAB_stats, fill_colour = NULL) { rank <- NULL conf_int <- NULL se2_jack <- NULL se2_boot <- NULL GOF_stat <- NULL value <- NULL variable <- NULL GOF_stats <- unique(JAB_stats$GOF_stat) num_stats <- length(GOF_stats) for (i in 1:num_stats) { GOF <- GOF_stats[i] selected_stats <- JAB_stats[JAB_stats$GOF_stat == GOF,] selected_stats_ranked <- selected_stats[order(selected_stats$seJab),] num_selected <- nrow(selected_stats) selected_stats_ranked$rank <- seq(from = 1, to = num_selected) if (i == 1) { all_stats <- selected_stats_ranked } else { all_stats <- rbind(all_stats, selected_stats_ranked) } } all_stats$conf_int <- all_stats$p95 - all_stats$p05 all_stats$se2_boot <- all_stats$seBoot * 2 all_stats$se2_jack <- all_stats$seJack * 2 if (!is.null(fill_colour)) { p1 <- ggplot() + geom_area(data = all_stats, aes(rank, se2_jack, fill = fill_colour)) + geom_line(data = all_stats, aes(rank, se2_boot, colour = "red")) + geom_line(data = all_stats, aes(rank, conf_int, colour = "black")) + xlab("Site index, ranked w.r.t. the Bootstrap estimates of the confidence intervals") + ylab("Uncertainty") + ylim(0, 0.5) + scale_colour_manual(name = '', values =c('black'='black','red'='red'), labels = c('Confidence interval (p95 - p05)', '2 x standard error (Bootstrap)')) + scale_fill_identity(name = '', guide = 'legend',labels = c("2 x standard error (Jackknife)")) + facet_wrap(~GOF_stat, nrow = 2) + guides( color = guide_legend(order = 1), fill = guide_legend(order = 2) ) } else { all_stats <- all_stats[, c("rank", "GOF_stat", "conf_int", "se2_boot", "se2_jack")] melted <- melt(all_stats, id.vars = c("rank", "GOF_stat"), measure_vars = c("conf_int", "se2_boot", "se2_jack")) melted$variable <- as.character(melted$variable) melted$variable[melted$variable == "conf_int"] <- "Confidence interval (p95 - p05)" melted$variable[melted$variable == "se2_boot"] <- "2 x standard error (Bootstrap)" melted$variable[melted$variable == "se2_jack"] <- "2 x standard error (Jackknife)" p1 <- ggplot(melted, aes(rank, value, colour = variable)) + geom_line() + xlab("Site index, ranked w.r.t. the Bootstrap estimates of the confidence intervals") + ylab("Uncertainty") + ylim(0, 0.5) + scale_colour_manual(name = '', values =c("black", "red", "orange"), labels = c('Confidence interval (p95 - p05)', '2 x standard error (Bootstrap)', "2 x standard error (Jackknife)")) + facet_wrap(~GOF_stat, nrow = 2) } return(p1) }
test_that("ptype print methods are descriptive", { tab1 <- new_table() tab2 <- new_table(dim = c(0L, 1L, 2L, 1L)) expect_equal(vec_ptype_abbr(tab1), "table") expect_equal(vec_ptype_abbr(tab2), "table[,1,2,1]") expect_equal(vec_ptype_full(tab1), "table") expect_equal(vec_ptype_full(tab2), "table[,1,2,1]") }) test_that("can find a common type among tables with identical dimensions", { tab1 <- new_table() tab2 <- new_table(1:2, dim = c(1L, 2L, 1L)) expect_identical(vec_ptype2(tab1, tab1), zap_dimnames(new_table())) expect_identical(vec_ptype2(tab2, tab2), zap_dimnames(new_table(dim = c(0L, 2L, 1L)))) }) test_that("size is not considered in the ptype", { x <- new_table(1:2, dim = 2L) y <- new_table(1:3, dim = 3L) expect_identical(vec_ptype2(x, y), zap_dimnames(new_table())) }) test_that("vec_ptype2() can broadcast table shapes", { x <- new_table(dim = c(0L, 1L)) y <- new_table(dim = c(0L, 2L)) expect_identical(vec_ptype2(x, y), zap_dimnames(new_table(dim = c(0L, 2L)))) x <- new_table(dim = c(0L, 1L, 3L)) y <- new_table(dim = c(0L, 2L, 1L)) expect_identical(vec_ptype2(x, y), zap_dimnames(new_table(dim = c(0L, 2L, 3L)))) }) test_that("implicit axes are broadcast", { x <- new_table(dim = c(0L, 2L)) y <- new_table(dim = c(0L, 1L, 3L)) expect_identical(vec_ptype2(x, y), zap_dimnames(new_table(dim = c(0L, 2L, 3L)))) }) test_that("errors on non-broadcastable dimensions", { x <- new_table(dim = c(0L, 2L)) y <- new_table(dim = c(0L, 3L)) expect_error(vec_ptype2(x, y), class = "vctrs_error_incompatible_type") }) test_that("vec_ptype2() errors on non-tables", { expect_error(vec_ptype2(new_table(), 1), class = "vctrs_error_incompatible_type") expect_error(vec_ptype2(new_table(), 1L), class = "vctrs_error_incompatible_type") expect_error(vec_ptype2(new_table(), "1"), class = "vctrs_error_incompatible_type") expect_error(vec_ptype2(1, new_table()), class = "vctrs_error_incompatible_type") expect_error(vec_ptype2(1L, new_table()), class = "vctrs_error_incompatible_type") expect_error(vec_ptype2("1", new_table()), class = "vctrs_error_incompatible_type") }) test_that("common types have symmetry when mixed with unspecified input", { x <- new_table() expect_identical(vec_ptype2(x, NA), new_table()) expect_identical(vec_ptype2(NA, x), new_table()) x <- new_table(dim = c(0L, 2L)) expect_identical(vec_ptype2(x, NA), new_table(dim = c(0L, 2L))) expect_identical(vec_ptype2(NA, x), new_table(dim = c(0L, 2L))) }) test_that("`table` delegates coercion", { expect_identical( vec_ptype2(new_table(1), new_table(FALSE)), zap_dimnames(new_table(double())) ) expect_error( vec_ptype2(new_table(1), new_table("")), class = "vctrs_error_incompatible_type" ) }) test_that("can cast to an identically shaped table", { x <- new_table(1:5, dim = 5L) y <- new_table(1:8, dim = c(2L, 2L, 2L)) expect_identical(vec_cast(x, x), x) expect_identical(vec_cast(y, y), y) }) test_that("vec_cast() can broadcast table shapes", { x <- new_table(dim = c(0L, 1L)) y <- new_table(dim = c(0L, 2L)) expect_identical(dim(vec_cast(x, y)), c(0L, 2L)) x <- new_table(dim = c(0L, 1L, 1L)) y <- new_table(dim = c(0L, 2L, 3L)) expect_identical(dim(vec_cast(x, y)), c(0L, 2L, 3L)) }) test_that("cannot decrease axis length", { x <- new_table(dim = c(0L, 3L)) y <- new_table(dim = c(0L, 1L)) expect_error(vec_cast(x, y), "Non-recyclable", class = "vctrs_error_incompatible_type") }) test_that("cannot decrease dimensionality", { x <- new_table(dim = c(0L, 1L, 1L)) y <- new_table(dim = c(0L, 1L)) expect_error(vec_cast(x, y), "decrease dimensions", class = "vctrs_error_incompatible_type") }) test_that("vec_cast() errors on non-tables", { expect_error(vec_cast(new_table(), 1), class = "vctrs_error_incompatible_type") expect_error(vec_cast(new_table(), 1L), class = "vctrs_error_incompatible_type") expect_error(vec_cast(new_table(), "1"), class = "vctrs_error_incompatible_type") expect_error(vec_cast(1, new_table()), class = "vctrs_error_incompatible_type") expect_error(vec_cast(1L, new_table()), class = "vctrs_error_incompatible_type") expect_error(vec_cast("1", new_table()), class = "vctrs_error_incompatible_type") }) test_that("can cast from, but not to, unspecified", { x <- new_table() expect_error(vec_cast(x, NA), class = "vctrs_error_incompatible_type") expect_identical(vec_cast(NA, x), new_table(NA_integer_, dim = 1L)) x <- new_table(dim = c(0L, 2L)) expect_error(vec_cast(x, NA), class = "vctrs_error_incompatible_type") expect_identical(vec_cast(NA, x), new_table(c(NA_integer_, NA_integer_), dim = c(1L, 2L))) }) test_that("`table` delegates casting", { expect_identical( vec_cast(new_table(1), new_table(FALSE)), new_table(TRUE) ) expect_error( vec_cast(new_table(1), new_table("")), class = "vctrs_error_incompatible_type" ) }) test_that("`new_table()` validates input", { expect_error(new_table(1L, 1), "`dim` must be an integer vector") expect_error(new_table(1:2, 1L), "must match the length of `x`") }) test_that("ptype is correct", { tab1 <- new_table(1L, dim = 1L) tab2 <- new_table(1:2, dim = c(1L, 2L, 1L)) expect_identical(vec_ptype(tab1), new_table()) expect_identical(vec_ptype(tab2), new_table(dim = c(0L, 2L, 1L))) }) test_that("can use a table in `vec_c()`", { expect_identical(vec_c(new_table()), new_table()) expect_identical(vec_c(new_table(), new_table()), new_table()) x <- new_table(1:5, 5L) y <- new_table(1:4, dim = c(2L, 2L)) expect_identical(vec_c(x, x), new_table(c(1:5, 1:5), dim = 10L)) expect_identical(vec_c(y, y), new_table(c(1:2, 1:2, 3:4, 3:4), dim = c(4L, 2L))) expect_identical(vec_c(x, y), new_table(c(1:5, 1:2, 1:5, 3:4), dim = c(7L, 2L))) }) test_that("names of the first dimension are kept in `vec_c()`", { x <- new_table(1:4, c(2L, 2L)) dimnames(x) <- list(c("r1", "r2"), c("c1", "c2")) xx <- vec_c(x, x) expect_identical(dimnames(xx), list(c("r1", "r2", "r1", "r2"), NULL)) }) test_that("can use a table in `vec_unchop()`", { x <- new_table(1:4, dim = c(2L, 2L)) expect_identical(vec_unchop(list(x)), x) expect_identical(vec_unchop(list(x, x), list(1:2, 4:3)), vec_slice(x, c(1:2, 2:1))) }) test_that("can concatenate tables", { x <- table(1:2) out <- vec_c(x, x) exp <- new_table(rep(1L, 4), dimnames = list(c("1", "2", "1", "2"))) expect_identical(out, exp) out <- vec_rbind(x, x) exp <- data_frame(`1` = new_table(c(1L, 1L)), `2` = new_table(c(1L, 1L))) expect_identical(out, exp) y <- table(list(1:2, 3:4)) out <- vec_c(y, y) exp <- new_table( matrix(int(1, 0, 1, 0, 0, 1, 0, 1), nrow = 4), dim = c(4L, 2L), dimnames = list(c("1", "2", "1", "2"), NULL) ) expect_identical(out, exp) out <- vec_rbind(y, y) exp <- new_data_frame(list( `3` = int(1, 0, 1, 0), `4` = int(0, 1, 0, 1) ), row.names = c("1...1", "2...2", "1...3", "2...4") ) expect_identical(out, exp) skip("FIXME: dimnames of matrices are not properly concatenated") }) test_that("can concatenate tables of type double ( x <- table(c(1, 2)) / 2 out <- vec_c(x, x) exp <- new_table(c(0.5, 0.5, 0.5, 0.5), dimnames = list(c("1", "2", "1", "2"))) expect_identical(out, exp) out <- vec_rbind(x, x) exp <- data_frame(`1` = new_table(c(0.5, 0.5)), `2` = new_table(c(0.5, 0.5))) expect_identical(out, exp) })
morphomap2Dmap<-function (morphomap.shape,rem.out = FALSE, fac.out = 0.5,smooth = FALSE,scale = TRUE, smooth.iter = 5,gamMap = FALSE,nrow = 90, ncol = 100,gdl = 250,method = "equiangular", unwrap = "A",plot = TRUE,pal = blue2green2red(101), aspect = 2) { thickarray<-morphomapThickness(morphomap.shape) data_t<-morphomapDF(thickarray,rem.out = rem.out, fac.out = fac.out, smooth = smooth, scale = scale, smooth.iter = smooth.iter, method = method, unwrap = unwrap) data <- data_t$XYZ labels <- data_t$labels if (gamMap == FALSE) { minx <- min(data$X, na.rm = T) miny <- min(data$Y, na.rm = T) maxx <- max(data$X, na.rm = T) maxy <- max(data$Y, na.rm = T) maxz <- max(data$Z, na.rm = T) minz <- min(data$Z, na.rm = T) atvalues <- seq(minz, maxz, length.out = 100) xat <- seq(1, 100, length.out = 5) ylabels<-round(seq(morphomap.shape$start,morphomap.shape$end,length.out = 5)*100,2) yat<-round(seq(miny,maxy,length.out = 5),2) map <- levelplot(data[, 3] ~ data[, 1] + data[, 2], xlab = "", ylab = "Biomechanical length", aspect = aspect, main = "2D thickness map", at = atvalues, col.regions = pal, scales = list(x = list(at = xat,labels = labels, rot = 90, alternating = 1), y = list(at = yat,labels = ylabels, rot = 90, alternating = 1))) if (plot == TRUE) { graphics::plot(map) } mat <- data } if (gamMap == TRUE) { m1 <- gam(Z ~ s(X, Y, k = gdl), data = data) minx <- min(data$X, na.rm = T) maxx <- max(data$X, na.rm = T) miny <- min(data$Y, na.rm = T) maxy <- max(data$Y, na.rm = T) wx <- maxx - minx wy <- maxy - miny sx <- wx/ncol sy <- wy/nrow xx <- seq(minx, maxx, length.out = ncol) yy <- seq(miny, maxy, length.out = nrow) xp <- vector() yp <- vector() xc <- vector() yc <- vector() for (i in seq(1, nrow)) for (j in seq(1, ncol)) { xp[(i - 1) * ncol + j] <- xx[j] yp[(i - 1) * ncol + j] <- yy[i] yc[(i - 1) * ncol + j] <- yy[i] xc[(i - 1) * ncol + j] <- xx[j] } fit <- predict.gam(m1, list(X = xp, Y = yp)) data <- data.frame(X = xc, Y = yc, Z = fit) if (scale == TRUE) { x <- data$Z thickvector <- (x - min(x))/(max(x) - min(x)) data$Z <- thickvector } minx <- min(data$X, na.rm = T) miny <- min(data$Y, na.rm = T) maxx <- max(data$X, na.rm = T) maxy <- max(data$Y, na.rm = T) maxz <- max(data$Z, na.rm = T) minz <- min(data$Z, na.rm = T) atvalues <- seq(minz, maxz, length.out = 100) xat <- seq(1, 100, length.out = 5) ylabels<-round(seq(morphomap.shape$start,morphomap.shape$end,length.out = 5)*100,2) yat<-round(seq(miny,maxy,length.out = 5),2) map <- levelplot(data[, 3] ~ data[, 1] + data[, 2], xlab = "", ylab = "Biomechanical length", aspect = aspect, main = "2D thickness map", at = atvalues, col.regions = pal, scales = list(x = list(at = xat,labels = labels, rot = 90, alternating = 1), y = list(at = yat,labels = ylabels, rot = 90, alternating = 1))) if (plot == TRUE) { graphics::plot(map) } mat <- data } if(gamMap==TRUE){ out <- list(dataframe = mat, `2Dmap` = map,gamoutput=m1,data=data)} if(gamMap==FALSE){ out <- list(dataframe = mat, `2Dmap` = map,gamoutput=NULL,data=data)} }
Rprof <- function(filename = "Rprof.out", append = FALSE, interval = 0.02, memory.profiling = FALSE, gc.profiling = FALSE, line.profiling = FALSE, filter.callframes = FALSE, numfiles = 100L, bufsize = 10000L) { if(is.null(filename)) filename <- "" invisible(.External(C_Rprof, filename, append, interval, memory.profiling, gc.profiling, line.profiling, filter.callframes, numfiles, bufsize)) } Rprofmem <- function(filename = "Rprofmem.out", append = FALSE, threshold = 0) { if(is.null(filename)) filename <- "" invisible(.External(C_Rprofmem, filename, append, as.double(threshold))) }
tabPanel('Line Graph', value = 'tab_line', fluidPage( fluidRow( column(12, align = 'left', h4('Line Chart') ) ), hr(), fluidRow( column(12, tabsetPanel(type = 'tabs', tabPanel('Variables', fluidRow( column(2, selectInput('line_select_x', 'X Axis Variable: ', choices = "", selected = ""), textInput('line_title', 'Title', value = ''), textInput('line_xlabel', 'X Axis Label', '') ), column(2, selectInput('line_select_y', 'Y Axis Variable: ', choices = "", selected = ""), textInput('line_subtitle', 'Subitle', value = ''), textInput('line_ylabel', 'Y Axis Label', '') ), column(8, plotOutput('line_plot_1') ) ) ), tabPanel('Aesthetics', column(4, tabsetPanel(type = 'tabs', tabPanel('Line', column(6, numericInput('line_width', 'Line Width', value = 1, step = 0.1), textInput('line_color', 'Color', value = 'black'), numericInput('line_type', 'Line Type', min = 1, max = 5, value = 1, step = 1) ) ), tabPanel('Points', column(6, flowLayout( selectInput('add_points', 'Add Points', choices = c("TRUE" = TRUE, "FALSE" = FALSE), selected = "FALSE"), numericInput('point_shape', 'Shape', min = 0, max = 25, value = 1), numericInput('point_size', 'Size', min = 0.5, value = 1), textInput('point_col', 'Color', 'black'), textInput('point_bg', 'Background Color', 'red') ) ) ) ) ), column(8, plotOutput('line_plot_2') ) ), tabPanel('Axis Range', column(2, uiOutput('ui_yrange_minl') ), column(2, uiOutput('ui_yrange_maxl') ), column(8, plotOutput('line_plot_3') ) ), tabPanel('Additional Lines', column(6, tabsetPanel(type = 'tabs', tabPanel('Add Lines', fluidRow( column(4, numericInput('n_lines', 'Lines', min = 0, value = 0, step = 1)) ), fluidRow( column(3, uiOutput('ui_nlines')), column(3, uiOutput('ui_ncolors')), column(3, uiOutput('ui_nltys')), column(3, uiOutput('ui_nlwds')) ) ) ) ), column(6, plotOutput('line_plot_4') ) ), tabPanel('Additional Points', column(6, tabsetPanel(type = 'tabs', tabPanel('Add Points', fluidRow( selectInput('extra_p', 'Add Points', choices = c("TRUE" = TRUE, "FALSE" = FALSE), selected = "FALSE") ), fluidRow( column(3, uiOutput('ui_pcolors')), column(3, uiOutput('ui_pbgcolor')), column(3, uiOutput('ui_psize')), column(3, uiOutput('ui_pshape')) ) ) ) ), column(6, plotOutput('line_plot_5') ) ), tabPanel('Others', column(4, tabsetPanel(type = 'tabs', tabPanel('Color', fluidRow( column(6, textInput('line_colaxis', 'Axis Color: ', 'black'), textInput('line_coltitle', 'Title Color: ', 'black') ), column(6, textInput('line_collabel', 'Label Color: ', 'black'), textInput('line_colsub', 'Subtitle Color: ', 'black') ) ) ), tabPanel('Size', fluidRow( column(6, numericInput('line_cexmain', 'Title Size: ', value = 1, min = 0.1, step = 0.1), numericInput('line_cexsub', 'Subtitle Size: ', value = 1, min = 0.1, step = 0.1) ), column(6, numericInput('line_cexaxis', 'Axis Size: ', value = 1, min = 0.1, step = 0.1), numericInput('line_cexlab', 'Label Size: ', value = 1, min = 0.1, step = 0.1) ) ) ), tabPanel('Font', fluidRow( column(6, numericInput('line_fontmain', 'Title Font', value = 1, min = 1, max = 5, step = 1), numericInput('line_fontsub', 'Subtitle Font', value = 1, min = 1, max = 5, step = 1) ), column(6, numericInput('line_fontaxis', 'Axis Font', value = 1, min = 1, max = 5, step = 1), numericInput('line_fontlab', 'Label Font', value = 1, min = 1, max = 5, step = 1) ) ) ) ) ), column(8, plotOutput('line_plot_6') ) ), tabPanel('Text', column(4, tabsetPanel(type = 'tabs', tabPanel('Text (Inside)', fluidRow( column(6, numericInput( inputId = "line_text_x_loc", label = "X Intercept: ", value = 1, step = 1), numericInput( inputId = "line_text_y_loc", label = "Y Intercept: ", value = 1, step = 1 ), textInput(inputId = "line_plottext", label = "Text:", value = "") ), column(6, numericInput( inputId = "line_textfont", label = "Text Font: ", value = 1, min = 1, max = 5, step = 1 ), numericInput( inputId = "line_textsize", label = "Text Size: ", value = 1, min = 0.1, step = 0.1 ), textInput( inputId = "line_textcolor", label = "Text Color: ", value = "black" ) ) ) ), tabPanel('Marginal Text', fluidRow( column(6, numericInput( inputId = "line_mtext_side", label = "Side: ", value = 1, min = 1, max = 4, step = 1 ), numericInput( inputId = "line_mtext_line", label = "Line: ", value = 1, step = 1 ), textInput(inputId = "line_mtextplot", label = "Text:", value = ""), numericInput( inputId = "line_mtextsize", label = "Text Size: ", value = 1, min = 0.1, step = 0.1 ) ), column(6, numericInput( inputId = "line_mtextadj", label = "Adj: ", value = 0.5, min = 0, max = 1, step = 0.1 ), numericInput( inputId = "line_mtextfont", label = "Text Font: ", value = 1, min = 1, max = 5, step = 1 ), textInput( inputId = "line_mtextcolor", label = "Text Color: ", value = "black" ) ) ) ) ) ), column(8, plotOutput('line_plot_7', height = '600px') ) ), tabPanel("Legend", column(6, tabsetPanel(type = 'tabs', tabPanel('General', br(), flowLayout( selectInput('line_leg_yn', 'Create Legend', choices = c("TRUE" = TRUE, "FALSE" = FALSE), selected = "FALSE") ), br(), h4('Axis Position', align = 'left', style = 'color:black'), flowLayout( numericInput('line_leg_x', 'X Axis:', value = 1), numericInput('line_leg_y', 'Y Axis:', value = 1) ), br(), h4('Legend Names', align = 'left', style = 'color:black'), flowLayout( numericInput('line_legnames', 'Select:', value = 0, min = 0, step = 1), uiOutput('ui_line_legnames') ), br(), h4('Lines', align = 'left', style = 'color:black'), flowLayout( numericInput('line_leg_line', 'Select:', value = 0, min = 1, max = 5, step = 1), uiOutput('ui_line_legline') ), br(), h4('Points', align = 'left', style = 'color:black'), flowLayout( numericInput('line_leg_point', 'Select:', value = 0, min = 0, max = 25, step = 1), uiOutput('ui_line_legpoint') ) ), tabPanel('Legend Box', flowLayout( selectInput('line_leg_boxtype', 'Box Type', choices = c('o', 'n'), selected = 'o'), textInput('line_leg_boxcol', 'Box Color', value = 'white'), numericInput('line_leg_boxlty', 'Box Border Line', value = 1, min = 1, max = 6, step = 1), numericInput('line_leg_boxlwd', 'Box Border Width', value = 1, min = 0, step = 0.1), textInput('line_leg_boxborcol', 'Box Border Color', value = 'black'), numericInput('line_leg_boxxjust', 'Horizontal Justification', value = 0, min = 0, max = 1), numericInput('line_leg_boxyjust', 'Vertical Justification', value = 1, min = 0, max = 1) ) ), tabPanel('Legend Text', flowLayout( selectInput('line_leg_texthoriz', 'Horizontal Text', choices = c(TRUE, FALSE), selected = FALSE), textInput('line_leg_textcol', 'Text Color', value = 'black'), textInput('line_leg_title', 'Title', value = ''), numericInput('line_leg_textfont', 'Text Font', value = 1, min = 1, max = 5, step = 1), numericInput('line_leg_textcolumns', 'Columns', value = 1, min = 0, step = 1), textInput('line_leg_titlecol', 'Title Color', value = 'black'), numericInput('line_leg_textadj', 'Text Horizontal Adj', value = 0.5, min = 0, max = 1, step = 0.1) ) ) ) ), column(6, plotOutput('line_plot_8', height = '400px') ) ), tabPanel('Plot', fluidRow( column(8, offset = 2, plotOutput('line_final') ) ) ) ) ) ) ) )
`pickcolors` <- function(COLLIST=colors(), BACK="white") { if(missing(COLLIST)) { COLLIST=colors() } if(missing(BACK)) { BACK="white" } ncol=5 cex = 1 if(length(COLLIST)>50) { ncol=15 cex=.6 } DF = SELOPT(COLLIST, onoff=-1, ncol=ncol, ocols =COLLIST, cex=.6 ) PDF = paste(sep="", "\"", paste(DF, collapse="\",\""), "\"") cat(file="Copy and paste this into your R session:","\n") cat(file="","\n") cat(file="",paste(sep="", "thecols", "=c(", PDF , ")") , fill=TRUE) cat(file="","\n") if(!is.null(DF)) { return(DF) } else { return(NULL) } }
fitplcs <- function(dfr, group, ...){ if(!group %in% names(dfr)) stop("You must provide a name in the dataframe to fit by.") dfrs <- split(dfr, dfr[,group]) fits <- lapply(dfrs, function(x)fitplc(x, ...)) class(fits) <- "manyplcfit" return(fits) } fitconds <- function(dfr, group, ...){ if(!group %in% names(dfr)) stop("You must provide a name in the dataframe to fit by.") dfrs <- split(dfr, dfr[,group]) fits <- lapply(dfrs, function(x)fitcond(x, ...)) class(fits) <- "manyplcfit" return(fits) }
test_that("coercing tbl_time to tibble works", { df <- as_tbl_time(FANG, date) x <- as_tibble(df) expect_s3_class(x, c("tbl_df", "tbl", "data.frame"), exact = TRUE) expect_null(attr(x, "index_quo")) expect_null(attr(x, "index_time_zone")) }) test_that("coercing grouped_tbl_time to tibble drops groupedness", { df <- as_tbl_time(FANG, date) gdf <- group_by(df, symbol) x <- as_tibble(gdf) expect_s3_class(x, c("tbl_df", "tbl", "data.frame"), exact = TRUE) })
inputsRecordUI <- function(id){ ns <- NS(id) box( title = h2("2. Input Record"), width = 4, collapsible = TRUE, solidHeader = TRUE, status = "success", selectizeInput(ns("InputSiteName"), label = "Site *", choices = NULL, options = list( placeholder = 'Please search or select a site below', onInitialize = I('function() { this.setValue(""); }') ) ), hr(), selectizeInput(ns("InputParentName"), label = "Parent *", choices = NULL, options = list( placeholder = 'Please search inputs by name or site', onInitialize = I('function() { this.setValue(""); }') ) ), hr(), textInput(ns("InputName"), label = "Name *", placeholder = ""), verbatimTextOutput(ns("autoname")), hr(), selectizeInput(ns("InputFormatName"), label = "Choose Format *", choices = NULL, options = list( placeholder = 'Please search Formats by name', onInitialize = I('function() { this.setValue(""); }') ) ), p("or"), hr(), dateInput( ns("InputStartDate"), label = "Start Date", format = "yyyy-mm-dd", startview = "decade" ), shinyTime::timeInput(ns("StartTimeInput"), label = "Start Time (Hours - Minutes)", seconds = FALSE), dateInput( ns('InputEndDate'), label = 'End Date', format = 'yyyy-mm-dd', startview = 'decade' ), shinyTime::timeInput(ns("EndTimeInput"), label = "End Time (Hours-Minutes)", seconds = FALSE), textInput(ns("Timezone"), label = "Timezone (UTC)", placeholder = "UTC +/-"), hr(), textAreaInput(ns("InputNotes"), label = "Notes", height = '150px'), actionButton(ns("createInput"), label = "Create Input"), p("* Denotes a Required Field"), hr(), verbatimTextOutput(ns("summInputs")) ) } inputsRecord <- function(input, output, session){ inputsList <- list() updateSelectizeInput(session, "InputSiteName", choices = sitenames, server = TRUE) updateSelectizeInput(session, "InputParentName", choices = input_names, server = TRUE) updateSelectizeInput(session, "InputFormatName", choices = formats, server = TRUE) observeEvent(input$createInput, { inputsList$siteName <- input$InputSiteName inputsList$siteID <- sites %>% dplyr::filter(sitename %in% inputsList$siteName) %>% pull(id) inputsList$parentName <- input$InputParentName inputsList$parentID <- inputs %>% dplyr::filter(name %in% inputsList$parentName) %>% pull(id) inputsList$formatName <- input$InputFormatName inputsList$formatID <- formats_sub %>% dplyr::filter(name %in% inputsList$formatName) %>% pull(id) inputsList$Name <- input$InputName inputsList$StartDate <- input$InputStartDate inputsList$StartTime <- input$StartTimeInput inputsList$EndDate <- input$InputEndDate inputsList$EndTime <- input$EndTimeInput inputsList$Timezone <- input$Timezone inputsList$Notes <- input$InputNotes output$summInputs <- renderPrint({print(inputsList)}) }) }