code
stringlengths
1
13.8M
library(testthat) library(hansard) test_check("hansard", filter = "misc1")
mlnaka <- function(x, na.rm = FALSE, ...) { if (na.rm) x <- x[!is.na(x)] else assertthat::assert_that(!anyNA(x)) ml_input_checker(x) assertthat::assert_that(min(x) > 0) n <- length(x) object <- mlgamma(x^2, na.rm = na.rm, ...) object["rate"] <- 1 / object["rate"] * object["shape"] names(object) <- c("shape", "scale") shape <- object["shape"] scale <- object["scale"] class(object) <- "univariateML" attr(object, "model") <- "Nakagami" attr(object, "density") <- "nakagami::dnaka" attr(object, "logLik") <- unname(n * (shape * log(shape) + log(2) - lgamma(shape) - shape * log(scale)) + (2 * shape - 1) * sum(log(x)) - shape / scale * sum(x^2)) attr(object, "support") <- c(0, Inf) attr(object, "n") <- length(x) attr(object, "call") <- match.call() object }
context("varying") if(identical(Sys.getenv("NCRAN"), "TRUE")) pwlddev <- eval(parse(text = paste0("plm", ":", ":", "pdata.frame(wlddev, index = c('iso3c', 'year'))"))) gwlddev <- fgroup_by(wlddev, iso3c) wdm <- qM(`cat_vars<-`(wlddev, dapply(cat_vars(wlddev), qG))) g <- GRP(wlddev, ~ region + year) test_that("vector, matrix and data.frame methods work as intended", { expect_true(all(dapply(wlddev, varying))) expect_true(all(varying(wlddev))) expect_true(all(varying(wdm))) expect_true(is.atomic(varying(wlddev, drop = TRUE))) expect_true(is.atomic(varying(wdm, drop = TRUE))) expect_true(is.data.frame(varying(wlddev, drop = FALSE))) expect_true(is.matrix(varying(wdm, drop = FALSE))) expect_true(all_identical(dapply(wlddev, varying), varying(wlddev), varying(wdm))) expect_true(all_identical(dapply(wlddev, varying, drop = FALSE), varying(wlddev, drop = FALSE), qDF(varying(wdm, drop = FALSE)))) expect_equal(dapply(unattrib(wlddev), varying, wlddev$iso3c), c(FALSE,FALSE,TRUE,TRUE,TRUE,FALSE,FALSE,FALSE,TRUE,TRUE,TRUE,TRUE,TRUE)) expect_true(all_identical(dapply(wlddev, varying, wlddev$iso3c), varying(wlddev, wlddev$iso3c), varying(wdm, wlddev$iso3c))) expect_true(all_identical(dapply(wlddev, varying, wlddev$iso3c, drop = FALSE), varying(wlddev, wlddev$iso3c, drop = FALSE), qDF(varying(wdm, wlddev$iso3c, drop = FALSE)))) expect_true(all_identical(qM(dapply(wlddev, varying, wlddev$iso3c, any_group = FALSE)), qM(varying(wlddev, wlddev$iso3c, any_group = FALSE)), varying(wdm, wlddev$iso3c, any_group = FALSE))) expect_true(all_identical(qM(dapply(wlddev, varying, wlddev$iso3c, any_group = FALSE, drop = FALSE)), qM(varying(wlddev, wlddev$iso3c, any_group = FALSE, drop = FALSE)), varying(wdm, wlddev$iso3c, any_group = FALSE, drop = FALSE))) expect_true(all_identical(qM(dapply(wlddev, varying, wlddev$iso3c, any_group = FALSE, use.g.names = FALSE)), qM(varying(wlddev, wlddev$iso3c, any_group = FALSE, use.g.names = FALSE)), varying(wdm, wlddev$iso3c, any_group = FALSE, use.g.names = FALSE))) expect_true(all_identical(qM(dapply(wlddev, varying, wlddev$iso3c, any_group = FALSE, use.g.names = FALSE, drop = FALSE)), qM(varying(wlddev, wlddev$iso3c, any_group = FALSE, use.g.names = FALSE, drop = FALSE)), varying(wdm, wlddev$iso3c, any_group = FALSE, use.g.names = FALSE, drop = FALSE))) expect_equal(dapply(unattrib(wlddev), varying, g), c(TRUE,TRUE,FALSE,FALSE,FALSE,FALSE,TRUE,TRUE,TRUE,TRUE,TRUE,TRUE,TRUE)) expect_true(all_identical(dapply(wlddev, varying, g), varying(wlddev, g), varying(wdm, g))) expect_true(all_identical(dapply(wlddev, varying, g, drop = FALSE), varying(wlddev, g, drop = FALSE), qDF(varying(wdm, g, drop = FALSE)))) expect_true(all_identical(qM(dapply(wlddev, varying, g, any_group = FALSE)), qM(varying(wlddev, g, any_group = FALSE)), varying(wdm, g, any_group = FALSE))) expect_true(all_identical(qM(dapply(wlddev, varying, g, any_group = FALSE, drop = FALSE)), qM(varying(wlddev, g, any_group = FALSE, drop = FALSE)), varying(wdm, g, any_group = FALSE, drop = FALSE))) expect_true(all_identical(qM(dapply(wlddev, varying, g, any_group = FALSE, use.g.names = FALSE)), qM(varying(wlddev, g, any_group = FALSE, use.g.names = FALSE)), varying(wdm, g, any_group = FALSE, use.g.names = FALSE))) expect_true(all_identical(qM(dapply(wlddev, varying, g, any_group = FALSE, use.g.names = FALSE, drop = FALSE)), qM(varying(wlddev, g, any_group = FALSE, use.g.names = FALSE, drop = FALSE)), varying(wdm, g, any_group = FALSE, use.g.names = FALSE, drop = FALSE))) }) test_that("data.frame method formula and cols work as intended", { expect_equal(varying(wlddev, cols = 2:5), varying(get_vars(wlddev, 2:5))) expect_equal(varying(wlddev, cols = c("PCGDP","country")), varying(get_vars(wlddev, c("PCGDP","country")))) expect_equal(varying(wlddev, cols = is.numeric), varying(num_vars(wlddev))) expect_equal(varying(wlddev, ~iso3c), varying(fselect(wlddev, -iso3c), wlddev$iso3c)) expect_equal(varying(wlddev, PCGDP + country ~ iso3c), varying(fselect(wlddev, PCGDP, country), wlddev$iso3c)) expect_equal(varying(wlddev, PCGDP + country ~ iso3c), varying(wlddev, ~ iso3c, cols = c("PCGDP", "country"))) expect_equal(varying(wlddev, ~iso3c, any_group = FALSE), varying(fselect(wlddev, -iso3c), wlddev$iso3c, any_group = FALSE)) expect_equal(varying(wlddev, PCGDP + country ~ iso3c, any_group = FALSE), varying(fselect(wlddev, PCGDP, country), wlddev$iso3c, any_group = FALSE)) expect_equal(varying(wlddev, PCGDP + country ~ iso3c, any_group = FALSE), varying(wlddev, ~ iso3c, cols = c("PCGDP", "country"), any_group = FALSE)) expect_equal(varying(wlddev, ~region + year), varying(fselect(wlddev, -region, -year), g)) expect_equal(varying(wlddev, PCGDP + country ~ region + year), varying(fselect(wlddev, PCGDP, country), g)) expect_equal(varying(wlddev, PCGDP + country ~ region + year), varying(wlddev, ~ region + year, cols = c("PCGDP", "country"))) expect_equal(varying(wlddev, ~region + year, any_group = FALSE), varying(fselect(wlddev, -region, -year),g, any_group = FALSE)) expect_equal(varying(wlddev, PCGDP + country ~ region + year, any_group = FALSE), varying(fselect(wlddev, PCGDP, country), g, any_group = FALSE)) expect_equal(varying(wlddev, PCGDP + country ~ region + year, any_group = FALSE), varying(wlddev, ~ region + year, cols = c("PCGDP", "country"), any_group = FALSE)) expect_error(varying(wlddev, ~ iso3c2)) expect_error(varying(wlddev, PCGDP + country ~ iso3c2)) expect_error(varying(wlddev, PCGDP + country2 ~ iso3c)) expect_error(varying(wlddev, ~ iso3c, cols = c("PCGDP", "country2"))) expect_error(varying(wlddev, ~ region2 + year)) expect_error(varying(wlddev, PCGDP + country ~ region2 + year)) expect_error(varying(wlddev, PCGDP + country2 ~ region3 + year)) expect_error(varying(wlddev, ~ region + year, cols = c("PCGDP", "country2"))) }) if(identical(Sys.getenv("NCRAN"), "TRUE")) { test_that("pseries and pdata.frame methods work as intended", { expect_equal(unattrib(varying(pwlddev)), c(FALSE,TRUE,TRUE,TRUE,FALSE,FALSE,FALSE,TRUE,TRUE,TRUE,TRUE,TRUE)) expect_equal(unattrib(varying(pwlddev, effect = "iso3c")), c(FALSE,TRUE,TRUE,TRUE,FALSE,FALSE,FALSE,TRUE,TRUE,TRUE,TRUE,TRUE)) expect_equal(unattrib(varying(pwlddev, effect = 2L)), c(TRUE,TRUE,FALSE,FALSE,TRUE,TRUE,TRUE,TRUE,TRUE,TRUE,TRUE,TRUE)) expect_equal(unattrib(varying(pwlddev, effect = "year")), c(TRUE,TRUE,FALSE,FALSE,TRUE,TRUE,TRUE,TRUE,TRUE,TRUE,TRUE,TRUE)) expect_true(is.atomic(varying(pwlddev, drop = TRUE))) expect_true(is.data.frame(varying(pwlddev, drop = FALSE))) expect_true(is.data.frame(varying(pwlddev, any_group = FALSE))) atrapply <- function(X, FUN, ...) { res <- vector("list", fncol(X)) for(i in seq_col(X)) { res[[i]] <- FUN(X[[i]], ...) } res } expect_identical(attributes(fselect(pwlddev, country:POP)), attributes(pwlddev)) expect_identical(attributes(get_vars(pwlddev, seq_col(pwlddev))), attributes(pwlddev)) expect_equal(unlist(atrapply(fselect(pwlddev, -iso3c), varying)), c(FALSE,TRUE,TRUE,TRUE,FALSE,FALSE,FALSE,TRUE,TRUE,TRUE,TRUE,TRUE)) expect_equal(unlist(atrapply(fselect(pwlddev, -iso3c), varying, effect = "iso3c")), c(FALSE,TRUE,TRUE,TRUE,FALSE,FALSE,FALSE,TRUE,TRUE,TRUE,TRUE,TRUE)) expect_equal(unlist(atrapply(fselect(pwlddev, -year), varying, effect = 2L)), c(TRUE,TRUE,FALSE,FALSE,TRUE,TRUE,TRUE,TRUE,TRUE,TRUE,TRUE,TRUE)) expect_equal(unlist(atrapply(fselect(pwlddev, -year), varying, effect = "year")), c(TRUE,TRUE,FALSE,FALSE,TRUE,TRUE,TRUE,TRUE,TRUE,TRUE,TRUE,TRUE)) expect_equal(varying(pwlddev$PCGDP), varying(wlddev$PCGDP, wlddev$iso3c)) expect_equal(varying(pwlddev$PCGDP, any_group = FALSE), varying(wlddev$PCGDP, wlddev$iso3c, any_group = FALSE)) expect_equal(varying(pwlddev$PCGDP, any_group = FALSE, use.g.names = FALSE), varying(wlddev$PCGDP, wlddev$iso3c, any_group = FALSE, use.g.names = FALSE)) expect_equal(lengths(varying(pwlddev, any_group = FALSE), FALSE), lengths(atrapply(fselect(pwlddev, -iso3c), varying, any_group = FALSE))) expect_identical(unattrib(varying(fselect(wlddev, -iso3c), wlddev$iso3c, any_group = FALSE)), unattrib(varying(pwlddev, any_group = FALSE))) expect_identical(unattrib(varying(fselect(wlddev, -iso3c), wlddev$iso3c, any_group = FALSE, drop = FALSE)), unattrib(varying(pwlddev, any_group = FALSE, drop = FALSE))) expect_identical(unattrib(varying(fselect(wlddev, -iso3c), wlddev$iso3c, any_group = FALSE, use.g.names = FALSE)), unattrib(varying(pwlddev, any_group = FALSE, use.g.names = FALSE))) expect_identical(unattrib(varying(fselect(wlddev, -iso3c), wlddev$iso3c, any_group = FALSE, use.g.names = FALSE, drop = FALSE)), unattrib(varying(pwlddev, any_group = FALSE, use.g.names = FALSE, drop = FALSE))) expect_identical(unattrib(varying(fselect(wlddev, -year), wlddev$year, any_group = FALSE)), unattrib(varying(pwlddev, any_group = FALSE, effect = "year"))) expect_identical(unattrib(varying(fselect(wlddev, -year), wlddev$year, any_group = FALSE, drop = FALSE)), unattrib(varying(pwlddev, any_group = FALSE, drop = FALSE, effect = "year"))) expect_identical(unattrib(varying(fselect(wlddev, -year), wlddev$year, any_group = FALSE, use.g.names = FALSE)), unattrib(varying(pwlddev, any_group = FALSE, use.g.names = FALSE, effect = "year"))) expect_identical(unattrib(varying(fselect(wlddev, -year), wlddev$year, any_group = FALSE, use.g.names = FALSE, drop = FALSE)), unattrib(varying(pwlddev, any_group = FALSE, use.g.names = FALSE, drop = FALSE, effect = "year"))) }) } test_that("grouped_df method works as intended", { expect_equal(unattrib(varying(gwlddev)), c(FALSE,TRUE,TRUE,TRUE,FALSE,FALSE,FALSE,TRUE,TRUE,TRUE,TRUE,TRUE)) expect_true(is.atomic(varying(gwlddev, drop = TRUE))) expect_true(is.data.frame(varying(gwlddev, drop = FALSE))) expect_true(is.data.frame(varying(gwlddev, any_group = FALSE))) expect_identical(names(varying(gwlddev)), names(wlddev)[-2L]) expect_identical(names(varying(get_vars(gwlddev, 9:12))), names(wlddev)[9:12]) expect_identical(names(varying(gwlddev, any_group = FALSE)), c("iso3c", names(wlddev)[-2L])) expect_identical(names(varying(gwlddev, any_group = FALSE, keep.group_vars = FALSE)), names(wlddev)[-2L]) expect_identical(names(varying(get_vars(gwlddev, 9:12), any_group = FALSE)), c("iso3c", names(wlddev)[9:12])) expect_identical(names(varying(get_vars(gwlddev, 9:12), any_group = FALSE, keep.group_vars = FALSE)), names(wlddev)[9:12]) expect_identical(unattrib(varying(fselect(wlddev, -iso3c), wlddev$iso3c, any_group = FALSE)), unattrib(varying(gwlddev, any_group = FALSE, keep.group_vars = FALSE))) expect_identical(unattrib(varying(fselect(wlddev, -iso3c), wlddev$iso3c, any_group = FALSE, drop = FALSE)), unattrib(varying(gwlddev, any_group = FALSE, drop = FALSE, keep.group_vars = FALSE))) expect_identical(unclass(varying(fselect(wlddev, -iso3c), wlddev$iso3c, any_group = FALSE, use.g.names = FALSE)), unclass(fungroup(varying(gwlddev, any_group = FALSE, use.g.names = FALSE, keep.group_vars = FALSE)))) expect_identical(unclass(varying(fselect(wlddev, -iso3c), wlddev$iso3c, any_group = FALSE, drop = FALSE)), unclass(fungroup(varying(gwlddev, any_group = FALSE, use.g.names = TRUE, drop = FALSE, keep.group_vars = FALSE)))) })
rlqESLTP <- function(dudiE, dudiS, dudiL, dudiT, dudiP, ...){ if(!is.null(dudiE)) tabE <- dudiE$li/sqrt(dudiE$eig[1]) if(!is.null(dudiS)) tabS <- dudiS$li/sqrt(dudiS$eig[1]) if(!is.null(dudiP)) tabP <- dudiP$li/sqrt(dudiP$eig[1]) if(!is.null(dudiT)) tabT <- dudiT$li/sqrt(dudiT$eig[1]) if(!is.null(dudiE)&!is.null(dudiS)){ tabES <- cbind.data.frame(tabE, tabS) names(tabES) <- c(paste("E", 1:ncol(tabE), sep = ""), paste("S", 1:ncol(tabS), sep = "")) pcaES <- dudi.pca(tabES, scale = FALSE, row.w = dudiL$lw, scannf = FALSE, nf = (length(dudiE$eig) + length(dudiS$eig))) } else{ if(!is.null(dudiE)) pcaES <- dudiE else{ if(!is.null(dudiS)) pcaES <- dudiS else stop("one table giving site attributes is missing") } } if(!is.null(dudiT)&!is.null(dudiP)){ tabTP <- cbind.data.frame(tabT, tabP) names(tabTP) <- c(paste("T", 1:ncol(tabT), sep = ""), paste("P", 1:ncol(tabP), sep = "")) pcaTP <- dudi.pca(tabTP, scale = FALSE, row.w = dudiL$cw, scannf = FALSE, nf = (length(dudiT$eig) + length(dudiP$eig))) } else{ if(!is.null(dudiT)) pcaTP <- dudiT else{ if(!is.null(dudiP)) pcaTP <- dudiP else stop("one table giving species attributes is missing") } } X <- rlq(pcaES, dudiL, pcaTP, ...) if(!is.null(dudiE)){ U <- as.matrix(X$l1) * unlist(X$lw) U <- data.frame(as.matrix(pcaES$tab[, 1:ncol(tabE)]) %*% U[1:ncol(tabE), 1:X$nf]) row.names(U) <- row.names(pcaES$tab) names(U) <- names(X$lR) X$lR_givenE <- U } if(!is.null(dudiS)){ U <- as.matrix(X$l1) * unlist(X$lw) if(!is.null(dudiE)){ U <- data.frame(as.matrix(pcaES$tab[, -(1:ncol(tabE))]) %*% U[-(1:ncol(tabE)), 1:X$nf]) row.names(U) <- row.names(pcaES$tab) } else{ U <- data.frame(as.matrix(pcaES$tab) %*% U[, 1:X$nf]) row.names(U) <- row.names(pcaES$tab) } names(U) <- names(X$lR) X$lR_givenS <- U } if(!is.null(dudiT)){ U <- as.matrix(X$c1) * unlist(X$cw) U <- data.frame(as.matrix(pcaTP$tab[, 1:ncol(tabT)]) %*% U[1:ncol(tabT), 1:X$nf]) row.names(U) <- row.names(pcaTP$tab) names(U) <- names(X$lQ) X$lQ_givenT <- U } if(!is.null(dudiP)){ U <- as.matrix(X$c1) * unlist(X$cw) if(!is.null(dudiT)){ U <- data.frame(as.matrix(pcaTP$tab[, -(1:ncol(tabT))]) %*% U[-(1:ncol(tabT)), 1:X$nf]) row.names(U) <- row.names(pcaTP$tab) } else{ U <- data.frame(as.matrix(pcaTP$tab) %*% U[, 1:X$nf]) row.names(U) <- row.names(pcaTP$tab) } names(U) <- names(X$lQ) X$lQ_givenP <- U } X$row.w <- dudiL$lw X$col.w <- dudiL$cw X$dudiL <- dudiL X$dudiR <- pcaES X$dudiQ <- pcaTP class(X) <- c("rlqESLTP", "rlq", "dudi") return(X) }
profile_ci_t <- function(data, lower1, upper1, lower2, upper2, cp, df=4, starVal=NA, nlm=FALSE, ...) { F <- prepare_data(data, lower1, upper1, lower2, upper2) B <- estimate_t(F, df=df, starVal=starVal, ...) r0 <- B$C[1,2] / sqrt(B$C[1,1]*B$C[2,2]) loglike <- genloglike5t(F,df=df) if (is.na(starVal)) { sv <- starting_values(F) } else { sv <- starVal } sv <- c(sv[1], sv[2], sv[3], sv[5]) q <- qchisq(cp, 1)/2 g <- function(r, nlm=FALSE, ...) { if(nlm==TRUE){ f <- genNegloglike4t(F, r, df=df) m <- nlm(f, sv, hessian = TRUE, ...) tmpllk <- -m$minimum sv <- c(m$estimate[1], m$estimate[2], m$estimate[3], m$estimate[4]) }else{ f <- genloglike4t(F, r, df=df) m <- try(optim(sv, f, control=list(fnscale=-1), ...), silent=TRUE) tmpllk <- m$value sv <- c(m$par[1], m$par[2], m$par[3], m$par[4]) } return(B$loglike - tmpllk - q) } llb <- -1 r1 <- try(bracket(g, r0, llb, nlm=nlm, ...), silent=TRUE) while (class(r1) == "try-error"){ llb <- llb/2 r1 <- try(bracket(g, r0, llb, nlm=nlm, ...), silent=TRUE) } lcl <- uniroot(g, c(r1, r0)) rlb <- 1 r2 <- try(bracket(g, r0, rlb, nlm=nlm, ...), silent=TRUE) while (class(r2) == "try-error"){ rlb <- rlb/2 r2 <- try(bracket(g, r0, rlb, nlm=nlm, ...), silent=TRUE) } ucl <- uniroot(g, c(r0, r2)) return(list(lcl=lcl$root, ucl=ucl$root)) }
gen2single <- function(pu,pa,ep1,ep2,nsoln=5) { if(pu<pa){ soln <- ph2single(pu=pu,pa=pa,ep1=ep1,ep2=ep2,nsoln=nsoln) }else if(pu>pa){ tmp.soln <- ph2single(pu=(1-pu),pa=(1-pa),ep1=ep1,ep2=ep2,nsoln=nsoln) soln <- tmp.soln soln$r <- tmp.soln$n-tmp.soln$r }else{ stop("!!!Should pu and pa be either pu>pa or pu<pa!!!\n") } soln ph1 <- list() ph1$pu <- pu ph1$pa <- pa ph1$alpha <- ep1 ph1$beta <- ep2 ph1$out <- soln ph1$nsoln <- nsoln class(ph1) <- "gen2single" ph1 } print.gen2single <- function(x, ...) { xout <- x$out nmax <- x$nsoln xopt <- xout[1,] dimnames(xopt)[[1]] <- c("Optimal") cat("\n Generalized 1-stage Phase II design \n\n") cat("Unacceptable response/toxicity rate: ",x$pu,"\n") cat("Desirable response/toxicity rate: ",x$pa,"\n") cat("Error rates: alpha = ",x$alpha,"; beta = ",x$beta,"\n\n") print(xopt, digits = 4, ...) cat("\n") } gen2simon <- function(pu, pa, ep1, ep2, nmax = 100) { if(nmax > 1000) stop("nmax cannot exceed 1000") alpha.beta <- function(data){ oc.gentwostage.bdry(data[1],data[2],data[3],data[4],data[5],data[6]) } if(pu<pa){ gph2 <- ph2simon(pu=pu,pa=pa,ep1=ep1,ep2=ep2,nmax=nmax) tout <- gph2$out t2out <- cbind(rep(pu,dim(tout)[1]),rep(pa,dim(tout)[1]),tout[,c(1:4)]) t3out <- apply(t2out,1,alpha.beta) tmp.alpha <- as.numeric(t3out[1,]) tmp.beta <- 1-as.numeric(t3out[2,]) t4out <- tout t5out <- cbind(t4out,alpha=tmp.alpha,beta=tmp.beta) gph2$out <- t5out }else if(pu>pa){ tmp.gph2 <- ph2simon(pu=(1-pu),pa=(1-pa),ep1=ep1,ep2=ep2,nmax=nmax) tout <- tmp.gph2$out t2out <- cbind(rep((1-pu),dim(tout)[1]),rep((1-pa),dim(tout)[1]),tout[,c(1:4)]) t3out <- apply(t2out,1,alpha.beta) tmp.alpha <- as.numeric(t3out[1,]) tmp.beta <- 1-as.numeric(t3out[2,]) t4out <- tout t5out <- cbind(t4out,alpha=tmp.alpha,beta=tmp.beta) tmp.gph2$out <- t5out gph2 <- tmp.gph2 gph2$pu <- pu gph2$pa <- pa gph2$out[,1] <- tmp.gph2$out[,2]-tmp.gph2$out[,1] gph2$out[,3] <- tmp.gph2$out[,4]-tmp.gph2$out[,3] }else{ stop("!!!Should pu and pa be either pu>pa or pu<pa!!!\n") } ph2 <- gph2 class(ph2) <- "gen2simon" ph2 } print.gen2simon <- function(x, ...) { xout <- x$out nmax <- x$nmax n <- nrow(xout) nopt <- ((1:n)[xout[,5]==min(xout[,5])])[1] xopt <- xout[c(nopt,1),] dimnames(xopt)[[1]] <- c("Optimal","Minimax") cat("\n Generalized 2-stage Phase II design \n\n") cat("Unacceptable response/toxicity rate: ",x$pu,"\n") cat("Desirable response/toxicity rate: ",x$pa,"\n") cat("Error rates: alpha = ",x$alpha,"; beta = ",x$beta,"\n\n") print(xopt, digits = 4, ...) cat("\n") if(xopt[1,4]>nmax-10) warning(paste(" Optimal sample size too close to nmax. \n Try increasing nmax (current value = ",nmax,")\n",sep="")) } plot.gen2simon <- function(x, ...) { xout <- x$out n <- nrow(xout) nopt <- ((1:n)[xout[,5]==min(xout[,5])])[1] nopt1 <- min(nopt+5,n) plot(xout[1:nopt1,4],xout[1:nopt1,5],type="l",xlab="Maximum number of patients",ylab="Expected trial size", ...) points(xout[1,4],xout[1,5],pch="M") points(xout[nopt,4],xout[nopt,5],pch="O") } oc.gentwostage.bdry <- function(pu, pa, r1, n1, r, n){ if(pu<pa){ out <- oc.twostage.bdry(pu=pu,pa=pa,r1=r1,n1=n1,r=r,n=n) }else if(pu>pa){ tmp.out <- oc.twostage.bdry(pu=(1-pu),pa=(1-pa),r1=(n1-r1),n1=n1,r=(n-r),n=n) out <- tmp.out }else{ stop("!!!Should pu and pa be either pu>pa or pu<pa!!!\n") } out }
SetOptions = function(y, t, optns){ methodMuCovEst = optns[['methodMuCovEst']] userBwMu =optns[['userBwMu']]; methodBwMu =optns[['methodBwMu']]; userBwCov =optns[['userBwCov']]; methodBwCov =optns[['methodBwCov']]; kFoldMuCov = optns[['kFoldMuCov']] methodSelectK =optns[['methodSelectK']]; FVEthreshold =optns[['FVEthreshold']]; FVEfittedCov =optns[['FVEfittedCov']]; fitEigenValues <- optns[['fitEigenValues']]; maxK =optns[['maxK']]; dataType =optns[['dataType']]; error =optns[['error']]; nRegGrid =optns[['nRegGrid']]; methodXi =optns[['methodXi']]; shrink =optns[['shrink']] kernel =optns[['kernel']]; numBins =optns[['numBins']]; yname =optns[['yname']]; methodRho =optns[['methodRho']]; usergrid =optns[['usergrid']]; userRho = optns[['userRho']]; diagnosticsPlot =optns[['diagnosticsPlot']]; plot =optns[['plot']]; if (!is.null(diagnosticsPlot)) { warning("The option 'diagnosticsPlot' is deprecated. Use 'plot' instead") plot = diagnosticsPlot } verbose =optns[['verbose']]; userMu =optns[['userMu']]; outPercent =optns[['outPercent']]; userCov =optns[['userCov']]; userSigma2 = optns[['userSigma2']] rotationCut =optns[['rotationCut']]; useBinnedData =optns[['useBinnedData']]; useBinnedCov = optns[['useBinnedCov']] lean = optns[['lean']]; useBW1SE =optns[['useBW1SE']]; imputeScores = optns[['imputeScores']]; if(is.null(methodBwMu)){ methodBwMu = 'Default' } if(is.null(userBwMu) && methodBwMu == 'Default'){ userBwMu = 0.05 * diff(range(unlist(t))); } if(is.null(userBwMu) && methodBwMu != 'Default'){ userBwMu = 0.0; } if(is.null(methodBwCov)){ methodBwCov = 'Default'; } if(is.null(userBwCov) && methodBwCov == 'Default'){ userBwCov = 0.10 * diff(range(unlist(t))); } if(is.null(userBwCov) && methodBwCov != 'Default'){ userBwCov = 0.0; } if (is.null(kFoldMuCov)) { kFoldMuCov <- 10L } else { kFoldMuCov <- as.integer(kFoldMuCov) } if(is.null(methodSelectK)){ methodSelectK = "FVE"; } if(is.null(FVEthreshold)){ FVEthreshold = 0.99; } if(is.null(FVEfittedCov)){ FVEfittedCov = NULL; } if(is.null(dataType)){ dataType = IsRegular(t); } if (is.null(fitEigenValues)) { fitEigenValues <- FALSE } if(is.null(methodMuCovEst)){ if (dataType == 'Sparse'){ methodMuCovEst = 'smooth'; } else { methodMuCovEst = 'cross-sectional'; } } if (fitEigenValues && dataType == 'Dense') { stop('Fit method only apply to sparse data') } if(is.null(error)){ error = TRUE; } if(is.null(nRegGrid)){ if(dataType == 'Dense' || dataType == 'DenseWithMV'){ tt = unlist(t) nRegGrid = length(unique(signif(tt[!is.na(tt)],6))); } else { nRegGrid = 51; } } if(is.null(maxK)){ maxK = min( nRegGrid-2, length(y)-2 ); if(methodMuCovEst == 'smooth'){ maxK = min( maxK, 20) } if(maxK < 1){ message("Automatically defined maxK cannot be less than 1. Reset to maxK = 1 now!\n") maxK = 1 } if( length(y) <= 3 ){ message("The sample size is less or equal to 3 curves. Be cautious!\n") } } methodNames = c("IN", "CE"); if(!is.null(methodXi) && !(methodXi %in% methodNames)){ message(paste('methodXi', methodXi, 'is unrecognizable! Reset to automatic selection now!\n')); methodXi = NULL; } if(is.null(methodXi)){ if(dataType == 'Dense'){ methodXi = "IN"; } else{ if(dataType == 'Sparse'){ if(min(sapply(1:length(t),function(i){length(t[[i]])}))>20){ tt = unlist(t); T_min=range(tt)[1]; T_max=range(tt)[2]; Spacing_max=max(sapply(1:length(t),function(i){max(c(t[[i]][1]-T_min,diff(t[[i]]),T_max-t[[i]][length(t[[i]])]))})); if(Spacing_max<=(max(tt)-min(tt))*0.06){ methodXi = "IN"; } else{ methodXi = "CE"; } } else{ methodXi = "CE"; } } else{ if(dataType == 'DenseWithMV'){ methodXi = "CE" } else{ methodXi = "IN" } } } } if(is.null(shrink)){ shrink = FALSE; } if(shrink == TRUE && (error != TRUE || methodXi != "IN")){ message('shrinkage method only has effects when methodXi = "IN" and error = TRUE! Reset to shrink = FALSE now!\n'); shrink = FALSE } if(is.null(kernel)){ if(dataType == "Dense"){ kernel = "epan"; }else{ kernel = "gauss"; } } kernNames = c("rect", "gauss", "epan", "gausvar", "quar"); if(!(kernel %in% kernNames)){ message(paste('kernel', kernel, 'is unrecognizable! Reset to automatic selection now!\n')); kernel = NULL; } if(is.null(kernel)){ if(dataType %in% c( "Dense", "DenseWithMV")){ kernel = "epan"; }else{ kernel = "gauss"; } } if(is.null(yname)){ yname = as.character(substitute(y)) } if(maxK > (nRegGrid-2)){ message(paste("maxK can only be less than or equal to", nRegGrid-2,"! Reset to be", nRegGrid-2, "now!\n")); maxK = nRegGrid -2; } if(is.numeric(methodSelectK)){ FVEthreshold <- 1 if(methodSelectK > (nRegGrid-2)){ message(paste("maxK can only be less than or equal to", nRegGrid-2,"! Reset to be", nRegGrid-2, "now!\n")); maxK = nRegGrid -2; }else if(methodSelectK <= 0){ message("methodSelectK must be a positive integer! Reset to BIC now!\n"); methodSelectK = "BIC" FVEthreshold = 0.95; } } if(is.null(plot)){ plot = FALSE; } if(is.null(methodRho)){ methodRho <- 'vanilla' } if(is.null(userRho)){ userRho = NULL } if(is.null(verbose)){ verbose = FALSE; } if(is.null(userMu)){ userMu <- NULL } if(is.null(userCov)){ userCov <- NULL } if(is.null(outPercent)){ outPercent <- c(0,1) } if(is.null(rotationCut)){ rotationCut <- c(0.25,.75) } if(!is.null(numBins)){ if(numBins < 10){ message("Number of bins must be at least +10!!\n"); numBins = NULL; } } if(is.null(useBinnedData)){ useBinnedData = 'AUTO'; } if (is.null(useBinnedCov)) { useBinnedCov <- TRUE if ( ( 128 > length(y) ) && ( 3 > mean ( unlist( lapply( y, length) ) ) )){ useBinnedCov <- FALSE } } if(is.null(usergrid)){ usergrid = FALSE; } if(is.null(lean)){ lean = FALSE; } if(is.null(useBW1SE)){ useBW1SE = FALSE; } if(is.null(imputeScores)){ imputeScores=TRUE; } retOptns <- list(userBwMu = userBwMu, methodBwMu = methodBwMu, userBwCov = userBwCov, methodBwCov = methodBwCov, kFoldMuCov = kFoldMuCov, methodSelectK = methodSelectK, FVEthreshold = FVEthreshold, FVEfittedCov = FVEfittedCov, fitEigenValues = fitEigenValues, maxK = maxK, dataType = dataType, error = error, shrink = shrink, nRegGrid = nRegGrid, rotationCut = rotationCut, methodXi = methodXi, kernel = kernel, lean = lean, diagnosticsPlot = diagnosticsPlot, plot=plot, numBins = numBins, useBinnedCov = useBinnedCov, usergrid = usergrid, yname = yname, methodRho = methodRho, verbose = verbose, userMu = userMu, userCov = userCov, methodMuCovEst = methodMuCovEst, userRho = userRho, userSigma2 = userSigma2, outPercent = outPercent, useBinnedData = useBinnedData, useBW1SE = useBW1SE, imputeScores = imputeScores) invalidNames <- !names(optns) %in% names(retOptns) if (any(invalidNames)) { stop(sprintf('Invalid option names: %s', paste0(names(optns)[invalidNames], collapse=', '))) } return( retOptns ) }
prepDocuments <- function(documents, vocab, meta=NULL, lower.thresh=1, upper.thresh=Inf, subsample=NULL, verbose=TRUE) { if((is.null(documents)|is.null(vocab))){ stop("One of your file inputs has no data") } if(!inherits(documents,"list")) { stop("documents must be a list in stm() format. See ?stm() for format. See ?readCorpus() for tools for converting from popular formats") } if(!is.null(subsample)) { index <- sample(1:length(documents), subsample) documents <- documents[index] if(!is.null(meta)) meta <- meta[index, , drop = FALSE] } len <- unlist(lapply(documents, length)) if(any(len==0)) { stop("Some documents have 0 length. Please check input. See ?prepDocuments() for more info.") } triplet <- doc.to.ijv(documents) nms <- names(documents) documents <- ijv.to.doc(triplet$i, triplet$j, triplet$v) names(documents) <- nms docs.removed <- c() miss.vocab <- NULL vocablist <- sort(unique(triplet$j)) wordcounts <- tabulate(triplet$j) if(length(vocablist)>length(vocab)) { stop("Your documents object has more unique features than your vocabulary file has entries.") } if(length(vocablist)<length(vocab)) { if(verbose) cat("Detected Missing Terms, renumbering \n") miss.vocab <- vocab[-vocablist] vocab <- vocab[vocablist] new.map <- cbind(vocablist, 1:length(vocablist)) documents <- lapply(documents, function(d) { nm <- names(d) d[1,] <- new.map[match(d[1,], new.map[,1]),2] names(d) <- nm return(d) }) wordcounts <- wordcounts[vocablist] } toremove <- which(wordcounts <= lower.thresh | wordcounts >= upper.thresh) keepers <- which(wordcounts > lower.thresh & wordcounts < upper.thresh) droppedwords <- c(miss.vocab,vocab[toremove]) if(length(toremove)) { if(verbose) cat(sprintf("Removing %i of %i terms (%i of %i tokens) due to frequency \n", length(toremove), length(wordcounts), sum(wordcounts[toremove]), sum(wordcounts))) vocab <- vocab[-toremove] remap <- 1:length(keepers) for(i in 1:length(documents)) { doc <- documents[[i]] dockeep <- doc[1,]%in%keepers doc <- doc[,dockeep,drop=FALSE] doc[1,] <- remap[match(doc[1,], keepers)] documents[[i]] <- doc if(ncol(doc)==0) docs.removed <- c(docs.removed,i) } if(length(docs.removed)) { if(verbose) cat(sprintf("Removing %i Documents with No Words \n", length(docs.removed))) documents <- documents[-docs.removed] } toprint <- sprintf("Your corpus now has %i documents, %i terms and %i tokens.", length(documents), length(vocab), sum(wordcounts[keepers])) if(verbose) cat(toprint) } if(!is.null(docs.removed) & !is.null(meta)){ meta<-meta[-docs.removed, , drop = FALSE] } documents <- lapply(documents, function(x) matrix(as.integer(x), nrow=2)) return(list(documents=documents, vocab=vocab, meta=meta, words.removed=droppedwords, docs.removed=docs.removed, tokens.removed=sum(wordcounts[toremove]), wordcounts=wordcounts)) }
tpaired.randtest <- function(vec1, vec2, nperm = 99, alternative = "two.sided", silent = FALSE) { n1 <- length(vec1) n2 <- length(vec2) if (n1 != n2) stop("The two vectors have different lengths. They cannot be paired.") alt <- match.arg(alternative, c("two.sided", "less", "greater")) res <- t.test(vec1, vec2, paired = TRUE, alternative = alt) t.ref <- res$statistic if (!silent) { cat('\nt-test comparing the means of two related samples','\n','\n') cat('Number of objects:',n1,'\n') cat('Mean of the differences:',res$estimate,'\n') cat('t statistic (paired observations):',t.ref,'\n') cat('95 percent confidence interval of t:',res$conf.int,'\n') cat('Degrees of freedom:',res$parameter,'\n') cat('Alternative hypothesis:',alt,'\n') cat('Prob (parametric):',res$p.value,'\n') } nPGE <- 1 for (i in 1:nperm) { mat <- cbind(vec1,vec2) topermute <- rbinom(n1,1,0.5) mat[topermute == 1,] <- mat[topermute == 1, 2:1] res.perm <- t.test(mat[,1], mat[,2], paired = TRUE, alternative = alt) t.perm <- res.perm$statistic if (alt == "two.sided") if (abs(t.perm) >= abs(t.ref) ) nPGE <- nPGE + 1 if (alt == "less") if (t.perm <= t.ref) nPGE <- nPGE + 1 if (alt == "greater") if (t.perm >= t.ref) nPGE <- nPGE + 1 } P <- nPGE / (nperm + 1) if (!silent) cat('Prob (',nperm,'permutations):', formatC(P, digits = 5, width = 7,format = "f"),'\n') return(list(estim = res$est[[1]], t.ref = t.ref, p.param = res$p.value, p.perm = P, nperm = nperm)) }
secondary_model_data <- function(model_name=NULL) { model_data <- list(CPM = list(identifier = "CPM", name = "Cardinal Parameter Model", pars = c("xmin", "xopt", "xmax", "n"), model = CPM_model, ref = paste("Rosso, L., Lobry, J. R., Bajard, S., and Flandrois, J. P. (1995).", "Convenient Model To Describe the Combined Effects of Temperature and pH on", "Microbial Growth. Applied and Environmental Microbiology, 61(2), 610-616.") ), Zwietering = list(identifier = "Zwietering", name = "Zwietering gamma function", pars = c("xmin", "xopt", "n"), model = zwietering_gamma, ref = paste("Zwietering, Marcel H., Wijtzes, T., De Wit, J. C., and Riet,", "K. V. (1992). A Decision Support System for Prediction of the Microbial", "Spoilage in Foods. Journal of Food Protection, 55(12), 973-979.", "https://doi.org/10.4315/0362-028X-55.12.973") ), fullRatkowsky = list(identifier = "fullRatkowsky", name = "(Adapted) Full Ratkowsky model", pars = c("xmin", "xmax", "c"), model = full_Ratkowski, ref = paste("Ratkowsky, D. A., Lowry, R. K., McMeekin, T. A.,", "Stokes, A. N., and Chandler, R. E. (1983). Model for", "bacterial culture growth rate throughout the entire", "biokinetic temperature range. Journal of Bacteriology,", "154(3), 1222-1226.") ) ) if (is.null(model_name)) { return(names(model_data)) } my_model <- model_data[[model_name]] if (is.null(my_model)) { stop(paste("Unknown model name:", model_name)) } else { my_model } } check_secondary_pars <- function(starting_point, known_pars, sec_model_names, primary_pars = "mu_opt") { if (any(names(starting_point) %in% names(known_pars))) { stop("Parameters cannot be defined as both fixed and to be fitted.") } par_names <- c(names(starting_point), names(known_pars)) missing_primary <- primary_pars[!primary_pars %in% par_names] if (length(missing_primary) > 0) { stop(paste("Parameter not defined:", missing_primary, "\n")) } my_regex <- paste(primary_pars, collapse="|") par_names <- par_names[!grepl(my_regex, par_names)] for (each_factor in names(sec_model_names)) { model_data <- secondary_model_data(sec_model_names[[each_factor]]) req_pars <- paste0(each_factor, "_", model_data$pars) missing_pars <- req_pars[!req_pars %in% par_names] if (length(missing_pars) > 0) { stop(paste("Parameter not defined:", missing_pars, "\n")) } this_pars <- par_names[grepl(paste0(each_factor, "_"), par_names)] unknown_pars <- this_pars[!this_pars %in% req_pars] if (length(unknown_pars) > 0) { stop(paste("Unknown parameter: ", unknown_pars, "\n")) } } my_regex <- paste(paste0(names(sec_model_names), "_"), collapse="|") wtpars <- par_names[!grepl(my_regex, par_names)] if (length(wtpars) > 0) { stop(paste("Unknown parameter: ", wtpars, "\n")) } }
knitr::opts_chunk$set(collapse = TRUE, comment = " library("mlrCPO") set.seed(123) base = knitr::opts_knit$get("output.dir") file = sys.frame(min(grep("^knitr::knit$|^knit$", sapply(sys.calls(), function(x) as.character(x)[1]))))$input file = basename(file) path = file.path(base, file) rpath = gsub("\\.[^.]*$", ".R", path) knitr::knit_hooks$set(document = function(x) { if (file_test("-f", rpath)) { lines = readLines(rpath) lines = gsub(" *(\n|$)", "\\1", lines) cat(lines, file = rpath, sep = "\n", append = FALSE) } x }) fullfile = file allfiles = list.files(path = base, pattern = ".*\\.Rmd$") stopifnot(file %in% allfiles) fileinfolist = list() for (cf in allfiles) { ismain = TRUE if (grepl("^z_", cf)) { infoslot = gsub("^z_", "", cf) infoslot = gsub("_terse\\.Rmd$", "", infoslot) subslot = "compact" } else { infoslot = gsub("^a_", "", cf) infoslot = gsub("\\.Rmd$", "", infoslot) subslot = "main" } content = scan(paste(base, cf, sep = "/"), what = "character", quiet = TRUE) pos = min(c(which(content == "title:"), Inf)) if (is.infinite(pos)) { stop(sprintf("parsing error: %s", cf)) } infolist = list(title = content[pos + 1], url = cf, iscurrent = cf == file) applist = list(infolist) names(applist) = subslot fileinfolist[[infoslot]] = c(fileinfolist[[infoslot]], applist) } linkify = function(info, title) { if (info$iscurrent) { title } else { sprintf("[%s](%s)", title, gsub("\\.Rmd$", ".html", info$url)) } } for (idx in seq_along(fileinfolist)) { content = fileinfolist[[sort(names(fileinfolist))[idx]]] if (!is.null(content$compact)) { if (paste(sub("[0-9]\\. ", "", content$main$title), "(No Output)") != sub("^z ", "", content$compact$title)) { stop(sprintf("File %s and its compact version %s have incompatible titles\nThe compact version must be paste(main_title, \"(No Output)\"). Is: '%s', expected: '%s'", content$main$url, content$compact$url, content$compact$title, paste(content$main$title, "(No Output)"))) } line = sprintf("%s (%s)", linkify(content$main, content$main$title), linkify(content$compact, "compact version")) } else { line = linkify(content$main, content$main$title) } cat(sprintf("%s. %s\n", idx, line)) if (content$main$iscurrent || content$compact$iscurrent) { fullfile = content$main$url } } fullpath = file.path(base, fullfile) printToc = function(print.level = 3) { owncontent = readLines(fullpath) tripletic = grepl("^```", owncontent) owncontent = owncontent[cumsum(tripletic) %% 2 == 0] headlines = grep("^ headlevels = nchar(gsub(" .*", "", headlines)) headlines = gsub("^[ links = gsub("[^-a-z. ]", "", tolower(headlines)) links = gsub(" +", "-", links) links = gsub("-$", "", links) if (!sum(headlevels <= print.level)) { return(invisible(NULL)) } cat("<h", headlevels[1], ">Table of Contents</h", headlevels[1], ">\n<div id=\"TOC\">\n", sep = "") lastlevel = headlevels[1] - 1 for (idx in seq_along(headlines)) { line = headlines[idx] level = headlevels[idx] link = links[idx] if (level > print.level) { next } if (level < headlevels[1]) { stop("First headline level must be the lowest one used, but '", line, "' is lower.") } lvldiff = level - lastlevel if (lvldiff > 1) { stop("Cannot jump headline levels. Error on: ", line) } if (lvldiff > 0) { cat("<ul>") } else { cat("</li>\n") } if (lvldiff < 0) { for (l in seq_len(-lvldiff)) { cat("</ul></li>") } } cat("<li><a href=\" lastlevel = level } lvldiff = lastlevel - headlevels[1] cat("</li></ul>\n</div>\n") } options(width = 80) replaceprint = function(ofunc) { force(ofunc) function(x, ...) { cu = capture.output({ret = ofunc(x, ...)}) cu = grep("time: [-+e0-9.]{1,6}", cu, value = TRUE, invert = TRUE) cat(paste(cu, collapse = "\n")) if (!grepl("\n$", tail(cu, 1))) { cat("\n") } ret } } for (pfunc in grep("print\\.", ls(asNamespace("mlr")), value = TRUE)) { ofunc = get(pfunc, asNamespace("mlr")) assign(pfunc, replaceprint(ofunc)) } printToc(4) cat(knitr::knit_child("a_1_getting_started.Rmd", options = list(eval = FALSE)), sep = "\n")
head.rstack <- function(x, n = 6L, ...) { newstack <- rstack() if(n < 0) { n = max(n, -1*length(x)) n = length(x) + n } if(n > length(x)) { n = length(x) } if(n == 0 | n < -1*length(x)) { return(newstack) } node <- x$head for(i in seq(1,n)) { if(!is.null(node)) { newstack <- insert_top(newstack, node$data) node <- node$nextnode } } return(rev(newstack)) }
expected <- eval(parse(text="FALSE")); test(id=0, code={ argv <- eval(parse(text="list(structure(list(weight = c(1.9, 3.1, 3.3, 4.8, 5.3, 6.1, 6.4, 7.6, 9.8, 12.4), depression = c(2, 1, 5, 5, 20, 20, 23, 10, 30, 25)), .Names = c(\"weight\", \"depression\"), row.names = c(NA, -10L), class = \"data.frame\"))")); do.call(`is.environment`, argv); }, o=expected);
library(checkargs) context("isIntegerOrNanOrInfVector") test_that("isIntegerOrNanOrInfVector works for all arguments", { expect_identical(isIntegerOrNanOrInfVector(NULL, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isIntegerOrNanOrInfVector(TRUE, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isIntegerOrNanOrInfVector(FALSE, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isIntegerOrNanOrInfVector(NA, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isIntegerOrNanOrInfVector(0, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isIntegerOrNanOrInfVector(-1, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isIntegerOrNanOrInfVector(-0.1, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isIntegerOrNanOrInfVector(0.1, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isIntegerOrNanOrInfVector(1, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isIntegerOrNanOrInfVector(NaN, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isIntegerOrNanOrInfVector(-Inf, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isIntegerOrNanOrInfVector(Inf, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isIntegerOrNanOrInfVector("", stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isIntegerOrNanOrInfVector("X", stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isIntegerOrNanOrInfVector(c(TRUE, FALSE), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isIntegerOrNanOrInfVector(c(FALSE, TRUE), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isIntegerOrNanOrInfVector(c(NA, NA), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isIntegerOrNanOrInfVector(c(0, 0), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isIntegerOrNanOrInfVector(c(-1, -2), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isIntegerOrNanOrInfVector(c(-0.1, -0.2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isIntegerOrNanOrInfVector(c(0.1, 0.2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isIntegerOrNanOrInfVector(c(1, 2), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isIntegerOrNanOrInfVector(c(NaN, NaN), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isIntegerOrNanOrInfVector(c(-Inf, -Inf), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isIntegerOrNanOrInfVector(c(Inf, Inf), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isIntegerOrNanOrInfVector(c("", "X"), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isIntegerOrNanOrInfVector(c("X", "Y"), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_error(isIntegerOrNanOrInfVector(NULL, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isIntegerOrNanOrInfVector(TRUE, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isIntegerOrNanOrInfVector(FALSE, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isIntegerOrNanOrInfVector(NA, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_identical(isIntegerOrNanOrInfVector(0, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isIntegerOrNanOrInfVector(-1, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_error(isIntegerOrNanOrInfVector(-0.1, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isIntegerOrNanOrInfVector(0.1, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_identical(isIntegerOrNanOrInfVector(1, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isIntegerOrNanOrInfVector(NaN, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isIntegerOrNanOrInfVector(-Inf, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isIntegerOrNanOrInfVector(Inf, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_error(isIntegerOrNanOrInfVector("", stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isIntegerOrNanOrInfVector("X", stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isIntegerOrNanOrInfVector(c(TRUE, FALSE), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isIntegerOrNanOrInfVector(c(FALSE, TRUE), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isIntegerOrNanOrInfVector(c(NA, NA), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_identical(isIntegerOrNanOrInfVector(c(0, 0), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isIntegerOrNanOrInfVector(c(-1, -2), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_error(isIntegerOrNanOrInfVector(c(-0.1, -0.2), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isIntegerOrNanOrInfVector(c(0.1, 0.2), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_identical(isIntegerOrNanOrInfVector(c(1, 2), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isIntegerOrNanOrInfVector(c(NaN, NaN), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isIntegerOrNanOrInfVector(c(-Inf, -Inf), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isIntegerOrNanOrInfVector(c(Inf, Inf), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_error(isIntegerOrNanOrInfVector(c("", "X"), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isIntegerOrNanOrInfVector(c("X", "Y"), stopIfNot = TRUE, message = NULL, argumentName = NULL)) })
lesionBurden.M <- matrix(c(20, 26.8, 9.6, 21.2, 26.5, 10.5, 20.8, 22.5, 10.6, 20.6, 23.1, 9.2, 20.2, 24.3, 10.4, 19.1, 24.1, 10.4, 21, 26, 10.1, 20.4, 26.8, 8, 19.2, 24.9, 10.1, 19.2, 27.7, 8.9), nrow=3) lesionBurden.G <- matrix(c(19.5, 22.1, 8.5, 19.5, 21.9, 8.5, 19.6, 22, 8.3, 19.7, 22.1, 8.3, 19.3, 21.9, 8.3, 19.1, 21.8, 8, 19.1, 21.7, 8, 19.3, 21.7, 8, 19.2, 21.7, 8, 19.5, 21.8, 8.1), nrow=3) lesionBurden <- array(0, dim=c(3, 10, 2)) lesionBurden[,,1] <- lesionBurden.M lesionBurden[,,2] <- lesionBurden.G dimnames(lesionBurden)[[3]] <- c("lesionBurden.M", "lesionBurden.G")
metacr <- function(x, comp.no = 1, outcome.no = 1, method, sm, level = gs("level"), level.ma = gs("level.ma"), fixed, random, hakn = FALSE, method.tau = "DL", method.tau.ci = gs("method.tau.ci"), tau.common = FALSE, prediction = gs("prediction"), level.predict = gs("level.predict"), swap.events, logscale, backtransf = gs("backtransf"), test.subgroup, text.fixed = gs("text.fixed"), text.random = gs("text.random"), text.predict = gs("text.predict"), text.w.fixed = gs("text.w.fixed"), text.w.random = gs("text.w.random"), title, complab, outclab, keepdata = gs("keepdata"), warn = FALSE, ...) { chkclass(x, "rm5") if (is.numeric(comp.no)) chknumeric(comp.no, length = 1) else chkchar(comp.no, length = 1) if (is.numeric(outcome.no)) chknumeric(outcome.no, length = 1) else chkchar(outcome.no, length = 1) chklevel(level) chklevel(level.ma) chklogical(hakn) method.tau <- setchar(method.tau, gs("meth4tau")) if (is.null(method.tau.ci)) method.tau.ci <- if (method.tau == "DL") "J" else "QP" method.tau.ci <- setchar(method.tau.ci, gs("meth4tau.ci")) chklogical(tau.common) chklogical(prediction) chklevel(level.predict) if (!missing(swap.events)) chklogical(swap.events) chklogical(backtransf) if (!is.null(text.fixed)) chkchar(text.fixed, length = 1) if (!is.null(text.random)) chkchar(text.random, length = 1) if (!is.null(text.predict)) chkchar(text.predict, length = 1) if (!is.null(text.w.fixed)) chkchar(text.w.fixed, length = 1) if (!is.null(text.w.random)) chkchar(text.w.random, length = 1) chklogical(keepdata) sel <- x$comp.no == comp.no & x$outcome.no == outcome.no if (sum(sel) == 0) { warning("No data available for comp.no = ", comp.no, " and outcome.no = ", outcome.no, ".") return(NULL) } x$sel <- sel if (missing(title)) title <- attributes(x)$title if (missing(complab)) complab <- unique(x$complab[sel]) if (missing(outclab)) outclab <- unique(x$outclab[sel]) label.e <- unique(x$label.e[sel]) label.c <- unique(x$label.c[sel]) label.left <- unique(x$label.left[sel]) label.right <- unique(x$label.right[sel]) overall <- replaceNULL(unique(x$overall[sel]), TRUE) if (is.na(overall)) overall <- TRUE type <- unique(x$type[sel]) if (missing(test.subgroup)) test.subgroup <- unique(x$test.subgroup[sel]) if (missing(method)) method <- unique(x$method[sel]) else method <- setchar(method, c("Inverse", "MH", "Peto")) chkchar(method, length = 1) if (missing(sm)) sm <- unique(x$sm[sel]) chkchar(sm, length = 1) if (sm == "PETO_OR") sm <- "OR" if (missing(fixed)) fixed <- unique(x$fixed[sel]) if (missing(random)) random <- unique(x$random[sel]) if (tau.common & method == "Peto") { if (warn) warning("Argument 'tau.common' not considered for Peto method.") tau.common <- FALSE } if (tau.common & method == "MH") { if (warn) warning("Argument 'tau.common' not considered for Mantel-Haenszel method.") tau.common <- FALSE } if (!all(is.na(x$logscale[sel]))) { if (!unique(x$logscale[sel])) { x$TE[sel] <- log(x$TE[sel]) logscale <- FALSE } else logscale <- TRUE } else { if (!missing(logscale)) { if (!logscale) x$TE[sel] <- log(x$TE[sel]) } else { if ((type == "I" & method != "Peto") & is.relative.effect(sm)) { warning("Assuming that values for 'TE' are on log scale. ", "Please use argument 'logscale = FALSE' if ", "values are on natural scale.", call. = FALSE) logscale <- TRUE } else logscale <- NA } } O.E <- TE <- V <- event.c <- event.e <- grplab <- mean.c <- mean.e <- n.c <- n.e <- sd.c <- sd.e <- seTE <- studlab <- NULL dropnames <- c("comp.no", "outcome.no", "group.no", "overall", "test.subgroup", "type", "method", "sm", "model", "fixed", "random", "outclab", "k", "event.e.pooled", "n.e.pooled", "event.c.pooled", "n.c.pooled", "TE.pooled", "lower.pooled", "upper.pooled", "weight.pooled", "Z.pooled", "pval.TE.pooled", "Q", "pval.Q", "I2", "tau2", "Q.w", "pval.Q.w", "I2.w", "swap.events", "enter.n", "logscale", "label.e", "label.c", "label.left", "label.right", "complab", "sel") varnames <- names(x)[!(names(x) %in% dropnames)] Q.Cochrane <- if (method == "MH" & method.tau == "DL") TRUE else FALSE if (length(unique(x$group.no[sel])) > 1) { if (type == "D") { if (missing(swap.events)) { swap.events <- unique(x$swap.events[sel]) swap.events <- !is.na(swap.events) && swap.events } if (swap.events) m1 <- metabin(n.e - event.e, n.e, n.c - event.c, n.c, sm = sm, method = method, studlab = studlab, data = x[sel, varnames], fixed = fixed, random = random, hakn = hakn, method.tau = method.tau, method.tau.ci = method.tau.ci, tau.common = tau.common, level = level, level.ma = level.ma, prediction = prediction, level.predict = level.predict, overall = overall, subgroup = grplab, subgroup.name = "grp", print.subgroup.name = FALSE, test.subgroup = test.subgroup, backtransf = backtransf, text.fixed = text.fixed, text.random = text.random, text.predict = text.predict, text.w.fixed = text.w.fixed, text.w.random = text.w.random, title = title, complab = complab, outclab = outclab, label.e = label.e, label.c = label.c, label.left = label.left, label.right = label.right, RR.Cochrane = TRUE, Q.Cochrane = Q.Cochrane, warn = warn, keepdata = keepdata) else m1 <- metabin(event.e, n.e, event.c, n.c, sm = sm, method = method, studlab = studlab, data = x[sel, varnames], fixed = fixed, random = random, hakn = hakn, method.tau = method.tau, method.tau.ci = method.tau.ci, tau.common = tau.common, level = level, level.ma = level.ma, prediction = prediction, level.predict = level.predict, overall = overall, subgroup = grplab, subgroup.name = "grp", print.subgroup.name = FALSE, test.subgroup = test.subgroup, backtransf = backtransf, text.fixed = text.fixed, text.random = text.random, text.predict = text.predict, text.w.fixed = text.w.fixed, text.w.random = text.w.random, title = title, complab = complab, outclab = outclab, label.e = label.e, label.c = label.c, label.left = label.left, label.right = label.right, RR.Cochrane = TRUE, Q.Cochrane = Q.Cochrane, warn = warn, keepdata = keepdata) } if (type == "C") m1 <- metacont(n.e, mean.e, sd.e, n.c, mean.c, sd.c, sm = sm, studlab = studlab, data = x[sel, varnames], fixed = fixed, random = random, hakn = hakn, method.tau = method.tau, method.tau.ci = method.tau.ci, tau.common = tau.common, level = level, level.ma = level.ma, prediction = prediction, level.predict = level.predict, overall = overall, subgroup = grplab, subgroup.name = "grp", print.subgroup.name = FALSE, test.subgroup = test.subgroup, text.fixed = text.fixed, text.random = text.random, text.predict = text.predict, text.w.fixed = text.w.fixed, text.w.random = text.w.random, title = title, complab = complab, outclab = outclab, label.e = label.e, label.c = label.c, label.left = label.left, label.right = label.right, keepdata = keepdata) if (type == "P") m1 <- metagen(O.E / V, sqrt(1 / V), sm = sm, studlab = studlab, data = x[sel, varnames], fixed = fixed, random = random, hakn = hakn, method.tau = method.tau, method.tau.ci = method.tau.ci, tau.common = tau.common, level = level, level.ma = level.ma, prediction = prediction, level.predict = level.predict, overall = overall, subgroup = grplab, subgroup.name = "grp", print.subgroup.name = FALSE, test.subgroup = test.subgroup, backtransf = backtransf, text.fixed = text.fixed, text.random = text.random, text.predict = text.predict, text.w.fixed = text.w.fixed, text.w.random = text.w.random, title = title, complab = complab, outclab = outclab, label.e = label.e, label.c = label.c, label.left = label.left, label.right = label.right, keepdata = keepdata) if (type == "I" & method != "Peto") m1 <- metagen(TE, seTE, sm = sm, studlab = studlab, data = x[sel, varnames], fixed = fixed, random = random, hakn = hakn, method.tau = method.tau, method.tau.ci = method.tau.ci, tau.common = tau.common, level = level, level.ma = level.ma, prediction = prediction, level.predict = level.predict, overall = overall, subgroup = grplab, subgroup.name = "grp", print.subgroup.name = FALSE, test.subgroup = test.subgroup, n.e = n.e, n.c = n.c, backtransf = backtransf, text.fixed = text.fixed, text.random = text.random, text.predict = text.predict, text.w.fixed = text.w.fixed, text.w.random = text.w.random, title = title, complab = complab, outclab = outclab, label.e = label.e, label.c = label.c, label.left = label.left, label.right = label.right, keepdata = keepdata) if (type == "I" & method == "Peto") m1 <- metagen(O.E / V, sqrt(1 / V), sm = sm, studlab = studlab, data = x[sel, varnames], fixed = fixed, random = random, hakn = hakn, method.tau = method.tau, method.tau.ci = method.tau.ci, tau.common = tau.common, level = level, level.ma = level.ma, prediction = prediction, level.predict = level.predict, overall = overall, subgroup = grplab, subgroup.name = "grp", print.subgroup.name = FALSE, test.subgroup = test.subgroup, backtransf = backtransf, text.fixed = text.fixed, text.random = text.random, text.predict = text.predict, text.w.fixed = text.w.fixed, text.w.random = text.w.random, title = title, complab = complab, outclab = outclab, label.e = label.e, label.c = label.c, label.left = label.left, label.right = label.right, keepdata = keepdata) } else { if (type == "D") { if (missing(swap.events)) { swap.events <- unique(x$swap.events[sel]) swap.events <- !is.na(swap.events) && swap.events } if (swap.events) m1 <- metabin(n.e - event.e, n.e, n.c - event.c, n.c, sm = sm, method = method, studlab = studlab, data = x[sel, varnames], fixed = fixed, random = random, hakn = hakn, method.tau = method.tau, method.tau.ci = method.tau.ci, tau.common = tau.common, level = level, level.ma = level.ma, prediction = prediction, level.predict = level.predict, overall = overall, backtransf = backtransf, text.fixed = text.fixed, text.random = text.random, text.predict = text.predict, text.w.fixed = text.w.fixed, text.w.random = text.w.random, title = title, complab = complab, outclab = outclab, label.e = label.e, label.c = label.c, label.left = label.left, label.right = label.right, RR.Cochrane = TRUE, Q.Cochrane = Q.Cochrane, warn = warn, keepdata = keepdata) else m1 <- metabin(event.e, n.e, event.c, n.c, sm = sm, method = method, studlab = studlab, data = x[sel, varnames], fixed = fixed, random = random, hakn = hakn, method.tau = method.tau, method.tau.ci = method.tau.ci, tau.common = tau.common, level = level, level.ma = level.ma, prediction = prediction, level.predict = level.predict, overall = overall, backtransf = backtransf, text.fixed = text.fixed, text.random = text.random, text.predict = text.predict, text.w.fixed = text.w.fixed, text.w.random = text.w.random, title = title, complab = complab, outclab = outclab, label.e = label.e, label.c = label.c, label.left = label.left, label.right = label.right, RR.Cochrane = TRUE, Q.Cochrane = Q.Cochrane, warn = warn, keepdata = keepdata) } if (type == "C") m1 <- metacont(n.e, mean.e, sd.e, n.c, mean.c, sd.c, sm = sm, studlab = studlab, data = x[sel, varnames], fixed = fixed, random = random, hakn = hakn, method.tau = method.tau, method.tau.ci = method.tau.ci, tau.common = tau.common, level = level, level.ma = level.ma, prediction = prediction, level.predict = level.predict, overall = overall, text.fixed = text.fixed, text.random = text.random, text.predict = text.predict, text.w.fixed = text.w.fixed, text.w.random = text.w.random, title = title, complab = complab, outclab = outclab, label.e = label.e, label.c = label.c, label.left = label.left, label.right = label.right, keepdata = keepdata) if (type == "P") m1 <- metagen(O.E / V, sqrt(1 / V), sm = sm, studlab = studlab, data = x[sel, varnames], fixed = fixed, random = random, hakn = hakn, method.tau = method.tau, method.tau.ci = method.tau.ci, tau.common = tau.common, level = level, level.ma = level.ma, prediction = prediction, level.predict = level.predict, overall = overall, backtransf = backtransf, text.fixed = text.fixed, text.random = text.random, text.predict = text.predict, text.w.fixed = text.w.fixed, text.w.random = text.w.random, title = title, complab = complab, outclab = outclab, label.e = label.e, label.c = label.c, label.left = label.left, label.right = label.right, keepdata = keepdata) if (type == "I" & method != "Peto") m1 <- metagen(TE, seTE, sm = sm, studlab = studlab, data = x[sel, varnames], fixed = fixed, random = random, hakn = hakn, method.tau = method.tau, method.tau.ci = method.tau.ci, tau.common = tau.common, level = level, level.ma = level.ma, prediction = prediction, level.predict = level.predict, overall = overall, n.e = n.e, n.c = n.c, backtransf = backtransf, text.fixed = text.fixed, text.random = text.random, text.predict = text.predict, text.w.fixed = text.w.fixed, text.w.random = text.w.random, title = title, complab = complab, outclab = outclab, label.e = label.e, label.c = label.c, label.left = label.left, label.right = label.right, keepdata = keepdata) if (type == "I" & method == "Peto") m1 <- metagen(O.E / V, sqrt(1 / V), sm = sm, studlab = studlab, data = x[sel, varnames], fixed = fixed, random = random, hakn = hakn, method.tau = method.tau, method.tau.ci = method.tau.ci, tau.common = tau.common, level = level, level.ma = level.ma, prediction = prediction, level.predict = level.predict, overall = overall, backtransf = backtransf, text.fixed = text.fixed, text.random = text.random, text.predict = text.predict, text.w.fixed = text.w.fixed, text.w.random = text.w.random, title = title, complab = complab, outclab = outclab, label.e = label.e, label.c = label.c, label.left = label.left, label.right = label.right, keepdata = keepdata) } if (sm == "OTHER") { warning('Meta-analysis not possible for sm = "OTHER".') return(NULL) } res <- m1 attr(res, "comp.no") <- comp.no attr(res, "outcome.no") <- outcome.no attr(res, "type") <- type if (type == "D") attr(res, "swap.events") <- swap.events attr(res, "logscale") <- logscale if (!is.null(x$enter.n)) attr(res, "enter.n") <- x$enter.n res }
germinationcount.test <- function(r, nsamples, n, N, K) { p.val <- 1 - pRangeHyper(r, nsamples, N, K, n) offrange <- r germrate <- K/N out <- list(R.value = offrange, p.value = p.val, germination.rate = germrate) class(out) <- "germinationcount.test" return(out) } print.germinationcount.test <- function(x, digits = 4, ...) { cat("\n Germination count range test for seed sample heterogeneity", "\n\nGermination rate of the seed lot:", 100*x$germination.rate, "%", "\nR-value (count difference):", x$R.value, "seeds", "\np-value: ", x$p.value) cat("\nNull hypothesis: germination homogeneity", "\n") invisible(x) } dRangeHyper <- function(r, size, N, K, n) { sapply(r, function(r) { if(r < 0) { prob <- 0 } else if(r == 0) { prob <- sum(dhyper(0:n, K, N-K, n)^size) } else { prob <- 0 for(x in 0:n) { prob <- prob + (phyper(x+r, K, N-K, n) - phyper(x-1, K, N-K, n))^size - (phyper(x+r, K, N-K, n) - phyper(x, K, N-K, n))^size - (phyper(x+r-1, K, N-K, n) - phyper(x-1, K, N-K, n))^size + (phyper(x+r-1, K, N-K, n) - phyper(x, K, N-K, n))^size } } return(prob) }) } pRangeHyper <- function(r, size, N, K, n) { sapply(r, function(r) { sum(dRangeHyper(0:r, size, N, K, n)) }) }
simCR <- function(n, bhr, beta.x.12, beta.x.13, beta.x.14){ bhr.11 <- function(t){return(0)}; eta.1.1 <- function(x.i, t){return(0*sum(x.i))} bhr.12 <- function(t){return(bhr)} bhr.13 <- function(t){return(bhr)} bhr.21 <- function(t){return(0)}; eta.2.1 <- function(x.i, t){return(0*sum(x.i))} bhr.22 <- function(t){return(0)}; eta.2.2 <- function(x.i, t){return(0*sum(x.i))} bhr.23 <- function(t){return(0)}; eta.2.3 <- function(x.i, t){return(0*sum(x.i))} bhr.31 <- function(t){return(0)}; eta.3.1 <- function(x.i, t){return(0*sum(x.i))} bhr.32 <- function(t){return(0)}; eta.3.2 <- function(x.i, t){return(0*sum(x.i))} bhr.33 <- function(t){return(0)}; eta.3.3 <- function(x.i, t){return(0*sum(x.i))} eta.1.2 <- function(x.i, t){ eta <- beta.x.12 * x.i return(eta)} eta.1.3 <- function(x.i, t){ eta <- beta.x.13 * x.i return(eta)} bhr.14 <- function(t){return(bhr)} bhr.24 <- function(t){return(0)}; eta.2.4 <- function(x.i, t){return(0*sum(x.i))} bhr.34 <- function(t){return(0)}; eta.3.4 <- function(x.i, t){return(0*sum(x.i))} bhr.41 <- function(t){return(0)}; eta.4.1 <- function(x.i, t){return(0*sum(x.i))} bhr.42 <- function(t){return(0)}; eta.4.2 <- function(x.i, t){return(0*sum(x.i))} bhr.43 <- function(t){return(0)}; eta.4.3 <- function(x.i, t){return(0*sum(x.i))} bhr.44 <- function(t){return(0)}; eta.4.4 <- function(x.i, t){return(0*sum(x.i))} eta.1.4 <- function(x.i, t){ eta <- beta.x.14 * x.i return(eta) } mpl <- list(from.1 = list(from = 1, all.to = c(2, 3, 4), all.bhr = list(bhr.11, bhr.12, bhr.13, bhr.14), eta = list(to.1 = eta.1.1, to.2 = eta.1.2, to.3 = eta.1.3, to.4 = eta.1.4)), from.2 = list(from = 2, all.to = NULL, all.bhr = list(bhr.21, bhr.22, bhr.23, bhr.24), eta = list(to.1 = eta.2.1, to.2 = eta.2.2, to.3 = eta.2.3, to.4 = eta.2.4)), from.3 = list(from = 3, all.to = NULL, all.bhr = list(bhr.31, bhr.32, bhr.33, bhr.34), eta = list(to.1 = eta.3.1, to.2 = eta.3.2, to.3 = eta.3.3, to.4 = eta.3.4)), from.4 = list(from = 4, all.to = NULL, all.bhr = list(bhr.41, bhr.42, bhr.43, bhr.44), eta = list(to.1 = eta.3.1, to.2 = eta.3.2, to.3 = eta.3.3, to.4 = eta.4.4))) x <- rnorm(n) + 1 X <- matrix(ncol = 1, nrow = n, data = x) colnames(X) <- c("x") max.time = 100 all.first.from <- rep(1, times=n) p <- ncol(X) histories <- NULL for (i in 1:n) { history.i <- simsinglehistory(first.entry = 0, first.from = all.first.from[i], max.time, mpl, x.i = X[i, ]) if (!is.null(nrow(history.i))) { history.i <- cbind(history.i, rep(i, 1)) for (x.index in 1:p) { history.i <- cbind(history.i, rep(X[i, x.index], 1)) } } else { history.i <- cbind(history.i, rep(i, nrow(history.i))) for (x.index in 1:p) { history.i <- cbind(history.i, rep(X[i, x.index], nrow(history.i))) } } histories <- rbind(histories, history.i) rm(history.i) } histories.as.list <- list(id = histories[, 5], entry = histories[, 1], exit = histories[, 2], from = histories[, 3], to = histories[, 4]) for (x.index in 1:p) { histories.as.list[[5 + x.index]] <- histories[, 5 + x.index] names(histories.as.list)[5 + x.index] <- colnames(X)[x.index] } histories <- data.frame(histories.as.list) rm(histories.as.list) for(i in 1:nrow(histories)){ cens <- sample(c(TRUE, FALSE), size = 1, prob = c(0.15, 0.85)) if(cens){histories$to[i] <- "cens"} } IDs <- unique(histories$id) for(i in IDs){ hi <- which(histories$id == i) ho <- histories[hi, ]$to == "cens" if(any(ho)){ if(min(hi[ho]) < max(hi)){ histories <- histories[-hi[which(hi > min(hi[ho]))], ] } } } histories$event <- as.numeric(histories$to != "cens") all.to.list <- list(from.1 = mpl$from.1$all.to, from.2 = mpl$from.2$all.to, from.3 = mpl$from.3$all.to, from.4 = mpl$from.4$all.to) d <- histories[1, ] for(i in 1:nrow(histories)){ all.to <- all.to.list[[as.numeric(histories$from[i])]] add <- rbind(histories[i, ], histories[i, ], histories[i, ], histories[i, ]) add <- add[1:length(all.to), ] reminder.to <- histories[i, "to"] reminder.event <- histories[i, "event"] add[, "to"] <- all.to add[, "event"] <- 0 if(reminder.event > 0.5){ add[which(all.to == as.numeric(reminder.to)), "event"] <- 1 } d <- rbind(d, add) } d <- d[-1, ] d$trans <- paste(d$from, d$to, sep="") d <- d[, c("id", "entry", "exit", "from", "to", "trans", "event", "x")] hi <- which(d$trans == 12) x.12.mean <- mean(d[hi, "x"]) ho <- d[, "x"] - x.12.mean ho[which(!(d$trans == 12))] <- 0 d$x.12 <- ho hi <- which(d$trans == 13) x.13.mean <- mean(d[hi, "x"]) ho <- d[, "x"] - x.13.mean ho[which(!(d$trans == 13))] <- 0 d$x.13 <- ho hi <- which(d$trans %in% c(12, 13)) x.12.13.mean <- mean(d[hi, "x"]) ho <- d[, "x"] - x.12.13.mean ho[which(!(d$trans %in% c(12, 13)))] <- 0 d$x.12.13 <- ho hi <- which(d$trans == 14) x.14.mean <- mean(d[hi, "x"]) ho <- d[, "x"] - x.14.mean ho[which(!(d$trans == 14))] <- 0 d$x.14 <- ho hi <- which(d$trans %in% c(12, 14)) x.12.14.mean <- mean(d[hi, "x"]) ho <- d[, "x"] - x.12.14.mean ho[which(!(d$trans %in% c(12, 14)))] <- 0 d$x.12.14 <- ho hi <- which(d$trans %in% c(13, 14)) x.13.14.mean <- mean(d[hi, "x"]) ho <- d[, "x"] - x.13.14.mean ho[which(!(d$trans %in% c(13, 14)))] <- 0 d$x.13.14 <- ho x.mean <- mean(d$x) d$x <- d$x - x.mean attributes(d)$x.means <- c(x.12.mean, x.13.mean, x.14.mean, x.12.13.mean, x.12.14.mean, x.13.14.mean, x.mean) return(d)}
airnow_loadAnnual <- function(year = NULL, parameter = 'PM2.5', baseUrl = 'https://haze.airfire.org/monitoring', dataDir = NULL) { if ( is.null(year) ) { stop("Required parameter 'year' is missing.") } year <- as.numeric(year) validParams <- c("PM2.5") if ( !parameter %in% validParams ) { paramsString <- paste(validParams, collapse=", ") stop(paste0("'", parameter, "' is not a supported parameter. Use 'parameter = ", paramsString, "'"), call.=FALSE) } if ( year < 2016 ) { stop("PWFSL has no annual data files for AirNow prior to 2016.") } baseUrl <- paste0(baseUrl, '/AirNow/RData/', year) filename <- paste0("airnow_", parameter, "_", year, ".RData") ws_monitor <- MazamaCoreUtils::loadDataFile(filename, baseUrl, dataDir) return(ws_monitor) }
get_dashboard_dependencies <- function() { list( htmlDependency( "semantic.dashboard", as.character(utils::packageVersion("semantic.dashboard")), c(file = system.file(package = "semantic.dashboard")), script = "semantic.dashboard.min.js", stylesheet = "semantic.dashboard.min.css" ) ) }
foldp <- function(p,eps){ (p+eps)/(1-p+eps) }
tar_test("database$append_lines() loops when it cannot append to the file", { path <- file.path(tempfile(), "x", "y") database <- database_init(path = path) expect_error( expect_warning(database$append_lines("line", max_attempts = 10)) ) }) tar_test("test on Windows: pipeline keeps going tar_script( list( tar_target(n_random, rep(1, 200)), tar_target(random, Sys.sleep(0.01), pattern = map(n_random)) ) ) px <- tar_make( callr_function = callr::r_bg, callr_arguments = list( stdout = "out.txt", stderr = "err.txt" ) ) tar_poll() expect_equal(tar_outdated(), character(0)) expect_equal(tar_progress_branches()$branches, 200L) expect_equal(tar_progress_branches()$built, 200L) writeLines(readLines("err.txt")) })
XbetaAndResidu=function( method, data, testCovInd, nRef, paraJobs, refTaxa, sequentialRun, standardize, allFunc, Mprefix, covsPrefix, binPredInd, seed){ results=list() dataForEst1=dataRecovTrans(data=data,ref=refTaxa[1],Mprefix=Mprefix, covsPrefix=covsPrefix) results$xTildLong=dataForEst1$xTildalong rm(dataForEst1) basicInfo=dataInfo(data=data,Mprefix=Mprefix, covsPrefix=covsPrefix, binPredInd=binPredInd) predNames=basicInfo$predNames testCovNam=predNames[testCovInd] colnames(data)%in%testCovNam reducedData=data[,!(colnames(data)%in%testCovNam)] rm(basicInfo) reducedBasicInfo=dataInfo(data=reducedData,Mprefix=Mprefix, covsPrefix=covsPrefix, binPredInd=binPredInd) taxaNames=reducedBasicInfo$taxaNames nTaxa=reducedBasicInfo$nTaxa nPredics=reducedBasicInfo$nPredics rm(reducedBasicInfo) gc() nNorm=nTaxa-1 nAlphaNoInt=nPredics*nNorm nAlphaSelec=nPredics*nTaxa countOfSelec=rep(0,nAlphaSelec) resultsByRefTaxon=list() nRef=length(refTaxa) startT=proc.time()[3] message("start generating residues for permutation") if(length(paraJobs)==0){ availCores=availableCores() if(is.numeric(availCores))paraJobs=max(1,availableCores()-2) if(!is.numeric(availCores))paraJobs=1 } if(!sequentialRun){ message(paraJobs, "parallel jobs are registered for generate residues in Phase 1a.") } batch=paraJobs forLoopN=ceiling(nRef/batch) for(jj in 1:forLoopN){ cl<-parallel::makeCluster(paraJobs) parallel::clusterExport(cl=cl, varlist=allFunc,envir=parent.env(environment())) doParallel::registerDoParallel(cl) if(length(seed)>0){ set.seed(as.numeric(seed)+jj+10^8) parallel::clusterSetRNGStream(cl=cl,(as.numeric(seed)+jj+10^9)) } if(sequentialRun){foreach::registerDoSEQ()} startT1=proc.time()[3] if(forLoopN>1 & jj<forLoopN){ residu1Resu.j=foreach(i=((jj-1)*batch+1):(jj*batch),.multicombine=T, .packages=c("picasso","Matrix"), .errorhandling="pass") %dopar% { ii=which(taxaNames==refTaxa[i]) dataForEst=dataRecovTrans(data=reducedData,ref=refTaxa[i],Mprefix=Mprefix, covsPrefix=covsPrefix) xTildLongTild.i=dataForEst$xTildalong yTildLongTild.i=dataForEst$UtildaLong rm(dataForEst) gc() if(method=="mcp") { Penal.i=runPicasso(x=xTildLongTild.i,y=yTildLongTild.i, nPredics=nPredics, method="mcp",permutY=FALSE, standardize=standardize, seed=seed,seedi=i) } betaInt=Penal.i$betaInt overalIntercp=Penal.i$overalIntercp rm(Penal.i) gc() xBeta=xTildLongTild.i%*%betaInt+overalIntercp rm(xTildLongTild.i) residu=yTildLongTild.i-xBeta rm(yTildLongTild.i) recturnlist=list() recturnlist[[1]]=xBeta recturnlist[[2]]=residu return(recturnlist) } parallel::stopCluster(cl) rm(data) gc() if(jj==1)residu1Resu=residu1Resu.j if(jj>1)residu1Resu=do.call(c,list(residu1Resu,residu1Resu.j)) } if(jj==forLoopN){ residu1Resu.j=foreach(i=((jj-1)*batch+1):nRef,.multicombine=T, .packages=c("picasso","Matrix"), .errorhandling="pass") %dopar% { ii=which(taxaNames==refTaxa[i]) dataForEst=dataRecovTrans(data=reducedData,ref=refTaxa[i],Mprefix=Mprefix, covsPrefix=covsPrefix) xTildLongTild.i=dataForEst$xTildalong yTildLongTild.i=dataForEst$UtildaLong rm(dataForEst) gc() if(method=="mcp") { Penal.i=runPicasso(x=xTildLongTild.i,y=yTildLongTild.i, nPredics=nPredics, method="mcp",permutY=FALSE, standardize=standardize, seed=seed,seedi=i) } betaInt=Penal.i$betaInt overalIntercp=Penal.i$overalIntercp rm(Penal.i) gc() xBeta=xTildLongTild.i%*%betaInt+overalIntercp rm(xTildLongTild.i) residu=yTildLongTild.i-xBeta rm(yTildLongTild.i) recturnlist=list() recturnlist[[1]]=xBeta recturnlist[[2]]=residu return(recturnlist) } parallel::stopCluster(cl) rm(data) gc() if(forLoopN==1)residu1Resu=residu1Resu.j if(forLoopN>1)residu1Resu=do.call(c,list(residu1Resu,residu1Resu.j)) } } endT=proc.time()[3] message("Generating residu is done and took ",round((endT-startT1)/60,3),"minutes") xBetaList=list() for(i in 1:nRef){ xBetaList[[i]]=residu1Resu[[i]][[1]] } residuList=list() for(i in 1:nRef){ residuList[[i]]=residu1Resu[[i]][[2]] } rm(residu1Resu) results$xBetaList=xBetaList rm(xBetaList) results$residuList=residuList rm(residuList) return(results) }
api_versions = function(url) { tryCatch({ if (endsWith(url, "/")) url = substr(url, 1, nchar(url) - 1) endpoint = "/.well-known/openeo" info = GET(url = paste0(url, endpoint),config=content_type_json()) if (info$status == 200) { vlist = content(info) if (is.raw(vlist)) { vlist=jsonlite::fromJSON(rawToChar(vlist),simplifyDataFrame = FALSE) } class(vlist) = "VersionsList" if (isNamespaceLoaded("tibble")) { return(tibble::as_tibble(vlist)) } return(as.data.frame(vlist)) } else { stop("Host is not reachable. Please check the URL.") } }, error = .capturedErrorToMessage) } capabilities = function(con=NULL) { tryCatch({ con = .assure_connection(con) con$stopIfNotConnected() return(con$getCapabilities()) }, error = function(e) { warning(e$message) return(invisible(e$message)) }) } list_features = function(con=NULL) { tryCatch({ con = .assure_connection(con) return(con$api.mapping[c("endpoint", "operation", "available")]) }, error = .capturedErrorToMessage) } list_file_formats = function(con=NULL) { tryCatch({ tag = "formats" con = .assure_connection(con) formats = con$request(tag = tag, authorized = con$isLoggedIn()) class(formats) = "FileFormatList" if (length(formats$input) > 0) { input_formats = names(formats$input) modified_input_formats = lapply(input_formats, function(format_name) { f = formats$input[[format_name]] f$name = format_name class(f) = "FileFormat" return(f) }) names(modified_input_formats) = input_formats } if (length(formats$output) > 0) { output_formats = names(formats$output) modified_output_formats = lapply(output_formats, function(format_name) { f = formats$output[[format_name]] f$name = format_name class(f) = "FileFormat" return(f) }) names(modified_output_formats) = output_formats formats$output = modified_output_formats } return(formats) }, error = .capturedErrorToMessage) } list_service_types = function(con=NULL) { tryCatch({ con = .assure_connection(con) con$stopIfNotConnected() tag = "ogc_services" services = con$request(tag = tag, authorized = con$isLoggedIn()) class(services) = "ServiceTypeList" services_type_names = names(services) services = lapply(services_type_names, function(service_name) { service = services[[service_name]] service$name = service_name class(service) = "ServiceType" return(service) }) names(services) = services_type_names return(services) }, error = .capturedErrorToMessage) return(con$list_service_types()) } terms_of_service = function(con = NULL) { tryCatch({ con = .assure_connection(con) con$stopIfNotConnected() capabilities = con$getCapabilities() sel = lapply(capabilities$links, function(link) { if (link$rel == "terms-of-service") { return(link) } else { return(NULL) } }) sel = as.list(unlist(sel)) if (length(sel) == 0) { .no_information_by_backend("terms of service") return(invisible(NULL)) } else { htmlViewer(content(GET(sel$href),as = "text",type = "text/html",encoding = "UTF-8")) return(invisible(sel)) } }, error = .capturedErrorToMessage) } privacy_policy = function(con = NULL) { tryCatch({ con = .assure_connection(con) con$stopIfNotConnected() capabilities = con$getCapabilities() sel = lapply(capabilities$links, function(link) { if (link$rel == "privacy-policy") { return(link) } else { return(NULL) } }) sel = as.list(unlist(sel)) if (length(sel) == 0) { .no_information_by_backend("privacy policy") return(invisible(NULL)) } else { htmlViewer(content(GET(sel$href),as = "text",type = "text/html",encoding = "UTF-8")) return(invisible(sel)) } }, error = .capturedErrorToMessage) } conformance = function(con=NULL) { tryCatch({ con = .assure_connection(con) con$stopIfNotConnected() tag = "ogc_conformance" return(con$request(tag = tag)) }, error = .capturedErrorToMessage) }
popFprojHigh <- read.delim(file='popFprojHigh.txt', comment.char='
Return.wealthindex <- function (R, wealth.index = TRUE, ...) { x = checkData(R) columns = ncol(x) columnnames = colnames(x) one = 0 if(!wealth.index) one = 1 for(column in 1:columns) { column.Return.cumulative = na.skip(x[,column,drop=FALSE],FUN = function(x,one) {cumprod(1+x) - one},one=one) if(column == 1) Return.cumulative = column.Return.cumulative else Return.cumulative = merge(Return.cumulative,column.Return.cumulative) } if(columns == 1) Return.cumulative = as.xts(Return.cumulative) colnames(Return.cumulative) = columnnames reclass(Return.cumulative,match.to=x) }
sortPairs <- function(c1, c2, spMat=FALSE){ if (anyNA(c1) | anyNA(c2)) stop("NA are not supported.") if (((!is.vector(c1) & !is.factor(c1)) | is.list(c1)) | ((!is.vector(c2) & !is.factor(c2)) | is.list(c2))) stop("c1 and c2 must be vectors or factors but not lists.") if (length(c1) != length(c2)) stop("the two vectors must have the same length.") n <- length(c1) if (is.integer(c1) & is.integer(c2)) { res1 <- getRank(c1) res2 <- getRank(c2) mylevels <- list(c1=res1$index, c2=res2$index) c1 <- res1$translated c2 <- res2$translated } else if (is.factor(c1) & is.factor(c2)) { mylevels <- list(c1 = levels(c1), c2 = levels(c2)) c1 <- as.integer(c1) - 1L c2 <- as.integer(c2) - 1L } else { mylevels <- list(c1 = unique(c1), c2 = unique(c2)) c1 <- as.integer(factor(c1, levels = mylevels$c1)) - 1L c2 <- as.integer(factor(c2, levels = mylevels$c2)) - 1L } i_order <- order(c1, c2, method="radix") - 1L out <- countPairs(c1, c2, i_order) if (spMat) { spOut <- sparseMatrix(i=out$pair_c1, j=out$pair_c2, x=out$pair_nb, dims=sapply(mylevels,length), dimnames = mylevels, index1=FALSE) } else { spOut <- NULL } res <- list(spMat = spOut, levels = mylevels, nij = out$pair_nb, ni. = out$c1_nb, n.j = out$c2_nb, pair_c1 = out$pair_c1, pair_c2 = out$pair_c2 ) res } ARI <- function(c1, c2){ res <- sortPairs(c1, c2) N <- length(c1) stot <- sum(choose(res$nij, 2), na.rm=TRUE) srow <- sum(choose(res$ni., 2), na.rm=TRUE) scol <- sum(choose(res$n.j, 2), na.rm=TRUE) expectedIndex <-(srow*scol)/(choose(N,2)) maximumIndex <- (srow+scol)/2 if (expectedIndex == maximumIndex & stot != 0) { res <- 1 } else { res <- (stot-expectedIndex)/(maximumIndex-expectedIndex) } res } RI <- function(c1, c2){ res <- sortPairs(c1, c2) N <- length(c1) res <- 1 + (sum(res$nij^2) - (sum(res$ni.^2) + sum(res$n.j^2))/2)/choose(N,2) res } MARI <- function(c1, c2){ res <- sortPairs(c1, c2) N <- length(c1) stot <- sum(choose(res$nij, 2), na.rm=TRUE) srow <- sum(choose(res$ni., 2), na.rm=TRUE) scol <- sum(choose(res$n.j, 2), na.rm=TRUE) T1 <- 2*N T2 <- sum(res$nij * res$ni.[res$pair_c1+1] * res$n.j[res$pair_c2+1], na.rm=TRUE) T3 <- -sum(res$nij^2, na.rm=TRUE) - sum(res$ni.^2, na.rm=TRUE) - sum(res$n.j^2, na.rm=TRUE) expectedIndex <- (srow*scol - stot - (T1+T2+T3)) / (6 *choose(N, 4)) expectedIndex <- expectedIndex * choose(N, 2) maximumIndex <- (srow+scol)/2 if (expectedIndex == maximumIndex & stot != 0) { res <- 1 } else { res <- (stot-expectedIndex)/(maximumIndex-expectedIndex) } res res } MARIraw <- function(c1, c2){ res <- sortPairs(c1, c2) N <- length(c1) stot <- sum(choose(res$nij, 2), na.rm=TRUE) srow <- sum(choose(res$ni., 2), na.rm=TRUE) scol <- sum(choose(res$n.j, 2), na.rm=TRUE) T1 <- 2*N T2 <- sum(res$nij * res$ni.[res$pair_c1+1] * res$n.j[res$pair_c2+1], na.rm=TRUE) T3 <- -sum(res$nij^2, na.rm=TRUE) - sum(res$ni.^2, na.rm=TRUE) - sum(res$n.j^2, na.rm=TRUE) expectedIndex <- (srow*scol - stot - (T1+T2+T3)) / (6 *choose(N, 4)) res <- (stot / choose(N, 2)) - expectedIndex res } Chi2 <- function(c1, c2){ res <- sortPairs(c1, c2) N <- length(c1) res <- N* sum(res$nij^2 / (res$ni.[res$pair_c1+1] * res$n.j[res$pair_c2+1]) ) res <- res - N res } entropy <- function(c1, c2){ res <- sortPairs(c1, c2) N <- length(c1) H.UV <- - sum(res$nij * log(res$nij))/N + log(N) H.U <- - sum(res$ni. * log(res$ni.))/N + log(N) H.V <- - sum(res$n.j * log(res$n.j))/N + log(N) res <- list(UV = H.UV, U = H.U, V = H.V, sortPairs = res) res } clustComp <- function(c1, c2) { H <- entropy(c1,c2) MI <- - H$UV + H$U + H$V VI <- H$UV - MI NVI <- 1 - MI/H$UV ID <- max(H$U, H$V) - MI NID <- 1 - MI / max(H$U, H$V) NMI <- MI / max(H$U, H$V) EMI <- expected_MI(as.integer(H$ni.), as.integer(H$n.j)) res <- list(RI = RI(c1,c2) , ARI = ARI(c1,c2) , MI = - H$UV + H$U + H$V , AMI = (- H$UV + H$U + H$V - EMI) / (max(H$U,H$V) - EMI), VI = H$UV - MI , NVI = 1 - MI/H$UV , ID = max(H$U, H$V) - MI , NID = 1 - MI / max(H$U, H$V), NMI = MI / max(H$U, H$V) , Chi2 = Chi2(c1,c2) , MARI = MARI(c1,c2) , MARIraw = MARIraw(c1,c2) ) res res } AMI <- function(c1, c2){ H <- entropy(c1,c2) MI <- - H$UV + H$U + H$V EMI <- expected_MI(as.integer(H$ni.), as.integer(H$n.j)) res <- (MI - EMI) / (max(H$U,H$V) - EMI) res } NMI <- function(c1, c2, variant = c("max", "min", "sqrt", "sum", "joint")) { variant <- match.arg(variant) H <- entropy(c1,c2) MI <- - H$UV + H$U + H$V D <- switch(variant, "max" = max(H$U, H$V), "sqrt" = sqrt(H$U * H$V), "min" = min(H$U, H$V), "sum" = .5*(H$U + H$V), "joint" = H$UV) res <- MI / D res } NID <- function(c1, c2) { H <- entropy(c1,c2) MI <- - H$UV + H$U + H$V res <- 1 - MI / max(H$U, H$V) res } NVI <- function(c1, c2) { H <- entropy(c1,c2) MI <- - H$UV + H$U + H$V res <- 1 - MI/H$UV res }
noKernel <- function (dat,smooth=0.1,sort=F,output=1,genplot=T,verbose=T) { if(verbose) cat("\n----- REMOVING GAUSSIAN KERNEL SMOOTHER FROM STRATIGRAPHIC SERIES -----\n") if(smooth <= 0) {stop("**** ERROR, FUNCTION TERMINATED: smooth must be > 0")} dat <- data.frame(dat) npts <- length(dat[,1]) if(verbose) cat(" * Number of data points input=", npts,"\n") dat1 <- data.frame(dat) if (sort) { if(verbose) cat(" * Sorting into increasing order\n") dat <- dat[order(dat[,1],na.last=NA,decreasing=F),] } if (smooth != 0) { if(verbose) cat(" * Smoothing/detrending with Gaussian kernel\n") smoothScaled= abs( dat[1,1]-dat[npts,1] ) * smooth * 2 smooth2 <- ksmooth(dat[,1],dat[,2],kernel=c("normal"),bandwidth=smoothScaled,x.points=dat[,1]) resid<-data.frame(cbind(smooth2$x,(dat[,2]-smooth2$y))) smoother<-data.frame( cbind(smooth2$x,smooth2$y) ) if(genplot) { par(mfrow=c(2,2)) plot(dat,cex=0.5, main="Stratigraphic Data Series",xlab="Location",ylab="Value") lines(smoother,col="red") plot(resid, cex=0.5,main="Gaussian Kernel Detrended Series",xlab="Location",ylab="Detrended Value"); lines(resid) hist(resid[,2],freq=F, xlab="Value", main="Distribution of Residual Values"); lines(density(resid[,2], bw="nrd0"),col="red"); grid() boxplot(resid[,2], ylab="Value", main="Boxplot of Residual Values") } } if (output==1) return(resid) if (output==2) return(smoother) }
test_that("Plot Time Series and Images", { cerrado_ndvi <- sits_select(cerrado_2classes, "NDVI") p <- plot(cerrado_ndvi[1, ]) expect_equal(p$labels$title, "location (-14.05, -54.23) - Cerrado") cerrado_ndvi_1class <- dplyr::filter(cerrado_ndvi, label == "Cerrado") p1 <- plot(cerrado_ndvi_1class) expect_equal( p1$labels$title, "Samples (400) for class Cerrado in band = NDVI" ) p2 <- plot(sits_patterns(cerrado_2classes)) expect_equal(p2$guides$colour$title, "Bands") expect_equal(p2$theme$legend.position, "bottom") samples_mt_ndvi <- sits_select(samples_modis_4bands, bands = "NDVI") point_ndvi <- sits_select(point_mt_6bands, bands = "NDVI") rfor_model <- sits_train(samples_mt_ndvi, ml_method = sits_rfor()) point_class <- sits_classify(point_ndvi, rfor_model) p3 <- plot(point_class) expect_equal(p3$labels$y, "Value") expect_equal(p3$labels$x, "Time") expect_equal(p3$theme$legend.position, "bottom") data_dir <- system.file("extdata/raster/mod13q1", package = "sits") sinop <- sits_cube( source = "BDC", collection = "MOD13Q1-6", data_dir = data_dir, parse_info = c("X1", "X2", "tile", "band", "date") ) bbox <- sits_bbox(sinop) size_x <- bbox["xmax"] - bbox["xmin"] size_y <- bbox["ymax"] - bbox["ymin"] roi <- c(floor(bbox["xmin"] + size_x/4), floor(bbox["xmax"] - size_x/4), floor(bbox["ymin"] + size_y/4), floor(bbox["ymax"] - size_y/4)) r_obj <- plot(sinop, red = "EVI", blue = "EVI", green = "NDVI", roi = roi) expect_equal(terra::nlyr(r_obj), 3) expect_equal(terra::ncol(r_obj), 127) r_obj <- plot(sinop, band = "EVI") expect_equal(terra::nlyr(r_obj), 1) expect_equal(terra::ncol(r_obj), 254) sinop_probs <- suppressMessages( sits_classify( sinop, ml_model = rfor_model, memsize = 2, multicores = 1, output_dir = tempdir() ) ) p_probs <- plot(sinop_probs) expect_equal(p_probs$adj, 0.5) expect_equal(p_probs$lend, "round") p_probs <- plot(sinop_probs, labels = "Forest") expect_equal(p_probs$adj, 0.5) expect_equal(p_probs$lend, "round") sinop_uncert <- sits_uncertainty(sinop_probs, output_dir = tempdir()) p_uncert <- plot(sinop_uncert, n_breaks = 11, breaks = "pretty") expect_equal(p_uncert$adj, 0.5) expect_equal(p_uncert$lend, "round") expect_equal(p_uncert$lty, "solid") sinop_labels <- sits_label_classification(sinop_probs, output_dir = tempdir()) p4 <- plot(sinop_labels, title = "Classified image") expect_equal(p4$labels$title, "Classified image") expect_equal(p4$layers[[1]]$geom_params$hjust, 0.5) expect_true(p4$layers[[1]]$inherit.aes) p5 <- plot(sinop_labels, title = "Classified image", legend = c("Cerrado" = " "Forest" = " "Pasture" = " "Soy_Corn" = " expect_equal(p5$labels$title, "Classified image") expect_equal(p5$layers[[1]]$geom_params$hjust, 0.5) expect_true(p5$layers[[1]]$inherit.aes) expect_true(all(file.remove(unlist(sinop_probs$file_info[[1]]$path)))) expect_true(all(file.remove(unlist(sinop_labels$file_info[[1]]$path)))) }) test_that("Dendrogram Plot", { cluster_obj <- sits:::.sits_cluster_dendrogram(cerrado_2classes, bands = c("NDVI", "EVI") ) cut.vec <- sits:::.sits_cluster_dendro_bestcut( cerrado_2classes, cluster_obj ) dend <- sits:::.sits_plot_dendrogram( data = cerrado_2classes, cluster = cluster_obj, cutree_height = cut.vec["height"], palette = "RdYlGn" ) expect_equal(class(dend), "dendrogram") }) source("./test-utils.R") test_that("Plot keras model", { Sys.setenv(TF_CPP_MIN_LOG_LEVEL = "1") samples_mt_2bands <- sits_select(samples_modis_4bands, bands = c("NDVI", "EVI") ) model <- suppress_keras( sits_train( samples_mt_2bands, sits_mlp( layers = c(128, 128), dropout_rates = c(0.5, 0.4), epochs = 50, verbose = 0 ) ) ) pk <- plot(model) expect_true(length(pk$layers) == 2) expect_true(pk$labels$colour == "data") expect_true(pk$labels$x == "epoch") expect_true(pk$labels$y == "value") }) test_that("Plot series with NA", { cerrado_ndvi <- cerrado_2classes %>% sits_select(bands = "NDVI") %>% dplyr::filter(label == "Cerrado") cerrado_ndvi_1 <- cerrado_ndvi[1,] ts <- cerrado_ndvi_1$time_series[[1]] ts[1,2] <- NA ts[10,2] <- NA cerrado_ndvi_1$time_series[[1]] <- ts pna <- suppressWarnings(plot(cerrado_ndvi_1)) expect_true(pna$labels$x == "Index") expect_true(pna$labels$y == "value") }) test_that("SOM map plot", { set.seed(1234) som_map <- suppressWarnings(sits_som_map( cerrado_2classes, grid_xdim = 5, grid_ydim = 5 )) p <- plot(som_map) expect_true(all(names(p$rect) %in% c("w", "h", "left", "top"))) pc <- plot(som_map, type = "mapping") expect_true(all(names(pc$rect) %in% c("w", "h", "left", "top"))) }) test_that("SOM evaluate cluster plot", { set.seed(1234) som_map <- suppressWarnings(sits_som_map( cerrado_2classes, grid_xdim = 5, grid_ydim = 5 )) cluster_purity_tb <- sits_som_evaluate_cluster(som_map) p <- plot(cluster_purity_tb) expect_equal(p$labels$title, "Confusion by cluster") expect_equal(p$labels$y, "Percentage of mixture") })
msmedse <- function(x, sewarn = TRUE, ...){ x=elimna(x) chk=sum(duplicated(x)) if (sewarn) { if(chk>0){ warning("Tied values detected. Estimate of standard error might be inaccurate.") }} y<-sort(x) n<-length(x) av<-round((n+1)/2-qnorm(.995)*sqrt(n/4)) if(av==0)av<-1 top<-n-av+1 sqse<-((y[top]-y[av])/(2*qnorm(.995)))^2 sqse<-sqrt(sqse) sqse }
.build_d <- function(model,M) { model$d = matrix(0,nrow=M,ncol=model$J) if(!all(!model$semi)){ sojourn.distribution=model$sojourn$type J = model$J if(sojourn.distribution=='nonparametric' | sojourn.distribution=="ksmoothed-nonparametric") { if(!is.null(model$sojourn$d)) { if(ncol(model$sojourn$d)!=J) stop("ncol(model$d)!=J") M = nrow(model$sojourn$d) model$d = model$sojourn$d }else stop("Sojourn distribution (model$sojourn$d) not specified.") } if(sojourn.distribution=="poisson") { if(is.null(model$sojourn$d)) { if(is.null(model$sojourn$lambda)) stop('Invalid waiting parameters supplied') if(is.null(model$sojourn$shift)) stop('No shift parameter provided for Poisson sojourn distribution (must be at least 1)') model$d = matrix(0,nrow=M,ncol=model$J) for(i in 1:J){ if(model$semi[i]) model$d[,i] = .dpois.hhsmm(1:M,model$sojourn$lambda[i],model$sojourn$shift[i]) } } else for(i in 1:J) model$d = model$sojourn$d } if(sojourn.distribution=="lnorm") { if(is.null(model$sojourn$d)) { if(is.null(model$sojourn$meanlog) | is.null(model$sojourn$sdlog)) stop('Invalid waiting parameters supplied') model$d = matrix(0,nrow=M,ncol=model$J) for(i in 1:J){ if(model$semi[i]){ for(u in 1:M){ model$d[u,i] = plnorm(u,meanlog=model$sojourn$meanlog[i],sdlog=model$sojourn$sdlog[i]) - plnorm(u-1,meanlog=model$sojourn$meanlog[i],sdlog=model$sojourn$sdlog[i]) model$d[u,i] = model$d[u,i] / plnorm(M,meanlog=model$sojourn$meanlog[i],sdlog=model$sojourn$sdlog[i]) } } } }else for(i in 1:J) model$d = model$sojourn$d } if(sojourn.distribution=="gamma") { if(is.null(model$sojourn$shape) | is.null(model$sojourn$scale)) { if(is.null(model$sojourn$d)) stop('Invalid waiting parameters supplied') else model$d = model$sojourn$d }else { model$d = matrix(0,nrow=M,ncol=model$J) for(i in 1:J) { if(model$semi[i]){ for(u in 1:M){ model$d[u,i] = pgamma(u,shape=model$sojourn$shape[i],scale=model$sojourn$scale[i]) - pgamma(u-1,shape=model$sojourn$shape[i],scale=model$sojourn$scale[i]) model$d[u,i] = model$d[u,i] / (pgamma(M,shape=model$sojourn$shape[i],scale=model$sojourn$scale[i])) } } } } } if(sojourn.distribution=="weibull") { if(is.null(model$sojourn$shape) | is.null(model$sojourn$scale)) { if(is.null(model$sojourn$d)) stop('Invalid waiting parameters supplied') else model$d = model$sojourn$d }else { model$d = matrix(0,nrow=M,ncol=model$J) for(i in 1:J) { if(model$semi[i]){ for(u in 1:M){ model$d[u,i] = pweibull(u,shape=model$sojourn$shape[i],scale=model$sojourn$scale[i]) - pweibull(u-1,shape=model$sojourn$shape[i],scale=model$sojourn$scale[i]) model$d[u,i] = model$d[u,i] / (pweibull(M,shape=model$sojourn$shape[i],scale=model$sojourn$scale[i])) } } } } } if(sojourn.distribution=="logarithmic") { if(is.null(model$sojourn$shape)) { if(is.null(model$sojourn$d)) stop('Invalid waiting parameters supplied') else model$d = model$sojourn$d } else { model$d = matrix(0,nrow=M,ncol=model$J) for(i in 1:J){ if(model$semi[i]) model$d[,i] = .dlog(1:M,model$sojourn$shape[i]) } } } if (sojourn.distribution == "nbinom") { model$d = matrix(0,nrow = M, ncol = J) if(is.null(model$sojourn$mu)) for (i in 1:J){ if(model$semi[i]) model$d[, i] = .dnbinom.hhsmm(1:M,size=model$sojourn$size[i],prob=model$sojourn$prob[i],shift=model$sojourn$shift[i]) } if(is.null(model$sojourn$prob)) for (i in 1:J){ if(model$semi[i]) model$d[, i] = .dnbinom.hhsmm(1:M,size=model$sojourn$size[i],mu=model$sojourn$mu[i],shift=model$sojourn$shift[i]) } } model$d=head(model$d,M) } model$D = apply(model$d,2,function(x) rev(cumsum(rev(x)))) model }
`points.radline` <- function (x, ...) { poi <- x$y rnk <- seq(along = poi) points(rnk, poi, ...) out <- list(species = cbind(rnk, poi)) class(out) <- "ordiplot" invisible(out) } `points.radfit` <- function(x, ...) { points.radline(x, ...) }
loo.design2 <- function(x, w, constraint, ptConstr, knots, pw, nrq, nl1, neqc, niqc, nvar, lambda) { degree <- 2 ks <- degree + 1 stopifnot(is.character(constraint), length(constraint) == length(niqc), nvar == as.integer(nvar), length(nvar) == 1, nvar >= 1) nvar <- as.integer(nvar) fieq <- FALSE nk <- length(knots) + 2*(ks - 1) ncoef <- nk - ks ox <- order(x) sortx <- x[ox] z1 <- .splBasis(ord = ks, knots, ncoef, xo = sortx) i1 <- rep.int(ox, rep.int(ks, nrq)) j1 <- c(outer(1:ks, z1$offsets, "+")) Xeq <- as.matrix.csr(new("matrix.coo", ra = c(t(t(z1$design) * rep(w[ox], ks))), ia = i1, ja = j1, dimension = as.integer(c(nrq, nvar)))) nd <- nk - 5 if(lambda != 0) { niqc1 <- 2*nd z2 <- .splBasis(ord = ks, knots, ncoef, xo = knots[1:nd], derivs = rep.int(2, nd)) Xl1 <- new("matrix.csr", ra = lambda, ja = as.integer(nvar), ia = 1:2, dimension = as.integer(c(1, nvar))) Xieq <- new("matrix.csr", ra = c(z2$design,-z2$design), ja = c(rep.int(outer(1:ks, z2$offsets, "+"),2)), ia = as.integer(seq(1,2*length(z2$design)+1, by = ks)), dimension = as.integer(c(niqc1, nvar-1))) Xeq <- rbind(Xeq, Xl1) Xieq <- cbind(Xieq, as.matrix.csr(rep.int(1, niqc1))) fieq <- TRUE } else niqc1 <- 0 niqc4 <- niqc - (niqc1 + ptConstr$n.smaller + ptConstr$n.greater) for(i.cnstr in seq(along=constraint)) { constr <- constraint[i.cnstr] niqc4. <- niqc4[i.cnstr] if(constr == "convex" || constr == "concave") { if(lambda == 0) z2 <- .splBasis(ord = ks, knots, ncoef, xo = knots[1:niqc4.], derivs = rep.int(2, niqc4.)) ra <- c(if(constr == "convex") z2$design else -z2$design) ja <- c(outer(1:ks, z2$offsets,"+")) ia <- as.integer(seq(1, length(z2$design)+1, by = ks)) Xc <- new("matrix.csr", ra = ra, ja = ja, ia = ia, dimension = as.integer(c(niqc4., nvar))) if(fieq) Xieq <- rbind(Xieq, Xc) else { Xieq <- Xc fieq <- TRUE } } else if(constr == "periodic") { z1.3 <- .splBasis(ord = ks, knots, ncoef, xo = sortx[c(1,nrq)], derivs = c(1,1)) ra <- c(z1.3$design) ja <- c(outer(1:ks, z1.3$offsets,"+")) ia <- as.integer(seq(1, length(z1.3$design)+1, by = ks)) Xp <- new("matrix.csr", ra = ra, ja = ja, ia = ia, dimension = as.integer(c(2,nvar))) Xp <- rbind(Xeq[ox[nrq],]- Xeq[ox[1],], Xp[2,]-Xp[1,]) if(fieq) Xieq <- rbind(Xieq, Xp,-Xp) else { Xieq <- rbind(Xp,-Xp) fieq <- TRUE } } else if(constr == "increase" || constr == "decrease") { z3 <- .splBasis(ord = ks, knots, ncoef, xo = knots[1:niqc4.], derivs = rep.int(1, niqc4.)) ra <- c(if(constr == "increase") z3$design else -z3$design) ja <- c(outer(1:ks, z3$offsets,"+")) ia <- as.integer(seq(1, length(z3$design)+1, by = ks)) X1 <- new("matrix.csr", ra = ra, ja = ja, ia = ia, dimension = as.integer(c(niqc4., nvar))) if(fieq) Xieq <- rbind(Xieq, X1) else { Xieq <- X1 fieq <- TRUE } } } if(ptConstr$n.smaller > 0) { o.smaller <- order(ptConstr$smaller[,2]) smaller.o <- ptConstr$smaller[,2][o.smaller] z3.1 <- .splBasis(ord = ks, knots, ncoef, xo = smaller.o) ra <- -c(z3.1$design) ja <- c(outer(1:ks, z3.1$offsets,"+")) ia <- as.integer(seq(1, length(z3.1$design)+1, by = ks)) Xp <- new("matrix.csr", ra = ra, ja = ja, ia = ia, dimension = as.integer(c(ptConstr$n.smaller, nvar))) if(fieq) Xieq <- rbind(Xieq, Xp) else { Xieq <- Xp fieq <- TRUE } } if(ptConstr$n.greater > 0) { o.greater <- order(ptConstr$greater[,2]) greater.o <- ptConstr$greater[,2][o.greater] z3.2 <- .splBasis(ord = ks, knots, ncoef, xo = greater.o) ra <- c(z3.2$design) ja <- c(outer(1:ks, z3.2$offsets,"+")) ia <- as.integer(seq(1, length(z3.2$design)+1, by = ks)) Xp <- new("matrix.csr", ra = ra, ja = ja, ia = ia, dimension = as.integer(c(ptConstr$n.greater, nvar))) if(fieq) Xieq <- rbind(Xieq, Xp) else { Xieq <- Xp fieq <- TRUE } } if(ptConstr$n.equal > 0) { o.equal <- order(ptConstr$equal[,2]) equal.o <- ptConstr$equal[,2][o.equal] z1.1 <- .splBasis(ord = ks, knots, ncoef, xo = equal.o) ra <- c(z1.1$design) ja <- c(outer(1:ks, z1.1$offsets,"+")) ia <- as.integer(seq(1, length(z1.1$design)+1, by = ks)) Xp <- new("matrix.csr", ra = ra, ja = ja, ia = ia, dimension = as.integer(c(ptConstr$n.equal, nvar))) if(fieq) Xieq <- rbind(Xieq, Xp,-Xp) else { Xieq <- rbind(Xp,-Xp) fieq <- TRUE } } if(ptConstr$n.gradient > 0) { o.gradient <- order(ptConstr$gradient[,2]) gradient.o <- ptConstr$gradient[,2][o.gradient] z1.2 <- .splBasis(ord = ks, knots, ncoef, xo = gradient.o, derivs = rep.int(1, ptConstr$n.gradient)) ra <- c(z1.2$design) ja <- c(outer(1:ks, z1.2$offsets,"+")) ia <- as.integer(seq(1, length(z1.2$design)+1, by = ks)) Xp <- new("matrix.csr", ra = ra, ja = ja, ia = ia, dimension = as.integer(c(ptConstr$n.gradient, nvar))) if(fieq) Xieq <- rbind(Xieq, Xp,-Xp) else { Xieq <- rbind(Xp,-Xp) fieq <- TRUE } } if(fieq) return(list(Xeq = Xeq, Xieq = Xieq, fieq = fieq, niqc1 = niqc1)) else return(list(Xeq = Xeq, fieq = fieq, niqc1 = niqc1)) }
test_that('output="modelsummary_list" and back to data.frame', { mod <- list( lm(mpg ~ hp, mtcars), lm(mpg ~ hp + drat, mtcars)) tab <- modelsummary(mod, "modelsummary_list") expect_true(all(sapply(tab, inherits, "modelsummary_list"))) expect_true(class(tab) == "list") tab <- modelsummary(tab, "data.frame") expect_s3_class(tab, "data.frame") expect_equal(dim(tab), c(13, 5)) }) test_that("tidiers empty", { mod <- lm(mpg ~ hp + drat + vs, mtcars) ml <- list(tidy = modelsummary:::get_estimates(mod)) class(ml) <- "modelsummary_list" gl <- generics::glance(ml) expect_s3_class(gl, "data.frame") expect_equal(dim(gl), c(1, 0)) ml <- list(glance = modelsummary:::get_gof(mod)) class(ml) <- "modelsummary_list" expect_error(tidy(ml)) })
library(propr) data(iris) keep <- iris$Species %in% c("setosa", "versicolor") counts <- iris[keep, 1:4] * 10 group <- ifelse(iris[keep, "Species"] == "setosa", "A", "B") pd <- propd(counts, group, alpha = NA, p = 100) theta_d <- setDisjointed(pd) theta_e <- setEmergent(pd) theta_d <- updateCutoffs(theta_d, cutoff = seq(0.05, 0.95, 0.3)) theta_e <- updateCutoffs(theta_e, cutoff = seq(0.05, 0.95, 0.3)) data(pd.d, package = "propr") data(pd.e, package = "propr") tab <- getResults(pd.d) plot(pd.d@counts[, 39], pd.d@counts[, 37], col = ifelse(pd.d@group == "WA", "red", "blue")) grp1 <- pd.d@group == "WA" grp2 <- pd.d@group != "WA" abline(a = 0, b = pd.d@counts[grp1, 37] / pd.d@counts[grp1, 39], col = "red") abline(a = 0, b = pd.d@counts[grp2, 37] / pd.d@counts[grp2, 39], col = "blue") plot(pd.d@counts[, 37] / pd.d@counts[, 39], col = ifelse(pd.d@group == "WA", "red", "blue")) tab <- getResults(pd.e) plot(pd.e@counts[, 106], pd.e@counts[, 2], col = ifelse(pd.d@group == "WA", "red", "blue")) grp1 <- pd.e@group == "WA" grp2 <- pd.e@group != "WA" abline(a = 0, b = pd.e@counts[grp1, 2] / pd.e@counts[grp1, 106], col = "red") abline(a = 0, b = pd.e@counts[grp2, 2] / pd.e@counts[grp2, 106], col = "blue") plot(pd.e@counts[, 2] / pd.e@counts[, 106], col = ifelse(pd.d@group == "WA", "red", "blue")) pd.f <- setActive(pd, what = "theta_f") parallel(pd.d, cutoff = .15, include = "c19327_g2_i3") parallel(pd.e, include = "c27054_g5_i1")
Return <- CONCAT("I love"," writing tests") expect_equal(Return,"I love writing tests")
hwe.ibf.mc <- function(y, t, M = 10000, verbose = TRUE) { if (class(y) != "HWEdata") { stop("y argument not of class 'HWEdata'. Type '?HWEdata' for help.") } y.mat <- [email protected] r <- y@size R <- r*(r + 1)/2 y.vec <- [email protected] n <- sum(y.vec, na.rm = TRUE) if ((t <= 0) | (t > n) | (is.null(t))) { stop("The training sample size t has to be an integer in between 1 and the sample size n.") } r.i <- rowSums(y.mat, na.rm = TRUE) c.i <- colSums(y.mat, na.rm = TRUE) theta.hat <- (y.vec + 1)/(n + R) const <- lfactorial(t) + lfactorial(t + R - 1) + lfactorial(2*n + r - 1) - lfactorial(2*t + r - 1) - lfactorial(n + t + R - 1) - (n - sum(diag(y.mat)))*log(2) - sum(lfactorial(r.i + c.i)) bf.draws <- vector(length = M) for (k in 1:M) { x.vec <- rmultinom(1, t, theta.hat) x <- matrix(NA, r, r) for (i in 1:r) { x[i, 1:i] <- x.vec[((i - 1)*i/2 + 1):(i*(i + 1)/2)] } z.i <- rowSums(x, na.rm = TRUE) d.i <- colSums(x, na.rm = TRUE) bf.draws[k] <- const + (t - sum(diag(x)))*log(2) + sum(lfactorial(z.i+d.i)) - 2*sum(lfactorial(x.vec)) + sum(lfactorial(x.vec + y.vec)) - dmultinom(x = x.vec, prob = theta.hat, log = TRUE) if (verbose) { if (round(k/10000) == k/10000) print(paste(k, "/", M, sep = ""), quote = FALSE) } } bf.draws <- exp(bf.draws) bf_mc <- mean(bf.draws) npp <- 1/(1 + bf_mc) out <- new("HWEintr", bf = bf_mc, npp = npp, draws = bf.draws, data = y.mat) return(out) } hwe.ibf <- function(y, t) { if (class(y) != "HWEdata") { stop("y argument not of class 'HWEdata'. Type '?HWEdata' for help.") } r <- y@size if (r != 2) { stop("The exact calculation for the Bayes Factor based on intrinsic priors is available only for r (number of alleles) equal to 2.") } y.mat <- [email protected] y.vec <- [email protected] R <- r*(r + 1)/2 n <- sum(y.vec, na.rm = TRUE) r.i <- rowSums(y.mat, na.rm = TRUE) c.i <- colSums(y.mat, na.rm = TRUE) C <- choose(t + R - 1, R - 1) tables <- matrix(NA, nrow = R, ncol = C) indx <- 1 for (i in 0:t) { for (j in 0:(t - i)) { tables[, indx] <- c(i, j, t - i - j) indx <- indx + 1 } } const <- lfactorial(t) + lfactorial(t + R - 1) + lfactorial(2*n + r - 1) - lfactorial(2*t + r - 1) - lfactorial(n + t + R - 1) - (n - sum(diag(y.mat)))*log(2) - sum(lfactorial(r.i + c.i)) bf.log <- vector(length = C) for (k in 1:C) { x.vec <- tables[, k] x <- matrix(NA, r, r) for (i in 1:r) { x[i, 1:i] <- x.vec[((i - 1)*i/2 + 1):(i*(i + 1)/2)] } z.i <- rowSums(x, na.rm = TRUE) d.i <- colSums(x, na.rm = TRUE) bf.log[k] <- const + (t - sum(diag(x)))*log(2) + sum(lfactorial(z.i + d.i)) - 2*sum(lfactorial(x.vec)) + sum(lfactorial(x.vec + y.vec)) } out <- sum(exp(bf.log)) return(out) } hwe.bf <- function(y) { if (class(y) != "HWEdata") { stop("y argument not of class 'HWEdata'. Type '?HWEdata' for help.") } y.mat <- [email protected] r <- y@size R <- r*(r + 1)/2 y.vec <- [email protected] n <- sum(y.vec, na.rm = TRUE) r.i <- rowSums(y.mat, na.rm = TRUE) c.i <- colSums(y.mat, na.rm = TRUE) bf.log <- lfactorial(R - 1) + lfactorial(2*n + r - 1) - lfactorial(n + R - 1) - lfactorial(r - 1) - (n - sum(diag(y.mat)))*log(2) - sum(lfactorial(r.i + c.i)) + sum(lfactorial(y.vec)) out <- exp(bf.log) return(out) } cip.tmp <- function(p11, p21, t, p) { R <- 3 C <- choose(t + R - 1, R - 1) tables <- matrix(NA, nrow = R, ncol = C) indx <- 1 for (i in 0:t) { for (j in 0:(t - i)) { tables[, indx] <- c(i, j, t - i - j) indx <- indx + 1 } } const <- factorial(t)*factorial(t + 2) cip.terms <- numeric(C) pij <- c(p11, p21, 1 - p11 - p21) if (all(pij <= 1) & all(pij >= 0)) { for (k in 1:C) { x <- tables[, k] cip.terms[k] <- 2^x[2] * p^(2*x[1] + x[2]) * (1 - p)^(x[2] + 2*x[3]) * prod(pij^x) / prod(factorial(x))^2 } out <- const*sum(cip.terms) } else { out <- NA } return(out) } cip.2 <- function(t, p, k = 30) { p11 <- p21 <- seq(0, 1, length.out = k) cip <- outer(X = p11, Y = p21, FUN = Vectorize(cip.tmp), t, p) cip[is.na(cip)] <- 0 nrz <- nrow(cip) ncz <- ncol(cip) colors <- colorRampPalette( c("gray","lightgray")) nbcol <- 100 color <- colors(nbcol) z <- cip zfacet <- z[-1, -1] + z[-1, -ncz] + z[-nrz, -1] + z[-nrz, -ncz] facetcol <- cut(zfacet, nbcol) persp(p11, p21, cip, xlab = "p_11", ylab = "p_21", zlab = "density", ticktype = "detailed", shade = .5, theta = -25, phi = 25, expand = 0.4, scale = TRUE, ltheta = 10, lphi = -10, cex.axis = 1.2, cex.lab = 1.2, col = color[facetcol]) } ip.tmp <- function(p11, p21, t) { R <- 3 C <- choose(t + R - 1, R - 1) tables <- matrix(NA, nrow = R, ncol = C) indx <- 1 for (i in 0:t) { for (j in 0:(t - i)) { tables[, indx] <- c(i, j, t - i - j) indx <- indx + 1 } } const <- factorial(t)*factorial(t + 2)/factorial(2*t + 1) ip.terms <- numeric(C) pij <- c(p11, p21, 1 - p11 - p21) if (all(pij <= 1) & all(pij >= 0)) { for (k in 1:C) { x <- tables[,k] ip.terms[k] <- 2^x[2] * factorial(2*x[1] + x[2]) * factorial(x[2] + 2*x[3]) * prod(pij^x) / prod(factorial(x))^2 } out <- const*sum(ip.terms) } else { out <- NA } return(out) } ip.2 <- function(t, k = 30) { p11 <- p21 <- seq(0, 1, length.out = k) ip <- outer(X = p11, Y = p21, FUN = Vectorize(ip.tmp), t) ip[is.na(ip)] <- 0 nrz <- nrow(ip) ncz <- ncol(ip) colors <- colorRampPalette( c("gray","lightgray")) nbcol <- 100 color <- colors(nbcol) z <- ip zfacet <- z[-1, -1] + z[-1, -ncz] + z[-nrz, -1] + z[-nrz, -ncz] facetcol <- cut(zfacet, nbcol) persp(p11, p21, ip, xlab = "p_11", ylab = "p_21", zlab = "density", ticktype = "detailed", shade = .5, theta = 50, phi = 35, expand = 0.4, scale = TRUE, ltheta = 40, lphi = -20, cex.axis = 1.2, cex.lab = 1.2, col = color[facetcol]) } lik.multin <- function(y, p11, p21) { if (class(y) != "HWEdata") { stop("y argument not of class 'HWEdata'. Type '?HWEdata' for help.") } y.vec <- [email protected] n <- sum(y.vec) out <- matrix(NA, nrow = length(p11), ncol = length(p21)) for (i in 1:length(p11)) { for (j in 1:length(p21)) { prob <- c(p11[i], p21[j], 1 - p11[i] - p21[j]) if (all(prob <= 1) & all(prob >= 0)) { out[i, j] <- dmultinom(y.vec, prob = prob) } else{ out[i, j] <- NA } } } const <- lfactorial(n) + sum(lgamma(y.vec + 1)) - sum(lfactorial(y.vec)) - lgamma(n + length(y.vec)) const <- exp(const) out <- out/const return(out) } hwe.ibf.plot <- function(y, t.vec, M = 100000, bf = FALSE) { if (class(y) != "HWEdata") { stop("y argument not of class 'HWEdata'. Type '?HWEdata' for help.") } n <- sum([email protected], na.rm = TRUE) H <- length(t.vec) out.mc <- matrix(NA, nrow = H, ncol = 2) for (h in 1:H) { print(paste(h, "/", H, sep = ""), quote = FALSE) res <- hwe.ibf.mc(y, t.vec[h], M, verbose = FALSE) out.mc[h,] <- c(log10(res@bf), res@npp) } if (y@size == 2) { out.exact <- matrix(NA, nrow = H, ncol = 2) hwe.ibf.exact <- Vectorize(hwe.ibf, "t") res <- hwe.ibf.exact(t.vec, y = y) out.exact <- cbind(log10(res), 1/(1 + res)) } res <- hwe.bf(y) out.std <- c(log10(res), 1/(1 + res)) if (bf) { idx = 1 ytxt = "Bayes Factor of Alternative vs. Null (log10)" } else { idx = 2 ytxt = "Null Posterior Probability" } if (y@size != 2) { out <- list(mc = out.mc, std = out.std) } else { out <- list(mc = out.mc, std = out.std, exact = out.exact) } plot(t.vec/n, out.mc[, idx], type = "n", ylab = ytxt, xlab = "f = t/n", main = "", cex.axis = 1.75, cex.lab = 1.75, col = gray(.5), ylim = c(min(out.std[idx], out.mc[, idx]), max(out.std[idx], out.mc[, idx]))) abline(h = out.std[idx], col = gray(.5), lty = "longdash") if (y@size == 2) lines(t.vec/n, out.exact[, idx], col = gray(.3), lty = "longdash", lwd = 2) lines(smooth.spline(t.vec/n, out.mc[, idx]), col = gray(0), lwd = 2) invisible(out) }
RGX_T <- "t" RGX_R <- "r" RGX_Q <- "Q\\s?-?\\s?(w|W|(w|W)ithin|b|B|(b|B)etween)?" RGX_F <- "F" RGX_CHI2 <- "((\\[CHI\\]|\\[DELTA\\]G)\\s?|(\\s[^trFzQWnD ]\\s?)|([^trFzQWnD ]2\\s?))2?" RGX_Z <- "([^a-z](z|Z))" RGX_DF_T_R_Q <- "\\(\\s?\\d*\\.?\\d+\\s?\\)" RGX_DF_F <- "\\(\\s?\\d*\\.?(I|l|\\d+)\\s?,\\s?\\d*\\.?\\d+\\s?\\)" RGX_DF_CHI2 <- "\\(\\s?\\d*\\.?\\d+\\s?(,\\s?N\\s?\\=\\s?\\d*\\,?\\d*\\,?\\d+\\s?)?\\)" RGX_T_DF <- paste0("(", RGX_T, "\\s?", RGX_DF_T_R_Q, ")") RGX_R_DF <- paste0("(", RGX_R, "\\s?", RGX_DF_T_R_Q, ")") RGX_Q_DF <- paste0("(", RGX_Q, "\\s?", RGX_DF_T_R_Q, ")") RGX_F_DF <- paste0("(", RGX_F, "\\s?", RGX_DF_F, ")") RGX_CHI2_DF <- paste0("(", RGX_CHI2, "\\s?", RGX_DF_CHI2, ")") RGX_TEST_DF <- paste0("(", RGX_T_DF, "|", RGX_R_DF, "|", RGX_Q_DF, "|", RGX_F_DF, "|", RGX_CHI2_DF, "|", RGX_Z, ")") RGX_TEST_VALUE <- "[<>=]\\s?[^a-zA-Z\\d\\.]{0,3}\\s?\\d*,?\\d*\\.?\\d+\\s?," RGX_NS <- "([^a-z]n\\.?s\\.?)" RGX_P <- "(p\\s?[<>=]\\s?\\d?\\.\\d+e?-?\\d*)" RGX_P_NS <- paste0("(", RGX_NS, "|", RGX_P, ")") RGX_NHST <- paste(RGX_TEST_DF, RGX_TEST_VALUE, RGX_P_NS, sep = "\\s?") RGX_OPEN_BRACKET <- "(.+?(?=\\())" RGX_TEST_TYPE <- paste(RGX_Z, RGX_OPEN_BRACKET, sep = "|") RGX_QW <- "w" RGX_QB <- "b" RGX_DF <- paste0("(", RGX_DF_T_R_Q, ")|(", RGX_DF_F, ")|(", RGX_DF_CHI2, ")") RGX_COMP <- "[<>=]" RGX_1000_SEP <- "(?<=\\d),(?=\\d+)" RGX_DEC <- "\\.\\d+" RGX_WEIRD_MINUS <- "\\s?[^\\d\\.\\s]+(?=\\d|\\.)" RGX_DF1_I_L <- "I|l"
setMethod(f="resid",signature=c(object="cold"), function (object, type = c( "pearson","response","null"),...) { type <- match.arg(type) data<[email protected] data$y<-as.vector(t([email protected])) ynew<-data$y mu <- object@Fitted switch(type, pearson = , response = ) if(type=="pearson"||type=="null"){ res = (ynew - mu)/sqrt(mu)} else {res = (ynew - mu)} names(res) <- c(1:length(res)) round(res,6) } )
"surf.tri" <- function(p,t){ faces = rbind(t[,-4], t[,-3], t[,-2], t[,-1]); node4 = rbind(t[, 4], t[, 3], t[, 2], t[, 1]); i.max = 3*(1:nrow(faces)-1) + max.col(faces) i.min = 3*(1:nrow(faces)-1) + max.col(-faces) faces = t(faces) faces = cbind(faces[i.min], faces[-c(i.max,i.min)], faces[i.max]) ix = order(faces[,1], faces[,2], faces[,3]) fo = apply(faces[ix,],2,diff) dup = (abs(fo) %*% rep(1,3)) == 0 dup = c(FALSE,dup) qx = diff(dup)==0 qx = c(qx, !dup[length(dup)]) tri = faces[ix[qx],] node4 = node4[ix[qx]] v1 = p[tri[,2],] - p[tri[,1],]; v2 = p[tri[,3],] - p[tri[,1],]; v3 = p[node4,] - p[tri[,1],]; ix = which( apply(extprod3d(v1,v2) * v3, 1, sum) > 0 ) tri[ix,c(2,3)] = tri[ix,c(3,2)] rownames(tri) = NULL tri }
plot.covfm <- function(x, which.plots = c(4, 3, 5), ...) { n.models <- length(x) mod.names <- names(x) choices <- c("All", "Eigenvalues of Covariance Estimate", "Mahalanobis Distances", "Ellipses Plot") if(n.models == 2) choices <- c(choices, "Distance - Distance Plot") else which.plots <- which.plots[which.plots != 5] all.plots <- 2:length(choices) tmenu <- paste("plot:", choices) if(is.numeric(which.plots)) { if(!all(which.plots %in% all.plots)) stop(sQuote("which"), " must be in 2:", length(choices)) if(length(which.plots) == 0) return(invisible(x)) if(length(which.plots) > 1) { par.ask <- par(ask = TRUE) on.exit(par(ask = par.ask)) } ask <- FALSE which.plots <- c(which.plots + 1, 1) } else if(which.plots == "all") { which.plots <- c(all.plots + 1, 1) ask <- FALSE par.ask <- par(ask = TRUE) on.exit(par(ask = par.ask)) } else ask <- TRUE repeat { if(ask) { which.plots <- menu(tmenu, title = "\nMake plot selections (or 0 to exit):\n") if(any(which.plots == 1)) { which.plots <- c(all.plots, 0) par.ask <- par(ask = TRUE) on.exit(par(ask = par.ask)) } which.plots <- which.plots + 1 } if(!length(which.plots)) stop(paste("Invalid choice of plot in \'which.plots\'")) for(pick in which.plots) { switch(pick, return(invisible(x)), place.holder <- 1, screePlot.covfm(x, xlab = "Principal Component", ylab = "Variances", main = "Screeplot", ...), distancePlot.covfm(x, xlab = "Index", ylab = "Mahalanobis Distance", pch = 16, ...), ellipsesPlot.covfm(x, ...), { strip <- paste(mod.names[1], "Distance vs.", mod.names[2], "Distance") ddPlot.covfm(x, strip = strip, xlab = paste(mod.names[2], "Distance"), ylab = paste(mod.names[1], "Distance"), main = "Distance-Distance Plot", pch = 16, ...) } ) } } invisible(x) }
imageClusterPipeline <- function(images, cluster.method = "hist", distance.method = "emd", lower = c(0, 140 / 255, 0), upper = c(60 / 255, 1, 60 / 255), hist.bins = 3, kmeans.bins = 27, bin.avg = TRUE, norm.pix = FALSE, plot.bins = FALSE, pausing = TRUE, color.space = "rgb", ref.white, from = "sRGB", bounds = c(0, 1), sample.size = 20000, iter.max = 50, nstart = 5, img.type = FALSE, ordering = "default", size.weight = 0.5, color.weight = 0.5, plot.heatmap = TRUE, return.distance.matrix = TRUE, save.tree = FALSE, save.distance.matrix = FALSE, a.bounds = c(-127, 128), b.bounds = c(-127, 128)) { color.space <- tolower(color.space) if (color.space == "hsv") { hsv <- TRUE } else { hsv <- FALSE } if (!is.character(images)) { stop("'images' argument must be a string (folder containing the images),", " a vector of strings (paths to individual images),", " or a combination of both") } im.paths <- c() if (length(which(dir.exists(images))) >= 1) { im.paths <- unlist(sapply(images[dir.exists(images)], getImagePaths), use.names = FALSE) } im.paths <- c(im.paths, images[!dir.exists(images)][file.exists(images[!dir.exists(images)])]) im.paths <- im.paths[grep(x = im.paths, pattern = "[.][jpg.|jpeg.|png.]", ignore.case = TRUE)] message(paste(length(im.paths), "images")) if (cluster.method == "hist") { message("Pixel binning method: histogram (predetermined bins)") message("Binning images...") if (color.space == "lab") { cluster.list <- getLabHistList(im.paths, bins = hist.bins, bin.avg = bin.avg, lower = lower, upper = upper, plotting = plot.bins, from = from, ref.white = ref.white, pausing = pausing, sample.size = sample.size, a.bounds = a.bounds, b.bounds = b.bounds) } else { cluster.list <- getHistList(im.paths, bins = hist.bins, bin.avg = bin.avg, lower = lower, upper = upper, norm.pix = norm.pix, plotting = plot.bins, pausing = pausing, hsv = hsv, bounds = bounds, img.type = img.type) } } else if (cluster.method == "kmeans") { message("Pixel binning method: kmeans (algorithmically determined bins)") message("Generating clusters...") cluster.list <- getKMeansList(im.paths, bins = kmeans.bins, sample.size = sample.size, plotting = plot.bins, color.space = color.space, lower = lower, upper = upper, iter.max = iter.max, nstart = nstart, img.type = img.type, ref.white = ref.white) cluster.list <- extractClusters(cluster.list, ordering = FALSE, normalize = norm.pix) } else { stop("cluster.method must be one of either 'hist' or 'kmeans'") } message(paste("\nComparison metric for distance matrix:", distance.method)) message("\nCalculating distance matrix...") distance.matrix <- getColorDistanceMatrix(cluster.list, method = distance.method, ordering = ordering, plotting = plot.heatmap, size.weight = size.weight, color.weight = color.weight) message("Done") if (save.tree != FALSE) { if (is.character(save.tree)) { if (dir.exists(save.tree)) { save.tree <- paste(save.tree, "/ColorTree.newick", sep = "") message(paste("No output filename specified, saving as", save.tree)) } } else if (save.tree) { save.tree <- "./ColorTree.newick" message("No output filename specified; saving as 'ColorTree.newick'") } else { stop("save.tree must be either a valid path or a logical") } exportTree(distance.matrix, file = save.tree) message(paste("Color dendrogram saved to", normalizePath(save.tree))) } if (save.distance.matrix != FALSE) { if (is.character(save.distance.matrix)) { if (dir.exists(save.distance.matrix)) { save.distance.matrix <- paste(save.distance.matrix, "/ColorDistanceMatrix.csv", sep = "") message(paste("No output filename specified, saving as", save.distance.matrix)) } } else if (save.distance.matrix) { save.distance.matrix <- "./ColorDistanceMatrix.csv" message("No output filename specified;", " saving as 'ColorDistanceMatrix.csv'") } else { stop("save.distance.matrix must be either a valid path or a logical") } write.csv(distance.matrix, file = save.distance.matrix) message(paste("Color distance matrix saved to", normalizePath(save.distance.matrix))) } if (return.distance.matrix) { return(distance.matrix) } }
as_track <- function(x, ...) { UseMethod("as_track", x) } as_track.SpatialPoints <- function(x, ...) { xx <- sp::coordinates(x) track(x = xx[, 1], y = xx[, 2], crs = sf::st_crs(sp::proj4string(x))) } as_track.sfc_POINT <- function(x, ...) { xx <- sf::st_coordinates(x) track(x = xx[, 1], y = xx[, 2], crs = sf::st_crs(x)) } as_track.steps_xyt <- function(x, ...) { n <- nrow(x) crs <- get_crs(x) if ("burst_" %in% names(x)) { xx <- tidyr::nest(x, data = -c(burst_)) %>% dplyr::mutate(data = purrr::map(data, function(y) { n1 <- nrow(y) tibble::tibble( xs = c(y$x1_, y$x2_[n1]), ys = c(y$y1_, y$y2_[n1]), t = c(y$t1_, y$t2_[n1]) ) })) %>% tidyr::unnest(cols = data) make_track(xx, xs, ys, t, burst_ = burst_, crs = crs) } else { xx <- tibble::tibble( xs = c(x$x1_, x$x2_[n]), ys = c(x$y1_, x$y2_[n]), t = c(x$t1_, x$t2_[n]) ) make_track(xx, xs, ys, t, crs = crs) } } as_track.data.frame <- function(x, ...) { cols <- colnames(x) if("x_" %in% cols & "y_" %in% cols & !("t_" %in% cols)) { make_track(x, .x = x_, .y = y_, ...) } else { if("x_" %in% cols & "y_" %in% cols & "t_" %in% cols) { make_track(x, .x = x_, .y = y_, .t = t_, ...) } } }
summary.rbga <- function(object, echo=FALSE, ...) { rbga.object = object output = paste( "GA Settings", "\n", " Type = ", rbga.object$type, "\n", " Population size = ", rbga.object$popSize, "\n", " Number of Generations = ", rbga.object$iters, "\n", " Elitism = ", rbga.object$elitism, "\n", " Mutation Chance = ", rbga.object$mutationChance, "\n", "\n", "Search Domain", "\n", sep="") for (var in 1:length(rbga.object$stringMin)) { minVar = rbga.object$stringMin[var] maxVar = rbga.object$stringMax[var] output = paste(output, " Var ", var, " = [", minVar, ",", maxVar, "]\n", sep=""); } output = paste(output, "\n", sep=""); if (!is.null(rbga.object$suggestions)) { optionPart = paste("Suggestions", "\n", sep=""); for (suggestion in 1:dim(rbga.object$suggestions)[1]) { optionPart = paste(optionPart, " ", suggestion, " = (", sep=""); for (var in 1:(dim(rbga.object$suggestions)[2]-1)) { optionPart = paste(optionPart, rbga.object$suggestions[suggestion,var], ", ", sep=""); } optionPart = paste(optionPart, rbga.object$suggestions[suggestion,dim(rbga.object$suggestions)[2]], ")\n", sep=""); } output = paste(output, optionPart, "\n", sep=""); } if (!is.null(rbga.object$population)) { optionPart = paste("GA Results", "\n", " Best Solution : ", sep=""); filter = rbga.object$evaluations == min(rbga.object$evaluations); bestObjectCount = sum(rep(1, rbga.object$popSize)[filter]); if (bestObjectCount > 1) { bestSolution = rbga.object$population[filter,][1,]; } else { bestSolution = rbga.object$population[filter,]; } for (var in 1:length(bestSolution)) { optionPart = paste(optionPart, bestSolution[var], " ", sep=""); } output = paste(output, optionPart, "\n", sep=""); } if (echo) cat(output); invisible(output); }
etry <- function(expr, silent = FALSE, outFile = getOption("try.outFile", default = stderr()), max.lines = 100L, dump.frames = c("partial", "full", "full_global", "no")) { dump.frames <- match.arg(dump.frames) TB <- NULL DP <- list() tryCatch( withCallingHandlers(expr, error = function(e) { if ("max.lines" %in% names(formals(.traceback))) { TB <<- do.call(.traceback, list(x = 4L, max.lines = max.lines)) } else { opt_bak <- options(deparse.max.lines = max.lines) on.exit(options(opt_bak)) TB <<- do.call(.traceback, list(x = 4L)) } if (dump.frames != "no") { calls <- sys.calls() DP <<- sys.frames() names(DP) <<- limitedLabels(calls) if (dump.frames == "full_global") { DP <<- c(.GlobalEnv = as.environment(as.list(.GlobalEnv, all.names = TRUE)), DP) } DP <<- DP[-c(length(DP) - 1L, length(DP))] } attr(DP, "error.message") <<- paste0(conditionMessage(e), "\n\n") class(DP) <<- "dump.frames" }), error = function(e) { if (dump.frames == "partial") { nc <- length(sys.calls()) idx2drop <- seq_len(nc - 5L) } else if (dump.frames == "no") { idx2drop <- seq_along(DP) } else { idx2drop <- integer() } DP[idx2drop] <<- NULL ret <- structure(paste0("Error: ", conditionMessage(e)), class = c("etry-error", "try-error"), condition = e, traceback = TB, dump.frames = DP) if (!silent && isTRUE(getOption("show.error.messages"))) { cat(capture.output(print(ret)), file = outFile, sep = "\n") } invisible(ret) } ) } `print.etry-error` <- function(x, max.lines = getOption("traceback.max.lines", getOption("deparse.max.lines", -1L)), ...) { cat(paste0(x, "\n\nTraceback:\n")) n <- length(xx <- attr(x, "traceback")) if (n == 0L) cat(gettext("No traceback available"), "\n") else { for (i in 1L:n) { xi <- xx[[i]] label <- paste0(n - i + 1L, ": ") m <- length(xi) srcloc <- if (!is.null(srcref <- attr(xi, "srcref"))) { srcfile <- attr(srcref, "srcfile") paste0(" at ", basename(srcfile$filename), " srcref[1L]) } if (is.numeric(max.lines) && max.lines > 0L && max.lines < m) { xi <- c(xi[seq_len(max.lines)], " ...") m <- length(xi) } else if (isTRUE(attr(xi, 'truncated'))) { xi <- c(xi, " ...") m <- length(xi) } if (!is.null(srcloc)) { xi[m] <- paste0(xi[m], srcloc) } if (m > 1) label <- c(label, rep(substr(" ", 1L, nchar(label, type = "w")), m - 1L)) cat(paste0(label, xi), sep = "\n") } } if (length(attr(x, "dump.frames"))) cat(paste0("\nCrash dump avilable. Use 'debugger(attr(*, \"dump.frames\"))' for debugging.\n")) invisible() }
check_G_mat <- function(gmat){ .Call('kmcRCPP_RevCHECK',PACKAGE='kmc',gmat) } lambdaoo<-function(kmctime,delta,lambda,gtmat){ .Call('kmcomegalambda', PACKAGE = 'kmc',kmctime,delta,lambda,gtmat) } kmcdata_rcpp<-function(kmctime,delta,lambda,gtmat){ .Call('kmcRCPP_KMCDATA', PACKAGE = 'kmc',kmctime,delta,lambda,gtmat) } kmc_routine4<-function( delta, lambda, gtmat ){ np=as.integer(dim(gtmat)) chk=numeric(np[1]) delta=as.integer(delta) lambda=as.vector(lambda); gtmat=as.numeric(gtmat) re=.C( "nocopy_kmc_data", delta,gtmat,lambda,np,chk ) return(re[[5]]); } kmc_find0loc <- function(d){ re=1L; d=as.integer(d); n=as.integer(length(d)); return(.C("locLastZero",d,n,re)[[3]]); }
source('Schelde_pars.R') FNAResidual <- function (tt, state, dy, parms, scenario = "B1") { with (as.list(c(state, dy, parms)), { pH <- -log10(H*1e-6) TA <- HCO3 + 2*CO3 + NH3 - H SumCO2 <- CO2 + HCO3 + CO3 SumNH4 <- NH4 + NH3 ECO2 <- KL * (CO2sat - CO2) EO2 <- KL * (O2sat - O2) ENH3 <- KL * (NH3sat - NH3) TO2 <- Transport(O2, O2_up, O2_down) TNO3 <- Transport(NO3, NO3_up, NO3_down) TTA <- Transport(TA, TA_up, TA_down) TSumCO2 <- Transport(SumCO2, SumCO2_up, SumCO2_down) TSumNH4 <- Transport(SumNH4, SumNH4_up, SumNH4_down) if (scenario == "A" && tt > 365) { TOM <- Transport(OM, OM_up_A, OM_down) } else TOM <- Transport(OM, OM_up , OM_down) if (scenario == "B1" && (tt > 360 && tt < 370)) { AddNH4NO3 <- SpillNH4NO3 } else AddNH4NO3 <- 0 if (scenario == "C" && (tt > 360 && tt < 370)) { AddNH3 <- SpillNH3 } else AddNH3 <- 0 ROx <- rOM * OM * (O2/(O2 + ksO2)) ROxCarbon <- ROx * C_Nratio RNit <- rNitri * NH4 * (O2/(O2 + ksO2)) ROM <- - dOM + TOM - ROx RO2 <- - dO2 + TO2 + EO2 - ROxCarbon - 2*RNit RNO3 <- - dNO3 + TNO3 + RNit + AddNH4NO3 RSumCO2 <- -dCO2 -dHCO3 -dCO3 + TSumCO2 + ECO2 + ROxCarbon RSumNH4 <- -dNH3 -dNH4 + TSumNH4 + ENH3 + ROx - RNit + AddNH3 + AddNH4NO3 RTA <- -dHCO3-2*dCO3-dNH3 +dH + TTA + ENH3 + ROx - 2*RNit + AddNH3 EquiCO2 <- H * HCO3 - K1CO2 * CO2 EquiHCO3<- H * CO3 - K2CO2 * HCO3 EquiNH4 <- H * NH3 - KNH4 * NH4 return(list(c(ROM, RO2, RNO3, RSumCO2, RSumNH4, RTA, EquiCO2, EquiHCO3, EquiNH4), c(pH = pH, TA = TA, SumCO2 = SumCO2, SumNH4 = SumNH4))) }) } TA_up <- TA_estimate(pH_up, SumCO2_up, SumNH4_up) TA_down <- TA_estimate(pH_down, SumCO2_down, SumNH4_down) H_ini <- 10^-pH_ini * 1e6 H <- H_ini NH3_ini <- KNH4/(KNH4+H)*SumNH4_ini NH4_ini <- SumNH4_ini - NH3_ini CO2_ini <- H*H/(H*K1CO2 + H*H + K1CO2*K2CO2)*SumCO2_ini HCO3_ini <- H*K1CO2/(H*K1CO2 + H*H + K1CO2*K2CO2)*SumCO2_ini CO3_ini <- K1CO2*K2CO2/(H*K1CO2 + H*H + K1CO2*K2CO2)*SumCO2_ini TA_ini <- HCO3_ini + 2*CO3_ini + NH3_ini - H_ini y <- c(OM = OM_ini, O2 = O2_ini, NO3 = NO3_ini, H = H_ini, NH4 = NH4_ini, NH3 = NH3_ini, CO2 = CO2_ini, HCO3 = HCO3_ini, CO3 = CO3_ini) dy <- c(dOM = 0, dO2 = 0, dNO3 = 0, dH = 0, dNH4 = 0, dNH3 = 0, dCO2 = 0, dHCO3 = 0, dCO3 = 0) times <- c(0, 350:405) outA <- daspk(y = y, times, res = FNAResidual, dy = dy, nalg = 3, parms = phPars, scenario = "A", hmax = 1) outB <- daspk(y = y, times, res = FNAResidual, dy = dy, nalg = 3, parms = phPars, scenario = "B1", hmax = 1) outC <- daspk(y = y, times, res = FNAResidual, dy = dy, nalg = 3, parms = phPars, scenario = "C", hmax = 1) par(mfrow = c(3, 4), mar = c(1, 2, 2, 1), oma = c(3, 3, 3, 0)) Selection <- c("pH","TA","SumCO2","O2") plot(outA, mfrow = NULL, xlim = c(350,405), type = "l", xaxt = "n", which = Selection) plot(outB, mfrow = NULL, xlim = c(350,405), type = "l", xaxt = "n", which = Selection) plot(outC, mfrow = NULL, xlim = c(350,405), type = "l", xaxt = "n", which = Selection) mtext(side = 1, outer = TRUE, "time, d", line = 2, cex = 1.2) mtext(side = 2, at = 0.2, outer = TRUE, "Scenario C", line = 1.5, cex = 1.2) mtext(side = 2, at = 0.5, outer = TRUE, "Scenario B", line = 1.5, cex = 1.2) mtext(side = 2, at = 0.8, outer = TRUE, "Scenario A", line = 1.5, cex = 1.2) mtext(side = 3, at = 0.125, outer = TRUE, "pH, -", line = 1, cex = 1.2) mtext(side = 3, at = 0.375, outer = TRUE, "TA, mol/kg", line = 1, cex = 1.2) mtext(side = 3, at = 1-0.375, outer = TRUE, "CO2, mol/kg", line = 1, cex = 1.2) mtext(side = 3, at = 1-0.125, outer = TRUE, "O2, mol/kg", line = 1, cex = 1.2)
path_precommit_exec <- function(check_if_exists = TRUE) { final <- getOption("precommit.executable") %>% as.character() if (!check_if_exists) { return(final) } if (!file_exists(final)) { rlang::abort(paste0( "pre-commit executable does not exist at ", final, ". Please locate your pre-commit ", "executable and set the R option `precommit.executable` to this ", "path so it can be used to perform various pre-commit commands from R." )) } final } path_pre_commit_exec <- function(check_if_exists = TRUE) { .Deprecated("path_precommit_exec", old = "path_pre_commit_exec") path_precommit_exec(check_if_exists = check_if_exists) } path_derive_precommit_exec <- function() { path <- path_derive_precommit_exec_path() os <- tolower(Sys.info()[["sysname"]]) if (os == "darwin") { path <- c(path, path_derive_precommit_exec_macOS()) } else if (os == "windows") { path <- c(path, path_derive_precommit_exec_win()) } else if (os == "linux") { path <- c(path, path_derive_precommit_exec_linux()) } path <- unique(path[path != ""]) if (length(path) == 0) { path_derive_precommit_exec_conda() } else if (length(path) == 1) { path } else { path_warn_multiple_execs(path) path[1] } } path_derive_precommit_exec_impl <- function(candidate) { existant <- path_candidate_to_actual(candidate) if (length(existant) >= 1) { existant } else { "" } } path_warn_multiple_execs <- function(paths) { rlang::warn(paste0( "We detected multiple pre-commit executables. This is likely ", "going to get you into trouble in the future, e.g. when you want to ", "upgrade, as you easily loose track of different versions. We strongly ", "suggest to only keep one pre-commit executable and uninstall (or delete) ", "the other ones. Here are the locations where we detected executables:\n\n", "- ", paste0(paths, collapse = "\n- "), "\n\n", "Note that in all local repos where you used pre-commit, the executable ", "path is hardcoded (in .git/hooks/pre-commit). Deleting a referenced ", "executable will break pre-commit for that local repo. A simple ", "re-initialization with `precommit::use_precommit()` or ", "`$ pre-commit install` will fix this for pre-commit hooks.\n\nIf you ", "have hook types other than pre-commit such as pre-push (you can check ", "which files are in .git/hooks/), you need to name the type and use the ", "command line, i.e. `$ pre-commit install -t pre-push`. " )) } path_candidate_to_actual <- function(candidate) { assumed <- fs::path(candidate, precommit_executable_file()) assumed[file_exists(assumed)] } path_derive_precommit_exec_linux <- function() { path_derive_precommit_exec_impl( path_if_exist(fs::path_home(".local/bin")) ) } path_derive_precommit_exec_win <- function() { path_derive_precommit_exec_impl(c( path_derive_precommit_exec_win_python3plus_base(), fs::path_home("AppData/Roaming/Python/Scripts") )) } path_derive_precommit_exec_win_python3plus_base <- function() { path_derive_precommit_exec_win_python3plus_candidates() %>% sort(decreasing = TRUE) %>% fs::path("Scripts") } path_derive_precommit_exec_win_python3plus_candidates <- function() { fs::dir_ls(path_if_exist(fs::path_home("AppData/Roaming/Python/")), regexp = "Python[0-9]+$") } path_derive_precommit_exec_macOS <- function() { path_derive_precommit_exec_macOS_candidates() %>% path_derive_precommit_exec_impl() } path_derive_precommit_exec_macOS_candidates <- function() { candidate_system <- fs::dir_ls( path_if_exist("/Library/Frameworks/Python.framework/Versions/"), regexp = "[0-9]$" ) candidate_user <- fs::dir_ls(path_if_exist("~/Library/Python/")) c( fs::path(sort(candidate_user, decreasing = TRUE), "bin"), fs::path(sort(candidate_system, decreasing = TRUE), "bin"), "/usr/local/bin", "/opt/homebrew/bin" ) } path_derive_precommit_exec_path <- function() { unname(Sys.which(precommit_executable_file())) } path_derive_precommit_exec_conda <- function() { path <- path_derive_precommit_exec_conda_impl("r-precommit") if (path == "") { path <- path_derive_precommit_exec_conda_impl("r-reticulate") if (path != "") { rlang::warn(paste0( "The R packae {precommit} now requires the executable to live ", "in the conda environment r-precommit, not r-reticulate anymore ", "where it is currently installed. ", "Please run `precommit::install_precommit(force = TRUE)` to re-install with conda ", "or choose another installation method as described in the README. To save ", "space on disk, you probably want to delete the pre-commit executable at ", path, " and the package sources in the ", "conda environment r-reticulate with ", "`reticulate::conda_remove('r-reticulate', 'pre-commit')`." )) } } path } path_derive_precommit_exec_conda_impl <- function(conda_env) { tryCatch( { ls <- reticulate::conda_list() path_reticulate <- fs::path_dir(ls[ls$name == conda_env, "python"][1]) derived <- fs::path( path_reticulate, ifelse(is_windows(), "Scripts", ""), precommit_executable_file() ) unname(ifelse(file_exists(derived), derived, "")) }, error = function(e) "" ) } precommit_executable_file <- function() { ifelse(is_windows(), "pre-commit.exe", "pre-commit") }
plot.wmat<-function(x, main="Preferences", ylab="Estimate", psymb=NULL, pcol=NULL, ylim = range(worthmat),log="", ...) { worthmat<-x coeff<-unclass(worthmat) objnames<-rownames(coeff) grnames<-colnames(coeff) if(length(grep(":",grnames))){ gr.lines<-unlist(strsplit(grnames[1],":")) ngrlin<-length(gr.lines)-0.5 grnames<-gsub(":","\n",grnames) } else ngrlin <- 1 nobj<-dim(coeff)[1] ngroups<-dim(coeff)[2] if (ngroups == 1) colnames(coeff) <- "" if (is.null(psymb)) psymb<-rep(16,nobj) if (is.null(pcol)) farbe <- rainbow_hcl(nobj) else if (length(pcol)>1) farbe <- pcol else if(pcol=="black") farbe <- "black" else if(pcol %in% c("heat","terrain")) farbe <- eval(call(paste(pcol,"_hcl",sep="",collapse=""), nobj)) else if(pcol=="gray") farbe <- eval(call(paste(pcol,".colors",sep="",collapse=""), nobj)) else farbe <- rainbow_hcl(nobj) pomi <- c(0.2,0.2,0.5,0.2) if (!(all(pomi==par("omi")))) par(omi = pomi, mar=c(3,4,0.1,0) ) plot(c(0.5,ngroups+0.5),c(min(coeff),max(coeff)),type="n",axes=FALSE, xlab="",ylab=ylab,ylim=ylim,log=log,...) title(main,outer=TRUE) box() axis(2) axis(1,at=1:ngroups,labels=grnames,mgp=c(3,ngrlin,0)) adj<-1/nchar(as.character(objnames)) adj<-strwidth(as.character(objnames))/2 d<-strwidth("d") adj<-adj+d for (i in 1:ngroups) { pm<-rep(c(1,-1),nobj) pm<-pm[1:nobj] o<-order(coeff[1:nobj,i]) sadj<-adj[o] sobjnames<-objnames[o] spsymb<-psymb[o] sfarbe<-farbe[o] scoeff<-sort(coeff[,i]) x<-rep(i,nobj) xy <- xy.coords(x, scoeff) lines(c(i,i), range(scoeff), ...) points(xy, pch=spsymb, cex=1.5, col=sfarbe) text(x+sadj*pm,scoeff,sobjnames) } }
library(vcfR) context("write.vcf R functions") test_that("read/write.vcf works for vcfR objects",{ data("vcfR_example") test_dir <- tempdir() setwd(test_dir) write.vcf(vcf, "test.vcf.gz") test <- read.vcfR("test.vcf.gz", verbose = FALSE) unlink("test.vcf.gz") expect_is(test, "vcfR") expect_identical(colnames(test@fix)[1], "CHROM") expect_equal(nrow(test@gt), nrow(vcf@gt)) expect_equal(ncol(test@gt), ncol(vcf@gt)) }) test_that("write.vcf.gz works for Chrom objects",{ data("chromR_example") test_dir <- tempdir() setwd(test_dir) write.vcf(chrom, "test.vcf.gz") test <- read.vcfR("test.vcf.gz", verbose = FALSE) unlink("test.vcf.gz") expect_is(test, "vcfR") expect_identical(colnames(test@fix)[1], "CHROM") expect_equal(nrow(test@gt), nrow(vcf@gt)) expect_equal(ncol(test@gt), ncol(vcf@gt)) }) test_that("write.vcf.gz works for Chrom objects with mask",{ data("chromR_example") test_dir <- tempdir() setwd(test_dir) [email protected]$mask <- FALSE [email protected]$mask[1:50] <- TRUE write.vcf(chrom, "test.vcf.gz", mask=TRUE) test <- read.vcfR("test.vcf.gz", verbose = FALSE) unlink("test.vcf.gz") [email protected]$mask <- TRUE expect_is(test, "vcfR") expect_identical(colnames(test@fix)[1], "CHROM") expect_equal(ncol(test@gt), ncol(vcf@gt)) expect_equal( nrow(test@fix), 50 ) }) test_that("write.var.info works for chromR objects",{ data("chromR_example") test_dir <- tempdir() setwd(test_dir) write.var.info(chrom, "test.csv") test <- read.table("test.csv", header=TRUE, sep=",") unlink("test.csv") expect_is(test, "data.frame") expect_equal(nrow(test), nrow(vcf@fix)) expect_equal(length(grep("CHROM", colnames(test))), 1) expect_equal(length(grep("POS", colnames(test))), 1) expect_equal(length(grep("mask", colnames(test))), 1) }) test_that("write.win.info works for Chrom objects",{ data("chromR_example") chrom <- proc.chromR(chrom, verbose = FALSE) test_dir <- tempdir() setwd(test_dir) write.win.info(chrom, "test.csv") test <- read.table("test.csv", header=TRUE, sep=",") unlink("test.csv") expect_is(test, "data.frame") expect_equal(nrow(test), nrow([email protected])) expect_equal(grep("CHROM", names(test), value=TRUE), "CHROM") expect_equal(grep("window", names(test), value=TRUE), "window") expect_equal(grep("start", names(test), value=TRUE), "start") expect_equal(grep("end", names(test), value=TRUE), "end") })
NULL rray_logical_and <- function(x, y) { out <- rray__logical_and(x, y) container <- vec_ptype_container2(x, y) vec_cast_container(out, container) } rray_logical_or <- function(x, y) { out <- rray__logical_or(x, y) container <- vec_ptype_container2(x, y) vec_cast_container(out, container) } rray_logical_not <- function(x) { out <- rray__logical_not(x) container <- vec_ptype_container(x) vec_cast_container(out, container) } rray_any <- function(x, axes = NULL) { axes <- vec_cast(axes, integer()) validate_axes(axes, x) res <- rray__any(x, as_cpp_idx(axes)) vec_cast_container(res, x) } rray_all <- function(x, axes = NULL) { axes <- vec_cast(axes, integer()) validate_axes(axes, x) res <- rray__all(x, as_cpp_idx(axes)) vec_cast_container(res, x) } rray_if_else <- function(condition, true, false) { out <- rray__if_else(condition, true, false) container <- vec_ptype_container2(true, false) vec_cast_container(out, container) }
NULL nba_fantasywidget <- function(active_players='N', date_from='', date_to='', last_n_games=0, league_id='00', location='', month='', opponent_team_id = '', po_round='', player_id='', position='', season='2019-20', season_segment='', season_type='Regular Season', team_id='', todays_opponent=0, todays_players='N', vs_conference='', vs_division=''){ season_type <- gsub(' ','+',season_type) version <- "fantasywidget" endpoint <- nba_endpoint(version) full_url <- paste0(endpoint, "?ActivePlayers=", active_players, "&DateFrom=",date_from, "&DateTo=",date_to, "&LastNGames=", last_n_games, "&LeagueID=",league_id, "&Location=",location, "&Month=",month, "&OpponentTeamID=", opponent_team_id, "&PORound=",po_round, "&PlayerID=",player_id, "&Position=",position, "&Season=",season, "&SeasonSegment=",season_segment, "&SeasonType=",season_type, "&TeamID=",team_id, "&TodaysOpponent=",todays_opponent, "&TodaysPlayers=",todays_players, "&VsConference=",vs_conference, "&VsDivision=",vs_division) tryCatch( expr={ resp <- full_url %>% .nba_headers() df_list <- purrr::map(1:length(resp$resultSets$name), function(x){ data <- resp$resultSets$rowSet[[x]] %>% data.frame(stringsAsFactors = F) %>% as_tibble() json_names <- resp$resultSets$headers[[x]] colnames(data) <- json_names return(data) }) names(df_list) <- resp$resultSets$name }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no fantasy widget data for {season} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } NULL nba_leaguedashlineups <- function( conference = '', date_from = '', date_to = '', division = '', game_segment = '', group_quantity=5, last_n_games=0, league_id='00', location='', measure_type='Base', month=0, opponent_team_id=0, outcome='', po_round='', pace_adjust='N', per_mode='Totals', period=0, plus_minus='N', rank='N', season='2020-21', season_segment='', season_type='Regular Season', shot_clock_range='', team_id='', vs_conference='', vs_division=''){ season_type <- gsub(' ','+',season_type) version <- "leaguedashlineups" endpoint <- nba_endpoint(version) full_url <- paste0(endpoint, "?Conference=", conference, "&DateFrom=", date_from, "&DateTo=", date_to, "&Division=", division, "&GameSegment=", game_segment, "&GroupQuantity=", group_quantity, "&LastNGames=", last_n_games, "&LeagueID=", league_id, "&Location=", location, "&MeasureType=", measure_type, "&Month=", month, "&OpponentTeamID=", opponent_team_id, "&Outcome=", outcome, "&PORound=", po_round, "&PaceAdjust=", pace_adjust, "&PerMode=", per_mode, "&Period=", period, "&PlusMinus=", plus_minus, "&Rank=", rank, "&Season=", season, "&SeasonSegment=", season_segment, "&SeasonType=", season_type, "&ShotClockRange=",shot_clock_range, "&TeamID=", team_id, "&VsConference=", vs_conference, "&VsDivision=", vs_division) tryCatch( expr={ resp <- full_url %>% .nba_headers() df_list <- purrr::map(1:length(resp$resultSets$name), function(x){ data <- resp$resultSets$rowSet[[x]] %>% data.frame(stringsAsFactors = F) %>% as_tibble() json_names <- resp$resultSets$headers[[x]] colnames(data) <- json_names return(data) }) names(df_list) <- resp$resultSets$name }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no league dashboard lineups data for {season} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } NULL nba_leaguelineupviz <- function( conference = '', date_from = '', date_to = '', division = '', game_segment = '', group_quantity=5, last_n_games=0, league_id='00', location='', measure_type='Base', minutes_min = 10, month=0, opponent_team_id=0, outcome='', po_round='', pace_adjust='N', per_mode='Totals', period=0, plus_minus='N', rank='N', season='2020-21', season_segment='', season_type='Regular Season', shot_clock_range='', team_id='', vs_conference='', vs_division=''){ season_type <- gsub(' ','+',season_type) version <- "leaguelineupviz" endpoint <- nba_endpoint(version) full_url <- paste0(endpoint, "?Conference=", conference, "&DateFrom=", date_from, "&DateTo=", date_to, "&Division=", division, "&GameSegment=", game_segment, "&GroupQuantity=", group_quantity, "&LastNGames=", last_n_games, "&LeagueID=", league_id, "&Location=", location, "&MeasureType=", measure_type, "&MinutesMin=", minutes_min, "&Month=", month, "&OpponentTeamID=", opponent_team_id, "&Outcome=", outcome, "&PORound=", po_round, "&PaceAdjust=", pace_adjust, "&PerMode=", per_mode, "&Period=", period, "&PlusMinus=", plus_minus, "&Rank=", rank, "&Season=", season, "&SeasonSegment=", season_segment, "&SeasonType=", season_type, "&ShotClockRange=",shot_clock_range, "&TeamID=", team_id, "&VsConference=", vs_conference, "&VsDivision=", vs_division) tryCatch( expr={ resp <- full_url %>% .nba_headers() df_list <- purrr::map(1:length(resp$resultSets$name), function(x){ data <- resp$resultSets$rowSet[[x]] %>% data.frame(stringsAsFactors = F) %>% as_tibble() json_names <- resp$resultSets$headers[[x]] colnames(data) <- json_names return(data) }) names(df_list) <- resp$resultSets$name }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no league lineup viz data for {season} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } NULL nba_leagueplayerondetails <- function( date_from = '', date_to = '', game_segment = '', last_n_games=0, league_id='00', location='', measure_type='Base', month=0, opponent_team_id=0, outcome='', pace_adjust='N', per_mode='Totals', period=0, plus_minus='N', rank='N', season='2020-21', season_segment='', season_type='Regular Season', team_id='1610612749', vs_conference='', vs_division=''){ season_type <- gsub(' ','+',season_type) version <- "leagueplayerondetails" endpoint <- nba_endpoint(version) full_url <- paste0(endpoint, "?DateFrom=", date_from, "&DateTo=", date_to, "&GameSegment=", game_segment, "&LastNGames=", last_n_games, "&LeagueID=", league_id, "&Location=", location, "&MeasureType=", measure_type, "&Month=", month, "&OpponentTeamID=", opponent_team_id, "&Outcome=", outcome, "&PaceAdjust=", pace_adjust, "&PerMode=", per_mode, "&Period=", period, "&PlusMinus=", plus_minus, "&Rank=", rank, "&Season=", season, "&SeasonSegment=", season_segment, "&SeasonType=", season_type, "&TeamID=", team_id, "&VsConference=", vs_conference, "&VsDivision=", vs_division) tryCatch( expr={ resp <- full_url %>% .nba_headers() df_list <- purrr::map(1:length(resp$resultSets$name), function(x){ data <- resp$resultSets$rowSet[[x]] %>% data.frame(stringsAsFactors = F) %>% as_tibble() json_names <- resp$resultSets$headers[[x]] colnames(data) <- json_names return(data) }) names(df_list) <- resp$resultSets$name }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no league player on/off details data for {season} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } NULL nba_leagueseasonmatchups <- function( def_player_id='', def_team_id='', league_id='00', off_player_id='', off_team_id='', per_mode='Totals', season='2020-21', season_type='Regular Season'){ season_type <- gsub(' ','+',season_type) version <- "leagueseasonmatchups" endpoint <- nba_endpoint(version) full_url <- paste0(endpoint, "?DefPlayerID=", def_player_id, "&DefTeamID=", def_team_id, "&LeagueID=", league_id, "&OffPlayerID=", off_player_id, "&OffTeamID=", off_team_id, "&PerMode=", per_mode, "&Season=", season, "&SeasonType=", season_type) tryCatch( expr={ resp <- full_url %>% .nba_headers() df_list <- purrr::map(1:length(resp$resultSets$name), function(x){ data <- resp$resultSets$rowSet[[x]] %>% data.frame(stringsAsFactors = F) %>% as_tibble() json_names <- resp$resultSets$headers[[x]] colnames(data) <- json_names return(data) }) names(df_list) <- resp$resultSets$name }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no league season matchups data for {season} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) } NULL nba_matchupsrollup <- function( def_player_id='', def_team_id='', league_id='00', off_player_id='', off_team_id='', per_mode='Totals', season='2020-21', season_type='Regular Season'){ season_type <- gsub(' ','+',season_type) version <- "matchupsrollup" endpoint <- nba_endpoint(version) full_url <- paste0(endpoint, "?DefPlayerID=", def_player_id, "&DefTeamID=", def_team_id, "&LeagueID=", league_id, "&OffPlayerID=", off_player_id, "&OffTeamID=", off_team_id, "&PerMode=", per_mode, "&Season=", season, "&SeasonType=", season_type) tryCatch( expr={ resp <- full_url %>% .nba_headers() df_list <- purrr::map(1:length(resp$resultSets$name), function(x){ data <- resp$resultSets$rowSet[[x]] %>% data.frame(stringsAsFactors = F) %>% as_tibble() json_names <- resp$resultSets$headers[[x]] colnames(data) <- json_names return(data) }) names(df_list) <- resp$resultSets$name }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid arguments or no matchups rollup data for {season} available!")) }, warning = function(w) { }, finally = { } ) return(df_list) }
QueryCountWorker <- R6::R6Class( "QueryCountWorker", private = list( defn = NA, data = NA, stateful = FALSE ) , public = list( initialize = function(defn, data, stateful = FALSE) { private$defn <- defn private$data <- data stopifnot(self$kosher()) }, getStateful = function() { private$stateful }, kosher = function() { TRUE }, queryCount = function() { data <- private$data filter_expr <- eval(parse(text = paste("rlang::expr(", private$defn$filterCondition, ")"))) data %>% dplyr::filter(!! filter_expr) %>% nrow() } ) ) QueryCountMaster <- R6::R6Class( "QueryCountMaster", private = list( defn = NA, dry_run = FALSE, sites = list(), mapFn = function(site) { payload <- list(objectId = site$instanceId, method = "queryCount") q <- httr::POST(.makeOpencpuURL(urlPrefix=site$url, fn="executeMethod"), body = jsonlite::toJSON(payload), httr::add_headers("Content-Type" = "application/json"), config = getConfig()$sslConfig ) .deSerialize(q) }, result_cache = list(), debug = FALSE ), public = list( initialize = function(defn, debug = FALSE) { 'Initialize the object with a dataset' private$defn <- defn private$debug <- debug stopifnot(self$kosher()) }, kosher = function() { ' Check for appropriateness' TRUE }, queryCount = function() { 'Compute the count' sites <- private$sites if (private$dry_run) { mapFn <- function(x) x$worker$queryCount() } else { mapFn <- private$mapFn } results <- Map(mapFn, sites) value <- Reduce(f = sum, results) if (private$debug) { print("value") print(value) } value }, getSites = function() { private$sites }, addSite = function(name, url = NULL, worker = NULL) { stopifnot(is.null(url) || is.null(worker)) n <- length(private$sites) if (is.null(url)) { private$dry_run <- private$dry_run || TRUE private$sites[[n+1]] <- list(name = name, worker = worker) } else { localhost <- (grepl("^http://localhost", url) || grepl("^http://127.0.0.1", url)) private$sites[[n+1]] <- list(name = name, url = url, localhost = localhost, dataFileName = if (localhost) paste0(name, ".rds") else NULL) } }, run = function() { 'Run Computation' dry_run <- private$dry_run defn <- private$defn debug <- private$debug n <- length(sites) if (debug) { print("run(): checking worker object creation") } if (dry_run) { sites <- private$sites } else { instanceId <- generateId(object=list(Sys.time(), self)) private$sites <- sites <- lapply(private$sites, function(x) list(name = x$name, url = x$url, localhost = x$localhost, dataFileName = x$dataFileName, instanceId = if (x$localhost) x$name else instanceId)) sitesOK <- sapply(sites, function(x) { payload <- if (is.null(x$dataFileName)) { list(defnId = defn$id, instanceId = x$instanceId) } else { list(defnId = defn$id, instanceId = x$instanceId, dataFileName = x$dataFileName) } q <- httr::POST(url = .makeOpencpuURL(urlPrefix=x$url, fn="createWorkerInstance"), body = jsonlite::toJSON(payload), httr::add_headers("Content-Type" = "application/json"), config = getConfig()$sslConfig ) .deSerialize(q) }) if (!all(sitesOK)) { stop("run(): Some sites did not respond successfully!") sites <- sites[which(sitesOK)] } } result <- self$queryCount() if (!dry_run) { if (debug) { print("run(): checking worker object cleanup") } sitesOK <- sapply(sites, function(x) { payload <- list(instanceId = x$instanceId) q <- POST(url = .makeOpencpuURL(urlPrefix=x$url, fn="destroyInstanceObject"), body = jsonlite::toJSON(payload), add_headers("Content-Type" = "application/json"), config=getConfig()$sslConfig ) .deSerialize(q) }) if (!all(sitesOK)) { warning("run(): Some sites did not clean up successfully!") } } result } ) ) HEQueryCountWorker <- R6Class( "HEQueryCountWorker", inherit = QueryCountWorker, private = list( result_cache = list() ), public = list( pubkey = NA, den = NA, initialize = function(defn, data, pubkey_bits = NULL, pubkey_n = NULL, den_bits = NULL) { private$defn <- defn private$data <- data private$stateful <- TRUE if (!is.null(pubkey_bits)) { self$pubkey <- homomorpheR::PaillierPublicKey$new(pubkey_bits, pubkey_n) self$den <- gmp::as.bigq(2)^(den_bits) } stopifnot(self$kosher()) }, setParams = function(pubkey_bits, pubkey_n, den_bits) { if(is.character(pubkey_n)) { pubkey_n <- gmp::as.bigz(pubkey_n) } if (!is.null(pubkey_bits)) { self$pubkey <- homomorpheR::PaillierPublicKey$new(pubkey_bits, pubkey_n) self$den <- gmp::as.bigq(2)^(den_bits) } TRUE }, queryCount = function(partyNumber, token) { result <- private$result_cache[[token]] if (is.null(result)) { result.int <- super$queryCount() pubkey <- self$pubkey offset <- homomorpheR::random.bigz(nBits = 256) zero <- pubkey$encrypt(0) ncp1Result <- list(int = pubkey$encrypt(result.int - offset), frac = zero) ncp2Result <- list(int = pubkey$encrypt(result.int + offset), frac = zero) result <- list(ncp1 = ncp1Result, ncp2 = ncp2Result) private$result_cache[[token]] <- result } if (partyNumber == 1) result$ncp1 else result$ncp2 } ) ) HEQueryCountMaster <- R6Class( "HEQueryCountMaster", inherit = QueryCountMaster, private = list( partyNumber = NA, defn = NA, mapFn = function(site, token) { payload <- list(objectId = site$instanceId, method = "queryCount", partyNumber = private$partyNumber, token = token) q <- httr::POST(.makeOpencpuURL(urlPrefix=site$url, fn="executeHEMethod"), body = jsonlite::toJSON(payload), httr::add_headers("Content-Type" = "application/json"), config = getConfig()$sslConfig ) .deSerialize(q) }, debug = FALSE ), public = list( pubkey = NA, pubkey_bits = NA, pubkey_n = NA, den = NA, den_bits = NA, initialize = function(defn, partyNumber, debug = FALSE) { 'Initialize the object with a dataset' private$defn <- defn private$partyNumber <- partyNumber private$debug <- debug stopifnot(self$kosher()) }, setParams = function(pubkey_bits, pubkey_n, den_bits) { self$pubkey_bits <- pubkey_bits if(is.character(pubkey_n)) { pubkey_n <- gmp::as.bigz(pubkey_n) } self$pubkey_n <- pubkey_n self$den_bits <- den_bits self$pubkey <- homomorpheR::PaillierPublicKey$new(pubkey_bits, pubkey_n) self$den <- gmp::as.bigq(2)^(den_bits) TRUE }, kosher = function() { ' Check for appropriateness' TRUE }, queryCount = function(token) { 'Compute the query count from all sites' sites <- private$sites if (private$dry_run) { mapFn <- function(site, token) site$worker$queryCount(private$partyNumber, token) } else { mapFn <- private$mapFn } results <- Map(mapFn, sites, rep(token, length(sites))) pubkey <- self$pubkey zero <- pubkey$encrypt(0) intResults <- lapply(results, function(x) gmp::as.bigz(x$int)) fracResults <- lapply(results, function(x) gmp::as.bigz(x$frac)) intSum <- Reduce(f = pubkey$add, x = intResults, init = zero) fracSum <- Reduce(f = pubkey$add, x = fracResults, init = zero) list(int = intSum, frac = fracSum) }, cleanup = function() { 'Send cleanup message to sites' if (!private$dry_run) { sites <- private$sites sitesOK <- sapply(sites, function(x) { payload <- list(instanceId = x$instanceId) q <- httr::POST(url = .makeOpencpuURL(urlPrefix=x$url, fn="destroyInstanceObject"), body = jsonlite::toJSON(payload), httr::add_headers("Content-Type" = "application/json"), config=getConfig()$sslConfig ) .deSerialize(q) }) if (!all(sitesOK)) { warning("run(): Some sites did not clean up successfully!") } } invisible(TRUE) }, run = function(token) { 'Run Computation' dry_run <- private$dry_run debug <- private$debug defn <- private$defn sites <- private$sites if (dry_run) { workers <- lapply(sites, function(x) x$worker) for (worker in workers) { worker$setParams(pubkey_bits = self$pubkey_bits, pubkey_n = self$pubkey_n, den_bits = self$den_bits) } } else { instanceId <- token private$sites <- sites <- lapply(private$sites, function(x) list(name = x$name, url = x$url, localhost = x$localhost, dataFileName = x$dataFileName, instanceId = if (x$localhost) x$name else instanceId)) sitesOK <- sapply(sites, function(x) { payload <- if (is.null(x$dataFileName)) { list(defnId = defn$id, instanceId = x$instanceId, pubkey_bits = self$pubkey_bits, pubkey_n = as.character(self$pubkey_n), den_bits = self$den_bits) } else { list(defnId = defn$id, instanceId = x$instanceId, dataFileName = x$dataFileName, pubkey_bits = self$pubkey_bits, pubkey_n = as.character(self$pubkey_n), den_bits = self$den_bits) } q <- httr::POST(url = .makeOpencpuURL(urlPrefix=x$url, fn="createHEWorkerInstance"), body = jsonlite::toJSON(payload), httr::add_headers("Content-Type" = "application/json"), config = getConfig()$sslConfig ) .deSerialize(q) }) if (!all(sitesOK)) { stop("run(): Some sites did not respond successfully!") sites <- sites[which(sitesOK)] } } self$queryCount(token) } ) )
source(system.file(file.path('tests', 'testthat', 'test_utils.R'), package = 'nimble')) context("Testing how nimbleFunctions use model variables and nodes") test_that("nimbleFunction use of model variables and nodes works", { code <- nimbleCode({ a ~ dnorm(0, 1) for(i in 1:5) { b[i] ~ dnorm(0, 1) for(j in 1:3) c[i,j] ~ dnorm(0, 1) } }) constants <- list() data <- list() inits <- list(a = 1, b=1:5, c = array(1:30, c(5,6))) Rmodel <- nimbleModel(code, constants, data, inits) nfDef <- nimbleFunction( setup = function(model) { aNode <- 'a' bNode <- 'b' cNode <- 'c' bNode2 <- 'b[2]' cNode34 <- 'c[3, 4]' }, run = function(aCheck = double(), bCheck = double(1), cCheck = double(2)) { ok <- TRUE bNode2v <- model[[bNode2]] cNode34v <- model[[cNode34]] bNode2v2 <- model[['b[2]']] cNode34v2 <- model[['c[3, 4]']] ok <- ok & bNode2v == bCheck[2] ok <- ok & bNode2v == bNode2v2 ok <- ok & cNode34v == cCheck[3, 4] ok <- ok & cNode34v2 == cNode34v a1 <- model[['a']] ok <- ok & a1 == aCheck b1 <- model[['b']] ok <- ok & sum(dim(b1) != dim(bCheck)) == 0 ok <- ok & sum(b1 != bCheck) == 0 c1 <- model[['c']] ok <- ok & sum(dim(c1) != dim(cCheck)) == 0 ok <- ok & sum(c1 != cCheck) == 0 model[['a']] <<- a1 + 1 model[['b']] <<- b1 + 1 model[['c']] <<- c1 + 1 aCheck <- aCheck + 1 bCheck <- bCheck + 1 cCheck <- cCheck + 1 a2 <- model$a ok <- ok & sum(a2 != aCheck) == 0 b2 <- model$b ok <- ok & sum(dim(b2) != dim(bCheck)) == 0 ok <- ok & sum(b2 != bCheck) == 0 c2 <- model$c ok <- ok & sum(dim(c2) != dim(cCheck)) == 0 ok <- ok & sum(c2 != cCheck) == 0 model$a <<- a2 + 1 model$b <<- b2 + 1 model$c <<- c2 + 1 aCheck <- aCheck + 1 bCheck <- bCheck + 1 cCheck <- cCheck + 1 bSubCheck <- bCheck[2:4] cSubCheck <- cCheck[2:4, 3:5] a3 <- model$a[1] ok <- ok & a3 == aCheck b3 <- model$b[2:4] ok <- ok & sum(dim(b3) != dim(bSubCheck)) == 0 ok <- ok & sum(b3 != bSubCheck) == 0 c3 <- model$c[2:4 , 3:5] ok <- ok & sum(dim(c3) != dim(cSubCheck)) == 0 ok <- ok & sum(c3 != cSubCheck) == 0 model$a[1] <<- a3 + 1 model$b[2:4] <<- bSubCheck + 1 model$c[2:4, 3:5] <<- cSubCheck + 1 aCheck <- aCheck + 1 bCheck[2:4] <- bSubCheck + 1 cCheck[2:4, 3:5] <- cSubCheck + 1 bSubCheck <- bCheck[2:4] cSubCheck <- cCheck[2:4, 3:5] b4 <- model[['b']][2:4] ok <- ok & sum(dim(b4) != dim(bSubCheck)) == 0 ok <- ok & sum(b4 != bSubCheck) == 0 c4 <- model[['c']][2:4 , 3:5] ok <- ok & sum(dim(c4) != dim(cSubCheck)) == 0 ok <- ok & sum(c4 != cSubCheck) == 0 model[['b']][2:4] <<- bSubCheck + 1 model[['c']][2:4, 3:5] <<- cSubCheck + 1 bCheck[2:4] <- bSubCheck + 1 cCheck[2:4, 3:5] <- cSubCheck + 1 bSubCheck <- bCheck[2:4] cSubCheck <- cCheck[2:4, 3:5] a5 <- model[[aNode]] ok <- ok & a5 == aCheck b5 <- model[[bNode]] ok <- ok & sum(dim(b5) != dim(bCheck)) == 0 ok <- ok & sum(b5 != bCheck) == 0 c5 <- model[[cNode]] ok <- ok & sum(dim(c5) != dim(cCheck)) == 0 ok <- ok & sum(c5 != cCheck) == 0 model[[aNode]] <<- a5 + 1 model[[bNode]] <<- b5 + 1 model[[cNode]] <<- c5 + 1 aCheck <- aCheck + 1 bCheck <- bCheck + 1 cCheck <- cCheck + 1 bSubCheck <- bCheck[2:4] cSubCheck <- cCheck[2:4, 3:5] b6 <- model[[bNode]][2:4] ok <- ok & sum(dim(b6) != dim(bSubCheck)) == 0 ok <- ok & sum(b6 != bSubCheck) == 0 c6 <- model[[cNode]][2:4 , 3:5] ok <- ok & sum(dim(c6) != dim(cSubCheck)) == 0 ok <- ok & sum(c6 != cSubCheck) == 0 model[[bNode]][2:4] <<- bSubCheck + 1 model[[cNode]][2:4, 3:5] <<- cSubCheck + 1 return(ok) returnType(logical()) } ) Rnf <- nfDef(Rmodel) uncompiledAns <- Rnf$run(Rmodel$a, Rmodel$b, Rmodel$c) expect_true(uncompiledAns) compiled <- compileNimble(Rmodel, Rnf) compiledAns <- compiled$Rnf$run(Rmodel$a, Rmodel$b, Rmodel$c) expect_true(compiledAns) })
expected <- eval(parse(text="NULL")); test(id=0, code={ argv <- eval(parse(text="list(c(0, 0, 0, 0, 0, 1.75368801162502e-134, 0, 0, 0, 2.60477585273833e-251, 1.16485035372295e-260, 0, 1.53160350210786e-322, 0.333331382328728, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3.44161262707711e-123, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.968811545398e-173, 0, 8.2359965384697e-150, 0, 0, 0, 0, 6.51733217171341e-10, 0, 2.36840184577368e-67, 0, 9.4348408357524e-307, 0, 1.59959906013771e-89, 0, 8.73836857865034e-286, 7.09716190970992e-54, 0, 0, 0, 1.530425353017e-274, 8.57590058044551e-14, 0.333333106397154, 0, 0, 1.36895217898448e-199, 2.0226102635783e-177, 5.50445388209462e-42, 0, 0, 0, 0, 1.07846402051283e-44, 1.88605464411243e-186, 1.09156111051203e-26, 0, 3.0702877273237e-124, 0.333333209689785, 0, 0, 0, 0, 0, 0, 3.09816093866831e-94, 0, 0, 4.7522727332095e-272, 0, 0, 2.30093251441394e-06, 0, 0, 1.27082826644707e-274, 0, 0, 0, 0, 0, 0, 0, 4.5662025456054e-65, 0, 2.77995853978268e-149, 0, 0, 0))")); do.call(`names`, argv); }, o=expected);
parse_single_roi <- function(data, min_time = 0, max_time = +Inf, reference_hour = NULL, verbose = TRUE, columns = NULL, cache=NULL, FUN = NULL, ...){ roi_idx = NULL id <- data$id region_id <- data$region_id path <- data$file_info[[1]]$path if(is.null(columns) & !is.null(FUN)){ needed_columns <- attr(FUN, "needed_columns") if(!is.null(needed_columns)) columns <- needed_columns(...) } if(verbose) cat(sprintf("Loading ROI number %i from:\n\t%s\n",region_id,path)) if(tools::file_ext(path) != "db") stop(sprintf("Unsuported file extention in %s",path)) fs = file.info(path)["size"] if(!is.null(cache)){ db <- memoise::cache_filesystem(cache, algo="md5") parse_single_roi_wrapped_memo <- memoise::memoise(parse_single_roi_wrapped, cache=db) } else{ parse_single_roi_wrapped_memo <- parse_single_roi_wrapped } out <- parse_single_roi_wrapped_memo( id, region_id, path, min_time, max_time, reference_hour, columns, file_size= fs, FUN, ... ) if(!is.null(out)) behavr::setbehavr(out, data) out } parse_single_roi_wrapped <- function(id, region_id,path, min_time = 0, max_time = +Inf, reference_hour = NULL, columns = NULL, file_size=0, FUN = NULL, ... ){ time_stamp = NULL out <- read_single_roi(path, region_id=region_id, min_time = min_time, max_time = max_time, reference_hour = reference_hour, columns=columns, time_stamp = time_stamp) if(is.null(out) || nrow(out) == 0){ warning(sprintf("No data in ROI %i, from FILE %s. Skipping",region_id, path)) return(NULL) } old_cols <- data.table::copy(names(out)) out[,id := id] data.table::setcolorder(out,c("id", old_cols)) data.table::setkeyv(out, "id") met <- data.table::data.table(id = id, key="id") behavr::setbehavr(out, met) if(!is.null(FUN)){ out <- FUN(out,...) is_empty <- is.null(out) if(!is_empty) is_empty <- nrow(out) == 0 if(is_empty){ warning(sprintf("No data in ROI %i after running FUN, from FILE %s. Skipping",region_id, path)) return(NULL) } } out }
logit.spls <- function(Xtrain, Ytrain, lambda.ridge, lambda.l1, ncomp, Xtest=NULL, adapt=TRUE, maxIter=100, svd.decompose=TRUE, center.X=TRUE, scale.X=FALSE, weighted.center=TRUE) { Xtrain <- as.matrix(Xtrain) ntrain <- nrow(Xtrain) p <- ncol(Xtrain) index.p <- c(1:p) if(is.factor(Ytrain)) { Ytrain <- as.numeric(levels(Ytrain))[Ytrain] } Ytrain <- as.integer(Ytrain) Ytrain <- as.matrix(Ytrain) q <- ncol(Ytrain) one <- matrix(1,nrow=1,ncol=ntrain) cnames <- NULL if(!is.null(colnames(Xtrain))) { cnames <- colnames(Xtrain) } else { cnames <- paste0(1:p) } if(length(table(Ytrain)) > 2) { warning("message from logit.spls: multicategorical response") results = multinom.spls(Xtrain=Xtrain, Ytrain=Ytrain, lambda.ridge=lambda.ridge, lambda.l1=lambda.l1, ncomp=ncomp, Xtest=Xtest, adapt=adapt, maxIter=maxIter, svd.decompose=svd.decompose, center.X=center.X, scale.X=scale.X, weighted.center=weighted.center) return(results) } if ((!is.matrix(Xtrain)) || (!is.numeric(Xtrain))) { stop("Message from logit.spls: Xtrain is not of valid type") } if (ncomp > p) { warning("Message from logit.spls: ncomp>p is not valid, ncomp is set to p") ncomp <- p } if (p==1) { warning("Message from logit.spls: p=1 is not valid, ncomp is set to 0") ncomp <- 0 } if (!is.null(Xtest)) { if (is.vector(Xtest)==TRUE) { Xtest <- matrix(Xtest,ncol=p) } Xtest <- as.matrix(Xtest) ntest <- nrow(Xtest) if ((!is.matrix(Xtest)) || (!is.numeric(Xtest))) { stop("Message from logit.spls: Xtest is not of valid type") } if (p != ncol(Xtest)) { stop("Message from logit.spls: columns of Xtest and columns of Xtrain must be equal") } } if ((!is.matrix(Ytrain)) || (!is.numeric(Ytrain))) { stop("Message from logit.spls: Ytrain is not of valid type") } if (q != 1) { stop("Message from logit.spls: Ytrain must be univariate") } if (nrow(Ytrain)!=ntrain) { stop("Message from logit.spls: the number of observations in Ytrain is not equal to the Xtrain row number") } if (sum(is.na(Ytrain))!=0) { stop("Message from logit.spls: NA values in Ytrain") } if (sum(!(Ytrain %in% c(0,1)))!=0) { stop("Message from logit.spls: Ytrain is not of valid type") } if (sum(as.numeric(table(Ytrain))==0)!=0) { stop("Message from logit.spls: there are empty classes") } if ((!is.numeric(lambda.ridge)) || (lambda.ridge<0) || (!is.numeric(lambda.l1)) || (lambda.l1<0)) { stop("Message from logit.spls: lambda is not of valid type") } if ((!is.numeric(ncomp)) || (round(ncomp)-ncomp!=0) || (ncomp<0) || (ncomp>p)) { stop("Message from logit.spls: ncomp is not of valid type") } if ((!is.numeric(maxIter)) || (round(maxIter)-maxIter!=0) || (maxIter<1)) { stop("Message from logit.spls: maxIter is not of valid type") } r <- min(p, ntrain) DeletedCol <- NULL sigma2train <- apply(Xtrain, 2, var) * (ntrain-1)/(ntrain) if (sum(sigma2train < .Machine$double.eps)!=0){ if (sum(sigma2train < .Machine$double.eps)>(p-2)){ stop("Message from logit.spls: the procedure stops because number of predictor variables with no null variance is less than 1.") } warning("There are covariables with nul variance") Xtrain <- Xtrain[,which(sigma2train >= .Machine$double.eps)] if (!is.null(Xtest)) { Xtest <- Xtest[,which(sigma2train>= .Machine$double.eps)] } DeletedCol <- index.p[which(sigma2train < .Machine$double.eps)] sigma2train <- sigma2train[which(sigma2train >= .Machine$double.eps)] p <- ncol(Xtrain) r <- min(p,ntrain) } if(!is.null(DeletedCol)) { cnames <- cnames[-DeletedCol] } meanXtrain <- apply(Xtrain,2,mean) if(center.X && scale.X) { sXtrain <- scale(Xtrain, center=meanXtrain, scale=sqrt(sigma2train)) } else if(center.X && !scale.X) { sXtrain <- scale(Xtrain, center=meanXtrain, scale=FALSE) } else { sXtrain <- Xtrain } sXtrain.nosvd <- sXtrain if ((p > ntrain) && (svd.decompose) && (p>1)) { svd.sXtrain <- svd(t(sXtrain)) r <- length(svd.sXtrain$d[abs(svd.sXtrain$d)>10^(-13)]) V <- svd.sXtrain$u[,1:r] D <- diag(c(svd.sXtrain$d[1:r])) U <- svd.sXtrain$v[,1:r] sXtrain <- U %*% D rm(D) rm(U) rm(svd.sXtrain) } if (!is.null(Xtest)) { meanXtest <- apply(Xtest,2,mean) sigma2test <- apply(Xtest,2,var) if(center.X && scale.X) { sXtest <- scale(Xtest, center=meanXtrain, scale=sqrt(sigma2train)) } else if(center.X && !scale.X) { sXtest <- scale(Xtest, center=meanXtrain, scale=FALSE) } else { sXtest <- Xtest } sXtest.nosvd <- sXtest if ((p > ntrain) && (svd.decompose)) { sXtest <- sXtest%*%V } } fit <- wirrls(Y=Ytrain, Z=cbind(rep(1,ntrain),sXtrain), Lambda=lambda.ridge, NbrIterMax=maxIter, WKernel=diag(rep(1,ntrain))) converged=fit$Cvg if (converged==0) { warning("Message from logit.spls : Ridge IRLS did not converge; try another lambda.ridge value") } if (ncomp==0) { BETA <- fit$Coefficients } if (ncomp!=0) { Eta <- cbind(rep(1, ntrain), sXtrain) %*% fit$Coefficients sXtrain = sXtrain.nosvd if (!is.null(Xtest)) { sXtest = sXtest.nosvd } mu = 1 / (1 + exp(-Eta)) diagV <- mu * (1-mu) V <- diag(c(diagV)) diagVinv = 1/ifelse(diagV!=0, diagV, diagV+0.00000001) Vinv = diag(c(diagVinv)) Psi <- Ytrain-mu pseudoVar = Eta + Vinv %*% Psi sumV=sum(diagV) VmeanPseudoVar <- sum(V %*% Eta + Psi ) / sumV VmeansXtrain <- t(diagV)%*%sXtrain/sumV resSPLS = spls(Xtrain=sXtrain, Ytrain=pseudoVar, ncomp=ncomp, weight.mat=V, lambda.l1=lambda.l1, adapt=adapt, center.X=center.X, scale.X=scale.X, center.Y=TRUE, scale.Y=FALSE, weighted.center=weighted.center) BETA = resSPLS$betahat.nc } else { resSPLS = list(A=NULL, X.score=NULL, X.weight=NULL, sXtrain=sXtrain, sYtrain=NULL, V=NULL) } hatY <- numeric(ntrain) hatY <- cbind(rep(1,ntrain),sXtrain) %*% BETA hatY <- as.numeric(hatY>0) proba <- numeric(ntrain) proba <- inv.logit( cbind(rep(1,ntrain),sXtrain) %*% BETA ) if (!is.null(Xtest)) { hatYtest <- cbind(rep(1,ntest),sXtest) %*% BETA hatYtest <- as.numeric(hatYtest>0) proba.test = inv.logit( cbind(rep(1,ntest),sXtest) %*% BETA ) } else { hatYtest <- NULL proba.test <- NULL } Coefficients=BETA if(p > 1) { Coefficients[-1] <- diag(c(1/sqrt(sigma2train)))%*%BETA[-1] } else { Coefficients[-1] <- (1/sqrt(sigma2train))%*%BETA[-1] } Coefficients[1] <- BETA[1] - meanXtrain %*% Coefficients[-1] Anames <- cnames[resSPLS$A] result <- list(Coefficients=Coefficients, hatY=hatY, hatYtest=hatYtest, DeletedCol=DeletedCol, A=resSPLS$A, Anames=Anames, converged=converged, X.score=resSPLS$X.score, X.weight=resSPLS$X.weight, sXtrain=resSPLS$sXtrain, sPseudoVar=resSPLS$sYtrain, lambda.ridge=lambda.ridge, lambda.l1=lambda.l1, ncomp=ncomp, V=resSPLS$V, proba=proba, proba.test=proba.test, Xtrain=Xtrain, Ytrain=Ytrain) class(result) <- "logit.spls" return(result) }
context("count_unique_geno") test_that("count_unique_geno works", { g <- rbind(c(NA, "A", "A", "A", "T"), c(NA, NA, NA, "A", "A"), c("A", "A", "T", "G", "G"), rep(NA, 5), c("N", "H", "", "A", "A"), c("N", "H", "", "A", "T"), c("C", "C", "G", "G", NA)) expected <- c(2,1,3,0,1,2,2) expect_equal(count_unique_geno(g), expected) rownames(g) <- names(expected) <- paste0("mar", 1:7) expect_equal(count_unique_geno(g), expected) }) test_that("count_unique_geno works multi-core", { if(isnt_karl()) skip("this test only run locally") g <- rbind(c(NA, "A", "A", "A", "T"), c(NA, NA, NA, "A", "A"), c("A", "A", "T", "G", "G"), rep(NA, 5), c("N", "H", "", "A", "A"), c("N", "H", "", "A", "T"), c("C", "C", "G", "G", NA)) expected <- c(2,1,3,0,1,2,2) expect_equal(count_unique_geno(g), expected) expect_equal(count_unique_geno(g, cores=2), expected) rownames(g) <- names(expected) <- paste0("mar", 1:7) expect_equal(count_unique_geno(g), expected) expect_equal(count_unique_geno(g, cores=2), expected) })
library(glue) make_new <- function(name, which = c("step", "check")) { which <- match.arg(which) stopifnot(is.character(name)) in_recipes_root <- tail(stringr::str_split(getwd(), "/")[[1]], 1) == "recipes" if (!in_recipes_root) { rlang::abort("Change working directory to package root") } if (glue::glue("{name}.R") %in% list.files("./R")) { rlang::abort("step or check already present with this name in /R") } boilerplate <- glue(" {create_documentation(name, which)} {create_function(name, which)} {create_generator(name, which)} {create_prep_method(name, which)} {create_bake_method(name, which)} {create_print_method(name, which)} {create_tidy_method(name, which)} ") file.create(glue("./R/{name}.R")) cat(boilerplate, file = glue("./R/{name}.R")) file.create(glue("./tests/testthat/test_{name}.R")) } create_documentation <- function(name, which) { glue(" ") } create_function <- function(name, which) { glue(' {which}_{name} <- function(recipe, ..., role = NA, trained = FALSE, <additional args here> skip = FALSE, id = rand_id("{name}")) {{ add_{which}( recipe, {which}_{name}_new( terms = ellipse_check(...), trained = trained, role = role, <additional args here> skip = skip, id = id ) ) }} ') } create_generator <- function(name, which) { glue(' {which}_{name}_new <- function(terms, role, <additional args here>, na_rm, skip, id) {{ step( subclass = "{name}", terms = terms, role = role, trained = trained, <additional args here> skip = skip, id = id ) }} ') } create_prep_method <- function(name, which) { glue(' prep.{which}_{name} <- function(x, training, info = NULL, ...) {{ col_names <- recipes_eval_select(x$terms, training, info) check_type(training[, col_names]) <prepping action here> {which}_{name}_new( terms = x$terms, role = x$role, trained = TRUE, <additional args here> skip = x$skip, id = x$id ) }} ') } create_bake_method <- function(name, which) { glue(' bake.{which}_{name} <- function(object, new_data, ...) {{ <baking actions here> as_tibble(new_data) }} ') } create_print_method <- function(name, which) { glue(' print.{which}_{name} <- function(x, width = max(20, options()$width - 30), ...) {{ cat("<describe action here> ", sep = "") printer(names(x$means), x$terms, x$trained, width = width) invisible(x) }} ') } create_tidy_method <- function(name, which) { glue(" tidy.{which}_{name} <- function(x, ...) {{ if (is_trained(x)) {{ res <- <action here> }} else {{ term_names <- sel2char(x$terms) res <- tibble(terms = term_names, value = na_dbl) }} res$id <- x$id res }} ") }
.onLoad <- function(libname, pkgname) { .jpackage(pkgname, lib.loc = libname) }
makeSrcDirs = function(repo, cores = 1, scm_auth) { binds = getBuilding(repo = repo) manifest = getBuildingManifest(repo = repo) scm_auth = replicate(scm_auth, n=nrow(manifest), simplify=FALSE) sources = mapply(makeSource, url = manifest$url, type = manifest$type, scm_auth= scm_auth, branch = manifest$branch, subdir = manifest$subdir, name = manifest$name) path = checkout_dir(repo) versions = versions_df(repo)[binds,] res <- mapply(function(nm, src, repo, path, version) { ret = makePkgDir(name = nm, source = src, path =path, latest_only = FALSE, param = param(repo), forceRefresh=FALSE) if(ret && !is.na(version) && file.exists(file.path(path, nm))) { gotoVersCommit(file.path(path, nm), version = version, src = src, param = param(repo)) } ret }, nm = manifest$name, version = versions$version, src = sources, path = path, repo = list(repo)) res = unlist(res) if(!is.logical(res)) print(res) fullres = repo_results(repo) fullres$status[binds][!res] = "source checkout failed" vrs = getCOedVersions(path, manifest = manifest, repo = repo) inds = fullres$name %in% names(vrs) fullres$version[inds] = vrs[match(fullres$name[inds], names(vrs))] repo_results(repo) = fullres repo }
lav_matrix_vec <- function(A) { as.vector(A) } lav_matrix_vecr <- function(A) { lav_matrix_vec(t(A)) } lav_matrix_vech <- function(S, diagonal = TRUE) { ROW <- row(S); COL <- col(S) if(diagonal) S[ROW >= COL] else S[ROW > COL] } lav_matrix_vechr <- function(S, diagonal = TRUE) { S[lav_matrix_vechr_idx(n = NCOL(S), diagonal = diagonal)] } lav_matrix_vechu <- function(S, diagonal = TRUE) { S[lav_matrix_vechu_idx(n = NCOL(S), diagonal = diagonal)] } lav_matrix_vechru <- function(S, diagonal = TRUE) { S[lav_matrix_vechru_idx(n = NCOL(S), diagonal = diagonal)] } lav_matrix_vech_idx <- function(n = 1L, diagonal = TRUE) { n <- as.integer(n) ROW <- matrix(seq_len(n), n, n) COL <- matrix(seq_len(n), n, n, byrow = TRUE) if(diagonal) which(ROW >= COL) else which(ROW > COL) } lav_matrix_vech_row_idx <- function(n = 1L, diagonal = TRUE) { n <- as.integer(n) if(diagonal ) { unlist(lapply(seq_len(n), seq.int, n)) } else { 1 + unlist(lapply(seq_len(n-1), seq.int, n-1)) } } lav_matrix_vech_col_idx <- function(n = 1L, diagonal = TRUE) { n <- as.integer(n) if(!diagonal) { n <- n - 1L } rep.int(seq_len(n), times = rev(seq_len(n))) } lav_matrix_vechr_idx <- function(n = 1L, diagonal = TRUE) { n <- as.integer(n) ROW <- matrix(seq_len(n), n, n) COL <- matrix(seq_len(n), n, n, byrow = TRUE) tmp <- matrix(seq_len(n*n), n, n, byrow = TRUE) if(diagonal) tmp[ROW <= COL] else tmp[ROW < COL] } lav_matrix_vechu_idx <- function(n = 1L, diagonal = TRUE) { n <- as.integer(n) ROW <- matrix(seq_len(n), n, n) COL <- matrix(seq_len(n), n, n, byrow = TRUE) if(diagonal) which(ROW <= COL) else which(ROW < COL) } lav_matrix_vechru_idx <- function(n = 1L, diagonal = TRUE) { n <- as.integer(n) ROW <- matrix(seq_len(n), n, n) COL <- matrix(seq_len(n), n, n, byrow = TRUE) tmp <- matrix(seq_len(n*n), n, n, byrow = TRUE) if(diagonal) tmp[ROW >= COL] else tmp[ROW > COL] } lav_matrix_vech_reverse <- lav_matrix_vechru_reverse <- lav_matrix_upper2full <- function(x, diagonal = TRUE) { if(diagonal) { p <- (sqrt(1 + 8*length(x))-1)/2 } else { p <- (sqrt(1 + 8*length(x))+1)/2 } S <- numeric(p * p) S[lav_matrix_vech_idx( p, diagonal = diagonal)] <- x S[lav_matrix_vechru_idx(p, diagonal = diagonal)] <- x attr(S, "dim") <- c(p, p) S } lav_matrix_vechr_reverse <- lav_matrix_vechu_reverse <- lav_matrix_lower2full <- function(x, diagonal = TRUE) { if(diagonal) { p <- (sqrt(1 + 8*length(x))-1)/2 } else { p <- (sqrt(1 + 8*length(x))+1)/2 } stopifnot(p == round(p,0)) S <- numeric(p * p) S[lav_matrix_vechr_idx(p, diagonal = diagonal)] <- x S[lav_matrix_vechu_idx(p, diagonal = diagonal)] <- x attr(S, "dim") <- c(p, p) S } lav_matrix_diag_idx <- function(n = 1L) { 1L + (seq_len(n) - 1L)*(n + 1L) } lav_matrix_diagh_idx <- function(n = 1L) { if(n < 1L) return(integer(0L)) if(n == 1L) return(1L) c(1L, cumsum(n:2L) + 1L) } lav_matrix_antidiag_idx <- function(n = 1L) { if(n < 1L) return(integer(0L)) 1L + seq_len(n)*(n-1L) } lav_matrix_vech_which_idx <- function(n = 1L, diagonal = TRUE, idx = integer(0L), type = "and") { if(length(idx) == 0L) return(integer(0L)) n <- as.integer(n) A <- matrix(FALSE, n, n) if(type == "and") { A[idx, idx] <- TRUE } else if(type == "or") { A[idx, ] <- TRUE A[ ,idx] <- TRUE } which(lav_matrix_vech(A, diagonal = diagonal)) } lav_matrix_vech_match_idx <- function(n = 1L, diagonal = TRUE, idx = integer(0L)) { if (length(idx) == 0L) return(integer(0L)) n <- as.integer(n) pstar <- n*(n+1)/2 A <- lav_matrix_vech_reverse(seq_len(pstar)) B <- A[idx, idx, drop = FALSE] lav_matrix_vech(B, diagonal = diagonal) } .dup1 <- function(n = 1L) { if ((n < 1L) | (round(n) != n)) { stop("n must be a positive integer") } if (n > 255L) { stop("n is too large") } n2 <- n * n; nstar <- n * (n + 1)/2 x <- numeric(n2 * nstar) r1 <- seq.int(from = n*n+1, by = -(n-1), length.out = n-1) r2 <- seq.int(from = n-1, by = n-1, length.out = n-1) r3 <- seq.int(from = 2*n+1, by = n, length.out = n-1) rr <- unlist(lapply((n-1):1, function(x) { c(rbind(r1[1:x], r2[1:x]), r3[n-x]) })) idx <- c(1L, cumsum(rr) + 1L) x[idx] <- 1.0 attr(x, "dim") <- c(n2, nstar) x } .dup2 <- function (n = 1L) { if ((n < 1L) | (round(n) != n)) { stop("n must be a positive integer") } if(n > 255L) { stop("n is too large") } nstar <- n * (n+1)/2 n2 <- n * n x <- numeric(n2 * nstar) idx1 <- lav_matrix_vech_idx(n) + ((1L:nstar)-1L) * n2 idx2 <- lav_matrix_vechru_idx(n) + ((1L:nstar)-1L) * n2 x[idx1] <- 1.0 x[idx2] <- 1.0 attr(x, "dim") <- c(n2, nstar) x } .dup3 <- function(n = 1L) { if ((n < 1L) | (round(n) != n)) { stop("n must be a positive integer") } if(n > 255L) { stop("n is too large") } nstar <- n * (n+1)/2 n2 <- n * n x <- numeric(n2 * nstar) tmp <- matrix(0L, n, n) tmp[lav_matrix_vech_idx(n)] <- 1:nstar tmp[lav_matrix_vechru_idx(n)] <- 1:nstar idx <- (1:n2) + (lav_matrix_vec(tmp)-1L) * n2 x[idx] <- 1.0 attr(x, "dim") <- c(n2, nstar) x } lav_matrix_duplication <- .dup3 lav_matrix_duplication_pre <- function(A = matrix(0,0,0)) { n2 <- NROW(A) stopifnot(sqrt(n2) == round(sqrt(n2))) n <- sqrt(n2) idx1 <- lav_matrix_vech_idx(n); idx2 <- lav_matrix_vechru_idx(n) OUT <- A[idx1, , drop = FALSE] + A[idx2 , , drop = FALSE] u <- which(idx1 %in% idx2); OUT[u,] <- OUT[u,] / 2.0 OUT } lav_matrix_duplication_dup_pre2 <- function(A = matrix(0,0,0)) { n2 <- NROW(A) stopifnot(sqrt(n2) == round(sqrt(n2))) n <- sqrt(n2) idx1 <- lav_matrix_vech_idx(n); idx2 <- lav_matrix_vechru_idx(n) OUT <- A[idx1,,drop=FALSE] u <- which(!idx1 %in% idx2); OUT[u,] <- OUT[u,] + A[idx2[u],] OUT } lav_matrix_duplication_post <- function(A = matrix(0,0,0)) { n2 <- NCOL(A) stopifnot(sqrt(n2) == round(sqrt(n2))) n <- sqrt(n2) idx1 <- lav_matrix_vech_idx(n); idx2 <- lav_matrix_vechru_idx(n) OUT <- A[, idx1, drop = FALSE] + A[, idx2, drop = FALSE] u <- which(idx1 %in% idx2); OUT[,u] <- OUT[,u] / 2.0 OUT } lav_matrix_duplication_pre_post <- function(A = matrix(0,0,0)) { n2 <- NCOL(A) stopifnot(NROW(A) == n2, sqrt(n2) == round(sqrt(n2))) n <- sqrt(n2) idx1 <- lav_matrix_vech_idx(n); idx2 <- lav_matrix_vechru_idx(n) OUT <- A[idx1, , drop = FALSE] + A[idx2, , drop = FALSE] u <- which(idx1 %in% idx2); OUT[u,] <- OUT[u,] / 2.0 OUT <- OUT[, idx1, drop = FALSE] + OUT[, idx2, drop = FALSE] OUT[,u] <- OUT[,u] / 2.0 OUT } .dup_ginv1 <- function(n = 1L) { if ((n < 1L) | (round(n) != n)) { stop("n must be a positive integer") } if(n > 255L) { stop("n is too large") } nstar <- n * (n+1)/2 n2 <- n * n x <- numeric(nstar * n2) tmp <- matrix(1:(n*n), n, n) idx1 <- lav_matrix_vech(tmp) + (0:(nstar-1L))*n2 x[idx1] <- 0.5 idx2 <- lav_matrix_vechru(tmp) + (0:(nstar-1L))*n2 x[idx2] <- 0.5 idx3 <- lav_matrix_diag_idx(n) + (lav_matrix_diagh_idx(n)-1L)*n2 x[idx3] <- 1.0 attr(x, "dim") <- c(n2, nstar) x <- t(x) x } .dup_ginv2 <- function(n = 1L) { if ((n < 1L) | (round(n) != n)) { stop("n must be a positive integer") } if(n > 255L) { stop("n is too large") } nstar <- n * (n+1)/2 n2 <- n * n x <- numeric(nstar * n2) x[(lav_matrix_vech_idx(n) - 1L)*nstar + 1:nstar] <- 0.5 x[(lav_matrix_vechru_idx(n) - 1L)*nstar + 1:nstar] <- 0.5 x[(lav_matrix_diag_idx(n) - 1L)*nstar + lav_matrix_diagh_idx(n)] <- 1.0 attr(x, "dim") <- c(nstar, n2) x } lav_matrix_duplication_ginv <- .dup_ginv2 lav_matrix_duplication_ginv_pre <- function(A = matrix(0,0,0)) { A <- as.matrix.default(A) n2 <- NROW(A) stopifnot(sqrt(n2) == round(sqrt(n2))) n <- sqrt(n2) nstar <- n * (n+1)/2 idx1 <- lav_matrix_vech_idx(n); idx2 <- lav_matrix_vechru_idx(n) OUT <- (A[idx1, , drop = FALSE] + A[idx2, , drop = FALSE]) / 2 OUT } lav_matrix_duplication_ginv_post <- function(A = matrix(0,0,0)) { A <- as.matrix.default(A) n2 <- NCOL(A) stopifnot(sqrt(n2) == round(sqrt(n2))) n <- sqrt(n2) idx1 <- lav_matrix_vech_idx(n); idx2 <- lav_matrix_vechru_idx(n) OUT <- (A[, idx1, drop = FALSE] + A[, idx2, drop = FALSE]) / 2 OUT } lav_matrix_duplication_ginv_pre_post <- function(A = matrix(0,0,0)) { A <- as.matrix.default(A) n2 <- NCOL(A) stopifnot(NROW(A) == n2, sqrt(n2) == round(sqrt(n2))) n <- sqrt(n2) idx1 <- lav_matrix_vech_idx(n); idx2 <- lav_matrix_vechru_idx(n) OUT <- (A[idx1, , drop = FALSE] + A[idx2, , drop = FALSE]) / 2 OUT <- (OUT[, idx1, drop = FALSE] + OUT[, idx2, drop = FALSE]) / 2 OUT } .com1 <- function(m = 1L, n = 1L) { if ((m < 1L) | (round(m) != m)) { stop("n must be a positive integer") } if ((n < 1L) | (round(n) != n)) { stop("n must be a positive integer") } p <- m*n x <- numeric( p*p ) pattern <- rep(c(rep((m+1L)*n, (m-1L)), n+1L), n) idx <- c(1L, 1L + cumsum(pattern)[-p]) x[idx] <- 1.0 attr(x, "dim") <- c(p,p) x } lav_matrix_commutation <- .com1 lav_matrix_commutation_pre <- function(A = matrix(0,0,0)) { n2 <- NROW(A) stopifnot(sqrt(n2) == round(sqrt(n2))) n <- sqrt(n2) row.idx <- rep(1:n, each = n) + (0:(n-1L))*n OUT <- A[row.idx, , drop = FALSE] OUT } lav_matrix_commutation_mn_pre <- function(A, m = 1L, n = 1L) { mn <- NROW(A) stopifnot(mn == m * n) row.idx <- rep(1:m, each = n) + (0:(n-1L))*m OUT <- A[row.idx, , drop = FALSE] OUT } lav_matrix_commutation_Nn <- function(n = 1L) { stop("not implemented yet") } lav_matrix_kronecker_square <- function(A, check = TRUE) { dimA <- dim(A); n <- dimA[1L]; n2 <- n*n if(check) { stopifnot(dimA[2L] == n) } out <- tcrossprod(as.vector(A)) dim(out) <- c(n,n,n,n) out <- aperm(out, perm = c(3,1,4,2)) dim(out) <- c(n2, n2) out } lav_matrix_kronecker_symmetric <- function(S, check = TRUE) { dimS <- dim(S); n <- dimS[1L]; n2 <- n*n if(check) { stopifnot(dimS[2L] == n) } out <- tcrossprod(as.vector(S)) dim(out) <- c(n,n*n,n) out <- aperm(out, perm = c(3L,2L,1L)) dim(out) <- c(n2, n2) out } lav_matrix_tS2_SxS_S2 <- function(S2, S, check = TRUE) { n <- NROW(S) if(check) { stopifnot(NROW(S2) == n*n) } A <- matrix(S %*% matrix(S2, n, ), n*n,) A2 <- A[rep(1:n, each=n) + (0:(n-1L))*n,,drop = FALSE] crossprod(A, A2) } lav_matrix_symmetric_sqrt <- function(S = matrix(0,0,0)) { n <- NROW(S) S.eigen <- eigen(S, symmetric = TRUE) V <- S.eigen$vectors; d <- S.eigen$values d[d < 0] <- 0.0 S.sqrt <- V %*% diag(sqrt(d), n, n) %*% t(V) S.sqrt } lav_matrix_orthogonal_complement <- function(A = matrix(0,0,0)) { QR <- qr(A) ranK <- QR$rank Q <- qr.Q(QR, complete = TRUE) OUT <- Q[, -seq_len(ranK), drop = FALSE] OUT } lav_matrix_bdiag <- function(...) { if(nargs() == 0L) return(matrix(0,0,0)) dots <- list(...) if(is.list(dots[[1]])) { mlist <- dots[[1]] } else { mlist <- dots } if(length(mlist) == 1L) return(mlist[[1]]) nmat <- length(mlist) nrows <- sapply(mlist, NROW); crows <- cumsum(nrows) ncols <- sapply(mlist, NCOL); ccols <- cumsum(ncols) trows <- sum(nrows) tcols <- sum(ncols) x <- numeric(trows * tcols) for(m in seq_len(nmat)) { if(m > 1L) { rcoffset <- trows*ccols[m-1] + crows[m-1] } else { rcoffset <- 0L } m.idx <- ( rep((0:(ncols[m] - 1L))*trows, each=nrows[m]) + rep(1:nrows[m], ncols[m]) + rcoffset ) x[m.idx] <- mlist[[m]] } attr(x, "dim") <- c(trows, tcols) x } lav_matrix_trace <- function(..., check = TRUE) { if(nargs() == 0L) return(as.numeric(NA)) dots <- list(...) if(is.list(dots[[1]])) { mlist <- dots[[1]] } else { mlist <- dots } nMat <- length(mlist) if(nMat == 1L) { S <- mlist[[1]] if(check) { stopifnot(NROW(S) == NCOL(S)) } out <- sum(S[lav_matrix_diag_idx(n = NROW(S))]) } else if(nMat == 2L) { out <- sum(mlist[[1]] * t(mlist[[2]])) } else if(nMat == 3L) { A <- mlist[[1]] B <- mlist[[2]] C <- mlist[[3]] B2 <- B %*% C out <- sum(A * t(B2)) } else { M1 <- mlist[[1]] M2 <- mlist[[2]] for(m in 3L:nMat) { M2 <- M2 %*% mlist[[m]] } out <- sum(M1 * t(M2)) } out } lav_matrix_crossprod <- function(A, B) { if(missing(B)) { if(!anyNA(A)) { return(base::crossprod(A)) } B <- A } else if(!anyNA(A) && !anyNA(B)) { return(base::crossprod(A, B)) } if(!inherits(A, "matrix")) { A <- matrix(A) } if(!inherits(B, "matrix")) { B <- matrix(B) } out <- apply(B, 2L, function(x) colSums(A * x, na.rm = TRUE)) if(!is.matrix(out)) { out <- t(matrix(out)) } out } lav_matrix_rref <- function(A, tol = sqrt( .Machine$double.eps)) { if(missing(tol)) { A.norm <- max(abs(apply(A,1,sum))) tol <- max(dim(A)) * A.norm * .Machine$double.eps } stopifnot(is.matrix(A)) nRow <- NROW(A); nCol <- NCOL(A) pivot = integer(0L) if(nRow == 0 && nCol == 0) return(matrix(0,0,0)) rowIndex <- colIndex <- 1 while( rowIndex <= nRow && colIndex <= nCol ) { i.below <- which.max(abs(A[rowIndex:nRow, colIndex])) i <- i.below + rowIndex - 1L p <- A[i, colIndex] if(abs(p) <= tol) { A[rowIndex:nRow, colIndex] <- 0L colIndex <- colIndex + 1 } else { pivot <- c(pivot, colIndex) if(rowIndex != i) { A[ c(rowIndex,i), colIndex:nCol ] <- A[ c(i,rowIndex), colIndex:nCol ] } A[ rowIndex, colIndex:nCol ] <- A[ rowIndex, colIndex:nCol] / p other <- seq_len(nRow)[-rowIndex] A[other, colIndex:nCol] <- A[other, colIndex:nCol] - tcrossprod(A[other,colIndex], A[rowIndex,colIndex:nCol]) rowIndex <- rowIndex + 1 colIndex <- colIndex + 1 } } list(R = A, pivot = pivot) } lav_matrix_orthogonal_complement2 <- function(A, tol = sqrt( .Machine$double.eps)) { A <- t(A) out <- lav_matrix_rref(A = A, tol = tol) nfree <- NCOL(A) - length(out$pivot) if(nfree) { R <- out$R zero.idx <- which(apply(R, 1, function(x) { all(abs(x) < tol) })) if(length(zero.idx) > 0) { R <- R[-zero.idx,, drop = FALSE] } FREE <- R[, -out$pivot, drop = FALSE] I <- diag( nfree ) N <- rbind(-FREE, I) } else { N <- matrix(0, nrow = NCOL(A), ncol = 0L) } N } lav_matrix_symmetric_inverse <- function(S, logdet = FALSE, Sinv.method = "eigen", zero.warn = FALSE) { zero.idx <- which(colSums(S) == 0 & diag(S) == 0 & rowSums(S) == 0) S.orig <- S if(length(zero.idx) > 0L) { if(zero.warn) { warning("lavaan WARNING: matrix to be inverted contains zero cols/rows") } S <- S[-zero.idx, -zero.idx] } P <- NCOL(S) if(P == 0L) { S.inv <- matrix(0,0,0) if(logdet) { attr(S.inv, "logdet") <- 0 } return(S.inv) } else if(P == 1L) { tmp <- S[1,1] S.inv <- matrix(1/tmp, 1, 1) if(logdet) { attr(S.inv, "logdet") <- log(tmp) } } else if(P == 2L) { a11 <- S[1,1]; a12 <- S[1,2]; a21 <- S[2,1]; a22 <- S[2,2] tmp <- a11*a22 - a12*a21 if(tmp == 0) { } else { S.inv <- matrix(c(a22/tmp, -a21/tmp, -a12/tmp, a11/tmp), 2, 2) if(logdet) { attr(S.inv, "logdet") <- log(tmp) } } } else if(Sinv.method == "eigen") { EV <- eigen(S, symmetric = TRUE) S.inv <- tcrossprod(EV$vectors / rep(EV$values, each = length(EV$values)), EV$vectors) if(logdet) { if(all(EV$values >= 0)) { attr(S.inv, "logdet") <- sum(log(EV$values)) } else { attr(S.inv, "logdet") <- as.numeric(NA) } } } else if(Sinv.method == "solve") { S.inv <- solve.default(S) if(logdet) { ev <- eigen(S, symmetric = TRUE, only.values = TRUE) if(all(ev$values >= 0)) { attr(S.inv, "logdet") <- sum(log(ev$values)) } else { attr(S.inv, "logdet") <- as.numeric(NA) } } } else if(Sinv.method == "chol") { cS <- chol.default(S) S.inv <- chol2inv(cS) if(logdet) { diag.cS <- diag(cS) attr(S.inv, "logdet") <- sum(log(diag.cS * diag.cS)) } } else { stop("method must be either `eigen', `solve' or `chol'") } if(length(zero.idx) > 0L) { logdet <- attr(S.inv, "logdet") tmp <- S.orig tmp[-zero.idx, -zero.idx] <- S.inv S.inv <- tmp attr(S.inv, "logdet") <- logdet attr(S.inv, "zero.idx") <- zero.idx } S.inv } lav_matrix_inverse_update <- function(A.inv, rm.idx = integer(0L)) { ndel <- length(rm.idx) if(ndel == 1L) { a <- A.inv[-rm.idx, rm.idx, drop = FALSE] b <- A.inv[rm.idx, -rm.idx, drop = FALSE] h <- A.inv[rm.idx, rm.idx] out <- A.inv[-rm.idx, -rm.idx, drop = FALSE] - (a %*% b) / h } else if(ndel < NCOL(A.inv)) { A <- A.inv[-rm.idx, rm.idx, drop = FALSE] B <- A.inv[ rm.idx,-rm.idx, drop = FALSE] H <- A.inv[ rm.idx, rm.idx, drop = FALSE] out <- A.inv[-rm.idx, -rm.idx, drop = FALSE] - A %*% solve.default(H, B) } else if(ndel == NCOL(A.inv)) { out <- matrix(0,0,0) } out } lav_matrix_symmetric_inverse_update <- function(S.inv, rm.idx = integer(0L), logdet = FALSE, S.logdet = NULL) { ndel <- length(rm.idx) if(ndel == 0L) { out <- S.inv if(logdet) { attr(out, "logdet") <- S.logdet } } else if(ndel == 1L) { h <- S.inv[rm.idx, rm.idx] a <- S.inv[-rm.idx, rm.idx, drop = FALSE] / sqrt(h) out <- S.inv[-rm.idx, -rm.idx, drop = FALSE] - tcrossprod(a) if(logdet) { attr(out, "logdet") <- S.logdet + log(h) } } else if(ndel < NCOL(S.inv)) { A <- S.inv[ rm.idx, -rm.idx, drop = FALSE] H <- S.inv[ rm.idx, rm.idx, drop = FALSE] out <- ( S.inv[-rm.idx, -rm.idx, drop = FALSE] - crossprod(A, solve.default(H, A)) ) if(logdet) { H.logdet <- log(det(H)) attr(out, "logdet") <- S.logdet + H.logdet } } else if(ndel == NCOL(S.inv)) { out <- matrix(0,0,0) } else { stop("lavaan ERROR: column indices exceed number of columns in S.inv") } out } lav_matrix_det_update <- function(det.A, A.inv, rm.idx = integer(0L)) { ndel <- length(rm.idx) if(ndel == 1L) { h <- A.inv[rm.idx, rm.idx] out <- det.A * h } else if(ndel < NCOL(A.inv)) { H <- A.inv[ rm.idx, rm.idx, drop = FALSE] det.H <- det(H) out <- det.A * det.H } else if(ndel == NCOL(A.inv)) { out <- matrix(0,0,0) } out } lav_matrix_symmetric_det_update <- function(det.S, S.inv, rm.idx = integer(0L)){ ndel <- length(rm.idx) if(ndel == 1L) { h <- S.inv[rm.idx, rm.idx] out <- det.S * h } else if(ndel < NCOL(S.inv)) { H <- S.inv[ rm.idx, rm.idx, drop = FALSE] cH <- chol.default(H); diag.cH <- diag(cH) det.H <- prod(diag.cH * diag.cH) out <- det.S * det.H } else if(ndel == NCOL(S.inv)) { out <- numeric(0L) } out } lav_matrix_symmetric_logdet_update <- function(S.logdet, S.inv, rm.idx = integer(0L)) { ndel <- length(rm.idx) if(ndel == 1L) { h <- S.inv[rm.idx, rm.idx] out <- S.logdet + log(h) } else if(ndel < NCOL(S.inv)) { H <- S.inv[ rm.idx, rm.idx, drop = FALSE] cH <- chol.default(H); diag.cH <- diag(cH) H.logdet <- sum(log(diag.cH * diag.cH)) out <- S.logdet + H.logdet } else if(ndel == NCOL(S.inv)) { out <- numeric(0L) } out } lav_matrix_symmetric_diff_smallest_root <- function(M = NULL, P = NULL, warn = FALSE) { stopifnot(is.matrix(M), is.matrix(P)) PdiagFlag <- FALSE tmp <- P diag(tmp) <- 0 if( all(abs(tmp) < sqrt(.Machine$double.eps)) ) { PdiagFlag <- TRUE } nP <- nrow(P) diagP <- P[lav_matrix_diag_idx(nP)] neg.idx <- which(diagP < 0) if(length(neg.idx) > 0L) { if(warn) { warning("some diagonal elements of P are negative (and set to zero)") } diag(P)[neg.idx] <- diagP[neg.idx] <- 0 } zero.idx <- which(abs(diagP) < sqrt(.Machine$double.eps)) if(length(zero.idx) == nP) { return(0.0) } else if(length(zero.idx) == 0L) { if(PdiagFlag) { Ldiag <- 1/sqrt(diagP) LML <- t(Ldiag * M) * Ldiag } else { L <- solve(lav_matrix_symmetric_sqrt(P)) LML <- L %*% M %*% t(L) } lambda <- eigen(LML, symmetric = TRUE, only.values = TRUE)$values[nP] } else { M.pp <- M[-zero.idx, -zero.idx, drop = FALSE] M.pn <- M[-zero.idx, zero.idx, drop = FALSE] M.np <- M[ zero.idx, -zero.idx, drop = FALSE] M.nn <- M[ zero.idx, zero.idx, drop = FALSE] Mp.n <- M.pp - M.pn %*% solve(M.nn) %*% M.np P.p <- P[-zero.idx, -zero.idx, drop = FALSE] if(PdiagFlag) { diagPp <- diag(P.p) Ldiag <- 1/sqrt(diagPp) LML <- t(Ldiag * Mp.n) * Ldiag } else { L <- solve(lav_matrix_symmetric_sqrt(P.p)) LML <- L %*% Mp.n %*% t(L) } lambda <- eigen(LML, symmetric = TRUE, only.values = TRUE)$values[nrow(P.p)] } lambda } lav_matrix_symmetric_force_pd <- function(S, tol = 1e-06) { if(ncol(S) == 1L) { return(matrix(max(S[1,1], tol), 1L, 1L)) } S.eigen <- eigen(S, symmetric = TRUE) ev <- S.eigen$values ev[ev/abs(ev[1]) < tol] <- tol*abs(ev[1]) out <- S.eigen$vectors %*% diag(ev) %*% t(S.eigen$vectors) out } lav_matrix_cov <- function(Y, Mu = NULL) { N <- NROW(Y) S1 <- stats::cov(Y) S <- S1 * (N-1) / N if(!is.null(Mu)) { P <- NCOL(Y) ybar <- base::.colMeans(Y, m = N, n = P) S <- S + tcrossprod(ybar - Mu) } S } lav_matrix_transform_mean_cov <- function(Y, target.mean = numeric( NCOL(Y) ), target.cov = diag( NCOL(Y) )) { Y <- as.matrix.default(Y) target.mean <- as.vector(target.mean) S <- lav_matrix_cov(Y) S.inv <- solve.default(S) S.inv.sqrt <- lav_matrix_symmetric_sqrt(S.inv) target.cov.sqrt <- lav_matrix_symmetric_sqrt(target.cov) X <- Y %*% S.inv.sqrt %*% target.cov.sqrt xbar <- colMeans(X) X <- t( t(X) - xbar + target.mean ) X } lav_matrix_mean_wt <- function(Y, wt = NULL) { Y <- unname(as.matrix.default(Y)) DIM <- dim(Y) if(is.null(wt)) { return(colMeans(Y, na.rm = TRUE)) } if(anyNA(Y)) { WT <- wt * !is.na(Y) wN <- .colSums(WT, m = DIM[1], n = DIM[2]) out <- .colSums(wt * Y, m = DIM[1], n = DIM[2], na.rm = TRUE) / wN } else { out <- .colSums(wt * Y, m = DIM[1], n = DIM[2]) / sum(wt) } out } lav_matrix_var_wt <- function(Y, wt = NULL, method = c("unbiased", "ML")) { Y <- unname(as.matrix.default(Y)) DIM <- dim(Y) if(is.null(wt)) { wt <- rep(1, nrow(Y)) } if(anyNA(Y)) { WT <- wt * !is.na(Y) wN <- .colSums(WT, m = DIM[1], n = DIM[2]) w.mean <- .colSums(wt * Y, m = DIM[1], n = DIM[2], na.rm = TRUE) / wN Ytc <- t( t(Y) - w.mean ) tmp <- .colSums(wt * Ytc*Ytc, m = DIM[1], n = DIM[2], na.rm = TRUE) out <- switch(match.arg(method), unbiased = tmp / (wN - 1), ML = tmp / wN) } else { w.mean <- .colSums(wt * Y, m = DIM[1], n = DIM[2]) / sum(wt) Ytc <- t( t(Y) - w.mean ) tmp <- .colSums(wt * Ytc*Ytc, m = DIM[1], n = DIM[2]) out <- switch(match.arg(method), unbiased = tmp / (sum(wt) - 1), ML = tmp / sum(wt)) } out } lav_matrix_cov_wt <- function(Y, wt = NULL) { Y <- unname(as.matrix.default(Y)) DIM <- dim(Y) if(is.null(wt)) { wt <- rep(1, nrow(Y)) } if(anyNA(Y)) { tmp <- na.omit( cbind(Y, wt) ) Y <- tmp[, seq_len(DIM[2]), drop = FALSE] wt <- tmp[,DIM[2] + 1L] DIM[1] <- nrow(Y) w.mean <- .colSums(wt * Y, m = DIM[1], n = DIM[2]) / sum(wt) Ytc <- t( t(Y) - w.mean ) tmp <- crossprod(sqrt(wt) * Ytc) out <- tmp / sum(wt) } else { w.mean <- .colSums(wt * Y, m = DIM[1], n = DIM[2]) / sum(wt) Ytc <- t( t(Y) - w.mean ) tmp <- crossprod(sqrt(wt) * Ytc) out <- tmp / sum(wt) } out } lav_matrix_inverse_iminus <- function(A = NULL) { nr <- nrow(A); nc <- ncol(A) stopifnot(nr == nc) IA <- A diag.idx <- lav_matrix_diag_idx(nr) IA[diag.idx] <- IA[diag.idx] + 1 IA.inv <- IA A2 <- A %*% A if(all(A2 == 0)) { return(IA.inv) } else { IA.inv <- IA.inv + A2 } A3 <- A2 %*% A if(all(A3 == 0)) { return(IA.inv) } else { IA.inv <- IA.inv + A3 } A4 <- A3 %*% A if(all(A4 == 0)) { return(IA.inv) } else { IA.inv <- IA.inv + A4 } A5 <- A4 %*% A if(all(A5 == 0)) { return(IA.inv) } else { IA.inv <- IA.inv + A5 } A6 <- A5 %*% A if(all(A6 == 0)) { return(IA.inv) } else { tmp <- -A tmp[diag.idx] <- tmp[diag.idx] + 1 IA.inv <- solve(tmp) return(IA.inv) } }
check.genotypes <- function(genotypes, geno.enc=c(1,2), minAmount = 20, verbose=FALSE){ if(verbose) cat("check.genotypes: ", ncol(genotypes)," markers, ", nrow(genotypes)," individuals\n") if(length(geno.enc) < 2) stop("argument 'geno.enc' length is incorrect, provide at least two genotype.values") toremove <- NULL idx <- 1 geno.encNaN <- c(geno.enc, NaN, NA) checks <- apply(genotypes,2 , function(geno){ for(x in geno.enc){ if(length(which(geno==x)) <= minAmount){ if(verbose) cat("Severe: Small/Empty group", x ," (size:",length(which(geno==x)),"), removing marker",idx,"\n") toremove <<- c(toremove, idx) } } if(any((geno %in% geno.encNaN) == FALSE)){ if(verbose) cat("Severe: Unknown genotype, removing marker",idx,"\n") toremove <<- c(toremove, idx) } idx <<- idx+1 }) toremove <- unique(toremove) if(length(toremove) > 0){ cat("check.genotypes: Removing", length(toremove),"/",ncol(genotypes), "markers\n") cat(toremove, "\n") } invisible(toremove) } munique <- function(x, ... , na.rm=TRUE){ res <- unique(x, ...) if(na.rm && any(is.na(res))) res <- res[-which(is.na(res))] return(res) } getRVM <- function(n.perms, n.rows){ rvm <- NULL for(x in 1:n.perms){ rvm <- rbind(rvm,sample(n.rows)); } rvm } lodscorestoscanone <- function(cross,lodscores,traitnames = NULL){ mymap <- qtl::pull.map(cross) n <- unlist(lapply(FUN=names,mymap)) chr <- NULL if(!is.null(ncol(mymap[[1]]))){ d <- as.numeric(unlist(lapply(mymap,FUN=function(x) {x[1,]}))) for(i in 1:qtl::nchr(cross)){ chr <- c(chr,rep(names(cross$geno)[i], ncol(mymap[[i]]))) } }else{ d <- as.numeric(unlist(mymap)) for(i in 1:qtl::nchr(cross)){ chr <- c(chr,rep(names(cross$geno)[i], length(mymap[[i]]))) } } qtlprofile <- cbind(chr,d,lodscores) qtlprofile <- as.data.frame(qtlprofile) qtlprofile[,1] <- chr qtlprofile[,2] <- as.numeric(d) if(!is.null(ncol(lodscores))){ for(x in 1:ncol(lodscores)){ qtlprofile[,2+x] <- as.numeric(lodscores[,x]) } traitnames = paste("lod",1:ncol(lodscores)) }else{ qtlprofile[,3] <- as.numeric(lodscores) traitnames = "lod" } rownames(qtlprofile) <- n colnames(qtlprofile) <- c("chr","cM",traitnames) class(qtlprofile) <- c("scanone", "data.frame") invisible(qtlprofile) } gcLoop <- function(verbose = FALSE){ p_usage <- gc()[2,3] n_usage <- gc()[2,3] while(n_usage < p_usage){ p_usage = n_usage n_usage <- gc()[2,3] if(verbose) cat("GCloop ",n_usage," ",p_usage,"\n") } }
lrtCapwire <- function(ecm, tirm, bootstraps=100){ likE <- ecm$likelihood likT <- tirm$likelihood LR <- likT - likE n <- ecm$ml.pop.size s <- ecm$sample.size mpop <- ecm$max.pop get.Lik.Ratio <- function(n, s, max.pop){ dd <- simEcm(n, s) l.ecm <- suppressWarnings(fitEcm(dd, max.pop)$likelihood) l.tirm <- suppressWarnings(fitTirm(dd, max.pop)$likelihood) l.ratio <- l.tirm - l.ecm return(l.ratio) } tstat <- sapply(1:bootstraps, function(x) get.Lik.Ratio(n, s, mpop)) p.value <- (length(which(tstat >= LR) + 1)) / (bootstraps + 1) return(list(LR=LR, p.value=p.value)) }
library(igraph) user <- 'johnmyleswhite' user.net <- suppressWarnings(read.graph(paste("data/", user, "/", user, "_net.graphml", sep = ""), format = "graphml")) user.net <- set.vertex.attribute(user.net, "Label", value = get.vertex.attribute(user.net, "name")) user.cores <- graph.coreness(user.net, mode = "in") user.clean <- subgraph(user.net, which(user.cores > 1) - 1) user.ego <- subgraph(user.net, c(0, neighbors(user.net, user, mode = "out"))) user.sp <- shortest.paths(user.ego) user.hc <- hclust(dist(user.sp)) png(paste('../images/', user, '_dendrogram.png', sep=''), width=1680, height=1050) plot(user.hc) dev.off() for(i in 2:10) { user.cluster <- as.character(cutree(user.hc, k = i)) user.cluster[1] <- "0" user.ego <- set.vertex.attribute(user.ego, name = paste("HC", i, sep = ""), value = user.cluster) } for(i in 2:10) { user.km <- kmeans(dist(user.sp), centers = i) user.cluster <- as.character(user.km$cluster) user.cluster[1] <- "0" user.ego <- set.vertex.attribute(user.ego, name = paste("KM", i, sep = ""), value = user.cluster) } write.graph(user.net, paste("data/", user, "/", user, "_net.graphml", sep = ""), format = "graphml") write.graph(user.clean, paste("data/", user, "/", user, "_clean.graphml", sep = ""), format = "graphml") write.graph(user.ego, paste("data/", user, "/", user, "_ego.graphml", sep = ""), format = "graphml")
expected <- eval(parse(text="\"|The| |quick| |brown| èé\"")); test(id=0, code={ argv <- eval(parse(text="list(\"\\\\b\", \"|\", \"The quick brown èé\", FALSE, TRUE, FALSE, FALSE)")); .Internal(gsub(argv[[1]], argv[[2]], argv[[3]], argv[[4]], argv[[5]], argv[[6]], argv[[7]])); }, o=expected);
context("Getting information on a graph series") test_that("graph series information can be obtained", { empty_series <- create_graph_series() empty_series_info <- empty_series %>% get_graph_series_info() expect_is( empty_series_info, "data.frame") expect_equal( nrow(empty_series_info), 0) expect_equal( ncol(empty_series_info), 7) expect_is( empty_series_info[, 1], "integer") expect_is( empty_series_info[, 2], "character") expect_is( empty_series_info[, 3], "POSIXct") expect_is( empty_series_info[, 4], "character") expect_is( empty_series_info[, 5], "integer") expect_is( empty_series_info[, 6], "integer") expect_is( empty_series_info[, 7], "logical") graph_1 <- create_graph() %>% add_node(type = 1) %>% add_node(type = 2) %>% add_node(type = 3) %>% add_edge( from = 1, to = 3) %>% add_edge( from = 1, to = 2) %>% add_edge( from = 2, to = 3) graph_2 <- graph_1 %>% add_node(type = 4) %>% add_edge( from = 4, to = 3) graph_3 <- graph_2 %>% add_node(type = 5) %>% add_edge( from = 5, to = 2) series <- create_graph_series(series_type = "sequential") series <- series %>% add_graph_to_graph_series( graph = graph_1) %>% add_graph_to_graph_series( graph = graph_2) %>% add_graph_to_graph_series( graph = graph_3) info_on_series <- series %>% get_graph_series_info() expect_is( info_on_series, "data.frame") expect_equal( nrow(info_on_series), 3) expect_equal( ncol(info_on_series), 7) expect_is( info_on_series[, 1], "integer") expect_is( info_on_series[, 2], "character") expect_is( info_on_series[, 3], "POSIXct") expect_is( info_on_series[, 4], "character") expect_is( info_on_series[, 5], "integer") expect_is( info_on_series[, 6], "integer") expect_is( info_on_series[, 7], "logical") expect_equal( info_on_series[1, 1], 1) expect_equal( info_on_series[2, 1], 2) expect_equal( info_on_series[3, 1], 3) graph_series_temporal_type <- create_graph_series(series_type = "temporal") graph <- create_graph( graph_name = "graph_no_tz_provided") %>% set_graph_time( time = "2015-03-25 03:00", tz = "GMT") graph_series_temporal_type <- graph_series_temporal_type %>% add_graph_to_graph_series( graph = graph) info_on_series_temporal <- graph_series_temporal_type %>% get_graph_series_info() expect_is( info_on_series_temporal, "data.frame") expect_equal( nrow(info_on_series_temporal), 1) expect_equal( ncol(info_on_series_temporal), 7) expect_is( info_on_series_temporal[, 1], "integer") expect_is( info_on_series_temporal[, 2], "character") expect_is( info_on_series_temporal[, 3], "POSIXct") expect_is( info_on_series_temporal[, 4], "character") expect_is( info_on_series_temporal[, 5], "integer") expect_is( info_on_series_temporal[, 6], "integer") expect_is( info_on_series_temporal[, 7], "logical") expect_equal( info_on_series_temporal[, 2], "graph_no_tz_provided") expect_true( !is.na(info_on_series_temporal[, 3])) expect_equal( info_on_series_temporal[, 4], "GMT") })
idealToMCMC <- function(object, burnin=NULL){ if(!inherits(object, "ideal")) stop("idealToMCMC only defined for objects of class ideal") if(is.null(burnin)) b <- eval(object$call$burnin) keep <- checkBurnIn(object,b) iters <- as.numeric(dimnames(object$x[keep,,])[[1]]) out <- object$x[keep,,] if(!is.null(object$beta)){ J <- dim(object$beta)[3] for(j in 1:J){ thisBeta <- object$beta[keep,,j] dimnames(thisBeta)[[2]] <- paste(dimnames(thisBeta[[2]]), dimnames(object$beta[[3]])[j]) out <- cbind(out,thisBeta) } } return(coda::mcmc(data=out, start=iters[1], thin=eval(object$call$thin), end=iters[length(iters)] ) ) }
set.seed(1) N <- 1000 X1 <- runif(N) X2 <- runif(N) X3 <- factor(sample(letters[1:4], N, replace = T)) mu <- c(-1, 0, 1, 2)[as.numeric(X3)] p <- 1 / (1 + exp(-(sin(3 * X1) - 4 * X2 + mu))) Y <- rbinom(N, 1, p) w <- rexp(N) w <- N * w / sum(w) data <- data.frame(Y = Y, X1 = X1, X2 = X2, X3 = X3) gbm1 <- gbm( Y ~ X1 + X2 + X3, data = data, weights = w, var.monotone = c(0, 0, 0), distribution = "bernoulli", n.trees = 3000, shrinkage = 0.001, interaction.depth = 3, bag.fraction = 0.5, train.fraction = 0.5, cv.folds = 5, n.cores = 1, n.minobsinnode = 10 ) best.iter.test <- gbm.perf(gbm1, method = "test", plot.it = FALSE) best.iter <- best.iter.test set.seed(2) N <- 1000 X1 <- runif(N) X2 <- runif(N) X3 <- factor(sample(letters[1:4], N, replace = T)) mu <- c(-1, 0, 1, 2)[as.numeric(X3)] p <- 1 / (1 + exp(-(sin(3 * X1) - 4 * X2 + mu))) Y <- rbinom(N, 1, p) data2 <- data.frame(Y = Y, X1 = X1, X2 = X2, X3 = X3) f.1.predict <- predict(gbm1, data2, n.trees = best.iter.test) f.new = sin(3 * X1) - 4 * X2 + mu expect_true(sd(f.new - f.1.predict) < 1.0)
replacemetdata <- function (metdfr, oldmetfile = "met.dat", columns=NULL, newmetfile = "met.dat", khrs=NA, setdates=TRUE){ metlines <- readLines(oldmetfile) datastart <- grep("DATA START", metlines, ignore.case=TRUE) preamble <- readLines(oldmetfile)[1:datastart] if(is.na(khrs)) khrs <- readPAR(oldmetfile,"khrsperday","metformat") N <- nrow(metdfr) if(N %% khrs != 0){ extralines <- N %% khrs metdfr <- metdfr[1:(N-extralines),] } writeLines(preamble, newmetfile) if(setdates){ startdate <- readPAR(oldmetfile,"startdate","metformat") startDate <- as.Date(startdate[1], "'%d/%m/%y'") if(is.na(startDate)) startDate <- as.Date(startdate[1], "%d/%m/%y") enddate <- startDate + N/khrs replacePAR(newmetfile, "enddate","metformat", format(enddate, "%d/%m/%y")) } replacePAR(newmetfile, "nocolumns","metformat", ncol(metdfr)) replacePAR(newmetfile, "khrsperday","metformat", khrs) if(!is.null(columns)) replacePAR(newmetfile,"columns","metformat",columns,noquotes=TRUE) g <- readLines(newmetfile,100) g[grep("data start",g,ignore.case=TRUE)] <- "DATA STARTS" writeLines(g,newmetfile) write.table(metdfr, newmetfile, sep = " ", row.names = FALSE, col.names = FALSE, append = TRUE) }
context("rma") skip_on_cran() skip_if_not_installed("modeltests") library(modeltests) skip_if_not_installed("metafor") library(metafor) skip_if_not_installed("lme4") library(lme4) test_that("metafor::rma tidier arguments", { check_arguments(tidy.rma) check_arguments(glance.rma) check_arguments(augment.rma, strict = FALSE) }) dat <- escalc( measure = "RR", ai = tpos, bi = tneg, ci = cpos, di = cneg, data = dat.bcg ) res.RE <- rma(yi, vi, data = dat, method = "EB", level = 95) res.ME <- rma( yi, vi, mods = ~ I(ablat - 33.46), data = dat, method = "EB" ) res.FE <- rma( yi, vi, mods = ~ I(ablat - 33.46), data = dat, method = "FE" ) dat2 <- data.frame( id = c(100, 308, 1596, 2479, 9021, 9028, 161, 172, 537, 7049), yi = c(-0.33, 0.32, 0.39, 0.31, 0.17, 0.64, -0.33, 0.15, -0.02, 0.00), vi = c(0.084, 0.035, 0.017, 0.034, 0.072, 0.117, 0.102, 0.093, 0.012, 0.067), random = c(0, 0, 0, 0, 0, 0, 1, 1, 1, 1), intensity = c(7, 3, 7, 5, 7, 7, 4, 4, 5, 6) ) res.WFE <- rma(yi, vi, mods = ~ random + intensity, data = dat2, method = "FE") dat.long <- to.long( measure = "OR", ai = tpos, bi = tneg, ci = cpos, di = cneg, data = dat.colditz1994 ) dat.long <- escalc( measure = "PLO", xi = out1, mi = out2, data = dat.long ) dat.long$tpos <- dat.long$tneg <- dat.long$cpos <- dat.long$cneg <- NULL levels(dat.long$group) <- c("EXP", "CON") dat.long$group <- relevel(dat.long$group, ref = "CON") res.MV <- rma.mv( yi, vi, mods = ~ group - 1, random = ~ group | trial, struct = "UN", data = dat.long, method = "ML" ) res.GLMM <- suppressWarnings( rma.glmm( measure = "PLO", xi = ci, ni = n2i, data = dat.nielweise2007 ) ) dat.yusuf1985$grp_ratios <- round(dat.yusuf1985$n1i / dat.yusuf1985$n2i, 2) suppressWarnings( res.peto <- rma.peto( ai = ai, n1i = n1i, ci = ci, n2i = n2i, data = dat.yusuf1985, subset = (table == "6") ) ) dat <- data.frame( age = c("Age <55", "Age 55+"), ai = c(8, 22), bi = c(98, 76), ci = c(5, 16), di = c(115, 69) ) res.MH <- rma.mh( ai = ai, bi = bi, ci = ci, di = di, data = dat, measure = "RD", digits = 3, level = 90 ) check_augment_rma_output <- function(x) { modeltests::check_tibble(x, "augment") } test_that(("tidy.rma"), { re.tidy <- tidy(res.RE, conf.int = TRUE, conf.level = 0.95) check_tidy_output(re.tidy) check_tidy_output(tidy(res.ME)) check_tidy_output(tidy(res.FE)) check_tidy_output(tidy(res.WFE)) check_tidy_output(tidy(res.MV)) check_tidy_output(tidy(res.GLMM)) check_tidy_output(tidy(res.peto)) check_tidy_output(tidy(res.MH)) abs_diff_conf_level <- function(res, conf.level){ res.tidy <- tidy(res.RE, conf.int = TRUE, conf.level = conf.level) return(abs(res.tidy$conf.high - res.tidy$conf.low)) } expect_true(all( abs_diff_conf_level(res.RE, 0.90) < abs_diff_conf_level(res.RE, 0.95), abs_diff_conf_level(res.RE, 0.95) < abs_diff_conf_level(res.RE, 0.99) )) expect_equal(re.tidy$conf.low, res.RE$ci.lb, tolerance = 0.001) expect_equal(re.tidy$conf.high, res.RE$ci.ub, tolerance = 0.001) }) test_that(("glance.rma"), { re.glance <- glance(res.RE) check_glance_outputs(re.glance) check_glance_outputs(glance(res.ME)) check_glance_outputs(glance(res.FE)) check_glance_outputs(glance(res.WFE)) check_glance_outputs(glance(res.MV)) check_glance_outputs(glance(res.GLMM)) check_glance_outputs(glance(res.peto)) check_glance_outputs(glance(res.MH)) fit.stats <- c("logLik", "deviance", "AIC", "BIC", "AICc") expect_true(all(fit.stats %in% names(re.glance))) }) test_that(("augment.rma"), { check_augment_rma_output(augment(res.RE)) check_augment_rma_output(augment(res.ME)) check_augment_rma_output(augment(res.FE)) check_augment_rma_output(augment(res.WFE)) check_augment_rma_output(augment(res.MV)) check_augment_rma_output(augment(res.GLMM)) check_augment_rma_output(augment(res.peto)) check_augment_rma_output(augment(res.MH)) })
globalVariables(c( "var" )) estimate_lambda <- function(n.sim, J, prior.z, overlap, pi0){ n.zones <- length(prior.z) q <- c(1, 1, rep(0, J-1)) var.q <- c(NA, NA, rep(0, J-1)) for(k in 2:J){ unit.zones <- sample(1:n.zones, k*n.sim, replace=TRUE, prob=prior.z) unit.zones <- matrix(unit.zones, ncol=k) no.overlap <- check_overlap(unit.zones, overlap) denom <- rep(factorial(k), n.sim) duplicates <- apply(unit.zones, 1, function(x){length(unique(x))}) duplicates <- which(duplicates != k) for(i in duplicates) { denom[i] <- factorial(k)/prod(factorial(table(unit.zones[i,]))) } q[k+1] <- mean(no.overlap/denom) var.q[k+1] <- var(no.overlap/denom)/n.sim } lambda <- (1-pi0)/( (1-pi0)*J + pi0*sum(q[-1]) ) lambda <- rep(lambda, J) lambda <- c(1-sum(lambda), lambda) prior.j <- normalize(lambda*q) return(list(lambda=lambda, prior.j=prior.j)) }
setMethod("getQuan", "PcaHubert", function(obj) obj@quan) PcaHubert <- function (x, ...) UseMethod("PcaHubert") PcaHubert.formula <- function (formula, data = NULL, subset, na.action, ...) { cl <- match.call() mt <- terms(formula, data = data) if (attr(mt, "response") > 0) stop("response not allowed in formula") mf <- match.call(expand.dots = FALSE) mf$... <- NULL mf[[1]] <- as.name("model.frame") mf <- eval.parent(mf) if (.check_vars_numeric(mf)) stop("PCA applies only to numerical variables") na.act <- attr(mf, "na.action") mt <- attr(mf, "terms") attr(mt, "intercept") <- 0 x <- model.matrix(mt, mf) res <- PcaHubert.default(x, ...) cl[[1]] <- as.name("PcaHubert") res@call <- cl res } PcaHubert.default <- function(x, k=0, kmax=10, alpha=0.75, mcd=TRUE, skew=FALSE, maxdir=250, scale=FALSE, signflip=TRUE, crit.pca.distances=0.975, trace=FALSE, ...) { cl <- match.call() if(missing(x)) stop("You have to provide at least some data") data <- as.matrix(x) n <- nrow(data) p <- ncol(data) Xsvd <- .classPC(data, scale=scale, signflip=signflip, scores=TRUE) if(Xsvd$rank == 0) stop("All data points collapse!") myrank <- Xsvd$rank myscale = if(is.logical(scale) && !scale) vector('numeric', p) + 1 else Xsvd$scale kmax <- max(min(floor(kmax), Xsvd$rank),1) if((k <- floor(k)) < 0) k <- 0 else if(k > kmax) { warning(paste("The number of principal components k = ", k, " is larger then kmax = ", kmax, "; k is set to ", kmax,".", sep="")) k <- kmax } if(missing(alpha)) { default.alpha <- alpha h <- min(h.alpha.n(alpha, n, kmax), n) alpha <- h/n if(k == 0) { if(h < floor((n+kmax+1)/2)) { h <- floor((n+kmax+1)/2) alpha <- h/n warning(paste("h should be larger than (n+kmax+1)/2. It is set to its minimum value ", h, ".", sep="")) } } else { if(h < floor((n+k+1)/2)) { h <- floor((n+k+1)/2) alpha <- h/n warning(paste("h should be larger than (n+k+1)/2. It is set to its minimum value ", h, ".", sep="")) } } if(h > n) { alpha <- default.alpha if(k == 0) h <- h.alpha.n(alpha, n, kmax) else h <- h.alpha.n(alpha, n, k) warning(paste("h should be smaller than n = ", n, ". It is set to its default value ", h, ".", sep="")) } }else { if(alpha < 0.5 | alpha > 1) stop("Alpha is out of range: should be between 1/2 and 1") if(k == 0) h <- h.alpha.n(alpha, n, kmax) else h <- h.alpha.n(alpha, n, k) } X <- Xsvd$scores center <- Xsvd$center rot <- Xsvd$loadings if(mcd && skew) { warning("The adjusted outlyingness algorithm for skewed data (skew=TRUE) cannot be applied with the MCD option (mcd=TRUE): 'mcd=FALSE' will be used.") mcd <- FALSE } if(ncol(X) <= min(floor(n/5), kmax) && mcd) { if(trace) cat("\nApplying MCD.\n") X.mcd <- CovMcd(as.data.frame(X), alpha=alpha) X.mcd.svd <- svd(getCov(X.mcd)) rank <- ncol(X) ev <- X.mcd.svd$d if(trace) cat("\nEigenvalues of S0: ", ev, "\nTotal variance: ", sum(ev), "\nExplained variance: ", cumsum(ev)/sum(ev), "\n") eig0 <- ev totvar0 <- sum(ev) Hsubsets0 <- c() if(k != 0) k <- min(k, ncol(X)) else { test <- which(ev/ev[1] <= 1.E-3) k <- if(length(test) != 0) min(min(rank, test[1]), kmax) else min(rank, kmax) cumulative <- cumsum(ev[1:k])/sum(ev) if(cumulative[k] > 0.8) { k <- which(cumulative >= 0.8)[1] } if(trace) cat("\n k, kmax, rank, p: ", k, kmax, rank, p, "\n") if(trace) cat("The number of principal components is defined by the algorithm. It is set to ", k,".\n", sep="") } scores <- (X - matrix(rep(getCenter(X.mcd), times=nrow(X)), nrow=nrow(X), byrow=TRUE)) %*% X.mcd.svd$u center <- as.vector(center + sweep(getCenter(X.mcd) %*% t(rot), 2, myscale, "*")) eigenvalues <- X.mcd.svd$d[1:k] loadings <- Xsvd$loadings %*% X.mcd.svd$u[,1:k] scores <- as.matrix(scores[,1:k]) if(is.list(dimnames(data)) && !is.null(dimnames(data)[[1]])) { dimnames(scores)[[1]] <- dimnames(data)[[1]] } else { dimnames(scores)[[1]] <- 1:n } dimnames(loadings) <- list(colnames(data), paste("PC", seq_len(ncol(loadings)), sep = "")) dimnames(scores)[[2]] <- as.list(paste("PC", seq_len(ncol(scores)), sep = "")) res <- new("PcaHubert",call=cl, loadings=loadings, eigenvalues=eigenvalues, center=center, scale=myscale, rank=myrank, scores=scores, k=k, quan=X.mcd@quan, alpha=alpha, skew=FALSE, ao=NULL, eig0=eig0, totvar0=totvar0, n.obs=n) } else { if(trace) cat("\nApplying the projection method of Hubert: skew=", skew, "\n") outl <- if(skew) adjOutlyingness(X, ndir=maxdir, alpha.cutoff=alpha, mcfun=mcVT)$adjout else outl(X, maxdir=maxdir, h=h) H0 <- order(outl) Xh <- X[H0[1:h],,drop=FALSE] Xh.svd <- .classPC(Xh) kmax <- min(Xh.svd$rank, kmax) if(trace){ cat("\nEigenvalues of S0: ", Xh.svd$eigenvalues, "\nTotal variance: ", sum(Xh.svd$eigenvalues), "\nExplained variance: ", cumsum(Xh.svd$eigenvalues)/sum(Xh.svd$eigenvalues), "\n") } eig0 <- Xh.svd$eigenvalues totvar0 <- sum(Xh.svd$eigenvalues) Hsubsets0 <- H0[1:h] if(k == 0) { test <- which(Xh.svd$eigenvalues/Xh.svd$eigenvalues[1] <= 1.E-3) k <- if(length(test) != 0) min(min(Xh.svd$rank, test[1]), kmax) else min(Xh.svd$rank, kmax) cumulative <- cumsum(Xh.svd$eigenvalues[1:k])/sum(Xh.svd$eigenvalues) if(cumulative[k] > 0.8) { k <- which(cumulative >= 0.8)[1] } if(trace) cat(paste("The number of principal components is set by the algorithm. It is set to ", k, ".\n", sep="")) } if(trace) cat("\nXsvd$rank, Xh.svd$rank, k and kmax: ", Xsvd$rank, Xh.svd$rank, k, kmax,"\n") if(k != Xsvd$rank) { if(trace) cat("\nPerform extra reweighting step (k != rank)", k) k <- min(Xh.svd$rank, k) XRc <- X - matrix(rep(Xh.svd$center, times=n), nrow=n, byrow=TRUE) Xtilde <- XRc %*% Xh.svd$loadings[,1:k] %*% t(Xh.svd$loadings[,1:k]) Rdiff <- XRc - Xtilde odh <- apply(Rdiff, 1, vecnorm) cutoffodh <- .crit.od(odh, crit=0.975, method=ifelse(skew, "skewed", "umcd"), quan=h) indexset <- (odh <= cutoffodh) if(trace) { cat("\nCutoff for the orthogonal distances:\n.........: ", cutoffodh) cat("\numcd.....: ", .crit.od(odh, method="umcd", quan=h), "\n") cat("\nmedmad...: ", .crit.od(odh), "\n") cat("\nskewed...: ", .crit.od(odh, method="skewed"), "\n") cat("\nclassic..: ", .crit.od(odh, method="classic"), "\n") } Xh.svd <- .classPC(X[indexset,]) k <- min(Xh.svd$rank, k) if(trace) cat("\nPerform extra reweighting step (k != rank)", k, "...Ready.") } center <- center + sweep(Xh.svd$center %*% t(rot), 2, myscale, "*") rot <- rot %*% Xh.svd$loadings X2 <- (X - matrix(rep(Xh.svd$center, times=n), nrow=n, byrow=TRUE)) %*% Xh.svd$loadings X2 <- as.matrix(X2[ ,1:k]) rot <- as.matrix(rot[ ,1:k]) outproj <- if(skew) projectAO(X2, k=k, alpha=alpha, h=h, rot=rot, center=center, scale=myscale, maxdir=maxdir, trace=trace) else projectMCD(X2, ev=Xh.svd$eigenvalues, k=k, alpha=alpha, h=h, niter=100, rot=rot, center=center, scale=myscale, trace=trace) center <- outproj$center eigenvalues <- outproj$eigenvalues loadings <- outproj$loadings scores <- outproj$scores if(is.list(dimnames(data)) && !is.null(dimnames(data)[[1]])) { dimnames(scores)[[1]] <- dimnames(data)[[1]] } else { dimnames(scores)[[1]] <- 1:n } dimnames(loadings) <- list(colnames(data), paste("PC", seq_len(ncol(loadings)), sep = "")) dimnames(scores)[[2]] <- as.list(paste("PC", seq_len(ncol(scores)), sep = "")) res <- new("PcaHubert",call=cl, loadings=loadings, eigenvalues=eigenvalues, center=center, scale=myscale, rank=myrank, scores=scores, k=k, quan=h, alpha=alpha, skew=skew, ao=outproj$ao, eig0=eig0, totvar0=totvar0, n.obs=n) } cl[[1]] <- as.name("PcaHubert") res@call <- cl res <- pca.distances(res, data, Xsvd$rank, crit.pca.distances) return(res) } extradir <- function(data, ndirect, all=TRUE){ if(all) { cc <- combn(nrow(data), 2) B2 <- data[cc[1,],] - data[cc[2,],] } else { if(TRUE){ uniran <- function(seed = 0){ seed<-floor(seed*5761)+999 quot<-floor(seed/65536) seed<-floor(seed)-floor(quot*65536) random<-seed/65536 list(seed=seed, random=random) } randomset <- function(n, k, seed){ ranset <- vector(mode="numeric", length=k) for(j in 1:k){ r <- uniran(seed) seed <- r$seed num <- floor(r$random * n) + 1 if(j > 1){ while(any(ranset == num)){ r <- uniran(seed) seed <- r$seed num <- floor(r$random * n) + 1 } } ranset[j] <- num } ans<-list() ans$seed <- seed ans$ranset <- ranset ans } n <- nrow(data) p <- ncol(data) r <- 1 B2 <- matrix(0,ndirect, p) seed <- 0 while(r <= ndirect) { sseed <- randomset(n, 2, seed) seed <- sseed$seed B2[r,] <- data[sseed$ranset[1], ] - data[sseed$ranset[2],] r <- r + 1 } } else { B2 <- matrix(0,ndirect, ncol(data)) for(r in 1:ndirect) { smpl <- sample(1:nrow(data), 2) B2[r,] <- data[smpl[1], ] - data[smpl[2], ] } } } return(B2) } outl <- function(X, maxdir=250, h) { if(!is.matrix(X)) X <- as.matrix(X) n <- nrow(X) p <- ncol(X) alldir <- choose(n, 2) ndir <- min(maxdir, alldir) all <- (ndir == alldir) B <- extradir(X, ndir, all=all) Bnorm <- vector(mode="numeric", length=nrow(B)) Bnorm <- apply(B, 1, vecnorm) Bnormr <- Bnorm[Bnorm > 1.E-12] m <- length(Bnormr) B <- B[Bnorm > 1.E-12,] A <- diag(1/Bnormr) %*% B Y <- X %*% t(A) Z <- matrix(0,n, m) for(i in 1:m) { umcd <- unimcd(Y[,i], quan=h) if(umcd$smcd < 1.E-12) { if((r2 <- rankMM(X[umcd$weights==1,])) == 1) stop("At least ", sum(umcd$weights), " observations are identical.") } else Z[,i] <- abs(Y[,i] - umcd$tmcd) / umcd$smcd } outl <- apply(Z, 1, max) outl } unimcd <- function(y, quan){ out <- list() ncas <- length(y) len <- ncas-quan+1 if(len == 1){ out$tmcd <- mean(y) out$smcd <- sqrt(var(y)) } else { ay <- c() I <- order(y) y <- y[I] ay[1] <- sum(y[1:quan]) for(samp in 2:len){ ay[samp]<-ay[samp-1]-y[samp-1]+y[samp+quan-1] } ay2<-ay^2/quan sq<-c() sq[1]<-sum(y[1:quan]^2)-ay2[1] for(samp in 2:len){ sq[samp]<-sq[samp-1]-y[samp-1]^2+y[samp+quan-1]^2-ay2[samp]+ay2[samp-1] } sqmin<-min(sq) Isq<-order(sq) ndup<-sum(sq == sqmin) ii<-Isq[1:ndup] slutn<-c() slutn[1:ndup]<-ay[ii] initmean<-slutn[floor((ndup+1)/2)]/quan initcov<-sqmin/(quan-1) res<-(y-initmean)^2/initcov sortres<-sort(res) factor<-sortres[quan]/qchisq(quan/ncas,1) initcov<-factor*initcov res<-(y-initmean)^2/initcov quantile<-qchisq(0.975,1) out$weights<-(res<quantile) out$tmcd<-sum(y*out$weights)/sum(out$weights) out$smcd<-sqrt(sum((y-out$tmcd)^2*out$weights)/(sum(out$weights)-1)) Iinv<-order(I) out$weights<-out$weights[Iinv] } return(out) } projectAO <- function(X2, k, alpha, h, rot, center, scale, maxdir, trace) { ao <- adjOutlyingness(X2, ndir=maxdir, alpha.cutoff=alpha) o2 <- ao$adjout H <- order(o2) X2h <- as.matrix(X2[H[1:h], ]) ee <- eigen(cov(X2h)) P6 <- ee$vectors X2center <- colMeans(X2h) if(trace) cat("\nFinal step - adjusted outlyingness in ", k, "-dimensional subspace used.\n") center <- as.vector(center + sweep(X2center %*% t(rot), 2, scale, "*")) eigenvalues <- ee$values loadings <- rot %*% P6 scores <- sweep(X2, 2, X2center, "-") %*% P6 list(eigenvalues=eigenvalues, loadings=loadings, scores=scores, center=center, ao=o2, ao.cutoff=as.numeric(ao$cutoff)) } projectMCD <- function(X2, ev, k, alpha, h, niter=100, rot, center, scale, trace=trace) { n <- nrow(X2) mah <- mahalanobis(X2, center=rep(0, ncol(X2)), cov=diag(ev[1:k], nrow=k)) oldobj <- prod(ev[1:k]) for(j in 1:niter) { if(trace) cat("\nIter=",j, " h=", h, " k=", k, " obj=", oldobj, "\n") Xh <- X2[order(mah)[1:h], ] Xh.svd <- .classPC(as.matrix(Xh)) obj <- prod(Xh.svd$eigenvalues) X2 <- (X2 - matrix(rep(Xh.svd$center, times=n), nrow=n, byrow=TRUE)) %*% Xh.svd$loadings center <- center + sweep(Xh.svd$center %*% t(rot), 2, scale, "*") rot <- rot %*% Xh.svd$loadings mah <- mahalanobis(X2, center=matrix(0,1, ncol(X2)), cov=diag(Xh.svd$eigenvalues, nrow=length(Xh.svd$eigenvalues))) if(Xh.svd$rank == k & abs(oldobj - obj) < 1.E-12) break oldobj <- obj if(Xh.svd$rank < k) { j <- 1 k <- Xh.svd$rank } } X2mcd <- CovMcd(X2, nsamp=250, alpha=alpha) if(trace) cat("\nMCD crit=",X2mcd@crit," and C-Step obj function=",obj," Abs difference=", abs(X2mcd@crit-obj), "\n") eps <- 1e-16 if(X2mcd@crit < obj + eps) { X2cov <- getCov(X2mcd) X2center <- getCenter(X2mcd) if(trace) cat("\nFinal step - PC of MCD cov used.\n") }else { consistencyfactor <- median(mah)/qchisq(0.5,k) mah <- mah/consistencyfactor weights <- ifelse(mah <= qchisq(0.975, k), TRUE, FALSE) wcov <- cov.wt(x=X2, wt=weights, method="ML") X2center <- wcov$center X2cov <- wcov$cov if(trace) cat("\nFinal step - PC of a reweighted cov used.\n") } ee <- eigen(X2cov) P6 <- ee$vectors center <- as.vector(center + sweep(X2center %*% t(rot), 2, scale, "*")) eigenvalues <- ee$values loadings <- rot %*% P6 scores <- (X2 - matrix(rep(X2center, times=n), nrow=n, byrow=TRUE)) %*% P6 if(trace){ cat("\nEigenvalues of X2:\n") print(eigenvalues) } list(eigenvalues=eigenvalues, loadings=loadings, scores=scores, center=center) }
library(lineprof) library(Gmisc) library(grid) grid.newpage() lineprof({ arrowGrob <- bezierArrowSmpl(x = c(.1,.3,.6,.9), y = c(0.2, 0.2, 0.9, 0.9)) }) -> lp grid.draw(arrowGrob) lineprof::shine(lp) lineprof({ arrowGrob <- bezierArrowGradient(x = c(.1,.3,.6,.9), y = c(0.2, 0.2, 0.9, 0.9)) }) -> lp lineprof::shine(lp)
test_HT_df <- dplyr::tibble( text = c("I really love my dog, he is the best most amazing friend anyone could ever ask for!", "cats are the best most amazing friends anyone could ask for except when they are being miserable horrible terrible demon spawn"), hashtags = c("dog", "cat"), created_at = lubridate::as_datetime(c('2018-02-09 17:56:30', '2018-02-10 18:46:10')), key = c("coolguy123", "crazycatperson1234")) test_HT_Tidy_df <- saotd::tweet_tidy( DataFrame = test_HT_df) test_HT_Scores_Tidy_df <- saotd::tweet_scores( DataFrameTidy = test_HT_Tidy_df, HT_Topic = "hashtag") test_HT <- saotd::tweet_max_scores( DataFrameTidyScores = test_HT_Scores_Tidy_df, HT_Topic = "hashtag") test_HT <- test_HT[[1, 8]] check_HT <- 2 test_HT_selection <- saotd::tweet_max_scores( DataFrameTidyScores = test_HT_Scores_Tidy_df, HT_Topic = "hashtag", HT_Topic_Selection = "dog") test_HT_selection <- test_HT_selection[[1, 8]] check_HT_selection <- 2 test_Topic_df <- dplyr::tibble( text = c("I really love my dog, he is the best most amazing friend anyone could ever ask for!", "cats are the best most amazing friends anyone could ask for except when they are being miserable horrible terrible demon spawn"), Topic = c("dog", "cat"), created_at = lubridate::as_datetime(c('2018-02-09 17:56:30', '2018-02-10 18:46:10')), key = c("coolguy123", "crazycatperson1234")) test_Topic_Tidy_df <- saotd::tweet_tidy( DataFrame = test_Topic_df) test_Topic_Scores_Tidy_df <- saotd::tweet_scores( DataFrameTidy = test_Topic_Tidy_df, HT_Topic = "topic") test_Topic <- saotd::tweet_max_scores( DataFrameTidyScores = test_Topic_Scores_Tidy_df, HT_Topic = "topic") test_Topic <- test_Topic[[1, 8]] check_Topic <- 2 test_Topic_selection <- saotd::tweet_max_scores( DataFrameTidyScores = test_Topic_Scores_Tidy_df, HT_Topic = "topic", HT_Topic_Selection = "dog") test_Topic_selection <- test_Topic_selection[[1, 8]] check_Topic_selection <- 2 testthat::test_that("tweet_max_scores function properly ingests data frame", { testthat::expect_error( object = saotd::tweet_max_scores( DataFrameTidyScores = text), "The input for this function is a data frame.") testthat::expect_error( object = saotd::tweet_max_scores( DataFrameTidyScores = test_HT_Scores_Tidy_df, HT_Topic = "HT"), "HT_Topic requires an input of either hashtag for analysis using hashtags, or topic for analysis looking at topics.") }) testthat::test_that("The tweet_max_scores function using hashtags properly computes scores", { testthat::expect_equal(test_HT, check_HT) }) testthat::test_that("The tweet_max_scores function using topics properly computes scores", { testthat::expect_equal(test_Topic, check_Topic) }) testthat::test_that("The tweet_max_scores function using hashtags and a hashtag selection properly computes scores", { testthat::expect_equal(test_HT_selection, check_HT_selection) }) testthat::test_that("The Max.Scores function using topics and a topic selection properly computes scores", { testthat::expect_equal(test_Topic_selection, check_Topic_selection) })
library(qfasar) context("Test ghost signature") test_obj <- make_ghost(prey_sigs = matrix(c(0.05, 0.10, 0.30, 0.55, 0.04, 0.11, 0.29, 0.56, 0.10, 0.05, 0.35, 0.50, 0.12, 0.03, 0.37, 0.48, 0.10, 0.06, 0.35, 0.49, 0.05, 0.15, 0.35, 0.45), ncol=6), loc = matrix(c(1, 3, 5, 2, 4, 6), ncol=2)) test_that("Objective function is correct",{ expect_equivalent(round(test_obj$dist, 3), 3.751) expect_equivalent(round(test_obj$sig, 2), c(0.14, 0.03, 0.22, 0.61)) })
melt_table <- function(file, locale = default_locale(), na = "NA", skip = 0, n_max = Inf, guess_max = min(n_max, 1000), progress = show_progress(), comment = "", skip_empty_rows = FALSE) { ds <- datasource(file, skip = skip, skip_empty_rows = skip_empty_rows) if (inherits(ds, "source_file") && empty_file(file)) { return(tibble::tibble( row = double(), col = double(), data_type = character(), value = character() )) } columns <- fwf_empty(ds, skip = skip, skip_empty_rows = skip_empty_rows, n = guess_max, comment = comment) tokenizer <- tokenizer_fwf(columns$begin, columns$end, na = na, comment = comment, skip_empty_rows = skip_empty_rows ) ds <- datasource(file = ds, skip = skip, skip_empty_rows = skip_empty_rows) out <- melt_tokens(ds, tokenizer, locale_ = locale, n_max = n_max, progress = progress ) warn_problems(out) } melt_table2 <- function(file, locale = default_locale(), na = "NA", skip = 0, n_max = Inf, progress = show_progress(), comment = "", skip_empty_rows = FALSE) { ds <- datasource(file, skip = skip, skip_empty_rows = skip_empty_rows) if (inherits(ds, "source_file") && empty_file(file)) { return(tibble::tibble( row = double(), col = double(), data_type = character(), value = character() )) } tokenizer <- tokenizer_ws( na = na, comment = comment, skip_empty_rows = skip_empty_rows ) ds <- datasource(file = ds, skip = skip, skip_empty_rows = skip_empty_rows) melt_delimited(ds, tokenizer, locale = locale, skip = skip, comment = comment, n_max = n_max, progress = progress ) }
phongLighting <- function(normals, view, light, color, color2, alpha, material = "default") { if (length(light) == 4) { LI <- light[4] light <- light[1:3] } else LI <- 1 if (is.character(material)) material <- getMaterial(material) ambient <- material$ambient diffuse <- material$diffuse specular <- material$specular exponent <- material$exponent sr <- material$sr V <- view / sqrt(sum(view^2)) L <- light / sqrt(sum(light^2)) H <- (L + V) / sqrt(sum((L + V)^2)) sgn <- as.vector(normals %*% V) > 0 N <- ifelse(sgn,1, -1) * normals Is <- as.vector(specular * abs(N %*% H) ^ exponent) Id <- as.vector(diffuse * pmax(N %*% L,0)) rgbcol <- t(col2rgb(ifelse(sgn, color, color2)) / 255) Lrgbcol <- pmin(LI * ((ambient + Id + sr * Is) * rgbcol + (1 - sr) * Is), 1) Lrgbcol[is.na(Lrgbcol)] <- 0 rgb(Lrgbcol[,1], Lrgbcol[,2], Lrgbcol[,3], alpha) } materials.database <- new.env(hash = TRUE) registerMaterial <- function(name, ambient = 0.3, diffuse = 0.7, specular = 0.1, exponent = 10, sr = 0) { value <- list(ambient = ambient, diffuse = diffuse, specular = specular, exponent = exponent, sr = sr) assign(name, value, materials.database) } getMaterial <- function(name) { if (exists(name, materials.database, inherits = FALSE)) get(name, materials.database) else get("default", materials.database, inherits = FALSE) } registerMaterial("shiny", ambient = 0.3, diffuse = 0.6, specular = 0.9, exponent = 20, sr = 0) registerMaterial("dull", ambient = 0.3, diffuse = 0.8, specular = 0.0, exponent = 10, sr = 0) registerMaterial("metal", ambient = 0.3, diffuse = 0.3, specular = 1.0, exponent = 25, sr = 0.5) registerMaterial("default", ambient = 0.3, diffuse = 0.7, specular = 0.1, exponent = 10, sr = 0) registerMaterial("metal", ambient = 0.45, diffuse = 0.45, specular = 1.5, exponent = 25, sr = 0.5) registerMaterial("shiny", ambient = 0.36, diffuse = 0.72, specular = 1.08, exponent = 20, sr = 0) perspLighting <- function(normals, view, light, color, color2, alpha, material = "default") { if (length(light) == 4) { LI <- light[4] light <- light[1:3] } else LI <- 1 if (is.character(material)) material <- getMaterial(material) exponent <- material$exponent V <- view / sqrt(sum(view^2)) L <- light / sqrt(sum(light^2)) sgn <- as.vector(normals %*% V) > 0 N <- ifelse(sgn,1, -1) * normals I <- (pmax(1 + as.vector(N %*% L), 0) / 2) ^ (exponent * (3 / 40)) Lrgbcol <- I * LI * t(col2rgb(ifelse(sgn, color, color2)) / 255) rgb(Lrgbcol[,1], Lrgbcol[,2], Lrgbcol[,3], alpha) } triangleNormalsPhong <- function(triangles) { N <- triangleNormals(triangles) ve <- t2ve(triangles) vt <- vertexTriangles(ve) VN <- vertexNormals(vt, N) interpolateVertexNormals(VN, ve$ib) } triangleNormalsPhongEX <- function(triangles, reps = 1) { N <- triangleNormals(triangles) ve <- t2ve(triangles) vt <- vertexTriangles(ve) VN <- vertexNormals(vt, N) vb <- ve$vb ib <- ve$ib n.tri <- nrow(N) while (reps > 0) { reps <- reps - 1 n.ver <- nrow(VN) mt <- triangleMidTriangles(vb, ib, VN) vb <- cbind(vb, mt$vb) VN <- rbind(VN, mt$VN) mtib <- mt$ib + n.ver ib <- matrix(rbind(ib[1,], mtib[1,],mtib[3,], mtib[1,], ib[2,],mtib[2,], mtib[2,], ib[3,], mtib[3,], mtib), nrow = 3) for (i in seq(along = triangles)) if (length(triangles[[i]]) == n.tri) triangles[[i]] <- rep(triangles[[i]], each = 4) n.tri <- 4 * n.tri } triangles$N <- interpolateVertexNormals(VN, ib) triangles$v1 <- t(vb[,ib[1,]]) triangles$v2 <- t(vb[,ib[2,]]) triangles$v3 <- t(vb[,ib[3,]]) triangles } triangleNormalsPhongEX <- function(triangles, reps = 1) { N <- triangleNormals(triangles) ve <- t2ve(triangles) vt <- vertexTriangles(ve) VN <- vertexNormals(vt, N) vb <- ve$vb ib <- ve$ib n.tri <- nrow(N) color <- rep(triangles$color, length = n.tri) color2 <- rep(triangles$color2, length = n.tri) col.mesh <- rep(triangles$col.mesh, length = n.tri) color2 <- ifelse(is.na(color2), color, color2) col.mesh <- ifelse(is.na(col.mesh), color, col.mesh) VC <- vertexColors(vt, color) VC2 <- vertexColors(vt, color2) VCm <- vertexColors(vt, col.mesh) while (reps > 0) { reps <- reps - 1 n.ver <- nrow(VN) edges <- triangleEdges(vb, ib) VC <- rbind(VC, (VC[edges[1,],] + VC[edges[2,],]) / 2) VC2 <- rbind(VC2, (VC2[edges[1,],] + VC2[edges[2,],]) / 2) VCm <- rbind(VCm, (VCm[edges[1,],] + VCm[edges[2,],]) / 2) mt <- triangleMidTriangles(vb, ib, VN) vb <- cbind(vb, mt$vb) VN <- rbind(VN, mt$VN) mtib <- mt$ib + n.ver ib <- matrix(rbind(ib[1,], mtib[1,],mtib[3,], mtib[1,], ib[2,],mtib[2,], mtib[2,], ib[3,], mtib[3,], mtib), nrow = 3) for (i in seq(along = triangles)) if (length(triangles[[i]]) == n.tri) triangles[[i]] <- rep(triangles[[i]], each = 4) n.tri <- 4 * n.tri } triangles$color <- interpolateVertexColors(VC, ib) triangles$color2 <- interpolateVertexColors(VC2, ib) triangles$color.mesh <- interpolateVertexColors(VCm, ib) triangles$N <- interpolateVertexNormals(VN, ib) triangles$v1 <- t(vb[,ib[1,]]) triangles$v2 <- t(vb[,ib[2,]]) triangles$v3 <- t(vb[,ib[3,]]) triangles } lightTriangles <- function(triangles, lighting, light) { view <- c(0, 0, 1) normals <- triangleNormals(triangles) smooth <- if (is.null(triangles$smooth)) 0 else triangles$smooth if (smooth == 0) normals <- triangleNormals(triangles) else if (smooth == 1) normals <- triangleNormalsPhong(triangles) else { triangles <- triangleNormalsPhongEX(triangles, reps = smooth - 1) normals <- triangles$N } n.tri <- nrow(normals) color <- rep(triangles$color, length = n.tri) color2 <- rep(triangles$color2, length = n.tri) color2 <- ifelse(is.na(color2), color, color2) alpha <- rep(triangles$alpha, length = n.tri) mat <- triangles$material triangles$col.light <- lighting(normals, view, light, color, color2, alpha, mat) triangles } lightScene <- function(scene, lighting, light) { if (is.Triangles3D(scene)) lightTriangles(scene, lighting, light) else lapply(scene, lightTriangles, lighting, light) }
SatVapPresSlope <- function(temp_C){ (2508.3/(temp_C+237.3)^2)*exp(17.3*temp_C/(temp_C+237.3)) }
isStrictlyPositiveNumberOrNaOrNanOrInfVector <- function(argument, default = NULL, stopIfNot = FALSE, n = NA, message = NULL, argumentName = NULL) { checkarg(argument, "N", default = default, stopIfNot = stopIfNot, nullAllowed = FALSE, n = NA, zeroAllowed = FALSE, negativeAllowed = FALSE, positiveAllowed = TRUE, nonIntegerAllowed = TRUE, naAllowed = TRUE, nanAllowed = TRUE, infAllowed = TRUE, message = message, argumentName = argumentName) }
GeomSiiRisksurface <- ggplot2::ggproto( "_class" = "GeomSiiRisksurface", "_inherit" = ggplot2::GeomPolygon ) GeomSiiRiskoutline <- ggplot2::ggproto( "_class" = "GeomSiiRiskoutline", "_inherit" = ggplot2::GeomPath ) GeomSiiRiskconnection <- ggplot2::ggproto( "_class" = "GeomSiiRiskconnection", "_inherit" = ggplot2::GeomSegment ) geom_sii_risksurface <- function(data = NULL, mapping = NULL, stat = "sii_risksurface", structure = ggsolvencyii::sii_structure_sf16_eng, squared = FALSE, levelmax = 99, aggregatesuffix = "_other", plotdetails = NULL, rotationdegrees = NULL, rotationdescription = NULL, maxscrvalue = NULL, scalingx = 1, scalingy = 1, position = "identity", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, ... ) { ggplot2::layer(data = data, stat = stat, geom = GeomSiiRisksurface, mapping = mapping, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list( na.rm = na.rm, levelmax = levelmax, structure = structure, maxscrvalue = maxscrvalue, aggregatesuffix = aggregatesuffix, scalingx = scalingx, scalingy = scalingy, rotationdegrees = rotationdegrees, rotationdescription = rotationdescription, squared = squared, plotdetails = plotdetails, tocenter = FALSE, relalpha = FALSE, purpose = "surface", ... ) ) } geom_sii_riskoutline <- function(data = NULL, mapping = NULL, stat = "sii_riskoutline", structure = ggsolvencyii::sii_structure_sf16_eng, squared = FALSE, levelmax = 99, aggregatesuffix = "_other", plotdetails = NULL, rotationdegrees = NULL, rotationdescription = NULL, maxscrvalue = NULL, scalingx = 1, scalingy = 1, position = "identity", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, ... ) { ggplot2::layer( data = data, stat = stat, geom = GeomSiiRiskoutline, mapping = mapping, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list( na.rm = na.rm, structure = structure, squared = squared, levelmax = levelmax, aggregatesuffix = aggregatesuffix, plotdetails = plotdetails, tocenter = FALSE, relalpha = FALSE, maxscrvalue = maxscrvalue, scalingx = scalingx, scalingy = scalingy, rotationdegrees = rotationdegrees, rotationdescription = rotationdescription, purpose = "outline", ... ) ) } geom_sii_riskconnection <- function(data = NULL, mapping = NULL, stat = "sii_riskconnection", position = "identity", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, ... ) { ggplot2::layer(data = data, stat = stat, geom = GeomSiiRiskconnection, mapping = mapping, position = position, show.legend = FALSE, inherit.aes = inherit.aes, params = list( na.rm = na.rm, ... ) ) } StatSiiRisksurface <- ggplot2::ggproto( "_class" = "StatSiiRisksurface", "_inherit" = ggplot2::Stat, required_aes = c("id", "x", "y", "description", "value"), setup_params = function(data, params) { params$maxscrvalue <- fn_maxscrvalue(data = data, params = params) if (is.null(params$plotdetails) ) { params$plotdetails <- fn_constructionplotdetails(params$structure) } return(params) }, setup_data = function(data, params) { data_out <- fn_setupdata_surfaces(data = data, params = params) return(data_out) }, compute_group = function(data, scales, levelmax, structure, maxscrvalue, aggregatesuffix, scalingx, scalingy, rotationdegrees, rotationdescription, squared, plotdetails, tocenter, relalpha, purpose, ... ) { siiparams <- list(levelmax = levelmax, structure = structure, maxscrvalue = maxscrvalue, aggregatesuffix = aggregatesuffix, scalingx = scalingx, scalingy = scalingy, rotationdegrees = rotationdegrees, rotationdescription = rotationdescription, squared = squared, plotdetails = plotdetails, tocenter = tocenter, relalpha = relalpha, purpose = purpose) df <- fn_computegroup( data = data, siiparams = siiparams, ... ) df <- df$df df <- dplyr::mutate(df, x_org = x, y_org = y) df <- dplyr::mutate(df, x = x + xpoint * scalingx, y = y + ypoint * scalingy) return(df) }, finish_layer = function(data, scales, params) { return(data) } ) StatSiiRiskoutline <- ggplot2::ggproto( "_class" = "StatSiiRiskoutline", "_inherit" = ggplot2::Stat, required_aes = c("id", "x", "y", "description", "value", "comparewithid"), default_aes = ggplot2::aes(color = "red", lwd = 0.2, comparewithid = 2 ), setup_params = function(data, params) { params$maxscrvalue <- fn_maxscrvalue(data = data, params = params) if (is.null(params$plotdetails)) { params$plotdetails <- fn_constructionplotdetails(params$structure) } return(params) }, setup_data = function(data, params) { if (!"comparewithid" %in% colnames(data)){ message("comparewithid is set to reference itself") data$comparewithid <- data$id } else { } data_out <- fn_setupdata_outline(data = data, params = params) return(data_out) }, compute_group = function(data, scales, levelmax, structure, maxscrvalue, aggregatesuffix, scalingx, scalingy, rotationdegrees, rotationdescription, squared, plotdetails, tocenter, relalpha, purpose, ... ) { siiparams <- list(levelmax = levelmax, structure = structure, maxscrvalue = maxscrvalue, aggregatesuffix = aggregatesuffix, scalingx = scalingx, scalingy = scalingy, rotationdegrees = rotationdegrees, rotationdescription = rotationdescription, squared = squared, plotdetails = plotdetails, tocenter = tocenter, relalpha = relalpha, purpose = purpose) df <- fn_computegroup(data = data, scales = scales, siiparams = siiparams ) df <- df$df df <- dplyr::mutate(df, x_org = x, y_org = y) df <- dplyr::mutate(df, x = x + xpoint * scalingx, y = y + ypoint * scalingy) return(df) }, finish_layer = function(data, scales, params) { return(data) } ) StatSiiRiskconnection <- ggplot2::ggproto( "_class" = "StatSiiRiskconnection", "_inherit" = ggplot2::Stat, required_aes = c("id", "x", "y", "comparewithid"), setup_data = function(data, params) { data <- fn_setupdata_connection(data = data) return(data) }, compute_group = function(data, scales, ...) { return(data) } ) stat_sii_risksurface <- function(mapping = NULL, data = NULL, geom = "sii_risksurface", position = "identity", show.legend = TRUE, inherit.aes = TRUE, na.rm = FALSE, levelmax = 99, structure = ggsolvencyii::sii_structure_sf16_eng, maxscrvalue = NULL, aggregatesuffix = "_other", scalingx = 1, scalingy = 1, rotationdegrees = NULL, rotationdescription = NULL, squared = FALSE, plotdetails = NULL, ... ) { ggplot2::layer(mapping = mapping, data = data, stat = "sii_risksurface", geom = geom, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list(na.rm = na.rm, levelmax = levelmax, structure = structure, maxscrvalue = maxscrvalue, aggregatesuffix = aggregatesuffix, scalingx = scalingx, scalingy = scalingy, rotationdegrees = rotationdegrees, rotationdescription = rotationdescription, plotdetails = plotdetails, purpose = "surface", ... ) ) }
miller_rabin <- function(n) { stopifnot(is.numeric(n), length(n) == 1) if (floor(n) != ceiling(n) || n <= 0) { stop("Argument 'n' must be a natural number.") } if (n < 2) { return(FALSE) } else if (n == 2) {return(TRUE) } else if (n %% 2 == 0) {return(FALSE) } else if (n >= 2^53) { stop("Argument 'n' too large to be handled as integer.") } if (!requireNamespace("gmp", quietly = TRUE)) { stop("Package 'gmp' needed: Please install separately.", call. = FALSE) } if (n < 2047) { N <- c(2) } else if (n < 1373653) { N <- c(2, 3) } else if (n < 25326001) { N <- c(2, 3, 5) } else if (n < 3215031751) { N <- c(2, 3, 5, 7) } else if (n < 2152302898747) { N <- c(2, 3, 5, 7, 11) } else if (n < 3474749660383) { N <- c(2, 3, 5, 7, 11, 13) } else if (n < 341550071728321) { N <- c(2, 3, 5, 7, 11, 13, 17) } else { N <- c(2, 3, 5, 7, 11, 13, 17, 23) } m <- n-1; s <- 0 while ((m %% 2) == 0) { s <- s + 1 m <- m / 2 } for (a in N) { if (a >= n) break x <- gmp::powm(a, m, n) if (x == 1) next t <- s while (x != (n-1)) { t <- t-1 if (t <= 0) return(FALSE) x = ((x*x) %% n) if (x == 1) return(FALSE) } } return(TRUE) }
make.args <- function(..., PRE.ARGS=list(), POST.ARGS=list()) { a <- list() l <- c(PRE.ARGS, list(...), POST.ARGS) for (name in unique(names(l))) { a[[name]] <- l[[name]] } return(a) } `plot.randomLCA` <- function(x,...,graphtype=ifelse(x$random,"marginal","conditional"),conditionalp=0.5,classhorizontal=TRUE) { if (!inherits(x, "randomLCA")) stop("Use only with 'randomLCA' objects.\n") if (missing(graphtype)) graphtype <- ifelse(x$random,"marginal","conditional") graphdata <- NULL if (graphtype=="marginal") { graphdata <- calcMargProb(x) graphdata <- cbind(perc=rep(0,dim(graphdata)[1]),graphdata) } if (graphtype=="conditional") graphdata <- calcCondProb(x,conditionalp) if (graphtype=="conditional2") graphdata <- calcCond2Prob(x,conditionalp) if (x$level2) blocksize <- x$level2size else blocksize <- x$blocksize noblocks <- dim(x$patterns)[2] %/% blocksize if (x$level2 | (blocksize!=dim(x$patterns)[2])) { thenames <- names(x$patterns) thenames <- strsplit(thenames,"\\.") temp <- NULL for (i in 1:noblocks) { temp <- c(temp,thenames[[1+(i-1)*blocksize]][2]) } thenames <- temp } else thenames <- names(x$patterns) if (blocksize==dim(x$patterns)[2]) { if (graphtype=="marginal") { arg.list <- make.args(..., x = as.formula("outcomep~outcome"), group=graphdata$class, data=graphdata, ylim=c(-0.05,1.05), xlab="Outcome", ylab="Outcome Prob.", scales=list(x=list(at=1:length(thenames),labels=thenames)) ) print(do.call(xyplot, arg.list)) } if ((graphtype=="conditional") || (graphtype=="conditional2")) { if (length(conditionalp)>1) { arg.list <- make.args(..., x = as.formula("outcomep~outcome|perc"), group=graphdata$class, data=graphdata, ylim=c(-0.05,1.05), xlab="Outcome", ylab="Outcome Prob.", scales=list(x=list(at=1:length(thenames),labels=thenames),alternating=FALSE) ) print(do.call(xyplot, arg.list)) } else { arg.list <- make.args(..., x = as.formula("outcomep~outcome"), group=graphdata$class, data=graphdata, ylim=c(-0.05,1.05), xlab="Outcome", ylab="Outcome Prob.", scales=list(x=list(at=1:length(thenames),labels=thenames)) ) print(do.call(xyplot, arg.list)) } } } else { if (classhorizontal) { if (graphtype=="marginal"){ arg.list <- make.args(..., x = as.formula("outcomep~block|class"), group=graphdata$outcome, data=graphdata, ylim=c(-0.05,1.05), xlab="Block", ylab="Outcome Prob.", scales=list(x=list(at=1:length(thenames),labels=thenames),alternating=FALSE) ) print(do.call(xyplot, arg.list)) } if ((graphtype=="conditional") || (graphtype=="conditional2")) { if (length(conditionalp)>1) { arg.list <- make.args(..., x = as.formula("outcomep~block|class*perc"), group=graphdata$outcome, data=graphdata, ylim=c(-0.05,1.05), xlab="Block", ylab="Outcome Prob.", scales=list(x=list(at=1:length(thenames),labels=thenames),alternating=FALSE) ) print(do.call(xyplot, arg.list)) } else { arg.list <- make.args(..., x = as.formula("outcomep~block|class"), group=graphdata$outcome, data=graphdata, ylim=c(-0.05,1.05), xlab="Block", ylab="Outcome Prob.", scales=list(x=list(at=1:length(thenames),labels=thenames),alternating=FALSE) ) print(do.call(xyplot, arg.list)) } } } else { if (graphtype=="marginal") { arg.list <- make.args(..., x = as.formula("outcomep~block|class"), group=graphdata$outcome, data=graphdata, ylim=c(-0.05,1.05), xlab="Block", ylab="Outcome Prob.", scales=list(x=list(at=1:length(thenames),labels=thenames),alternating=FALSE) ) print(do.call(xyplot, arg.list)) } if ((graphtype=="conditional") || (graphtype=="conditional2")) { if (length(conditionalp)>1) arg.list <- make.args(..., x = as.formula("outcomep~block|perc*class"), group=graphdata$outcome, data=graphdata, ylim=c(-0.05,1.05), xlab="Block", ylab="Outcome Prob.", scales=list(x=list(at=1:length(thenames),labels=thenames),alternating=FALSE) ) print(do.call(xyplot, arg.list)) } else { if (length(conditionalp)>1) arg.list <- make.args(..., x = as.formula("outcomep~block|perc*class"), group=graphdata$outcome, data=graphdata, ylim=c(-0.05,1.05), xlab="Block", ylab="Outcome Prob.", scales=list(x=list(at=1:length(thenames),labels=thenames),alternating=FALSE) ) print(do.call(xyplot, arg.list)) } } } }
NULL Geom <- gganimintproto("Geom", required_aes = character(), non_missing_aes = character(), default_aes = aes(), draw_key = draw_key_point, handle_na = function(self, data, params) { remove_missing(data, params$na.rm, c(self$required_aes, self$non_missing_aes), snake_class(self) ) }, draw_layer = function(self, data, params, panel, coord) { if (empty(data)) { n <- if (is.factor(data$PANEL)) nlevels(data$PANEL) else 1L return(rep(list(zeroGrob()), n)) } params <- params[intersect(names(params), self$parameters())] args <- c(list(quote(data), quote(panel_scales), quote(coord)), params) plyr::dlply(data, "PANEL", function(data) { if (empty(data)) return(zeroGrob()) panel_scales <- panel$ranges[[data$PANEL[1]]] do.call(self$draw_panel, args) }, .drop = FALSE) }, draw_panel = function(self, data, panel_scales, coord, ...) { groups <- split(data, factor(data$group)) grobs <- lapply(groups, function(group) { self$draw_group(group, panel_scales, coord, ...) }) ggname(snake_class(self), gTree( children = do.call("gList", grobs) )) }, draw_group = function(self, data, panel_scales, coord) { stop("Not implemented") }, setup_data = function(data, params) data, use_defaults = function(self, data, params = list()) { missing_aes <- setdiff(names(self$default_aes), names(data)) if (empty(data)) { data <- plyr::quickdf(self$default_aes[missing_aes]) } else { data[missing_aes] <- self$default_aes[missing_aes] } aes_params <- intersect(self$aesthetics(), names(params)) check_aesthetics(params[aes_params], nrow(data)) data[aes_params] <- params[aes_params] data }, extra_params = c("na.rm"), parameters = function(self, extra = FALSE) { panel_args <- names(gganimintproto_formals(self$draw_panel)) group_args <- names(gganimintproto_formals(self$draw_group)) args <- if ("..." %in% panel_args) group_args else panel_args args <- setdiff(args, names(gganimintproto_formals(Geom$draw_group))) if (extra) { args <- union(args, self$extra_params) } args }, aesthetics = function(self) { c(union(self$required_aes, names(self$default_aes)), "group") }, pre_process = function(g, g.data, ranges){ list(g = g, g.data = g.data) }, export_animint = function(l, d, meta, layer_name, ggplot, built, AnimationInfo) { xminv <- y <- xmaxv <- chunks.for <- NULL g <- list(geom=strsplit(layer_name, "_")[[1]][2]) g$classed <- layer_name ranges <- built$panel$ranges g$aes <- sapply(l$mapping, function(k) as.character(as.expression(k))) g$params <- getLayerParams(l) s.aes <- selectSSandCS(g$aes) meta$selector.aes[[g$classed]] <- s.aes do.not.copy <- colsNotToCopy(g, s.aes) copy.cols <- ! names(d) %in% do.not.copy g.data <- d[copy.cols] is.ss <- names(g$aes) %in% s.aes$showSelected$one show.vars <- g$aes[is.ss] pre.subset.order <- as.list(names(show.vars)) is.cs <- names(g$aes) %in% s.aes$clickSelects$one update.vars <- g$aes[is.ss | is.cs] update.var.names <- if(0 < length(update.vars)){ data.frame(variable=names(update.vars), value=NA) } interactive.aes <- with(s.aes, { rbind(clickSelects$several, showSelected$several, update.var.names) }) for(row.i in seq_along(interactive.aes$variable)){ aes.row <- interactive.aes[row.i, ] is.variable.value <- !is.na(aes.row$value) selector.df <- if(is.variable.value){ selector.vec <- g.data[[paste(aes.row$variable)]] data.frame(value.col=aes.row$value, selector.name=unique(paste(selector.vec))) }else{ value.col <- paste(aes.row$variable) data.frame(value.col, selector.name=update.vars[[value.col]]) } for(sel.i in 1:nrow(selector.df)){ sel.row <- selector.df[sel.i,] value.col <- paste(sel.row$value.col) selector.name <- paste(sel.row$selector.name) meta$selectors[[selector.name]]$is.variable.value <- is.variable.value if(is.null(meta$selectors[[selector.name]]$type)){ selector.type <- meta$selector.types[[selector.name]] if(is.null(selector.type))selector.type <- "single" stopifnot(is.character(selector.type)) stopifnot(length(selector.type)==1) stopifnot(selector.type %in% c("single", "multiple")) meta$selectors[[selector.name]]$type <- selector.type } for(look.for in c("showSelected", "clickSelects")){ if(grepl(look.for, aes.row$variable)){ meta$selectors[[selector.name]][[look.for]] <- TRUE } } value.vec <- unique(g.data[[value.col]]) key <- paste(g$classed, row.i, sel.i) meta$selector.values[[selector.name]][[key]] <- list(values=paste(value.vec), update=g$classed) } } is.show <- grepl("showSelected", names(g$aes)) has.show <- any(is.show) stat.type <- class(l$stat)[[1]] checkForNonIdentityAndSS(stat.type, has.show, is.show, l, g$classed, names(g.data), names(g$aes)) position.type <- class(l$position)[[1]] if(has.show && position.type != "PositionIdentity"){ print(l) warning("showSelected only works with position=identity, problem: ", g$classed) } processed_values <- l$geom$pre_process(g, g.data, ranges) g <- processed_values$g g.data <- processed_values$g.data for(color.var in c("colour", "color", "fill")){ if(color.var %in% names(g.data)){ g.data[,color.var] <- toRGB(g.data[,color.var]) } if(color.var %in% names(g$params)){ g$params[[color.var]] <- toRGB(g$params[[color.var]]) } } has.no.fill <- g$geom %in% c("path", "line") zero.size <- any(g.data$size == 0, na.rm=TRUE) if(zero.size && has.no.fill){ warning(sprintf("geom_%s with size=0 will be invisible",g$geom)) } if(inherits(ggplot$coordinates, "CoordFlip")){ names(g.data) <- switch_axes(names(g.data)) } g$types <- sapply(g.data, function(x) { type <- paste(class(x), collapse="-") if(type == "character"){ if(sum(!is.rgb(x))==0){ "rgb" }else if(sum(!is.linetype(x))==0){ "linetype" }else { "character" } }else{ type } }) g$types[["group"]] <- "character" ordfactidx <- which(g$types=="ordered-factor") for(i in ordfactidx){ g.data[[i]] <- factor(as.character(g.data[[i]])) g$types[[i]] <- "factor" } time.col <- NULL if(is.list(AnimationInfo$time)){ g.time.list <- list() for(c.or.s in names(s.aes)){ cs.info <- s.aes[[c.or.s]] for(a in cs.info$one){ if(g$aes[[a]] == AnimationInfo$time$var){ g.time.list[[a]] <- g.data[[a]] time.col <- a } } for(row.i in seq_along(cs.info$several$value)){ cs.row <- cs.info$several[row.i,] c.name <- paste(cs.row$variable) is.time <- g.data[[c.name]] == AnimationInfo$time$var g.time.list[[c.name]] <- g.data[is.time, paste(cs.row$value)] } } u.vals <- unique(unlist(g.time.list)) if(length(u.vals)){ AnimationInfo$timeValues[[paste(g$classed)]] <- sort(u.vals) } } if(length(time.col)){ pre.subset.order <- pre.subset.order[order(pre.subset.order != time.col)] } subset.vec <- unlist(pre.subset.order) if("chunk_vars" %in% names(g$params)){ designer.chunks <- g$params$chunk_vars if(!is.character(designer.chunks)){ stop("chunk_vars must be a character vector; ", "use chunk_vars=character() to specify 1 chunk") } not.subset <- !designer.chunks %in% g$aes[subset.vec] if(any(not.subset)){ stop("invalid chunk_vars ", paste(designer.chunks[not.subset], collapse=" "), "; possible showSelected variables: ", paste(g$aes[subset.vec], collapse=" ")) } is.chunk <- g$aes[subset.vec] %in% designer.chunks chunk.cols <- subset.vec[is.chunk] nest.cols <- subset.vec[!is.chunk] }else{ if(length(meta$selectors)==0){ nest.cols <- subset.vec chunk.cols <- NULL }else{ selector.types <- sapply(meta$selectors, "[[", "type") selector.names <- g$aes[subset.vec] subset.types <- selector.types[selector.names] can.chunk <- subset.types != "multiple" names(can.chunk) <- subset.vec tmp <- tempfile() some.lines <- rbind(head(g.data), tail(g.data)) write.table(some.lines, tmp, col.names=FALSE, quote=FALSE, row.names=FALSE, sep="\t") bytes <- file.info(tmp)$size bytes.per.line <- bytes/nrow(some.lines) bad.chunk <- function(){ if(all(!can.chunk))return(NULL) can.chunk.cols <- subset.vec[can.chunk] maybe.factors <- g.data[, can.chunk.cols, drop=FALSE] for(N in names(maybe.factors)){ maybe.factors[[N]] <- paste(maybe.factors[[N]]) } rows.per.chunk <- table(maybe.factors) bytes.per.chunk <- rows.per.chunk * bytes.per.line if(all(4096 < bytes.per.chunk))return(NULL) dim.byte.list <- list() if(length(can.chunk.cols) == 1){ dim.byte.list[[can.chunk.cols]] <- sum(bytes.per.chunk) }else{ for(dim.i in seq_along(can.chunk.cols)){ dim.name <- can.chunk.cols[[dim.i]] dim.byte.list[[dim.name]] <- apply(bytes.per.chunk, -dim.i, sum) } } selector.df <- data.frame(chunks.for=length(rows.per.chunk), chunks.without=sapply(dim.byte.list, length), min.bytes=sapply(dim.byte.list, min)) not.one <- subset(selector.df, 1 < chunks.for) if(nrow(not.one) == 0){ NULL }else{ rownames(not.one)[[which.max(not.one$min.bytes)]] } } while({ bad <- bad.chunk() !is.null(bad) }){ can.chunk[[bad]] <- FALSE } if(any(can.chunk)){ nest.cols <- subset.vec[!can.chunk] chunk.cols <- subset.vec[can.chunk] }else{ nest.cols <- subset.vec chunk.cols <- NULL } } } plot.has.panels <- nrow(built$panel$layout) > 1 g.data <- removeUniquePanelValue(g.data, plot.has.panels) if(length(chunk.cols)){ selector.names <- as.character(g$aes[chunk.cols]) chunk.name <- paste(selector.names, collapse="_") g$chunk_order <- as.list(selector.names) for(selector.name in selector.names){ meta$selectors[[selector.name]]$chunks <- unique(c(meta$selectors[[selector.name]]$chunks, chunk.name)) } }else{ g$chunk_order <- list() } g$nest_order <- as.list(nest.cols) names(g$chunk_order) <- NULL names(g$nest_order) <- NULL g$subset_order <- g$nest_order if(plot.has.panels){ g$subset_order <- c(g$subset_order, "PANEL") g$nest_order <- c(g$nest_order, "PANEL") } if((nrow(s.aes$showSelected$several) > 0)){ g$nest_order <- with(s.aes$showSelected$several, { c(g$nest_order, paste(variable), paste(value)) }) g$subset_order <- c(g$subset_order, paste(s.aes$showSelected$several$variable)) } data.object.geoms <- c("line", "path", "ribbon", "polygon") if("group" %in% names(g$aes) && g$geom %in% data.object.geoms){ g$nest_order <- c(g$nest_order, "group") } if(any(is.na(g.data)) && "group" %in% names(g$aes)){ sp.cols <- unlist(c(chunk.cols, g$nest_order)) order.args <- list() for(sp.col in sp.cols){ order.args[[sp.col]] <- g.data[[sp.col]] } ord <- do.call(order, order.args) g.data <- g.data[ord,] is.missing <- apply(is.na(g.data), 1, any) diff.vec <- diff(is.missing) new.group.vec <- c(FALSE, diff.vec == 1) for(chunk.col in sp.cols){ one.col <- g.data[[chunk.col]] is.diff <- c(FALSE, one.col[-1] != one.col[-length(one.col)]) new.group.vec[is.diff] <- TRUE } subgroup.vec <- cumsum(new.group.vec) g.data$group <- subgroup.vec } for(xy in c("x", "y")){ range.name <- paste0(xy, ".range") range.mat <- sapply(ranges, "[[", range.name) xy.col.vec <- grep(paste0("^", xy), names(g.data), value=TRUE) xy.col.df <- g.data[, xy.col.vec, drop=FALSE] cmp.list <- list(`<`, `>`) for(row.i in seq_along(cmp.list)){ panel.vec <- if("PANEL" %in% names(g.data)){ g.data$PANEL }else{ rep(1, nrow(g.data)) } extreme.vec <- range.mat[row.i, panel.vec] cmp <- cmp.list[[row.i]] to.rep <- cmp(xy.col.df, extreme.vec) row.vec <- row(to.rep)[to.rep] xy.col.df[to.rep] <- extreme.vec[row.vec] } g.data[, xy.col.vec] <- xy.col.df } data.or.null <- getCommonChunk(g.data, chunk.cols, g$aes) g.data.varied <- if(is.null(data.or.null)){ split.x(na.omit(g.data), chunk.cols) }else{ g$columns$common <- as.list(names(data.or.null$common)) tsv.name <- sprintf("%s_chunk_common.tsv", g$classed) tsv.path <- file.path(meta$out.dir, tsv.name) write.table(data.or.null$common, tsv.path, quote = FALSE, row.names = FALSE, sep = "\t") data.or.null$varied } list(g=g, g.data.varied=g.data.varied, timeValues=AnimationInfo$timeValues) } ) NULL .pt <- 72.27 / 25.4 .stroke <- 96 / 25.4 check_aesthetics <- function(x, n) { ns <- vapply(x, length, numeric(1)) good <- ns == 1L | ns == n if (all(good)) { return() } stop( "Aesthetics must be either length 1 or the same as the data (", n, "): ", paste(names(!good), collapse = ", "), call. = FALSE ) }
marginal.effects <- function (object, ...) UseMethod("marginal.effects")
getParametrosOfModel <- function(ajuste, base=NULL, formula = NULL){ if (is.null(ajuste)){ if(is.null(base) || is.null(formula)) stop("se ajuste eh null base e formula devem ser informados e vice versa") return(getColumnsOfBase(base=base, strColumns = formula)) } return(getColumnsOfAjust(ajuste = ajuste)) }
grid.vwline <- function(...) { grid.draw(vwlineGrob(...)) } vwlineGrob <- function(x, y, w, default.units="npc", open=TRUE, linejoin="round", lineend="butt", mitrelimit=4, stepWidth=FALSE, render=if (open) vwPolygon else vwPath(), gp=gpar(fill="black"), name=NULL, debug=FALSE) { if (!is.unit(x)) { x <- unit(x, default.units) } if (!is.unit(y)) { y <- unit(y, default.units) } if (!inherits(w, "widthSpec")) { w <- widthSpec(w, default.units) } checkvwline(x, y, w) gTree(x=x, y=y, w=w, open=open, render=render, linejoin=linejoin, lineend=lineend, mitrelimit=mitrelimit, stepWidth=stepWidth, gp=gp, name=name, cl="vwlineGrob", debug=debug) } checkvwline <- function(x, y, w) { if (max(length(x), length(y), length(w)) < 2) stop("A vwline must have at least two points") nx <- length(x) ny <- length(y) nw <- length(w) if (nx != ny || nx != nw) { stop("x, y, and w must all have same length") } } buildEdge <- function(join, perpStart, perpEnd, inside, mitrelen, mitrelimit, intpt1, intpt2, arc, linejoin, leftedge) { N <- length(perpStart) x <- vector("list", N+1) x[[1]] <- perpStart[1] if (N > 1) { for (i in 1:(N-1)) { if (inside[i]) { x[[i+1]] <- c(perpEnd[i], join[i+1], perpStart[i+1]) } else { switch(linejoin, round= { if (leftedge) { x[[i+1]] <- c(perpEnd[i], arc[[i]], perpStart[i+1]) } else { x[[i+1]] <- c(perpEnd[i], rev(arc[[i]]), perpStart[i+1]) } }, mitre= { if (mitrelen[i] < mitrelimit) { x[[i+1]] <- c(intpt1[i], intpt2[i]) } else { x[[i+1]] <- c(perpEnd[i], perpStart[i+1]) } }, bevel= { x[[i+1]] <- c(perpEnd[i], perpStart[i+1]) }, stop("Invalid linejoin value") ) } } } x[[N+1]] <- perpEnd[N] unlist(x) } vwlinePoints <- function(grob) { x <- convertX(grob$x, "in", valueOnly=TRUE) y <- convertY(grob$y, "in", valueOnly=TRUE) w <- grob$w w$left <- pmin(convertWidth(w$left, "in", valueOnly=TRUE), convertHeight(w$left, "in", valueOnly=TRUE)) w$right <- pmin(convertWidth(w$right, "in", valueOnly=TRUE), convertHeight(w$right, "in", valueOnly=TRUE)) sinfo <- segInfo(x, y, w, grob$open, grob$stepWidth, grob$debug) cinfo <- cornerInfo(sinfo, grob$open, grob$stepWidth, grob$debug) carcinfo <- cornerArcInfo(sinfo, cinfo, grob$open, grob$debug) if (!grob$open) { x <- c(x, x[1]) y <- c(y, y[1]) } leftx <- buildEdge(x, sinfo$perpStartLeftX, sinfo$perpEndLeftX, cinfo$leftInside, cinfo$leftMitreLength, grob$mitrelimit, cinfo$leftIntx1, cinfo$leftIntx2, carcinfo$leftarcx, grob$linejoin, TRUE) lefty <- buildEdge(y, sinfo$perpStartLeftY, sinfo$perpEndLeftY, cinfo$leftInside, cinfo$leftMitreLength, grob$mitrelimit, cinfo$leftInty1, cinfo$leftInty2, carcinfo$leftarcy, grob$linejoin, TRUE) rightx <- buildEdge(rev(x), rev(sinfo$perpEndRightX), rev(sinfo$perpStartRightX), rev(cinfo$rightInside), rev(cinfo$rightMitreLength), grob$mitrelimit, rev(cinfo$rightIntx2), rev(cinfo$rightIntx1), rev(carcinfo$rightarcx), grob$linejoin, FALSE) righty <- buildEdge(rev(y), rev(sinfo$perpEndRightY), rev(sinfo$perpStartRightY), rev(cinfo$rightInside), rev(cinfo$rightMitreLength), grob$mitrelimit, rev(cinfo$rightInty2), rev(cinfo$rightInty1), rev(carcinfo$rightarcy), grob$linejoin, FALSE) list(left=list(x=leftx, y=lefty), right=list(x=rightx, y=righty), sinfo=sinfo) } buildEnds <- function(w, einfo, earcinfo, stepWidth, lineend, mitrelimit) { switch(lineend, butt= { startx <- starty <- endx <- endy <- numeric() }, round= { startx <- earcinfo[[1]]$arcx[[1]] starty <- earcinfo[[1]]$arcy[[1]] endx <- earcinfo[[2]]$arcx[[1]] endy <- earcinfo[[2]]$arcy[[1]] }, mitre= { width <- w$left[1] + w$right[1] if (width > 0 && is.finite(einfo$startmitrelength) && einfo$startmitrelength/width <= mitrelimit && abs(earcinfo[[1]]$cornerangle) < pi) { startx <- einfo$startmitre$x starty <- einfo$startmitre$y } else { startx <- c(einfo$startcorner2$x, einfo$startcorner1$x) starty <- c(einfo$startcorner2$y, einfo$startcorner1$y) } N <- length(w$left) if (stepWidth) { width <- w$left[N-1] + w$right[N-1] } else { width <- w$left[N] + w$right[N] } if (width > 0 && is.finite(einfo$endmitrelength) && einfo$endmitrelength/width <= mitrelimit && abs(earcinfo[[2]]$cornerangle) < pi) { endx <- einfo$endmitre$x endy <- einfo$endmitre$y } else { endx <- c(einfo$endcorner1$x, einfo$endcorner2$x) endy <- c(einfo$endcorner1$y, einfo$endcorner2$y) } }, square= { startx <- c(einfo$startcorner2$x, einfo$startcorner1$x) starty <- c(einfo$startcorner2$y, einfo$startcorner1$y) endx <- c(einfo$endcorner1$x, einfo$endcorner2$x) endy <- c(einfo$endcorner1$y, einfo$endcorner2$y) }, stop("Invalid lineend value") ) list(startx=startx, starty=starty, endx=endx, endy=endy) } vwlineOutline <- function(grob, simplify=TRUE) { x <- convertX(grob$x, "in", valueOnly=TRUE) y <- convertY(grob$y, "in", valueOnly=TRUE) w <- grob$w w$left <- pmin(convertWidth(w$left, "in", valueOnly=TRUE), convertHeight(w$left, "in", valueOnly=TRUE)) w$right <- pmin(convertWidth(w$right, "in", valueOnly=TRUE), convertHeight(w$right, "in", valueOnly=TRUE)) pts <- vwlinePoints(grob) if (grob$open) { sinfo <- segInfo(x, y, w, grob$open, grob$stepWidth, grob$debug) einfo <- endInfo(x, y, w, sinfo, grob$stepWidth, grob$debug) earcinfo <- endArcInfo(sinfo, einfo, grob$debug) ends <- buildEnds(w, einfo, earcinfo, grob$stepWidth, grob$lineend, grob$mitrelimit) outline <- list(x=c(ends$startx, pts$left$x, ends$endx, pts$right$x), y=c(ends$starty, pts$left$y, ends$endy, pts$right$y)) } else { outline <- list(x=pts$left, y=pts$right) } xna <- is.na(outline$x) yna <- is.na(outline$y) if (any(xna | yna)) { outline$x <- outline$x[!(xna | yna)] outline$y <- outline$y[!(xna | yna)] warning("Removed NA values from outline") } if (simplify) polysimplify(outline, filltype="nonzero") else outline } makeContent.vwlineGrob <- function(x, ...) { outline <- vwlineOutline(x) addGrob(x, x$render(unlist(lapply(outline, "[[", "x")), unlist(lapply(outline, "[[", "y")), sapply(outline, function(o) length(o$x)), x$gp, "outline")) } edgePoints.vwlineGrob <- function(x, d, x0, y0, which=1, direction="forward", debug=FALSE, ...) { which <- which[1] outline <- vwlineOutline(x) if (which > length(outline)) { stop("Invalid which value") } edge <- outline[[which]] if (!is.unit(x0)) x0 <- unit(x0, "npc") if (!is.unit(y0)) y0 <- unit(y0, "npc") pts <- reorderEdge(edge, x0, y0) vwEdgePoints(pts, d, direction == "forward", x$open, debug) } outline.vwlineGrob <- function(x, simplify=TRUE, ...) { vwlineOutline(x, simplify=simplify) }
generate_heatmap_chart = function(shots, base_court, court_theme = court_themes$dark) { base_court + stat_density_2d( data = shots, aes(x = loc_x, y = loc_y, fill = stat(density / max(density))), geom = "raster", contour = FALSE, interpolate = TRUE, n = 200 ) + geom_path( data = court_points, aes(x = x, y = y, group = desc), color = court_theme$lines ) + scale_fill_viridis_c( "Shot Frequency ", limits = c(0, 1), breaks = c(0, 1), labels = c("lower", "higher"), option = "inferno", guide = guide_colorbar(barwidth = 15) ) + theme(legend.text = element_text(size = rel(0.6))) }
context("test-savitzkyGolay") test_that("savitzkyGolay works", { nirdata <- data("NIRsoil") X_savitzkyGolay <- savitzkyGolay(NIRsoil$spc, m = 1, p = 1, w = 3) expect_is(X_savitzkyGolay, "matrix") expect_true(round(max(abs(X_savitzkyGolay[1, ])), 5) == 0.00528) })
NULL NULL set_all_borders <- function(ht, row, col, value = 0.4) { recall_ltrb(ht, "set_%s_border") } map_all_borders <- function (ht, row, col, fn) { recall_ltrb(ht, "map_%s_border") } set_all_border_colors <- function(ht, row, col, value) { recall_ltrb(ht, "set_%s_border_color") } map_all_border_colors <- function (ht, row, col, fn) { recall_ltrb(ht, "map_%s_border_color") } set_all_border_styles <- function(ht, row, col, value) { recall_ltrb(ht, "set_%s_border_style") } map_all_border_styles <- function (ht, row, col, fn) { recall_ltrb(ht, "map_%s_border_style") } set_all_padding <- function(ht, row, col, value) { recall_ltrb(ht, "set_%s_padding") } map_all_padding <- function (ht, row, col, fn) { recall_ltrb(ht, "map_%s_padding") } set_tb_padding <- function (ht, row, col, value) { recall_ltrb(ht, "set_%s_padding", sides = c("top", "bottom")) } map_tb_padding <- function (ht, row, col, fn) { recall_ltrb(ht, "map_%s_padding", sides = c("top", "bottom")) } set_lr_padding <- function (ht, row, col, value) { recall_ltrb(ht, "set_%s_padding", sides = c("left", "right")) } map_lr_padding <- function (ht, row, col, fn) { recall_ltrb(ht, "map_%s_padding", sides = c("left", "right")) } set_tb_borders <- function (ht, row, col, value) { recall_ltrb(ht, "set_%s_border", sides = c("top", "bottom")) } map_tb_borders <- function (ht, row, col, fn) { recall_ltrb(ht, "map_%s_border", sides = c("top", "bottom")) } set_lr_borders <- function (ht, row, col, value) { recall_ltrb(ht, "set_%s_border", sides = c("left", "right")) } map_lr_borders <- function (ht, row, col, fn) { recall_ltrb(ht, "map_%s_border", sides = c("left", "right")) } set_tb_border_colors <- function (ht, row, col, value) { recall_ltrb(ht, "set_%s_border_color", sides = c("top", "bottom")) } map_tb_border_colors <- function (ht, row, col, fn) { recall_ltrb(ht, "map_%s_border_color", sides = c("top", "bottom")) } set_lr_border_colors <- function (ht, row, col, value) { recall_ltrb(ht, "set_%s_border_color", sides = c("left", "right")) } map_lr_border_colors <- function (ht, row, col, fn) { recall_ltrb(ht, "map_%s_border_color", sides = c("left", "right")) } set_tb_border_styles <- function (ht, row, col, value) { recall_ltrb(ht, "set_%s_border_style", sides = c("top", "bottom")) } map_tb_border_styles <- function (ht, row, col, fn) { recall_ltrb(ht, "map_%s_border_style", sides = c("top", "bottom")) } set_lr_border_styles <- function (ht, row, col, value) { recall_ltrb(ht, "set_%s_border_style", sides = c("left", "right")) } map_lr_border_styles <- function (ht, row, col, fn) { recall_ltrb(ht, "map_%s_border_style", sides = c("left", "right")) } recall_ltrb <- function(ht, template, sides = c("left", "top", "right", "bottom")) { call <- sys.call(sys.parent(1L)) call_names <- parse(text = paste0("huxtable::", sprintf(template, sides))) for (cn in call_names) { call[[1]] <- cn call[[2]] <- quote(ht) ht <- eval(call, list(ht = ht), parent.frame(2L)) } ht }
partial.q <- function(x, PI, MU, S, t, logit.PI = TRUE){ K <- length(PI) N <- dim(x)[1] p <- dim(x)[2] mp <- p * (p + 1) / 2 M <- K - 1 + K * p + K * p * (p + 1) / 2 G <- Gmat(p) Id <- diag(p) invS <- apply(S, 3, solve) dim(invS) <- c(p, p, K) SS <- lapply(1:N, function(i){ Sbuf.1 <- NULL if(K != 1){ if(logit.PI){ Sbuf.1 <- t[i, -K] - PI[-K] } else{ tmp <- t[i, ] / PI Sbuf.1 <- tmp[1:(K-1)] - tmp[K] } } Sbuf.2 <- list() Sbuf.3 <- list() for(j in 1:K){ tmp <- x[i,] - MU[j,] dim(tmp) <- c(p, 1) tmp.1 <- t[i,j] * invS[,,j] Sbuf.2[[j]] <- tmp.1 %*% tmp Smat <- tmp.1 %*% (tmp %*% t(tmp) %*% invS[,,j] - Id) / 2 Sbuf.3[[j]] <- as.vector(Smat) %*% G } c(Sbuf.1, do.call("c", Sbuf.2), do.call("c", Sbuf.3)) }) do.call("cbind", SS) }
transform <- function(xy, m) { newX = m[1] * xy[,1] + m[3] * xy[,2] + m[5] newY = m[2] * xy[,1] + m[4] * xy[,2] + m[6] cbind(newX, newY) } oneline <- function(x, id) { x <- trimws(gsub('^m', "", x)) ss <- trimws(unlist(strsplit(x, "m "))) out <- list() for (j in 1:length(ss)) { v <- unlist(utils::read.table(text=ss[j], sep=" ")) vv <- as.numeric(unlist(strsplit(v, ","))) vv <- matrix(vv, ncol=2, byrow=TRUE) if (j > 1) { vv[1,] <- vv[1,] + a[1,] } a <- apply(vv, 2, cumsum) out[[j]] <- a } out <- lapply(1:length(out), function(p) cbind(id=id, part=p, out[[p]], hole=0)) out <- do.call(rbind, out) out[,4] <- -out[,4] out } oneline2 <- function(x, id) { x <- trimws(gsub('^M', "", x)) ss <- trimws(unlist(strsplit(x, "ZM"))) out <- list() for (j in 1:length(ss)) { v <- unlist(strsplit(ss[j], "L")) v <- unlist(strsplit(v, "C")) v <- unlist(strsplit(v, " ")) v <- gsub("Z", "", v) vv <- as.numeric(unlist(strsplit(v, ","))) vv <- matrix(vv, ncol=2, byrow=TRUE) out[[j]] <- vv } out <- lapply(1:length(out), function(p) cbind(id=id, part=p, out[[p]], hole=0)) do.call(rbind, out) } readSVG <- function(f) { doc <- XML::htmlParse(f) p <- XML::xpathSApply(doc, "//path", XML::xmlGetAttr, "d") s <- list() for (i in 1:length(p)) { s[[i]] <- oneline2(p[i], i) } ss <- do.call(rbind, s) v <- vect(ss, type="polygons") a <- XML::xpathSApply(doc, "//path", XML::xmlAttrs) a <- unique(unlist(sapply(a, names))) a <- a[-grep(":", a)] a <- a[a != "d"] if (length(a) > 0) { att <- list() for (i in 1:length(a)) { z <- XML::xpathSApply(doc, "//path", XML::xmlGetAttr, a[i]) att[[i]] <- sapply(z, function(i) if (is.null(i)) NA else i, USE.NAMES = FALSE) } names(att) <- a values(v) <- data.frame(att) } v }
require(testthat) if(FALSE){ deffile = system.file("extdata/fastq_haplotyper.def", package = "flowr") flowdef = as.flowdef(deffile) plot_flow(head(flowdef, 4), pdf = TRUE) plot_flow(head(flowdef, 7), pdf = TRUE) plot_flow(flowdef, pdf = TRUE) }
gamma.shape <- function(object, ...) UseMethod("gamma.shape") gamma.shape.glm <- function(object, it.lim = 10, eps.max = .Machine$double.eps^0.25, verbose = FALSE, ...) { if(is.null(object$y)) object <- update(object, y = TRUE) y <- object$y A <- object$prior.weights if(is.null(A)) A <- rep(1, length(y)) u <- object$fitted.values Dbar <- object$deviance/object$df.residual alpha <- (6 + 2*Dbar)/(Dbar*(6 + Dbar)) if(verbose) { message(gettextf("Initial estimate: %s", format(alpha)), domain = NA) utils::flush.console() } fixed <- -y/u - log(u) + log(A) + 1 + log(y + (y == 0)) eps <- 1 itr <- 0 while(abs(eps) > eps.max && (itr <- itr + 1) <= it.lim) { sc <- sum(A * (fixed + log(alpha) - digamma(A * alpha))) inf <- sum(A * (A * trigamma(A * alpha) - 1/alpha)) alpha <- alpha + (eps <- sc/inf) if(verbose) { message(gettextf("Iter. %d Alpha: %s", itr, format(alpha)), domain = NA) utils::flush.console() } } if(itr > it.lim) warning("iteration limit reached") res <- list(alpha = alpha, SE = sqrt(1/inf)) class(res) <- "gamma.shape" res } gamma.dispersion <- function(object, ...) 1/gamma.shape(object, ...)[[1L]] print.gamma.shape <- function(x, ...) { y <- x x <- array(unlist(x), dim = 2L:1L, dimnames = list(c("Alpha:", "SE:"), "")) NextMethod("print") invisible(y) }
dmnom <- function(x, size, prob, log = FALSE) { if (is.vector(prob)) prob <- matrix(prob, nrow = 1) else if (!is.matrix(prob)) prob <- as.matrix(prob) if (is.vector(x)) x <- matrix(x, nrow = 1) else if (!is.matrix(x)) x <- as.matrix(x) cpp_dmnom(x, size, prob, log[1L]) } rmnom <- function(n, size, prob) { if (length(n) > 1) n <- length(n) if (is.vector(prob)) prob <- matrix(prob, nrow = 1) else if (!is.matrix(prob)) prob <- as.matrix(prob) cpp_rmnom(n, size, prob) }
export.snowprofileCsv <- function(profile, filename = stop("filename must be provided"), sep = ",", export.all = "Layers", variables = NA) { stopifnot(is.snowprofile(profile)) if (!all(is.na(variables))) if (!is.list(variables)) stop("variables must be either NA or a tag-value list of the format: height = 'height_top'; see ?export.snowprofileCsv") if (!all(names(variables) %in% c(names(profile), names(profile$layers)))) { warning("At least one of your specified variable names does not exist in the snowprofile object, ignoring...") variables <- variables[names(variables) %in% c(names(profile), names(profile$layers))] } if (isTRUE(export.all)) { vexp <- c(names(profile$layers), names(profile)) } else if (isFALSE(export.all)) { vexp <- names(variables) } else if (export.all == "Layers") { vexp <- unique(c(names(profile$layers), names(variables))) } else { stop("export.all must either be TRUE, FALSE or 'Layers'") } layers <- profile$layers[vexp[which(vexp %in% names(profile$layers))]] meta <- profile[vexp[which(vexp %in% names(profile))]] if ((length(layers) > 0) && (length(meta) > 0)) { DF <- data.frame(layers, meta) } else if ((length(layers) > 0) && (length(meta) == 0)) { DF <- data.frame(layers) } else if ((length(layers) == 0) && (length(meta) > 0)) { DF <- data.frame(meta) } if (is.list(variables)) { cn <- colnames(DF) cn[which(cn %in% names(variables))] <- as.character(variables[cn[which(cn %in% names(variables))]]) colnames(DF) <- cn DF <- DF[, as.character(c(variables, cn[!cn %in% variables]))] } write.csv(DF, file = filename, row.names = FALSE, quote = FALSE) }
longst <- function(longdat, long.formula, model, longdat2) { if (model == "int") { rf <- as.formula( paste("~1", colnames(longdat)[1], sep = "|")) } else if (model == "intslope") { rf <- as.formula( paste(paste0("~", colnames(longdat)[3]), colnames(longdat)[1], sep = "|")) } else { tsq <- paste0(paste0("I(", paste(colnames(longdat)[3], "^2", sep = "")), ")") rf <- as.formula( paste(paste0("~", paste(colnames(longdat)[3], tsq, sep = "+")), colnames(longdat)[1], sep = "|")) } long.start <- nlme::lme(long.formula, random = rf, method = "ML", data = data.frame(longdat2), na.action = na.omit, control = lmeControl(maxIter = 1000, msMaxIter = 1000, opt = "optim", tolerance = 1e-05, msTol = 1e-06)) q <- dim(nlme::VarCorr(long.start))[1] - 1 sigma.u <- as.matrix(nlme::getVarCov(long.start)) rownames(sigma.u) <- paste("U_", 0:(q - 1), sep = "") colnames(sigma.u) <- paste("U_", 0:(q - 1), sep = "") if (model == "intslope") { corr <- as.numeric(nlme::VarCorr(long.start)[2, 3]) } else if (model == "int") { corr <- NA } else if (model == "quad") { corr <- as.numeric(nlme::VarCorr(long.start)[2:3, 3]) } sigma.z <- long.start$sigma^2 ll <- long.start$logLik b1 <- nlme::fixef(long.start) list("b1" = data.frame(b1), "sigma.z" = sigma.z, "sigma.u" = sigma.u, "corr" = corr, "log.like" = ll) }
setMethod( "readability", signature(txt.file="kRp.corpus"), function( txt.file, summary=TRUE, mc.cores=getOption("mc.cores", 1L), quiet=TRUE, ... ){ tagged_list <- split_by_doc_id(txt.file) corpusReadability(txt.file) <- mclapply(names(tagged_list), function(thisText){ dot_args <- list(...) if(any(!is.null(dot_args[["keep.input"]]), !is.null(dot_args[["as.feature"]]))){ stop(simpleError("The arguments \"keep.input\" and \"as.feature\" are FALSE by default and can't be changed!")) } else {} if(any(names(corpusHyphen(txt.file)) == thisText)){ default <- list(txt.file=tagged_list[[thisText]], quiet=quiet, keep.input=FALSE, ...) args <- modifyList(default, list(hyphen=corpusHyphen(txt.file)[[thisText]])) rdb <- do.call(readability, args) } else { rdb <- readability( tagged_list[[thisText]], quiet=quiet, keep.input=FALSE, as.feature=FALSE, ... ) } return(rdb) }, mc.cores=mc.cores) corpusMeta(txt.file, "readability") <- list(index=c()) corpusMeta(txt.file, "readability")[["index"]] <- sort( unique( unlist(mclapply(corpusReadability(txt.file), function(thisText){ names(summary(thisText, flat=TRUE)) }, mc.cores=mc.cores) ) ) ) names(corpusReadability(txt.file)) <- names(describe(txt.file)) if(isTRUE(summary)){ txt.file <- summary(txt.file) } else {} return(txt.file) } )
glaguerre.quadrature.rules <- function( n, alpha, normalized=FALSE ) { recurrences <- glaguerre.recurrences( n, alpha, normalized ) inner.products <- glaguerre.inner.products( n, alpha ) return( quadrature.rules( recurrences, inner.products ) ) }
`RODM_create_dt_model` <- function( database, data_table_name, case_id_column_name = NULL, target_column_name, model_name = "DT_MODEL", auto_data_prep = TRUE, cost_matrix = NULL, gini_impurity_metric = TRUE, max_depth = NULL, minrec_split = NULL, minpct_split = NULL, minrec_node = NULL, minpct_node = NULL, retrieve_outputs_to_R = TRUE, leave_model_in_dbms = TRUE, sql.log.file = NULL) { if (!is.null(sql.log.file)) write(paste("--- SQL calls by ODM function: RODM_create_dt_model ", date(), "---"), file = sql.log.file, append = TRUE, ncolumns = 1000) DT.settings.table <- data.frame(matrix(c( "ALGO_NAME", "ALGO_DECISION_TREE"), nrow = 1, ncol=2, byrow=TRUE)) names(DT.settings.table) <- c("SETTING_NAME", "SETTING_VALUE") if (gini_impurity_metric == FALSE) { DT.settings.table <- rbind(DT.settings.table, data.frame(matrix(c("TREE_IMPURITY_METRIC", "TREE_IMPURITY_ENTROPY"), nrow=1, ncol=2, byrow=TRUE, dimnames = list(NULL,c("SETTING_NAME", "SETTING_VALUE"))))) } if (!is.null(max_depth)) { DT.settings.table <- rbind(DT.settings.table, data.frame(matrix(c("TREE_TERM_MAX_DEPTH", max_depth), nrow=1, ncol=2, byrow=TRUE, dimnames = list(NULL,c("SETTING_NAME", "SETTING_VALUE"))))) } if (!is.null(minrec_split)) { DT.settings.table <- rbind(DT.settings.table, data.frame(matrix(c("TREE_TERM_MINREC_SPLIT", minrec_split), nrow=1, ncol=2, byrow=TRUE, dimnames = list(NULL,c("SETTING_NAME", "SETTING_VALUE"))))) } if (!is.null(minpct_split)) { DT.settings.table <- rbind(DT.settings.table, data.frame(matrix(c("TREE_TERM_MINPCT_SPLIT", minpct_split), nrow=1, ncol=2, byrow=TRUE, dimnames = list(NULL,c("SETTING_NAME", "SETTING_VALUE"))))) } if (!is.null(minrec_node)) { DT.settings.table <- rbind(DT.settings.table, data.frame(matrix(c("TREE_TERM_MINREC_NODE", minrec_node), nrow=1, ncol=2, byrow=TRUE, dimnames = list(NULL,c("SETTING_NAME", "SETTING_VALUE"))))) } if (!is.null(minpct_node)) { DT.settings.table <- rbind(DT.settings.table, data.frame(matrix(c("TREE_TERM_MINPCT_NODE", minpct_node), nrow=1, ncol=2, byrow=TRUE, dimnames = list(NULL,c("SETTING_NAME", "SETTING_VALUE"))))) } RODM_store_settings(database, DT.settings.table, auto_data_prep, sql.log.file, cost_matrix) dt.list <- RODM_create_model( database, model_name, "dbms_data_mining.classification", data_table_name, case_id_column_name, target_column_name, retrieve_outputs_to_R, sql.log.file) if (retrieve_outputs_to_R == TRUE) { query.string <- paste( "SELECT * FROM ", " XMLTable('for $s in /PMML/TreeModel//ScoreDistribution ", " return ", " <scores id=\"{$s/../@id}\" ", " tvalue=\"{$s/@value}\" ", " tcount=\"{$s/@recordCount}\" ", " />' ", " passing dbms_data_mining.get_model_details_xml('", model_name, "') ", " COLUMNS ", " node_id NUMBER PATH '/scores/@id', ", " target_value VARCHAR2(4000) PATH '/scores/@tvalue', ", " target_count NUMBER PATH '/scores/@tcount') ", sep=""); distributions <- sqlQuery(database, query = query.string) if (!is.null(sql.log.file)) write(query.string, file = sql.log.file, append = TRUE, ncolumns = 1000) dt.list <- c(dt.list, list("dt.distributions" = distributions)) query.string <- paste( "WITH X as ", "(SELECT * FROM ", " XMLTable('for $n in /PMML/TreeModel//Node ", " let $rf := ", " if (count($n/CompoundPredicate) > 0) then ", " $n/CompoundPredicate/*[1]/@field ", " else ", " if (count($n/SimplePredicate) > 0) then ", " $n/SimplePredicate/@field ", " else ", " $n/SimpleSetPredicate/@field ", " let $ro := ", " if (count($n/CompoundPredicate) > 0) then ", " if ($n/CompoundPredicate/*[1] instance of ", " element(SimplePredicate)) then ", " $n/CompoundPredicate/*[1]/@operator ", " else if ($n/CompoundPredicate/*[1] instance of ", " element(SimpleSetPredicate)) then ", " (\"in\") ", " else () ", " else ", " if (count($n/SimplePredicate) > 0) then ", " $n/SimplePredicate/@operator ", " else if (count($n/SimpleSetPredicate) > 0) then ", " (\"in\") ", " else () ", " let $rv := ", " if (count($n/CompoundPredicate) > 0) then ", " if ($n/CompoundPredicate/*[1] instance of ", " element(SimplePredicate)) then ", " $n/CompoundPredicate/*[1]/@value ", " else ", " $n/CompoundPredicate/*[1]/Array/text() ", " else ", " if (count($n/SimplePredicate) > 0) then ", " $n/SimplePredicate/@value ", " else ", " $n/SimpleSetPredicate/Array/text() ", " let $sf := ", " if (count($n/CompoundPredicate) > 0) then ", " $n/CompoundPredicate/*[2]/@field ", " else () ", " let $so := ", " if (count($n/CompoundPredicate) > 0) then ", " if ($n/CompoundPredicate/*[2] instance of ", " element(SimplePredicate)) then ", " $n/CompoundPredicate/*[2]/@operator ", " else if ($n/CompoundPredicate/*[2] instance of ", " element(SimpleSetPredicate)) then ", " (\"in\") ", " else () ", " else () ", " let $sv := ", " if (count($n/CompoundPredicate) > 0) then ", " if ($n/CompoundPredicate/*[2] instance of ", " element(SimplePredicate)) then ", " $n/CompoundPredicate/*[2]/@value ", " else ", " $n/CompoundPredicate/*[2]/Array/text() ", " else () ", " return ", " <pred id=\"{$n/../@id}\" ", " score=\"{$n/@score}\" ", " rec=\"{$n/@recordCount}\" ", " cid=\"{$n/@id}\" ", " rf=\"{$rf}\" ", " ro=\"{$ro}\" ", " rv=\"{$rv}\" ", " sf=\"{$sf}\" ", " so=\"{$so}\" ", " sv=\"{$sv}\" ", " />' ", "passing dbms_data_mining.get_model_details_xml('", model_name, "') ", " COLUMNS ", " parent_node_id NUMBER PATH '/pred/@id', ", " child_node_id NUMBER PATH '/pred/@cid', ", " rec NUMBER PATH '/pred/@rec', ", " score VARCHAR2(4000) PATH '/pred/@score', ", " rule_field VARCHAR2(4000) PATH '/pred/@rf', ", " rule_op VARCHAR2(20) PATH '/pred/@ro', ", " rule_value VARCHAR2(4000) PATH '/pred/@rv', ", " surr_field VARCHAR2(4000) PATH '/pred/@sf', ", " surr_op VARCHAR2(20) PATH '/pred/@so', ", " surr_value VARCHAR2(4000) PATH '/pred/@sv')) ", "select pid parent_node, nid node, rec record_count, ", " score prediction, rule_pred local_rule, surr_pred local_surrogate, ", " rtrim(replace(full_rule,'$O$D$M$'),' AND') full_simple_rule from ( ", " select row_number() over (partition by nid order by rn desc) rn, ", " pid, nid, rec, score, rule_pred, surr_pred, full_rule from ( ", " select rn, pid, nid, rec, score, rule_pred, surr_pred, ", " sys_connect_by_path(pred, '$O$D$M$') full_rule from ( ", " select row_number() over (partition by nid order by rid) rn, ", " pid, nid, rec, score, rule_pred, surr_pred, ", " nvl2(pred,pred || ' AND ',null) pred from( ", " select rid, pid, nid, rec, score, rule_pred, surr_pred, ", " decode(rn, 1, pred, null) pred from ( ", " select rid, nid, rec, score, pid, rule_pred, surr_pred, ", " nvl2(root_op, '(' || root_field || ' ' || root_op || ' ' || root_value || ')', null) pred, ", " row_number() over (partition by nid, root_field, root_op order by rid desc) rn from ( ", " SELECT ", " connect_by_root(parent_node_id) rid, ", " child_node_id nid, ", " rec, score, ", " connect_by_root(rule_field) root_field, ", " connect_by_root(rule_op) root_op, ", " connect_by_root(rule_value) root_value, ", " nvl2(rule_op, '(' || rule_field || ' ' || rule_op || ' ' || rule_value || ')', null) rule_pred, ", " nvl2(surr_op, '(' || surr_field || ' ' || surr_op || ' ' || surr_value || ')', null) surr_pred, ", " parent_node_id pid ", " FROM ( ", " SELECT parent_node_id, child_node_id, rec, score, rule_field, surr_field, rule_op, surr_op, ", " replace(replace(rule_value,'&quot; &quot;', ''', '''),'&quot;', '''') rule_value, ", " replace(replace(surr_value,'&quot; &quot;', ''', '''),'&quot;', '''') surr_value ", " FROM ( ", " SELECT parent_node_id, child_node_id, rec, score, rule_field, surr_field, ", " decode(rule_op,'lessOrEqual','<=','greaterThan','>',rule_op) rule_op, ", " decode(rule_op,'in','('||rule_value||')',rule_value) rule_value, ", " decode(surr_op,'lessOrEqual','<=','greaterThan','>',surr_op) surr_op, ", " decode(surr_op,'in','('||surr_value||')',surr_value) surr_value ", " FROM X) ", " ) ", " CONNECT BY PRIOR child_node_id = parent_node_id ", " ) ", " ) ", " ) ", " ) ", " CONNECT BY PRIOR rn = rn - 1 ", " AND PRIOR nid = nid ", " START WITH rn = 1 ", " ) ", ") ", "where rn = 1", sep=""); nodes <- sqlQuery(database, query = query.string) if (!is.null(sql.log.file)) write(query.string, file = sql.log.file, append = TRUE, ncolumns = 1000) dt.list <- c(dt.list, list("dt.nodes" = nodes)) } if (leave_model_in_dbms == FALSE) RODM_drop_model(database, model_name, sql.log.file) return(dt.list) }