code
stringlengths
1
13.8M
drake_context("lock") test_with_dir("lock_environment()", { skip_on_cran() skip_if_not_installed("tibble") scenario <- get_testing_scenario() e <- eval(parse(text = scenario$envir)) jobs <- scenario$jobs parallelism <- scenario$parallelism caching <- scenario$caching plan <- drake_plan( x = try( assign("a", 1L, envir = parent.env(drake_envir("targets"))), silent = TRUE ) ) make( plan, envir = e, jobs = jobs, parallelism = parallelism, caching = caching, lock_envir = TRUE, verbose = 1L, session_info = FALSE ) expect_true(inherits(readd(x), "try-error")) e$a <- 123 e$plan$four <- "five" plan <- drake_plan( x = assign("a", 1, envir = drake_envir("targets")) ) make( plan, envir = e, jobs = jobs, parallelism = parallelism, caching = caching, lock_envir = FALSE, verbose = 0L, session_info = FALSE ) expect_true("x" %in% cached()) expect_equal(readd(x), 1L) }) test_with_dir("Try to modify a locked environment", { skip_on_cran() e <- new.env() lock_environment(e) plan <- drake_plan(x = { e$a <- 1 2 }) expect_error( make(plan, session_info = FALSE, cache = storr::storr_environment()), regexp = "Self-invalidation" ) }) test_with_dir("unlock_environment()", { skip_on_cran() expect_error( unlock_environment(NULL), regexp = "use of NULL environment is defunct" ) expect_error( unlock_environment("x"), regexp = "not an environment" ) e <- new.env(parent = emptyenv()) e$y <- 1 expect_false(environmentIsLocked(e)) assign(x = ".x", value = "x", envir = e) expect_equal(get(x = ".x", envir = e), "x") lock_environment(e) msg1 <- "cannot change value of locked binding" msg2 <- "cannot add bindings to a locked environment" expect_true(environmentIsLocked(e)) assign(x = ".x", value = "y", envir = e) expect_equal(get(x = ".x", envir = e), "y") expect_error(assign(x = "y", value = "y", envir = e), regexp = msg1) expect_error(assign(x = "a", value = "x", envir = e), regexp = msg2) expect_error(assign(x = "b", value = "y", envir = e), regexp = msg2) unlock_environment(e) assign(x = ".x", value = "1", envir = e) assign(x = "y", value = "2", envir = e) assign(x = "a", value = "x", envir = e) expect_equal(get(x = ".x", envir = e), "1") expect_equal(get(x = "y", envir = e), "2") expect_equal(get(x = "a", envir = e), "x") expect_false(environmentIsLocked(e)) unlock_environment(e) assign(x = "b", value = "y", envir = e) expect_equal(get(x = "b", envir = e), "y") expect_false(environmentIsLocked(e)) })
.packageName <- "mbrdr" mbrdr <- function(formula, data, subset, na.action=na.fail, weights, ...){ mf <- match.call(expand.dots=FALSE) mf$na.action <- na.action mf$... <- NULL mf[[1]] <- as.name("model.frame") mf <- eval(mf, sys.frame(sys.parent())) mt <- attr(mf,"terms") Y <- model.extract(mf,"response") if (dim(Y)[2]<2) stop("The responses must be multivariate !") X <- model.matrix(mt, mf) y.name <- if(is.matrix(Y)) colnames(Y) else as.character(attr(mt, "variables")[2]) int <- match("(Intercept)", dimnames(X)[[2]], nomatch=0) if (int > 0) X <- X[, -int, drop=FALSE] weights <- mf$"(weights)" if(is.null(weights)){ weights <- rep(1,dim(X)[1])} else { if(any(weights<0))stop("Negative weights") pos.weights <- weights > 1.e-30 weights <- weights[pos.weights] weights <- dim(X)[1]*weights/sum(weights) X <- X[pos.weights,] Y <- if(is.matrix(Y)) Y[pos.weights,] else Y[pos.weights]} ans <- mbrdr.compute(Y, X, weights=weights,...) ans$call <- match.call() ans$y.name <- y.name ans } mbrdr.compute <- function(y, x, weights, method="upfrr",...){ if (NROW(y) != nrow(x)) stop("The response and predictors have differing number of observations") classname<- c(method) genclassname<-"mbrdr" sweights <- sqrt(weights) ans <- list(y=y, x=x, weights=weights,method=method,cases=NROW(y)) class(ans) <- c(classname,genclassname) ans <- mbrdr.fit(object=ans, ...) class(ans) <- c(classname,genclassname) ans } mbrdr.x <- function(object) {object$x} mbrdr.wts <- function(object) {object$weights} mbrdr.y.name <- function(object) {object$y.name} mbrdr.fit <- function(object, numdir=4,...) UseMethod("mbrdr.fit") mbrdr.fit.default <-function(object, numdir=4,...){ M <-mbrdr.M(object, ...) evalues <- M$evalues evectors <- as.matrix(M$M) numdir <- min( M$numdir, dim(evectors)[2] ) stats <- M$stats if (is.null(M$fx)) {fx <- NULL} else{ fx <- M$fx} names <- colnames(mbrdr.y(object))[1:dim(evectors)[1]] dimnames(evectors)<- list(names, paste("Dir", 1:NCOL(evectors), sep="")) aa<-c( object, list(evectors=evectors, evalues=evalues, stats=stats, fx=fx, numdir=numdir)) class(aa) <- class(object) return(aa) } mbrdr.M <- function(object, ...){UseMethod("mbrdr.M")} mbrdr.y <- function(object) {UseMethod("mbrdr.y")} mbrdr.y.default <- function(object){object$y} mbrdr.test <- function(object, nd){ UseMethod("mbrdr.test")} mbrdr.test.default <-function(object, nd) {NULL} mbrdr.M.yc <- function(object, num.d=NULL, ...) { y <- mbrdr.y(object) x <- mbrdr.x(object) n <- dim(y)[1] r <- dim(y)[2] if (is.null(num.d) ) num.d <- (r-1) sigmay=cov(y) sigmax=cov(x) Sigmahat = solve(sigmay) %*% cov(y,x) %*% solve(sigmax) eg_S<- eigen(Sigmahat%*%t(Sigmahat)); ev_S <- eg_S$vectors evectors <- as.matrix(ev_S[,1:num.d]) evalues <- eg_S$values[1:num.d] cumsum.evalues <- rev(cumsum(rev(evalues))) ans <- list(M=evectors, stats=n*cumsum.evalues, evalues=evalues, numdir=num.d) return(ans) } mbrdr.M.prr <- function(object, num.d=NULL,...) { y <- mbrdr.y(object) n <- dim(y)[1] r <- dim(y)[2] if (is.null(num.d) ) num.d <- (r-1) Sigmahat = cov(y) eg_S<- eigen(Sigmahat); ev_S <- eg_S$vectors evectors <- as.matrix(ev_S[,1:num.d]) evalues <- eg_S$values[1:num.d] cumsum.evalues <- rev(cumsum(rev(evalues))) ans <- list(M=evectors, stats=n*cumsum.evalues, evalues=evalues, numdir=num.d) return(ans) } mbrdr.M.pfrr <- function(object, num.d=NULL, fx.choice=NULL, nclust=NULL, fx=NULL,...) { lik <- function(h, S, S_res, n) { p <- dim(as.matrix(h))[1]; d <- dim(as.matrix(h))[2] h <- eigen(h %*% t(h))$vectors[, 1:d] h0 <- eigen(h %*% t(h))$vectors[, (d+1):p] lik <- (-n/2)*log( det( t(h0) %*% S %*% h0 ) ) + (-n/2)*log( det( t(h) %*% S_res %*% h ) ) return(lik)} seq.dir <- function(cand_mat, d=1, S, S_res, n){ h <- h1 <- NULL r <- dim(cand_mat)[2] f.lik <- -(n/2)*log(det(S_res)) for (i in 1:d){ l.lik <- NULL for(j in 1:r){ l.lik[j] <- lik(cbind(h1, cand_mat[,j]), S, S_res, n) } stat <- 2*(f.lik - l.lik) sel <- which(stat >= 0 ); l.lik <- l.lik[sel]; stat <- stat[sel] cand_mat <- cand_mat[, sel] h <- cbind(h,cand_mat[,which.max(l.lik)]) h1 <- h cand_mat <- cand_mat[, -(which.max(l.lik))] r <- length(sel)-1 } out <- list(dir=h, loglik=max(l.lik), stat=min(stat) ) return(out)} y <- mbrdr.y(object) x <- mbrdr.x(object) n <- dim(y)[1] r <- dim(y)[2] if (is.null(num.d) ) num.d <- (r-1) num.f <- {if(is.null(fx.choice)) 1 else fx.choice} h <- {if(is.null(nclust)) 5 else nclust} if(num.f>4 & is.null(fx)) stop("fx.choice must be less than or equal to 4. If you want to other candidates for fx, use the fx option") else { if(!is.null(fx)) fx<-fx else fx <- choose.fx(x, fx.choice=num.f, nclust=h)} Sigmas<-SIGMAS(y, fx) Sigmahat <- Sigmas$Sigmahat Sigmahat_fit<-Sigmas$Sigmahat_fit Sigmahat_res<-Sigmas$Sigmahat_res eg_S<- eigen(Sigmahat); ev_S <- eg_S$vectors eg_fit <- eigen(Sigmahat_fit); ev_fit <- eg_fit$vectors eg_res <- eigen(Sigmahat_res); ev_res <- eg_res$vectors cand <- cbind(ev_fit, ev_S, ev_res) logliks <- NULL for (i in 1:num.d ){ logliks[i] <- seq.dir(cand, d=i, S=Sigmahat, S_res=Sigmahat_res, n=n)$loglik } evectors <- seq.dir(cand, d=num.d, S=Sigmahat, S_res=Sigmahat_res, n=n)$dir evectors <- qr.Q( qr(evectors) ) evalues <- c((-(n/2)*log(det(Sigmahat))), logliks) full.loglik <- (-(n/2)*log(det(Sigmahat_res))) stat <- 2*(full.loglik - evalues ) ans <- list(M=evectors, stats=stat, evalues=evalues, fx=fx, numdir=num.d) return(ans) } mbrdr.test.pfrr <-function(object, nd) { stat <- object$stats y <- mbrdr.y(object) fx <- object$fx r <- dim(y)[2]; q<- dim(fx)[2] st<-df<-pv<-0 nt <- nd for (i in 0:nt-1) {st[i+1]<-stat[i+1] df[i+1]<-(r-i)*q pv[i+1]<-1-pchisq(st[i+1],df[i+1]) } z<-data.frame(cbind(st,df, round(pv,4))) rr<-paste(0:(nt-1),"D vs >= ",1:nt,"D",sep="") dimnames(z)<-list(rr,c("Stat","df","p-value")) z } mbrdr.M.upfrr <- function(object, num.d=NULL, fx.choice=NULL, fx=NULL, nclust=NULL, epsilon=1e-7,...) { upfrr = function(Y, d=d, fx=fx, epsilon=1e-7,...){ n <- dim(Y)[1] r <- dim(Y)[2] q <- dim(fx)[2] muhat <- array(colMeans(Y),dim=c(1,r)) Y.centered <- as.matrix(Y-array(rep(1,times=n),dim=c(n,1))%*%muhat ); Sigmas<-SIGMAS(Y, fx); Sigmahat <- Sigmas$Sigmahat; Sigmahat_fit<-Sigmas$Sigmahat_fit;Sigmahat_res<-Sigmas$Sigmahat_res; sqrt_Sigmahat_res<-matpower(Sigmahat_res,0.5); Inv_Sqrt_Sigmahat_res<-solve(sqrt_Sigmahat_res); lf_matrix <- Inv_Sqrt_Sigmahat_res%*% Sigmahat_fit %*% Inv_Sqrt_Sigmahat_res; Vd<-eigen(lf_matrix, symmetric=TRUE)$vectors[, 1:d]; Gammahat<-(sqrt_Sigmahat_res)%*%Vd%*%solve( matpower( (t(Vd)%*%Sigmahat_res%*%Vd), 0.5) ) ; Khat<-diag(0, r); if ( d<min(r,q) ) {diag(Khat)[(d+1):min(r,q)]<- eigen(lf_matrix, symmetric=TRUE)$values[(d+1):min(r,q)] }; if ((r<d) | (r <d)) stop("d needs to be less than min(r, q)"); Vhat<-eigen(lf_matrix, symmetric=TRUE)$vectors; Deltahat<-Sigmahat_res + sqrt_Sigmahat_res %*% Vhat %*% Khat %*% t(Vhat) %*% sqrt_Sigmahat_res; Betahat <- solve(t(Gammahat)%*%solve(Deltahat)%*%Gammahat)%*%t(Gammahat) %*% solve(Deltahat)%*% t(Y.centered) %*% fx%*% solve(t(fx)%*%fx) Rhat <- t(Gammahat)%*% solve(Deltahat)%*%t(Y.centered); temp0<- -(n*r/2)*(1 + log(2*pi) ); temp1<- -(n/2)*sum( log( eigen(Sigmahat_res, symmetric=TRUE)$values) ); temp2<-0; if ( d<min(r,q) ) { temp2<- -(n/2)*sum( log( 1+ eigen(lf_matrix, symmetric=TRUE)$values[(d+1):min(r,q)] ) ); } loglik=temp0 + temp1 + temp2; return(list(Gammahat=Gammahat, loglik=loglik, muhat=muhat, Betahat=Betahat, Deltahat=Deltahat, Rhat=Rhat)) } y <- mbrdr.y(object) x <- mbrdr.x(object) n <- dim(y)[1] r <- dim(y)[2] if (is.null(num.d) ) num.d <- (r-1) num.f <- {if(is.null(fx.choice)) 1 else fx.choice} h <- {if(is.null(nclust)) 5 else nclust} if(num.f>4 & is.null(fx)) stop("fx.choice must be less than or equal to 4. If you want to other candidates for fx, use the fx option") else { if(!is.null(fx)) fx<-fx else fx <- choose.fx(x, fx.choice=num.f, nclust=h)} logliks <- NULL Gammahats <- list(NULL) for (i in 1:num.d) { temp.fit <- upfrr(y, d=i, fx=fx) logliks[i] <- temp.fit$loglik Gammahats[[i]] <- temp.fit$Gammahat } d0.loglik <- upfrr(y, d=0, fx=fx)$loglik full.loglik <- upfrr(y, d=r, fx=fx)$loglik logliks <- c(d0.loglik, logliks) stat <- 2*(full.loglik - logliks) ans <- list(M=Gammahats[[num.d]], stats=stat, evalues=logliks, Gammahats=Gammahats, fx=fx, numdir=num.d) return(ans) } mbrdr.test.upfrr <-function(object, nd) { stat <- object$stats y <- mbrdr.y(object) fx <- object$fx r <- dim(y)[2]; q<- dim(fx)[2] st<-df<-pv<-0 nt <- nd for (i in 0:nt-1) {st[i+1]<-stat[i+1] df[i+1]<-(r-i)*(q-i) pv[i+1]<-1-pchisq(st[i+1],df[i+1]) } z<-data.frame(cbind(st,df, round(pv,4))) rr<-paste(0:(nt-1),"D vs >= ",1:nt,"D",sep="") dimnames(z)<-list(rr,c("Stat","df","p-value")) z } "print.mbrdr" <- function(x, digits = max(3, getOption("digits") - 3), ...) { cat("\nCall:\n",deparse(x$call),"\n\n",sep="") cat("Eigenvectors:\n") evectors<-as.matrix(x$evectors) print.default(evectors) stats <- t(as.matrix(round(x$stats,4))) nt <- length(x$stats) rr <- paste("H0: d=", 0:(nt-1),sep="") colnames(stats)<-rr rownames(stats) <- c("") cat("Statistics:\n") print(stats) cat("\n") invisible(x) } "summary.mbrdr" <- function (object, ...){ z <- object ans <- z[c("call")] nd <- z$numdir stats <- t(as.matrix(round(z$stats,4))) nt <- length(z$stats) rr <- paste("H0: d=", 0:(nt-1),sep="") colnames(stats)<-rr rownames(stats) <- c("") ans$evectors <- z$evectors[,1:nd] ans$method <- z$method ans$weights <- mbrdr.wts(z) sw <- sqrt(ans$weights) y <- z$y ans$n <- z$cases ans$test <- mbrdr.test(z, nt) ans$stats <- stats class(ans) <- "summary.mbrdr" ans } "print.summary.mbrdr" <- function (x, digits = max(3, getOption("digits") - 3), ...) { cat("\nCall:\n") cat(paste(deparse(x$call), sep="\n", collapse = "\n"), "\n\n", sep="") cat("Method:\n") cat(paste(x$method, ", n = ", x$n,sep="")) if(diff(range(x$weights)) > 0) cat(", using weights.\n") else cat(".\n") cat("\n") cat("\nEigenvectors:\n") print(x$evectors, digits=digits) cat("\n") cat("\nStatistics:\n") print(x$stats,digits=digits) cat("\n") if (!is.null(x$test)){ cat("\nAsymp. Chi-square tests for dimension:\n") print(as.matrix(x$test),digits=digits)} invisible(x) } choose.fx = function(X, fx.choice=1, nclust=5){ CategoricalBasis<-function(y){ nobs=length(y); bin.y<-unique(sort(y)); r<- length(unique(sort(y)))-1; fy<-array(rep(0), c(r, nobs)); ny<-array(rep(0), c(r, 1)); for (i in 1:r){ fy[i,]<-sapply(y, function(x) (x==bin.y[i]) ) } return(fy); } if (fx.choice==1) {fx = scale(X)} if (fx.choice==2) {fx = cbind(scale(X), scale(X^2))} if (fx.choice==3) {fx = cbind(scale(X), scale(exp(X)))} if (fx.choice==4) {slice = kmeans(X, nclust)$clust; fx=t(CategoricalBasis(slice))} if (fx.choice >4) {fx= NULL} return(fx) } SIGMAS = function(Y, fx) { if (!is.vector(Y)) { nobs <- dim(Y)[1]; npred <- dim(Y)[2]; mu <- array(colMeans(Y),dim=c(1,npred)); } if (is.vector(Y)){ nobs <- length(Y); npred <- 1 ; Y<-array(Y, dim=c(nobs,1)); mu <- array(mean(Y),dim=c(1,npred)); } r <- dim(fx)[2]; X.centered <- as.matrix( Y-array(rep(1,times=nobs),dim=c(nobs,1))%*%mu ) ; Sigmahat <- 1/nobs*t(X.centered)%*%X.centered; P_F <- fx%*%solve(t(fx)%*%fx)%*%t(fx); Sigmahat_fit <- 1/nobs*t(X.centered)%*%P_F%*%X.centered; rm(P_F) Sigmahat_res<-Sigmahat-Sigmahat_fit; return(list(Sigmahat_fit=Sigmahat_fit, Sigmahat=Sigmahat, Sigmahat_res=Sigmahat_res)); } matpower <-function(M,pow) { if (!is.matrix(M)) stop("The argument is not a matrix") if ((dim(M)[1]==1) & (dim(M)[2]==1)) return( as.matrix(M^pow) ); svdM<-svd(M); return(svdM$u %*% diag(c(svdM$d)^pow) %*% t(svdM$v)); }
context("[validate] NICE TSD2 program 2b") test_that("The summaries match", { result <- replicate.example("dietfat.fe", dietfat, likelihood="poisson", link="log", linearModel="fixed") compare.summaries(result$s1, result$s2) })
ypbpSurv <- function(time, z, par, tau, degree, baseline=c("hazard", "odds")){ baseline <- match.arg(baseline) q <- length(z) base <- bp(time, degree, tau) psi <- par[1:q] phi <- par[(q+1):(2*q)] gamma <- par[(2*q+1):(2*q+degree)] theta_S <- exp( as.numeric(z%*%psi) ) theta_L <- exp( as.numeric(z%*%phi) ) if(baseline=="hazard"){ Ht0 <- as.numeric(base$B%*%gamma) + as.numeric(time>tau)*(time-tau)*degree*gamma[degree]/tau St0 <- exp(-Ht0) Ft0 <- 1-St0 St <- exp( -theta_L*(log(theta_L*St0 + theta_S*Ft0)-(as.numeric(z%*%phi) - Ht0) ) ) }else{ ratio <- exp( as.numeric(z%*%psi) - as.numeric(z%*%phi) ) Rt0 <- as.numeric(base$B%*%gamma) + as.numeric(time>tau)*(time-tau)*degree*gamma[degree]/tau St <- exp(-theta_L*log(1 + ratio*Rt0)) } return(St) } ypbpSurv2 <- function(time, z, x, par, tau, degree, baseline=c("hazard", "odds")){ baseline <- match.arg(baseline) q <- length(z) p <- length(x) base <- bp(time, degree, tau) psi <- par[1:q] phi <- par[(q+1):(2*q)] beta <- par[(2*q+1):(2*q+p)] gamma <- par[(2*q+p+1):(2*q+p+degree)] theta_S <- exp( as.numeric(z%*%psi) ) theta_L <- exp( as.numeric(z%*%phi) ) theta_C <- exp( as.numeric(x%*%beta) ) ratio <- exp( as.numeric(z%*%psi) - as.numeric(z%*%phi) ) if(baseline=="hazard"){ Ht0 <- as.numeric(base$B%*%gamma) + as.numeric(time>tau)*(time-tau)*degree*gamma[degree]/tau St0 <- exp(-Ht0) Ft0 <- 1-St0 St <- exp( -theta_L*theta_C*(log(theta_L*St0 + theta_S*Ft0)-(as.numeric(z%*%phi) - Ht0) ) ) }else{ St <- exp(-theta_L*theta_C*log(1 + ratio*Rt0)) Rt0 <- as.numeric(base$B%*%gamma) + as.numeric(time>tau)*(time-tau)*degree*gamma[degree]/tau } return(St) } survfit.ypbp <- function(formula, newdata, ...){ object <- formula mf <- object$mf labels <- names(mf)[-1] baseline <- object$baseline time <- sort( stats::model.response(mf)[,1]) status <- sort( stats::model.response(mf)[,2]) data <- data.frame(cbind(time, status, mf[,-1])) names(data) <- c("time", "status", names(mf)[-1]) degree <- object$degree tau <- object$tau labels <- match.arg(names(newdata), labels, several.ok = TRUE) formula <- object$formula Z <- as.matrix(stats::model.matrix(formula, data = newdata, rhs = 1)[,-1]) X <- suppressWarnings(try( as.matrix(stats::model.matrix(formula, data = newdata, rhs = 2)[,-1]), TRUE)) St <- list() if(object$approach=="mle"){ par <- object$fit$par if(object$p==0){ for(i in 1:nrow(newdata)){ St[[i]] <- ypbpSurv(time, Z[i, ], par, tau, degree, baseline) } }else{ for(i in 1:nrow(newdata)){ St[[i]] <- ypbpSurv2(time, Z[i, ], X[i, ], par, tau, degree, baseline) } } }else{ samp <- rstan::extract(object$fit) if(object$p==0){ par <- cbind(samp$psi, samp$phi, samp$gamma) for(i in 1:nrow(newdata)){ aux <- apply(par, 1, ypbpSurv, time=time, z=Z[i,], tau=tau, degree=degree, baseline=baseline) St[[i]] <- apply(aux, 1, mean) } }else{ par <- cbind(samp$psi, samp$phi, samp$beta, samp$gamma) for(i in 1:nrow(newdata)){ aux <- apply(par, 1, ypbpSurv, time=time, z=Z[i,], x=X[i, ], tau=tau, degree=degree, baseline=baseline) St[[i]] <- apply(aux, 1, mean) } } } out <- list(time = time, surv = St) class(out) <- "survfit.ypbp" return(out) } ypbpCrossSurv <- function(z1, z2, par, tau0, tau, degree, baseline){ diff_St <- function(time, z1, z2, par, tau, degree, baseline){ St1 <- ypbpSurv(time=time, z=z1, par=par, tau=tau, degree=degree, baseline=baseline) St2 <- ypbpSurv(time=time, z=z2, par=par, tau=tau, degree=degree, baseline=baseline) return(St1-St2) } I <- c(tau0, 1.5*tau) t <- try(stats::uniroot(diff_St, interval=I, z1=z1, z2=z2, par=par, tau=tau, degree=degree, baseline=baseline)$root, TRUE) if(class(t)=="try-error") { return(NA) }else{ return(t) } } ypbpCrossSurv2 <- function(z1, z2, x, par, tau0, tau, degree, baseline){ diff_St <- function(time, z1, z2, x, par, tau, degree, baseline){ St1 <- ypbpSurv2(time=time, z=z1, x=x, par=par, tau=tau, degree=degree, baseline=baseline) St2 <- ypbpSurv2(time=time, z=z2, x=x, par=par, tau=tau, degree=degree, baseline=baseline) return(St1-St2) } I <- c(tau0, 1.5*tau) t <- try(stats::uniroot(diff_St, interval=I, z1=z1, z2=z2, x=x, par=par, tau=tau, degree=degree, baseline=baseline)$root, TRUE) if(class(t)=="try-error") { return(NA) }else{ return(t) } } crossTime <- function(object, ...) UseMethod("crossTime") crossTime.ypbp <- function(object, newdata1, newdata2, conf.level=0.95, nboot=4000, ...){ q <-object$q p <-object$p mf <- object$mf labels <- names(mf)[-1] baseline <- object$baseline time <- stats::model.response(mf)[,1] status <- stats::model.response(mf)[,2] o <- order(time) data <- data.frame(cbind(time, status, mf[,-1]))[o,] names(data) <- c("time", "status", labels) tau0 <- min(time) degree <- object$degree tau <- object$tau labels <- match.arg(names(newdata1), names(newdata2), several.ok=TRUE) labels <- match.arg(names(mf)[-1], names(newdata1), several.ok=TRUE) z1 <- matrix(stats::model.matrix(object$formula, data = newdata1, rhs = 1)[,-1], ncol=q) z2 <- matrix(stats::model.matrix(object$formula, data = newdata2, rhs = 1)[,-1], ncol=q) if(p>0){ x <- matrix(stats::model.matrix(object$formula, data = newdata2, rhs = 2)[,-1], ncol=p) } I <- c(tau0, 1.5*tau) alpha <- 1 - conf.level prob <- c(alpha/2, 1-alpha/2) if(object$approach=="mle"){ t <- c() par <- object$fit$par for(i in 1:nrow(newdata1)){ if(p==0){ t[i] <- ypbpCrossSurv(z1=z1[i,], z2=z2[i,], par=par, tau0, tau, degree=degree, baseline=baseline) }else{ t[i] <- ypbpCrossSurv2(z1=z1[i,], z2=z2[i,], x=x[i,], par=par, tau0, tau, degree=degree, baseline=baseline) } } par <- with(object, ypbpBoot(formula=formula, data=data, n_int=n_int, rho=rho, tau=tau, nboot=nboot, prob=prob)) ci <- matrix(nrow=nrow(newdata1), ncol=2) if(object$p==0){ for(i in 1:nrow(newdata1)){ aux <- apply(par, 1, ypbpCrossSurv, z1=z1[i,], z2=z2[i,], tau0, tau, degree=degree, baseline=baseline) ci[i,] <- stats::quantile(aux, probs=prob, na.rm=TRUE) } }else{ for(i in 1:nrow(newdata1)){ aux <- apply(par, 1, ypbpCrossSurv2, z1=z1[i,], z2=z2[i,], x=x[i,], tau0, tau, degree=degree, baseline=baseline) ci[i,] <- stats::quantile(aux, probs=prob, na.rm=TRUE) } } t <- data.frame(cbind(t, ci)) names(t) <- c("Est.", paste(100*prob, "%", sep="")) }else{ t <- matrix(nrow=nrow(newdata1), ncol=3) samp <- rstan::extract(object$fit) if(object$p==0){ par <- cbind(samp$psi, samp$phi, samp$gamma) for(i in 1:nrow(newdata1)){ aux <- apply(par, 1, ypbpCrossSurv, z1=z1[i,], z2=z2[i,], tau0, tau, degree=degree, baseline=baseline) ci <- stats::quantile(aux, probs=prob, na.rm=TRUE) t[i,] <- c(mean(aux, na.rm=TRUE), ci) } }else{ par <- cbind(samp$psi, samp$phi, samp$beta, samp$gamma) for(i in 1:nrow(newdata1)){ aux <- apply(par, 1, ypbpCrossSurv2, z1=z1[i,], z2=z2[i,], x=x[i,], tau0, tau, degree=degree, baseline=baseline) ci <- stats::quantile(aux, probs=prob, na.rm=TRUE) t[i,] <- c(mean(aux, na.rm=TRUE), ci) } } t <- as.data.frame(t) names(t) <- c("Est.", names(ci) ) } return(t) }
context("Bounding box using ru_rcpp") normal_box <- function(d, sigma = diag(d), rotate = TRUE, r = 1 / 2) { sigma <- as.matrix(sigma) if (rotate & d > 1) { l_mat <- t(chol(solve(sigma))) l_mat <- l_mat / det(l_mat) ^ (1/d) sigma <- t(l_mat) %*% sigma %*% l_mat } val <- sqrt((r * d + 1) / r) ar <- 1 bplus <- val * exp(-1 /2) * sqrt(diag(sigma)) bminus <- -bplus box <- c(ar, bminus, bplus) adj_mat <- t(sqrt(diag(sigma)) * stats::cov2cor(sigma)) vals <- rbind(rep(0, d), -val * adj_mat, val * adj_mat) colnames(vals) <- paste("vals", 1:d, sep="") conv <- rep(0, 2 * d + 1) box <- cbind(box, vals, conv) bs <- paste(paste("b", 1:d, sep=""),rep(c("minus", "plus"), each=d), sep="") rownames(box) <- c("a", bs) return(box) } my_tol <- 1e-5 ptr_N01 <- create_xptr("logdN01") x1a <- ru_rcpp(logf = ptr_N01, d = 1, n = 1, init = 0) test_that("N(0,1)", { testthat::expect_equal(x1a$box, normal_box(d = 1), tolerance = my_tol) }) ptr_mvn <- create_xptr("logdmvnorm") sigma <- 2 covmat <- matrix(sigma, 1, 1) x1b <- ru_rcpp(logf = ptr_mvn, sigma = covmat, d = 1, n = 1, init = 0) test_that("N(0,2)", { testthat::expect_equal(x1b$box, normal_box(d = 1, sigma = 2), tolerance = my_tol) }) ptr_bvn <- create_xptr("logdnorm2") rho <- 0 x2ai <- ru_rcpp(logf = ptr_bvn, rho = rho, d = 2, n = 1, init = c(0, 0), rotate = TRUE) test_that("BVN, rotation", { testthat::expect_equal(x2ai$box, normal_box(d = 2), tolerance = my_tol) }) x2aii <- ru_rcpp(logf = ptr_bvn, rho = rho, d = 2, n = 1, init = c(0, 0), rotate = FALSE) test_that("BVN, no rotation", { testthat::expect_equal(x2aii$box, normal_box(d = 2), tolerance = my_tol) }) ptr_mvn <- create_xptr("logdmvnorm") rho <- 0.9 covmat <- matrix(c(1, rho, rho, 1), 2, 2) x2bi <- ru_rcpp(logf = ptr_mvn, sigma = covmat, d = 2, n = 1, init = c(0, 0), rotate = FALSE) test_that("BVN, rho = 0.9, no rotation", { testthat::expect_equal(x2bi$box, normal_box(d = 2, sigma = covmat, rotate = FALSE), tolerance = my_tol) }) x2bii <- ru_rcpp(logf = ptr_mvn, sigma = covmat, d = 2, n = 1, init = c(0, 0), rotate = TRUE) test_that("BVN, rho = 0.9, rotation", { testthat::expect_equal(x2bii$box, normal_box(d = 2, sigma = covmat, rotate = TRUE), tolerance = my_tol) }) covmat <- matrix(c(10, 3, 3, 2), 2, 2) x2ci <- ru_rcpp(logf = ptr_mvn, sigma = covmat, d = 2, n = 1, init = c(0, 0), rotate = FALSE) test_that("BVN, general Sigma, no rotation", { testthat::expect_equal(x2ci$box, normal_box(d = 2, sigma = covmat, rotate = FALSE), tolerance = my_tol) }) x2cii <- ru_rcpp(logf = ptr_mvn, sigma = covmat, d = 2, n = 1, init = c(0, 0), rotate = TRUE) test_that("BVN, general Sigma, rotation", { testthat::expect_equal(x2cii$box, normal_box(d = 2, sigma = covmat, rotate = TRUE), tolerance = my_tol) }) covmat <- matrix(c(10, -3, -3, 2), 2, 2) x2di <- ru_rcpp(logf = ptr_mvn, sigma = covmat, d = 2, n = 1, init = c(0, 0), rotate = FALSE, mean = c(1, 2)) test_that("BVN, non-zero mu, general Sigma, no rotation", { testthat::expect_equal(x2di$box, normal_box(d = 2, sigma = covmat, rotate = FALSE), tolerance = my_tol) }) x2dii <- ru_rcpp(logf = ptr_mvn, sigma = covmat, d = 2, n = 1, init = c(0, 0), rotate = TRUE, mean = c(1, 2)) test_that("BVN, non-zero mu, general Sigma, rotation", { testthat::expect_equal(x2dii$box, normal_box(d = 2, sigma = covmat, rotate = TRUE), tolerance = my_tol) }) covmat <- matrix(rho, 3, 3) + diag(1 - rho, 3) x3ai <- ru_rcpp(logf = ptr_mvn, sigma = covmat, d = 3, n = 1, init = c(0, 0, 0), rotate = FALSE) test_that("TVN, rho = 0.9, no rotation", { testthat::expect_equal(x3ai$box, normal_box(d = 3, sigma = covmat, rotate = FALSE), tolerance = my_tol) }) x3aii <- ru_rcpp(logf = ptr_mvn, sigma = covmat, d = 3, n = 1, init = c(0, 0, 0), rotate = TRUE) test_that("TVN, rho = 0.9, rotation", { testthat::expect_equal(x3aii$box, normal_box(d = 3, sigma = covmat, rotate = TRUE), tolerance = my_tol) }) lambda <- 0 ptr_lnorm <- create_xptr("logdlnorm") mu <- 0 sigma <- 1 lambda <- 0 x <- ru_rcpp(logf = ptr_lnorm, mu = mu, sigma = sigma, d = 1, n = 1, lower = 0, init = 0.1, trans = "BC", lambda = lambda) test_that("Log-normal", { testthat::expect_equal(x$box, normal_box(d = 1), tolerance = my_tol) }) gamma_box <- function(shape = 1, rate = 1, r = 1 / 2) { if (shape < 1) { stop("A ratio-of-uniforms bounding box cannot be found when shape < 1") } x_mode <- (shape - 1) / rate x_max <- stats::dgamma(x_mode, shape = shape, rate = rate) ar <- 1 a_quad <- rate * r / (r + 1) b_quad <- -(1 + r * (shape - 1) / (r + 1) - a_quad * x_mode) c_quad <- -x_mode b_vals <- Re(polyroot(c(c_quad, b_quad, a_quad))) vals1 <- c(0, b_vals) b_fun <- function(x) { x * (stats::dgamma(x + x_mode, shape = shape) / x_max) ^ (r / (r + 1)) } box <- c(ar, b_fun(b_vals)) conv <- rep(0, 3) box <- cbind(box, vals1, conv) bs <- paste(paste("b", 1, sep=""),rep(c("minus", "plus"), each=1), sep="") rownames(box) <- c("a", bs) return(box) } ptr_gam <- create_xptr("logdgamma") alpha <- 1 x1 <- suppressWarnings(ru_rcpp(logf = ptr_gam, alpha = alpha, d = 1, n = 1, lower = 0, init = alpha)) test_that("Gamma(1, 1)", { testthat::expect_equal(x1$box, gamma_box(shape = 1), tolerance = my_tol) }) alpha <- 10 x2 <- ru_rcpp(logf = ptr_gam, alpha = alpha, d = 1, n = 1, lower = 0, init = alpha) test_that("Gamma(10, 1)", { testthat::expect_equal(x2$box, gamma_box(shape = 10), tolerance = my_tol) })
make.X <- function(df, num.groups, groups){ if (any(class(df)=="spec_tbl_df")){df <- as.data.frame(df)} xrow <- dim(df)[1] x.s <- numeric() for (i in 1:num.groups){ x.s[i] <- length(groups[[i]]) } xcol <- sum(x.s) X <- matrix(0, nrow=xrow, ncol=xcol) counter <-1 for (j in 1:num.groups){ for (k in 1:x.s[j]){ x <- groups[[j]][k] X[, counter] <- df[, x] counter <- counter + 1 } counter <- counter } colnames(X) <- unlist(groups) return(X) }
bar_plot <- function(df_plot, x, y, fill, label, xlb = "", ylb = "", ttl = "", sttl = "", lgnd = NULL, rotate = FALSE, col_palette = NULL, ylim_range = NULL){ plt <- df_plot %>% ggplot(aes_string(x = x, y = y, fill = fill, label = label)) + geom_bar(stat = "identity") + labs(x = xlb, y = ylb, title = ttl, subtitle = sttl) + scale_fill_manual(values = user_colours(nrow(df_plot), col_palette)) if(is.null(lgnd)){ plt <- plt + guides(fill = FALSE) } else { plt <- plt + scale_fill_discrete(name = lgnd) } if(!is.null(ylim_range)){ plt <- plt + ylim(ylim_range) } if(rotate){ plt <- plt + theme(axis.text.x = element_text(angle = 45, hjust = 1)) } return(plt) }
NULL snowball_cancel_cluster <- function(ClusterId) { op <- new_operation( name = "CancelCluster", http_method = "POST", http_path = "/", paginator = list() ) input <- .snowball$cancel_cluster_input(ClusterId = ClusterId) output <- .snowball$cancel_cluster_output() config <- get_config() svc <- .snowball$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .snowball$operations$cancel_cluster <- snowball_cancel_cluster snowball_cancel_job <- function(JobId) { op <- new_operation( name = "CancelJob", http_method = "POST", http_path = "/", paginator = list() ) input <- .snowball$cancel_job_input(JobId = JobId) output <- .snowball$cancel_job_output() config <- get_config() svc <- .snowball$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .snowball$operations$cancel_job <- snowball_cancel_job snowball_create_address <- function(Address) { op <- new_operation( name = "CreateAddress", http_method = "POST", http_path = "/", paginator = list() ) input <- .snowball$create_address_input(Address = Address) output <- .snowball$create_address_output() config <- get_config() svc <- .snowball$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .snowball$operations$create_address <- snowball_create_address snowball_create_cluster <- function(JobType, Resources, Description = NULL, AddressId, KmsKeyARN = NULL, RoleARN, SnowballType = NULL, ShippingOption, Notification = NULL, ForwardingAddressId = NULL, TaxDocuments = NULL) { op <- new_operation( name = "CreateCluster", http_method = "POST", http_path = "/", paginator = list() ) input <- .snowball$create_cluster_input(JobType = JobType, Resources = Resources, Description = Description, AddressId = AddressId, KmsKeyARN = KmsKeyARN, RoleARN = RoleARN, SnowballType = SnowballType, ShippingOption = ShippingOption, Notification = Notification, ForwardingAddressId = ForwardingAddressId, TaxDocuments = TaxDocuments) output <- .snowball$create_cluster_output() config <- get_config() svc <- .snowball$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .snowball$operations$create_cluster <- snowball_create_cluster snowball_create_job <- function(JobType = NULL, Resources = NULL, Description = NULL, AddressId = NULL, KmsKeyARN = NULL, RoleARN = NULL, SnowballCapacityPreference = NULL, ShippingOption = NULL, Notification = NULL, ClusterId = NULL, SnowballType = NULL, ForwardingAddressId = NULL, TaxDocuments = NULL, DeviceConfiguration = NULL) { op <- new_operation( name = "CreateJob", http_method = "POST", http_path = "/", paginator = list() ) input <- .snowball$create_job_input(JobType = JobType, Resources = Resources, Description = Description, AddressId = AddressId, KmsKeyARN = KmsKeyARN, RoleARN = RoleARN, SnowballCapacityPreference = SnowballCapacityPreference, ShippingOption = ShippingOption, Notification = Notification, ClusterId = ClusterId, SnowballType = SnowballType, ForwardingAddressId = ForwardingAddressId, TaxDocuments = TaxDocuments, DeviceConfiguration = DeviceConfiguration) output <- .snowball$create_job_output() config <- get_config() svc <- .snowball$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .snowball$operations$create_job <- snowball_create_job snowball_create_return_shipping_label <- function(JobId, ShippingOption = NULL) { op <- new_operation( name = "CreateReturnShippingLabel", http_method = "POST", http_path = "/", paginator = list() ) input <- .snowball$create_return_shipping_label_input(JobId = JobId, ShippingOption = ShippingOption) output <- .snowball$create_return_shipping_label_output() config <- get_config() svc <- .snowball$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .snowball$operations$create_return_shipping_label <- snowball_create_return_shipping_label snowball_describe_address <- function(AddressId) { op <- new_operation( name = "DescribeAddress", http_method = "POST", http_path = "/", paginator = list() ) input <- .snowball$describe_address_input(AddressId = AddressId) output <- .snowball$describe_address_output() config <- get_config() svc <- .snowball$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .snowball$operations$describe_address <- snowball_describe_address snowball_describe_addresses <- function(MaxResults = NULL, NextToken = NULL) { op <- new_operation( name = "DescribeAddresses", http_method = "POST", http_path = "/", paginator = list() ) input <- .snowball$describe_addresses_input(MaxResults = MaxResults, NextToken = NextToken) output <- .snowball$describe_addresses_output() config <- get_config() svc <- .snowball$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .snowball$operations$describe_addresses <- snowball_describe_addresses snowball_describe_cluster <- function(ClusterId) { op <- new_operation( name = "DescribeCluster", http_method = "POST", http_path = "/", paginator = list() ) input <- .snowball$describe_cluster_input(ClusterId = ClusterId) output <- .snowball$describe_cluster_output() config <- get_config() svc <- .snowball$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .snowball$operations$describe_cluster <- snowball_describe_cluster snowball_describe_job <- function(JobId) { op <- new_operation( name = "DescribeJob", http_method = "POST", http_path = "/", paginator = list() ) input <- .snowball$describe_job_input(JobId = JobId) output <- .snowball$describe_job_output() config <- get_config() svc <- .snowball$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .snowball$operations$describe_job <- snowball_describe_job snowball_describe_return_shipping_label <- function(JobId = NULL) { op <- new_operation( name = "DescribeReturnShippingLabel", http_method = "POST", http_path = "/", paginator = list() ) input <- .snowball$describe_return_shipping_label_input(JobId = JobId) output <- .snowball$describe_return_shipping_label_output() config <- get_config() svc <- .snowball$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .snowball$operations$describe_return_shipping_label <- snowball_describe_return_shipping_label snowball_get_job_manifest <- function(JobId) { op <- new_operation( name = "GetJobManifest", http_method = "POST", http_path = "/", paginator = list() ) input <- .snowball$get_job_manifest_input(JobId = JobId) output <- .snowball$get_job_manifest_output() config <- get_config() svc <- .snowball$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .snowball$operations$get_job_manifest <- snowball_get_job_manifest snowball_get_job_unlock_code <- function(JobId) { op <- new_operation( name = "GetJobUnlockCode", http_method = "POST", http_path = "/", paginator = list() ) input <- .snowball$get_job_unlock_code_input(JobId = JobId) output <- .snowball$get_job_unlock_code_output() config <- get_config() svc <- .snowball$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .snowball$operations$get_job_unlock_code <- snowball_get_job_unlock_code snowball_get_snowball_usage <- function() { op <- new_operation( name = "GetSnowballUsage", http_method = "POST", http_path = "/", paginator = list() ) input <- .snowball$get_snowball_usage_input() output <- .snowball$get_snowball_usage_output() config <- get_config() svc <- .snowball$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .snowball$operations$get_snowball_usage <- snowball_get_snowball_usage snowball_get_software_updates <- function(JobId) { op <- new_operation( name = "GetSoftwareUpdates", http_method = "POST", http_path = "/", paginator = list() ) input <- .snowball$get_software_updates_input(JobId = JobId) output <- .snowball$get_software_updates_output() config <- get_config() svc <- .snowball$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .snowball$operations$get_software_updates <- snowball_get_software_updates snowball_list_cluster_jobs <- function(ClusterId, MaxResults = NULL, NextToken = NULL) { op <- new_operation( name = "ListClusterJobs", http_method = "POST", http_path = "/", paginator = list() ) input <- .snowball$list_cluster_jobs_input(ClusterId = ClusterId, MaxResults = MaxResults, NextToken = NextToken) output <- .snowball$list_cluster_jobs_output() config <- get_config() svc <- .snowball$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .snowball$operations$list_cluster_jobs <- snowball_list_cluster_jobs snowball_list_clusters <- function(MaxResults = NULL, NextToken = NULL) { op <- new_operation( name = "ListClusters", http_method = "POST", http_path = "/", paginator = list() ) input <- .snowball$list_clusters_input(MaxResults = MaxResults, NextToken = NextToken) output <- .snowball$list_clusters_output() config <- get_config() svc <- .snowball$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .snowball$operations$list_clusters <- snowball_list_clusters snowball_list_compatible_images <- function(MaxResults = NULL, NextToken = NULL) { op <- new_operation( name = "ListCompatibleImages", http_method = "POST", http_path = "/", paginator = list() ) input <- .snowball$list_compatible_images_input(MaxResults = MaxResults, NextToken = NextToken) output <- .snowball$list_compatible_images_output() config <- get_config() svc <- .snowball$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .snowball$operations$list_compatible_images <- snowball_list_compatible_images snowball_list_jobs <- function(MaxResults = NULL, NextToken = NULL) { op <- new_operation( name = "ListJobs", http_method = "POST", http_path = "/", paginator = list() ) input <- .snowball$list_jobs_input(MaxResults = MaxResults, NextToken = NextToken) output <- .snowball$list_jobs_output() config <- get_config() svc <- .snowball$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .snowball$operations$list_jobs <- snowball_list_jobs snowball_update_cluster <- function(ClusterId, RoleARN = NULL, Description = NULL, Resources = NULL, AddressId = NULL, ShippingOption = NULL, Notification = NULL, ForwardingAddressId = NULL) { op <- new_operation( name = "UpdateCluster", http_method = "POST", http_path = "/", paginator = list() ) input <- .snowball$update_cluster_input(ClusterId = ClusterId, RoleARN = RoleARN, Description = Description, Resources = Resources, AddressId = AddressId, ShippingOption = ShippingOption, Notification = Notification, ForwardingAddressId = ForwardingAddressId) output <- .snowball$update_cluster_output() config <- get_config() svc <- .snowball$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .snowball$operations$update_cluster <- snowball_update_cluster snowball_update_job <- function(JobId, RoleARN = NULL, Notification = NULL, Resources = NULL, AddressId = NULL, ShippingOption = NULL, Description = NULL, SnowballCapacityPreference = NULL, ForwardingAddressId = NULL) { op <- new_operation( name = "UpdateJob", http_method = "POST", http_path = "/", paginator = list() ) input <- .snowball$update_job_input(JobId = JobId, RoleARN = RoleARN, Notification = Notification, Resources = Resources, AddressId = AddressId, ShippingOption = ShippingOption, Description = Description, SnowballCapacityPreference = SnowballCapacityPreference, ForwardingAddressId = ForwardingAddressId) output <- .snowball$update_job_output() config <- get_config() svc <- .snowball$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .snowball$operations$update_job <- snowball_update_job snowball_update_job_shipment_state <- function(JobId, ShipmentState) { op <- new_operation( name = "UpdateJobShipmentState", http_method = "POST", http_path = "/", paginator = list() ) input <- .snowball$update_job_shipment_state_input(JobId = JobId, ShipmentState = ShipmentState) output <- .snowball$update_job_shipment_state_output() config <- get_config() svc <- .snowball$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .snowball$operations$update_job_shipment_state <- snowball_update_job_shipment_state
niter=100 fit=LSM(Y=School9network, senderCov=School9NodeCov, receiverCov=School9NodeCov, edgeCov=School9EdgeCov, niter=niter) random.fit = HLSMrandomEF(Y = ps.advice.mat, senderCov = ps.node.df, receiverCov=ps.node.df, edgeCov=ps.edge.df, dd = 2,niter = niter) summary(random.fit) names(random.fit) fixed.fit = HLSMfixedEF(Y = ps.advice.mat, senderCov = ps.node.df, receiverCov=ps.node.df, edgeCov=ps.edge.df, dd = 2,niter = niter) summary(fixed.fit) names(fixed.fit)
"getDiffThetaCl" <- function(th, thetaClasslist, mod) { modeldiff <- mod@modeldiffs modellist <- mod@modellist parorder <- mod@parorderdiff parorderchange <- mod@parorderchange pcnt <- 1 if(length(modeldiff$change)!=0) thetaClasslist <- getDiffThetaClChange(th, parorderchange, modellist, thetaClasslist, modeldiff$change) if(length(modeldiff$free)!=0 || length(modeldiff$add) != 0) for(diff in append(modeldiff$free, modeldiff$add)){ partmp <- th[parorder[[pcnt]]$ind] removepar <- parorder[[pcnt]]$rm pcnt <- pcnt + 1 if(diff$what %in% modellist[[diff$dataset[1]]]@positivepar) partmp <- exp(partmp) for(fx in removepar){ if(fx %in% modellist[[diff$dataset]]@fvecind[[diff$what]]) partmp <- append(partmp, unlist(slot(modellist[[diff$dataset]], diff$what))[fx], after=(fx-1)) else partmp <- append(partmp, 0, after=(fx-1)) } if(length(diff$ind) == 2) for (d in diff$dataset) slot(thetaClasslist[[d]], diff$what)[[diff$ind[1]]][diff$ind[2]] <- partmp if(length(diff$ind) == 1) for (d in diff$dataset) slot(thetaClasslist[[d]], diff$what)[diff$ind] <- partmp } if(length(modeldiff$remove)!=0) for(diff in modeldiff$remove){ if(length(diff$ind) == 2) for (d in diff$dataset) slot(thetaClasslist[[d]], diff$what)[[diff$ind[1]]][- diff$ind[2]] if(length(diff$ind) == 1) for (d in diff$dataset) slot(thetaClasslist[[d]], diff$what)[-diff$ind] } if(length(modeldiff$rel)!=0) for(diff in modeldiff$rel){ ds1 <- diff$dataset1 ds2 <- diff$dataset2 if(length(diff$rel) == 0 || diff$rel == "lin"){ if( length(diff$fix) !=0) thscal <- diff$start else thscal <- th[parorder[[pcnt]]$ind] pcnt <- pcnt+1 if(length(diff$ind1)==1 && length(diff$ind2)==1){ for(i in 1:length(ds1)){ slot(thetaClasslist[[ds1[i]]], diff$what1)[diff$ind1] <- slot(thetaClasslist[[ds2[i]]], diff$what2)[diff$ind2] * thscal[1] + thscal[2] } } if(length(diff$ind1)==1 && length(diff$ind2)==2){ for(i in 1:length(ds1)) slot(thetaClasslist[[ds1[i]]], diff$what1)[diff$ind1] <- slot(thetaClasslist[[ds2[i]]], diff$what2)[[diff$ind2[1]]][diff$ind2[2]] * thscal[1] + thscal[2] } if(length(diff$ind1)==2 && length(diff$ind2)==1){ for(i in 1:length(ds1)) slot(thetaClasslist[[ds1[i]]], diff$what1)[[diff$ind1[1]]][diff$ind1[2]] <- slot(thetaClasslist[[ds2[i]]], diff$what2)[diff$ind2] * thscal[1] + thscal[2] } if(length(diff$ind1)==2 && length(diff$ind2)==2){ for(i in 1:length(ds1)) slot(thetaClasslist[[ds1[i]]], diff$what1)[[diff$ind1[1]]][diff$ind1[2]] <- slot(thetaClasslist[[ds2[i]]], diff$what2)[[diff$ind2[1]]][diff$ind2[2]] * thscal[1] + thscal[2] } } } if(length(modeldiff$dscal) != 0) { for(i in 1:length(modeldiff$dscal)) { parvec <- getPar(modellist[[modeldiff$dscal[[i]]$to]], parorder[[pcnt]], th, thetaClasslist[[i]]) pcnt <- pcnt + 1 slot(thetaClasslist[[modeldiff$dscal[[i]]$to]], "drel") <- parvec } } thetaClasslist }
get_ndx_scores <- function(weights, geno, names) { scored = as.vector(weights != 0) geno2 = subset(geno, scored == TRUE) col = match(geno2,names) u = as.vector(na.omit(unique(col))) return (sort(u)) }
require(NPBayesImputeCat) data('NYexample') model <- CreateModel(X,MCZ,50,200000,0.25,0.25,8888) model$Run(100,1000,100) result <- model$snapshot IX <- GetDataFrame(result$ImputedX,X) View(IX)
shorten.to.string <- function(line, token) { if (FALSE) { ans <- regexpr(strsplit("token", ",", fixed = TRUE)[[1L]][1L], line, fixed = TRUE) if (ans == -1L) line else substr(line, 1L, ans + attr(ans, "match.length") - 1L) } else { substr(line, 1L, 1L) } } write.etags <- function(src, tokens, startlines, lines, nchars, ..., shorten.lines = c("token", "simple", "none")) { shorten.lines <- match.arg(shorten.lines) offsets <- (cumsum(nchars + 1L) - (nchars + 1L))[startlines] lines <- switch(shorten.lines, none = lines, simple = sapply(strsplit(lines, "function", fixed = TRUE), "[", 1), token = mapply(shorten.to.string, lines, tokens)) tag.lines <- paste(sprintf("%s\x7f%s\x01%d,%d", lines, tokens, startlines, as.integer(offsets)), collapse = "\n") tagsize <- nchar(tag.lines, type = "bytes") + 1L cat("\x0c\n", src, ",", tagsize, "\n", tag.lines, "\n", sep = "", ...) } expr2token <- function(x, ok = c("<-", "=", "<<-", "assign", "setGeneric", "setGroupGeneric", "setMethod", "setClass", "setClassUnion"), extended = TRUE) { id <- "" value <- if ((length(x) > 1L) && (length(token <- as.character(x[[2L]])) == 1L) && (length(id <- as.character(x[[1L]])) == 1L) && (id %in% ok)) token else character(0L) if (extended && identical(id, "setMethod")) { sig <- tryCatch(eval(x[[3L]]), error = identity) if (!inherits(sig, "error") && is.character(sig)) value <- paste(c(value, sig), collapse=",") } value } rtags.file <- function(src, ofile = "", append = FALSE, write.fun = write.etags) { elist <- parse(src, srcfile = srcfile(src)) if (length(elist) == 0) return(invisible()) lines <- readLines(src) tokens <- lapply(elist, expr2token) startlines <- sapply(attr(elist, "srcref"), "[", 1L) if (length(tokens) != length(startlines)) stop("length mismatch: bug in code!", domain = NA) keep <- lengths(tokens) == 1L if (!any(keep)) return(invisible()) tokens <- unlist(tokens[keep]) startlines <- startlines[keep] write.fun(src = src, tokens = tokens, startlines = startlines, lines = lines[startlines], nchars = nchar(lines, type = "bytes"), file = ofile, append = append) } rtags <- function(path = ".", pattern = "\\.[RrSs]$", recursive = FALSE, src = list.files(path = path, pattern = pattern, full.names = TRUE, recursive = recursive), keep.re = NULL, ofile = "", append = FALSE, verbose = getOption("verbose")) { if (nzchar(ofile) && !append) { if (!file.create(ofile, showWarnings = FALSE)) stop(gettextf("Could not create file %s, aborting", ofile), domain = NA) } if (!missing(keep.re)) src <- grep(keep.re, src, value = TRUE) for (s in src) { if (verbose) message(gettextf("Processing file %s", s), domain = NA) tryCatch( rtags.file(s, ofile = ofile, append = TRUE), error = function(e) NULL) } invisible() }
print.flexCPH <- function (x, digits = max(4, getOption("digits") - 4), ...) { cat("\nCall:\n", paste(deparse(x$call), sep = "\n", collapse = "\n"), "\n\n", sep = "") print(lapply(x$coefficients, round, digits = digits)) cat("\nlog-Lik:", x$logLik, "\n\n") invisible(x) }
computeCost <- function(X, y, theta) { m <- length(y) J <- 0 dif <- X %*% theta - y J <- (t(dif) %*% dif) / (2 * m) J }
as.character.formula <- function(x, ...) { form <- paste( deparse(x), collapse=" " ) form <- gsub( "\\s+", " ", form, perl=FALSE ) return(form) }
NULL length.blockmatrix <- function (x) { return(length(x$value)) }
NULL setMethod("length", signature=c(x="TreeHarp"), function(x) { return(length(x@adjList)) }) setMethod("show", signature(object = "TreeHarp"), function (object) { cat(object@repr, "\n") return(invisible(NULL)) } ) setMethod("names", signature=c(x="TreeHarp"), function(x) { return(names(x@adjList)) }) setGeneric("get_parent_id", function(x, node_num) standardGeneric("get_parent_id"), signature = "x" ) setMethod("get_parent_id", signature=c(x="TreeHarp"), function(x, node_num) { get_parent_id2(x@adjList, node_num) }) setMethod("get_parent_id", signature=c(x="list"), function(x, node_num) { get_parent_id2(x, node_num) }) setGeneric("get_child_ids", function(x, node_num) standardGeneric("get_child_ids"), signature = "x" ) setMethod("get_child_ids", signature=c(x="TreeHarp"), function(x, node_num) { get_child_ids2(x@adjList, node_num) }) setMethod("get_child_ids", signature=c(x="list"), function(x, node_num) { get_child_ids2(x, node_num) }) setGeneric("get_adj_list", function(x, ...) standardGeneric("get_adj_list"), signature = "x" ) setMethod("get_adj_list", signature=c(x="TreeHarp"), function(x, ...) { return(x@adjList) }) setGeneric("get_node_types", function(x, ...) standardGeneric("get_node_types"), signature = "x" ) setMethod("get_node_types", signature=c(x="TreeHarp"), function(x, ...) { return(x@nodeTypes) }) setMethod("plot", signature=c("TreeHarp"), function(x, y, ...){ ig <- igraph::graph_from_adj_list(get_adj_list(x), mode="all", duplicate=FALSE) ll <- names(x@adjList) igraph::plot.igraph(ig, layout=igraph::layout_as_tree(ig, root=1), vertex.label=ll, ...) })
lmrob <- function(formula, data, subset, weights, na.action, method = 'MM', model = TRUE, x = !control$compute.rd, y = FALSE, singular.ok = TRUE, contrasts = NULL, offset = NULL, control = NULL, init = NULL, ...) { if (miss.ctrl <- missing(control)) control <- if (missing(method)) lmrob.control(...) else lmrob.control(method = method, ...) else if (length(list(...))) warning("arguments .. in ", sub(")$", "", sub("^list\\(", "", deparse(list(...), control = c()))), " are disregarded.\n", " Maybe use lmrob(*, control=lmrob.control(....) with all these.") ret.x <- x ret.y <- y cl <- match.call() mf <- match.call(expand.dots = FALSE) m <- match(c("formula", "data", "subset", "weights", "na.action", "offset"), names(mf), 0) mf <- mf[c(1, m)] mf$drop.unused.levels <- TRUE mf[[1]] <- as.name("model.frame") mf <- eval(mf, parent.frame()) mt <- attr(mf, "terms") y <- model.response(mf, "numeric") w <- as.vector(model.weights(mf)) if(!is.null(w) && !is.numeric(w)) stop("'weights' must be a numeric vector") offset <- as.vector(model.offset(mf)) if(!is.null(offset) && length(offset) != NROW(y)) stop(gettextf("number of offsets is %d, should equal %d (number of observations)", length(offset), NROW(y)), domain = NA) if (!miss.ctrl && !missing(method) && method != control$method) { warning("The 'method' argument is different from 'control$method'\n", "Using the former, method = ", method) control$method <- method } if (is.empty.model(mt)) { x <- NULL singular.fit <- FALSE z <- list(coefficients = if(is.matrix(y)) matrix(NA_real_, 0, ncol(y)) else numeric(), residuals = y, scale = NA, fitted.values = 0 * y, cov = matrix(NA_real_,0,0), weights = w, rank = 0, df.residual = if(!is.null(w)) sum(w != 0) else NROW(y), converged = TRUE, iter = 0) if(!is.null(offset)) { z$fitted.values <- offset z$residuals <- y - offset z$offset <- offset } } else { x <- model.matrix(mt, mf, contrasts) contrasts <- attr(x, "contrasts") assign <- attr(x, "assign") p <- ncol(x) if(!is.null(offset)) y <- y - offset if (!is.null(w)) { ny <- NCOL(y) n <- nrow(x) if (NROW(y) != n | length(w) != n) stop("incompatible dimensions") if (any(w < 0 | is.na(w))) stop("missing or negative weights not allowed") zero.weights <- any(w == 0) if (zero.weights) { save.r <- y save.w <- w save.f <- y ok <- w != 0 nok <- !ok w <- w[ok] x0 <- x[nok, , drop = FALSE] x <- x[ ok, , drop = FALSE] n <- nrow(x) y0 <- if (ny > 1L) y[nok, , drop = FALSE] else y[nok] y <- if (ny > 1L) y[ ok, , drop = FALSE] else y[ok] attr(mf, "zero.weights") <- which(nok) } wts <- sqrt(w) save.y <- y x <- wts * x y <- wts * y } if(getRversion() >= "3.1.0") { z0 <- .lm.fit(x, y, tol = control$solve.tol) piv <- z0$pivot } else { z0 <- lm.fit(x, y, tol = control$solve.tol) piv <- z0$qr$pivot } rankQR <- z0$rank singular.fit <- rankQR < p if (rankQR > 0) { if (singular.fit) { if (!singular.ok) stop("singular fit encountered") pivot <- piv p1 <- pivot[seq_len(rankQR)] p2 <- pivot[(rankQR+1):p] dn <- dimnames(x) x <- x[,p1] attr(x, "assign") <- assign[p1] } if (is.function(control$eps.x)) control$eps.x <- control$eps.x(max(abs(x))) if (!is.null(ini <- init)) { if (is.character(init)) { init <- switch(init, "M-S" = lmrob.M.S(x, y, control, mf=mf), "S" = lmrob.S (x, y, control), stop('init must be "S", "M-S", function or list')) if(ini == "M-S") { ini <- init$control$method } } else if (is.function(init)) { init <- init(x=x, y=y, control=control, mf=mf) } else if (is.list(init)) { if (singular.fit) { init$coef <- na.omit(init$coef) if (length(init$coef) != ncol(x)) stop("Length of initial coefficients vector does not match rank of singular design matrix x") } } else stop("unknown init argument") stopifnot(is.numeric(init$coef), is.numeric(init$scale)) if (control$method == "MM" || substr(control$method, 1, 1) == "S") control$method <- substring(control$method, 2) if (class(init)[1] != "lmrob.S" && control$cov == '.vcov.avar1') control$cov <- ".vcov.w" } z <- lmrob.fit(x, y, control, init=init) if(is.character(ini) && !grepl(paste0("^", ini), control$method)) control$method <- paste0(ini, control$method) if (singular.fit) { coef <- numeric(p) coef[p2] <- NA coef[p1] <- z$coefficients names(coef) <- dn[[2L]] z$coefficients <- coef d.p <- p-rankQR n <- NROW(y) z$qr[c("qr","qraux","pivot")] <- list(matrix(c(z$qr$qr, rep.int(0, d.p*n)), n, p, dimnames = list(dn[[1L]], dn[[2L]][piv])), c(z$qr$qraux, rep.int(0, d.p)), piv) } } else { z <- list(coefficients = if (is.matrix(y)) matrix(NA_real_,p,ncol(y)) else rep.int(NA_real_, p), residuals = y, scale = NA, fitted.values = 0 * y, cov = matrix(NA_real_,0,0), rweights = rep.int(NA_real_, NROW(y)), weights = w, rank = 0, df.residual = NROW(y), converged = TRUE, iter = 0, control=control) if (is.matrix(y)) colnames(z$coefficients) <- colnames(x) else names(z$coefficients) <- colnames(x) if(!is.null(offset)) z$residuals <- y - offset } if (!is.null(w)) { z$residuals <- z$residuals/wts z$fitted.values <- save.y - z$residuals z$weights <- w if (zero.weights) { coef <- z$coefficients coef[is.na(coef)] <- 0 f0 <- x0 %*% coef if (ny > 1) { save.r[ok, ] <- z$residuals save.r[nok, ] <- y0 - f0 save.f[ok, ] <- z$fitted.values save.f[nok, ] <- f0 } else { save.r[ok] <- z$residuals save.r[nok] <- y0 - f0 save.f[ok] <- z$fitted.values save.f[nok] <- f0 } z$residuals <- save.r z$fitted.values <- save.f z$weights <- save.w rw <- z$rweights z$rweights <- rep.int(0, length(save.w)) z$rweights[ok] <- rw } } } if(!is.null(offset)) z$fitted.values <- z$fitted.values + offset z$na.action <- attr(mf, "na.action") z$offset <- offset z$contrasts <- contrasts z$xlevels <- .getXlevels(mt, mf) z$call <- cl z$terms <- mt z$assign <- assign if(control$compute.rd && !is.null(x)) z$MD <- robMD(x, attr(mt, "intercept"), wqr=z$qr) if (model) z$model <- mf if (ret.x) z$x <- if (singular.fit || (!is.null(w) && zero.weights)) model.matrix(mt, mf, contrasts) else x if (ret.y) z$y <- if (!is.null(w)) model.response(mf, "numeric") else y class(z) <- "lmrob" z } if(getRversion() < "3.1.0") globalVariables(".lm.fit") chk.s <- function(...) { if(length(list(...))) warning("arguments ", sub(")$", '', sub("^list\\(", '', deparse(list(...), control=c()))), " are disregarded in\n ", deparse(sys.call(-1), control=c()), call. = FALSE) } robMD <- function(x, intercept, wqr, ...) { if(intercept == 1) x <- x[, -1, drop=FALSE] if(ncol(x) >= 1) { rob <- tryCatch(covMcd(x, ...), warning = function(w) structure("covMcd produced a warning", class="try-error", condition = w), error = function(e) structure("covMcd failed with an error", class="try-error", condition = e)) if (inherits(rob, "try-error")) { warning("Failed to compute robust Mahalanobis distances, reverting to robust leverages.") .lmrob.hat(wqr = wqr) } else sqrt( mahalanobis(x, rob$center, rob$cov) ) } } alias.lmrob <- function(object, ...) { if (is.null(x <- object[["x"]])) x <- model.matrix(object) weights <- weights(object) if (!is.null(weights) && diff(range(weights))) x <- x * sqrt(weights) object$qr <- qr(x) class(object) <- "lm" alias(object) } case.names.lmrob <- function(object, full = FALSE, ...) { w <- weights(object) dn <- names(residuals(object)) if(full || is.null(w)) dn else dn[w!=0] } confint.lmrob <- confint.lm dummy.coef.lmrob <- dummy.coef.lm family.lmrob <- function(object, ...) gaussian() kappa.lmrob <- function(z, ...) kappa.qr(z$qr, ...) qrLmr <- function(x) { if(!is.list(r <- x$qr)) stop("lmrob object does not have a proper 'qr' component. Rank zero?") r } labels.lmrob <- function(object, ...) { tl <- attr(object$terms, "term.labels") asgn <- object$assign[qrLmr(object)$pivot[seq_len(object$rank)]] tl[unique(asgn)] } model.matrix.lmrob <- model.matrix.lm nobs.lmrob <- function(object, ...) if (!is.null(w <- object$weights)) sum(w != 0) else NROW(object$residuals) if(FALSE) predict.lmrob <- function (object, newdata = NULL, scale = NULL, ...) { class(object) <- c(class(object), "lm") object$qr <- qr(sqrt(object$rweights) * object$x) predict.lm(object, newdata = newdata, scale = object$s, ...) } print.summary.lmrob <- function (x, digits = max(3, getOption("digits") - 3), symbolic.cor = x$symbolic.cor, signif.stars = getOption("show.signif.stars"), showAlgo = TRUE, ...) { cat("\nCall:\n", paste(deparse(x$call, width.cutoff=72), sep = "\n", collapse = "\n"), "\n", sep = "") control <- lmrob.control.minimal(x$control) cat(" \\--> method = \"", control$method, '"\n', sep = "") resid <- x$residuals df <- x$df rdf <- df[2L] cat(if (!is.null(x$weights) && diff(range(x$weights))) "Weighted ", "Residuals:\n", sep = "") if (rdf > 5L) { nam <- c("Min", "1Q", "Median", "3Q", "Max") rq <- if (NCOL(resid) > 1) structure(apply(t(resid), 1, quantile), dimnames = list(nam, dimnames(resid)[[2]])) else setNames(quantile(resid), nam) print(rq, digits = digits, ...) } else print(resid, digits = digits, ...) if( length(x$aliased) ) { if( !(x$converged) ) { if (x$scale == 0) { cat("\nExact fit detected\n\nCoefficients:\n") } else { cat("\nAlgorithm did not converge\n") if (control$method == "S") cat("\nCoefficients of the *initial* S-estimator:\n") else cat(sprintf("\nCoefficients of the %s-estimator:\n", control$method)) } printCoefmat(x$coef, digits = digits, signif.stars = signif.stars, ...) } else { if (nsingular <- df[3L] - df[1L]) cat("\nCoefficients: (", nsingular, " not defined because of singularities)\n", sep = "") else cat("\nCoefficients:\n") coefs <- x$coefficients if(!is.null(aliased <- x$aliased) && any(aliased)) { cn <- names(aliased) coefs <- matrix(NA, length(aliased), 4, dimnames=list(cn, colnames(coefs))) coefs[!aliased, ] <- x$coefficients } printCoefmat(coefs, digits = digits, signif.stars = signif.stars, na.print="NA", ...) cat("\nRobust residual standard error:", format(signif(x$scale, digits)),"\n") if(nzchar(mess <- naprint(x$na.action))) cat(" (",mess,")\n", sep = "") if(!is.null(x$r.squared) && x$df[1] != attr(x$terms, "intercept")) { cat("Multiple R-squared: ", formatC(x$r.squared, digits = digits)) cat(",\tAdjusted R-squared: ", formatC(x$adj.r.squared, digits = digits), "\n") } correl <- x$correlation if (!is.null(correl)) { p <- NCOL(correl) if (p > 1) { cat("\nCorrelation of Coefficients:\n") if (is.logical(symbolic.cor) && symbolic.cor) { print(symnum(correl), abbr.colnames = NULL) } else { correl <- format(round(correl, 2), nsmall = 2, digits = digits) correl[!lower.tri(correl)] <- "" print(correl[-1, -p, drop = FALSE], quote = FALSE) } } } cat("Convergence in", x$iter, "IRWLS iterations\n") } cat("\n") if (!is.null(rw <- x$rweights)) { if (any(zero.w <- x$weights == 0)) rw <- rw[!zero.w] eps.outlier <- if (is.function(EO <- control$eps.outlier)) EO(nobs(x)) else EO summarizeRobWeights(rw, digits = digits, eps = eps.outlier, ...) } } else cat("\nNo Coefficients\n") if (showAlgo && !is.null(control)) printControl(control, digits = digits, drop. = "method") invisible(x) } print.lmrob <- function(x, digits = max(3, getOption("digits") - 3), ...) { cat("\nCall:\n", cl <- deparse(x$call, width.cutoff=72), "\n", sep = "") control <- lmrob.control.minimal(x$control) if(!any(grepl("method *= *['\"]", cl))) cat(" \\--> method = \"", control$method, '"\n', sep = "") else cat("\n") if(length((cf <- coef(x)))) { if( x$converged ) cat("Coefficients:\n") else { if (x$scale == 0) { cat("Exact fit detected\n\nCoefficients:\n") } else { cat("Algorithm did not converge\n\n") if (control$method == "S") cat("Coefficients of the *initial* S-estimator:\n") else cat(sprintf("Coefficients of the %s-estimator:\n", control$method)) } } print(format(cf, digits = digits), print.gap = 2, quote = FALSE) } else cat("No coefficients\n") cat("\n") invisible(x) } print.lmrob.S <- function(x, digits = max(3, getOption("digits") - 3), showAlgo = TRUE, ...) { cat("S-estimator lmrob.S():\n") if(length((cf <- coef(x)))) { if (x$converged) cat("Coefficients:\n") else if (x$scale == 0) cat("Exact fit detected\n\nCoefficients:\n") else cat("Algorithm did not converge\n\n") print(format(cf, digits = digits), print.gap = 2, quote = FALSE) } else cat("No coefficients\n") cat("scale = ",format(x$scale, digits=digits), "; ", if(x$converged)"converged" else "did NOT converge", " in ", x$k.iter, " refinement steps\n") if (showAlgo && !is.null(x$control)) printControl(x$control, digits = digits, drop. = "method") invisible(x) } qr.lmrob <- function (x, ...) { if (is.null(r <- x$qr)) stop("lmrob object does not have a proper 'qr' component. Rank must be zero") r } residuals.lmrob <- function(object, ...) residuals.lm(object, ...) residuals.lmrob.S <- function(obj) obj$residuals summary.lmrob <- function(object, correlation = FALSE, symbolic.cor = FALSE, ...) { if (is.null(object$terms)) stop("invalid 'lmrob' object: no terms component") p <- object$rank df <- object$df.residual sigma <- object[["scale"]] aliased <- is.na(coef(object)) cf.nms <- c("Estimate", "Std. Error", "t value", "Pr(>|t|)") if (p > 0) { n <- p + df p1 <- seq_len(p) se <- sqrt(if(length(object$cov) == 1L) object$cov else diag(object$cov)) est <- object$coefficients[object$qr$pivot[p1]] tval <- est/se ans <- object[c("call", "terms", "residuals", "scale", "rweights", "na.action", "converged", "iter", "control")] if (!is.null(ans$weights)) ans$residuals <- ans$residuals * sqrt(object$weights) ans$df <- c(p, df, NCOL(object$qr$qr)) ans$coefficients <- if( ans$converged) cbind(est, se, tval, 2 * pt(abs(tval), df, lower.tail = FALSE)) else cbind(est, if(sigma <= 0) 0 else NA, NA, NA) dimnames(ans$coefficients) <- list(names(est), cf.nms) if (p != attr(ans$terms, "intercept")) { df.int <- if (attr(ans$terms, "intercept")) 1L else 0L resid <- object$residuals pred <- object$fitted.values resp <- if (is.null(object[["y"]])) pred + resid else object$y wgt <- object$rweights ctrl <- object$control c.psi <- ctrl$tuning.psi psi <- ctrl$psi correc <- if (psi == 'ggw') { if (isTRUE(all.equal(c.psi, c(-.5, 1.0, 0.95, NA)))) 1.121708 else if (isTRUE(all.equal(c.psi, c(-.5, 1.5, 0.95, NA)))) 1.163192 else if (isTRUE(all.equal(c.psi, c(-.5, 1.0, 0.85, NA)))) 1.33517 else if (isTRUE(all.equal(c.psi, c(-.5, 1.5, 0.85, NA)))) 1.395828 else lmrob.E(wgt(r), ctrl) / lmrob.E(r*psi(r), ctrl) } else if (any(psi == .Mpsi.R.names) && isTRUE(all.equal(c.psi, .Mpsi.tuning.default(psi)))) { switch(psi, bisquare = 1.207617, welsh = 1.224617, optimal = 1.068939, hampel = 1.166891, lqq = 1.159232, stop('unsupported psi function -- should not happen')) } else lmrob.E(wgt(r), ctrl) / lmrob.E(r*psi(r), ctrl) resp.mean <- if (df.int == 1L) sum(wgt * resp)/sum(wgt) else 0 yMy <- sum(wgt * (resp - resp.mean)^2) rMr <- sum(wgt * resid^2) ans$r.squared <- r2correc <- (yMy - rMr) / (yMy + rMr * (correc - 1)) ans$adj.r.squared <- 1 - (1 - r2correc) * ((n - df.int) / df) } else ans$r.squared <- ans$adj.r.squared <- 0 ans$cov <- object$cov if(length(object$cov) > 1L) dimnames(ans$cov) <- dimnames(ans$coefficients)[c(1,1)] if (correlation) { ans$correlation <- ans$cov / outer(se, se) ans$symbolic.cor <- symbolic.cor } } else { ans <- object ans$df <- c(0L, df, length(aliased)) ans$coefficients <- matrix(ans$coefficients[0L], 0L, 4L, dimnames = list(NULL, cf.nms)) ans$r.squared <- ans$adj.r.squared <- 0 ans$cov <- object$cov } ans$aliased <- aliased ans$sigma <- sigma if (is.function(ans$control$eps.outlier)) ans$control$eps.outlier <- ans$control$eps.outlier(nobs(object)) if (is.function(ans$control$eps.x)) ans$control$eps.x <- if(!is.null(o.x <- object[['x']])) ans$control$eps.x(max(abs(o.x))) structure(ans, class = "summary.lmrob") } variable.names.lmrob <- function(object, full = FALSE, ...) { if(full) dimnames(qrLmr(object)$qr)[[2L]] else if(object$rank) dimnames(qrLmr(object)$qr)[[2L]][seq_len(object$rank)] else character() } vcov.lmrob <- function (object, cov = object$control$cov, complete = TRUE, ...) { if(!is.null(object$cov) && (missing(cov) || identical(cov, object$control$cov))) .vcov.aliased(aliased = is.na(coef(object)), object$cov, complete= if(is.na(complete)) FALSE else complete) else { lf.cov <- if (!is.function(cov)) get(cov, mode = "function") else cov lf.cov(object, complete=complete, ...) } } sigma.lmrob <- function(object, ...) object$scale weights.lmrob <- function(object, type = c("prior", "robustness"), ...) { type <- match.arg(type) res <- if (type == "prior") { if (is.null(object[["weights"]]) && identical(parent.frame(), .GlobalEnv)) warning("No weights defined for this object. Use type=\"robustness\" argument to get robustness weights.") object[["weights"]] } else object[["rweights"]] if (is.null(object$na.action)) res else naresid(object$na.action, res) } printControl <- function(ctrl, digits = getOption("digits"), str.names = "seed", drop. = character(0), header = "Algorithmic parameters:", ...) { PR <- function(LST, ...) if(length(LST)) print(unlist(LST), ...) cat(header,"\n") is.str <- (nc <- names(ctrl)) %in% str.names do. <- !is.str & !(nc %in% drop.) is.ch <- vapply(ctrl, is.character, NA) real.ctrl <- vapply(ctrl, function(x) length(x) > 0 && is.numeric(x) && any(x %% 1 != 0), NA) PR(ctrl[do. & real.ctrl], digits = digits, ...) PR(ctrl[do. & !is.ch & !real.ctrl], ...) PR(ctrl[do. & is.ch], ...) if(any(is.str)) for(n in nc[is.str]) { cat(n,":") str(ctrl[[n]], vec.len = 2) } } summarizeRobWeights <- function(w, digits = getOption("digits"), header = "Robustness weights:", eps = 0.1 / length(w), eps1 = 1e-3, ...) { stopifnot(is.numeric(w)) cat(header,"\n") cat0 <- function(...) cat('', ...) n <- length(w) if(n <= 10) print(w, digits = digits, ...) else { n1 <- sum(w1 <- abs(w - 1) < eps1) n0 <- sum(w0 <- abs(w) < eps) if(any(w0 & w1)) warning("weights should not be both close to 0 and close to 1!\n", "You should use different 'eps' and/or 'eps1'") if(n0 > 0 || n1 > 0) { if(n0 > 0) { formE <- function(e) formatC(e, digits = max(2, digits-3), width=1) i0 <- which(w0) maxw <- max(w[w0]) c3 <- paste0("with |weight| ", if(maxw == 0) "= 0" else paste("<=", formE(maxw)), " ( < ", formE(eps), ");") cat0(if(n0 > 1) { cc <- sprintf("%d observations c(%s)", n0, strwrap(paste(i0, collapse=","))) c2 <- " are outliers" paste0(cc, if(nchar(cc)+ nchar(c2)+ nchar(c3) > getOption("width")) "\n ", c2) } else sprintf("observation %d is an outlier", i0), c3, "\n") } if(n1 > 0) cat0(ngettext(n1, "one weight is", sprintf("%s%d weights are", if(n1 == n)"All " else '', n1)), "~= 1.") n.rem <- n - n0 - n1 if(n.rem <= 0) { if(n1 > 0) cat("\n") return(invisible()) } cat0("The remaining", ngettext(n.rem, "one", sprintf("%d ones", n.rem)), "are") if(is.null(names(w))) names(w) <- as.character(seq(along = w)) w <- w[!w1 & !w0] if(n.rem <= 10) { cat("\n") print(w, digits = digits, ...) return(invisible()) } else cat(" summarized as\n") } print(summary(w, digits = digits), digits = digits, ...) } }
library(recipes) library(caret) library(testthat) context('updating objects') diff_coef <- function(x, y) { x_nm <- names(x$fit$finalModel$coefficients) y_nm <- names(y$fit$finalModel$coefficients) delta <- c(setdiff(x_nm, y_nm), setdiff(y_nm, x_nm)) length(delta) > 0 } set.seed(3545) dat <- SLC14_1(100) y_ind <- which(names(dat) == "y") test_that("train updating", { ctrl <- trainControl(method = "cv") lm_obj_form <- train(y ~ Var01 + Var02, data = dat, method = "lm", trControl = ctrl) lm_obj_form_2 <- update(lm_obj_form, list(intercept = FALSE)) expect_equal(length(lm_obj_form_2$finalModel$coefficients), 2) rec <- recipe(y ~ Var01 + Var02, data = dat) %>% step_mutate(Var01 = Var01/2) lm_obj_rec <- train(rec, data = dat, method = "lm", trControl = ctrl) lm_obj_rec_2 <- update(lm_obj_rec, list(intercept = FALSE)) expect_equal(length(lm_obj_rec_2$finalModel$coefficients), 2) }) test_that("safs updating", { ctrl <- safsControl(functions = caretSA, method = "cv", number = 3) set.seed(3997) sa_xy <- safs(x = dat[, -y_ind], y = dat$y, safsControl = ctrl, iters = 2, differences = FALSE, method = "lm", trControl = trainControl(method = "cv") ) new_iter <- ifelse(sa_xy$optIter == 1, 2, 1) sa_xy_2 <- update(sa_xy, iter = new_iter, x = dat[, -y_ind], y = dat$y) expect_true(diff_coef(sa_xy, sa_xy_2)) expect_error(update(sa_xy, iter = new_iter)) rec <- recipe(y ~ ., data = dat) %>% step_mutate(Var01 = Var01/2) set.seed(3997) sa_rec <- safs(rec, data = dat, safsControl = ctrl, iters = 2, differences = FALSE, method = "lm", trControl = trainControl(method = "cv") ) new_iter <- ifelse(sa_rec$optIter == 1, 2, 1) sa_rec_2 <- update(sa_rec, iter = new_iter) expect_true(diff_coef(sa_rec, sa_rec_2)) sa_rec$recipe$template <- NULL expect_error(update(sa_rec, iter = new_iter)) }) test_that("gafs updating", { ctrl <- gafsControl(functions = caretGA, method = "cv", number = 3) set.seed(3997) ga_xy <- gafs(x = dat[, -y_ind], y = dat$y, gafsControl = ctrl, popSize = 4, iters = 2, differences = FALSE, method = "lm", trControl = trainControl(method = "cv") ) new_iter <- ifelse(ga_xy$optIter == 1, 2, 1) ga_xy_2 <- update(ga_xy, iter = new_iter, x = dat[, -y_ind], y = dat$y) expect_true(diff_coef(ga_xy, ga_xy_2)) expect_error(update(ga_xy, iter = new_iter)) rec <- recipe(y ~ ., data = dat) %>% step_mutate(Var01 = Var01/2) set.seed(3997) ga_rec <- gafs(rec, data = dat, gafsControl = ctrl, popSize = 4, iters = 2, differences = FALSE, method = "lm", trControl = trainControl(method = "cv") ) new_iter <- ifelse(ga_rec$optIter == 1, 2, 1) ga_rec_2 <- update(ga_rec, iter = new_iter) expect_true(diff_coef(ga_rec, ga_rec_2)) ga_rec$recipe$template <- NULL expect_error(update(ga_rec, iter = new_iter)) }) test_that("rfe updating", { ctrl <- rfeControl(functions = caretFuncs, method = "cv", number = 3) set.seed(3997) rfe_xy <- rfe(x = dat[, -y_ind], y = dat$y, rfeControl = ctrl, sizes = 1:5, method = "lm", trControl = trainControl(method = "none") ) rfe_xy_2 <- expect_warning(update(rfe_xy, size = 5, x = dat[, -y_ind], y = dat$y)) expect_equal(length(rfe_xy_2$fit$finalModel$coefficients), 6) expect_error(update(rfe_xy, size = 5)) rec <- recipe(y ~ ., data = dat) %>% step_mutate(Var01 = Var01/2) set.seed(3997) rfe_rec <- rfe(rec, data = dat, rfeControl = ctrl, sizes = 1:5, method = "lm", trControl = trainControl(method = "none") ) expect_warning(rfe_rec_2 <- update(rfe_rec, size = 5)) expect_equal(length(rfe_rec_2$fit$finalModel$coefficients), 6) rfe_rec$recipe$template <- NULL expect_error(update(rfe_rec, size = 5)) })
library(survival) pfit2 <- coxph(Surv(time, status > 0) ~ trt + log(bili) + log(protime) + age + platelet + sex, data = pbc) esurv <- survexp(~ trt, ratetable = pfit2, data = pbc) temp <- pbc temp$sex2 <- factor(as.numeric(pbc$sex), levels=2:0, labels=c("f", "m", "unknown")) esurv2 <- survexp(~ trt, ratetable = pfit2, data = temp, rmap=list(sex=sex2)) all.equal(unclass(esurv)[-1], unclass(esurv2)[-1]) Datedate <- function(x) { offset <- as.numeric(as.Date("1970-01-01") - as.Date("1960-01-01")) y <- as.numeric(x) + offset class(y) <- "date" y } as.data.frame.date <- as.data.frame.vector n <- nrow(lung) tdata <- data.frame(age=lung$age + (1:n)/365.25, sex = c('male', 'female')[lung$sex], ph.ecog = lung$ph.ecog, time = lung$time*3, status = lung$status, entry = as.Date("1940/01/01") + (n:1)*50) tdata$entry2 <- as.POSIXct(tdata$entry) tdata$entry3 <- Datedate(tdata$entry) p1 <- pyears(Surv(time, status) ~ ph.ecog, data=tdata, ratetable=survexp.us, rmap= list(age=age*365.25, sex=sex, year=entry)) p2 <- pyears(Surv(time, status) ~ ph.ecog, data=tdata, ratetable=survexp.us, rmap= list(age=age*365.25, sex=sex, year=entry2)) p3 <- pyears(Surv(time, status) ~ ph.ecog, data=tdata, ratetable=survexp.us, rmap= list(age=age*365.25, sex=sex, year=entry3)) all.equal(p1$expected, p2$expected) all.equal(p1$expected, p3$expected) trate <- survexp.us attr(trate, 'type') <- c(2,1,3) p4 <- pyears(Surv(time, status) ~ ph.ecog, data=tdata, ratetable=trate, rmap= list(age=age*365.25, sex=sex, year=entry)) p5 <- pyears(Surv(time, status) ~ ph.ecog, data=tdata, ratetable=trate, rmap= list(age=age*365.25, sex=sex, year=entry2)) p6 <- pyears(Surv(time, status) ~ ph.ecog, data=tdata, ratetable=trate, rmap= list(age=age*365.25, sex=sex, year=entry3)) all.equal(p4$expected, p5$expected) all.equal(p5$expected, p6$expected)
rescale.parafac2 <- function(x, mode="A", newscale=1, absorb="C", ...){ mode <- mode[1] absorb <- absorb[1] if(mode==absorb) stop("Inputs 'mode' and 'absorb' must be different.") if(is.null(x$D)){ if(!any(mode==c("A","B","C"))) stop("Incorrect input for 'mode'. Must set to 'A', 'B', or 'C' for 3-way Parafac2.") if(!any(absorb==c("A","B","C"))) stop("Incorrect input for 'absorb'. Must set to 'A', 'B', or 'C' for 3-way Parafac2.") } else { if(!any(mode==c("A","B","C","D"))) stop("Incorrect input for 'mode'. Must set to 'A', 'B', 'C', or 'D' for 4-way Parafac2.") if(!any(absorb==c("A","B","C","D"))) stop("Incorrect input for 'absorb'. Must set to 'A', 'B', 'C', or 'D' for 4-way Parafac2.") } nfac <- ncol(x$B) if(length(newscale)!=nfac) newscale <- rep(newscale[1],nfac) if(any(newscale <= 0)) stop("Input 'newscale' must contain positive values.") if(mode=="A"){ Ascale <- sqrt(diag(x$Phi) / mean(sapply(x$A,nrow))) if(any(Ascale == 0)) Ascale[Ascale == 0] <- 1 svec <- newscale/Ascale if(nfac==1L) { Smat <- matrix(svec) } else { Smat <- diag(svec) } for(k in 1:length(x$A)) x$A[[k]] <- x$A[[k]] %*% Smat x$Phi <- Smat %*% x$Phi %*% Smat if(nfac==1L) { Smat <- matrix(1/svec) } else { Smat <- diag(1/svec) } if(absorb=="B") { x$B <- x$B %*% Smat } else if(absorb=="C"){ x$C <- x$C %*% Smat } else { x$D <- x$D %*% Smat } return(x) } else if(mode=="B"){ Bscale <- sqrt(colMeans(x$B^2)) if(any(Bscale == 0)) Bscale[Bscale == 0] <- 1 svec <- newscale/Bscale if(nfac==1L) { Smat <- matrix(svec) } else { Smat <- diag(svec) } x$B <- x$B %*% Smat if(nfac==1L) { Smat <- matrix(1/svec) } else { Smat <- diag(1/svec) } if(absorb=="A") { for(k in 1:length(x$A)) x$A[[k]] <- x$A[[k]] %*% Smat x$Phi <- Smat %*% x$Phi %*% Smat } else if(absorb=="C"){ x$C <- x$C %*% Smat } else { x$D <- x$D %*% Smat } return(x) } else if(mode=="C"){ Cscale <- sqrt(colMeans(x$C^2)) if(any(Cscale == 0)) Cscale[Cscale == 0] <- 1 svec <- newscale/Cscale if(nfac==1L) { Smat <- matrix(svec) } else { Smat <- diag(svec) } x$C <- x$C %*% Smat if(nfac==1L) { Smat <- matrix(1/svec) } else { Smat <- diag(1/svec) } if(absorb=="A") { for(k in 1:length(x$A)) x$A[[k]] <- x$A[[k]] %*% Smat x$Phi <- Smat %*% x$Phi %*% Smat } else if(absorb=="B"){ x$B <- x$B %*% Smat } else { x$D <- x$D %*% Smat } return(x) } else if(mode=="D"){ Dscale <- sqrt(colMeans(x$D^2)) if(any(Dscale == 0)) Dscale[Dscale == 0] <- 1 svec <- newscale/Dscale if(nfac==1L) { Smat <- matrix(svec) } else { Smat <- diag(svec) } x$D <- x$D %*% Smat if(nfac==1L) { Smat <- matrix(1/svec) } else { Smat <- diag(1/svec) } if(absorb=="A") { for(k in 1:length(x$A)) x$A[[k]] <- x$A[[k]] %*% Smat x$Phi <- Smat %*% x$Phi %*% Smat } else if(absorb=="B"){ x$B <- x$B %*% Smat } else { x$C <- x$C %*% Smat } return(x) } }
test.naOmitMatrix = function() { x = as.timeSeries(data(LPP2005REC))[1:20, 1:4] colnames(x) = abbreviate(colnames(x), 6) x[1, 1] = NA x[3:4, 2] = NA x[18:20, 4] = NA show(x) timeSeries:::.naOmitMatrix(as.matrix(x)) timeSeries:::.naOmitMatrix(as.matrix(x), "s") timeSeries:::.naOmitMatrix(as.matrix(x), "z") timeSeries:::.naOmitMatrix(as.matrix(x), "ir") timeSeries:::.naOmitMatrix(as.matrix(x), "iz") timeSeries:::.naOmitMatrix(as.matrix(x), "ie") return() } test.na.omit = function() { x = as.timeSeries(data(LPP2005REC))[1:20, 1:4] colnames(x) = abbreviate(colnames(x), 6) x[1, 1] = NA x[3:4, 2] = NA x[18:20, 4] = NA show(x) na.omit(x) na.omit(x, "s") na.omit(x, "z") na.omit(x, "ir") na.omit(x, "iz") na.omit(x, "ie") return() }
knitr::opts_chunk$set( collapse = TRUE, comment = " ) library(goodpractice) check_simple_tf <- make_check( description = "TRUE and FALSE is used, not T and F", gp = "avoid 'T' and 'F', use 'TRUE' and 'FALSE' instead.", check = function(state) { length(tools::checkTnF(dir = state$path)) == 0 } ) pkg_path <- system.file("bad1", package = "goodpractice") gp(pkg_path, checks = c("simple_tf", "truefalse_not_tf"), extra_checks = list(simple_tf = check_simple_tf)) desc_fun <- function(path, quiet) { desc::description$new(path) } prep_desc <- make_prep(name = "desc", func = desc_fun) check_url <- make_check( description = "URL field in DESCRIPTION", preps = "desc", gp = "have a URL field in DESCRIPTION", check = function(state) state$desc$has_fields("URL") ) check_bugreports <- make_check( description = "BugReports in DESCRIPTION", preps = "desc", gp = "add a BugReports field to DESCRIPTION", check = function(state) state$desc$has_fields('BugReports') ) gp(pkg_path, checks = c("url", "bugreports"), extra_preps = list("desc" = prep_desc), extra_checks = list("url" = check_url, "bugreports" = check_bugreports))
R_rc_double_index <- function(w, Sigma, b = NA, r = w*(Sigma %*% w)) { N <- length(w) return(2*(N*sum(r^2) - sum(r)^2)) } R_grad_rc_double_index <- function(w, Sigma, b = NA, Sigma_w = Sigma %*% w, r = w*Sigma_w) { N <- length(w) v <- 4*(N*r - sum(r)) return(as.vector(Sigma %*% (w*v) + Sigma_w*v)) } g_rc_double_index <- function(w, Sigma, b = NA, r = w*(Sigma %*% w)) { N <- length(w) return(rep(r, times = N) - rep(r, each = N)) } A_rc_double_index <- function(w, Sigma, b = NA, Sigma_w = Sigma %*% w) { N <- length(w) Sigma_w <- as.vector(Sigma_w) Ut <- diag(Sigma_w) + Sigma*w return(matrix(rep(t(Ut), N), ncol = N, byrow = TRUE) - matrix(rep(Ut, each = N), ncol = N)) } R_rc_over_b_double_index <- function(w, Sigma, b, r = w*(Sigma %*% w)) { N <- length(w) rb <- r/b return(2*(N*sum(rb^2) - sum(rb)^2)) } R_grad_rc_over_b_double_index <- function(w, Sigma, b, Sigma_w = Sigma %*% w, r = w*Sigma_w) { N <- length(w) rb <- r/b v <- 4*(N*rb - sum(rb))/b return(as.vector(Sigma %*% (w*v) + Sigma_w*v)) } g_rc_over_b_double_index <- function(w, Sigma, b, r = w*(Sigma %*% w)) { N <- length(w) rb <- r/b return(rep(rb, times = N) - rep(rb, each = N)) } A_rc_over_b_double_index <- function(w, Sigma, b, Sigma_w = Sigma %*% w) { N <- length(w) Sigma_w <- as.vector(Sigma_w) Ut <- diag(Sigma_w) + Sigma*w Utb <- Ut / b return(matrix(rep(t(Utb), N), ncol = N, byrow = TRUE) - matrix(rep(Utb, each = N), ncol = N)) } g_rc_over_var_vs_b <- function(w, Sigma, b, r = w*(Sigma %*% w)) { return(as.vector(r/sum(r) - b)) } R_rc_over_var_vs_b <- function(w, Sigma, b, r = w*(Sigma %*% w)) { return(sum((g_rc_over_var_vs_b(w, Sigma, b, r = r))^2)) } R_grad_rc_over_var_vs_b <- function(w, Sigma, b, Sigma_w = Sigma %*% w, r = w*Sigma_w) { sum_r <- sum(r) r_sumr_b <- r/sum_r - b v <- (2/sum_r)*(r_sumr_b - sum(r_sumr_b*r)/sum_r) return(as.vector(Sigma %*% (w*v) + Sigma_w*v)) } A_rc_over_var_vs_b <- function(w, Sigma, b = NA, Sigma_w = Sigma %*% w, r = w*Sigma_w) { sum_r <- sum(r) Sigma_w <- as.vector(Sigma_w) r <- as.vector(r) Ut <- diag(Sigma_w) + Sigma*w return(Ut/sum_r - 2/(sum_r^2) * r %o% Sigma_w) } g_rc_over_var <- function(w, Sigma, b = NA, r = w*(Sigma %*% w)) { return(as.vector(r/sum(r))) } R_rc_over_var <- function(w, Sigma, b = NA, r = w*(Sigma %*% w)) { return(sum((g_rc_over_var(w, Sigma, r = r))^2)) } R_grad_rc_over_var <- function(w, Sigma, b, Sigma_w = Sigma %*% w, r = w*Sigma_w) { sum_r <- sum(r) r_sumr <- r/sum_r v <- (2/sum_r)*(r_sumr - sum(r_sumr^2)) return(as.vector(Sigma %*% (w*v) + Sigma_w*v)) } A_rc_over_var <- A_rc_over_var_vs_b g_rc_over_sd_vs_b_times_sd <- function(w, Sigma, b, r = w*(Sigma %*% w)) { sqrt_sum_r <- sqrt(sum(r)) return(r/sqrt_sum_r - b*sqrt_sum_r) } R_rc_over_sd_vs_b_times_sd <- function(w, Sigma, b, r = w*(Sigma %*% w)) { return(sum((g_rc_over_sd_vs_b_times_sd(w, Sigma, b, r = r))^2)) } R_grad_rc_over_sd_vs_b_times_sd <- function(w, Sigma, b, Sigma_w = Sigma %*% w, r = w*Sigma_w) { sum_r <- sum(r) r_sumr_b <- r/sum_r - b v <- 2*r_sumr_b - sum(r_sumr_b^2) return(as.vector(Sigma %*% (w*v) + Sigma_w*v)) } A_rc_over_sd_vs_b_times_sd <- function(w, Sigma, b, Sigma_w = Sigma %*% w, r = w*Sigma_w) { sum_r <- sum(r) Sigma_w <- as.vector(Sigma_w) r <- as.vector(r) Ut <- diag(Sigma_w) + Sigma * w return((Ut - (r/sum_r + b) %o% Sigma_w) / sqrt(sum_r)) } g_rc_vs_b_times_var <- function(w, Sigma, b, r = w*(Sigma %*% w)) { return(as.vector(r - b*sum(r))) } R_rc_vs_b_times_var <- function(w, Sigma, b, r = w*(Sigma %*% w)) { return(sum((g_rc_vs_b_times_var(w, Sigma, b, r = r))^2)) } R_grad_rc_vs_b_times_var <- function(w, Sigma, b, Sigma_w = Sigma %*% w, r = w*Sigma_w) { sum_r <- sum(r) v <- 2*(r - b*sum_r - sum(b*r) + sum(b^2)*sum_r) return(as.vector(Sigma %*% (w*v) + Sigma_w*v)) } A_rc_vs_b_times_var <- function(w, Sigma, b, Sigma_w = Sigma %*% w, r = w*Sigma_w) { Sigma_w <- as.vector(Sigma_w) Ut <- diag(Sigma_w) + Sigma * w return(Ut - 2 * b %o% Sigma_w) } R_rc_vs_theta <- function(wtheta, Sigma, b = NA, r = NA) { return(sum(g_rc_vs_theta(wtheta, Sigma)^2)) } R_grad_rc_vs_theta <- function(wtheta, Sigma, b = NA) { N <- length(wtheta)-1 w <- wtheta[1:N] theta <- wtheta[N+1] Sigma_w <- as.vector(Sigma %*% w) r <- as.vector(w*Sigma_w) v <- 2*(r - theta) return(c(as.vector(Sigma %*% (w*v) + Sigma_w*v), -sum(v))) } g_rc_vs_theta <- function(wtheta, Sigma, b = NA, r = NA) { N <- length(wtheta)-1 theta <- wtheta[N+1] w <- wtheta[1:N] r <- as.vector(w*(Sigma %*% w)) return(as.vector(r - theta)) } A_rc_vs_theta <- function(wtheta, Sigma, b = NA, Sigma_w = NA) { N <- length(wtheta)-1 w <- wtheta[1:N] Sigma_w <- as.vector(Sigma %*% w) Ut <- diag(Sigma_w) + Sigma * w return(cbind(Ut, -1)) } R_rc_over_b_vs_theta <- function(wtheta, Sigma, b, r = NA) { return(sum(g_rc_over_b_vs_theta(wtheta, Sigma, b)^2)) } R_grad_rc_over_b_vs_theta <- function(wtheta, Sigma, b) { N <- length(wtheta)-1 w <- wtheta[1:N] theta <- wtheta[N+1] Sigma_w <- as.vector(Sigma %*% w) r <- as.vector(w*Sigma_w) v <- 2*(r/b - theta) vb <- v/b return(c(as.vector(Sigma %*% (w*vb) + Sigma_w*vb), -sum(v))) } g_rc_over_b_vs_theta <- function(wtheta, Sigma, b, r = NA) { N <- length(wtheta)-1 theta <- wtheta[N+1] w <- wtheta[1:N] r <- as.vector(w*(Sigma %*% w)) return(as.vector(r/b - theta)) } A_rc_over_b_vs_theta <- function(wtheta, Sigma, b, Sigma_w = NA) { N <- length(wtheta)-1 w <- wtheta[1:N] Sigma_w <- as.vector(Sigma %*% w) Ut <- diag(Sigma_w) + Sigma * w return(cbind(Ut/b, -1)) }
context("Testing get_entity()") description <- paste0("test_get_entity_", openssl::sha1(x = as.character(Sys.time()))) endpoint <- Sys.getenv("FDP_endpoint") entity_url <- post_data("object", list(description = description), endpoint = endpoint) test_that("entity returns as a named list", { expect_silent(get_entity(entity_url)) expect_true(is.list(get_entity(entity_url))) expect_true(all(c("url", "last_updated") %in% names(get_entity(entity_url)))) }) test_that("invalid table produces and error", { expect_error(get_entity("unknown", entity_id)) }) test_that("invalid entity_id produces and error", { expect_error(get_entity("object", "NotANumber")) expect_error(get_entity("object", list(something = "something"))) expect_error(get_entity("object", NaN)) expect_error(get_entity("object", Inf)) expect_error(get_entity("object", -Inf)) })
knitr::opts_chunk$set( collapse = TRUE, comment = " ) importedExample <- preregr::import_from_html("https://r-packages.gitlab.io/preregr/articles/specifying_prereg_content.html"); importedExample; lightenColor <- function(x, amount = .4) { x <- 255 - col2rgb(x); x <- amount * x; x <- 255 - x; x <- rgb(t(x), maxColorValue=255); return(x); } Okabe_Ito <- c(" " " orange <- Okabe_Ito[1]; lightBlue <- Okabe_Ito[2]; green <- Okabe_Ito[3] yellow <- Okabe_Ito[4] darkBlue <- Okabe_Ito[5]; red <- Okabe_Ito[6]; pink <- Okabe_Ito[7]; orange_l <- lightenColor(orange); lightBlue_l <- lightenColor(lightBlue); green_l <- lightenColor(green); yellow_l <- lightenColor(yellow); darkBlue_l <- lightenColor(darkBlue); red_l <- lightenColor(red); pink_l <- lightenColor(pink); orangeBg <- lightenColor(orange, amount=.05); greenBg <- lightenColor(green, amount=.05); oldKableViewOption <- getOption("kableExtra_view_html", NULL); options(kableExtra_view_html = FALSE); oldSilentOption <- preregr::opts$get("silent"); preregr::opts$set(silent = TRUE); knitr::opts_chunk$set(echo = FALSE, comment=""); if (!exists('headingLevel') || !is.numeric(headingLevel) || (length(headingLevel) != 1)) { headingLevel <- 0; } if (is.null(section)) { sectionsToShow <- x$form$sections$section_id; } else { sectionsToShow <- intersect( x$form$sections$section_id, section ); } preregr::heading( x$form$metadata[x$form$metadata$field == "title", "content"], idSlug("preregr-prereg-spec"), headingLevel=headingLevel ); for (section in sectionsToShow) { preregr::heading( "Section: ", x$form$sections[ x$form$sections$section_id==section, "section_label" ], idSlug("preregr-prereg-spec"), headingLevel=headingLevel + 1 ); item_ids <- x$form$items$item_id[x$form$items$section_id == section]; item_labels <- x$form$items$item_label[x$form$items$section_id == section]; names(item_labels) <- item_ids; for (currentItemId in item_ids) { cat0("<div class=\"preregr preregr-item-spec "); if (x$specs[[currentItemId]] == x$config$initialText) { cat0("preregr-unspecified\">\n"); } else { cat0("preregr-specified\">\n"); } cat0("<div class=\"preregr-item-heading\">\n"); cat0("<div class=\"preregr-item-label\">", item_labels[currentItemId], "</div>\n"); cat0("<div class=\"preregr-item-id\">", currentItemId, "</div>\n"); cat0("</div>\n"); cat0("<div class=\"preregr-item-spec-text\">", ifelse(!is.null(x$specs[[currentItemId]]$text) && !is.na(x$specs[[currentItemId]]$text) && nchar(x$specs[[currentItemId]]$text) > 0, x$specs[[currentItemId]]$text, "&nbsp;"), "</div>\n"); cat0("</div>\n"); } } preregr::opts$set(silent = oldSilentOption); if (!is.null(oldKableViewOption)) { options(kableExtra_view_html = oldKableViewOption); } preregrJSON <- preregr::prereg_spec_to_json(x); preregrJSON <- gsub("'", "& preregrJSON ); slug <- paste0("preregr-data-", preregr::randomSlug()); preregr::prereg_knit_item_content( importedExample, section="metadata" ); freshPrereg <- preregr::prereg_initialize( importedExample ); freshPrereg;
SISDemogStoch <- function(pars, init, end.time) { init2 <- NULL init2 <- init equations <- function(pars, init, time.step) { with(as.list(pars), { rate1 <- beta * (N - init) * init / N rate2 <- gamma * init r1 <- runif(1) r2 <- runif(1) step <- -log(r2) / (rate1 + rate2) if (r1 < (rate1 / (rate1 + rate2))) { init <- init + 1 } else { init <- init - 1 } return(c(step, init)) }) } lop <- 1 output <- time.step <- 0 output.tmp <- c(0, 0) while (time.step[lop] < end.time & init > 0) { output.tmp <- equations(pars, init, output.tmp[1]) lop <- lop + 1 time.step <- c(time.step, (time.step[lop - 1] + output.tmp[1])) output <- c(output, init) lop <- lop + 1 time.step <- c(time.step, (time.step[lop - 1])) output <- c(output, output.tmp[2]) init <- output.tmp[2] } return(list(pars = pars, init = init2, time = end.time, results = data.frame(time = time.step, Y = output))) }
PS3_RNA<- function(seqs,binaryType="numBin",label=c(),outFormat="mat",outputFileDist="") { if(length(seqs)==1&&file.exists(seqs)){ seqs<-fa.read(seqs,alphabet="rna") seqs_Lab<-alphabetCheck(seqs,alphabet = "rna",label) seqs<-seqs_Lab[[1]] label<-seqs_Lab[[2]] } else if(is.vector(seqs)){ seqs<-sapply(seqs,toupper) seqs_Lab<-alphabetCheck(seqs,alphabet = "rna",label) seqs<-seqs_Lab[[1]] label<-seqs_Lab[[2]] } else { stop("ERROR: Input sequence is not in the correct format. It should be a FASTA file or a string vector.") } lenSeqs<-sapply(seqs,nchar) numSeqs=length(seqs) dict=1:64 names(dict)=nameKmer(k=3,type="rna") nuc<-names(dict) if(outFormat=="mat"){ if(length(unique(lenSeqs))>1){ stop("ERROR: All sequences should have the same length in 'mat' mode. For sequences with different lengths, please use 'txt' for outFormat parameter") } lenSeq<-lenSeqs[1] if(binaryType=="strBin"){ binary<-rep(strrep(0,64),64) names(binary)=names(dict) for(i in 1:length(dict)) { pos<-dict[i] substr(binary[i],pos,pos)<-"1" } featureMatrix<-matrix("",nrow = numSeqs, ncol = (lenSeq-2)) for(n in 1:numSeqs){ seq<-seqs[n] seqChars<-unlist(strsplit(seq,split = "")) temp<-seqChars[1:(lenSeq-2)] temp2<-seqChars[2:(lenSeq-1)] temp3<-seqChars[3:lenSeq] Trimer<-paste(temp,temp2,temp3,sep = "") vect<-unlist(binary[Trimer]) featureMatrix[n,]<-vect } colnames(featureMatrix)<-paste("pos",1:(lenSeq-2),sep = "") } else if(binaryType=="logicBin"){ featureMatrix<-matrix(FALSE,nrow = numSeqs, ncol = ((lenSeq-2)*64)) rng<-(0:(lenSeq-3))*64 for(n in 1:numSeqs){ seq<-seqs[n] seqChars<-unlist(strsplit(seq,split = "")) temp<-seqChars[1:(lenSeq-2)] temp2<-seqChars[2:(lenSeq-1)] temp3<-seqChars[3:lenSeq] Trimer<-paste(temp,temp2,temp3,sep = "") pos1<-as.numeric(dict[Trimer]) pos1<-rng+pos1 featureMatrix[n,pos1]<-TRUE } colnames(featureMatrix)<-paste("pos:",rep(1:(lenSeq-2),each=64),"-",rep(nuc,(lenSeq-2))) } else if(binaryType=="numBin"){ featureMatrix<-matrix(0,nrow = numSeqs, ncol = ((lenSeq-2)*64)) rng<-(0:(lenSeq-3))*64 for(n in 1:numSeqs){ seq<-seqs[n] seqChars<-unlist(strsplit(seq,split = "")) temp<-seqChars[1:(lenSeq-2)] temp2<-seqChars[2:(lenSeq-1)] temp3<-seqChars[3:lenSeq] Trimer<-paste(temp,temp2,temp3,sep = "") pos1<-as.numeric(dict[Trimer]) pos1<-rng+pos1 featureMatrix[n,pos1]<-1 } colnames(featureMatrix)<-paste("pos:",rep(1:(lenSeq-2),each=64),"-",rep(nuc,(lenSeq-2))) } else{ stop("ERROR! Choose one of 'strBin', 'logicBin', or 'numBin' for binaryFormat") } if(length(label)==numSeqs){ featureMatrix<-as.data.frame(featureMatrix) featureMatrix<-cbind(featureMatrix,label) } row.names(featureMatrix)<-names(seqs) return(featureMatrix) } else if(outFormat=="txt"){ vect<-vector() nameSeq<-names(seqs) binary<-rep(strrep(0,64),64) names(binary)=nuc for(i in 1:length(dict)) { pos<-dict[i] substr(binary[i],pos,pos)<-"1" } for(n in 1:numSeqs){ seq<-seqs[n] seqChars<-unlist(strsplit(seq,split = "")) temp<-seqChars[1:(lenSeq-2)] temp2<-seqChars[2:(lenSeq-1)] temp3<-seqChars[3:lenSeq] Trimer<-paste(temp,temp2,temp3,sep = "") temp<-c(nameSeq[n],binary[Trimer]) temp<-paste(temp,collapse = "\t") write(temp,outputFileDist,append = TRUE) } } else{ stop("ERROR: outFormat should be 'mat' or 'txt' ") } }
knitr::opts_chunk$set( collapse = TRUE ) library(easylabel) knitr::include_graphics("scatter1.png") knitr::include_graphics("plotly_output.png") knitr::include_graphics("scatter3.png") knitr::include_graphics("bubble.png") knitr::include_graphics("plot1.png") head(volc1) head(volc2) knitr::include_graphics("MAplot1.png") knitr::include_graphics("table1.png") knitr::include_graphics("plot7.png") knitr::include_graphics("plot3.png") knitr::include_graphics("plot4.png") knitr::include_graphics("plot5.png") knitr::include_graphics("MAplot2.png") knitr::include_graphics(c("labdir_horiz.png", "labdir_vert.png")) knitr::include_graphics("rect_red_outline.png") knitr::include_graphics("rect_invert.png") knitr::include_graphics("match1.png") knitr::include_graphics("match2.png") knitr::include_graphics("manhattan.png") knitr::include_graphics("locus.png")
tTestN <- function (delta.over.sigma, alpha = 0.05, power = 0.95, sample.type = ifelse(!is.null(n2), "two.sample", "one.sample"), alternative = "two.sided", approx = FALSE, n2 = NULL, round.up = TRUE, n.max = 5000, tol = 1e-07, maxiter = 1000) { sample.type <- match.arg(sample.type, c("one.sample", "two.sample")) alternative <- match.arg(alternative, c("two.sided", "less", "greater")) if (!is.vector(delta.over.sigma, mode = "numeric") || !is.vector(alpha, mode = "numeric") || !is.vector(power, mode = "numeric")) stop("'delta.over.sigma', 'alpha', and 'power' must be numeric vectors.") if (!all(is.finite(delta.over.sigma)) || !all(is.finite(alpha)) || !all(is.finite(power))) stop(paste("Missing (NA), Infinite (Inf, -Inf), and", "Undefined (Nan) values are not allowed in", "'delta.over.sigma', 'alpha', or 'power'")) if (any(abs(delta.over.sigma) <= 0)) stop("All values of 'delta.over.sigma' must be non-zero") if (any(alpha <= 0) || any(alpha >= 1)) stop("All values of 'alpha' must be greater than 0 and less than 1") if (any(power <= alpha) || any(power >= 1)) stop(paste("All values of 'power' must be greater than or equal to", "the corresponding elements of 'alpha' and less than 1")) if (alternative == "greater" && any(delta.over.sigma <= 0)) stop("When alternative='greater', all values of 'delta.over.sigma' must be positive.") if (alternative == "less" && any(delta.over.sigma >= 0)) stop("When alternative='less', all values of 'delta.over.sigma' must be negative.") if (!is.vector(n.max, mode = "numeric") || length(n.max) != 1 || !is.finite(n.max) || n.max != trunc(n.max) || n.max < 2) stop("'n.max' must be a positive integer greater than 1") if (!is.vector(maxiter, mode = "numeric") || length(maxiter) != 1 || !is.finite(maxiter) || maxiter != trunc(maxiter) || maxiter < 2) stop("'maxiter' must be a positive integer greater than 1") if (n2.constrained <- sample.type == "two.sample" && !is.null(n2)) { if (!is.vector(n2, mode = "numeric")) stop("'n2' must be a numeric vector") if (!all(is.finite(n2))) stop(paste("Missing (NA), Infinite (Inf, -Inf), and", "Undefined (Nan) values are not allowed in 'n2'")) if (any(n2 != trunc(n2)) || any(n2 < 2)) stop("All values of 'n2' must be positive integers larger than 1") arg.mat <- cbind.no.warn(power = as.vector(power), delta.over.sigma = as.vector(delta.over.sigma), alpha = as.vector(alpha), n2 = as.vector(n2)) N <- nrow(arg.mat) n.vec <- numeric(N) for (i in c("power", "delta.over.sigma", "alpha", "n2")) assign(i, arg.mat[, i]) } else { arg.mat <- cbind.no.warn(power = as.vector(power), delta.over.sigma = as.vector(delta.over.sigma), alpha = as.vector(alpha)) N <- nrow(arg.mat) n.vec <- numeric(N) for (i in c("power", "delta.over.sigma", "alpha")) assign(i, arg.mat[, i]) } type.fac <- ifelse(sample.type == "two.sample", 2, 1) alt.fac <- ifelse(alternative == "two.sided", 2, 1) sod2 <- 1/delta.over.sigma^2 fcn.for.root <- function(n, power, delta.over.sigma, alpha, sample.type, alternative, approx) { power - tTestPower(n.or.n1 = n, delta.over.sigma = delta.over.sigma, alpha = alpha, sample.type = sample.type, alternative = alternative, approx = approx) } power.2 <- tTestPower(n.or.n1 = 2, delta.over.sigma = delta.over.sigma, alpha = alpha, sample.type = sample.type, alternative = alternative, approx = approx) power.n.max <- tTestPower(n.or.n1 = n.max, delta.over.sigma = delta.over.sigma, alpha = alpha, sample.type = sample.type, alternative = alternative, approx = approx) for (i in 1:N) { power.i <- power[i] power.2.i <- power.2[i] if (power.2.i >= power.i) n.vec[i] <- 2 else { power.n.max.i <- power.n.max[i] if (power.n.max.i < power.i) { n.vec[i] <- NA warning(paste("Error in search algorithm for element ", i, ". Try increasing the argument 'n.max'", sep = "")) } else { delta.over.sigma.i <- delta.over.sigma[i] alpha.i <- alpha[i] n.vec[i] <- uniroot(fcn.for.root, lower = 2, upper = n.max, f.lower = power.i - power.2.i, f.upper = power.i - power.n.max.i, power = power.i, delta.over.sigma = delta.over.sigma.i, alpha = alpha.i, sample.type = sample.type, alternative = alternative, approx = approx, tol = tol, maxiter = maxiter)$root } } } if (n2.constrained) { n1 <- (n.vec * n2)/(2 * n2 - n.vec) if (any(index <- !is.finite(n1) | n1 < 0)) { n1[index] <- NA warning(paste("One or more constrained values of 'n2' is(are)", "too small given the associated values of", "'power', 'delta.over.sigma', and 'alpha'")) } names(n1) <- names(n2) <- NULL if (round.up) n1 <- ceiling(n1) ret.val <- list(n1 = n1, n2 = n2) } else { if (round.up) n.vec <- ceiling(n.vec) ret.val <- n.vec } ret.val }
ungroup_data <- function(X,effX){ effX = as.matrix(effX) g = ncol(effX) bloc = matrix(0,nrow=1,ncol=g) i = 1 ma = 0 s = ncol(X) while (i <= nrow(X)){ bloc = abs(effX[i,]) if ((i < nrow(X))&&(sum(X[i+1,]==X[i,])==s)){ bloc = bloc + abs(effX[i+1,]) i = i + 1 } ma = ma + max(bloc) i = i + 1 } effY = matrix(nrow=ma,ncol=g) Y = matrix(0,nrow=ma,ncol=ncol(X)) comp_init = 1 comp_fin = 1 i = 1 while (i <= nrow(X)){ i0 = i for (gr in 1:g){ comp = comp_init i = i0 e = effX[i,gr] for (j in 1:abs(e)){ Y[comp,] = X[i,] effY[comp,gr] = sign(e) comp=comp+1 } if ((i < nrow(X))&&(sum(X[i+1,]==X[i,])==s)){ i = i0 + 1 e = effX[i,gr] for (j in 1:abs(e)){ Y[comp,] = X[i,] effY[comp,gr] = sign(e) comp = comp + 1 } } comp_fin = max(comp_fin,comp) } comp_init = comp_fin i = i + 1 } return(cbind(Y,effY)) }
matchEnsembleMembers.ensembleMOSnormal <- function(fit, ensembleData) { if (!is.null(dim(fit$B))) { fitMems <- dimnames(fit$B)[[1]] } else { fitMems <- names(fit$B) } ensMems <- ensembleMemberLabels(ensembleData) if (!is.null(fitMems) && !is.null(ensMems) && length(fitMems) > length(ensMems)) stop("model fit has more ensemble members than ensemble data") WARN <- rep(FALSE,3) WARN[1] <- is.null(fitMems) && !is.null(ensMems) WARN[2] <- !is.null(fitMems) && is.null(ensMems) WARN[3] <- is.null(fitMems) && is.null(ensMems) if (any(WARN) && length(fitMems) != length(ensMems)) stop("model fit and ensemble data differ in ensemble size") if (any(WARN)) warning("cannot check correspondence between model fit and ensemble data members") M <- match(fitMems, ensMems, nomatch = 0) if (any(!M)) stop("ensembleData is missing a member used in fit") M }
CombineCaseControlC <- function(cases, controls) { cases = sort(cases) controls = sort(controls) combCC = .Call(C_CombineSortedVectorC, as.numeric(cases), as.numeric(controls)) combL = .Call(C_FindUniqueInSortedArrayC, as.numeric(combCC)) combZX = .Call(C_CombineToUniqueValueC, as.numeric(cases), as.numeric(controls), as.numeric(combL)) combZ = as.numeric(combZX[,1]) combX = as.numeric(combZX[,2]) return(list(combX=combX, combZ=combZ, combL=combL)) }
genmf <- function(mf.type, mf.params) { FUN <- match.fun(mf.type) FUN(mf.params) } evalmftype <- function(x, mf.type, mf.params) { MF <- genmf(mf.type, mf.params) sapply(c(MF), function(F) F(x)) } evalmf <- function(...) { params <- list(...) params.len <- length(params) x <- params[[1]] if (params.len == 3) { MF <- genmf(mf.type = params[[2]], mf.params = params[[3]]) } else if (params.len == 2) { MF <- params[[2]] } else if (params.len == 6 || params.len == 7) { return(evalmf.ns(...)) } else { stop("incorrect parameters") } sapply(c(MF), function(F) F(x)) } evalmf.ns <- function(...) { params <- list(...) params.len <- length(params) x <- params[[1]] if (params.len == 7) { MF <- genmf(mf.type = params[[2]], mf.params = params[[3]]) } else if (params.len == 6) { MF <- params[[2]] } else { stop("incorrect number of parameters") } idx <- params.len - 3 fuzzification.method <- paste0(params[[idx]], '.fuzzification') fuzzification.params <- params[[idx + 1]] X <- sapply(x, x.fuzzification, f = fuzzification.method, m = fuzzification.params) firing.method <- params[[idx + 2]] x.range <- params[[idx + 3]] tmp <- unlist(strsplit(firing.method, "\\.")) if (length(tmp) == 3 && tmp[1] == 'tnorm' && tmp[3] == 'max') { tnorm.operator <- tmp[2] result <- sapply(X, fuzzy.firing, operator = tnorm.operator, ante.mf = MF, lower = x.range[1], upper = x.range[2]) } else if (tmp[1] == 'tnorm' && tmp[3] == 'defuzz') { tnorm.operator <- tmp[2] defuzz.type <- tmp[4] result <- sapply(X, fuzzy.firing.defuzz, operator = tnorm.operator, ante.mf = MF, lower = x.range[1], upper = x.range[2], defuzz.type) } else if (tmp[1] == 'similarity') { similarity.type <- tmp[2] fuzzy.firing.fun <- match.fun(paste0('fuzzy.firing.similarity.', similarity.type)) result <- sapply(X, fuzzy.firing.fun, ante.mf = MF, lower = x.range[1], upper = x.range[2]) } else { stop(paste0("firing.method '", firing.method, "' is not supported")) } if (length(result) > 1) { result <- as.matrix(result) } result } gbellmf <- function(mf.params) { if (length(mf.params) != 3 && length(mf.params) != 4) { stop("improper parameters for generalised bell membership function") } a <- mf.params[1] b <- mf.params[2] c <- mf.params[3] if (length(mf.params) == 4) { h <- mf.params[4] } else { h <- 1 } gbellmf <- function(x) { h / (1 + (((x - c) / a)^2)^b) } } gbell.fuzzification <- function(x, mf.params) { if (length(mf.params) != 2 && length(mf.params) != 3) { stop("improper parameters for gbellmf fuzzification") } mf.params <- append(mf.params, x, 2) genmf('gbellmf', mf.params) } it2gbellmf <- function(mf.params) { if (length(mf.params) != 4 && length(mf.params) != 6) { stop("improper parameters for generalised bell membership function") } a.lower <- mf.params[1] a.upper <- mf.params[2] b <- mf.params[3] c <- mf.params[4] if (length(mf.params) == 6) { h.lower <- mf.params[5] h.upper <- mf.params[6] } else { h.lower <- 1 h.upper <- 1 } it2gbellmf.lower <- function(x) { h.lower / (1 + (((x - c) / a.lower)^2)^b) } it2gbellmf.upper <- function(x) { h.upper / (1 + (((x - c) / a.upper)^2)^b) } it2gbellmf <- c(it2gbellmf.lower, it2gbellmf.upper) } it2gbell.fuzzification <- function(x, mf.params) { if (length(mf.params) != 3 && length(mf.params) != 5) { stop("improper parameters for it2gbellmf fuzzification") } mf.params <- append(mf.params, x, 3) genmf('it2gbellmf', mf.params) } singletonmf <- function(mf.params) { if (length(mf.params) != 1 && length(mf.params) != 2) { stop("improper parameters for singleton membership function") } x.prime <- mf.params[1] if (length(mf.params) == 2) { h <- mf.params[2] } else { h <- 1 } singletonmf <- function(x) { ifelse(x == x.prime, h, 0) } } singleton.fuzzification <- function(x, mf.params = NULL) { if (!is.null(mf.params) && length(mf.params) != 1) { stop("improper parameters for singleton fuzzification") } mf.params <- c(x, mf.params) genmf('singletonmf', mf.params) } linearmf <- function(mf.params) { if (length(mf.params) < 2) { stop("improper parameters for linear membership function") } linearmf <- function(x) { x %*% mf.params } } gaussmf <- function(mf.params) { sig <- mf.params[1] c <- mf.params[2] if (length(mf.params) == 3) { h <- mf.params[3] } else { h <- 1 } gaussmf <- function(x) { exp(-(x - c)^2 / (2 * sig^2)) * h } } gauss.fuzzification <- function(x, mf.params) { if (length(mf.params) != 1 && length(mf.params) != 2) { stop("improper parameters for gaussmf fuzzification") } mf.params <- append(mf.params, x, 1) genmf('gaussmf', mf.params) } it2gaussmf <- function(mf.params) { if (length(mf.params) != 4 && length(mf.params) != 6) { stop("improper parameters for it2gaussmf membership function") } sig.lower <- mf.params[1] c.lower <- mf.params[2] sig.upper <- mf.params[3] c.upper <- mf.params[4] if (length(mf.params) == 6) { h.lower <- mf.params[5] h.upper <- mf.params[6] } else { h.lower <- 1 h.upper <- 1 } it2gaussmf.lower <- function(x) { exp(-(x - c.lower)^2 / (2 * sig.lower^2)) * h.lower } it2gaussmf.upper <- function(x) { exp(-(x - c.upper)^2 / (2 * sig.upper^2)) * h.upper } it2gaussmf <- c(it2gaussmf.lower, it2gaussmf.upper) } trapmf <- function(mf.params) { a <- mf.params[1] b <- mf.params[2] c <- mf.params[3] d <- mf.params[4] if (length(mf.params) == 5) { h <- mf.params[5] } else { h <- 1 } trapmf <- function(x) { y <- pmax(pmin((x - a) / (b - a), h, (d - x) / (d - c)), 0) y[is.na(y)] = h; y } } it2trapmf <- function(x, mf.params) { if (length(mf.params) != 8 && length(mf.params) != 10) { stop("improper parameters for it2gaussmf membership function") } a.lower <- mf.params[1] b.lower <- mf.params[2] c.lower <- mf.params[3] d.lower <- mf.params[4] a.upper <- mf.params[5] b.upper <- mf.params[6] c.upper <- mf.params[7] d.upper <- mf.params[8] if (length(mf.params) == 10) { h.lower <- mf.params[9] h.upper <- mf.params[10] } else { h.lower <- 1 h.upper <- 1 } it2trapmf.lower <- function(x) { y <- pmax(pmin((x - a.lower) / (b.lower - a.lower), h.lower, (d.lower - x) / (d.lower - c.lower)), 0) y[is.na(y)] = h.lower; y } it2trapmf.upper <- function(x) { y <- pmax(pmin((x - a.upper) / (b.upper - a.upper), h.upper, (d.upper - x) / (d.upper - c.upper)), 0) y[is.na(y)] = h.upper; y } it2trapmf <- c(it2trapmf.lower, it2trapmf.upper) } trimf <- function(mf.params) { a <- mf.params[1] b <- mf.params[2] c <- mf.params[3] if (length(mf.params) == 4) { h <- mf.params[4] } else { h <- 1 } trimf <- function(x) { y <- h * pmax(pmin((x - a) / (b - a), (c - x) / (c - b)), 0) y[is.na(y)] = h; y } } it2trimf <- function(mf.params) { a.lower <- mf.params[1] b.lower <- mf.params[2] c.lower <- mf.params[3] a.upper <- mf.params[4] b.upper <- mf.params[5] c.upper <- mf.params[6] if (length(mf.params) == 8) { h.lower <- mf.params[7] h.upper <- mf.params[8] } else { h.lower <- 1 h.upper <- 1 } it2trimf.lower <- function(x) { y <- h.lower * pmax(pmin((x - a.lower) / (b.lower - a.lower), (c.lower - x) / (c.lower - b.lower)), 0) y[is.na(y)] = h.lower; y } it2trimf.upper <- function(x) { y <- h.upper * pmax(pmin((x - a.upper) / (b.upper - a.upper), (c.upper - x) / (c.upper - b.upper)), 0) y[is.na(y)] = h.upper; y } it2trimf <- c(it2trimf.lower, it2trimf.upper) } tri.fuzzification <- function(x, mf.params) { if (length(mf.params) != 2 && length(mf.params) != 3) { stop("improper parameters for trimf fuzzification") } mf.params <- append(mf.params, x, 1) genmf('trimf', mf.params) }
RISE_C <- function(train, test, Q=1, S=2){ alg <- RKEEL::R6_RISE_C$new() alg$setParameters(train, test, Q, S) return (alg) } R6_RISE_C <- R6::R6Class("R6_RISE_C", inherit = ClassificationAlgorithm, public = list( Q = 1, S = 2, setParameters = function(train, test, Q=1, S=2){ super$setParameters(train, test) self$Q <- Q self$S <- S } ), private = list( jarName = "RISE.jar", algorithmName = "RISE-C", algorithmString = "RISE", getParametersText = function(){ text <- "" text <- paste0(text, "Q = ", self$Q, "\n") text <- paste0(text, "S = ", self$S, "\n") return(text) } ) )
context("Comprehensive Test for Binary Dataset Creation") test_that("running dataset test", { skip_on_cran() dd <- aif360::aif_dataset( data_path = system.file("extdata", "data.csv", package="aif360"), favor_label=0, unfavor_label=1, unprivileged_protected_attribute=0, privileged_protected_attribute=1, target_column="income", protected_attribute="sex") expect_equal(dd$favorable_label, 0) expect_equal(dd$unfavorable_label, 1) })
"parse.formula.mnl" <- function(formula, data, baseline=NULL, intercept=TRUE){ mt <- terms(formula, data=data) if(missing(data)) data <- sys.frame(sys.parent()) mf <- match.call(expand.dots = FALSE) mf$intercept <- mf$baseline <- NULL mf$drop.unused.levels <- TRUE mf[[1]] <- as.name("model.frame") mf <- eval(mf, sys.frame(sys.parent())) if (!intercept){ attributes(mt)$intercept <- 0 } Y <- as.matrix(model.response(mf, "numeric")) if (ncol(Y)==1){ Y <- factor(Y) number.choices <- length(unique(Y)) choice.names <- sort(unique(Y)) Ymat <- matrix(NA, length(Y), number.choices) colnames(Ymat) <- choice.names for (i in 1:(number.choices)){ Ymat[,i] <- as.numeric(Y==choice.names[i]) } } else{ number.choices <- ncol(Y) Ytemp <- Y Ytemp[Y== -999] <- NA if ( min(unique(array(Y)) %in% c(-999,0,1))==0 || min(apply(Ytemp, 1, sum, na.rm=TRUE) == rep(1, nrow(Y)))==0){ stop("Y is a matrix but it is not composed of 0/1/-999 values\n and/or rows do not sum to 1\n") } Ymat <- Y choice.names <- colnames(Y) } colnames(Ymat) <- choice.names rownames(Ymat) <- 1:nrow(Ymat) X <- if (!is.empty.model(mt)) model.matrix(mt, mf) X <- as.matrix(X) xvars <- dimnames(X)[[2]] xobs <- dimnames(X)[[1]] if (is.null(baseline)){ baseline <- choice.names[1] } if (! baseline %in% choice.names){ stop("'baseline' not consistent with observed choice levels in y\n") } choicevar.indic <- rep(FALSE, length(xvars)) choicevar.indic[grep("^choicevar\\(", xvars)] <- TRUE if (sum(choicevar.indic) > 0){ cvarname1.vec <- rep(NA, sum(choicevar.indic)) cvarname2.vec <- rep(NA, sum(choicevar.indic)) counter <- 0 for (i in 1:length(xvars)){ if (choicevar.indic[i]){ counter <- counter + 1 vn2 <- strsplit(xvars[i], ",") vn3 <- strsplit(vn2[[1]], "\\(") vn4 <- strsplit(vn3[[3]], "=") cvarname1 <- vn3[[2]][1] cvarname1 <- strsplit(cvarname1, "\"")[[1]] cvarname1 <- cvarname1[length(cvarname1)] cvarname2 <- vn4[[1]][length(vn4[[1]])] cvarname2 <- strsplit(cvarname2, "\"")[[1]][2] if (! cvarname2 %in% choice.names){ stop("choicelevel that was set in choicevar() not consistent with\n observed choice levels in y") } cvarname1.vec[counter] <- cvarname1 cvarname2.vec[counter] <- cvarname2 xvars[i] <- paste(cvarname1, cvarname2, sep=".") } } X.cho <- X[, choicevar.indic] X.cho.mat <- matrix(NA, length(choice.names)*nrow(X), length(unique(cvarname1.vec))) rownames(X.cho.mat) <- rep(rownames(X), rep(length(choice.names), nrow(X))) rownames(X.cho.mat) <- paste(rownames(X.cho.mat), choice.names, sep=".") colnames(X.cho.mat) <- unique(cvarname1.vec) choice.names.n <- rep(choice.names, nrow(X)) for (j in 1:length(unique(cvarname1.vec))){ for (i in 1:length(cvarname2.vec)){ if (colnames(X.cho.mat)[j] == cvarname1.vec[i]){ X.cho.mat[choice.names.n==cvarname2.vec[i], j] <- X.cho[,i] } } } } xvars.ind.mat <- rep(xvars[!choicevar.indic], rep(length(choice.names), sum(!choicevar.indic))) xvars.ind.mat <- paste(xvars.ind.mat, choice.names, sep=".") if (sum(!choicevar.indic) > 0){ X.ind.mat <- X[,!choicevar.indic] %x% diag(length(choice.names)) colnames(X.ind.mat) <- xvars.ind.mat rownames(X.ind.mat) <- rep(rownames(X), rep(length(choice.names), nrow(X))) rownames(X.ind.mat) <- paste(rownames(X.ind.mat), choice.names, sep=".") ivarname1 <- strsplit(xvars.ind.mat, "\\.") ivar.keep.indic <- rep(NA, ncol(X.ind.mat)) for (i in 1:ncol(X.ind.mat)){ ivar.keep.indic[i] <- ivarname1[[i]][length(ivarname1[[i]])] != baseline } X.ind.mat <- X.ind.mat[,ivar.keep.indic] } if (sum(choicevar.indic) > 0 & sum(!choicevar.indic) > 0){ X <- cbind(X.cho.mat, X.ind.mat) } else if (sum(!choicevar.indic) > 0){ X <- X.ind.mat } else if (sum(choicevar.indic) > 0){ X <- X.cho.mat } else { stop("X matrix appears to have neither choice-specific nor individual-specific variables.\n") } xvars <- colnames(X) xobs <- rownames(X) return(list(Ymat, X, xvars, xobs, number.choices)) } "choicevar" <- function(var, varname, choicelevel){ junk1 <- varname junk2 <- choicelevel return(var) } "mnl.logpost.noNA" <- function(beta, new.Y, X, b0, B0){ nobs <- length(new.Y) ncat <- nrow(X) / nobs Xb <- X %*% beta Xb <- matrix(Xb, byrow=TRUE, ncol=ncat) indices <- cbind(1:nobs, new.Y) Xb.reform <- Xb[indices] eXb <- exp(Xb) z <- rep(1, ncat) denom <- log(eXb %*% z) log.prior <- 0.5 * t(beta - b0) %*% B0 %*% (beta - b0) return(sum(Xb.reform - denom) + log.prior) } "mnl.logpost.NA" <- function(beta, Y, X, b0, B0){ k <- ncol(X) numer <- exp(X %*% beta) numer[Y== -999] <- NA numer.mat <- matrix(numer, nrow(Y), ncol(Y), byrow=TRUE) denom <- apply(numer.mat, 1, sum, na.rm=TRUE) choice.probs <- numer.mat / denom Yna <- Y Yna[Y == -999] <- NA log.like.mat <- log(choice.probs) * Yna log.like <- sum(apply(log.like.mat, 1, sum, na.rm=TRUE)) log.prior <- 0.5 * t(beta - b0) %*% B0 %*% (beta - b0) return(log.like + log.prior) } "MCMCmnl" <- function(formula, baseline=NULL, data=NULL, burnin = 1000, mcmc = 10000, thin=1, mcmc.method = c("IndMH", "RWM", "slice"), tune = 1.0, tdf=6, verbose = 0, seed = NA, beta.start = NA, b0 = 0, B0 = 0, ...) { check.offset(list(...)) check.mcmc.parameters(burnin, mcmc, thin) if (tdf <= 0){ stop("degrees of freedom for multivariate-t proposal must be positive.\n Respecify tdf and try again.\n") } seeds <- form.seeds(seed) lecuyer <- seeds[[1]] seed.array <- seeds[[2]] lecuyer.stream <- seeds[[3]] holder <- parse.formula.mnl(formula=formula, baseline=baseline, data=data) Y <- holder[[1]] if (is.null(baseline)){ if (max(Y[,1] == -999) == 1){ stop("Baseline choice not available in all choicesets.\n Respecify baseline category and try again.\n") } } else{ if (max(Y[,baseline] == -999) == 1){ stop("Baseline choice not available in all choicesets.\n Respecify baseline category and try again.\n") } } X <- holder[[2]] xnames <- holder[[3]] xobs <- holder[[4]] number.choices <- holder[[5]] K <- ncol(X) tune <- vector.tune(tune, K) mvn.prior <- form.mvn.prior(b0, B0, K) b0 <- mvn.prior[[1]] B0 <- mvn.prior[[2]] beta.init <- rep(0, K) cat("Calculating MLEs and large sample var-cov matrix.\n") cat("This may take a moment...\n") if (max(is.na(Y))){ optim.out <- optim(beta.init, mnl.logpost.NA, method="BFGS", control=list(fnscale=-1), hessian=TRUE, Y=Y, X=X, b0=b0, B0=B0) } else{ new.Y <- apply(Y==1, 1, which) optim.out <- optim(beta.init, mnl.logpost.noNA, method="BFGS", control=list(fnscale=-1), hessian=TRUE, new.Y=new.Y, X=X, b0=b0, B0=B0) } cat("Inverting Hessian to get large sample var-cov matrix.\n") V <- chol2inv(chol(-1*optim.out$hessian)) beta.mode <- matrix(optim.out$par, K, 1) if (is.na(beta.start) || is.null(beta.start)){ beta.start <- matrix(optim.out$par, K, 1) } else if(is.null(dim(beta.start))) { beta.start <- matrix(beta.start, K, 1) } else if (length(beta.start != K)){ stop("beta.start not of appropriate dimension\n") } sample <- matrix(data=0, mcmc/thin, dim(X)[2] ) posterior <- NULL if (mcmc.method=="RWM"){ auto.Scythe.call(output.object="posterior", cc.fun.name="MCMCmnlMH", sample.nonconst=sample, Y=Y, X=X, burnin=as.integer(burnin), mcmc=as.integer(mcmc), thin=as.integer(thin), tune=tune, lecuyer=as.integer(lecuyer), seedarray=as.integer(seed.array), lecuyerstream=as.integer(lecuyer.stream), verbose=as.integer(verbose), betastart=beta.start, betamode=beta.mode, b0=b0, B0=B0, V=V, RW=as.integer(1), tdf=as.double(tdf)) output <- form.mcmc.object(posterior, names=xnames, title="MCMCmnl Posterior Sample") } else if (mcmc.method=="IndMH"){ auto.Scythe.call(output.object="posterior", cc.fun.name="MCMCmnlMH", sample.nonconst=sample, Y=Y, X=X, burnin=as.integer(burnin), mcmc=as.integer(mcmc), thin=as.integer(thin), tune=tune, lecuyer=as.integer(lecuyer), seedarray=as.integer(seed.array), lecuyerstream=as.integer(lecuyer.stream), verbose=as.integer(verbose), betastart=beta.start, betamode=beta.mode, b0=b0, B0=B0, V=V, RW=as.integer(0), tdf=as.double(tdf)) output <- form.mcmc.object(posterior, names=xnames, title="MCMCmnl Posterior Sample") } else if (mcmc.method=="slice"){ auto.Scythe.call(output.object="posterior", cc.fun.name="MCMCmnlslice", sample.nonconst=sample, Y=Y, X=X, burnin=as.integer(burnin), mcmc=as.integer(mcmc), thin=as.integer(thin), lecuyer=as.integer(lecuyer), seedarray=as.integer(seed.array), lecuyerstream=as.integer(lecuyer.stream), verbose=as.integer(verbose), betastart=beta.start, b0=b0, B0=B0, V=V) output <- form.mcmc.object(posterior, names=xnames, title="MCMCmnl Posterior Sample") } return(output) }
base.class.R6 <- R6Class("palm", public = list( n.patterns = NULL, lims = NULL, lims.list = NULL, vol = NULL, vol.list = NULL, dim = NULL, dim.list = NULL, classes = NULL, initialize = function(lims.list, classes, ...){ self$lims.list <- lims.list self$vol.list <- lapply(self$lims.list, function(x) prod(apply(x, 1, diff))) self$dim.list <- lapply(self$lims.list, function(x) nrow(x)) self$n.patterns <- length(lims.list) self$classes <- classes }, setup.pattern = function(pattern){ if (pattern > self$n.patterns){ stop("Pattern index exceeds the number of patterns") } self$lims <- self$lims.list[[pattern]] self$vol <- self$vol.list[[pattern]] self$dim <- self$dim.list[[pattern]] }, simulate = function(pars = self$par.fitted){ out <- vector(mode = "list", length = self$n.patterns) for (i in 1:self$n.patterns){ self$setup.pattern(i) out[[i]] <- self$simulate.pattern(pars) } if (self$n.patterns == 1){ out <- out[[1]] } out }, simulate.pattern = function(pars){}, trim.points = function(points, output.indices = FALSE){ in.window <- rep(TRUE, nrow(points)) for (i in 1:self$dim){ in.window <- in.window & (self$lims[i, 1] <= points[, i] & self$lims[i, 2] >= points[, i]) } if (output.indices){ out <- which(in.window) } else { out <- points[in.window, , drop = FALSE] } out } )) set.CLASSNAME.class <- function(class, class.env){ assign("CLASSNAME.inherit", class, envir = class.env) R6Class("palm_CLASSNAME", inherit = class.env$CLASSNAME.inherit, public = list( )) } set.fit.class <- function(class, class.env){ assign("fit.inherit", class, envir = class.env) R6Class("palm_fit", inherit = class.env$fit.inherit, public = list( points.list = NULL, points = NULL, n.points = NULL, n.points.list = NULL, contrasts = NULL, contrasts.list = NULL, n.contrasts = NULL, n.contrasts.list = NULL, contrast.pairs = NULL, contrast.pairs.list = NULL, R = NULL, boots = NULL, trace = NULL, conv.code = NULL, converged = NULL, n.par = NULL, set.start = NULL, set.bounds = NULL, par.names = NULL, fixed.names = NULL, par.names.link = NULL, par.start = NULL, par.start.link = NULL, par.fixed = NULL, par.fixed.link = NULL, par.links = NULL, par.invlinks = NULL, par.fitted = NULL, par.fitted.link = NULL, par.lower = NULL, par.lower.link = NULL, par.upper = NULL, par.upper.link = NULL, pi.multiplier = NULL, initialize = function(points.list, R, trace, start, bounds, ...){ super$initialize(...) self$points.list <- points.list if (length(self$points.list) != length(self$lims.list)){ stop("The list 'points' must have the same number of components as 'lims'.") } self$R <- R self$n.points.list <- lapply(points.list, nrow) self$contrasts.list <- list() self$contrast.pairs.list <- list() self$n.contrasts.list <- list() for (i in 1:self$n.patterns){ self$get.contrasts(i) } self$setup.pattern(1) self$trace <- trace self$set.start <- start self$set.bounds <- bounds self$get.pars() self$n.par <- length(self$par.start) self$par.start.link <- self$link.pars(self$par.start) self$get.link.bounds() }, setup.pattern = function(pattern, do.contrasts = TRUE){ super$setup.pattern(pattern) self$points <- self$points.list[[pattern]] self$n.points <- self$n.points.list[[pattern]] if (do.contrasts){ self$contrast.pairs <- self$contrast.pairs.list[[pattern]] self$contrasts <- self$contrasts.list[[pattern]] self$n.contrasts <- self$n.contrasts.list[[pattern]] } }, get.contrasts = function(pattern){ self$n.contrasts.list[[pattern]] <- length(self$contrasts.list[[pattern]]) }, get.pars = function(){ self$fetch.pars() }, fetch.pars = function(){ }, add.pars = function(name, link.name = NULL, link, invlink = NULL, start, lower, upper){ self$par.names <- c(self$par.names, name) if (identical(link, log)){ full.link <- function(pars) log(pars[name]) if (is.null(link.name)){ link.name <- paste("log", name, sep = ".") } if (is.null(invlink)){ full.invlink <- function(pars) exp(pars[link.name]) } } else if (identical(link, logit)){ full.link <- function(pars) link(pars[name]) if (is.null(link.name)){ link.name <- paste("logit", name, sep = ".") } if (is.null(invlink)){ full.invlink <- function(pars) invlogit(pars[link.name]) } } else { if (is.null(link.name)){ stop("Please provide link name.") } if (is.null(invlink)){ stop("Please provide inverse link function.") } full.link <- link full.invlink <- invlink } self$par.links <- c(self$par.links, full.link) names(self$par.links) <- self$par.names self$par.invlinks <- c(self$par.invlinks, full.invlink) names(self$par.invlinks) <- self$par.names self$par.names.link <- c(self$par.names.link, link.name) if (any(name == names(self$set.start))){ start <- self$set.start[name] } if (any(name == names(self$set.bounds))){ lower <- self$set.bounds[[name]][1] upper <- self$set.bounds[[name]][2] } self$par.upper <- c(self$par.upper, upper) names(self$par.upper) <- self$par.names self$par.lower <- c(self$par.lower, lower) if (start >= upper){ start <- lower + 0.9*(upper - lower) } else if (start <= lower){ start <- lower + 0.9*(upper - lower) } self$par.start <- c(self$par.start, start) names(self$par.start) <- self$par.names names(self$par.lower) <- self$par.names }, get.link.bounds = function(){ self$par.lower.link <- self$link.pars(self$par.lower) self$par.upper.link <- self$link.pars(self$par.upper) }, link.pars = function(pars){ out <- numeric(self$n.par) for (i in 1:self$n.par){ out[i] <- self$par.links[[i]](pars) } names(out) <- self$par.names.link out }, invlink.pars = function(pars){ out <- numeric(self$n.par) for (i in 1:self$n.par){ out[i] <- self$par.invlinks[[i]](pars) } names(out) <- self$par.names out }, obj.fun = function(link.pars, fixed.link.pars = NULL, est.names = NULL, fixed.names = NULL){ combined.pars <- c(link.pars, fixed.link.pars) names(combined.pars) <- c(est.names, fixed.names) link.pars <- combined.pars[self$par.names.link] pars <- self$invlink.pars(link.pars) obj.fun.components <- numeric(self$n.patterns) for (i in 1:self$n.patterns){ self$setup.pattern(i) obj.fun.components[i] <- self$neg.log.palm.likelihood(pars) } out <- sum(obj.fun.components) ll <- -out if (self$trace){ for (i in 1:self$n.par){ cat(self$par.names[i], ": ", sep = "") cat(pars[i], ", ", sep = "") } cat("Log-lik: ", ll, "\n", sep = "") } out }, palm.intensity = function(r, pars){}, sum.log.intensities = function(pars){ sum(log(self$pi.multiplier*self$palm.intensity(self$contrasts, pars))) }, palm.likelihood.integral = function(pars){ f <- function(r, pars){ self$palm.intensity(r, pars)*Sd(r, self$dim) } -self$pi.multiplier*integrate(f, lower = 0, upper = self$R, pars = pars)$value }, log.palm.likelihood = function(pars){ self$sum.log.intensities(pars) + self$palm.likelihood.integral(pars) }, neg.log.palm.likelihood = function(pars){ -self$log.palm.likelihood(pars) }, palm.optimise = function(){}, palm.not.optimise = function(){ self$converged <- FALSE self$par.fitted.link <- rep(NA, self$n.par) names(self$par.fitted.link) <- self$par.names.link self$par.fitted <- rep(NA, self$n.par) self$conv.code <- 5 }, fit = function(){ if (self$n.contrasts <= 1){ warning("Not enough observed points to compute parameter estimates.") self$palm.not.optimise() } else { self$palm.optimise() } }, boot = function(N, prog = TRUE){ boots <- matrix(0, nrow = N, ncol = self$n.par) if (prog){ pb <- txtProgressBar(min = 0, max = N, style = 3) } for (i in 1:N){ zero.points <- TRUE while (zero.points){ sim.obj <- self$simulate() if (self$n.patterns > 1){ sim.obj$points <- lapply(sim.obj, function(x) x$points) sim.obj$sibling.list <- lapply(sim.obj, function(x) x$sibling.list) zero.points <- sum(sapply(sim.obj$points, nrow)) == 0 } else { zero.points <- nrow(sim.obj$points) == 0 } } obj.boot <- create.obj(classes = self$classes, points = sim.obj$points, lims = self$lims, R = self$R, child.list = self$child.list, sibling.list = sim.obj$sibling.list, trace = FALSE, start = self$par.fitted, bounds = self$bounds) obj.boot$fit() if (obj.boot$converged){ boots[i, ] <- obj.boot$par.fitted } else { boots[i, ] <- rep(NA, self$n.par) } if (prog){ setTxtProgressBar(pb, i) } } cat("\n") self$boots <- boots colnames(self$boots) <- self$par.names }, plot = function(xlim = NULL, ylim = NULL, show.empirical = TRUE, breaks = 50, ...){ if (show.empirical){ emp <- self$empirical(xlim, breaks) } if (is.null(xlim)){ xlim <- self$get.xlim() } xx <- seq(xlim[1], xlim[2], length.out = 1000) yy <- self$palm.intensity(xx, self$par.fitted) if (is.null(ylim)){ if (show.empirical){ ylim <- c(0, max(c(emp$y, yy))) } else { ylim <- c(0, max(yy)) } } par(xaxs = "i") plot(xx, yy, xlab = "", ylab = "", xlim = range(xx), ylim = ylim, type = "n", ...) title(xlab = "r", ylab = "Palm intensity") lines(xx, yy) if (show.empirical){ lines(emp$x, emp$y, lty = "dashed") } }, get.xlim = function(){ c(0, self$R) }, empirical = function(xlim = NULL, breaks = 50){ if (is.null(xlim)){ xlim <- self$get.xlim() } dists <- pbc_distances(self$points, self$lims) midpoints <- seq(0, xlim[2], length.out = breaks) midpoints <- midpoints[-length(midpoints)] h <- diff(midpoints[c(1, 2)]) midpoints[1] <- midpoints[1] + h/2 intensities <- numeric(length(midpoints)) for (i in 1:length(midpoints)){ halfwidth <- ifelse(i == 1, 0.25*h, 0.5*h) n.interval <- sum(dists <= (midpoints[i] + halfwidth)) - sum(dists <= (midpoints[i] - halfwidth)) area <- Vd(midpoints[i] + halfwidth, self$dim) - Vd(midpoints[i] - halfwidth, self$dim) intensities[i] <- n.interval/(self$pi.multiplier*area) } list(x = midpoints, y = intensities) } )) } set.bobyqa.class <- function(class, class.env){ assign("bobyqa.inherit", class, envir = class.env) R6Class("palm_bobyqa", inherit = class.env$bobyqa.inherit, public = list( palm.optimise = function(){ out <- try(bobyqa(self$par.start.link, self$obj.fun, lower = self$par.lower.link, upper = self$par.upper.link, fixed.link.pars = self$par.fixed.link, est.names = self$par.names.link, fixed.names = self$fixed.names.link, control = list(maxfun = 2000, npt = 2*self$n.par + 1)), silent = TRUE) if (class(out)[1] == "try-error"){ self$palm.not.optimise() } else { if (out$ierr > 0){ warning("Failed convergence.") self$converged <- FALSE } else { self$converged <- TRUE } self$par.fitted.link <- out$par names(self$par.fitted.link) <- self$par.names.link self$par.fitted <- self$invlink.pars(self$par.fitted.link) self$conv.code <- out$ierr } } )) } set.nlminb.class <- function(class, class.env){ assign("nlminb.inherit", class, envir = class.env) R6Class("palm_nlminb", inherit = class.env$nlminb.inherit, public = list( palm.optimise = function(){ out <- nlminb(self$par.start.link, self$obj.fun, fixed.link.pars = self$par.fixed.link, est.names = self$par.names.link, fixed.names = self$fixed.names.link, control = list(eval.max = 2000, iter.max = 1500), lower = self$par.lower.link, upper = self$par.upper.link) if (out$convergence > 1){ warning("Failed convergence.") self$converged <- FALSE } else { self$converged <- TRUE } self$par.fitted.link <- out$par names(self$par.fitted.link) <- self$par.names.link self$par.fitted <- self$invlink.pars(self$par.fitted.link) self$conv.code <- out$convergence } )) } set.pbc.class <- function(class, class.env){ assign("pbc.inherit", class, envir = class.env) R6Class("palm_pbc", inherit = class.env$pbc.inherit, public = list( setup.pattern = function(pattern, do.contrasts = TRUE){ super$setup.pattern(pattern, do.contrasts) self$pi.multiplier <- self$n.points/2 }, get.contrasts = function(pattern){ self$setup.pattern(pattern, do.contrasts = FALSE) contrast.pairs <- matrix(0, nrow = (self$n.points^2 - self$n.points)/2, ncol = 2) k <- 1 if (self$n.points > 1){ for (i in 1:(self$n.points - 1)){ for (j in (i + 1):self$n.points){ contrast.pairs[k, ] <- c(i, j) k <- k + 1 } } contrasts <- pbc_distances(points = self$points, lims = self$lims) self$contrast.pairs.list[[pattern]] <- contrast.pairs[contrasts <= self$R, ] self$contrasts.list[[pattern]] <- contrasts[contrasts <= self$R] } else { self$contrast.pairs.list[[pattern]] <- contrast.pairs self$contrasts[[pattern]] <- numeric(0) } super$get.contrasts(pattern) } )) } set.buffer.class <- function(class, class.env){ assign("buffer.inherit", class, envir = class.env) R6Class("palm_buffer", inherit = class.env$buffer.inherit, public = list( setup.pattern = function(pattern, do.contrasts = TRUE){ super$setup.pattern(pattern, do.contrasts) self$pi.multiplier <- self$n.points }, get.contrasts = function(pattern){ self$setup.pattern(pattern, do.contrasts = FALSE) buffer.keep <- buffer_keep(points = self$points, lims = self$lims, R = self$R) contrasts <- as.vector(as.matrix(dist(self$points))[buffer.keep]) contrast.pairs.1 <- matrix(rep(1:self$n.points, self$n.points), nrow = self$n.points) contrast.pairs.2 <- matrix(rep(1:self$n.points, self$n.points), nrow = self$n.points, byrow = TRUE) contrast.pairs.1 <- as.vector(contrast.pairs.1[buffer.keep]) contrast.pairs.2 <- as.vector(contrast.pairs.2[buffer.keep]) contrast.pairs <- cbind(contrast.pairs.1, contrast.pairs.2) self$contrasts.list[[pattern]] <- contrasts[contrasts <= self$R] self$contrast.pairs.list[[pattern]] <- contrast.pairs[contrasts <= self$R, ] super$get.contrasts(pattern) } )) } set.ns.class <- function(class, class.env){ assign("ns.inherit", class, envir = class.env) R6Class("palm_ns", inherit = class.env$ns.inherit, public = list( child.list = NULL, fetch.pars = function(){ super$fetch.pars() link <- function(pars){ log(pars["D"]*self$child.expectation(pars)) } invlink <- function(pars, out){ exp(pars["log.Dc"])/self$child.expectation(out) } self$add.pars(name = "D", link.name = "log.Dc", link = link, invlink = invlink, start = sqrt(self$n.points/self$vol), lower = 0, upper = Inf) }, invlink.pars = function(pars){ out <- numeric(self$n.par) names(out) <- self$par.names which.D <- which(self$par.names == "D") for (i in (1:self$n.par)[-which.D]){ out[i] <- self$par.invlinks[[i]](pars) } out[which.D] <- self$par.invlinks[[which.D]](pars, out) out }, simulate.pattern = function(pars = self$par.fitted){ parent.locs <- self$get.parents(pars) n.parents <- nrow(parent.locs) sim.n.children <- self$simulate.n.children(n.parents, pars) n.children <- sim.n.children$n.children sibling.list <- sim.n.children$sibling.list child.locs <- matrix(0, nrow = sum(n.children), ncol = self$dim) j <- 0 for (i in seq_along(n.children)){ if (n.children[i] > 0){ child.locs[(j + 1):(j + n.children[i]), ] <- self$simulate.children(n.children[i], parent.locs[i, ], pars) j <- j + n.children[i] } } parent.ids <- rep(seq_along(n.children), times = n.children) trimmed <- self$trim.points(child.locs, output.indices = TRUE) list(points = child.locs[trimmed, , drop = FALSE], parents = parent.locs, parent.ids = parent.ids[trimmed], child.ys = sim.n.children$child.ys[trimmed], sibling.list = self$trim.siblings(sibling.list, trimmed)) }, trim.siblings = function(sibling.list, trimmed){ sibling.list }, get.parents = function(pars){ expected.parents <- pars["D"]*self$vol n.parents <- rpois(1, expected.parents) parent.locs <- matrix(0, nrow = n.parents, ncol = self$dim) for (i in 1:self$dim){ parent.locs[, i] <- runif(n.parents, self$lims[i, 1], self$lims[i, 2]) } parent.locs }, palm.intensity = function(r, pars){ self$sibling.pi(r, pars) + self$nonsibling.pi(pars) }, child.expectation = function(pars){}, child.variance = function(pars){}, sibling.expectation = function(pars){ (self$child.variance(pars) + self$child.expectation(pars)^2)/self$child.expectation(pars) - 1 }, fq = function(r, pars){}, Fq = function(r, pars){}, fq.over.s = function(r, pars){ self$fq(r, pars)/Sd(r, dim) }, nonsibling.pi = function(pars){ pars["D"]*self$child.expectation(pars) }, sibling.pi = function(r, pars){ self$sibling.expectation(pars)*self$fq.over.s(r, pars) } )) } set.sibling.class <- function(class, class.env){ assign("sibling.inherit", class, envir = class.env) R6Class("palm_sibling", inherit = class.env$sibling.inherit, public = list( siblings = NULL, siblings.list = NULL, sibling.list = NULL, sibling.mat = NULL, sibling.alpha = NULL, sibling.beta = NULL, initialize = function(sibling.list, ...){ self$sibling.list <- sibling.list super$initialize(...) self$siblings.list <- list() for (i in 1:self$n.patterns){ self$get.siblings(i) } }, setup.pattern = function(pattern, do.contrasts = TRUE, do.siblings = TRUE){ super$setup.pattern(pattern, do.contrasts) self$sibling.mat <- self$sibling.list[[pattern]]$sibling.mat self$sibling.alpha <- self$sibling.list[[pattern]]$alpha self$sibling.beta <- self$sibling.list[[pattern]]$beta if (do.siblings){ self$siblings <- self$siblings.list[[pattern]] } }, get.siblings = function(pattern){ self$setup.pattern(pattern, do.siblings = FALSE) siblings <- numeric(self$n.contrasts) for (i in 1:self$n.contrasts){ pair <- self$contrast.pairs[i, ] siblings[i] <- self$sibling.mat[pair[1], pair[2]] } siblings <- as.numeric(siblings) siblings[is.na(siblings)] <- 2 self$siblings.list[[pattern]] <- siblings }, sum.log.intensities = function(pars){ all.palm.intensities <- numeric(self$n.contrasts) all.palm.intensities[self$siblings == 0] <- self$sibling.beta*self$nonsibling.pi(pars) all.palm.intensities[self$siblings == 1] <- self$sibling.alpha* self$sibling.pi(self$contrasts[self$siblings == 1], pars) all.palm.intensities[self$siblings == 2] <- (1 - self$sibling.beta)*self$nonsibling.pi(pars) + (1 - self$sibling.alpha)* self$sibling.pi(self$contrasts[self$siblings == 2], pars) sum(log(self$n.points*all.palm.intensities)) } )) } set.poischild.class <- function(class, class.env){ assign("poischild.inherit", class, envir = class.env) R6Class("palm_poischild", inherit = class.env$poischild.inherit, public = list( fetch.pars = function(){ super$fetch.pars() self$add.pars(name = "lambda", link = log, start = sqrt(self$n.points/self$vol), lower = 0, upper = self$n.points) }, simulate.n.children = function(n, pars){ list(n.children = rpois(n, pars["lambda"])) }, child.expectation = function(pars){ pars["lambda"] }, child.variance = function(pars){ pars["lambda"] } )) } set.binomchild.class <- function(class, class.env){ assign("binomchild.inherit", class, envir = class.env) R6Class("palm_binomchild", inherit = class.env$binomchild.inherit, public = list( binom.size = NULL, initialize = function(child.list, ...){ self$child.list <- child.list self$binom.size <- child.list$size super$initialize(...) }, fetch.pars = function(){ super$fetch.pars() p.start <- sqrt(self$n.points/self$vol)/self$binom.size p.start <- ifelse(p.start > 1, 0.9, p.start) p.start <- ifelse(p.start < 0, 0.1, p.start) self$add.pars(name = "p", link = logit, start = p.start, lower = 0, upper = 1) }, simulate.n.children = function(n, pars){ list(n.children = rbinom(n, self$binom.size, pars["p"])) }, child.expectation = function(pars){ self$binom.size*pars["p"] }, child.variance = function(pars){ self$binom.size*pars["p"]*(1 - pars["p"]) } )) } set.twocamerachild.class <- function(class, class.env){ assign("twocamerachild.inherit", class, envir = class.env) R6Class("palm_twocamerachild", inherit = class.env$twocamerachild.inherit, public = list( twocamera.w = NULL, twocamera.b = NULL, twocamera.l = NULL, twocamera.tau = NULL, initialize = function(child.list, ...){ self$child.list <- child.list self$twocamera.w <- child.list$twocamera.w self$twocamera.b <- child.list$twocamera.b self$twocamera.l <- child.list$twocamera.l self$twocamera.tau <- child.list$twocamera.tau super$initialize(...) self$setup.pattern(1) if (self$dim != 1){ stop("Analysis of two-camera surveys is only implemented for one-dimensional processes.") } }, fetch.pars = function(){ super$fetch.pars() self$add.pars(name = "kappa", link = log, start = 0.1*self$twocamera.tau, lower = 0, upper = self$twocamera.tau) }, simulate.pattern = function(pars = self$par.fitted){ if (any(names(pars) == "D.2D")){ which.D <- which(names(pars) == "D.2D") pars[which.D] <- 2*pars[which.D]*self$twocamera.b names(pars)[which.D] <- "D" } super$simulate.pattern(pars) }, simulate.n.children = function(n, pars){ probs <- twocamera.probs(self$twocamera.l, self$twocamera.tau, self$twocamera.w, self$twocamera.b, pars["kappa"], pars["sigma"]) parent.ys <- runif(n, -self$twocamera.b, self$twocamera.b) child.ys <- matrix(nrow = n, ncol = 2) for (i in 1:n){ child.ys[i, ] <- rnorm(2, parent.ys[i], pars["sigma"]) } camera1.in <- ifelse(child.ys[, 1] < self$twocamera.w & child.ys[, 1] > -self$twocamera.w, TRUE, FALSE) camera2.in <- ifelse(child.ys[, 2] < self$twocamera.w & child.ys[, 2] > -self$twocamera.w, TRUE, FALSE) camera1.up <- sample(c(TRUE, FALSE), n, replace = TRUE, prob = c(probs$p.up, probs$p.down)) camera2.up <- logical(n) for (i in 1:n){ p.up <- ifelse(camera1.up[i], 1 - probs$p.down.up, probs$p.up.down) camera2.up[i] <- sample(c(TRUE, FALSE), 1, prob = c(p.up, 1 - p.up)) } camera1.det <- camera1.in & camera1.up camera2.det <- camera2.in & camera2.up child.ys <- t(child.ys)[t(cbind(camera1.det, camera2.det))] n.children <- camera1.det + camera2.det cameras <- numeric(sum(n.children)) j <- 1 for (i in 1:n){ if (n.children[i] > 0){ cameras[j:(j + n.children[i] - 1)] <- c(1[camera1.det[i]], 2[camera2.det[i]]) } j <- j + n.children[i] } sibling.list <- siblings.twocamera(cameras) sibling.list$cameras <- cameras list(n.children = n.children, sibling.list = sibling.list, child.ys = child.ys) }, trim.siblings = function(sibling.list, trimmed){ sibling.list$sibling.mat <- sibling.list$sibling.mat[trimmed, trimmed, drop = FALSE] sibling.list$cameras <- sibling.list$cameras[trimmed] super$trim.siblings(sibling.list, trimmed) }, child.expectation = function(pars){ probs <- twocamera.probs(self$twocamera.l, self$twocamera.tau, self$twocamera.w, self$twocamera.b, pars["kappa"], pars["sigma"]) 2*probs$p.10/(probs$p.10 + probs$p.01) }, child.variance = function(pars){ probs <- twocamera.probs(self$twocamera.l, self$twocamera.tau, self$twocamera.w, self$twocamera.b, pars["kappa"], pars["sigma"]) 2*probs$p.10*probs$p.01*(2 - probs$p.10 - probs$p.01)/(probs$p.10 + probs$p.01)^2 } )) } set.thomas.class <- function(class, class.env){ assign("thomas.inherit", class, envir = class.env) R6Class("palm_thomas", inherit = class.env$thomas.inherit, public = list( fetch.pars = function(){ super$fetch.pars() self$add.pars(name = "sigma", link = log, start = 0.1*self$R, lower = 0, upper = self$R) }, simulate.children = function(n, parent.loc, pars){ rmvnorm(n, parent.loc, pars["sigma"]^2*diag(self$dim)) }, palm.likelihood.integral = function(pars){ -self$pi.multiplier*(pars["D"]*self$child.expectation(pars)*Vd(self$R, self$dim) + self$sibling.expectation(pars)*self$Fq(self$R, pars)) }, fq = function(r, pars){ 2^(1 - self$dim/2)*r^(self$dim - 1)*exp(-r^2/(4*pars["sigma"]^2))/ ((pars["sigma"]*sqrt(2))^self$dim*gamma(self$dim/2)) }, Fq = function(r, pars){ pgamma(r^2/(4*pars["sigma"]^2), self$dim/2) }, fq.over.s = function(r, pars){ exp(-r^2/(4*pars["sigma"]^2))/((2*pars["sigma"])^self$dim*pi^(self$dim/2)) }, get.xlim = function(){ c(0, min(self$R, 10*self$par.fitted["sigma"])) } )) } set.matern.class <- function(class, class.env){ assign("matern.inherit", class, envir = class.env) R6Class("palm_matern", inherit = class.env$matern.inherit, public = list( fetch.pars = function(){ super$fetch.pars() self$add.pars(name = "tau", link = log, start = 0.1*self$R, lower = 0, upper = self$R) }, simulate.children = function(n, parent.loc, pars){ out <- matrix(0, nrow = n, ncol = self$dim) for (i in 1:n){ keep <- FALSE while (!keep){ proposal <- runif(self$dim, -pars["tau"], pars["tau"]) if (sqrt(sum(proposal^2)) <= pars["tau"]){ proposal <- proposal + parent.loc out[i, ] <- proposal keep <- TRUE } } } out }, fq = function(r, pars){ ifelse(r > 2*pars["tau"], 0, 2*self$dim*r^(self$dim - 1)*(pars["tau"]*hyperg_2F1(0.5, 0.5 - self$dim/2, 1.5, 1) - r/2*hyperg_2F1(0.5, 0.5 - self$dim/2, 1.5, r^2/(4*pars["tau"]^2)))/ (beta(self$dim/2 + 0.5, 0.5)*pars["tau"]^(self$dim + 1))) }, Fq = function(r, pars){ alpha <- r^2/(4*pars["tau"]^2) r^2/pars["tau"]^2*(1 - pbeta(alpha, 0.5, self$dim/2 + 0.5)) + 2^self$dim*incomplete.beta(alpha, self$dim/2 + 0.5, self$dim/2 + 0.5)/ beta(0.5, self$dim/2 + 0.5) }, fq.over.s = function(r, pars){ ifelse(r > 2*pars["tau"], 0, 2*(pars["tau"]*hyperg_2F1(0.5, 0.5 - self$dim/2, 1.5, 1) - r/2*hyperg_2F1(0.5, 0.5 - self$dim/2, 1.5, r^2/(4*pars["tau"]^2)))*gamma(self$dim/2 + 1)/ (beta(self$dim/2 + 0.5, 0.5)*pars["tau"]^(self$dim + 1)*pi^(self$dim/2))) }, get.xlim = function(){ c(0, min(self$R, 10*self$par.fitted["tau"])) } )) } set.void.class <- function(class, class.env){ assign("void.inherit", class, envir = class.env) R6Class("palm_void", inherit = class.env$void.inherit, public = list( fetch.pars = function(){ super$fetch.pars() self$add.pars(name = "Dp", link = log, start = 10/self$vol, lower = 0, upper = Inf) self$add.pars(name = "Dc", link = log, start = self$n.points/self$vol, lower = 0, upper = Inf) }, simulate.pattern = function(pars = self$par.fitted){ expected.children <- pars["Dc"]*self$vol n.children <- rpois(1, expected.children) child.locs <- matrix(0, nrow = n.children, ncol = self$dim) for (i in 1:self$dim){ child.locs[, i] <- runif(n.children, self$lims[i, 1], self$lims[i, 2]) } parent.locs <- self$get.parents(pars) list(points = self$delete.points(child.locs, parent.locs, pars), parents = parent.locs) }, get.parents = function(pars){ expected.parents <- pars["Dp"]*self$vol n.parents <- rpois(1, expected.parents) parent.locs <- matrix(0, nrow = n.parents, ncol = self$dim) for (i in 1:self$dim){ parent.locs[, i] <- runif(n.parents, self$lims[i, 1], self$lims[i, 2]) } parent.locs }, palm.intensity = function(r, pars){ pars["Dc"]*self$prob.safe(r, pars) } )) } set.totaldeletion.class <- function(class, class.env){ assign("totaldeletion.inherit", class, envir = class.env) R6Class("palm_totaldeletion", inherit = class.env$totaldeletion.inherit, public = list( fetch.pars = function(){ super$fetch.pars() self$add.pars(name = "tau", link = log, start = 0.1*self$R, lower = 0, upper = self$R) }, prob.safe = function(r, pars){ exp(-pars["Dp"]*Vd(pars["tau"], self$dim)*(1 - pbeta(1 - (r/(2*pars["tau"])), (self$dim + 1)/2, 0.5))) }, delete.points = function(child.locs, parent.locs, pars){ dists <- euc_distances(child.locs[, 1], child.locs[, 2], parent.locs[, 1], parent.locs[, 2]) child.locs[apply(dists, 1, min) > pars["tau"], ] }, get.xlim = function(){ c(0, min(self$R, 10*self$par.fitted["tau"])) } )) } set.giveparent.class <- function(class, class.env){ assign("giveparent.inherit", class, envir = class.env) R6Class("palm_giveparent", inherit = class.env$giveparent.inherit, public = list( parent.locs = NULL, initialize = function(parent.locs, ...){ self$parent.locs <- parent.locs super$initialize(...) }, get.parents = function(pars){ if (!(ncol(self$parent.locs) == self$dim)){ stop("Incorrection dimensions of parent locations.") } self$parent.locs } )) } create.obj <- function(classes, points, lims, R, child.list, parent.locs, sibling.list, trace, start, bounds){ class <- base.class.R6 n.classes <- length(classes) class.env <- new.env() for (i in 1:n.classes){ set.class <- get(paste("set", classes[i], "class", sep = ".")) class <- set.class(class, class.env) } if (any(classes == "twocamerachild") & !any(classes == "thomas")){ stop("Analysis of two-camera surveys is only implemented for Thomas processes.") } if (!is.null(points) & !(is.matrix(points) | is.list(points))){ stop("The argument 'points' must be a matrix, or a list of matrices.") } if (is.matrix(points)){ points <- list(points) sibling.list <- list(sibling.list) } if (is.matrix(lims)){ lims <- list(lims) } class$new(points.list = points, lims.list = lims, R = R, child.list = child.list, parent.locs = parent.locs, sibling.list = sibling.list, trace = trace, classes = classes, start = start, bounds = bounds) } super <- NULL self <- NULL
saveWPX<-function(twpx, destdir="." ) { RDATES = rangedatetime(twpx) if(RDATES$max$yr == 0 & RDATES$min$yr == 0) { return() } fout1 = filedatetime(RDATES$min, 0) fout2 = paste(fout1,"RDATA", sep="." ) fout3 = paste(destdir, fout2, sep="/") save(file=fout2, twpx) invisible(fout2) }
freqs <- function(df, ..., wt = NULL, rel = FALSE, results = TRUE, variable_name = NA, plot = FALSE, rm.na = FALSE, title = NA, subtitle = NA, top = 20, abc = FALSE, save = FALSE, subdir = NA) { vars <- quos(...) weight <- enquo(wt) if (is.vector(df)) { values <- df <- data.frame(values = df) vars <- quos(values) } df <- as.data.frame(df) if (length(vars) == 0) { output <- freqs_df(df, plot = plot, save = save, subdir = subdir) return(output) } output <- df %>% group_by(!!!vars) %>% tally(wt = !!weight) %>% arrange(desc(.data$n)) %>% { if (!rel) ungroup(.) else . } %>% mutate(p = round(100 * .data$n / sum(.data$n), 2)) if (abc) { output <- output %>% arrange(!!!vars, desc(n)) %>% mutate(order = row_number()) } else { output <- output %>% arrange(desc(.data$n)) %>% mutate(order = row_number()) } output <- mutate(output, pcum = cumsum(.data$p)) if (!plot && !save) { if (results) { return(output) } else { invisible(return()) } } if (ncol(output) - 4 >= 4) { stop( paste( "Sorry, but trying to plot more than 3 features is as complex as it sounds.", "You should try another method to understand your analysis!" ) ) } obs_total <- sum(output$n) obs <- sprintf("Total Obs.: %s", formatNum(obs_total, 0)) weight_text <- ifelse((as_label(weight) != "NULL"), sprintf("(weighted by %s)", as_label(weight)), "" ) values <- unique(output[, length(vars)]) if (nrow(values) > top) { if (!is.na(top)) { output <- output %>% arrange(desc(.data$n)) %>% slice(1:top) message( sprintf( "Slicing the top %s (out of %s) values; use 'top' parameter to overrule.", top, nrow(values) ) ) note <- sprintf("[%s most frequent]", top) obs <- sprintf("Obs.: %s (out of %s)", formatNum(sum(output$n), 0), formatNum(obs_total, 0)) } } else { note <- "" } if (abc) note <- gsub("most frequent", "A-Z sorted values", note) reorder_within <- function(x, by, within, fun = mean, sep = "___", ...) { new_x <- paste(x, within, sep = sep) stats::reorder(new_x, by, FUN = fun) } scale_x_reordered <- function(..., sep = "___") { reg <- paste0(sep, ".+$") ggplot2::scale_x_discrete(labels = function(x) gsub(reg, "", x), ...) } plot <- ungroup(output) if (rm.na) plot <- plot[complete.cases(plot), ] plot$labels <- paste0(formatNum(plot$n, decimals = 0), " (", signif(plot$p, 4), "%)") plot$label_colours <- ifelse(plot$p > mean(range(plot$p)) * 0.9, "TRUE", "FALSE") lim <- 0.35 plot$label_hjust <- ifelse( plot$n < min(plot$n) + diff(range(plot$n)) * lim, -0.1, 1.05 ) plot$label_colours <- ifelse( plot$label_colours == "TRUE" & plot$label_hjust < lim, "FALSE", plot$label_colours ) variable <- colnames(plot)[1] if (ncol(output) - 3 == 2) { type <- 1 colnames(plot)[1] <- "names" p <- ggplot(plot, aes( x = reorder(.data$names, -.data$order), y = .data$n, label = .data$labels, fill = .data$p )) } else if (ncol(output) - 3 == 3) { type <- 2 facet_name <- colnames(plot)[2] colnames(plot)[1] <- "facet" colnames(plot)[2] <- "names" plot$facet <- suppressWarnings(replacefactor(plot$facet, NA, "NA")) p <- plot %>% ggplot(aes( x = reorder_within(.data$names, -.data$order, .data$facet), y = .data$n, label = .data$labels, fill = .data$p )) + scale_x_reordered() } else if (ncol(output) - 3 == 4) { type <- 3 facet_name1 <- colnames(plot)[2] facet_name2 <- colnames(plot)[3] colnames(plot)[1] <- "facet2" colnames(plot)[2] <- "facet1" colnames(plot)[3] <- "names" plot$facet2 <- suppressWarnings(replacefactor(plot$facet2, NA, "NA")) plot$facet1 <- suppressWarnings(replacefactor(plot$facet1, NA, "NA")) p <- plot %>% ggplot(aes( x = reorder_within(.data$names, .data$n, .data$facet2), y = .data$n, label = .data$labels, fill = .data$p )) + scale_x_reordered() } p <- p + geom_col(alpha = 0.95, width = 0.8, colour = "transparent") + geom_text(aes(hjust = .data$label_hjust, colour = .data$label_colours), size = 2.8) + coord_flip() + guides(colour = "none") + labs( x = NULL, y = NULL, fill = NULL, title = ifelse(is.na(title), paste("Frequencies and Percentages"), title), subtitle = ifelse(is.na(subtitle), paste( "Variable:", ifelse(!is.na(variable_name), variable_name, variable), note, weight_text ), subtitle ), caption = obs ) + scale_fill_gradient(low = "lightskyblue2", high = "navy") + theme_lares(pal = 4, which = "c", legend = "none", grid = "Xx") + scale_y_comma(position = "right", expand = c(0, 0), limits = c(0, 1.03 * max(output$n))) if (type == 2) { p <- p + facet_grid(as.character(.data$facet) ~ ., scales = "free", space = "free") + labs( subtitle = ifelse(is.na(subtitle), paste("Variables:", facet_name, "grouped by", variable, "\n", note, weight_text), subtitle ), caption = obs ) } else if (type >= 3) { if (length(unique(facet_name2)) > 3) { p <- freqs_plot(df, ..., top = top, rm.na = rm.na, title = title, subtitle = subtitle) return(p) } p <- p + facet_grid(as.character(.data$facet2) ~ as.character(.data$facet1), scales = "free") + labs( title = ifelse(is.na(title), "Frequencies and Percentages:", title), subtitle = ifelse(is.na(subtitle), paste( "Variables:", facet_name2, "grouped by", facet_name1, "[x] and", variable, "[y]", "\n", note, weight_text ), subtitle ), caption = obs ) } if (save) export_plot(p, "viz_freqs", vars, subdir = subdir) return(p) } freqs_df <- function(df, max = 0.9, min = 0.0, novar = TRUE, plot = FALSE, top = 30, quiet = FALSE, save = FALSE, subdir = NA) { if (is.vector(df)) { temp <- data.frame(values = df) ret <- freqs(temp, .data$values) return(ret) } df <- df[!unlist(lapply(df, is.list))] names <- lapply(df, function(x) length(unique(x))) unique <- as.data.frame(names) colnames(unique) <- names(names) which <- rownames(t(-sort(unique))) no <- names(unique)[unique > nrow(df) * max] if (length(no) > 0) { if (!quiet) { message(paste( length(no), "variables with more than", max, "variance exluded:", vector2text(no) )) } which <- which[!which %in% no] } if (novar) { no <- zerovar(df) if (length(no) > 0) { if (!quiet) { message(paste( length(no), "variables with no variance exluded:", vector2text(no) )) } which <- which[!which %in% no] } } if (length(which) > top) { no <- which[(top + 1):length(which)] if (!quiet) { message(paste( "Using the", top, "variables with less distinct categories.", length(no), "variables excluded:", vector2text(no) )) } which <- which[1:top] } if (length(which) > 0) { for (i in seq_along(which)) { if (i == 1) out <- NULL iter <- which[i] counter <- table(df[iter], useNA = "ifany") res <- data.frame( value = names(counter), count = as.vector(counter), col = iter ) %>% arrange(desc(.data$count)) out <- rbind(out, res) } out <- out %>% mutate(p = round(100 * .data$count / nrow(df), 2)) %>% mutate(value = ifelse(.data$p > min * 100, as.character(.data$value), "(HF)")) %>% group_by(.data$col, .data$value) %>% summarise(p = sum(.data$p), count = sum(.data$count)) %>% arrange(desc(.data$count)) %>% ungroup() } else { warning("No relevant information to display regarding your data.frame!") return(invisible(NULL)) } if (plot) { out <- out %>% mutate(value = ifelse(is.na(.data$value), "NA", as.character(.data$value))) %>% mutate(col = factor(.data$col, levels = which)) %>% mutate(label = ifelse(.data$p > 8, as.character(.data$value), "")) %>% group_by(.data$col) %>% mutate(alpha = log(.data$count)) %>% mutate(alpha = as.numeric(ifelse(.data$value == "NA", 0, .data$alpha))) %>% mutate(alpha = as.numeric(ifelse(is.infinite(.data$alpha), 0, .data$alpha))) p <- ggplot(out, aes( x = .data$col, y = .data$count, fill = .data$col, label = .data$label, colour = .data$col )) + geom_col(aes(alpha = .data$alpha), position = "fill", colour = "80000000", width = 0.95, size = 0.1 ) + geom_text(position = position_fill(vjust = .5), size = 3) + coord_flip() + labs(x = NULL, y = NULL, title = "Overall Values Frequencies") + scale_y_percent(expand = c(0, 0)) + guides(fill = "none", colour = "none", alpha = "none") + theme_lares(pal = 1) + theme( panel.background = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank() ) + geom_hline( yintercept = c(0.25, 0.5, 0.75), linetype = "dashed", color = "black", size = 0.5, alpha = 0.3 ) if (save) export_plot(p, "viz_freqs_df", subdir = subdir) return(p) } else { out <- select(out, .data$col, .data$value, .data$count, .data$p) %>% rename(n = .data$count, variable = .data$col) %>% group_by(.data$variable) %>% mutate(pcum = round(cumsum(.data$p), 2)) return(out) } } freqs_plot <- function(df, ..., top = 10, rm.na = FALSE, abc = FALSE, title = NA, subtitle = NA) { vars <- quos(...) if (length(vars) == 0) { return(freqs(df)) } aux <- df %>% freqs(!!!vars, rm.na = rm.na) %>% mutate_if(is.factor, as.character) %>% mutate_at(seq_along(vars), as.character) %>% mutate(order = ifelse(.data$order > top, "...", .data$order)) if ("..." %in% aux$order) { message(paste( "Showing", top, "most frequent values. Tail of", nrow(aux) - top, "other values grouped into one" )) } for (i in 1:(ncol(aux) - 4)) { aux[, i][aux$order == "...", ] <- "Tail" } aux <- aux %>% group_by(!!!vars, .data$order) %>% summarise_all(sum) %>% ungroup() vars_names <- colnames(aux)[1:(ncol(aux) - 4)] labels <- aux %>% mutate_all(as.character) %>% tidyr::gather("name", "value", 1:(ncol(aux) - 4)) %>% mutate(label = sprintf("%s: %s", .data$name, .data$value)) %>% mutate( n = as.integer(.data$n), pcum = as.numeric(.data$pcum), p = as.numeric(.data$p) ) %>% ungroup() %>% arrange(desc(.data$pcum)) if (is.na(title)) { title <- "Absolute Frequencies" } if (is.na(subtitle)) { subtitle <- paste("Grouped by", vector2text(vars_names, quotes = FALSE)) } mg <- 5 p1 <- aux %>% mutate(aux = ifelse(.data$order == "...", "grey", "black")) %>% mutate(order = paste0(.data$order, "\n", signif(as.numeric(.data$p), 2), "%")) %>% ggplot(aes(x = reorder(.data$order, .data$pcum), y = .data$n, label = .data$p)) + geom_col(aes(fill = .data$aux)) + scale_fill_manual(values = c("black", "grey55")) + labs(x = NULL, y = NULL, title = title, subtitle = subtitle) + scale_y_comma() + guides(fill = "none") + theme_lares() + theme(plot.margin = margin(mg, mg, 0, mg)) p2 <- labels %>% { if (abc) mutate(., n = -rank(.data$label)) else . } %>% mutate(label = ifelse(.data$order == "...", " Mixed Tail", .data$label)) %>% ggplot(aes( x = reorder(.data$order, .data$pcum), y = reorder(.data$label, .data$n), group = .data$pcum )) + geom_point(size = 4) + labs( x = NULL, y = NULL, caption = paste("Total observations:", formatNum(nrow(df), 0)) ) + guides(colour = "none") + theme_lares(which = "XY") + theme( axis.text.x = element_blank(), plot.margin = margin(0, mg, mg, mg) ) if (length(vars) > 1) { p2 <- p2 + geom_path() } p <- (p1 / p2) attr(p, "data") <- aux attr(p, "labels") <- labels return(p) } freqs_list <- function(df, var = NULL, wt = NULL, fx = "mean", rm.na = FALSE, min_elements = 1, limit = 10, limit_x = NA, limit_y = NA, tail = TRUE, size = 10, unique = TRUE, abc = FALSE, title = "", plot = TRUE) { dff <- df var_str <- as_label(enquo(var)) if (var_str != "NULL") { check_opts(var_str, colnames(df)) colnames(df)[colnames(df) == var_str] <- "which" } else { duos <- data.frame( count = unlist(lapply(df, function(x) length(unique(x)))) ) %>% filter(.data$count == 2) if (nrow(duos) == 0) { stop("Please, define a valid 'var' column or make sure to have binary/logical columns.") } duos <- rownames(duos) message(paste(">>> Binary columns detected:", v2t(duos))) which <- unlist(sapply(df[, duos], function(x) x == 1)) result <- NULL for (i in seq_len(nrow(df[, duos]))) { result <- c(result, v2t(colnames(df[, duos])[which[i, ]], quotes = FALSE)) } df$which <- result } wt_str <- as_label(enquo(wt)) if (wt_str == "NULL") wt_str <- NULL if (length(wt_str) > 0) { if (wt_str %in% colnames(df)) { colnames(df)[colnames(df) == wt_str] <- "wt" weights <- as.numeric(df$wt) } else { stop(sprintf("'%s' is not a valid weight column", wt_str)) } } else { weights <- 0 } if (is.list(df$which)) { df$which <- unlist(lapply(df$which, function(x) paste(x, collapse = ","))) } if (!any(grepl(",", df$which))) { stop(paste( "Your inputs may not be valid: no valid binary columns OR", "'var' does NOT contain commas nor is a list vector." )) } if (unique) { values <- strsplit(unlist(df$which), ",") values <- lapply(values, sort) values <- unlist(lapply(values, function(x) paste(x, collapse = ","))) } else { values <- df$which } vals <- data.frame(var = values, wt = weights) %>% filter(.data$var != "") %>% { if (rm.na) filter(., !is.na(.data$wt)) else . } %>% group_by(.data$var) %>% summarise( n = n(), wt = ifelse( fx == "mean", mean(.data$wt, na.rm = TRUE), ifelse(fx == "sum", sum(.data$wt, na.rm = TRUE), 1) ), .groups = "drop" ) %>% arrange(desc(.data$n)) %>% mutate(p = 100 * .data$n / sum(.data$n), order = row_number()) %>% data.frame() %>% ohe_commas(var) %>% as_tibble(.name_repair = "unique") %>% mutate(combs = rowSums(.[unlist(lapply(., is.logical))], na.rm = TRUE)) %>% filter(.data$combs >= min_elements) %>% select(-.data$combs) if (limit == 0) limit <- nrow(df) if (is.na(limit_x)) limit_x <- nrow(vals) if (is.na(limit_y)) limit_y <- nrow(vals) elements <- vals %>% tidyr::gather(.) %>% mutate(n = rep(vals$n, ncol(vals))) %>% mutate(wt = rep(vals$wt, ncol(vals))) %>% filter(.data$value == TRUE) %>% group_by(.data$key) %>% summarise( n = sum(.data$n), wt = ifelse( fx == "mean", mean(.data$wt, na.rm = TRUE), ifelse(fx == "sum", sum(.data$wt, na.rm = TRUE), 1) ), .groups = "drop" ) %>% { if (abc) arrange(., .data$key) else arrange(., desc(.data$n)) } %>% mutate(p = 100 * .data$n / nrow(df), order = row_number()) %>% mutate(key = as.factor(.data$key)) %>% mutate(label = sprintf("%s (%s)", .data$key, formatNum(.data$p, 0, pos = "%"))) %>% mutate(label = ifelse(.data$order > min(limit, limit_y), "...", .data$label)) %>% mutate(label = as.factor(.data$label)) tgthr <- vals %>% select(contains("var_")) %>% tidyr::gather("var") %>% mutate(var = factor(.data$var, levels = rev(elements$key))) %>% group_by(.data$var) %>% mutate(id = row_number(), order = row_number()) %>% mutate(label = sprintf(" filter(.data$value == TRUE) %>% mutate(label = ifelse(.data$id > min(limit, limit_x), "...", .data$label)) %>% ungroup() %>% mutate(var = ifelse( as.character(.data$var) %in% as.character(elements$key[elements$label != "..."]), as.character(.data$var), "..." )) %>% mutate(var = factor(.data$var, levels = rev(c(as.character(elements$key), "...")))) caption <- sprintf( "Observations: %s | Elements: %s", formatNum(sum(vals$n), 0), formatNum(sum(elements$n), 0) ) if (min_elements > 1) { caption <- v2t(c(caption, sprintf( "Excluding combinations with less than %s elements", min_elements )), quotes = FALSE, sep = "\n" ) } if (!tail) caption <- paste(caption, "Tail combinations suppressed from plot", sep = "\n") p1 <- tgthr %>% ggplot(aes( x = reorder(.data$label, .data$order), y = var, group = .data$label )) + geom_point(size = 3.5) + geom_path() + theme_lares(size = size, mg = -1, grid = "XY") + labs(x = "Combination rank", y = NULL, caption = caption) + theme( axis.text.y = element_blank(), plot.margin = margin(0, 0, 0, 0) ) + scale_x_discrete(position = "top") p2 <- elements %>% mutate(label = gsub("var_", "", .data$label)) %>% ggplot(aes( x = reorder(.data$label, -.data$order), y = -.data$n, fill = .data$wt )) + coord_flip() + geom_col() + labs(y = "Element Size", x = NULL) + theme_lares(size = size, mg = -1, grid = "X") + theme(plot.margin = margin(0, 0, 0, 0)) + scale_y_continuous( position = "right", labels = function(x) formatNum(abs(x), 0) ) + guides(fill = "none") p3 <- vals %>% mutate(var = ifelse(row_number() > min(limit, limit_x), "...", .data$var)) %>% { if (!tail) mutate(., n = ifelse(.data$var == "...", 1e-8, .data$n)) else . } %>% ggplot(aes( x = reorder(.data$var, .data$order), y = .data$n, fill = .data$wt )) + geom_col() + theme_lares(size = size, mg = -1, grid = "Y") + scale_y_continuous(labels = function(x) formatNum(abs(x), 0)) + labs( x = NULL, y = "Combination Size", fill = if (length(wt_str) > 0) { paste(str_to_title(fx), wt_str, sep = "\n") } else { NULL } ) + theme( axis.text.x = element_blank(), plot.margin = margin(0, 0, 0, 0) ) + scale_fill_continuous(guide = guide_colourbar(direction = "horizontal")) if (length(wt_str) == 0) p3 <- p3 + guides(fill = "none") layout <- " ABBB CBBB DEEE DEEE" p <- noPlot(title, size = 3.5) + p3 + guide_area() + p2 + p1 + plot_layout(design = layout) + plot_layout(guides = "collect") if (plot) plot(p) elements <- mutate(elements, key = gsub("var_", "", .data$key)) %>% rename("element" = .data$key) %>% select(-.data$label) vals <- mutate(vals, var = gsub("var_", "", .data$var)) %>% rename("combination" = .data$var) colnames(vals) <- gsub("var_", "", colnames(vals)) results <- list( plot = p, data = rename(df, "combination" = "which"), elements = elements, combinations = vals ) return(invisible(results)) }
Bass_spatial_main<-function(userpath,forcings){ cat('Bass bioenergetic individual model spatialized\n') cat(" \n") out_pre<-Bass_spatial_pre(userpath,forcings) sst=forcings[[2]] times=out_pre[[6]] ti=times[1] tf=times[2] Dates=as.Date(out_pre[[7]],"%d/%m/%Y") weight<-data.frame(matrix(0,ncol(sst),nrow=tf)) actual_ingestion<-data.frame(matrix(0,ncol(sst),nrow=tf)) potential_ingestion<-data.frame(matrix(0,ncol(sst),nrow=tf)) faeces_P<-data.frame(matrix(0,ncol(sst),nrow=tf)) faeces_L<-data.frame(matrix(0,ncol(sst),nrow=tf)) faeces_C<-data.frame(matrix(0,ncol(sst),nrow=tf)) waste_P<-data.frame(matrix(0,ncol(sst),nrow=tf)) waste_L<-data.frame(matrix(0,ncol(sst),nrow=tf)) waste_C<-data.frame(matrix(0,ncol(sst),nrow=tf)) Tfun_A<-data.frame(matrix(0,ncol(sst),nrow=tf)) Tfun_C<-data.frame(matrix(0,ncol(sst),nrow=tf)) anabolism<-data.frame(matrix(0,ncol(sst),nrow=tf)) catabolism<-data.frame(matrix(0,ncol(sst),nrow=tf)) NH4<-data.frame(matrix(0,ncol(sst),nrow=tf)) O2<-data.frame(matrix(0,ncol(sst),nrow=tf)) days_commercial<-matrix(0,ncol(sst),nrow=1) pb <- txtProgressBar(min = 0, max = ncol(sst), style = 3) for (i in 1:ncol(sst)) { forcings[[2]] = sst[1:tf,i] output<- Bass_spatial_loop(userpath, forcings) temp=output[[1]] weight[ti:tf,i]=temp temp=output[[2]] faeces_P[ti:tf,i]=temp[,1] faeces_L[ti:tf,i]=temp[,2] faeces_C[ti:tf,i]=temp[,3] temp=output[[3]] waste_P[ti:tf,i]=temp[,1] waste_L[ti:tf,i]=temp[,2] waste_C[ti:tf,i]=temp[,3] temp=output[[4]] potential_ingestion[ti:tf,i]=temp temp=output[[5]] actual_ingestion[ti:tf,i]=temp temp=output[[6]] Tfun_A[ti:tf,i]=temp[,1] Tfun_C[ti:tf,i]=temp[,2] temp=output[[7]] anabolism[ti:tf,i]=temp[,1] catabolism[ti:tf,i]=temp[,2] temp=output[[8]] NH4[ti:tf,i]=temp temp=output[[9]] O2[ti:tf,i]=temp temp=output[[10]] days_commercial[i]=temp setTxtProgressBar(pb, i) } close(pb) weight<-weight[-(1:(ti-1)),] actual_ingestion<-actual_ingestion[-(1:(ti-1)),] potential_ingestion<-potential_ingestion[-(1:(ti-1)),] faeces_P<-faeces_P[-(1:(ti-1)),] faeces_L<-faeces_L[-(1:(ti-1)),] faeces_C<-faeces_C[-(1:(ti-1)),] waste_P<-waste_P[-(1:(ti-1)),] waste_L<-waste_L[-(1:(ti-1)),] waste_C<-waste_C[-(1:(ti-1)),] Tfun_A<-Tfun_A[-(1:(ti-1)),] Tfun_C<-Tfun_C[-(1:(ti-1)),] anabolism<-anabolism[-(1:(ti-1)),] catabolism<-catabolism[-(1:(ti-1)),] NH4<-NH4[-(1:(ti-1)),] O2<-O2[-(1:(ti-1)),] write.table(weight,paste0(userpath,"/Bass_spatial/Outputs/Out_csv/weight.csv"),sep=',') write.table(potential_ingestion,paste0(userpath,"/Bass_spatial/Outputs/Out_csv/potential_ingestion.csv"),sep=',') write.table(actual_ingestion,paste0(userpath,"/Bass_spatial/Outputs/Out_csv/actual_ingestion.csv"),sep=',') write.table(faeces_P,paste0(userpath,"/Bass_spatial/Outputs/Out_csv/faeces_production_Proteins.csv"),sep=',') write.table(faeces_L,paste0(userpath,"/Bass_spatial/Outputs/Out_csv/faeces_production_Lipids.csv"),sep=',') write.table(faeces_C,paste0(userpath,"/Bass_spatial/Outputs/Out_csv/faeces_production_Carbohydrates.csv"),sep=',') write.table(waste_P,paste0(userpath,"/Bass_spatial/Outputs/Out_csv/wasted_feed_Proteins.csv"),sep=',') write.table(waste_L,paste0(userpath,"/Bass_spatial/Outputs/Out_csv/wasted_feed_Lipids.csv"),sep=',') write.table(waste_C,paste0(userpath,"/Bass_spatial/Outputs/Out_csv/wasted_Carbohydrates.csv"),sep=',') write.table(Tfun_A,paste0(userpath,"/Bass_spatial/Outputs/Out_csv/temperature_response_anabolism.csv"),sep=',') write.table(Tfun_C,paste0(userpath,"/Bass_spatial/Outputs/Out_csv/temperature_response_catabolism.csv"),sep=',') write.table(anabolism,paste0(userpath,"/Bass_spatial/Outputs/Out_csv/anabolic_rate.csv"),sep=',') write.table(catabolism,paste0(userpath,"/Bass_spatial/Outputs/Out_csv/catabolic_rate.csv"),sep=',') write.table(NH4,paste0(userpath,"/Bass_spatial/Outputs/Out_csv/NH4_release.csv"),sep=',') write.table(O2,paste0(userpath,"/Bass_spatial/Outputs/Out_csv/O2_consumption.csv"),sep=',') write.table(days_commercial,paste0(userpath,"/Bass_spatial/Outputs/Out_csv/days_to_commercial_size.csv"),sep=',') coord <- read.csv(paste0(userpath,"/Bass_spatial/Inputs/Spatial forcings//coordinates.csv")) coord <- coord[,-(1)] weight_map<-as.data.frame(cbind(t(coord),t(weight))) potential_ingestion_map<-as.data.frame(cbind(t(coord),t(potential_ingestion))) actual_ingestion_map<-as.data.frame(cbind(t(coord),t(actual_ingestion))) faeces_P_map<-as.data.frame(cbind(t(coord),t(faeces_P))) faeces_L_map<-as.data.frame(cbind(t(coord),t(faeces_L))) faeces_C_map<-as.data.frame(cbind(t(coord),t(faeces_C))) waste_P_map<-as.data.frame(cbind(t(coord),t(waste_P))) waste_L_map<-as.data.frame(cbind(t(coord),t(waste_L))) waste_C_map<-as.data.frame(cbind(t(coord),t(waste_C))) Tfun_A_map<-as.data.frame(cbind(t(coord),t(Tfun_A))) Tfun_C_map<-as.data.frame(cbind(t(coord),t(Tfun_C))) anabolism_map<-as.data.frame(cbind(t(coord),t(anabolism))) catabolism_map<-as.data.frame(cbind(t(coord),t(catabolism))) NH4_map<-as.data.frame(cbind(t(coord),t(NH4))) O2_map<-as.data.frame(cbind(t(coord),t(O2))) days_commercial_map<-as.data.frame(cbind(t(coord),t(days_commercial))) sp::coordinates(weight_map) <- ~V1+V2 sp::proj4string(weight_map)=sp::CRS(("+proj=longlat +datum=WGS84")) sp::gridded(weight_map) = TRUE weight_brick <- raster::brick(weight_map) weight_brick <- raster::setZ(weight_brick, as.Date(Dates[1])+ 0:(tf-ti)) raster::writeRaster(weight_brick, paste0(userpath,"/Bass_spatial/Outputs/Out_nc/weight.nc"), format="CDF", varname="weight", varunit= "g", longname="Weight of Dicentrarchus labrax estimated through the R RAC package developed by Baldan et al", zname="time", zunit="day", overwrite=T) sp::coordinates(potential_ingestion_map) <- ~V1+V2 sp::proj4string(potential_ingestion_map)=sp::CRS(("+proj=longlat +datum=WGS84")) sp::gridded(potential_ingestion_map) = TRUE potential_ingestion_brick <- brick(potential_ingestion_map) potential_ingestion_brick <- setZ(potential_ingestion_brick, as.Date(Dates[1])+ 0:(tf-ti)) writeRaster(potential_ingestion_brick, paste0(userpath,"/Bass_spatial/Outputs/Out_nc/potential_ingestion.nc"), format="CDF", varname="potential ingestion", varunit= "g/d", longname="Potential ingestion of Dicentrarchus labrax estimated through the R RAC package developed by Baldan et al", zname="time", zunit="day", overwrite=T) sp::coordinates(actual_ingestion_map) <- ~V1+V2 sp::proj4string(actual_ingestion_map)=sp::CRS(("+proj=longlat +datum=WGS84")) sp::gridded(actual_ingestion_map) = TRUE actual_ingestion_brick <- brick(actual_ingestion_map) actual_ingestion_brick <- setZ(actual_ingestion_brick, as.Date(Dates[1])+ 0:(tf-ti)) writeRaster(actual_ingestion_brick, paste0(userpath,"/Bass_spatial/Outputs/Out_nc/actual_ingestion.nc"), format="CDF", varname="actual ingestion", varunit= "g/d", longname="actual ingestion of Dicentrarchus labrax estimated through the R RAC package developed by Baldan et al", zname="time", zunit="day", overwrite=T) sp::coordinates(faeces_C_map) <- ~V1+V2 sp::proj4string(faeces_C_map)=sp::CRS(("+proj=longlat +datum=WGS84")) sp::gridded(faeces_C_map) = TRUE faeces_C_brick <- brick(faeces_C_map) faeces_C_brick <- setZ(faeces_C_brick, as.Date(Dates[1])+ 0:(tf-ti)) writeRaster(faeces_C_brick, paste0(userpath,"/Bass_spatial/Outputs/Out_nc/faeces_carbohydrates.nc"), format="CDF", varname="faeces carbohydrates", varunit= "g/d", longname="Carbohydrate in faeces produced by Dicentrarchus labrax estimated through the R RAC package developed by Baldan et al", zname="time", zunit="day", overwrite=T) sp::coordinates(faeces_P_map) <- ~V1+V2 sp::proj4string(faeces_P_map)=sp::CRS(("+proj=longlat +datum=WGS84")) sp::gridded(faeces_P_map) = TRUE faeces_P_brick <- brick(faeces_P_map) faeces_P_brick <- setZ(faeces_P_brick, as.Date(Dates[1])+ 0:(tf-ti)) writeRaster(faeces_P_brick, paste0(userpath,"/Bass_spatial/Outputs/Out_nc/faeces_proteins.nc"), format="CDF", varname="faeces proteins", varunit= "g/d", longname="Proteins in faeces produced by Dicentrarchus labrax estimated through the R RAC package developed by Baldan et al", zname="time", zunit="day", overwrite=T) sp::coordinates(faeces_L_map) <- ~V1+V2 sp::proj4string(faeces_L_map)=sp::CRS(("+proj=longlat +datum=WGS84")) sp::gridded(faeces_L_map) = TRUE faeces_L_brick <- brick(faeces_L_map) faeces_L_brick <- setZ(faeces_L_brick, as.Date(Dates[1])+ 0:(tf-ti)) writeRaster(faeces_L_brick, paste0(userpath,"/Bass_spatial/Outputs/Out_nc/faeces_lipids.nc"), format="CDF", varname="faeces lipids", varunit= "g/d", longname="Lipids in faeces produced by Dicentrarchus labrax estimated through the R RAC package developed by Baldan et al", zname="time", zunit="day", overwrite=T) sp::coordinates(waste_C_map) <- ~V1+V2 sp::proj4string(waste_C_map)=sp::CRS(("+proj=longlat +datum=WGS84")) sp::gridded(waste_C_map) = TRUE waste_C_brick <- brick(waste_C_map) waste_C_brick <- setZ(waste_C_brick, as.Date(Dates[1])+ 0:(tf-ti)) writeRaster(waste_C_brick, paste0(userpath,"/Bass_spatial/Outputs/Out_nc/wasted_feed_carbohydrates.nc"), format="CDF", varname="wasted carbohydrates", varunit= "g/d", longname="Carbohydrates wasted feed by Dicentrarchus labrax estimated through the R RAC package developed by Baldan et al", zname="time", zunit="day", overwrite=T) sp::coordinates(waste_L_map) <- ~V1+V2 sp::proj4string(waste_L_map)=sp::CRS(("+proj=longlat +datum=WGS84")) sp::gridded(waste_L_map) = TRUE waste_L_brick <- brick(waste_L_map) waste_L_brick <- setZ(waste_L_brick, as.Date(Dates[1])+ 0:(tf-ti)) writeRaster(waste_L_brick, paste0(userpath,"/Bass_spatial/Outputs/Out_nc/wasted_feed_lipids.nc"), format="CDF", varname="wasted lipids", varunit= "g/d", longname="Lipids wasted feed by Dicentrarchus labrax estimated through the R RAC package developed by Baldan et al", zname="time", zunit="day", overwrite=T) sp::coordinates(waste_P_map) <- ~V1+V2 sp::proj4string(waste_P_map)=sp::CRS(("+proj=longlat +datum=WGS84")) sp::gridded(waste_P_map) = TRUE waste_P_brick <- brick(waste_P_map) waste_P_brick <- setZ(waste_P_brick, as.Date(Dates[1])+ 0:(tf-ti)) writeRaster(waste_P_brick, paste0(userpath,"/Bass_spatial/Outputs/Out_nc/wasted_feed_proteins.nc"), format="CDF", varname="wasted proteins", varunit= "g/d", longname="Proteins wasted by Dicentrarchus labrax estimated through the R RAC package developed by Baldan et al", zname="time", zunit="day", overwrite=T) sp::coordinates(Tfun_A_map) <- ~V1+V2 sp::proj4string(Tfun_A_map)=sp::CRS(("+proj=longlat +datum=WGS84")) sp::gridded(Tfun_A_map) = TRUE Tfun_A_brick <- brick(Tfun_A_map) Tfun_A_brick <- setZ(Tfun_A_brick, as.Date(Dates[1])+ 0:(tf-ti)) writeRaster(Tfun_A_brick, paste0(userpath,"/Bass_spatial/Outputs/Out_nc/temperature_response_A.nc"), format="CDF", varname="Temperature response anabolism", varunit= "-", longname="temperature response function for anabolism of Dicentrarchus labrax estimated through the R RAC package developed by Baldan et al", zname="time", zunit="day", overwrite=T) sp::coordinates(Tfun_C_map) <- ~V1+V2 sp::proj4string(Tfun_C_map)=sp::CRS(("+proj=longlat +datum=WGS84")) sp::gridded(Tfun_C_map) = TRUE Tfun_C_brick <- brick(Tfun_C_map) Tfun_C_brick <- setZ(Tfun_C_brick, as.Date(Dates[1])+ 0:(tf-ti)) writeRaster(Tfun_C_brick, paste0(userpath,"/Bass_spatial/Outputs/Out_nc/temperature_response_C.nc"), format="CDF", varname="Temperature response catabolism", varunit= "-", longname="temperature response function for catabolism of Dicentrarchus labrax estimated through the R RAC package developed by Baldan et al", zname="time", zunit="day", overwrite=T) sp::coordinates(anabolism_map) <- ~V1+V2 sp::proj4string(anabolism_map)=sp::CRS(("+proj=longlat +datum=WGS84")) sp::gridded(anabolism_map) = TRUE anabolism_brick <- brick(anabolism_map) anabolism_brick <- setZ(anabolism_brick, as.Date(Dates[1])+ 0:(tf-ti)) writeRaster(anabolism_brick, paste0(userpath,"/Bass_spatial/Outputs/Out_nc/anabolic_rate.nc"), format="CDF", varname="Anabolic rate", varunit= "J/d", longname="anabolic rate for catabolism of Dicentrarchus labrax estimated through the R RAC package developed by Baldan et al", zname="time", zunit="day", overwrite=T) sp::coordinates(catabolism_map) <- ~V1+V2 sp::proj4string(catabolism_map)=sp::CRS(("+proj=longlat +datum=WGS84")) sp::gridded(catabolism_map) = TRUE catabolism_brick <- brick(catabolism_map) catabolism_brick <- setZ(catabolism_brick, as.Date(Dates[1])+ 0:(tf-ti)) writeRaster(catabolism_brick, paste0(userpath,"/Bass_spatial/Outputs/Out_nc/catabolic_rate.nc"), format="CDF", varname="Catabolic rate", varunit= "J/d", longname="catabolic rate for catabolism of Dicentrarchus labrax estimated through the R RAC package developed by Baldan et al", zname="time", zunit="day", overwrite=T) sp::coordinates(NH4_map) <- ~V1+V2 sp::proj4string(NH4_map)=sp::CRS(("+proj=longlat +datum=WGS84")) sp::gridded(NH4_map) = TRUE NH4_brick <- brick(NH4_map) NH4_brick <- setZ(NH4_brick, as.Date(Dates[1])+ 0:(tf-ti)) writeRaster(NH4_brick, paste0(userpath,"/Bass_spatial/Outputs/Out_nc/NH4_release.nc"), format="CDF", varname="NH4 release", varunit= "gN", longname="Ammonia released by Dicentrarchus labrax estimated through the R RAC package developed by Baldan et al", zname="time", zunit="day", overwrite=T) sp::coordinates(O2_map) <- ~V1+V2 sp::proj4string(O2_map)=sp::CRS(("+proj=longlat +datum=WGS84")) sp::gridded(O2_map) = TRUE O2_brick <- brick(O2_map) O2_brick <- setZ(O2_brick, as.Date(Dates[1])+ 0:(tf-ti)) writeRaster(O2_brick, paste0(userpath,"/Bass_spatial/Outputs/Out_nc/O2_consumption.nc"), format="CDF", varname="O2 consumption", varunit= "g", longname="Oxygen consumed by Dicentrarchus labrax estimated through the R RAC package developed by Baldan et al", zname="time", zunit="day", overwrite=T) sp::coordinates(days_commercial_map) <- ~V1+V2 sp::proj4string(days_commercial_map)=sp::CRS(("+proj=longlat +datum=WGS84")) sp::gridded(days_commercial_map) = TRUE days_commercial_raster = raster::raster(days_commercial_map) raster::projection(days_commercial_raster) = sp::CRS("+proj=longlat +datum=WGS84") writeRaster(days_commercial_raster,paste0(userpath,"/Bass_spatial/Outputs/Out_asc/days_to_commercial_size.asc"),format="ascii",overwrite=TRUE) }
pipeline <- function(...) { if(missing(...)) return(invisible(NULL)) dots <- match.call(expand.dots = FALSE)$... if(length(dots) == 1L) { dots <- .subset2(dots, 1L) if(class(dots) == "{") dots <- .subset(dots, -1L) else return(eval(dots, envir = parent.frame())) } expr <- Reduce(function(pl, p) as.call(list(pipe_op, pl, p)), dots) eval(expr, envir = parent.frame()) }
fitcml <- function(mt_ind, nrlist, x_mt, rtot, W, ngroups, gind, x_mtlist, NAstruc, g_NA, st.err, etaStart, gby){ cml <- function(eta){ beta <- as.vector(W %*% eta) beta.list <- split(beta,gind) beta.list1 <- beta.list betaNA <- mapply(function(x,y) {rbind(x,y)},beta.list1,NAstruc,SIMPLIFY=FALSE) Lg <- lapply(betaNA, function(betaNAmat) { beta.vec <- betaNAmat[1,] Lg.NA <- apply(matrix(betaNAmat[-1,],ncol=length(beta.vec)),1, function(NAvec) { beta_list <- as.list(split(beta.vec[NAvec==1],mt_ind[1:(length(beta.vec[NAvec==1]))])) parlist <- lapply(beta_list,exp) g_iter <- NULL K <- length(parlist) for (t in 1:(K-1)) { if (t==1) { gterm <- c(1,parlist[[t]]) }else { gterm <- g_iter g_iter <- NULL } parvek <- c(1,parlist[[t+1]]) h <- length(parvek) mt <- length(gterm) rtot1 <- h+mt-1 gtermvek <- rep(c(gterm,rep(0,h)),h) gtermvek <- gtermvek[-((length(gtermvek)-h+1):length(gtermvek))] gmat <- matrix(gtermvek,nrow=rtot1,ncol=h) emat <- matrix(rep(parvek,rep(rtot1,h)),ncol=h,nrow=rtot1) gmat_new <- gmat*emat g_iter <- rowSums(gmat_new) } Lg.NA <- as.vector(g_iter[2:(rtot+1)]) return(Lg.NA) }) }) L1 <- sum(mapply(function(x,z) { x[!is.na(z)]%*%na.exclude(z) },nrlist,lapply(Lg,log))) L2 <- sum(mapply("%*%",x_mtlist,beta.list1)) L1-L2 } eta <- etaStart if(!exists("fitctrl")) fitctrl <- "nlm" if(fitctrl == "nlm"){ suppressWarnings( fit <- nlm(cml, eta, hessian = st.err, iterlim = 5000L) ) } else if(fitctrl == "optim"){ suppressWarnings( fit <- optim(eta, cml, method = "BFGS", hessian = TRUE, control = list(maxit = 5000L)) ) fit$counts<-fit$counts[1] names(fit)<-c("estimate","minimum","iterations","code","message","hessian") } else stop("optimizer misspecified in fitctrl\n") fit }
pool_mi <- function( qhat, u=NULL, se=NULL, dfcom=1E7, method="smallsample" ) { CALL <- match.call() eps <- 1E-100 m <- length(qhat) k <- length(qhat[[1]] ) if ( ! is.null(se) ){ u <- list(1:m) for (ii in 1:m){ u[[ii]] <- diag( se[[ii]]^2 ) } } q1 <- qhat[[1]] names1 <- names(q1) qhat <- unlist(qhat) qhat <- matrix( qhat, nrow=m, ncol=k, byrow=TRUE ) qbar <- colMeans(qhat) u0 <- u u <- array( 0, dim=c(m,k,k) ) for (ii in 1:m){ u[ii,,] <- u0[[ii]] } ubar <- apply( u, c(2, 3), mean ) e <- qhat - matrix(qbar, nrow=m, ncol=k, byrow=TRUE) b <- ( t(e) %*% e )/(m - 1 + eps ) t <- ubar + (1 + 1/m) * b r <- (1 + 1/m) * diag(b/ubar) lambda <- (1 + 1/m) * diag(b/t) df <- mice_df(m, lambda, dfcom, method) fmi <- (r + 2/(df + 3))/(r + 1) names(lambda) <- names1 names(fmi) <- names1 names(df) <- names1 names(r) <- names1 names(qbar) <- names1 rownames(t) <- colnames(t) <- names1 tval <- qbar / sqrt( diag(t) ) pval <- 2 * stats::pt( - abs(tval), df=df ) names(tval) <- names(pval) <- names1 res <- list( nmis=NA, m=m, qhat=qhat, u=u, qbar=qbar, ubar=ubar, b=b, t=t, r=r, dfcom=dfcom, df=df, fmi=fmi, lambda=lambda, tval=tval, pval=pval, qhat_names=names1, call=CALL) class(res) <- "pool_mi" return(res) } mice_df <- function (m, lambda, dfcom, method) { eps <- 1E-4 lambda[lambda < eps ] <- eps dfold <- (m - 1 + eps )/lambda^2 dfobs <- (dfcom + 1)/(dfcom + 3) * dfcom * (1 - lambda) df <- dfold * dfobs/(dfold + dfobs) if (method !="smallsample"){ df <- dfold } return(df) } summary.pool_mi <-function(object, alpha=0.05, ...) { cat("Multiple imputation results:\nCall: ") print(object$call) out <- data.frame( results=object$qbar, se=sqrt(diag( object$t)) ) crit <- stats::qt(alpha/2,object$df, lower.tail=FALSE) out$t <- object$tval out$p <- object$pval out$"(lower"<- out$results-crit*out$se out$"upper)"<- out$results+crit*out$se out$"missInfo" <- paste0(round(100*object$fmi,1), " %") print(out, ...) } coef.pool_mi <- function(object, ...) { return(object$qbar) } vcov.pool_mi <- function(object, ...) { return(object$t) }
NULL render_email <- function(input, envir = parent.frame(), quiet = TRUE, output_options = list(), render_options = list()) { output_file <- tempfile(pattern = "email", fileext = ".html") on.exit(unlink(output_file), add = TRUE) output_options$self_contained <- TRUE do.call(rmarkdown::render, c( list( input = input, output_file = output_file, envir = envir, output_options = output_options, quiet = quiet ), render_options )) email_obj <- cid_images(output_file) email_obj } render_connect_email <- function(input, connect_footer = TRUE, envir = parent.frame(), quiet = TRUE, output_options = list(), render_options = list()) { if (is.null(output_options$connect_footer)) { output_options$connect_footer <- connect_footer } render_email(input, envir, quiet, output_options, render_options) }
get.my.logPosteriorAllPred <- function(model.Phi){ if(!any(model.Phi[1] %in% .CF.CT$model.Phi)){ stop("model.Phi is not found.") } ret <- eval(parse(text = paste("my.logPosteriorAllPred.", model.Phi[1], sep = ""))) assign("my.logPosteriorAllPred", ret, envir = .cubfitsEnv) ret } my.logPosteriorAllPred.lognormal <- function(phi, y, n, b, p.Curr, reu13.df = NULL){ nu.Phi <- p.Curr[1] sigma.Phi <- p.Curr[2] ret <- .cubfitsEnv$my.logdmultinomCodAllR(b, phi, y, n, reu13.df = reu13.df) + dlnorm(phi, nu.Phi, sigma.Phi, log = TRUE) ret } my.logPosteriorAllPred.logmixture <- function(phi, y, n, b, p.Curr, reu13.df = NULL){ paramlog <- p.Curr ret <- .cubfitsEnv$my.logdmultinomCodAllR(b, phi, y, n, reu13.df = reu13.df) + dlmixnorm(log(phi), paramlog, log = TRUE) ret }
groupBycoord <- function (data, x=1, k=3, which="rows", cex.labls=0.75){ categ=NULL res <- CA(data, graph=FALSE) ifelse(which=="rows", dtf <- data.frame(categ=row.names(res$row$coord), coord.x=res$row$coord[,x]), dtf <- data.frame(categ=row.names(res$col$coord), coord.x=res$col$coord[,x])) dtf <- dtf[order(dtf$coord.x),] Jclassif <- classInt::classIntervals(dtf$coord.x, k, style = "jenks") GoFtest <- jenks.tests(Jclassif) dtf$group <- as.factor(cut(dtf$coord.x, unique(Jclassif$brks), labels=FALSE, include.lowest=TRUE)) dotchart2(dtf$coord.x, labels=dtf$categ, groups=as.factor(paste0("group ", dtf$group)), lty=2, cex.labels=cex.labls, xlab=paste0("coordinate on the ", x, " dim."), main=paste0(ifelse(which=="rows", "Row", "Column"), " categories clustered into ", k, " groups (Jenks' natural breaks on the coord. of the selected dim.)"), cex.main=0.90, sub=paste0("Goodness of Fit: ", round(GoFtest[2],2)), cex.sub=0.7) colnames(dtf)[2] <- paste0("coord.", x,".Dim") return(subset(dtf, , -c(categ))) }
geometaLogger <- R6Class("geometaLogger", private = list( logger = function(type, text){ cat(sprintf("[geometa][%s] %s \n", type, text)) } ), public = list( INFO = function(text){private$logger("INFO", text)}, WARN = function(text){private$logger("WARN", text)}, ERROR = function(text){private$logger("ERROR", text)}, initialize = function(){} ) )
d13C.to.diffCaCi<- function(d13C, year, elevation, temp, frac = 0) { d13C.plant <- d13C d13C.atm <- CO2data[which(CO2data$yr == year),3] Ca <- CO2data[which(CO2data$yr == year),2] a <- 4.4 b <- 28 d <- frac D13C <- ((d13C.atm - (d13C.plant - d))/(1 + ((d13C.plant - d)/1000))) f <- 12 P0 <- 101325 Base.temp <- 298.15 ALR <- 0.0065 Grav <- 9.80665 R <- 8.3145 MWair <- 0.028963 Patm <- P0*(1.0 - ALR*elevation/Base.temp)^(Grav*MWair/(R*ALR)) deltaHa <- 37830 Temp.C <- temp Gammastar25 <- 4.332 Gammastar <- Gammastar25*Patm/P0*exp(1)^((deltaHa*((Temp.C+273.15)-298.15))/(R*(Temp.C+273.15)*298.15)) pCa <- (1.0e-6)*Ca*Patm Ci <- ((D13C-a+f*(Gammastar/pCa))/(b-a))*Ca diffCaCi <- Ca - Ci return(diffCaCi) }
NULL ggdensity <- function(data, x, y = "..density..", combine = FALSE, merge = FALSE, color = "black", fill = NA, palette = NULL, size = NULL, linetype = "solid", alpha = 0.5, title = NULL, xlab = NULL, ylab = NULL, facet.by = NULL, panel.labs = NULL, short.panel.labs = TRUE, add = c("none", "mean", "median"), add.params = list(linetype = "dashed"), rug = FALSE, label = NULL, font.label = list(size = 11, color = "black"), label.select = NULL, repel = FALSE, label.rectangle = FALSE, ggtheme = theme_pubr(), ...){ .opts <- list( combine = combine, merge = merge, color = color, fill = fill, palette = palette, linetype = linetype, size = size, alpha = alpha, title = title, xlab = xlab, ylab = ylab, facet.by = facet.by, panel.labs = panel.labs, short.panel.labs = short.panel.labs, add = add, add.params = add.params, rug = rug, label = label, font.label = font.label, label.select = label.select, repel = repel, label.rectangle = label.rectangle, ggtheme = ggtheme, ...) if(!missing(data)) .opts$data <- data if(!missing(x)) .opts$x <- x if(!missing(y)) .opts$y <- y .user.opts <- as.list(match.call(expand.dots = TRUE)) .user.opts[[1]] <- NULL for(opt.name in names(.opts)){ if(is.null(.user.opts[[opt.name]])) .opts[[opt.name]] <- NULL } .opts$fun <- ggdensity_core if(missing(ggtheme) & (!is.null(facet.by) | combine)) .opts$ggtheme <- theme_pubr(border = TRUE) if(missing(y)) .opts$y <- y if(missing(add.params)) .opts$add.params <- add.params p <- do.call(.plotter, .opts) if(.is_list(p) & length(p) == 1) p <- p[[1]] return(p) } ggdensity_core <- function(data, x, y = "..density..", color = "black", fill = NA, palette = NULL, size = NULL, linetype = "solid", alpha = 0.5, title = NULL, xlab = NULL, ylab = NULL, add = c("none", "mean", "median"), add.params = list(linetype = "dashed"), rug = FALSE, facet.by = NULL, ggtheme = theme_classic(), ...) { grouping.vars <- grp <- c(color, fill, linetype, size, alpha, facet.by) %>% unique() %>% intersect(colnames(data)) add <- match.arg(add) add.params <- .check_add.params(add, add.params, error.plot = "", data, color, fill, ...) if(is.null(add.params$size)) add.params$size <- size if(is.null(add.params$linetype)) add.params$linetype <- linetype p <- ggplot(data, create_aes(list(x = x, y = y))) p <- p + geom_exec(geom_density, data = data, color = color, fill = fill, size = size, linetype = linetype, alpha = alpha, ...) if(add %in% c("mean", "median")){ p <- p %>% .add_center_line(add = add, grouping.vars = grouping.vars, color = add.params$color, linetype = add.params$linetype, size = add.params$size) } if(rug) { grps <- c(color, fill, linetype, size, alpha) %>% unique() %>% intersect(colnames(data)) alpha <- ifelse(.is_empty(grps), 1, alpha) .args <- geom_exec(NULL, data = data, color = color, sides = "b", alpha = alpha) mapping <- .args$mapping mapping[["y"]] <- 0 option <- .args$option option[["mapping"]] <- create_aes(mapping) p <- p + do.call(geom_rug, option) } p <- ggpar(p, palette = palette, ggtheme = ggtheme, title = title, xlab = xlab, ylab = ylab,...) p }
getzstart = function(Q, mu, x, r, N) { v0_tilde = c(r, sqrt(1 - x[2:N])) v0_bar = v0_tilde - sum(mu * v0_tilde)/sum(mu) v0 = v0_bar/sqrt(sum(v0_bar^2 * mu)) zstart = sum(v0_bar * (-Q %*% v0_tilde) * mu)/sum(v0_bar^2 * mu) return(zstart) } eff.ini.seceig.general = function(Q, z0 = NULL, c1 = 1000, digit.thresh = 6) { if (sum(rowSums(Q) > 1e-10) > 0) stop("Input matrix Q should be a conservative matrix!") N = dim(Q)[1] Q1 = Q Q1[N, N] = c1 * Q[N, N] q1 = 1/diag(Q1) P = diag(q1, N) %*% Q1 + diag(1, N) if (z0 == "fixed") { lambda0Q1 = -eff.ini.maxeig.general(Q1, digit.thresh = digit.thresh, xi = 1)$z } x = rep(NA, N) x[1] = 1 x[2:N] = solve(diag(1, N - 1) - P[-1, -1], P[2:N, 1]) mu = rep(1, N) mu[2:N] = solve(t(Q)[-N, -1], -t(Q)[1:(N - 1), 1]) z0func = function(r) { return(getzstart(Q, mu, x, r, N)) } ropt = optim(0.9, z0func, method = c("L-BFGS-B"), lower = 0, upper = 1)$par v0_tilde = c(ropt, sqrt(1 - x[2:N])) v0_bar = v0_tilde - sum(mu * v0_tilde)/sum(mu) v0 = v0_bar/sqrt(sum(v0_bar^2 * mu)) zstart = switch(z0, fixed = lambda0Q1[length(lambda0Q1)], Auto = sum(v0_bar * (-Q %*% v0_tilde) * mu)/sum(v0_bar^2 * mu)) ray = ray.quot.seceig.general(Q = Q, mu = mu, v0_tilde = v0_bar, zstart = zstart, digit.thresh = digit.thresh) return(list(z = unlist(ray$z), v = ray$v, iter = ray$iter)) }
test3sr <- function(X,freq,verbose=TRUE,rounding=3){ n = dim(X)[1] K = dim(X)[2] result = data.frame(component = rep(NA,K-2),stat = rep(NA,K-2), p_val = rep(NA,K-2), signed_test = rep(NA,K-2), test_perf = rep(FALSE,K-2)) it3 = 2:(K-1) before = rep(0,n) after = apply(X,1,sum) - X[,1] i = 0 for (j in it3){ U = c(0,0,0,'None') i = i+1 result[i,1] = j before = before + X[,j-1] after = after - X[,j] select = X[,j] & (!((after == 0) & (freq < 0))) ind = which(select) nj = length(ind) if (nj > 0){ newORold = matrix(0,nrow = nj,ncol = 2) recORnev = newORold freqj = freq[ind] afreqj = abs(freqj) newORold[,1] = (before[ind]>0)*afreqj newORold[,2] = (before[ind]==0)*afreqj recORnev[,1] = (after[ind]!=0) recORnev[,2] = (after[ind]==0) cont_tab = t(newORold) %*% recORnev ML = apply(cont_tab,1,sum) MC = apply(cont_tab,2,sum) df = all(ML!=0) & all(MC!=0) if (df == TRUE) U = ind_test_22(cont_tab,2) } result[i,2] = U[1] result[i,3] = U[2] result[i,4] = U[3] result[i,5] = U[4] } stat = sum(as.numeric(result[,2])) stat = round(stat,rounding) dof = sum(result$test_perf != 'None') pval = 1 - stats::pchisq(stat,dof) pval = round(pval,rounding) tot_signed = round(sum(as.numeric(result$signed_test))/sqrt(length(result$signed_test)),rounding) if (verbose==TRUE) return(list(test3sr=c(stat=stat,df=dof,p_val=pval,sign_test = tot_signed),details=result)) if (verbose==FALSE) return(list(test3sr=c(stat=stat,df=dof,p_val=pval,sign_test = tot_signed))) }
plotDecisionBoundary <- function (theta, X, y, axLables = c("Exam 1 score","Exam 2 score"), legLabels = c('Admitted', 'Not admitted')) { plotData(X[,2:3], y,axLables,legLabels) if (dim(X)[2] <= 3) { plot_x <- cbind(min(X[,2] - 2), max(X[,2] + 2)) plot_y <- -1 / theta[3] * (theta[2] * plot_x + theta[1]) lines(plot_x, plot_y, col = "blue") } else { u <- seq(-1,1.5, length.out = 50) v <- seq(-1,1.5, length.out = 50) z <- matrix(0, length(u), length(v)) for (i in 1:length(u)) for (j in 1:length(v)) z[i,j] <- mapFeature(u[i], v[j]) %*% theta contour( u, v, z, xlab = 'Microchip Test 1', ylab = 'Microchip Test 2', levels = 0, lwd = 2, add = TRUE, drawlabels = FALSE, col = "green" ) mtext(paste("lambda = ",lambda), 3) } }
tmpdir <- tempdir() if (.Platform$OS.type == "windows") tmpdir <- normalizePath(tmpdir, winslash = "/") registry_tmp <- file.path(tmpdir, "registry") data_dir_tmp <- file.path(tmpdir, "data_dir") if (!file.exists(registry_tmp)){ dir.create (registry_tmp) } else { file.remove(list.files(registry_tmp, full.names = TRUE)) } if (!file.exists(data_dir_tmp)) dir.create(data_dir_tmp) regdir_envvar <- Sys.getenv("CORPUS_REGISTRY") Sys.setenv(CORPUS_REGISTRY = registry_tmp) library(cwbtools) library(data.table) teidir <- system.file(package = "cwbtools", "xml", "UNGA") teifiles <- list.files(teidir, full.names = TRUE) list.files(teidir) unga_data_dir_tmp <- file.path(data_dir_tmp, "unga") if (!file.exists(unga_data_dir_tmp)) dir.create(unga_data_dir_tmp) file.remove(list.files(unga_data_dir_tmp, full.names = TRUE)) UNGA <- CorpusData$new() UNGA metadata <- c( lp = "//legislativePeriod", session = "//titleStmt/sessionNo", date = "//publicationStmt/date", url = "//sourceDesc/url", src = "//sourceDesc/filetype" ) UNGA$import_xml(filenames = teifiles, meta = metadata) UNGA to_keep <- which(is.na(UNGA$metadata[["speaker"]])) UNGA$chunktable <- UNGA$chunktable[to_keep] UNGA$metadata <- UNGA$metadata[to_keep][, speaker := NULL] setnames(UNGA$metadata, old = c("sp_who", "sp_state", "sp_role"), new = c("who", "state", "role")) UNGA$tokenize(lowercase = FALSE, strip_punct = FALSE) UNGA UNGA$tokenstream s_attrs <- c("id", "who", "state", "role", "lp", "session", "date") UNGA$encode( registry_dir = registry_tmp, data_dir = unga_data_dir_tmp, corpus = "UNGA", encoding = "utf8", method = "R", p_attributes = "word", s_attributes = character(), compress = FALSE ) RcppCWB::cqp_initialize() id_peace <- RcppCWB::cl_str2id( corpus = "UNGA", p_attribute = "word", str = "peace", registry = registry_tmp ) cpos_peace <- RcppCWB::cl_id2cpos( corpus = "UNGA", p_attribute = "word", id = id_peace, registry = registry_tmp ) tab <- data.frame( i = unlist(lapply(1:length(cpos_peace), function(x) rep(x, times = 11))), cpos = unlist(lapply(cpos_peace, function(x) (x - 5):(x + 5))) ) tab[["id"]] <- RcppCWB::cl_cpos2id( corpus = "UNGA", p_attribute = "word", cpos = tab[["cpos"]], registry = registry_tmp ) tab[["str"]] <- RcppCWB::cl_id2str( corpus = "UNGA", p_attribute = "word", id = tab[["id"]], registry = registry_tmp ) peace_context <- split(tab[["str"]], as.factor(tab[["i"]])) peace_context <- unname(sapply(peace_context, function(x) paste(x, collapse = " "))) head(peace_context) austen_data_dir_tmp <- file.path(data_dir_tmp, "austen") if (!file.exists(austen_data_dir_tmp)) dir.create(austen_data_dir_tmp) file.remove(list.files(austen_data_dir_tmp, full.names = TRUE)) Austen <- CorpusData$new() books <- janeaustenr::austen_books() tbl <- tidytext::unnest_tokens(books, word, text, to_lower = FALSE) Austen$tokenstream <- as.data.table(tbl) Austen$tokenstream[, stem := SnowballC::wordStem(tbl[["word"]], language = "english")] Austen$tokenstream[, cpos := 0L:(nrow(tbl) - 1L)] cpos_max_min <- function(x) list(cpos_left = min(x[["cpos"]]), cpos_right = max(x[["cpos"]])) Austen$metadata <- Austen$tokenstream[, cpos_max_min(.SD), by = book] Austen$metadata[, book := as.character(book)] setcolorder(Austen$metadata, c("cpos_left", "cpos_right", "book")) Austen$tokenstream[, book := NULL] setcolorder(Austen$tokenstream, c("cpos", "word", "stem")) Austen$tokenstream Austen$encode( corpus = "AUSTEN", encoding = "utf8", p_attributes = c("word", "stem"), s_attributes = "book", registry_dir = registry_tmp, data_dir = austen_data_dir_tmp, method = "R", compress = FALSE ) RcppCWB::cqp_reset_registry(registry = registry_tmp) corpus <- "AUSTEN" token <- "pride" p_attr <- "word" id <- RcppCWB::cl_str2id(corpus = corpus, p_attribute = p_attr, str = token, registry = registry_tmp) cpos <- RcppCWB::cl_id2cpos(corpus = corpus, p_attribute = p_attr, id = id, registry = registry_tmp) count <- length(cpos) count library(tm) reut21578 <- system.file("texts", "crude", package = "tm") reuters.tm <- VCorpus(DirSource(reut21578), list(reader = readReut21578XMLasPlain)) library(tidytext) reuters.tbl <- tidy(reuters.tm) reuters.tbl reuters.tbl[["topics_cat"]] <- sapply( reuters.tbl[["topics_cat"]], function(x) paste(x, collapse = "|") ) reuters.tbl[["places"]] <- sapply( reuters.tbl[["places"]], function(x) paste(x, collapse = "|") ) Reuters <- CorpusData$new() reuters_data_dir_tmp <- file.path(data_dir_tmp, "reuters") if (!file.exists(reuters_data_dir_tmp)) dir.create(reuters_data_dir_tmp) file.remove(list.files(reuters_data_dir_tmp, full.names = TRUE)) Reuters$chunktable <- data.table(reuters.tbl[, c("id", "text")]) Reuters$metadata <- data.table(reuters.tbl[,c("id", "topics_cat", "places")]) Reuters Reuters$tokenize() Reuters$tokenstream Reuters$encode( corpus = "REUTERS", encoding = "utf8", p_attributes = "word", s_attributes = c("topics_cat", "places"), registry_dir = registry_tmp, data_dir = data_dir_tmp, method = "R", compress = FALSE ) RcppCWB::cqp_reset_registry(registry = registry_tmp) id <- RcppCWB::cl_str2id(corpus = "REUTERS", p_attribute = "word", str = "oil", registry = registry_tmp) cpos <- RcppCWB::cl_id2cpos(corpus = "REUTERS", p_attribute = "word", id = id, registry = registry_tmp) count <- length(cpos) count unlink(registry_tmp, recursive = TRUE) unlink(data_dir_tmp, recursive = TRUE) Sys.setenv(CORPUS_REGISTRY = regdir_envvar)
NIblcontrib<-function(obj,lambda,X,nobj,ENV) { naidx<-1-as.numeric(obj$notnaidx) ncat<-ENV$ncat R<-matrix(rep(naidx,ncat^ENV$ncomp),nrow=ncat^ENV$ncomp,byrow=T) XX<-X if (ENV$MISmod=="obj"){ if (ENV$MISalpha){ RBstar<-R %*%abs(pcdesign(nobj)) XX<-cbind(X,RBstar[,ENV$Malph]) } if (ENV$MISbeta){ YRBstar<-do.call(cbind,lapply(1:(nobj),function(i) RBstar[,i]*ENV$Y[,i])) XX<-cbind(X,RBstar[,ENV$Malph],YRBstar[,ENV$Mbeta]) } } if (ENV$MISmod=="comp"){ if (ENV$MISalpha) XX<-cbind(X,R[,ENV$Malph]) if (ENV$MISbeta){ YR<-ENV$Y[,ENV$Mbeta] * R[,ENV$Mbeta] XX<-cbind(X,R[,ENV$Malph],YR) } } if (ENV$MIScommon) { r<-sum(naidx) XX<-cbind(X,r) } if(ENV$undec) XX<-cbind(XX,ENV$U) if(ENV$ia) XX<-cbind(XX,ENV$XI) patt.all <- exp(XX %*% lambda) patt<-tapply(patt.all,obj$s,sum) patt<-patt/ENV$nrm.all ll<-sum(obj$counts*log(patt)) p.cnts<-obj$counts/sum(obj$counts) fl<-sum(log(p.cnts[p.cnts>0])*obj$counts[obj$counts>0]) RET<-list(ll=ll,fl=fl) RET }
solve_unipoly <- function(mpoly, real_only = FALSE) { mpoly <- reorder(mpoly) degs <- vapply(mpoly, function(term) { if(length(term) == 1) return(0L) term[[1]] }, double(1)) coefs <- sapply(mpoly, `[[`, "coef") coef_vec <- rep(0L, degs[1]+1) names(coef_vec) <- 0:degs[1] for(k in 1:length(mpoly)) coef_vec[as.character(degs[k])] <- coefs[k] solns <- polyroot(coef_vec) if (real_only) { is.real <- function(x) Im(x) == 0 solns <- Re(Filter(is.real, solns)) } solns }
plot.simsurvdata <- function(x, ...) { n <- x$sample.size if (n <= 25) obs.plot <- x$sample.size else obs.plot <- 25 yindex <- matrix(rep(seq_len(obs.plot), 2), ncol = 2, byrow = FALSE) tindex <- matrix(c(rep(0, obs.plot), x$survdata$time[1:obs.plot]), ncol = 2, byrow = FALSE) graphics::plot(tindex[1, ], yindex[1, ], type ="l", ylim = c(0, obs.plot + 10), xlim = c(0, max(x$survdata$time[1:obs.plot])), ylab = "", xlab = "time") if(x$survdata$delta[1:obs.plot][1] == 1) { graphics::lines(tindex[1, 2], yindex[1,2], type ="p", pch = 19) } else { graphics::lines(tindex[1, 2], yindex[1,2], type ="p", pch = 4, lwd = 2) } if (obs.plot > 1) { for (i in 2:obs.plot) { graphics::lines(tindex[i, ], yindex[i, ], type = "l") if(x$survdata$delta[1:obs.plot][i] == 1) { graphics::lines(tindex[i, 2], yindex[i, 2], type ="p", pch = 19) } else { graphics::lines(tindex[i, 2], yindex[i,2], type ="p", pch = 4, lwd = 2) } } } graphics::legend("topright", c("Right censored", "Event occured"), lty = c("blank", "blank"), pch = c(4, 19), lwd = c(2, 1), bty = "n") }
dbHasCompleted_MariaDBResult <- function(res, ...) { result_has_completed(res@ptr) } setMethod("dbHasCompleted", "MariaDBResult", dbHasCompleted_MariaDBResult)
normTail <- function(m=0, s=1, L=NULL, U=NULL, M=NULL, df=1000, curveColor=1, border=1, col=' if(is.null(xlim)[1]){ xlim <- m + c(-1,1)*3.5*s } temp <- diff(range(xlim)) x <- seq(xlim[1] - temp/4, xlim[2] + temp/4, length.out=detail) y <- dt((x-m)/s, df)/s if(is.null(ylim)[1]){ ylim <- range(c(0,y)) } plot(x, y, type='l', xlim=xlim, ylim=ylim, xlab=xlab, ylab=ylab, axes=FALSE, col=curveColor, ...) if(!is.null(L[1])){ these <- (x <= L) X <- c(x[these][1], x[these], rev(x[these])[1]) Y <- c(0, y[these], 0) polygon(X, Y, border=border, col=col) } if(!is.null(U[1])){ these <- (x >= U) X <- c(x[these][1], x[these], rev(x[these])[1]) Y <- c(0, y[these], 0) polygon(X, Y, border=border, col=col) } if(all(!is.null(M[1:2]))){ these <- (x >= M[1] & x <= M[2]) X <- c(x[these][1], x[these], rev(x[these])[1]) Y <- c(0, y[these], 0) polygon(X, Y, border=border, col=col) } if(axes == 1 || axes > 2){ if(xLab[1]=='symbol'){ xAt <- m + (-3:3)*s xLab <- expression(mu-3*sigma, mu-2*sigma, mu-sigma, mu, mu+sigma, mu+2*sigma, mu+3*sigma) } else if(xLab[1] != 'number'){ stop('Argument "xLab" not recognized.\n') } else { temp <- seq(xAxisIncr, max(abs(xlim-m))/s, xAxisIncr)*s xAt <- m + c(-temp, 0, temp) xLab <- round(xAt, digits=digits) } } if(axes > 2){ axis(1, at=xAt, labels=xLab, cex.axis=cex.axis) buildAxis(2, c(y,0), n=3, nMax=3, cex.axis=cex.axis) } else if(axes > 1){ buildAxis(2, c(y,0), n=3, nMax=3, cex.axis=cex.axis) } else if(axes > 0){ axis(1, at=xAt, labels=xLab, cex.axis=cex.axis) } abline(h=0) } chiTail <- function(U=NULL, df = 10, curveColor=1, border=1, col=" temp <- diff(range(xlim)) x <- seq(xlim[1] - temp/4, xlim[2] + temp/4, length.out=detail) y <- dchisq(x, df) ylim <- range(c(0,y)) plot(x, y, type='l', xlim=xlim, ylim=ylim, axes=FALSE, col=curveColor, xlab = "", ylab = "") these <- (x >= U) X <- c(x[these][1], x[these], rev(x[these])[1]) Y <- c(0, y[these], 0) polygon(X, Y, border=border, col=col) abline(h=0) axis(1, at = c(0,U), label = c(NA,round(U,4))) } FTail <- function(U=NULL, df_n=100, df_d = 100, curveColor=1, border=1, col=" if(U <= 5){xlim <- c(0,5)} if(U > 5){xlim <- c(0,U+0.01*U)} temp <- diff(range(xlim)) x <- seq(xlim[1] - temp/4, xlim[2] + temp/4, length.out=detail) y <- df(x, df_n, df_d) ylim <- range(c(0,y)) plot(x, y, type='l', xlim=xlim, ylim=ylim, axes=FALSE, col=curveColor, xlab = "", ylab = "") these <- (x >= U) X <- c(x[these][1], x[these], rev(x[these])[1]) Y <- c(0, y[these], 0) polygon(X, Y, border=border, col=col) abline(h=0) axis(1, at = c(0,U), label = c(NA,round(U,4))) }
`calc.foldrange` <- function(n,lower,upper,conf.level=.95){ alpha<-1-conf.level s.t<- (sqrt(n)*(log10(upper)-log10(lower)))/(2*qt(1-alpha/2,n-1)) s.z<-(sqrt(n)*(log10(upper)-log10(lower)))/(2*qnorm(1-alpha/2)) range.t<- 10^(( qnorm(1-alpha/2) - qnorm(alpha/2) )*s.t ) range.z<- 10^(( qnorm(1-alpha/2) - qnorm(alpha/2) )*s.z ) col.names<-c("n",paste("lower",100*conf.level,"% cl"), paste("upper",100*conf.level,"% cl"), "standard deviation (log10 scale) by t", "standard deviation (log10 scale) by Z", paste(100*conf.level,"% fold-range, s estimated by t"), paste(100*conf.level,"% fold-range, s estimated by Z")) out<-data.frame(n=n,lower=lower,upper=upper,s.byt=s.t,s.byz=s.z, foldrange.byt=range.t,foldrange.byz=range.z) out }
simpleMH <- function(f, inits, theta.cov, max.iter, coda = FALSE, ...) { theta_samples <- matrix(NA_real_, nrow = max.iter, ncol = length(inits)) log_p <- rep_len(NA_real_, max.iter) theta_now <- inits p_theta <- f(theta_now, ...) p_samples <- rep(0, max.iter) p_theta_now <- p_theta log_p[1] <- p_theta_now theta_samples[1, ] <- theta_now for (m in 2:max.iter) { theta_new <- rmvnorm(n = 1, mean = theta_now, sigma = theta.cov) names(theta_new) <- names(inits) p_theta <- f(theta_new, ...) p_theta_new <- p_theta p_samples[m] <- p_theta_new a <- exp(p_theta_new - p_theta_now) z <- runif(1) if (isTRUE(z < a)) { theta_now <- theta_new p_theta_now <- p_theta_new } theta_samples[m, ] <- theta_now log_p[m] <- p_theta_now } if (is.null(names(inits))) { colnames(theta_samples) <- paste0("para_", seq_along(inits)) } else { colnames(theta_samples) <- names(inits) } res <- list(samples = theta_samples, log.p = log_p) if (coda) { if (!requireNamespace("coda", quietly = TRUE)) { stop( "Package 'coda' needed for to create coda objects. ", "Please install it or use `coda = TRUE`.", call. = FALSE ) } res$samples <- coda::as.mcmc(res$samples) } return(res) }
power.t.test <- function(n=NULL, delta=NULL, sd=1, sig.level=0.05, power=NULL, type=c("two.sample", "one.sample", "paired"), alternative=c("two.sided", "one.sided"), strict=FALSE, tol = .Machine$double.eps^0.25) { if ( sum(sapply(list(n, delta, sd, power, sig.level), is.null)) != 1 ) stop("exactly one of 'n', 'delta', 'sd', 'power', and 'sig.level' must be NULL") if(!is.null(sig.level) && !is.numeric(sig.level) || any(0 > sig.level | sig.level > 1)) stop("'sig.level' must be numeric in [0, 1]") type <- match.arg(type) alternative <- match.arg(alternative) tsample <- switch(type, one.sample = 1, two.sample = 2, paired = 1) force(tsample) tside <- switch(alternative, one.sided = 1, two.sided = 2) if (tside == 2 && !is.null(delta)) delta <- abs(delta) p.body <- if (strict && tside == 2) quote({ nu <- (n - 1) * tsample qu <- qt(sig.level/tside, nu, lower.tail = FALSE) pt( qu, nu, ncp = sqrt(n/tsample) * delta/sd, lower.tail = FALSE) + pt(-qu, nu, ncp = sqrt(n/tsample) * delta/sd, lower.tail = TRUE) }) else quote({nu <- (n - 1) * tsample pt(qt(sig.level/tside, nu, lower.tail = FALSE), nu, ncp = sqrt(n/tsample) * delta/sd, lower.tail = FALSE)}) if (is.null(power)) power <- eval(p.body) else if (is.null(n)) n <- uniroot(function(n) eval(p.body) - power, c(2, 1e7), tol=tol, extendInt = "upX")$root else if (is.null(sd)) sd <- uniroot(function(sd) eval(p.body) - power, delta * c(1e-7, 1e+7), tol=tol, extendInt = "downX")$root else if (is.null(delta)) delta <- uniroot(function(delta) eval(p.body) - power, sd * c(1e-7, 1e+7), tol=tol, extendInt = "upX")$root else if (is.null(sig.level)) sig.level <- uniroot(function(sig.level) eval(p.body) - power, c(1e-10, 1-1e-10), tol=tol, extendInt = "yes")$root else stop("internal error", domain = NA) NOTE <- switch(type, paired = "n is number of *pairs*, sd is std.dev. of *differences* within pairs", two.sample = "n is number in *each* group", NULL) METHOD <- paste(switch(type, one.sample = "One-sample", two.sample = "Two-sample", paired = "Paired"), "t test power calculation") structure(list(n=n, delta=delta, sd=sd, sig.level=sig.level, power=power, alternative=alternative, note=NOTE, method=METHOD), class="power.htest") } power.prop.test <- function(n=NULL, p1=NULL, p2=NULL, sig.level=0.05, power=NULL, alternative=c("two.sided", "one.sided"), strict=FALSE, tol = .Machine$double.eps^0.25) { if ( sum(sapply(list(n, p1, p2, power, sig.level), is.null)) != 1 ) stop("exactly one of 'n', 'p1', 'p2', 'power', and 'sig.level' must be NULL") if(!is.null(sig.level) && !is.numeric(sig.level) || any(0 > sig.level | sig.level > 1)) stop("'sig.level' must be numeric in [0, 1]") alternative <- match.arg(alternative) tside <- switch(alternative, one.sided = 1, two.sided = 2) p.body <- if (strict && tside == 2) quote({ qu <- qnorm(sig.level/tside, lower.tail = FALSE) d <- abs(p1 - p2) q1 <- 1 - p1 q2 <- 1 - p2 pbar <- (p1 + p2)/2 qbar <- 1 - pbar v1 <- p1 * q1 v2 <- p2 * q2 vbar <- pbar * qbar pnorm((sqrt(n)*d - qu * sqrt(2 * vbar) ) / sqrt(v1 + v2)) + pnorm((sqrt(n)*d + qu * sqrt(2 * vbar) ) / sqrt(v1 + v2), lower.tail=FALSE) }) else quote(pnorm((sqrt(n) * abs(p1 - p2) - (qnorm(sig.level/tside, lower.tail = FALSE) * sqrt((p1 + p2) * (1 - (p1 + p2)/2)))) / sqrt(p1 * (1 - p1) + p2 * (1 - p2)))) if (is.null(power)) power <- eval(p.body) else if (is.null(n)) n <- uniroot(function(n) eval(p.body) - power, c(1,1e7), tol=tol, extendInt = "upX")$root else if (is.null(p1)) { p1 <- uniroot(function(p1) eval(p.body) - power, c(0,p2), tol=tol, extendInt = "yes")$root if(p1 < 0) warning("No p1 in in [0, p2] can be found to achieve the desired power") } else if (is.null(p2)) { p2 <- uniroot(function(p2) eval(p.body) - power, c(p1,1), tol=tol, extendInt = "yes")$root if(p2 > 1) warning("No p2 in in [p1, 1] can be found to achieve the desired power") } else if (is.null(sig.level)) { sig.level <- uniroot(function(sig.level) eval(p.body) - power, c(1e-10, 1-1e-10), tol=tol, extendInt = "upX")$root if(sig.level < 0 || sig.level > 1) warning("No significance level [0, 1] can be found to achieve the desired power") } else stop("internal error", domain = NA) structure(list(n=n, p1=p1, p2=p2, sig.level=sig.level, power=power, alternative=alternative, note = "n is number in *each* group", method = "Two-sample comparison of proportions power calculation"), class="power.htest") } print.power.htest <- function(x, digits = getOption("digits"), ...) { cat("\n ", x$method, "\n\n") note <- x$note x[c("method", "note")] <- NULL cat(paste(format(names(x), width = 15L, justify = "right"), format(x, digits=digits), sep = " = "), sep = "\n") if(!is.null(note)) cat("\n", "NOTE: ", note, "\n\n", sep = "") else cat("\n") invisible(x) }
resample_idx <- readRDS(test_path("data/test_autoplot.rds")) two_class_resamples <- dplyr::bind_rows( lapply(resample_idx, function(idx) two_class_example[idx,]), .id = "Resample" ) %>% dplyr::group_by(Resample) hpc_cv2 <- dplyr::filter(hpc_cv, Resample %in% c("Fold06", "Fold07", "Fold08", "Fold09", "Fold10")) %>% dplyr::as_tibble() %>% dplyr::group_by(Resample) %>% dplyr::arrange(as.character(obs)) %>% dplyr::ungroup() test_that("ROC Curve - two class", { res <- roc_curve(two_class_example, truth, Class1) expect_error(.plot <- ggplot2::autoplot(res), NA) expect_s3_class(.plot, "gg") .plot_data <- ggplot2::ggplot_build(.plot) expect_equal(1 - res$specificity, .plot_data$data[[1]]$x) expect_equal(res$sensitivity, .plot_data$data[[1]]$y) expect_equal(.plot_data$data[[2]]$intercept, 0) expect_equal(.plot_data$data[[2]]$slope, 1) }) test_that("ROC Curve - two class, with resamples", { res <- roc_curve(two_class_resamples, truth, Class1) expect_error(.plot <- ggplot2::autoplot(res), NA) expect_s3_class(.plot, "gg") .plot_data <- ggplot2::ggplot_build(.plot) expect_equal(1 - res$specificity, .plot_data$data[[1]]$x) expect_equal(res$sensitivity, .plot_data$data[[1]]$y) expect_equal(length(unique(.plot_data$data[[1]]$colour)), 10) }) test_that("ROC Curve - multi class", { res <- roc_curve(hpc_cv2, obs, VF:L) expect_error(.plot <- ggplot2::autoplot(res), NA) expect_s3_class(.plot, "gg") expect_true(".level" %in% colnames(res)) .plot_data <- ggplot2::ggplot_build(.plot) expect_equal(nrow(.plot_data$data[[2]]), 4) }) test_that("ROC Curve - multi class, with resamples", { res <- roc_curve(dplyr::group_by(hpc_cv2, Resample), obs, VF:L) expect_error(.plot <- ggplot2::autoplot(res), NA) expect_s3_class(.plot, "gg") expect_true(".level" %in% colnames(res)) expect_true("Resample" %in% colnames(res)) .plot_data <- ggplot2::ggplot_build(.plot) expect_equal(nrow(.plot_data$data[[2]]), 4) }) test_that("PR Curve - two class", { res <- pr_curve(two_class_example, truth, Class1) expect_error(.plot <- ggplot2::autoplot(res), NA) expect_s3_class(.plot, "gg") .plot_data <- ggplot2::ggplot_build(.plot) expect_equal(res$recall, .plot_data$data[[1]]$x) expect_equal(res$precision, .plot_data$data[[1]]$y) }) test_that("PR Curve - two class, with resamples", { res <- pr_curve(two_class_resamples, truth, Class1) expect_error(.plot <- ggplot2::autoplot(res), NA) expect_s3_class(.plot, "gg") .plot_data <- ggplot2::ggplot_build(.plot) expect_equal(res$recall, .plot_data$data[[1]]$x) expect_equal(res$precision, .plot_data$data[[1]]$y) expect_equal(length(unique(.plot_data$data[[1]]$colour)), 10) }) test_that("PR Curve - multi class", { res <- pr_curve(hpc_cv2, obs, VF:L) expect_error(.plot <- ggplot2::autoplot(res), NA) expect_s3_class(.plot, "gg") expect_true(".level" %in% colnames(res)) .plot_data <- ggplot2::ggplot_build(.plot) expect_equal(length(unique(.plot_data$data[[1]]$PANEL)), 4) }) test_that("PR Curve - multi class, with resamples", { res <- pr_curve(dplyr::group_by(hpc_cv2, Resample), obs, VF:L) expect_error(.plot <- ggplot2::autoplot(res), NA) expect_s3_class(.plot, "gg") expect_true(".level" %in% colnames(res)) expect_true("Resample" %in% colnames(res)) .plot_data <- ggplot2::ggplot_build(.plot) expect_equal(length(unique(.plot_data$data[[1]]$PANEL)), 4) expect_equal(length(unique(.plot_data$data[[1]]$colour)), 5) }) test_that("Gain Curve - two class", { res <- gain_curve(two_class_example, truth, Class1) expect_error(.plot <- ggplot2::autoplot(res), NA) expect_s3_class(.plot, "gg") .plot_data <- ggplot2::ggplot_build(.plot) expect_equal(res$.percent_tested, .plot_data$data[[2]]$x) expect_equal(res$.percent_found, .plot_data$data[[2]]$y) expect_equal(.plot_data$data[[1]]$x[2], 51.6) }) test_that("Gain Curve - two class, with resamples", { res <- gain_curve(two_class_resamples, truth, Class1) expect_error(.plot <- ggplot2::autoplot(res), NA) expect_s3_class(.plot, "gg") .plot_data <- ggplot2::ggplot_build(.plot) expect_equal(res$.percent_tested, .plot_data$data[[2]]$x) expect_equal(res$.percent_found, .plot_data$data[[2]]$y) expect_equal(length(unique(.plot_data$data[[2]]$colour)), 10) expect_equal(.plot_data$data[[1]]$x[2], 43 + 2/3) }) test_that("Gain Curve - multi class", { res <- gain_curve(hpc_cv2, obs, VF:L) expect_error(.plot <- ggplot2::autoplot(res), NA) expect_s3_class(.plot, "gg") expect_true(".level" %in% colnames(res)) .plot_data <- ggplot2::ggplot_build(.plot) expect_equal(length(unique(.plot_data$data[[2]]$PANEL)), 4) corners <- c(2, 5, 8, 11) corner_vals <- c(31.0623556581986, 5.94688221709007, 11.9515011547344, 51.0392609699769) expect_equal(.plot_data$data[[1]]$x[corners], corner_vals) }) test_that("Gain Curve - multi class, with resamples", { res <- gain_curve(dplyr::group_by(hpc_cv2, Resample), obs, VF:L) expect_error(.plot <- ggplot2::autoplot(res), NA) expect_s3_class(.plot, "gg") expect_true(".level" %in% colnames(res)) expect_true("Resample" %in% colnames(res)) .plot_data <- ggplot2::ggplot_build(.plot) expect_equal(length(unique(.plot_data$data[[2]]$PANEL)), 4) expect_equal(length(unique(.plot_data$data[[2]]$colour)), 5) corners <- c(2, 5, 8, 11) corner_vals <- c(30.9248554913295, 5.78034682080925, 11.8155619596542, 50.8620689655172) expect_equal(.plot_data$data[[1]]$x[corners], corner_vals) }) test_that("Lift Curve - two class", { res <- lift_curve(two_class_example, truth, Class1) expect_error(.plot <- ggplot2::autoplot(res), NA) expect_s3_class(.plot, "gg") .plot_data <- ggplot2::ggplot_build(.plot) res <- res[-1,] expect_equal(nrow(.plot_data$data[[1]]), 500) expect_equal(res$.percent_tested, .plot_data$data[[1]]$x) expect_equal(res$.lift, .plot_data$data[[1]]$y) expect_equal(.plot_data$data[[2]]$x, c(0, 100)) }) test_that("Lift Curve - two class, with resamples", { res <- lift_curve(two_class_resamples, truth, Class1) expect_error(.plot <- ggplot2::autoplot(res), NA) expect_s3_class(.plot, "gg") .plot_data <- ggplot2::ggplot_build(.plot) expect_equal(nrow(.plot_data$data[[1]]), nrow(res) - 10) res <- dplyr::filter(res, .n_events != 0) expect_equal(res$.percent_tested, .plot_data$data[[1]]$x) expect_equal(res$.lift, .plot_data$data[[1]]$y) expect_equal(length(unique(.plot_data$data[[1]]$colour)), 10) }) test_that("Lift Curve - multi class", { res <- lift_curve(hpc_cv2, obs, VF:L) expect_error(.plot <- ggplot2::autoplot(res), NA) expect_s3_class(.plot, "gg") expect_true(".level" %in% colnames(res)) .plot_data <- ggplot2::ggplot_build(.plot) expect_equal(length(unique(.plot_data$data[[1]]$PANEL)), 4) }) test_that("Lift Curve - multi class, with resamples", { res <- lift_curve(dplyr::group_by(hpc_cv2, Resample), obs, VF:L) expect_error(.plot <- ggplot2::autoplot(res), NA) expect_s3_class(.plot, "gg") expect_true(".level" %in% colnames(res)) expect_true("Resample" %in% colnames(res)) .plot_data <- ggplot2::ggplot_build(.plot) expect_equal(length(unique(.plot_data$data[[1]]$PANEL)), 4) expect_equal(length(unique(.plot_data$data[[1]]$colour)), 5) }) test_that("Confusion Matrix - type argument", { res <- conf_mat(two_class_example, truth, predicted) expect_error(.plot <- ggplot2::autoplot(res, type = "wrong"), "type") }) test_that("Confusion Matrix - two class - heatmap", { res <- conf_mat(two_class_example, truth, predicted) expect_error(.plot <- ggplot2::autoplot(res, type = "heatmap"), NA) expect_s3_class(.plot, "gg") .plot_data <- ggplot2::ggplot_build(.plot) expect_equal(nrow(.plot_data$data[[1]]), length(res$table)) }) test_that("Confusion Matrix - multi class - heatmap", { res <- hpc_cv %>% dplyr::filter(Resample == "Fold01") %>% conf_mat(obs, pred) expect_error(.plot <- ggplot2::autoplot(res, type = "heatmap"), NA) expect_s3_class(.plot, "gg") .plot_data <- ggplot2::ggplot_build(.plot) expect_equal(nrow(.plot_data$data[[1]]), length(res$table)) expect_equal(rlang::expr_label(.plot$mapping[["x"]]), "`~Truth`") expect_equal(rlang::expr_label(.plot$mapping[["y"]]), "`~Prediction`") expect_equal(rlang::expr_label(.plot$mapping[["fill"]]), "`~Freq`") }) test_that("Confusion Matrix - heatmap - can use non-standard labels ( df <- dplyr::filter(hpc_cv, Resample == "Fold01") res1 <- conf_mat(df, obs, pred, dnn = c("Pred", "True")) expect_error(p1 <- ggplot2::autoplot(res1, type = "heatmap"), NA) expect_identical(p1$labels$x, "True") expect_identical(p1$labels$y, "Pred") res2 <- conf_mat(df, obs, pred, dnn = NULL) expect_error(p2 <- ggplot2::autoplot(res2, type = "heatmap"), NA) expect_identical(p2$labels$x, "Truth") expect_identical(p2$labels$y, "Prediction") }) test_that("Confusion Matrix - mosaic - can use non-standard labels ( df <- dplyr::filter(hpc_cv, Resample == "Fold01") res1 <- conf_mat(df, obs, pred, dnn = c("Pred", "True")) expect_error(p1 <- ggplot2::autoplot(res1, type = "mosaic"), NA) expect_identical(p1$labels$x, "True") expect_identical(p1$labels$y, "Pred") res2 <- conf_mat(df, obs, pred, dnn = NULL) expect_error(p2 <- ggplot2::autoplot(res2, type = "mosaic"), NA) expect_identical(p2$labels$x, "Truth") expect_identical(p2$labels$y, "Prediction") }) test_that("Confusion Matrix - two class - mosaic", { res <- conf_mat(two_class_example, truth, predicted) expect_error(.plot <- ggplot2::autoplot(res, type = "mosaic"), NA) expect_s3_class(.plot, "gg") .plot_data <- ggplot2::ggplot_build(.plot) expect_equal(nrow(.plot_data$data[[1]]), length(res$table)) }) test_that("Confusion Matrix - multi class - mosaic", { res <- hpc_cv %>% dplyr::filter(Resample == "Fold01") %>% conf_mat(obs, pred) expect_error(.plot <- ggplot2::autoplot(res, type = "mosaic"), NA) expect_s3_class(.plot, "gg") .plot_data <- ggplot2::ggplot_build(.plot) expect_equal(nrow(.plot_data$data[[1]]), length(res$table)) })
lav_uvord_fit <- function(y = NULL, X = NULL, wt = rep(1, length(y)), lower = -Inf, upper = +Inf, optim.method = "nlminb", logistic = FALSE, control = list(), output = "list") { if(!is.integer(y)) { y <- as.integer(y) } if(!min(y, na.rm = TRUE) == 1L) { y <- as.integer(ordered(y)) } if(is.null(wt)) { wt = rep(1, length(y)) } else { if(length(y) != length(wt)) { stop("lavaan ERROR: length y is not the same as length wt") } if(any(wt < 0)) { stop("lavaan ERROR: all weights should be positive") } } minObjective <- lav_uvord_min_objective minGradient <- lav_uvord_min_gradient minHessian <- lav_uvord_min_hessian if(optim.method == "nlminb" || optim.method == "nlminb2") { } else if(optim.method == "nlminb0") { minGradient <- minHessian <- NULL } else if(optim.method == "nlminb1") { minHessian <- NULL } cache <- lav_uvord_init_cache(y = y, X = X, wt = wt, logistic = logistic) control.nlminb <- list(eval.max = 20000L, iter.max = 10000L, trace = 0L, abs.tol=(.Machine$double.eps * 10)) control.nlminb <- modifyList(control.nlminb, control) optim <- nlminb(start = cache$theta, objective = minObjective, gradient = minGradient, hessian = minHessian, control = control.nlminb, lower = lower, upper = upper, cache = cache) if(output == "cache") { return(cache) } out <- list(theta = optim$par, nexo = cache$nexo, nth = cache$nth, th.idx = seq_len(cache$nth), slope.idx = seq_len(length(optim$par))[-seq_len(cache$nth)], missing.idx = cache$missing.idx, y = cache$y, wt = cache$wt, Y1 = cache$Y1, Y2 = cache$Y2, z1 = cache$z1, z2 = cache$z2, X = cache$X) } lav_uvord_th <- function(y = NULL, wt = NULL) { y.freq <- tabulate(y) y.ncat <- length(y.freq) if(is.null(wt)) { y.prop <- y.freq/sum(y.freq) } else { y.freq <- numeric(y.ncat) for(cat in seq_len(y.ncat)) { y.freq[cat] <- sum(wt[y == cat], na.rm = TRUE) } y.prop <- y.freq/sum(y.freq) } qnorm(cumsum(y.prop[-length(y.prop)])) } lav_uvord_init_cache <- function(y = NULL, X = NULL, wt = rep(1, length(y)), logistic = FALSE, parent = parent.frame()) { nobs <- length(y) y.ncat <- length(tabulate(y)) nth <- y.ncat - 1L if(is.null(X)) { nexo <- 0L } else { X <- unname(X); nexo <- ncol(X) } if(is.null(wt)) { N <- nobs } else { N <- sum(wt) } y.freq <- numeric(y.ncat) for(cat in seq_len(y.ncat)) { y.freq[cat] <- sum(wt[y == cat], na.rm = TRUE) } y.prop <- y.freq/sum(y.freq) missing.idx <- which(is.na(y)) if(any(is.na(y)) || (!is.null(X) && any(is.na(X)) )) { lav_crossprod <- lav_matrix_crossprod } else { lav_crossprod <- base::crossprod } if(logistic) { pfun <- plogis dfun <- dlogis gfun <- function (x) { out <- numeric(length(x)) out[ is.na(x) ] <- NA x.ok <- which(abs(x) < 200) e <- exp(-x[x.ok]) e1 <- 1 + e; e2 <- e1 * e1; e4 <- e2 * e2 out[x.ok] <- -e/e2 + e*(2 * (e*e1))/e4 out } } else { pfun <- pnorm dfun <- dnorm gfun <- function(x) { -x * dnorm(x) } } o1 <- ifelse(y == nth + 1, 100, 0) o2 <- ifelse(y == 1, -100, 0) Y1 <- matrix(1:nth, nobs, nth, byrow = TRUE) == y Y2 <- matrix(1:nth, nobs, nth, byrow = TRUE) == (y - 1L) if(nexo == 0L) { if(logistic) { th.start <- qlogis(cumsum(y.prop[-length(y.prop)])) } else { th.start <- qnorm(cumsum(y.prop[-length(y.prop)])) } } else if(nth == 1L && nexo > 0L) { th.start <- 0 } else { if(logistic) { th.start <- qlogis((1:nth) / (nth + 1) ) } else { th.start <- qnorm((1:nth) / (nth + 1) ) } } beta.start <- rep(0, nexo) theta <- c( th.start, beta.start ) out <- list2env(list(y = y, X = X, wt = wt, o1 = o1, o2 = o2, missing.idx = missing.idx, N = N, pfun = pfun, dfun = dfun, gfun = gfun, lav_crossprod = lav_crossprod, nth = nth, nobs = nobs, y.ncat = y.ncat, nexo = nexo, Y1 = Y1, Y2 = Y2, theta = theta), parent = parent) out } lav_uvord_loglik <- function(y = NULL, X = NULL, wt = rep(1, length(y)), logistic = FALSE, cache = NULL) { if(is.null(cache)) { cache <- lav_uvord_fit(y = y, X = X, wt = wt, logistic = logistic, output = "cache") } lav_uvord_loglik_cache(cache = cache) } lav_uvord_loglik_cache <- function(cache = NULL) { with(cache, { th <- theta[1:nth]; TH <- c(0, th, 0); beta <- theta[-c(1:nth)] if(nexo > 0L) { eta <- drop(X %*% beta) z1 <- TH[y+1L] - eta + o1 z2 <- TH[y ] - eta + o2 } else { z1 <- TH[y+1L] + o1 z2 <- TH[y ] + o2 } pi.i <- pfun(z1) - pfun(z2) large.idx <- which(z2 > 1) if(length(large.idx) > 0L) { pi.i[large.idx] <- ( pfun(z2[large.idx], lower.tail = FALSE) - pfun(z1[large.idx], lower.tail = FALSE) ) } loglik <- sum( wt * log(pi.i), na.rm = TRUE) return( loglik ) }) } lav_uvord_scores <- function(y = NULL, X = NULL, wt = rep(1, length(y)), use.weights = TRUE, logistic = FALSE, cache = NULL) { if(is.null(cache)) { cache <- lav_uvord_fit(y = y, X = X, wt = wt, logistic = logistic, output = "cache") } SC <- lav_uvord_scores_cache(cache = cache) if(!is.null(wt) && use.weights) { SC <- SC * wt } SC } lav_uvord_scores_cache <- function(cache = NULL) { with(cache, { dldpi <- 1 / pi.i p1 <- dfun(z1); p2 <- dfun(z2) scores.th <- dldpi * (Y1*p1 - Y2*p2) if(nexo > 0L) { scores.beta <- dldpi * (-X) * (p1 - p2) return( cbind(scores.th, scores.beta, deparse.level = 0) ) } else { return( scores.th ) } }) } lav_uvord_gradient_cache <- function(cache = NULL) { with(cache, { wtp <- wt / pi.i p1 <- dfun(z1); p2 <- dfun(z2) dxa <- Y1*p1 - Y2*p2 scores.th <- wtp * dxa if(nexo > 0L) { dxb <- X * (p1 - p2) scores.beta <- wtp * (-dxb) return( colSums(cbind(scores.th, scores.beta, deparse.level = 0), na.rm = TRUE) ) } else { return( colSums(scores.th, na.rm = TRUE) ) } }) } lav_uvord_hessian <- function(y = NULL, X = NULL, wt = rep(1, length(y)), logistic = FALSE, cache = NULL) { if(is.null(cache)) { cache <- lav_uvord_fit(y = y, X = X, wt = wt, logistic = logistic, output = "cache") } tmp <- lav_uvord_loglik_cache(cache = cache) tmp <- lav_uvord_gradient_cache(cache = cache) lav_uvord_hessian_cache(cache = cache) } lav_uvord_hessian_cache <- function(cache = NULL) { with(cache, { wtp2 <- wt/(pi.i * pi.i) g1w <- gfun(z1) * wtp g2w <- gfun(z2) * wtp Y1gw <- Y1 * g1w Y2gw <- Y2 * g2w dx2.tau <- ( lav_crossprod(Y1gw, Y1) - lav_crossprod(Y2gw, Y2) - lav_crossprod(dxa, dxa * wtp2) ) if(nexo == 0L) { return( dx2.tau ) } dxb2 <- dxb * wtp2 dx2.beta <- ( lav_crossprod(X * g1w, X) - lav_crossprod(X * g2w, X) - lav_crossprod(dxb, dxb2) ) dx.taubeta <- ( -lav_crossprod(Y1gw, X) + lav_crossprod(Y2gw, X) + lav_crossprod(dxa, dxb2) ) Hessian <- rbind( cbind( dx2.tau, dx.taubeta, deparse.level = 0), cbind( t(dx.taubeta), dx2.beta, deparse.level = 0), deparse.level = 0 ) return( Hessian ) }) } lav_uvord_min_objective <- function(x, cache = NULL) { if(cache$nth > 1L && x[1] > x[2]) { return(+Inf) } if(cache$nth > 2L && x[2] > x[3]) { return(+Inf) } if(cache$nth > 3L && x[3] > x[4]) { return(+Inf) } cache$theta <- x -1 * lav_uvord_loglik_cache(cache = cache)/cache$N } lav_uvord_min_gradient <- function(x, cache = NULL) { if(!all(x == cache$theta)) { cache$theta <- x tmp <- lav_uvord_loglik_cache(cache = cache) } -1 * lav_uvord_gradient_cache(cache = cache)/cache$N } lav_uvord_min_hessian <- function(x, cache = NULL) { if(!all(x == cache$theta)) { cache$theta <- x tmp <- lav_uvord_loglik_cache(cache = cache) tmp <- lav_uvord_gradient_cache(cache = cache) } -1 * lav_uvord_hessian_cache(cache = cache)/cache$N } lav_uvord_update_fit <- function(fit.y = NULL, th.new = NULL, sl.new = NULL) { if(is.null(th.new) && is.null(sl.new)) { return(fit.y) } if(!is.null(th.new)) { fit.y$theta[fit.y$th.idx] <- th.new } if(!is.null(sl.new)) { fit.y$theta[fit.y$slope.idx] <- sl.new } nth <- length(fit.y$th.idx) o1 <- ifelse(fit.y$y == nth + 1, 100, 0) o2 <- ifelse(fit.y$y == 1, -100, 0) theta <- fit.y$theta th <- theta[1:nth]; TH <- c(0, th, 0); beta <- theta[-c(1:nth)] y <- fit.y$y; X <- fit.y$X if(length(fit.y$slope.idx) > 0L) { eta <- drop(X %*% beta) fit.y$z1 <- TH[y+1L] - eta + o1 fit.y$z2 <- TH[y ] - eta + o2 } else { fit.y$z1 <- TH[y+1L] + o1 fit.y$z2 <- TH[y ] + o2 } fit.y }
test_that("entropy works", { .act <- ds_entropy(de_county, starts_with('pop_')) .exp <- c(0.638090971561592, 0.638090971561592, 0.638090971561592) expect_equal(.act, .exp, tolerance = 1e-6) }) test_that("entropy .name works", { .act <- ds_entropy(de_county, starts_with('pop_'), .name = 'special_name') expect_true('special_name' %in% names(.act)) }) test_that("entropy .comp works", { .act <- ds_entropy(de_county, starts_with('pop_'), .comp = TRUE) .exp <- c(0.116761244988572, 0.399314289368122, 0.122015437204899) expect_equal(.act, .exp, tolerance = 1e-6) })
github_api_org_members = function(org) { arg_is_chr_scalar(org) ghclass_api_v3_req( endpoint = "GET /orgs/:org/members", org = org ) } org_members = function(org, filter = NULL, exclude = FALSE, include_admins = TRUE) { arg_is_chr_scalar(org) arg_is_chr_scalar(filter, allow_null = TRUE) res = purrr::safely(github_api_org_members)(org) members = purrr::map_chr(result(res), "login") if (!include_admins) members = setdiff(members, org_admins(org)) filter_results(members, filter, exclude) }
bonferroni.dataProcessed <- function(x) { r <- length(x$yh) t <- 2:r g <- dim(x$Phl)[2] s <- dim(x$Qhlk)[3] g_names <- colnames(x$Phl) nhl <- x$Phl nhl[t, ] <- NA nhl[t, ] <- x$Phl[t, ] - x$Phl[t - 1, ] nh <- rowSums(nhl) nl <- colSums(nhl) N <- sum(nl) fl <- nl / N ol <- apply(nhl, 2, function (l) min(which(l > 0))) pl_h <- x$Phl / rowSums(x$Phl) wllh <- array(sapply(1:r, function(h) outer(fl, pl_h[h, ])), c(g, g, r)) dimnames(wllh) <- list(l1 = g_names, l2 = g_names, h = 1:r) Shlk <- x$Qhlk Shlk[t, , ] <- NA Shlk[t, , ] <- x$Qhlk[t, , ] - x$Qhlk[t-1, , ] tmp <- Minfhlk <- x$Qhlk tmp[] <- Minfhlk[] <- NA for (k in 1:s) { for (h in 1:r) { for (l in 1:g) { tmp[h, l, k] <- x$Qhlk[h, l, k] / x$Phl[h, l] Minfhlk[h, l, k] <- ifelse( is.nan(tmp[h, l, k]) == TRUE, Shlk[ol[l], l, k] / nhl[ol[l], l], tmp[h, l, k] ) } } } Minfhl <- apply(Minfhlk, c(1, 2), sum) MY <- sum(Minfhl[r, ] %*% x$Phl[r, ]) / sum(x$Phl[r, ]) Mlk <- array(Minfhlk[r, , ], c(g, s)) dimnames(Mlk) <- dimnames(Minfhlk)[-1] tmp <- array( sapply(1:s, function(k) sapply(1:r, function(h) outer(Mlk[, k], Minfhlk[h, , k], "-") / MY ) ), c(g, g, r, s) ) Vllhk <- array( sapply(1:s, function(k) tmp[, , , k] * wllh), c(g, g, r, s) ) dimnames(Vllhk) <- list( l1 = g_names, l2 = g_names, h = 1:r, k = dimnames(x$Qhlk)[[3]] ) rm(tmp) res <- list( index = "Bonferroni", decomposition = Vllhk, dataProcessed = x ) class(res) <- "decomposition" return(res) }
knitr::opts_chunk$set( collapse = TRUE, comment = " ) library(ampir) my_protein_df <- read_faa(system.file("extdata/little_test.fasta", package = "ampir")) display_df <- my_protein_df display_df$seq_aa <- paste(substring(display_df$seq_aa,1,45),"...",sep="") knitr::kable(display_df) my_prediction <- predict_amps(my_protein_df, model = "precursor") my_prediction$seq_aa <- paste(substring(my_prediction$seq_aa,1,45),"...",sep="") knitr::kable(my_prediction, digits = 3) my_predicted_amps <- my_protein_df[my_prediction$prob_AMP > 0.8,] my_predicted_amps$seq_aa <- paste(substring(my_predicted_amps$seq_aa,1,45),"...",sep="") knitr::kable(my_predicted_amps) df_to_faa(my_predicted_amps, tempfile("my_predicted_amps.fasta", tempdir()))
sel.score.rank<- function(data, bmat, genotype){ b<- matrix(bmat, ncol = 1) mean.df<- function(data, genotype){ odr<- unique(genotype) geno<- list(factor(genotype, ordered(odr))) mean<- aggregate(data, geno, mean) matrix<- as.matrix(mean[,-1]) return(matrix) } df<- mean.df(data, genotype) odr<- unique(genotype) sel.score<- df %*% b rank<- as.numeric(rank(as.vector(-sel.score))) rank.df<- data.frame("Genotype" = odr, "Selection score" = sel.score, "Rank" = rank) return(rank.df) }
context("Testing time series metadata retrieval and checks") test_that("ki_timeseries_list throws error when no hub specified", { skip_if_net_down() skip_if_exp_down() expect_error(ki_timeseries_list(hub = "", station_id = "12345")) }) test_that("ki_timeseries_list throws error if provided hub in not reachable", { skip_if_net_down() skip_if_exp_down() expect_error(ki_timeseries_list(hub = "https://xxxx", ts_name = "A*")) }) test_that("ki_timeseries_list throws error when no station_id, group_id or ts_name provided", { skip_if_net_down() skip_if_exp_down() expect_error(ki_timeseries_list(hub = example_hub)) expect_error(ki_timeseries_list(hub = example_hub, station_id = "")) expect_error(ki_timeseries_list(hub = example_hub, ts_name = "")) expect_error(ki_timeseries_list(hub = example_hub, group_id = "")) }) test_that("ki_timeseries_list accepts station_id for retrieving metadata", { skip_if_net_down() skip_if_exp_down() ts_meta <- ki_timeseries_list(hub = example_hub, station_id = test_stn_id) expect_type(ts_meta, "list") }) test_that("ki_timeseries_list accepts ts_name for retrieving metadata", { skip_if_net_down() skip_if_exp_down() ts_meta <- ki_timeseries_list(hub = example_hub, ts_name = "Vel*") expect_type(ts_meta, "list") }) test_that("ki_timeseries_list accepts group_id for retrieving metadata", { skip_if_net_down() skip_if_exp_down() ts_meta <- ki_timeseries_list(hub = example_hub, group_id = test_ts_group_id) expect_type(ts_meta, "list") }) test_that("ki_timeseries_list returns coverage columns by default", { skip_if_net_down() skip_if_exp_down() ts_meta <- ki_timeseries_list(hub = example_hub, station_id = test_stn_id) expect( sum(c("from", "to") %in% names(ts_meta)) == 2, failure_message = "Timeseries metadata doesn't contain expected columns" ) }) test_that("ki_timeseries_list allows for turning coverage off increase query speed", { skip_if_net_down() skip_if_exp_down() ts_meta <- ki_timeseries_list(hub = example_hub, station_id = test_stn_id, coverage = FALSE) expect( sum(c("from", "to") %in% names(ts_meta)) == 0, failure_message = "Timeseries metadata doesn't contain expected columns" ) }) test_that("ki_timeseries_list allows for custom return fields (vector or string)", { skip_if_net_down() skip_if_exp_down() cust_ret_str <- "station_name,ts_name,ts_id" cust_ret_v <- c("station_name", "ts_name", "ts_id") fake_ret_str <- "metadatathatdoesntactuallyexist" stn_cust_retr <- ki_timeseries_list( hub = example_hub, station_id = test_stn_id, return_fields = cust_ret_str ) stn_cust_retr2 <- ki_timeseries_list( hub = example_hub, station_id = test_stn_id, return_fields = cust_ret_v ) expect_type(stn_cust_retr, "list") expect_type(stn_cust_retr2, "list") expect_equal(stn_cust_retr, stn_cust_retr2) expect_error( ki_timeseries_list( hub = example_hub, station_id = test_stn_id, return_fields = fake_ret_str ) ) })
CNs <- function(X){ X = as.matrix(X) if (dim(X)[2] == 2){ salida = CN(X) } else { nc1 = CN(X[,-1]) nc2 = CN(X) incremento = ((nc2-nc1)/nc2)*100 salida = list(nc1, nc2, incremento) names(salida) = c("Condition Number without intercept", "Condition Number with intercept", "Increase (in percentage)") } return(salida) }
.fowa.stat <- function(x,phi,um){ folk.ward=data.frame(matrix(ncol=0,nrow=9)) for (b in 1:dim(x)[2]) {y=x[b] sum.sieve=sum(y) class.weight=(y*100)/sum.sieve cum.sum=cumsum(class.weight)[,1] if (min(cum.sum)>5) { fowa=data.frame(rep(0,9)) row.names(fowa)=c("Sediment","Mean.fw.um","Sd.fw.um","Skewness.fw.um","Kurtosis.fw.um","Mean.fw.phi","Sd.fw.phi","Skewness.fw.phi","Kurtosis.fw.phi") names(fowa)=names(x)[b] } if (min(cum.sum)<5) { mat.D=.percentile(x[,b],phi,um) mean.phi=(mat.D[6,1]+mat.D[4,1]+mat.D[2,1])/3 mean.mm=(exp(log(mat.D[6,2])+log(mat.D[4,2])+log(mat.D[2,2])/3))/1000 sd.phi=-(((mat.D[2,1]-mat.D[6,1])/4)+((mat.D[1,1]-mat.D[7,1])/6.6)) sd.mm=exp(((log(mat.D[2,2])-log(mat.D[6,2]))/4)+((log(mat.D[1,2])-log(mat.D[7,2]))/6.6)) skewness.phi=-(((mat.D[6,1]+mat.D[2,1]-(2*mat.D[4,1]))/(2*(mat.D[2,1]-mat.D[6,1])))+ ((mat.D[7,1]+mat.D[1,1]-(2*mat.D[4,1]))/(2*(mat.D[1,1]-mat.D[7,1])))) skewness.mm=-skewness.phi kurtosis.phi=(mat.D[1,1]-mat.D[7,1])/(2.44*(mat.D[3,1]-mat.D[5,1])) kurtosis.mm=kurtosis.phi if (mean.phi<=-5) mean.descript="Very Coarse Gravel" if (mean.phi>-5 & mean.phi<=-4) mean.descript="Coarse Gravel" if (mean.phi>-4 & mean.phi<=-3) mean.descript="Medium Gravel" if (mean.phi>-3 & mean.phi<=-2) mean.descript="Fine Gravel" if (mean.phi>-2 & mean.phi<=-1) mean.descript="Very Fine Gravel" if (mean.phi>-1 & mean.phi<=0) mean.descript="Very Coarse Sand" if (mean.phi>0 & mean.phi<=1) mean.descript="Coarse Sand" if (mean.phi>1 & mean.phi<=2) mean.descript="Medium Sand" if (mean.phi>2 & mean.phi<=3) mean.descript="Fine Sand" if (mean.phi>3 & mean.phi<=4) mean.descript="Very Fine Sand" if (mean.phi>4 & mean.phi<=5) mean.descript="Very Coarse Silt" if (mean.phi>5 & mean.phi<=6) mean.descript="Coarse Silt" if (mean.phi>6 & mean.phi<=7) mean.descript="Medium Silt" if (mean.phi>7 & mean.phi<=8) mean.descript="Fine Silt" if (mean.phi>8 & mean.phi<=9) mean.descript="Very Fine Silt" if (mean.phi>8) mean.descript="Clay" if (sd.phi<0.35) sorting="Very Well Sorted" if (sd.phi>=0.35 & sd.phi<0.5) sorting="Well Sorted" if (sd.phi>=0.5 & sd.phi<0.7) sorting="Moderately Well Sorted" if (sd.phi>=0.7 & sd.phi<1) sorting="Moderately Sorted" if (sd.phi>=1 & sd.phi<2) sorting="Poorly Sorted" if (sd.phi>=2 & sd.phi<4) sorting="Very Poorly Sorted" if (sd.phi>=4) sorting="Extremely Poorly Sorted" if (skewness.phi>=0.3) skewness.descript="Very Fine Skewed" if (skewness.phi<0.3 & skewness.phi>=0.1) skewness.descript="Fine Skewed" if (skewness.phi<0.1 & skewness.phi>-0.1) skewness.descript="Symmetrical" if (skewness.phi<=-0.1 & skewness.phi>-0.3) skewness.descript="Coarse Skewed" if (skewness.phi<=-0.3) skewness.descript="Very Coarse Skewed" if (kurtosis.phi<0.67) kurtosis.descript="Very Platykurtic" if (kurtosis.phi>=0.67 & kurtosis.phi<0.9) kurtosis.descript="Platykurtic" if (kurtosis.phi>=0.9 & kurtosis.phi<=1.11) kurtosis.descript="Mesokurtic" if (kurtosis.phi>1.11 & kurtosis.phi<=1.5) kurtosis.descript="Leptokurtic" if (kurtosis.phi>1.5 & kurtosis.phi<=3) kurtosis.descript="Very Leptokurtic" if (kurtosis.phi>3) kurtosis.descript="Extremely Leptokurtic" .sedim.descript=paste(mean.descript,sorting,skewness.descript,kurtosis.descript,sep=",") result.fw.phi=data.frame(c(round(mean.phi,3),round(sd.phi,3),round(skewness.phi,3),round(kurtosis.phi,3))) names(result.fw.phi)=names(x)[b] result.fw.mm=data.frame(c(round(mean.mm,3),round(sd.mm,3),round(skewness.mm,3),round(kurtosis.mm,3))) names(result.fw.mm)=names(x)[b] fowa=data.frame(rbind(.sedim.descript,result.fw.mm,result.fw.phi)) row.names(fowa)=c("Sediment","Mean.fw.um","Sd.fw.um","Skewness.fw.um","Kurtosis.fw.um","Mean.fw.phi","Sd.fw.phi","Skewness.fw.phi","Kurtosis.fw.phi") names(fowa)=names(x)[b] } folk.ward=cbind(folk.ward,fowa) } folk.ward } .G2Sd_web <- function(){ runApp(appDir=paste0(.libPaths()[1],"/G2Sd/extdata")) } .grancompat <- function(x) { x <- as.data.frame(x) n.sieve <- nrow(x) n.sample <- ncol(x) if (!is.data.frame(x)) stop("dataframe expected.") if (any(x < 0)) stop("negative entries in dataframe.") if (any(x > 300)) warning("Some high values are present.", call. = FALSE,immediate.=TRUE) return(x) } .index.sedim <- function(x,phi,um){ x=as.data.frame(x) INDEX=data.frame(matrix(ncol=0,nrow=9)) for (b in 1:dim(x)[2]) { mat.D=.percentile(x[,b],phi,um) index=data.frame(matrix(ncol=1,nrow=9)) row.names(index)=c("D10(um)","D50(um)","D90(um)","D90/D10","D90-D10","D75/D25","D75-D25","Trask(So)","Krumbein(Qd)") names(index)=names(x)[b] index[1,1]=round(mat.D["10",2],3) index[2,1]=round(mat.D["50",2],3) index[3,1]=round(mat.D["90",2],3) index[4,1]=round(mat.D["90",2]/mat.D["10",2],3) index[5,1]=round(mat.D["90",2]-mat.D["10",2],3) index[6,1]=round(mat.D["75",2]/mat.D["25",2],3) index[7,1]=round(mat.D["75",2]-mat.D["25",2],3) index[8,1]=round(sqrt(mat.D["25",2]/mat.D["75",2]),3) index[9,1]=round((mat.D["25",1]-mat.D["75",1])/2,3) INDEX=cbind(INDEX,index) } return(INDEX) } .mgrep <- function(mpattern,x,FUN="grep") { select=NULL for (i in 1:length(mpattern)) { if (FUN=="grep") values=grep(mpattern[i],x) if (FUN=="which") values=which(x==mpattern[i]) select=c(select,values) } return(sort(select)) } .mode.sedim <- function(x,um){ x=as.data.frame(x) sum.sieve=apply(x,2,sum) MODE=data.frame(matrix(ncol=0,nrow=5)) for (b in 1:dim(x)[2]) { class.weight=(x[,b]*100)/sum.sieve[b] tab.mod=cbind(um,class.weight) if (pmatch(0,um)!=0) tab.mod=tab.mod[-pmatch(0,um),] plot(tab.mod[,1],tab.mod[,2],type="b",lwd=3,xlab="Particule size (microns)",ylab="Pourcentage (%)",xaxt="n",log="x") a=identify(tab.mod,plot=FALSE,n=4) mod=data.frame(tab.mod[a,1]) names(mod)=names(x)[b] row.names(mod)=tab.mod[a,1] if (dim(mod)[1]==1) mod.descript="1 Mode" else mod.descript=paste(dim(mod)[1],"Modes") MODE.sedim=data.frame(matrix(ncol=1,nrow=4)) for (i in 1:dim(mod)[1]) MODE.sedim[i,]=mod[i,] MODE.sedim=rbind(mod.descript,MODE.sedim) names(MODE.sedim)=names(x)[b] row.names(MODE.sedim)[1]="Nb Mode" MODE.sedim MODE=cbind(MODE,MODE.sedim) } return(MODE) } .moment.arith <- function(x,um){ x=as.data.frame(x) sum.sieve=apply(x,2,sum) arith=data.frame(matrix(ncol=0,nrow=4)) for (b in 1:dim(x)[2]) { class.weight=(x[b]*100)/sum.sieve[b] mid.point=rep(0,(length(um))) for(i in 2:length(um)) { mid.point[i]=(um[i]+um[i-1])/2 } fm=class.weight*mid.point mean.arith=apply(fm,2,sum)/100 fmM2=class.weight*(mid.point-mean.arith)^2 sd.arith=sqrt(apply(fmM2,2,sum)/100) fmM3=class.weight*(mid.point-mean.arith)^3 skewness.arith=apply(fmM3,2,sum)/(100*sd.arith^3) fmM4=class.weight*(mid.point-mean.arith)^4 kurtosis.arith=apply(fmM4,2,sum)/(100*sd.arith^4) moment.arit=data.frame(rbind(round(mean.arith,3),round(sd.arith,3),round(skewness.arith,3),round(kurtosis.arith,3))) colnames(moment.arit)=colnames(x)[b] arith=cbind(arith,moment.arit) rownames(arith)=c("mean.arith.um","sd.arith.um","skewness.arith.um","kurtosis.arith.um") } return(arith) } .moment.geom <- function(x,phi){ x=as.data.frame(x) sum.sieve=apply(x,2,sum) geom=data.frame(matrix(ncol=0,nrow=4)) for (b in 1:dim(x)[2]) { class.weight=(x[b]*100)/sum.sieve[b] mid.point=rep(0,(length(phi))) for(i in 2:length(phi)) { mid.point[i]=(phi[i]+phi[i-1])/2 } logm=log10(2^(-mid.point)*1000) flogm=class.weight*logm mean.geom=10^(apply(flogm,2,sum)/100) fmM2=class.weight*(logm-log10(mean.geom))^2 sd.geom=10^(sqrt(apply(fmM2,2,sum)/100)) fmM3=class.weight*(logm-log10(mean.geom))^3 skewness.geom=(apply(fmM3,2,sum)/(100*log10(sd.geom)^3)) fmM4=class.weight*(logm-log10(mean.geom))^4 kurtosis.geom=(apply(fmM4,2,sum)/(100*log10(sd.geom)^4)) kurtosis3.geom=kurtosis.geom moment.geo=as.data.frame(rbind(round(mean.geom,3),round(sd.geom,3),round(skewness.geom,3),round(kurtosis.geom,3))) names(moment.geo)=names(x)[b] geom=cbind(geom,moment.geo) rownames(geom)=c("mean.geom.um","sd.geom.um","skewness.geom.um","kurtosis.geom.um") } return(geom) } .northarrow <- function(loc,size,bearing=0,cols,letter_dist=1,cex=1,...) { if(missing(loc)) stop("loc is missing") if(missing(size)) stop("size is missing") if(missing(cols)) cols <- rep(c("white","black"),8) radii <- rep(size/c(1,4,2,4),4) x <- radii[(0:15)+1]*cos((0:15)*pi/8+bearing)+loc[1] y <- radii[(0:15)+1]*sin((0:15)*pi/8+bearing)+loc[2] for (i in 1:15) { x1 <- c(x[i],x[i+1],loc[1]) y1 <- c(y[i],y[i+1],loc[2]) polygon(x1,y1,col=cols[i]) } polygon(c(x[16],x[1],loc[1]),c(y[16],y[1],loc[2]),col=cols[16]) b <- c("E","N","W","S") for (i in 0:3) text((size+letter_dist*par("cxy")[1])*cos(bearing+i*pi/2)+loc[1], (size+letter_dist*par("cxy")[2])*sin(bearing+i*pi/2)+loc[2],b[i+1], cex=cex) } .percentile <- function(x,phi,um){ x=as.numeric(x) sum.sieve=sum(x) class.weight=(x*100)/sum.sieve cum.sum=as.numeric(cumsum(class.weight)) D=c(5,16,25,50,75,84,95,10,90) minimum.cumsum <- min(cum.sum) if (any(D< minimum.cumsum)) { warning(paste0(paste0("D",D[D< minimum.cumsum],collapse=", ")," can't be calculated"), call. = FALSE,immediate.=TRUE) class.weight.PHI=cbind(cum.sum,all$phi,all$um) mat.D=data.frame(matrix(ncol=2,nrow=9)) row.names(mat.D)=D names(mat.D)=c("Phi","um") nbclass <- which(D> minimum.cumsum,arr.ind=TRUE) } if (all(D> minimum.cumsum)) { class.weight.PHI=cbind(cum.sum,phi,um) mat.D=data.frame(matrix(ncol=2,nrow=9)) row.names(mat.D)=D names(mat.D)=c("Phi","um") nbclass <- 1:9 } for (i in nbclass) { greaterpercent=subset(class.weight.PHI,class.weight.PHI[,1]>D[i]) greaterphi=subset(greaterpercent,greaterpercent[,1]==min(greaterpercent[,1]),select=-1) greaterphi=as.numeric(subset(greaterphi,greaterphi[,2]==max(greaterphi[,2]),select=1)) greaterpercent=min(greaterpercent[,1]) lesspercent=subset(class.weight.PHI,class.weight.PHI[,1]<D[i]) lessphi=subset(lesspercent,lesspercent[,1]==max(lesspercent[,1]),select=-1) lessphi=as.numeric(subset(lessphi,lessphi[,2]==min(lessphi[,2]),select=1)) lesspercent=max(lesspercent[,1]) ifelse (dim(subset(class.weight.PHI,class.weight.PHI[,1]==D[i]))[1]==0, {ratio1=(D[i]-lesspercent)/(greaterpercent-lesspercent) ratio2=(greaterphi-lessphi)*ratio1 phi=lessphi+ratio2 um=1/(2^phi)*1000}, {phi=as.numeric(subset(class.weight.PHI,class.weight.PHI[,1]==D[i],2)) um=as.numeric(subset(class.weight.PHI,class.weight.PHI[,1]==D[i],3))*1000}) result=c(phi,um) mat.D[i,]=result } return(mat.D) } .sedim.descript <- function(x,um){ um=as.numeric(um) x=as.data.frame(x) sum.sieve=apply(x,2,sum) sediment=data.frame(matrix(ncol=0,nrow=13)) for (b in 1:dim(x)[2]) { class.weight=(x[,b])*100/sum.sieve[b] class.weight.um=cbind(class.weight,um) seuil.sedim=c(63000,31500,2^c(4:-3)*1000,63,40,NA) class.sedim=c("boulder","vcgravel","cgravel","mgravel","fgravel","vfgravel","vcsand","csand","msand","fsand","vfsand","vcsilt","silt") sedim=data.frame(cbind(seuil.sedim,class.sedim),stringsAsFactors = FALSE) sedim[,1]=as.numeric(sedim[,1]) result=data.frame(matrix(nrow=dim(sedim)[1],ncol=dim(sedim)[1])) result[,1]=sedim[,1] names(result)=c("Sedim","Pourcentage") sedim.result=0 sedim.percent=subset(class.weight.um,class.weight.um[,2]>=sedim[1,1]) sedim.result=sum(as.numeric(sedim.percent[,1])) result[1,1]=sedim.result sedim.percent=subset(class.weight.um,class.weight.um[,2]<sedim[1,1] & class.weight.um[,2]>=(sedim[2,1])) sedim.result=sum(as.numeric(sedim.percent[,1])) result[2,1]=sedim.result sedim.percent=subset(class.weight.um,class.weight.um[,2]<sedim[2,1] & class.weight.um[,2]>=(sedim[3,1])) sedim.result=sum(as.numeric(sedim.percent[,1])) result[3,1]=sedim.result sedim.percent=subset(class.weight.um,class.weight.um[,2]<sedim[3,1] & class.weight.um[,2]>=(sedim[4,1])) sedim.result=sum(as.numeric(sedim.percent[,1])) result[4,1]=sedim.result sedim.percent=subset(class.weight.um,class.weight.um[,2]<sedim[4,1] & class.weight.um[,2]>=(sedim[5,1])) sedim.result=sum(as.numeric(sedim.percent[,1])) result[5,1]=sedim.result sedim.percent=subset(class.weight.um,class.weight.um[,2]<sedim[5,1] & class.weight.um[,2]>=(sedim[6,1])) sedim.result=sum(as.numeric(sedim.percent[,1])) result[6,1]=sedim.result sedim.percent=subset(class.weight.um,class.weight.um[,2]<sedim[6,1] & class.weight.um[,2]>=(sedim[7,1])) sedim.result=sum(as.numeric(sedim.percent[,1])) result[7,1]=sedim.result sedim.percent=subset(class.weight.um,class.weight.um[,2]<sedim[7,1] & class.weight.um[,2]>=(sedim[8,1])) sedim.result=sum(as.numeric(sedim.percent[,1])) result[8,1]=sedim.result sedim.percent=subset(class.weight.um,class.weight.um[,2]<sedim[8,1] & class.weight.um[,2]>=(sedim[9,1])) sedim.result=sum(as.numeric(sedim.percent[,1])) result[9,1]=sedim.result sedim.percent=subset(class.weight.um,class.weight.um[,2]<sedim[9,1] & class.weight.um[,2]>=(sedim[10,1])) sedim.result=sum(as.numeric(sedim.percent[,1])) result[10,1]=sedim.result sedim.percent=subset(class.weight.um,class.weight.um[,2]<sedim[10,1] & class.weight.um[,2]>=(sedim[11,1])) sedim.result=sum(as.numeric(sedim.percent[,1])) result[11,1]=sedim.result sedim.percent=subset(class.weight.um,class.weight.um[,2]<sedim[11,1] & class.weight.um[,2]>=(sedim[12,1])) sedim.result=sum(as.numeric(sedim.percent[,1])) result[12,1]=sedim.result sedim.percent=subset(class.weight.um,class.weight.um[,2]<sedim[12,1]) sedim.result=sum(as.numeric(sedim.percent[,1])) result[13,1]=sedim.result result=data.frame(result[,1]) names(result)=names(x)[b] row.names(result)=class.sedim sediment=cbind(sediment,round(result,3)) } return(sediment) } .texture.sedim <- function(x,um){ um=as.numeric(um) x=as.data.frame(x) sum.sieve=apply(x,2,sum) Texture=data.frame(matrix(ncol=0,nrow=5)) for (b in 1:dim(x)[2]) { class.weight=(x[,b]*100)/sum.sieve[b] class.weight.um=cbind(class.weight,um) class.weight.um[,1] <- as.numeric(as.character(class.weight.um[,1])) class.weight.um[,2] <- as.numeric(as.character(class.weight.um[,2])) seuil.texture=c(63000,2000,63,0) class.texture=c("Boulder","Gravel","Sand","mud") texture=data.frame(cbind(seuil.texture,class.texture),stringsAsFactors = FALSE) texture[,1]=as.numeric(texture[,1]) result=data.frame(matrix(nrow=dim(texture)[1],ncol=dim(texture)[2])) result[,1]=texture[,2] names(result)=c("Texture","Pourcentage") texture.result=0 texture.percent=subset(class.weight.um,class.weight.um[,2]>=texture[1,1]) texture.result=sum(texture.percent[,1]) result[1,2]=texture.result texture.percent=subset(class.weight.um,class.weight.um[,2]<texture[1,1] & class.weight.um[,2]>=(texture[2,1])) texture.result=sum(texture.percent[,1]) result[2,2]=texture.result texture.percent=subset(class.weight.um,class.weight.um[,2]<texture[2,1] & class.weight.um[,2]>=(texture[3,1])) texture.result=sum(texture.percent[,1]) result[3,2]=texture.result texture.percent=subset(class.weight.um,class.weight.um[,2]<(texture[3,1])) texture.result=sum(texture.percent[,1]) result[4,2]=texture.result mud=round(result[4,2],3) gravel=round(result[2,2],3) sand=round(result[3,2],3) {if (mud==0 & sand==0) mudsand=0 if (mud==0 & sand>0) mudsand=10 if (sand==0 & mud>0) mudsand=0.01 if (sand>0 & mud>0) mudsand=sand/mud} if (mudsand>=9){ if (gravel>80) texture="Gravel" if (gravel>30 & gravel<=80) texture="Sandy Gravel" if (gravel>5 & gravel<=30) texture="Gravelly Sand" if (gravel>0 & gravel<=5) texture="Slightly Gravelly Sand" if (gravel==0) texture="Sand"} if (mudsand>=1 & mudsand<9){ if (gravel>80) texture="Gravel" if (gravel>30 & gravel<=80) texture="Muddy Sandy Gravel" if (gravel>5 & gravel<=30) texture="Gravelly Muddy Sand" if (gravel>0 & gravel<=5) texture="Slightly Gravelly Muddy Sand" if (gravel==0) texture="Muddy Sand"} if (mudsand>=(1/9) & mudsand<1){ if (gravel>80) texture="Gravel" if (gravel>30 & gravel<=80) texture="Muddy Gravel" if (gravel>5 & gravel<=30) texture=" Gravelly Mud" if (gravel>0 & gravel<=5) texture="Slightly Gravelly Sandy Mud" if (gravel==0) texture="Sandy Mud"} if (mudsand<(1/9)){ if (gravel>80) texture="Gravel" if (gravel>30 & gravel<=80) texture="Muddy Gravel" if (gravel>5 & gravel<=30) texture=" Gravelly Mud" if (gravel>0 & gravel<=5) texture="Slightly Gravelly Mud" if (gravel==0) texture="Mud"} row.names(result)=result[,1] name.texture=row.names(result) result=data.frame(result[,2]) texture.sedim=data.frame(rbind(texture,round(result,3))) row.names(texture.sedim)=c("Texture",name.texture) names(texture.sedim)=names(x)[b] texture.sedim Texture=cbind(Texture,texture.sedim) } return(Texture) }
variableType <- function(v, ...) { vClass <- oClass(v)[1] summaryResult(list(feature="Variable type", result = vClass, value = vClass)) } variableType <- summaryFunction(variableType, "Data class of variable", allClasses())
DfFroc2Lroc <- function(dataset) { I <- length(dataset$ratings$NL[,1,1,1]) J <- length(dataset$ratings$NL[1,,1,1]) K <- length(dataset$ratings$NL[1,1,,1]) K2 <- length(dataset$ratings$LL[1,1,,1]) K1 <- K - K2 NL <- apply(dataset$ratings$NL, c(1, 2, 3), max) dim(NL) <- c(dim(NL), 1) LL <- dataset$ratings$LL lowestRating <- min(min(NL[is.finite(NL)]), min(LL[is.finite(LL)])) NL[,,1:K1,1][!is.finite(NL[,,1:K1,1])] <- lowestRating - 10 LL <- array(lowestRating - 10, dim = c(I,J,K2,1)) LL_IL <- array(lowestRating - 10, dim = c(I,J,K2,1)) LL1 <- dataset$ratings$LL for (i in 1:I) { for (j in 1:J) { for (k in 1:K2) { maxLL <- max(LL1[i,j,k,]) maxNL <- NL[i,j,k+K1,1] if (maxLL > maxNL) { LL[i,j,k,1] <- maxLL } else { LL_IL[i,j,k,1] <- maxNL } NL[i,j,k+K1,1] <- -Inf } } } perCase <- array(1, dim = c(K2)) IDs <- array(1, dim = c(K2,1)) weights <- array(1, dim = c(K2,1)) weights[,1] <- 1 fileName <- paste0("DfFroc2Lroc(", dataset$descriptions$fileName, ")") name <- dataset$descriptions$name design <- "FCTRL" truthTableStr <- NA type <- "LROC" modalityID <- dataset$descriptions$modalityID readerID <- dataset$descriptions$readerID return(convert2dataset(NL, LL, LL_IL, perCase, IDs, weights, fileName, type, name, truthTableStr, design, modalityID, readerID)) }
excl.missing <- function(mat, phyno) { mat = mat[!is.na(phyno$surv),] phyno$censor = phyno$censor[!is.na(phyno$surv)] phyno$surv = phyno$surv[!is.na(phyno$surv)] return(list(mat = mat, phyno = phyno)) }
filterFeatures = function(task, method = "randomForestSRC_importance", fval = NULL, perc = NULL, abs = NULL, threshold = NULL, fun = NULL, fun.args = NULL, mandatory.feat = NULL, select.method = NULL, base.methods = NULL, cache = FALSE, ...) { assertClass(task, "SupervisedTask") if (!is.null(fun)) { assertFunction(fun) } assertChoice(method, choices = append(ls(.FilterRegister), ls(.FilterEnsembleRegister))) if (method %in% ls(.FilterEnsembleRegister) && !is.null(base.methods)) { if (length(base.methods) == 1) { warningf("You only passed one base filter method to an ensemble filter. Please use at least two base filter methods to have a voting effect.") } method = list(method, base.methods) } select = checkFilterArguments(perc, abs, threshold, fun) p = getTaskNFeats(task) nselect = switch(select, perc = round(perc * p), abs = min(abs, p), threshold = p, fun = p ) if (is.null(fval)) { if (!isFALSE(cache)) { requirePackages("memoise", why = "caching of filter features", default.method = "load") if (is.character(cache)) { assertString(cache) if (!dir.exists(cache)) { dir.create(cache, recursive = TRUE) } cache.dir = cache } else { assertFlag(cache) if (!dir.exists(rappdirs::user_cache_dir("mlr", "mlr-org"))) { dir.create(rappdirs::user_cache_dir("mlr", "mlr-org")) } cache.dir = rappdirs::user_cache_dir("mlr", "mlr-org") } cache.dir = memoise::cache_filesystem(cache.dir) generate.fv.data = memoise::memoise(generateFilterValuesData, cache = cache.dir) } else { generate.fv.data = generateFilterValuesData } fval = generate.fv.data(task = task, method = method, nselect = getTaskNFeats(task), ...)$data } else { assertClass(fval, "FilterValues") if (!is.null(fval$method)) { colnames(fval$data)[which(colnames(fval$data) == "val")] = fval$method method = fval$method fval = fval$data[, c(1, 3, 2)] } else { methods = unique(fval$data$method) if (length(methods) > 1) { assert(method %in% methods) } else { method = methods fval = fval$data } } } if (all(is.na(fval$value))) { stopf("Filter method returned all NA values!") } if (!is.null(mandatory.feat)) { assertCharacter(mandatory.feat) if (!all(mandatory.feat %in% fval$name)) { stop("At least one mandatory feature was not found in the task.") } if (select != "threshold" && select != "fun" && nselect < length(mandatory.feat)) { stop("The number of features to be filtered cannot be smaller than the number of mandatory features.") } fval[fval$name %in% mandatory.feat, "value"] = Inf } if (select == "threshold") { nselect = sum(fval[["value"]] >= threshold, na.rm = TRUE) } else if (select == "fun") { nselect = do.call(fun, args = c(list("values" = fval[with(fval, order(filter, -value)), ][["value"]]), fun.args)) } if (length(levels(as.factor(fval$filter))) >= 2) { if (is.null(select.method) && !method[[1]] %in% ls(.FilterEnsembleRegister)) { stopf("You supplied multiple filters. Please choose which should be used for the final subsetting of the features.") } if (is.null(select.method)) { fval = fval[filter == method[[1]], ] } else { assertSubset(select.method, choices = unique(fval$filter)) fval = fval[fval$filter == select.method, ] } } if (nselect > 0L) { features = fval[with(fval, order(filter, -value)), ] features = features[1:nselect, ][1:nselect]$name } else { features = NULL } allfeats = getTaskFeatureNames(task) j = match(features, allfeats) features = allfeats[sort(j)] subsetTask(task, features = features) } checkFilterArguments = function(perc, abs, threshold, fun) { sum.null = sum(!is.null(perc), !is.null(abs), !is.null(threshold), !is.null(fun)) if (sum.null == 0L) { stop("At least one of 'perc', 'abs', 'threshold' or 'fun' must be not NULL") } if (sum.null >= 2L) { stop("Arguments 'perc', 'abs', 'threshold' and 'fun' are mutually exclusive") } if (!is.null(perc)) { assertNumber(perc, lower = 0, upper = 1) return("perc") } if (!is.null(abs)) { assertCount(abs) return("abs") } if (!is.null(threshold)) { assertNumber(threshold) return("threshold") } if (!is.null(fun)) { assertFunction(fun) return("fun") } }
test_that("can reorder columns", { dt <- lazy_dt(data.frame(x = 1:3, y = 1), "DT") expect_equal( dt %>% step_colorder(c("y", "x")) %>% show_query(), expr(setcolorder(copy(DT), !!c("y", "x"))) ) expect_named( dt %>% step_colorder(c("y", "x")) %>% collect(), c("y", "x") ) expect_equal( dt %>% step_colorder(c(2L, 1L)) %>% show_query(), expr(setcolorder(copy(DT), !!c(2L, 1L))) ) expect_named( dt %>% step_colorder(c(2L, 1L)) %>% collect(), c("y", "x") ) }) test_that("can handle duplicate column names", { dt <- lazy_dt(data.table(x = 3, x = 2, y = 1), "DT") expect_snapshot_error(dt %>% step_colorder(c("y", "x"))) expect_equal( dt %>% step_colorder(c(3L, 2L)) %>% show_query(), expr(setcolorder(copy(DT), !!c(3L, 2L))) ) expect_equal( dt %>% step_colorder(c(3L, 2L)) %>% as.data.table(), data.table(y = 1, x = 2, x = 3) ) }) test_that("checks col_order", { dt <- lazy_dt(data.frame(x = 1:3, y = 1), "DT") expect_snapshot_error(dt %>% step_colorder(c("y", "y"))) expect_snapshot_error(dt %>% step_colorder(c(1L, 1L))) }) test_that("works for empty input", { dt <- lazy_dt(data.frame(x = 1), "DT") expect_equal(dt %>% step_colorder(character()), dt) expect_equal(dt %>% step_colorder(integer()), dt) }) test_that("doesn't add step if not necessary", { dt <- lazy_dt(data.frame(x = 1, y = 2), "DT") expect_equal(dt %>% step_colorder(c("x", "y")), dt) expect_equal(dt %>% step_colorder("x"), dt) expect_equal(dt %>% step_colorder(1:2), dt) expect_equal(dt %>% step_colorder(1L), dt) })
f1=function(x,y,u){u-(u-x)/y } f2=function(x,y,l){l+(x-l)/y } fLB= function (x1,y1,x0,y0,l,u){ ifelse(y1>0, max(l,f1(x1,y1,u)),l)-ifelse(y0>0,min(u,f2(x0,y0,l)),u) } fUB= function (x1,y1,x0,y0,l,u){ ifelse(y1>0, min(u,f2(x1,y1,l)),u)-ifelse(y0>0,max(l,f1(x0,y0,u)),l) } CalC= function (x,hat.LB,hat.UB,sigma.LB,sigma.UB,alpha){ pnorm(x+(hat.UB-hat.LB)/max(sigma.LB,sigma.UB))-pnorm(-x)-(1-alpha) }
reqManagedAccts <- function(twsconn) { if( !is.twsConnection(twsconn)) stop('invalid twsConnection') VERSION <- "1" writeBin(c(.twsOutgoingMSG$REQ_MANAGED_ACCTS, VERSION), twsconn[[1]]) } requestFA <- function(twsconn, faDataType) { if( !is.twsConnection(twsconn)) stop('invalid twsConnection') VERSION <- "1" writeBin(c(.twsOutgoingMSG$REQ_FA, VERSION, as.character(faDataType)), twsconn[[1]]) } replaceFA <- function(twsconn, faDataType, xml) { if( !is.twsConnection(twsconn)) stop('invalid twsConnection') VERSION <- "1" writeBin( c(.twsOutgoingMSG$REPLACE_FA, VERSION, as.character(faDataType), as.character(xml)), twsconn[[1]]) }
LoadBeatVector <- function(HRVData, beatPositions, scale = 1, datetime = "1/1/1900 0:0:0"){ VerboseMessage(HRVData$Verbose, "Loading beats positions") dir = getwd() on.exit(setwd(dir)) VerboseMessage(HRVData$Verbose, paste("Scale:", scale)) beatsaux = beatPositions beatPositions = beatsaux[!duplicated(beatsaux)] if (length(beatsaux) != length(beatPositions)) { warning(paste("Removed", length(beatsaux) - length(beatPositions), "duplicated beat positions")) } datetimeaux = strptime(datetime, "%d/%m/%Y %H:%M:%S") if (is.na(datetimeaux)) { stop("Date/time format is dd/mm/yyyy HH:MM:SS") } VerboseMessage(HRVData$Verbose, paste("Date: ", sprintf("%02d", datetimeaux$mday), "/", sprintf("%02d", 1 + datetimeaux$mon), "/", 1900 + datetimeaux$year, sep = "")) VerboseMessage(HRVData$Verbose, paste("Time: ", sprintf("%02d", datetimeaux$hour), ":", sprintf("%02d", datetimeaux$min), ":", sprintf("%02d", datetimeaux$sec), sep = "")) HRVData$datetime = datetimeaux HRVData$Beat = data.frame(Time = beatPositions * scale) VerboseMessage(HRVData$Verbose, paste("Number of beats:", length(HRVData$Beat$Time))) return(HRVData) }
`minbinder` <- function(psm, cls.draw=NULL, method=c("avg","comp","draws","laugreen","all"), max.k=NULL, include.lg=FALSE, start.cl=NULL, tol=0.001){ if(any(psm !=t(psm)) | any(psm >1) | any(psm < 0) | sum(diag(psm)) != nrow(psm) ){ stop("psm must be a symmetric matrix with entries between 0 and 1 and 1's on the diagonals")} method <- match.arg(method, choices=method) if(method %in% c("draws","all") & is.null(cls.draw)) stop("cls.draw must be provided if method=''draws''") if(method == "avg" | method == "all"){ if(is.null(max.k)) max.k <- ceiling(dim(psm)[1]/4) hclust.avg <- hclust(as.dist(1-psm), method="average") cls.avg <- t(apply(matrix(1:max.k),1,function(x) cutree(hclust.avg,k=x))) binder.avg <- binder(cls.avg,psm) val.avg <- min(binder.avg) cl.avg <- cls.avg[which.min(binder.avg),] if(method== "avg") return(list(cl=cl.avg, value=val.avg, method="avg")) } if(method == "comp" | method == "all"){ if(is.null(max.k)) max.k <- ceiling(dim(psm)[1]/4) hclust.comp <- hclust(as.dist(1-psm), method="complete") cls.comp <- t(apply(matrix(1:max.k),1,function(x) cutree(hclust.comp,k=x))) binder.comp <- binder(cls.comp,psm) val.comp <- min(binder.comp) cl.comp <- cls.comp[which.min(binder.comp),] if(method== "comp") return(list(cl=cl.comp, value=val.comp, method="comp")) } if(method == "draws" | method == "all"){ compIpi <- function(cl){ mat <- cltoSim(cl)*psm sum(mat[lower.tri(mat)]) } n <- ncol(psm) no2 <- choose(n,2) sumpij <- sum(psm[lower.tri(psm)]) sumIij <- apply(cls.draw,1, function(x) sum(choose(table(x),2))) sumIpi <- apply(cls.draw,1, compIpi) binder.draws <- sumIij - 2*sumIpi + sumpij val.draws <- min(binder.draws) cl.draw <- cls.draw[which.min(binder.draws),] names(cl.draw) <- NULL if(method== "draws") return(list(cl=cl.draw, value=val.draws, method="draws")) } if(method == "laugreen" | (method == "all" & include.lg)){ res.lg <- laugreen(psm, start.cl=start.cl, tol=tol) if(method=="laugreen") return(res.lg) } vals <- c(val.avg, val.comp, val.draws) cls <- rbind(cl.avg,cl.comp,cl.draw) if(include.lg){ vals <- c(vals,res.lg$value) cls <- rbind(cls,res.lg$cl) } cls <- rbind(cls[which.min(vals),], cls) vals <- c(min(vals), vals) if(include.lg){ rownames(cls) <- names(vals) <- c("best","avg","comp","draws","laugreen") } else rownames(cls) <- names(vals) <- c("best","avg","comp","draws") colnames(cls) <- NULL res <- list(cl=cls, value=vals) if(include.lg) return(c(res,list(iter.lg=res.lg$iter.lg))) res }
theme_paleo <- function(...) { ggplot2::theme_bw(...) + ggplot2::theme(strip.background = ggplot2::element_blank()) } rotated_facet_labels <- function(angle = 45, direction = "x", remove_label_background = TRUE) { stopifnot( all(direction %in% c("x", "y")), is.numeric(angle), length(angle) == 1, angle >= -90, angle <= 90, is.logical(remove_label_background), length(remove_label_background) == 1 ) structure( list( angle = angle, direction = direction, remove_label_background = remove_label_background ), class = "rotate_facet_label_spec" ) } ggplot_add.rotate_facet_label_spec <- function(object, plot, object_name) { plot$facet <- modify_facet_clip(plot$facet, remove_clip = object$direction) facet_switch <- plot$facet$params$switch %||% plot$facet$params$strip.position %||% "none" strip_position_x <- if(facet_switch %in% c("x", "both", "bottom")) "bottom" else "top" strip_position_y <- if(facet_switch %in% c("y", "both", "left")) "left" else "right" theme_mods <- ggplot2::theme() if("x" %in% object$direction) { theme_mods <- theme_mods + theme_modify_paleo( rotate_labels_x = object$angle, remove_label_background_x = object$remove_label_background, strip_position_x = strip_position_x ) } if("y" %in% object$direction) { theme_mods <- theme_mods + theme_modify_paleo( rotate_labels_y = object$angle, remove_label_background_y = object$remove_label_background, strip_position_y = strip_position_y ) } plot + theme_mods } rotated_axis_labels <- function(angle = 90, direction = "x") { stopifnot( all(direction %in% c("x", "y")), is.numeric(angle), length(angle) == 1 ) theme_mods <- ggplot2::theme() if("x" %in% direction) { theme_mods <- theme_mods + theme_modify_paleo(rotate_axis_labels_x = angle) } if("y" %in% direction) { theme_mods <- theme_mods + theme_modify_paleo(rotate_axis_labels_y = angle) } theme_mods } theme_modify_paleo <- function(rotate_labels_x = NULL, rotate_labels_y = NULL, remove_label_background_x = FALSE, remove_label_background_y = FALSE, rotate_axis_labels_x = NULL, rotate_axis_labels_y = NULL, pad_right_inches = NULL, strip_position_x = c("top", "bottom"), strip_position_y = c("left", "right")) { strip_position_x <- match.arg(strip_position_x) strip_position_y <- match.arg(strip_position_y) theme_elements <- list( strip.text.x.top = if(!is.null(rotate_labels_x) && strip_position_x == "top") { ggplot2::element_text( angle = rotate_labels_x, hjust = if(rotate_labels_x > 0) 0 else if(rotate_labels_x < 0) 1 else 0.5, vjust = if(abs(rotate_labels_x) == 90) 0.5 else if(rotate_labels_x > 0) 0 else if(rotate_labels_x < 0) 1.1 else 0.5 ) }, strip.text.x.bottom = if(!is.null(rotate_labels_x) && strip_position_x == "bottom") { ggplot2::element_text( angle = rotate_labels_x, hjust = if(rotate_labels_x > 0) 1 else if(rotate_labels_x < 0) 0 else 0.5, vjust = if(abs(rotate_labels_x) == 90) 0.5 else if(rotate_labels_x > 0) 1 else if(rotate_labels_x < 0) 0 else 0.5 ) }, strip.text.y.right = if(!is.null(rotate_labels_y) && strip_position_y == "right") { ggplot2::element_text( angle = rotate_labels_y, hjust = if(abs(rotate_labels_y) == 90) 0.5 else 0, vjust = if(rotate_labels_y == 0) 0.5 else 0 ) }, strip.text.y.left = if(!is.null(rotate_labels_y) && strip_position_y == "left") { ggplot2::element_text( angle = rotate_labels_y, hjust = if(abs(rotate_labels_y %% 180) == 90) 0.5 else 1, vjust = if(rotate_labels_y %% 180 == 0) 0.5 else 1 ) }, axis.text.x.bottom = if(!is.null(rotate_axis_labels_x)) ggplot2::element_text( angle = rotate_axis_labels_x, hjust = if(rotate_axis_labels_x > 0) 1 else if(rotate_axis_labels_x < 0) 0 else 0.5, vjust = if(abs(rotate_axis_labels_x) == 90) 0.5 else if(abs(rotate_axis_labels_x) != 0) 1 else 0.5 ), axis.text.y.left = if(!is.null(rotate_axis_labels_y)) ggplot2::element_text( angle = rotate_axis_labels_y, hjust = if(abs(rotate_axis_labels_y) == 90) 0.5 else 1, vjust = if(rotate_axis_labels_y == 0) 0.5 else 1 ), axis.text.x.top = if(!is.null(rotate_axis_labels_x)) ggplot2::element_text( angle = rotate_axis_labels_x, hjust = if(rotate_axis_labels_x > 0) 0 else if(rotate_axis_labels_x < 0) 1 else 0.5, vjust = if(abs(rotate_axis_labels_x) == 90) 0.5 else if(abs(rotate_axis_labels_x) != 0) 0 else 0.5 ), axis.text.y.right = if(!is.null(rotate_axis_labels_y)) ggplot2::element_text( angle = rotate_axis_labels_y, hjust = if(abs(rotate_axis_labels_y) == 90) 0.5 else 0, vjust = if(rotate_axis_labels_y == 0) 0.5 else 0 ), strip.background.x = if(remove_label_background_x) ggplot2::element_blank(), strip.background.y = if(remove_label_background_y) ggplot2::element_blank(), plot.margin = if(!is.null(pad_right_inches)) grid::unit(c(0, pad_right_inches, 0, 0), "inches") ) do.call(ggplot2::theme, theme_elements[!vapply(theme_elements, is.null, logical(1))]) } modify_facet_clip <- function(facet_super_obj, remove_clip = NULL) { if(!(inherits(facet_super_obj, "FacetGrid") || inherits(facet_super_obj, "FacetWrap"))) { stop( "The current facet is not a facet_grid() or facet_wrap(). Rotate the labels after setting the facet!", call. = FALSE ) } stopifnot( all(remove_clip %in% c("x", "y", "b", "l", "r", "t")) ) ggplot2::ggproto( NULL, facet_super_obj, draw_panels = function(self, panels, layout, x_scales, y_scales, ranges, coord, data, theme, params) { panel_table <- ggplot2::ggproto_parent(facet_super_obj, self)$draw_panels( panels, layout, x_scales, y_scales, ranges, coord, data, theme, params ) if("x" %in% remove_clip) { panel_table <- set_clip(panel_table, "strip-t", "off") panel_table <- set_clip(panel_table, "strip-b", "off") } if("y" %in% remove_clip) { panel_table <- set_clip(panel_table, "strip-l", "off") panel_table <- set_clip(panel_table, "strip-r", "off") } if("b" %in% remove_clip) { panel_table <- set_clip(panel_table, "strip-b", "off") } if("r" %in% remove_clip) { panel_table <- set_clip(panel_table, "strip-r", "off") } if("t" %in% remove_clip) { panel_table <- set_clip(panel_table, "strip-t", "off") } if("l" %in% remove_clip) { panel_table <- set_clip(panel_table, "strip-l", "off") } panel_table } ) } set_clip <- function(panel_table, regex, value) { for(i in which(grepl(regex, panel_table$layout$name))){ panel_table$grobs[[i]]$layout$clip <- value } panel_table }
`%^%`=function(x, y) { paste0(x, y) } `%notin%`=function(x, vector) { match(x, vector, nomatch=0) == 0 } `%allin%`=function(x, vector) { all(x %in% vector) } `%anyin%`=function(x, vector) { any(x %in% vector) } `%nonein%`=function(x, vector) { !any(x %in% vector) } `%partin%`=function(pattern, vector) { any(grepl(pattern, vector, perl=TRUE)) } pkg_depend=function(pkgs, excludes=NULL) { default.pkgs=c("base", "boot", "class", "cluster", "codetools", "compiler", "datasets", "foreign", "graphics", "grDevices", "grid", "KernSmooth", "lattice", "MASS", "Matrix", "methods", "mgcv", "nlme", "nnet", "parallel", "rpart", "spatial", "splines", "stats", "stats4", "survival", "tcltk", "tools", "translations", "utils") exclude.pkgs=default.pkgs for(ex in excludes) exclude.pkgs=union(exclude.pkgs, unlist(tools::package_dependencies(ex, recursive=TRUE))) for(pkg in pkgs) pkgs=union(pkgs, unlist(tools::package_dependencies(pkg, recursive=TRUE))) return(sort(setdiff(pkgs, exclude.pkgs))) } pkg_install_suggested=function(by) { if(missing(by)) { pkgs.suggests=" rstudioapi, devtools, pacman, tidyverse, ggstatsplot, jmv, dplyr, tidyr, stringr, forcats, data.table, rio, haven, foreign, readxl, openxlsx, clipr, tibble, plyr, glue, crayon, emmeans, effectsize, performance, pwr, simr, MASS, sampling, careless, irr, correlation, corpcor, corrplot, afex, car, psych, lmtest, nnet, lme4, lmerTest, multilevel, r2mlm, MuMIn, metafor, meta, metaSEM, metapower, mediation, interactions, JSmediation, lavaan, lavaanPlot, semPlot, processR, jtools, reghelper, summarytools, texreg, sjstats, sjPlot, apaTables, forecast, vars, pls, plm, AER, TOSTER, BEST, BayesFactor, brms, mlr, caret, party, randomForest, e1071, varImp, downloader, rvest, RCurl, RSelenium, mailR, jiebaR, ggplot2, ggtext, cowplot, see, ggrepel, ggeffects, ggsignif, ggridges, ggthemes, ggbreak, ggplotify, ggExtra, GGally, wordcloud2, patchwork, showtext" cat("\n") Print(pkgs.suggests) cat("\n") yesno=utils::menu(title="All these packages would be installed. Do you want to install them?", choices=c("Yes", "No")) if(yesno==1) { pkgs.suggests=pkgs.suggests %>% str_remove_all("\\s") %>% str_split(",", simplify=TRUE) %>% as.character() } else { return(invisible()) } } else { pkgs.suggests=pacman::p_depends(by, character.only=TRUE, local=TRUE)$Suggests } pkgs.installed=pacman::p_library() pkgs.need.install=base::setdiff(pkgs.suggests, pkgs.installed) if(length(pkgs.need.install)>0) { utils::install.packages(pkgs.need.install) } else { if(missing(by)) Print("<<green Done!>>") else Print("<<green All packages suggested by `{by}` have been installed!>>") } } Print=function(...) { tryCatch({ output=glue::glue(..., .transformer=sprintf_transformer, .envir=parent.frame()) output_color=glue::glue_col( gsub("<<", "{", gsub(">>", "}", output)) ) print(output_color) }, error=function(e) { warning(e) print(...) }) } Glue=function(...) { output=glue::glue(..., .transformer=sprintf_transformer, .envir=parent.frame()) output_color=glue::glue_col( gsub("<<", "{", gsub(">>", "}", output)) ) return(output_color) } sprintf_transformer=function(text, envir) { text=glue::glue(text, .envir=envir) m=regexpr(":.+$", text) if(m!=-1) { format=substring(regmatches(text, m), 2) regmatches(text, m)="" res=eval(parse(text=text, keep.source=FALSE), envir) do.call(sprintf, list(glue("%{format}f"), res)) } else { eval(parse(text=text, keep.source=FALSE), envir) } } Run=function(..., silent=FALSE) { text=glue::glue(..., .sep="\n", .envir=parent.frame()) if(silent) { suppressWarnings({ eval(parse(text=text), envir=parent.frame()) }) } else { eval(parse(text=text), envir=parent.frame()) } invisible(text) } rep_char=function(char, rep.times) { paste(rep(char, times=rep.times), collapse="") } capitalize=function(string) { capped=grep("^[A-Z]", string, invert = TRUE) substr(string[capped], 1, 1)=toupper(substr(string[capped], 1, 1)) return(string) } print_table=function(x, digits=3, nsmalls=digits, row.names=TRUE, col.names=TRUE, title="", note="", append="", line=TRUE, file=NULL, file.align.head="auto", file.align.text="auto") { if(!inherits(x, c("matrix", "data.frame", "data.table"))) { coef.table=coef(summary(x)) if(!is.null(coef.table)) x=coef.table } x=as.data.frame(x) sig=NULL if(length(nsmalls)==1) nsmalls=rep(nsmalls, length(x)) for(j in 1:length(x)) { if(inherits(x[,j], "factor")) x[,j]=as.character(x[,j]) if(grepl("Pr\\(|pval|p.value|<i>p</i>", names(x)[j])) { sig=formatF(sig.trans(x[,j]), 0) if(grepl("<i>p</i>", names(x)[j])==FALSE) names(x)[j]="p" x[,j]=p.trans(x[,j]) } else { x[,j]=formatF(x[,j], nsmalls[j]) } if(grepl("^S\\.E\\.$|^Std\\. Error$|^se$|^SE$|^BootSE$", names(x)[j])) { x[,j]=paste0("(", x[,j], ")") x[grepl("\\d", x[,j])==FALSE, j]="" if(grepl("S\\.E\\.", names(x)[j])==FALSE) names(x)[j]="S.E." } if(grepl("^S\\.D\\.$|^Std\\. Deviation$", names(x)[j])) { x[,j]=paste0("(", x[,j], ")") x[grepl("\\d", x[,j])==FALSE, j]="" if(grepl("S\\.D\\.", names(x)[j])==FALSE) names(x)[j]="S.D." } names(x)[j]=gsub(" value$|val$", "", names(x)[j]) } if(is.null(sig)==FALSE & "sig" %notin% names(x)) { p.pos=which(names(x) %in% c("p", "<i>p</i>")) nvars=length(names(x)) if(p.pos<nvars) x=cbind(x[1:p.pos], ` `=sig, x[(p.pos+1):nvars]) else x=cbind(x, ` `=sig) x$` `=as.character(x$` `) } if(class(row.names)=="character") { row.names(x)=row.names row.names=TRUE } if(class(col.names)=="character") { names(x)=col.names col.names=TRUE } linechar=ifelse(line, "\u2500", "-") title.length=nchar(names(x), type="width") vars.length=c() for(j in 1:length(x)) vars.length[j]=max(nchar(x[,j], type="width")) n.lines=apply(rbind(title.length, vars.length), 2, max)+2 n.lines.rn=max(nchar(row.names(x), type="width"))+2 if(row.names) table.line=rep_char(linechar, sum(n.lines)+n.lines.rn) else table.line=rep_char(linechar, sum(n.lines)) if(is.null(file)) { if(title!="") Print(title) Print(table.line) if(row.names) cat(rep_char(" ", n.lines.rn)) for(j in 1:length(x)) { name.j=names(x)[j] cat(rep_char(" ", n.lines[j]-nchar(name.j, type="width")) %^% name.j) } cat("\n") Print(table.line) for(i in 1:nrow(x)) { if(row.names) { row.name.i=row.names(x)[i] cat(row.name.i %^% rep_char(" ", n.lines.rn-nchar(row.name.i, type="width"))) } for(j in 1:length(x)) { x.ij=ifelse(is.na(x[i,j]) | grepl("NA$", x[i,j]), "", x[i,j]) cat(rep_char(" ", n.lines[j]-nchar(x.ij, type="width")) %^% x.ij) } cat("\n") } Print(table.line) if(note!="") Print(note) } if(row.names) { x=cbind(rn=row.names(x), x) names(x)[1]="" } if(!is.null(file)) { html=df_to_html(x, title=title, note=note, append=append, file=file, align.head=file.align.head, align.text=file.align.text) } else { html=NULL } invisible(list(df=x, html=html)) } df_to_html=function(df, title="", note="", append="", file=NULL, align.head="auto", align.text="auto") { if(!is.null(file)) { if(file=="NOPRINT") { file=NULL } else { file=str_replace(file, "\\.docx$", ".doc") if(str_detect(file, "\\.doc$")==FALSE) file=paste0(file, ".doc") } } TITLE=title TNOTE=note APPEND=append if(length(align.head)==1) { if(align.head=="auto") align.head=c("left", rep("right", times=ncol(df)-1)) else align.head=rep(align.head, times=ncol(df)) } if(length(align.text)==1) { if(align.text=="auto") align.text=c("left", rep("right", times=ncol(df)-1)) else align.text=rep(align.text, times=ncol(df)) } df=as.data.frame(df) for(j in 1:ncol(df)) { df[[j]]="<td align='" %^% align.text[j] %^% "'>" %^% str_trim(str_replace_all(df[[j]], "^\\s*-{1}", "\u2013")) %^% "</td>" } THEAD="<tr> " %^% paste("<th align='" %^% align.head %^% "'>" %^% names(df) %^% "</th>", collapse=" ") %^% " </tr>" TBODY="<tr> " %^% paste(apply(df, 1, function(...) paste(..., collapse=" ")), collapse=" </tr>\n<tr> ") %^% " </tr>" TBODY=TBODY %>% str_replace_all(">\\s*NA\\s*<", "><") %>% str_replace_all("\\s+</td>", "</td>") %>% str_replace_all("\\[\\s+", "[") %>% str_replace_all("\\,\\s+", ", ") %>% str_replace_all("<\\.001", "< .001") TABLE=paste0(" <table> <thead> ", THEAD, " </thead> <tbody> ", TBODY, " </tbody> </table> ") HTML=paste0("<!DOCTYPE html> <html> <head> <meta charset='utf-8'> <title></title> <style> ", ifelse( grepl("\\.doc$", file), "body, pre {font-size: 10.5pt; font-family: Times New Roman;}", "" ), " p {margin: 0px;} table {border-collapse: collapse; border-spacing: 0px; color: border-top: 2px solid table thead th {border-bottom: 1px solid table th, table td {padding-left: 5px; padding-right: 5px; height: 19px;} </style> </head> <body> <p>", TITLE, "</p>", TABLE, "<p>", TNOTE, "</p>", APPEND, " </body> </html>") if(!is.null(file)) { if(file!="NOPRINT") { f=file(file, "w", encoding="UTF-8") cat(HTML, file=f) close(f) Print("<<green \u221a>> Table saved to <<bold \"{paste0(getwd(), '/', file)}\">>") cat("\n") } } invisible(list(HTML=HTML, TABLE=TABLE)) } formatN=function(x, mark=",") { format(x, big.mark=mark) } formatF=function(x, digits=3, nsmall=digits) { if(inherits(x, "character")) { xf=sprintf(paste0("%-", max(nchar(x), na.rm=TRUE), "s"), x) } else { x=sprintf(paste0("%.", nsmall, "f"), x) xf=sprintf(paste0("%", max(nchar(x), na.rm=TRUE), "s"), x) } return(xf) } RGB=function(r, g, b, alpha) { grDevices::rgb(r/255, g/255, b/255, alpha) } dtime=function(t0, unit="secs", digits=0, nsmall=digits) { dt=difftime(Sys.time(), t0, units=unit) format(dt, digits=1, nsmall=nsmall) } set.wd=function(path=NULL, ask=FALSE) { is.windows=ifelse(Sys.info()[["sysname"]]=="Windows", TRUE, FALSE) if(is.null(path)) { tryCatch({ if(ask) { if(is.windows) path=iconv(rstudioapi::selectDirectory(), from="UTF-8", to="GBK") else path=rstudioapi::selectDirectory() } else { path=dirname(rstudioapi::getSourceEditorContext()$path) } }, error=function(e) { message("Your RStudio version is: ", rstudioapi::getVersion(), "\n") message("Please update RStudio to the latest version:\n", "https://rstudio.com/products/rstudio/download/preview/\n") }) } if(length(path)>0) { Run("setwd(\"{path}\")") Print("<<green \u221a>> Set working directory to <<bold \"{getwd()}\">>") } invisible(path) } set_wd=set.wd file_ext=function(filename) { filename=str_trim(filename) pos=regexpr("\\.([[:alnum:]]+)$", filename) ifelse(pos>-1L, tolower(substring(filename, pos+1L)), "") } import=function(file, sheet=NULL, range=NULL, encoding=NULL, header="auto", setclass=as, as="data.frame") { if(missing(file)) { file="clipboard" fmt="clipboard" } else { if(file.exists(file)==FALSE) stop("No such file. Did you forget adding the path or file extension?", call.=FALSE) fmt=file_ext(file) } if(fmt=="") { stop("File has no extension.", call.=FALSE) } else if(fmt=="clipboard") { if(header=="auto") header=TRUE x=clipr::read_clip() if(is.null(x) | (is.character(x) & length(x)==1 & x[1]=="")) stop("The system clipboard is empty. You may first copy something.", call.=FALSE) else data=clipr::read_clip_tbl(x=x, header=header) } else if(fmt %in% c("rds")) { data=readRDS(file=file) } else if(fmt %in% c("rda", "rdata")) { envir=new.env() load(file=file, envir=envir) if(length(ls(envir))>1) warning("Rdata file contains multiple objects. Returning the first object.", call.=TRUE) data=get(ls(envir)[1], envir) } else if(fmt %in% c("txt", "csv", "csv2", "tsv", "psv")) { if(is.null(encoding)) encoding="unknown" data=data.table::fread(input=file, sep="auto", encoding=encoding, header=header) } else if(fmt %in% c("xls", "xlsx")) { if(header=="auto") header=TRUE data=readxl::read_excel(path=file, sheet=sheet, range=range, col_names=header) } else if(fmt %in% c("sav")) { try({ error=TRUE data=foreign::read.spss( file=file, reencode=ifelse(is.null(encoding), NA, encoding), to.data.frame=TRUE, use.value.labels=FALSE) error=FALSE }, silent=TRUE) if(error) { message("[Retry] Using `haven::read_sav()` to import the data...") data=haven::read_sav(file=file, encoding=encoding) } } else if(fmt %in% c("dta")) { try({ error=TRUE data=foreign::read.dta(file=file, convert.factors=FALSE) error=FALSE }, silent=TRUE) if(error) { message("[Retry] Using `haven::read_dta()` to import the data...") data=haven::read_dta(file=file, encoding=encoding) } } else { data=rio::import(file=file) } if(is.data.frame(data)) Print("<<green \u221a>> Successfully imported: {nrow(data)} obs. of {ncol(data)} variables") else Print("<<green \u221a>> Successfully imported: {length(data)} values of class `{class(data)[1]}`") if(is.null(setclass) | fmt %in% c("rds", "rda", "rdata")) { return(data) } else if(setclass %in% c("data.frame", "df", "DF")) { return(base::as.data.frame(data)) } else if(setclass %in% c("data.table", "dt", "DT")) { return(data.table::as.data.table(data)) } else if(setclass %in% c("tibble", "tbl_df", "tbl")) { return(tibble::as_tibble(data)) } else { return(data) } } export=function(x, file, sheet=NULL, encoding=NULL, header="auto", overwrite=TRUE) { if(missing(file)) { file="clipboard" fmt="clipboard" } else { if(file.exists(file)==TRUE) { if(overwrite) message("Overwrite file \"", file, "\" ...") else stop("File \"", file, "\" existed!", call.=FALSE) } fmt=file_ext(file) } if(fmt=="") { stop("File has no extension.", call.=FALSE) } else if(fmt=="clipboard") { if(header=="auto") header=TRUE suppressWarnings({ clipr::write_clip(content=x, sep="\t", row.names=FALSE, col.names=header) }) } else if(fmt %in% c("rds")) { saveRDS(object=x, file=file) } else if(fmt %in% c("rda", "rdata")) { if(is.data.frame(x)) { save(x, file=file) } else if(is.list(x)) { if(inherits(x, "list")==FALSE) x=list(x) if(is.null(names(x))) names(x)=paste0("List", 1:length(x)) envir=as.environment(x) save(list=names(x), file=file, envir=envir) } else if(is.environment(x)) { save(list=ls(x), file=file, envir=x) } else if(is.character(x)) { save(list=x, file=file) } else { stop("`x` must be a data.frame, list, or environment.", call.=FALSE) } } else if(fmt %in% c("txt", "csv", "csv2", "tsv", "psv")) { sep=switch(fmt, txt="\t", csv=",", csv2=";", tsv="\t", psv="|") dec=ifelse(fmt=="csv2", ",", ".") if(header=="auto") header=TRUE if(is.null(encoding)) { data.table::fwrite(x=x, file=file, sep=sep, dec=dec, row.names=FALSE, col.names=header) } else { utils::write.table(x=x, file=file, sep=sep, dec=dec, row.names=FALSE, col.names=header, quote=FALSE, na="", fileEncoding=encoding) } } else if(fmt %in% c("xls", "xlsx")) { if(inherits(x, "list")==FALSE) x=list(x) if(header=="auto") header=TRUE if(is.null(sheet)) { if(is.null(names(x))) names(x)=paste0("Sheet", 1:length(x)) openxlsx::write.xlsx(x=x, file=file, overwrite=overwrite, rowNames=FALSE, colNames=header) } else { sheet=as.character(sheet) if(length(x)==length(sheet)) { n=length(x) if(file.exists(file)) { wb=openxlsx::loadWorkbook(file=file) sheets=openxlsx::getSheetNames(file=file) for(i in 1:n) { if(sheet[i] %in% sheets) openxlsx::removeWorksheet(wb, sheet=sheet[i]) openxlsx::addWorksheet(wb, sheetName=sheet[i]) openxlsx::writeData(wb, sheet=sheet[i], x=x[[i]], rowNames=FALSE, colNames=header) } openxlsx::saveWorkbook(wb, file=file, overwrite=TRUE) } else { names(x)=sheet openxlsx::write.xlsx(x=x, file=file, overwrite=overwrite, rowNames=FALSE, colNames=header) } } else { stop("Length of sheet should be equal to length of x!", call.=FALSE) } } } else if(fmt %in% c("sav")) { x=restore_labelled(x) haven::write_sav(data=x, path=file) } else if(fmt %in% c("dta")) { x=restore_labelled(x) haven::write_dta(data=x, path=file) } else { rio::export(x=x, file=file) } if(fmt=="clipboard") Print("<<green \u221a>> Successfully paste to clipboard") else Print("<<green \u221a>> Successfully saved to <<bold \"{paste0(getwd(), '/', file)}\">>") } restore_labelled=function(x) { x[]=lapply(x, function(v) { if(is.factor(v)) { haven::labelled( x=as.numeric(v), labels=stats::setNames(seq_along(levels(v)), levels(v)), label=attr(v, "label", exact=TRUE)) } else if(!is.null(attr(v, "labels", exact=TRUE)) | !is.null(attr(v, "label", exact=TRUE))) { haven::labelled( x=v, labels=attr(v, "labels", exact=TRUE), label=attr(v, "label", exact=TRUE)) } else { v } }) x } LOOKUP=function(data, vars, data.ref, vars.ref, vars.lookup, return=c("new.data", "new.var", "new.value")) { by=vars.ref names(by)=vars data.ref=as.data.frame(data.ref) data.new=left_join(data, data.ref[c(vars.ref, vars.lookup)], by=by) if(nrow(data.new)>nrow(data)) warning("More than one values are matched!", call.=TRUE) if(length(return)==3) return="new.data" if(return=="new.value" & length(vars.lookup)>=2) return="new.var" if(return=="new.data") { return(data.new) } else if(return=="new.var") { return(data.new[vars.lookup]) } else if(return=="new.value") { return(data.new[[vars.lookup]]) } }
seriate_dist_spectral <- function(x, control = NULL) { .get_parameters(control, NULL) W <- 1 / (1 + as.matrix(x)) D <- diag(rowSums(W)) L <- D - W q <- eigen(L) fiedler <- q$vectors[, ncol(W) - 1L] o <- order(fiedler) names(o) <- names(x)[o] o } seriate_dist_spectral_norm <- function(x, control = NULL) { .get_parameters(control, NULL) W <- 1 / (1 + as.matrix(x)) D_sqrt <- diag(rowSums(1 / W ^ .5)) L <- D_sqrt %*% W %*% D_sqrt z <- eigen(L)$vectors q <- D_sqrt %*% z largest_ev <- q[, 2L] o <- order(largest_ev) names(o) <- names(x)[o] o } set_seriation_method( "dist", "Spectral", seriate_dist_spectral, "Spectral seriation (Ding and He 2004) uses a relaxation to minimize the 2-Sum Problem (Barnard, Pothen, and Simon 1993). It uses the order of the Fiedler vector of the similarity matrix's Laplacian." ) set_seriation_method( "dist", "Spectral_norm", seriate_dist_spectral_norm, "Spectral seriation (Ding and He 2004) uses a relaxation to minimize the 2-Sum Problem (Barnard, Pothen, and Simon 1993). It uses the order of the Fiedler vector of the similarity matrix's normalized Laplacian." )
set <- function(dend, ...) { UseMethod("set") } set.dendrogram <- function(dend, what = c( "labels", "labels_colors", "labels_cex", "labels_to_character", "leaves_pch", "leaves_cex", "leaves_col", "nodes_pch", "nodes_cex", "nodes_col", "hang_leaves", "rank_branches", "branches_k_color", "branches_k_lty", "branches_col", "branches_lwd", "branches_lty", "by_labels_branches_col", "by_labels_branches_lwd", "by_labels_branches_lty", "by_lists_branches_col", "by_lists_branches_lwd", "by_lists_branches_lty", "highlight_branches_col", "highlight_branches_lwd", "clear_branches", "clear_leaves" ), value, order_value = FALSE, ...) { if (missing(what)) { if (dendextend_options("warn")) warning("'what' is missing, returning the dendrogram as is") return(dend) } if (order_value) value <- value[order.dendrogram(dend)] what <- match.arg(what) dend <- switch(what, labels = `labels<-.dendrogram`(dend, value = value, ...), labels_colors = color_labels(dend, col = value, ...), labels_cex = assign_values_to_leaves_nodePar(dend, value, "lab.cex", ...), labels_to_character = set(dend, what = "labels", value = as.character(labels(dend)), ...), leaves_pch = assign_values_to_leaves_nodePar(dend, value, "pch", ...), leaves_cex = assign_values_to_leaves_nodePar(dend, value, "cex", ...), leaves_col = assign_values_to_leaves_nodePar(dend, value, "col", ...), nodes_pch = assign_values_to_nodes_nodePar(dend, value, "pch", ...), nodes_cex = assign_values_to_nodes_nodePar(dend, value, "cex", ...), nodes_col = assign_values_to_nodes_nodePar(dend, value, "col", ...), hang_leaves = hang.dendrogram(dend, hang = ifelse(missing(value), .1, value), ...), rank_branches = rank_branches(dend, ...), branches_k_color = color_branches(dend, col = value, ...), branches_k_lty = lty_branches(dend, lty = value, ...), branches_col = assign_values_to_branches_edgePar(dend, value = value, edgePar = "col", ...), branches_lwd = assign_values_to_branches_edgePar(dend, value = value, edgePar = "lwd", ...), branches_lty = assign_values_to_branches_edgePar(dend, value = value, edgePar = "lty", ...), by_labels_branches_col = branches_attr_by_labels(dend, labels = value, attr = "col", ...), by_labels_branches_lwd = branches_attr_by_labels(dend, labels = value, attr = "lwd", ...), by_labels_branches_lty = branches_attr_by_labels(dend, labels = value, attr = "lty", ...), by_lists_branches_col = branches_attr_by_lists(dend, lists = value, attr = "col", ...), by_lists_branches_lwd = branches_attr_by_lists(dend, lists = value, attr = "lwd", ...), by_lists_branches_lty = branches_attr_by_lists(dend, lists = value, attr = "lty", ...), highlight_branches_col = highlight_branches_col(dend, values = value, ...), highlight_branches_lwd = highlight_branches_lwd(dend, values = value, ...), clear_branches = remove_branches_edgePar(dend, ...), clear_leaves = remove_leaves_nodePar(dend, ...) ) dend } set.dendlist <- function(dend, ..., which) { if (missing(which)) which <- 1:length(dend) for (i in which) { dend[[i]] <- set(dend[[i]], ...) } dend } set.data.table <- function(...) { warning("set function has been overridden from data.table - which means that data.table's set() is now slower. You may solve this by using the prefix 'data.table::'' in your for loop.") data.table::set(...) }
g.triESS <- function(params, respvec, VC, TIn){ mean1 <- TIn$theta12 * TIn$mar1 mean2 <- TIn$theta13 * TIn$mar1 mean3 <- TIn$theta12 * TIn$mar2 mean4 <- TIn$theta23 * TIn$mar2 mean5 <- TIn$theta13 * TIn$mar3 mean6 <- TIn$theta23 * TIn$mar3 var1 <- 1 - TIn$theta12^2 var2 <- 1 - TIn$theta13^2 var3 <- 1 - TIn$theta23^2 cov1 <- TIn$theta23 - TIn$theta12 * TIn$theta13 cov2 <- TIn$theta13 - TIn$theta12 * TIn$theta23 cov3 <- TIn$theta12 - TIn$theta13 * TIn$theta23 cov1 <- mmf(cov1, max.pr = VC$max.pr) cov2 <- mmf(cov2, max.pr = VC$max.pr) cov3 <- mmf(cov3, max.pr = VC$max.pr) d.1 <- dnorm(TIn$mar1) d.2 <- dnorm(TIn$mar2) d.3 <- dnorm(TIn$mar3) p.1.11 <- mm(pbinorm( TIn$mar2, TIn$mar3, mean1 = mean1[VC$inde], mean2 = mean2[VC$inde], var1 = var1, var2 = var2, cov12 = cov1), min.pr = VC$min.pr, max.pr = VC$max.pr ) p.1.10 <- mm(pbinorm( TIn$mar2, -TIn$mar3, mean1 = mean1[VC$inde], mean2 = -mean2[VC$inde], var1 = var1, var2 = var2, cov12 = -cov1), min.pr = VC$min.pr, max.pr = VC$max.pr ) p.1.00 <- mm(pbinorm(-TIn$mar2, -TIn$mar3, mean1 = -mean1[VC$inde], mean2 = -mean2[VC$inde], var1 = var1, var2 = var2, cov12 = cov1), min.pr = VC$min.pr, max.pr = VC$max.pr ) p.1.01 <- mm(pbinorm(-TIn$mar2, TIn$mar3, mean1 = -mean1[VC$inde], mean2 = mean2[VC$inde], var1 = var1, var2 = var2, cov12 = -cov1), min.pr = VC$min.pr, max.pr = VC$max.pr ) p.2.11 <- mm(pbinorm( TIn$mar1[VC$inde], TIn$mar3, mean1 = mean3, mean2 = mean4, var1 = var1, var2 = var3, cov12 = cov2) , min.pr = VC$min.pr, max.pr = VC$max.pr) p.2.10 <- mm(pbinorm( TIn$mar1[VC$inde], -TIn$mar3, mean1 = mean3, mean2 = -mean4, var1 = var1, var2 = var3, cov12 = -cov2) , min.pr = VC$min.pr, max.pr = VC$max.pr) p.3.11 <- mm(pbinorm( TIn$mar1[VC$inde], TIn$mar2, mean1 = mean5, mean2 = mean6, var1 = var2, var2 = var3, cov12 = cov3) , min.pr = VC$min.pr, max.pr = VC$max.pr) p.3.10 <- mm(pbinorm( TIn$mar1[VC$inde], -TIn$mar2, mean1 = mean5, mean2 = -mean6, var1 = var2, var2 = var3, cov12 = -cov3) , min.pr = VC$min.pr, max.pr = VC$max.pr) dmar1 <- probm(TIn$eta1, VC$margins[1], only.pr = FALSE, min.dn = VC$min.dn, min.pr = VC$min.pr, max.pr = VC$max.pr)$d.n dmar2 <- probm(TIn$eta2, VC$margins[2], only.pr = FALSE, min.dn = VC$min.dn, min.pr = VC$min.pr, max.pr = VC$max.pr)$d.n dmar3 <- probm(TIn$eta3, VC$margins[3], only.pr = FALSE, min.dn = VC$min.dn, min.pr = VC$min.pr, max.pr = VC$max.pr)$d.n dF1.de1 <- (1/d.1) * dmar1 dF2.de2 <- (1/d.2) * dmar2 dF3.de3 <- (1/d.3) * dmar3 dl.dF1.1 <- - respvec$cy1/TIn$p0 * d.1 dl.dF1.1[VC$inde] <- respvec$y1.y2.y3/TIn$p111 * d.1[VC$inde] * p.1.11 + respvec$y1.y2.cy3/TIn$p110 * d.1[VC$inde] * p.1.10 + respvec$y1.cy2.cy3/TIn$p100 * d.1[VC$inde] * p.1.00 + respvec$y1.cy2.y3/TIn$p101 * d.1[VC$inde] * p.1.01 dl.dF1 <- dl.dF1.1 dl.de1 <- dl.dF1 * dF1.de1 dl.dF2 <- respvec$y1.y2.y3/TIn$p111 * d.2 * p.2.11 + respvec$y1.y2.cy3/TIn$p110 * d.2 * p.2.10 - respvec$y1.cy2.cy3/TIn$p100 * d.2 * p.2.10 - respvec$y1.cy2.y3/TIn$p101 * d.2 * p.2.11 dl.de2 <- dl.dF2 * dF2.de2 dl.dF3 <- respvec$y1.y2.y3/TIn$p111 * d.3 * p.3.11 - respvec$y1.y2.cy3/TIn$p110 * d.3 * p.3.11 - respvec$y1.cy2.cy3/TIn$p100 * d.3 * p.3.10 + respvec$y1.cy2.y3/TIn$p101 * d.3 * p.3.10 dl.de3 <- dl.dF3 * dF3.de3 mean.12 <- ( TIn$mar1[VC$inde] * (TIn$theta13 - TIn$theta12 * TIn$theta23) + TIn$mar2 * (TIn$theta23 - TIn$theta12 * TIn$theta13) )/( 1 - TIn$theta12^2 ) mean.13 <- ( TIn$mar1[VC$inde] * (TIn$theta12 - TIn$theta13 * TIn$theta23) + TIn$mar3 * (TIn$theta23 - TIn$theta12 * TIn$theta13) )/( 1 - TIn$theta13^2 ) mean.23 <- ( TIn$mar2 * (TIn$theta12 - TIn$theta13 * TIn$theta23) + TIn$mar3 * (TIn$theta13 - TIn$theta12 * TIn$theta23) )/( 1 - TIn$theta23^2 ) deno <- 1 - TIn$theta12^2 - TIn$theta13^2 - TIn$theta23^2 + 2 * TIn$theta12 * TIn$theta13 * TIn$theta23 sd.12 <- sqrt( deno / ( 1 - TIn$theta12^2 ) ) sd.13 <- sqrt( deno / ( 1 - TIn$theta13^2 ) ) sd.23 <- sqrt( deno / ( 1 - TIn$theta23^2 ) ) p12.g <- mm( pnorm( (TIn$mar3 - mean.12)/sd.12) , min.pr = VC$min.pr, max.pr = VC$max.pr) p13.g <- mm( pnorm( (TIn$mar2 - mean.13)/sd.13) , min.pr = VC$min.pr, max.pr = VC$max.pr) p23.g <- mm( pnorm( (TIn$mar1[VC$inde] - mean.23)/sd.23) , min.pr = VC$min.pr, max.pr = VC$max.pr) p12.g.c <- mm(1 - p12.g, min.pr = VC$min.pr, max.pr = VC$max.pr) p13.g.c <- mm(1 - p13.g, min.pr = VC$min.pr, max.pr = VC$max.pr) p23.g.c <- mm(1 - p23.g, min.pr = VC$min.pr, max.pr = VC$max.pr) d11.12 <- dbinorm( TIn$mar1[VC$inde], TIn$mar2, cov12 = TIn$theta12) d11.13 <- dbinorm( TIn$mar1[VC$inde], TIn$mar3, cov12 = TIn$theta13) d11.23 <- dbinorm( TIn$mar2 , TIn$mar3, cov12 = TIn$theta23) dl.dtheta12 <- respvec$y1.y2.y3/TIn$p111 * d11.12 * p12.g + respvec$y1.y2.cy3/TIn$p110 * d11.12 * p12.g.c - respvec$y1.cy2.cy3/TIn$p100 * d11.12 * p12.g.c - respvec$y1.cy2.y3/TIn$p101 * d11.12 * p12.g dl.dtheta13 <- respvec$y1.y2.y3/TIn$p111 * d11.13 * p13.g - respvec$y1.y2.cy3/TIn$p110 * d11.13 * p13.g - respvec$y1.cy2.cy3/TIn$p100 * d11.13 * p13.g.c + respvec$y1.cy2.y3/TIn$p101 * d11.13 * p13.g.c dl.dtheta23 <- respvec$y1.y2.y3/TIn$p111 * d11.23 * p23.g - respvec$y1.y2.cy3/TIn$p110 * d11.23 * p23.g + respvec$y1.cy2.cy3/TIn$p100 * d11.23 * p23.g - respvec$y1.cy2.y3/TIn$p101 * d11.23 * p23.g if(VC$Chol == FALSE){ dtheta12.dtheta12.st <- 4 * exp( 2 * TIn$theta12.st )/( exp(2 * TIn$theta12.st) + 1 )^2 dtheta13.dtheta13.st <- 4 * exp( 2 * TIn$theta13.st )/( exp(2 * TIn$theta13.st) + 1 )^2 dtheta23.dtheta23.st <- 4 * exp( 2 * TIn$theta23.st )/( exp(2 * TIn$theta23.st) + 1 )^2 dl.dtheta12.st <- dl.dtheta12 * dtheta12.dtheta12.st dl.dtheta13.st <- dl.dtheta13 * dtheta13.dtheta13.st dl.dtheta23.st <- dl.dtheta23 * dtheta23.dtheta23.st } if(VC$Chol == TRUE){ dl.dtheta <- matrix(c ( dl.dtheta12, dl.dtheta13, dl.dtheta23), length(which(VC$inde==TRUE)), 3) dth12.dth12.st <- 1/(1 + TIn$theta12.st^2)^(3/2) dth12.dth13.st <- 0 dth12.dth23.st <- 0 dth13.dth12.st <- 0 dth13.dth13.st <- (1 + TIn$theta23.st^2)/(1 + TIn$theta13.st^2 + TIn$theta23.st^2)^(3/2) dth13.dth23.st <- - (TIn$theta13.st * TIn$theta23.st)/(1 + TIn$theta13.st^2 + TIn$theta23.st^2)^(3/2) dth23.dth12.st <- TIn$theta13.st/sqrt((1 + TIn$theta12.st^2) * (1 + TIn$theta13.st^2 + TIn$theta23.st^2)) - (TIn$theta12.st * (TIn$theta12.st * TIn$theta13.st + TIn$theta23.st))/((1 + TIn$theta12.st^2)^(3/2) * sqrt(1 + TIn$theta13.st^2 + TIn$theta23.st^2)) dth23.dth13.st <- TIn$theta12.st/sqrt((1 + TIn$theta12.st^2) * (1 + TIn$theta13.st^2 + TIn$theta23.st^2)) - (TIn$theta13.st * (TIn$theta12.st * TIn$theta13.st + TIn$theta23.st))/(sqrt(1 + TIn$theta12.st^2) * (1 + TIn$theta13.st^2 + TIn$theta23.st^2)^(3/2)) dth23.dth23.st <- 1/sqrt((1 + TIn$theta12.st^2) * (1 + TIn$theta13.st^2 + TIn$theta23.st^2)) - (TIn$theta23.st * (TIn$theta12.st * TIn$theta13.st + TIn$theta23.st))/(sqrt(1 + TIn$theta12.st^2) * (1 + TIn$theta13.st^2 + TIn$theta23.st^2)^(3/2)) dtheta.theta.st <- matrix( c( dth12.dth12.st, dth13.dth12.st, dth23.dth12.st, dth12.dth13.st, dth13.dth13.st, dth23.dth13.st, dth12.dth23.st, dth13.dth23.st, dth23.dth23.st ), 3 , 3) dl.dtheta.st <- dl.dtheta %*% dtheta.theta.st dl.dtheta12.st <- dl.dtheta.st[, 1] dl.dtheta13.st <- dl.dtheta.st[, 2] dl.dtheta23.st <- dl.dtheta.st[, 3] } GTRIVec <- list(p12.g = p12.g, p13.g = p13.g, p23.g = p23.g, p12.g.c = p12.g.c, p13.g.c = p13.g.c, d.1 = d.1, d.2 = d.2, d.3 = d.3, dmar1 = dmar1, dmar2 = dmar2, dmar3 = dmar3, d11.12 = d11.12, d11.13 = d11.13, d11.23 = d11.23, p.1.11 = p.1.11, p.1.10 = p.1.10, p.1.00 = p.1.00, p.1.01 = p.1.01, p.2.11 = p.2.11, p.2.10 = p.2.10, p.3.11 = p.3.11, p.3.10 = p.3.10, dF1.de1 = dF1.de1, dF2.de2 = dF2.de2, dF3.de3 = dF3.de3, dl.dF1 = dl.dF1, dl.dF2 = dl.dF2, dl.dF3 = dl.dF3, dl.de1 = VC$weights*dl.de1, dl.de2 = VC$weights[VC$inde]*dl.de2, dl.de3 = VC$weights[VC$inde]*dl.de3, dl.dtheta12.st = VC$weights[VC$inde]*dl.dtheta12.st, dl.dtheta13.st = VC$weights[VC$inde]*dl.dtheta13.st, dl.dtheta23.st = VC$weights[VC$inde]*dl.dtheta23.st, mean.12 = mean.12, mean.13 = mean.13, mean.23 = mean.23, sd.12 =sd.12, sd.13 =sd.13, sd.23 =sd.23, dl.dtheta12 =dl.dtheta12, dl.dtheta13 = dl.dtheta13, dl.dtheta23 = dl.dtheta23) GTRIVec }
library(liteq) library(DBI) require(tidyverse) require(jsonlite) queues_db <- "~/Downloads/queuesdb" q <- ensure_queue("jobs", db = queues_db) urls <- paste0("https://news.ycombinator.com/news?p=", 1) map(urls, partial(publish, q = q, title = "get_links")) result_db <- src_sqlite(path = "~/Downloads/resultdb", create = TRUE) result_tbl <- tibble( id = integer(), title = character(), points = integer(), comments = integer(), html_title = character(), url = character(), timestamp = integer()) %>% copy_to(result_db, ., "hackernews", indexes = list(id_idx = "id")) parse_hackernews_row <- function(row){ tibble( id = row[[1]] %>% html_attr("id") %>% as.integer, title = row[[1]] %>% html_node(".storylink") %>% html_text, points = row[[2]] %>% html_node(".score") %>% html_text %>% parse_number, comments = row[[2]] %>% html_node("a+ a") %>% html_text %>% parse_number(na = c("", "NA", "discuss")), html_title = character(1), url = row[[1]] %>% html_node(".storylink") %>% html_attr("href"), timestamp = as.integer(Sys.time()) ) } scrape_hackernews <- function(url){ doc <- read_html(url) doc %>% html_node(".itemlist") %>% html_nodes("tr") %>% .[-c(length(.):(length(.)-1))] %>% {split(., rep(seq(length(.)/3), each = 3))} %>% map_df(parse_hackernews_row) } flawed_scraper <- function(url){ read_html(url) %>% html_node("title") %>% html_text } do_job <- function(msg, db, q){ if(msg$title == "get_links"){ out <- scrape_hackernews(msg$message) messages <- build_messages(out[, c("id", "url")]) map(unlist(messages), partial(publish, q = q, title = "get_title")) dbWriteTable(db$con, "hackernews", out, append = TRUE) } if(msg$title == "get_title"){ message <- fromJSON(msg$message) out <- flawed_scraper(message$url) sql <- sprintf("UPDATE hackernews SET html_title='%s' WHERE id=%d", out, message$id) dbExecute(db$con, sql) } } build_messages <- function(dat){ by_row(dat, ~toJSON(as.list(.), auto_unbox = TRUE))$.out } msg <- try_consume(q) while(!is.null(msg)){ cat(msg$id, msg$title, "\n") tryCatch({do_job(msg, result_db, q); ack(msg)}, error = function(e) nack(msg)) msg <- try_consume(q) } failed_messages <- list_failed_messages(q) result_without_html_table <- result_tbl %>% filter(html_title == "") %>% collect nrow(failed_messages) == nrow(result_without_html_table)
faMAP <- function(R, max.fac = 8, Print=TRUE, Plot=TRUE, ...) { nvars <- nrow(R) ULU <- eigen(R) eigval <- ULU$values eigvect = ULU$vectors I <- diag(nvars) loadings = eigvect %*% diag(sqrt(eigval)) fm4 <- fm <- rep(0,max.fac) fm[1] <- sum(R^2 - I)/(nvars*(nvars-1)) fm4[1] <- sum(R^4 - I)/(nvars*(nvars-1)) for(m in 1:(max.fac-1)){ biga <- loadings[,1:m] partcov = R - (biga %*% t(biga)) d <- diag ( (1 / sqrt(diag(partcov)))) pr <- d %*% partcov %*% d fm[m+1] <- (sum(pr^2)-nvars)/(nvars*(nvars-1)) fm4[m+1] <- (sum(pr^4)-nvars)/(nvars*(nvars-1)) } minfm.loc <- which.min(fm) minfm4.loc <- which.min(fm4) if(Print){ cat("\nVelicer's Minimum Average Partial (MAP) Test\n\n") cat("The smallest average squared partial correlation is: ", round(min(fm),3),"\n") cat("The smallest average 4rth power partial correlation is: ", round(min(fm4),3),"\n\n") cat("The Number of Components According to the Original (1976) MAP Test is = ", minfm.loc,"\n") cat("The Number of Components According to the Revised (2000) MAP Test is = ",minfm4.loc) } PlotAvgSq <- NULL m1 <- c("Original MAP (Avg squared partial r)", paste("\nNumber of Components = ", minfm.loc, sep="")) if(Plot){ plot(1:max.fac,fm,type="b", main=m1, xlab="Dimensions", ylab="Avg squared partial r", xlim=c(1,max.fac), ...) PlotAvgSq <- recordPlot() m1 <- c("Revised MAP (Avg 4th partial r):\n", paste("\nNumber of Components = ", minfm4.loc, sep="")) plot(1:max.fac,fm4,type="b", main=m1, xlab="Dimensions", ylab="Avg 4th partial r", ...) PlotAvg4th <- recordPlot() } invisible(list(MAP = minfm.loc, MAP4 = minfm4.loc, fm = fm, fm4 = fm4, PlotAvgSq = PlotAvgSq, PlotAvg4th = PlotAvg4th)) }
.pkgglobalenv <- new.env(parent=emptyenv()) ndvar <- function(n) { if(!exists("mc.control", envir=.pkgglobalenv)) assign("mc.control",list(nsv=1001,nsu=101),envir=.pkgglobalenv ) x <- get("mc.control", envir=.pkgglobalenv) if(!is.list(x) || is.null(x$nsv) || is.null(x$nsu)) assign("mc.control",list(nsv=1001,nsu=101),envir=.pkgglobalenv ) if(!missing(n)){ if (n > 0) x$nsv <- ceiling(n) else stop("Invalid n") assign("mc.control",x, envir=.pkgglobalenv)} return(x$nsv)} ndunc <- function(n) { if(!exists("mc.control", envir=.pkgglobalenv)) assign("mc.control",list(nsv=1001,nsu=101),envir=.pkgglobalenv ) x <- get("mc.control", envir=.pkgglobalenv) if(!is.list(x) || is.null(x$nsv) || is.null(x$nsu)) assign("mc.control",list(nsv=1001,nsu=101),envir=.pkgglobalenv ) if(!missing(n)){ if (n > 0) x$nsu <- ceiling(n) else stop("Invalid n") assign("mc.control",x, envir=.pkgglobalenv)} return(x$nsu)}
library(RSSL) library(ggplot2) library(dplyr) set.seed(1) df_circles <- generateTwoCircles(400,noise=0.1) %>% add_missinglabels_mar(Class~.,0.99) df_circles %>% ggplot(aes(x=X1,y=X2,color=Class)) + geom_point() + coord_equal() class_grf <- GRFClassifier(Class~.,df_circles, adjacency="heat", adjacency_sigma = 0.1) df_circles %>% filter(is.na(Class)) %>% mutate(Responsibility=responsibilities(class_grf)[,1]) %>% ggplot(aes(x=X1,y=X2,color=Responsibility)) + geom_point() + coord_equal() df_para <- generateParallelPlanes() df_para$Class <- NA df_para$Class[1] <- "a" df_para$Class[101] <- "b" df_para$Class[201] <- "c" df_para$Class <- factor(df_para$Class) df_para %>% ggplot(aes(x=x,y=y,color=Class)) + geom_point() + coord_equal() class_grf <- GRFClassifier(Class~.,df_para) df_para %>% filter(is.na(Class)) %>% mutate(Assignment=factor(apply(responsibilities(class_grf),1,which.max))) %>% ggplot(aes(x=x,y=y,color=Assignment)) + geom_point()
layout_tbl_graph_treemap <- function(graph, algorithm = 'split', weight = NULL, circular = FALSE, sort.by = NULL, direction = 'out', height = 1, width = 1) { weight <- enquo(weight) weight <- eval_tidy(weight, .N()) sort.by <- enquo(sort.by) sort.by <- eval_tidy(sort.by) hierarchy <- tree_to_hierarchy(graph, direction, sort.by, weight) layout <- switch( algorithm, split = splitTreemap(hierarchy$parent, hierarchy$order, hierarchy$weight, width, height), stop('Unknown algorithm') )[-1, ] layout <- new_data_frame(list( x = layout[, 1] + layout[, 3] / 2, y = layout[, 2] + layout[, 4] / 2, width = layout[, 3], height = layout[, 4], circular = FALSE, leaf = degree(graph, mode = direction) == 0, depth = node_depth(graph, mode = direction) )) extra_data <- as_tibble(graph, active = 'nodes') warn_dropped_vars(layout, extra_data) layout <- cbind(layout, extra_data[, !names(extra_data) %in% names(layout), drop = FALSE]) layout }
dcsd.mcmc.list <- function(object, ...) { ncl <- nclones(object) if (is.null(ncl)) ncl <- 1 mcmcapply(object, sd, ...) * sqrt(ncl) }
test_that("throws when number of events exceed total observations", { te <- c(2, 2) tt <- c(1, 1) ce <- c(3, 3) ct <- c(0, 0) expect_error(rema(te, tt, ce, ct), " may not exceed the respective element in ") })
"uneqvar"
removeSource = function (fn) { recurse <- function(part) { if (is.name(part)) return(part) attr(part, "srcref") <- NULL attr(part, "wholeSrcref") <- NULL attr(part, "srcfile") <- NULL if (is.language(part) && is.recursive(part)) { for (i in seq_along(part)) part[i] <- list(recurse(part[[i]])) } part } if (is.function(fn)) { if (!is.primitive(fn)) { attr(fn, "srcref") <- NULL attr(body(fn), "wholeSrcref") <- NULL attr(body(fn), "srcfile") <- NULL body(fn) <- recurse(body(fn)) } fn } else if (is.language(fn)) { recurse(fn) } else { stop("argument is not a function or language object:", typeof(fn)) } }
agePyramidPlot <- function(males, females, ageLabels, mcol, fcol, laxlab, raxlab, gap, currentDate) { pyramid.plot(lx = males, rx = females, labels = ageLabels, main = stri_c("Total on ", year(currentDate), "-", month(currentDate, label = TRUE), "-", day(currentDate), ": ", sum(c(males, females))), top.labels = c( stri_c("Male = ", sum(males)), "Age", stri_c("Female = ", sum(females))), lxcol = mcol, rxcol = fcol, laxlab = laxlab, raxlab = raxlab, gap = gap, unit = "Number of Animals", show.values = TRUE, ndig = 0) }
context("drawManifolds") on.exit(unlink('Rplots.pdf')) example5.flowField <- flowField(phaseR::example5, xlim = c(-3, 3), ylim = c(-3, 3), points = 19, add = FALSE) ex5.pars <- list(y0 = c(0, 0), tend = 100) ex5.out <- do.call(drawManifolds, c(deriv=phaseR::example5, ex5.pars)) test_that("behavior equal to reference behavior", { expect_equal_to_reference(ex5.out[c("dx","dy")], "test-drawManifolds_ref-ex5.rds") }) test_that("alternative formulation equal to reference behavior", { ex5.alt <- function(t, state, parameters) { with(as.list(c(state, parameters)), { dx = 2*x + y dy = 2*x -y list(c(dx, dy)) }) } ex5.alt.out <- do.call(drawManifolds, c(deriv=ex5.alt, ex5.pars)) expect_equal(ex5.alt.out[c("dx","dy")], ex5.out[c("dx","dy")]) })
utility.endnode.classcounts.create <- function(name.node, name.attrib, u.max.inc, names.u.max.inc = list(), exceed.next = TRUE, utility = TRUE, required = FALSE, col = "black", shift.levels = 0) { check.ok <- T n <- length(name.attrib) if ( length(u.max.inc) != n ) { cat("*** Warning: Number of elements of u.max.inc not equal to number of elements of name.attrib:", length(u.max.inc),n,"\n") check.ok <- F } for ( i in 1:n ) { if ( !is.vector(u.max.inc[[i]]) ) { cat("*** Warning: Eelements of u.max.inc must be vectors","\n") check.ok <- F } } if ( length(names.u.max.inc) != 0 & length(names.u.max.inc) != n ) { cat("*** Warning: Number of elements of names.u.max.inc not equal to zero or to the number of elements of name.attrib:", length(names.u.max.inc),n,"\n") check.ok <- F } if ( ! check.ok ) { cat("*** Warning: node \"",name.node,"\" could not be constructed","\n", sep="") return(NA) } node <- list() node$name <- name.node node$description <- "utility/value class counts end node" node$type <- "endnode" node$attrib <- name.attrib node$u.max.inc <- u.max.inc for ( i in 1:n ) { l <- length(node$u.max.inc[[i]]) if ( l < n+2-i ) node$u.max.inc[[i]] <- c(node$u.max.inc[[i]],rep(0,n+2-i-l)) if ( l > n+2-i ) node$u.max.inc[[i]] <- node$u.max.inc[[i]][1:(n+2-i)] } if ( length(node$names.u.max.inc) == n ) { for ( i in 1:n ) { l <- length(node$names.u.max.inc[[i]]) if ( l < n+2-i ) node$names.u.max.inc[[i]] <- c(node$names.u.max.inc[[i]],rep(NA,n+2-i-l)) if ( l > n+2-i ) node$names.u.max.inc[[i]] <- node$names.u.max.inc[[i]][1:(n+2-i)] } } node$names.u.max.inc <- names.u.max.inc node$exceed.next <- exceed.next node$required <- required node$utility <- utility node$col <- col node$shift.levels <- shift.levels class(node) <- "utility.endnode.classcounts" return(node) } updatepar.utility.endnode.classcounts <- function(x,par=NA,...) { node <- x n <- length(node$attrib) if ( length(names(par)) == 0 ) return(node) if ( length(node$names.u.max.inc) != n ) return(node) for ( i in 1:length(node$attrib) ) { for ( j in 1:(n+2-i) ) { if ( ! is.na(node$names.u.max.inc[[i]][j]) ) { ind <- which(node$names.u.max.inc[[i]][j] == names(par) ) if ( length(ind) > 1 ) { warning("Node \"",node$name,"\": multiple occurrences of parameter", names(par)[ind[1]]) ind <- ind[1] } if ( length(ind) == 1 ) { node$u.max.inc[[i]][j] <- par[ind] } } } } return(n) } evaluate.utility.endnode.classcounts <- function(x, attrib, par = NA, ...) { node <- x n <- length(node$attrib) node <- updatepar(node,par) if ( is.data.frame(attrib) | is.matrix(attrib) ) { ind <- match(node$attrib,colnames(attrib)) if ( sum(ifelse(is.na(ind),1,0)) > 0 ) { warning("Node \"",node$name,"\": attribute(s) \"", paste(node$attrib[is.na(ind)],collapse=","),"\" not found",sep="") return(rep(NA,nrow(attrib))) } a <- attrib[,ind] } else { if ( ! is.vector(attrib) ) { warning("Node \"",node$name,"\": unknown format of attribute(s) \"",node$attrib,"\"",sep="") return(NA) } if ( length(names(attrib)) == 0 ) { if ( length(attrib) == 2 ) a <- as.matrix(attrib,nrow=1) } else { ind <- match(node$attrib,names(attrib)) if ( sum(ifelse(is.na(ind),1,0)) > 0 ) { warning("Node \"",node$name,"\": attribute(s) \"", paste(node$attrib[is.na(ind)],collapse=","),"\" not found",sep="") return(rep(NA,nrow(attrib))) } a <- as.matrix(attrib[ind],nrow=1) } } u <- rep(NA,nrow(a)) for ( k in 1:nrow(a) ) { att <- as.numeric(a[k,]) i <- match(TRUE,att>0) if ( is.na(i) ) { if ( sum(!is.na(att)) > 0 ) u[k] <- 0 } else { u[k] <- node$u.max.inc[[i]][1] u[k] <- u[k] + (att[i]-1)*node$u.max.inc[[i]][2] if ( i < n ) { for ( j in 1:(n-i) ) u[k] <- u[k] + att[i+j]*node$u.max.inc[[i]][2+j] } u[k] <- min(1,u[k]) if ( i > 1 & !node$exceed.next ) { u[k] <- min(node$u.max.inc[[i-1]][1],u[k]) } } } return(u) } print.utility.endnode.classcounts <- function(x,...) { cat(paste(rep("-",50),collapse=""),"\n") summary(x,...) cat(paste(rep("-",50),collapse=""),"\n") } summary.utility.endnode.classcounts <- function(object,...) { node <- object cat(node$name,"\n") cat(paste(rep("-",nchar(node$name)),collapse=""),"\n") cat(node$description,"\n") cat("attribute(s): ",paste(node$attrib,collapse=","),"\n") funtype <- "utility"; if ( !node$utility ) funtype <- "value" cat("function type: ",funtype,"\n") cat("required: ",node$required,"\n") cat("basic level, multiplicity increments","\n") for ( i in 1:length(node$attrib) ) { cat(paste(node$u.max.inc[[i]],collapse=", "),"\n") } } plot.utility.endnode.classcounts <- function(x, par = NA, col = utility.calc.colors(), gridlines = c(0.2,0.4,0.6,0.8), main = "", cex.main = 1, ...) { node <- x space <- 0.2 n <- updatepar(node,par) title <- main; if ( nchar(title) == 0 ) title <- n$name funtype <- "utility"; if ( !n$utility ) funtype <- "value" n.attrib <- length(n$attrib) u.max.inc <- matrix(0,nrow=n.attrib+1,ncol=n.attrib) colnames(u.max.inc) <- n$attrib for ( i in 1:n.attrib ) u.max.inc[1:(n.attrib+2-i),i] <- node$u.max.inc[[i]] print(u.max.inc) barplot(u.max.inc,main=title,ylab=paste(funtype,"(base + inc)"), cex.main=cex.main,xlim=c(0,n.attrib*(1+space)),ylim=c(0,1), space=space,beside=FALSE,xaxs="i",yaxs="i") max.val <- 0.995*rep(1,n.attrib) if ( !n$exceed.next ) max.val <- c(0.995,u.max.inc[1,1:(n.attrib-1)]) for ( i in 1:n.attrib ) { lines(space+(i-1)*(1+space)+0.5+c(-0.5,0.5),max.val[i]*c(1,1),col="red",lwd=2) } }
patternbar<-function(data,x, y, group=NULL, xlab='', ylab='', label.size=3.5,vjust=-1,hjust=-1, pattern.type, pattern.line.size=rep(5, ifelse(is.null(group), length(x), length(unique(group)))), pattern.color=rep('black', ifelse(is.null(group), length(x), length(unique(group)))), background.color=rep('white', ifelse(is.null(group), length(x), length(unique(group)))), frame.color=rep('black', ifelse(is.null(group), length(x), length(unique(group)))),frame.size=1, pixel=20, density=rep(7, ifelse(is.null(group), length(x), length(unique(group)))), legend.type='h', legend.h=6, legend.x.pos=1.1, legend.y.pos=0.49, legend.w=0.2, legend.pixel=20, bar.width=0.9){ location<-gsub('\\','/',tempdir(), fixed=T) if(is.null(group)){ bplot <- ggplot(data, aes(x, y)) + geom_bar(stat="identity", width = bar.width)+geom_text(aes(label=y)) gdata<-ggplot_build(bplot)$data[[1]] gdata<-gdata[order(gdata$group),] boxmatrix<-list() picdata<-list() picdf<-list() xmax<-max(gdata[, c('xmax')]) xmin<-min(gdata[, c('xmin')]) ymax<-max(gdata[, c('ymax')]) ymin<-min(gdata[, c('ymin')]) for (i in 1:dim(gdata)[1]){ boxmatrix[[i]]<-matrix(c(gdata[i,"xmin"], 0, gdata[i,"xmax"], 0, gdata[i,"xmax"], gdata[i,"ymax"], gdata[i,"xmin"], gdata[i,"ymax"], gdata[i,"xmin"], 0), nrow=5, ncol=2, byrow=T) suppressWarnings(pattern(type=pattern.type[i], density=density[i], color=pattern.color[i], pattern.line.size=pattern.line.size[i], background.color=background.color[i], pixel=pixel, res=pixel)) if (sub( "_.*", "", pattern.type[i])=='Unicode'){ picdata[[i]]<-imagetodf2(readPNG(paste(location,'/','Unicode',".png", sep='')), boxmatrix[[i]],left =xmin, right = xmax ,bottom = ymin,top =ymax) }else{ picdata[[i]]<-imagetodf2(readPNG(paste(location,'/',pattern.type[i],".png", sep='')), boxmatrix[[i]],left =xmin, right = xmax ,bottom = ymin,top =ymax) } picdata[[i]] <- filter(picdata[[i]], pos==1) } ldata<-ggplot_build(bplot)$data[[2]] g<- ggplot()+ mapply(function(i) geom_tile(data = picdata[[i]], aes(x = X, y = Y, fill = rgb(r,g, b,a))),1:dim(gdata)[1])+scale_fill_identity()+geom_rect(aes(xmin=gdata[,"xmin"],xmax=gdata[,"xmax"],ymin=0,ymax=gdata[,"ymax"]), color=frame.color,size=frame.size, fill=NA) g+ theme_bw()+xlab(xlab)+ylab(ylab)+ scale_x_continuous(breaks=seq(1:length(levels(x))), labels=levels(x))+geom_text(data=ldata, aes(x, y, label=label), vjust=vjust,hjust=hjust, size=label.size) }else{ bplot <- ggplot(data, aes(x, y, fill=group)) + geom_bar(stat="identity", position=position_dodge(), width = bar.width) +geom_text(aes(label=y),position=position_dodge(width=0.9)) gdata<-ggplot_build(bplot)$data[[1]] gdata<-gdata[order(gdata$group),] boxmatrix<-list() picdata<-list() picdf<-list() xmax<-max(gdata[, c('xmax')]) xmin<-min(gdata[, c('xmin')]) ymax<-max(gdata[, c('ymax')]) ymin<-min(gdata[, c('ymin')]) pattern.type2<-rep(pattern.type, time=length(unique(x))) background.color2<-rep(background.color,time=length(unique(x))) pattern.color2<-rep(pattern.color,time=length(unique(x))) density2<-rep(density,time=length(unique(x))) pattern.line.size2<-rep(pattern.line.size,time=length(unique(x))) for (i in 1:dim(gdata)[1]){ boxmatrix[[i]]<-matrix(c(gdata[i,"xmin"], 0, gdata[i,"xmax"], 0, gdata[i,"xmax"], gdata[i,"ymax"], gdata[i,"xmin"], gdata[i,"ymax"], gdata[i,"xmin"], 0), nrow=5, ncol=2, byrow=T) suppressWarnings(pattern(type=pattern.type2[i], density=density2[i], color=pattern.color2[i], pattern.line.size=pattern.line.size2[i], background.color=background.color2[i], pixel=pixel, res=pixel)) if (sub( "_.*", "", pattern.type2[i])=='Unicode'){ picdata[[i]]<-imagetodf2(readPNG(paste(location,'/','Unicode',".png", sep='')), boxmatrix[[i]],left =xmin, right = xmax ,bottom = ymin,top =ymax) }else{ picdata[[i]]<-imagetodf2(readPNG(paste(location,'/',pattern.type2[i],".png", sep='')), boxmatrix[[i]],left =xmin, right = xmax ,bottom = ymin,top =ymax) } picdata[[i]] <- filter(picdata[[i]], pos==1) } legendbox<-list() legenddata<-list() if(legend.type=='v'){ legend.y<-seq(from =ymax+(0.1+0.05*legend.h)*ymax, to = ymax+0.1*ymax, length.out=length(pattern.type)+1) legend.x<-seq(from = xmin, to = xmin+ 0.5*(gdata[1,"xmax"]-xmin), length.out=2) legend.frame.xmin<-vector(mode="numeric", length=length(pattern.type)) legend.frame.xmax<-vector(mode="numeric", length=length(pattern.type)) legend.frame.ymin<-vector(mode="numeric", length=length(pattern.type)) legend.frame.ymax<-vector(mode="numeric", length=length(pattern.type)) for (i in 1:length(pattern.type)){ legendbox[[i]]<-matrix(c(legend.x[1], legend.y[i], legend.x[2], legend.y[i], legend.x[2],legend.y[i+1], legend.x[1],legend.y[i+1], legend.x[1],legend.y[i]), nrow=5, ncol=2, byrow=T) suppressWarnings(pattern(type=pattern.type[i], density=0.6*density[i], color=pattern.color[i], pattern.line.size=pattern.line.size[i], background.color=background.color[i], pixel=legend.pixel, res=legend.pixel)) if (sub( "_.*", "", pattern.type[i])=='Unicode'){ legenddata[[i]]<-imagetodf2(readPNG(paste(location,'/','Unicode',".png", sep='')), legendbox[[i]],left =legendbox[[i]][1, 1], right = legendbox[[i]][2, 1] ,bottom = legendbox[[i]][1, 2],top =legendbox[[i]][3, 2]) }else{ legenddata[[i]]<-imagetodf2(readPNG(paste(location,'/',pattern.type[i],".png", sep='')), legendbox[[i]],left =legendbox[[i]][1, 1], right = legendbox[[i]][2, 1] ,bottom = legendbox[[i]][1, 2],top =legendbox[[i]][3, 2]) } legend.frame.xmin[i]<-legend.x[1] legend.frame.xmax[i]<-legend.x[2] legend.frame.ymax[i]<-legend.y[i] legend.frame.ymin[i]<-legend.y[i+1] } legend.label.y<-legend.y.pos*(legend.frame.ymin+legend.frame.ymax) legend.label.x<-legend.x.pos*legend.w } if(legend.type=='h'){ legend.y<-c(ymax+0.1*ymax, ymax+(0.1+0.01*legend.h)*ymax) legend.x.s<-seq(from =xmin, to =0.67* xmax, length.out=length(pattern.type)) legend.frame.xmin<-vector(mode="numeric", length=length(pattern.type)) legend.frame.xmax<-vector(mode="numeric", length=length(pattern.type)) legend.frame.ymin<-vector(mode="numeric", length=length(pattern.type)) legend.frame.ymax<-vector(mode="numeric", length=length(pattern.type)) for (i in 1:length(pattern.type)){ legendbox[[i]]<-matrix(c(legend.x.s[i], legend.y[1], legend.x.s[i]+legend.w, legend.y[1], legend.x.s[i]+legend.w,legend.y[2], legend.x.s[i],legend.y[2], legend.x.s[i],legend.y[1]), nrow=5, ncol=2, byrow=T) suppressWarnings(pattern(type=pattern.type[i], density=0.6*density[i], color=pattern.color[i], pattern.line.size=pattern.line.size[i], background.color=background.color[i], pixel=legend.pixel, res=legend.pixel)) if (sub( "_.*", "", pattern.type[i])=='Unicode'){ legenddata[[i]]<-imagetodf2(readPNG(paste(location,'/','Unicode',".png", sep='')), legendbox[[i]],left =legendbox[[i]][1, 1], right = legendbox[[i]][2, 1] ,bottom = legendbox[[i]][1, 2],top =legendbox[[i]][3, 2]) }else{ legenddata[[i]]<-imagetodf2(readPNG(paste(location,'/',pattern.type[i],".png", sep='')), legendbox[[i]],left =legendbox[[i]][1, 1], right = legendbox[[i]][2, 1] ,bottom = legendbox[[i]][1, 2],top =legendbox[[i]][3, 2]) } legend.frame.xmin[i]<-legendbox[[i]][1,1] legend.frame.xmax[i]<-legendbox[[i]][2,1] legend.frame.ymax[i]<-legendbox[[i]][3,2] legend.frame.ymin[i]<-legendbox[[i]][1,2] } legend.label.y<-(legend.frame.ymin+legend.frame.ymax)*legend.y.pos legend.label.x<-legend.x.s+legend.x.pos*legend.w } ldata<-ggplot_build(bplot)$data[[2]] X<-Y<-r<-g<-b<-a<-pos<-label<-NULL g<- ggplot()+ mapply(function(i) geom_tile(data = picdata[[i]], aes(x = X, y = Y, fill = rgb(r,g, b,a))),1:dim(gdata)[1])+scale_fill_identity()+geom_rect(aes(xmin=gdata[,"xmin"],xmax=gdata[,"xmax"],ymin=0,ymax=gdata[,"ymax"]), color=frame.color,size=frame.size, fill=NA) g<-g+ theme_bw()+xlab(xlab)+ylab(ylab)+ scale_x_continuous(breaks=seq(1:length(levels(x))), labels=levels(x))+geom_text(data=ldata, aes(x, y, label=label), vjust=vjust,hjust=hjust, size=label.size) g+ mapply(function(i) geom_tile(data = legenddata[[i]], aes(x = X, y = Y, fill = rgb(r,g, b,a))),1:length(pattern.type))+geom_rect(aes(xmin=legend.frame.xmin,xmax=legend.frame.xmax,ymin=legend.frame.ymin,ymax=legend.frame.ymax), color=frame.color,size=frame.size, fill=NA)+geom_text(aes(x=legend.label.x, y=legend.label.y, label=levels(group)), hjust=0, vjust=0, size=label.size) } }