code
stringlengths
1
13.8M
library(BART) B <- getOption('mc.cores', 1) figures = getOption('figures', default='NONE') data(arq) str(arq) arth <- as.matrix(arq) N <- length(arth[ , 'riagendr']) table(arth[ , 'riagendr']) summary(arth[ , 'bmxbmi']) post1 <- mc.pbart(x.train=arth[ , 5:10], y.train=arth[ , 4], mc.cores=B, seed=99) post2 <- mc.pbart(x.train=arth[ , 5:10], y.train=arth[ , 3], mc.cores=B, seed=99) bmxbmi <- seq(15, 45, by=5) H <- length(bmxbmi) for(i in 1:2) for(j in 1:H) { x. <- arth[ , 5:10] x.[ , 'riagendr'] <- i x.[ , 'bmxbmi'] <- bmxbmi[j] if(i==1 && j==1) x.test <- x. else x.test <- rbind(x.test, x.) } table(x.test[ , 'riagendr']) table(x.test[ , 'bmxbmi']) pred1 <- predict(post1, newdata=x.test, mc.cores=B) pred2 <- predict(post2, newdata=x.test, mc.cores=B) M <- nrow(pred1$prob.test) pd1 <- matrix(nrow=M, ncol=H) pd2 <- matrix(nrow=M, ncol=H) k <- (H+2)*N for(j in 1:H) { h <- (H+j-1)*N pd1[ , j] <- apply(pred1$prob.test[ , h+1:N]- pred1$prob.test[ , k+1:N], 1, mean) pd2[ , j] <- apply(pred2$prob.test[ , h+1:N]- pred2$prob.test[ , k+1:N], 1, mean) } pd1.mean <- apply(pd1, 2, mean) pd2.mean <- apply(pd2, 2, mean) pd1.025 <- apply(pd1, 2, quantile, probs=0.025) pd2.025 <- apply(pd2, 2, quantile, probs=0.025) pd1.975 <- apply(pd1, 2, quantile, probs=0.975) pd2.975 <- apply(pd2, 2, quantile, probs=0.975) par(mfrow=c(1, 2)) plot(bmxbmi, pd1.mean, type='l', col='blue', ylim=c(-0.2, 0.2), xlab='BMI', ylab=expression(p(x)-p(25)), sub='Chronic pain: low-back(blue)') lines(bmxbmi, pd1.025, type='l', col='blue', lty=2) lines(bmxbmi, pd1.975, type='l', col='blue', lty=2) lines(bmxbmi, rep(0, H)) plot(bmxbmi, pd2.mean, type='l', col='red', ylim=c(-0.2, 0.2), xlab='BMI', ylab=expression(p(x)-p(25)), sub='Chronic pain: neck(red)') lines(bmxbmi, pd2.025, type='l', col='red', lty=2) lines(bmxbmi, pd2.975, type='l', col='red', lty=2) lines(bmxbmi, rep(0, H)) par(mfrow=c(1, 1)) if(figures!='NONE') dev.copy2pdf(file=paste(figures, 'chronic-pain2.pdf', sep='/'))
.min.criterion.VGAM <- c("deviance" = TRUE, "loglikelihood" = FALSE, "AIC" = TRUE, "Likelihood" = FALSE, "ResSS" = TRUE, "coefficients" = TRUE) vlm.control <- function(save.weights = TRUE, tol = 1e-7, method = "qr", checkwz = TRUE, wzepsilon = .Machine$double.eps^0.75, ...) { if (tol <= 0) { warning("argument 'tol' not positive; using 1e-7 instead") tol <- 1e-7 } if (!is.logical(checkwz) || length(checkwz) != 1) stop("bad input for argument 'checkwz'") if (!is.Numeric(wzepsilon, length.arg = 1, positive = TRUE)) stop("bad input for argument 'wzepsilon'") list(save.weights = save.weights, tol = tol, method = method, checkwz = checkwz, wzepsilon = wzepsilon) } vglm.control <- function(checkwz = TRUE, Check.rank = TRUE, Check.cm.rank = TRUE, criterion = names(.min.criterion.VGAM), epsilon = 1e-7, half.stepsizing = TRUE, maxit = 30, noWarning = FALSE, stepsize = 1, save.weights = FALSE, trace = FALSE, wzepsilon = .Machine$double.eps^0.75, xij = NULL, ...) { if (mode(criterion) != "character" && mode(criterion) != "name") criterion <- as.character(substitute(criterion)) criterion <- pmatch(criterion[1], names(.min.criterion.VGAM), nomatch = 1) criterion <- names(.min.criterion.VGAM)[criterion] if (!is.logical(checkwz) || length(checkwz) != 1) stop("bad input for argument 'checkwz'") if (!is.Numeric(wzepsilon, length.arg = 1, positive = TRUE)) stop("bad input for argument 'wzepsilon'") convergence <- expression({ switch(criterion, coefficients = if (iter == 1) iter < maxit else (iter < maxit && max(abs(new.crit - old.crit) / ( abs(old.crit) + epsilon)) > epsilon), iter < maxit && sqrt(eff.n) * abs(old.crit - new.crit) / ( abs(old.crit) + epsilon) > epsilon) }) if (!is.Numeric(epsilon, length.arg = 1, positive = TRUE)) { warning("bad input for argument 'epsilon'; using 0.00001 instead") epsilon <- 0.00001 } if (!is.Numeric(maxit, length.arg = 1, positive = TRUE, integer.valued = TRUE)) { warning("bad input for argument 'maxit'; using 30 instead") maxit <- 30 } if (!is.Numeric(stepsize, length.arg = 1, positive = TRUE)) { warning("bad input for argument 'stepsize'; using 1 instead") stepsize <- 1 } list(checkwz = checkwz, Check.rank = Check.rank, Check.cm.rank = Check.cm.rank, convergence = convergence, criterion = criterion, epsilon = epsilon, half.stepsizing = as.logical(half.stepsizing)[1], maxit = maxit, noWarning = as.logical(noWarning)[1], min.criterion = .min.criterion.VGAM, save.weights = as.logical(save.weights)[1], stepsize = stepsize, trace = as.logical(trace)[1], wzepsilon = wzepsilon, xij = if (is(xij, "formula")) list(xij) else xij) } vcontrol.expression <- expression({ control <- control mylist <- family@vfamily for (jay in length(mylist):1) { for (ii in 1:2) { temp <- paste(if (ii == 1) "" else paste(function.name, ".", sep = ""), mylist[jay], ".control", sep = "") if (exists(temp, envir = VGAMenv)) { temp <- get(temp) temp <- temp(...) for (kk in names(temp)) control[[kk]] <- temp[[kk]] } } } orig.criterion <- control$criterion if (control$criterion != "coefficients") { try.crit <- c(names(.min.criterion.VGAM), "coefficients") for (i in try.crit) { if (any(slotNames(family) == i) && length(body(slot(family, i)))) { control$criterion <- i break } else { control$criterion <- "coefficients" } } } control$min.criterion <- control$min.criterion[control$criterion] for (ii in 1:2) { temp <- paste(if (ii == 1) "" else paste(function.name, ".", sep = ""), family@vfamily[1], ".", control$criterion, ".control", sep = "") if (exists(temp, inherit = TRUE)) { temp <- get(temp) temp <- temp(...) for (k in names(temp)) control[[k]] <- temp[[k]] } } })
bcontSurvGuniv_ExcessHazard <- function(params, respvec, VC, ps, AT = FALSE){ p1 <- p2 <- pdf1 <- pdf2 <- c.copula.be2 <- c.copula.be1 <- c.copula2.be1be2 <- NA n <- VC$n c1 <- VC$hrate monP <- monP1 <- monP2 <- k <- 0; V <- list() etad <- etas1 <- etas2 <- l.ln <- NULL params1 <- params[1:VC$X1.d2] params1[VC$mono.sm.pos] <- exp( params1[VC$mono.sm.pos] ) eta1 <- VC$X1%*%params1 Xd1P <- VC$Xd1%*%params1 indN <- as.numeric(Xd1P < 0) Xd1P <- ifelse(Xd1P < VC$min.dn, VC$min.dn, Xd1P ) if( any(indN == TRUE) && !is.null(VC$indexT) ){ monP22 <- matrix(0, length(params),length(params)) for(i in 1:length(VC$pos.pb)){ V[[i]] <- as.numeric(diff(params1[ VC$pos.pb[[i]] ]) < 0) monP22[ VC$pos.pb[[i]], VC$pos.pb[[i]] ] <- t(VC$D[[i]]*V[[i]])%*%VC$D[[i]] } k <- VC$my.env$k monP2 <- k*monP22 monP <- k/2*crossprod(params, monP22)%*%params monP1 <- k*(monP22%*%params) VC$my.env$k <- k*2 } pd1 <- probmS(eta1, VC$margins[1], min.dn = VC$min.dn, min.pr = VC$min.pr, max.pr = VC$max.pr) p1 <- pd1$pr dS1eta1 <- pd1$dS d2S1eta1 <- pd1$d2S d3S1eta1 <- pd1$d3S l.par <- VC$weights*( VC$cens*log(c1*p1 - dS1eta1*Xd1P) + (1 - VC$cens)*log(p1) ) res <- -sum(l.par) der.par1 <- der2.par1 <- params1 der.par1[-c( VC$mono.sm.pos )] <- 1 der2.par1[-c( VC$mono.sm.pos )] <- 0 der2eta1dery1b1 <- t(t(VC$Xd1)*der.par1) dereta1derb1 <- t(t(VC$X1)*der.par1) dl.dbe1 <- -VC$weights*( VC$cens*( c((c1*p1 - dS1eta1*Xd1P)^-1)*( c(c1*dS1eta1)*dereta1derb1 - c(d2S1eta1*Xd1P)*dereta1derb1 - c(dS1eta1)*der2eta1dery1b1 ) ) + (1 - VC$cens)*c(p1^-1*dS1eta1)*dereta1derb1 ) G <- colSums(dl.dbe1) H <- -( crossprod(c(VC$weights*VC$cens*( ( c1*p1 - dS1eta1*Xd1P )^-1*(c1*d2S1eta1) ))*dereta1derb1, dereta1derb1 ) + crossprod(c(VC$weights*VC$cens*(-( c1*p1 - dS1eta1*Xd1P )^-1*(d3S1eta1*Xd1P) ))*dereta1derb1, dereta1derb1 ) + crossprod(c(VC$weights*VC$cens*(-( c1*p1 - dS1eta1*Xd1P )^-1*d2S1eta1 ))*dereta1derb1, der2eta1dery1b1 ) + crossprod(c(VC$weights*VC$cens*(-( c1*p1 - dS1eta1*Xd1P )^-1*d2S1eta1 ))*der2eta1dery1b1, dereta1derb1 ) + diag( colSums( t( t(c(VC$weights*VC$cens*( c1*p1 - dS1eta1*Xd1P )^-1*(c1*dS1eta1) )*VC$X1)*der2.par1 ) ) ) + diag( colSums( t( t(c(VC$weights*VC$cens*-( c1*p1 - dS1eta1*Xd1P )^-1*(d2S1eta1*Xd1P) )*VC$X1)*der2.par1 ) ) ) + diag( colSums( t( t(c(VC$weights*VC$cens*-( c1*p1 - dS1eta1*Xd1P )^-1*dS1eta1 )*VC$Xd1)*der2.par1 ) ) ) + crossprod(c(VC$weights*VC$cens*(-( c1*p1 - dS1eta1*Xd1P )^-2*(c1*dS1eta1)^2 ))*dereta1derb1, dereta1derb1) + crossprod(c(VC$weights*VC$cens*(-( c1*p1 - dS1eta1*Xd1P )^-2*(d2S1eta1*Xd1P)^2 ))*dereta1derb1, dereta1derb1) + crossprod(c(VC$weights*VC$cens*(-( c1*p1 - dS1eta1*Xd1P )^-2*dS1eta1^2 ))*der2eta1dery1b1, der2eta1dery1b1) + crossprod(c(VC$weights*VC$cens*(2*( c1*p1 - dS1eta1*Xd1P )^-2*( (c1*dS1eta1)*(d2S1eta1*Xd1P) ) ))*dereta1derb1, dereta1derb1) + crossprod(c(VC$weights*VC$cens*( ( c1*p1 - dS1eta1*Xd1P )^-2*(c1*dS1eta1^2) ))*dereta1derb1, der2eta1dery1b1) + crossprod(c(VC$weights*VC$cens*( ( c1*p1 - dS1eta1*Xd1P )^-2*(c1*dS1eta1^2) ))*der2eta1dery1b1, dereta1derb1 ) + crossprod(c(VC$weights*VC$cens*(-( c1*p1 - dS1eta1*Xd1P )^-2*( (d2S1eta1*Xd1P)*dS1eta1 ) ))*dereta1derb1, der2eta1dery1b1) + crossprod(c(VC$weights*VC$cens*(-( c1*p1 - dS1eta1*Xd1P )^-2*( (d2S1eta1*Xd1P)*dS1eta1 ) ))*der2eta1dery1b1, dereta1derb1) + crossprod(c(VC$weights*(1 - VC$cens)*(-p1^-2*dS1eta1^2+p1^-1*d2S1eta1))*dereta1derb1, dereta1derb1) + diag( colSums( t( t(c(VC$weights*(1 - VC$cens)*p1^-1*dS1eta1)*VC$X1)*der2.par1 ) ) ) ) if(VC$extra.regI == "pC") H <- regH(H, type = 1) S.h <- ps$S.h + monP2 S.h1 <- 0.5*crossprod(params, ps$S.h)%*%params + monP S.h2 <- S.h%*%params + monP1 S.res <- res res <- S.res + S.h1 G <- G + S.h2 H <- H + S.h if(VC$extra.regI == "sED") H <- regH(H, type = 2) list(value=res, gradient=G, hessian=H, S.h=S.h, S.h1=S.h1, S.h2=S.h2, indN = indN, V = V, l=S.res, l.ln = l.ln, l.par=l.par, ps = ps, k = VC$my.env$k, monP2 = monP2, params1 = params1, eta1=eta1, p1 = p1, p2 = p2, pdf1 = -dS1eta1, pdf2 = pdf2, c.copula.be2 = c.copula.be2, c.copula.be1 = c.copula.be1, c.copula2.be1be2 = c.copula2.be1be2, dl.dbe1 = NULL, dl.dbe2 = NULL, dl.dteta.st = NULL) }
qtlRaster = function(pdR, threshold, thresholdType = "area", genplot = TRUE, outDir = NULL){ if(class(pdR)[1] != "RasterLayer" & class(pdR)[1] != "RasterStack" & class(pdR)[1] != "RasterBrick"){ stop("input probability density map (pdR) should be one of the following classes: RasterLayer, RasterStack or RasterBrick") } if(class(threshold)[1] != "numeric"){ stop("threshold must be a number between 0 and 1 ") } if(length(threshold)[1] != 1){ stop("threshold must be a number between 0 and 1 ") } if(threshold < 0 | threshold > 1){ stop("threshold must be a number between 0 and 1") } if(thresholdType != "area" & thresholdType != "prob"){ stop("thresholdType must be 'area' or 'prob'. See help page for further information") } if(class(genplot)[1] != "logical"){ stop("genplot must be logical (T/F)") } if(!is.null(outDir)){ if(class(outDir)[1] != "character"){ stop("outDir should be a character string") } if(!dir.exists(outDir)){ message("outDir does not exist, creating") dir.create(outDir) } } result = pdR n = nlayers(result) if(thresholdType == "prob"){ for(i in seq_len(n)){ if(threshold == 0){ cut = 1 } else if(threshold == 1){ cut = 0 } else{ pdR.values = na.omit(getValues(pdR[[i]])) pdR.values = sort(pdR.values) k = length(pdR.values) left = 1 right = k while((right-left) > 2){ start = round((left+right)/2) total = sum(pdR.values[start:k]) if(total > threshold){ left = start } if(total < threshold){ right = start } } cut = pdR.values[start] } if(n == 1){ result = pdR[[i]] > cut }else{ result[[i]] = pdR[[i]] > cut } } title1 = "probability" } if(thresholdType == "area"){ for(i in seq_len(n)){ if(threshold == 0){ cut = 1 } else if(threshold == 1){ cut = 0 } else{ pdR.values = na.omit(getValues(pdR[[i]])) k = length(pdR.values) cut = sort(pdR.values)[round((1-threshold)*k)] } if(n == 1){ result = pdR[[i]] > cut }else{ result[[i]] = pdR[[i]]>cut } } title1 = "area" } names(result) = names(pdR) tls = character(n) if(n > 1){ for(i in seq_len(n)){ tls[i] = paste0("Top ", threshold*100, "% quantile by ", title1, " for ", names(result)[i]) } } else{ tls = paste0("Top ", threshold*100, "% quantile by ", title1) } if(genplot){ for(i in seq_len(n)){ plot(result[[i]], legend=FALSE) title(tls[i]) } } if(!is.null(outDir)){ pdf(paste0(outDir, "/qtlRaster_result.pdf")) for(i in seq_len(n)){ plot(result[[i]], legend=FALSE) title(tls[i]) } dev.off() } return(result) }
`stressplot`<- function(object, ...) { UseMethod("stressplot") } `stressplot.monoMDS` <- function(object, pch, p.col = "blue", l.col = "red", lwd, ...) { if (missing(lwd)) if (object$ngrp > 2) lwd <- 1 else lwd <- 2 x <- object$diss y <- object$dist yf <- object$dhat if (object$iregn == 3) pts <- seq_along(x) < object$istart[2] else if (object$ngrp > 2) pts <- object$iidx > object$jidx else pts <- !logical(length(x)) if (missing(pch)) if (sum(pts) > 5000) pch <- "." else pch <- 1 plot(x[pts], y[pts], pch = pch, col = p.col, xlab = "Observed Dissimilarity", ylab = "Ordination Distance", ...) ralscal <- 0 if (object$iregn > 1) { if (object$iregn == 3) { k <- seq(object$istart[2], object$ndis) yl <- range(yf[k]) xl <- range(x[k]) ralscal <- cor(y[k], yf[k])^2 } else { yl <- range(yf) xl <- range(x) ralscal <- cor(y, yf)^2 } lines(xl, yl, col = l.col, lwd = lwd, ...) } if (object$iregn != 2) { ist <- c(object$istart, object$ndis + 1) if (object$iregn == 3) object$ngrp <- 1 for(j in 1:object$ngrp) { k <- seq(ist[j], ist[j+1]-1) ralscal <- ralscal + cor(y[k], yf[k])^2 lines(x[k], yf[k], type = "S", col = l.col, lwd = lwd, ...) } } rstress <- 1 - object$stress^2 ralscal <- if(object$iregn == 3) ralscal/2 else ralscal/object$ngrp Rst <- format(rstress, digits = 3) Ral <- format(ralscal, digits = 3) lab1 <- bquote("Non-metric fit, " * R^2 == .(Rst)) lab2 <- bquote("Linear fit, " * R^2 == .(Ral)) text(min(x), 0.95*max(y), lab1, pos=4) text(min(x), 0.95*max(y) - strheight(lab1), lab2, pos=4) o <- order(object$jidx, object$iidx) invisible(list("x" = x[o], "y" = y[o], "yf" = yf[o])) } `stressplot.default` <- function(object, dis, pch, p.col = "blue", l.col = "red", lwd = 2, ...) { if (!(inherits(object, "metaMDS") || all(c("points", "stress") %in% names(object)))) stop("can be used only with objects that are compatible with MASS::isoMDS results") if (missing(dis)) if (inherits(object, "metaMDS")) dis <- metaMDSredist(object) else stop("needs dissimilarities 'dis'") if (attr(dis, "Size") != nrow(object$points)) stop("dimensions do not match in ordination and dissimilarities") shep <- Shepard(dis, object$points) stress <- sum((shep$y - shep$yf)^2)/sum(shep$y^2) rstress <- 1 - stress ralscal <- cor(shep$y, shep$yf)^2 stress <- sqrt(stress)*100 if ( abs(stress - object$stress) > 0.001) stop("dissimilarities and ordination do not match") if (missing(pch)) if (length(dis) > 5000) pch <- "." else pch <- 1 plot(shep, pch = pch, col = p.col, xlab = "Observed Dissimilarity", ylab = "Ordination Distance", ...) lines(shep$x, shep$yf, type = "S", col = l.col, lwd = lwd, ...) Rst <- format(rstress, digits = 3) Ral <- format(ralscal, digits = 3) lab1 <- bquote("Non-metric fit, " * R^2 == .(Rst)) lab2 <- bquote("Linear fit, " * R^2 == .(Ral)) text(min(shep$x), 0.95*max(shep$y), lab1, pos=4) text(min(shep$x), 0.95*max(shep$y) - strheight(lab1), lab2, pos=4) invisible(shep) }
library(shiny.fluent) if (interactive()) { shinyApp( ui = Label("Required label", required = TRUE), server = function(input, output) {} ) }
setMethodS3("isEof", "connection", function(con, ...) { offset <- seek(con, rw="read") bfr <- readChar(con, nchars=1) seek(con, where=offset, rw="read") (nchar(bfr) == 0) })
mvmeta.mm <- function(Xlist, ylist, Slist, nalist, k, m, p, nall, control, ...) { Psi <- diag(0,k) gls <- glsfit(Xlist,ylist,Slist,nalist,Psi,onlycoef=FALSE) Wlist <- mapply(function(invU,na) { W <- matrix(0,k,k) W[!na,!na] <- tcrossprod(invU) return(W)},gls$invUlist,nalist,SIMPLIFY=FALSE) I <- diag(m) W <- do.call("cbind",lapply(seq(Wlist), function(i) I[,i] %x% Wlist[[i]])) na <- unlist(nalist) X <- matrix(0,m*k,k*p) X[!na,] <- do.call("rbind",Xlist) y <- rep(0,m*k) y[!na] <- unlist(ylist) tXWXtot <- sumlist(lapply(gls$invtUXlist,crossprod)) invtXWXtot <- chol2inv(chol(tXWXtot)) H <- X %*% invtXWXtot %*% crossprod(X,W) IminusH <- diag(m*k)-H Q <- fbtr(W%*%tcrossprod(IminusH%*%y),k) A <- crossprod(IminusH,W) B <- crossprod(IminusH,diag(!na)) btrB <- fbtr(B,k) ind <- (seq(m)-1)*k indrow <- rep(ind,length(ind)) indcol <- rep(ind,each=length(ind)) tBA <- sumlist(lapply(seq(indrow), function(i) { row <- indrow[i]+(seq(k)) col <- indcol[i]+(seq(k)) t(B[row,col]%x%A[row,col])})) Psi1 <- qr.solve(tBA,as.numeric(Q-btrB)) dim(Psi1) <- c(k,k) Psi <- (Psi1+t(Psi1))/2 eig <- eigen(Psi) negeigen <- sum(eig$values<0) Psi <- eig$vectors %*% diag(pmax(eig$values,control$set.negeigen),k) %*% t(eig$vectors) gls <- glsfit(Xlist,ylist,Slist,nalist,Psi,onlycoef=FALSE) qrinvtUX <- qr(gls$invtUX) R <- qr.R(qrinvtUX) Qty <- qr.qty(qrinvtUX,gls$invtUy) vcov <- tcrossprod(backsolve(R,diag(1,ncol(gls$invtUX)))) res <- NULL fitted <- lapply(Xlist,"%*%",gls$coef) rank <- qrinvtUX$rank list(coefficients=gls$coef,vcov=vcov,Psi=Psi,residuals=res, fitted.values=fitted,df.residual=nall-rank-length(par),rank=rank,logLik=NA, negeigen=negeigen,control=control) }
plot.tuneclus<-function(x, dims = c(1,2), what = c(TRUE,TRUE), cludesc = FALSE, topstdres = 20, attlabs = NULL, binary = FALSE, subplot = FALSE, ...){ out=list() if (class(x$clusobjbest) == "cluspca") { out = plot.cluspca(x$clusobjbest, dims = dims, what = what, cludesc = cludesc, ...) } if (class(x$clusobjbest) == "cluspcamix") { out = plot.cluspcamix(x$clusobjbest, dims = dims, what = what, cludesc = cludesc, ...) } if (class(x$clusobjbest) == "clusmca") { out = plot.clusmca(x$clusobjbest,dims = dims, what = what, cludesc = cludesc, topstdres = topstdres, attlabs = attlabs, binary = binary, subplot = subplot, ...) } out }
entropy <- function(p, ...) { UseMethod("entropy") } entropy.default <- function(p, ...) { q <- p[p>0] -sum(q*log(q))/sum(q) } entropy.array <- function(p, margin, ...) { if (!missing(margin)) p <- marginTable(p, margin) q <- p[p > 0] -sum(q*log(q))/sum(q) } entropy.tables <- function(p, margin, ...) { if (!missing(margin)) p <- margin.tables(p, margin) tmp <- p*log(p) tmp[is.nan(tmp)] <- 0 -rowSums(tmp)/rowSums(p) } mutualInf <- function(p, m1, m2, condition, ...) { UseMethod("mutualInf") } mutualInf.default <- function(p, m1, m2, condition, ...) { if (missing(condition)) condition <- integer(0) if (length(intersect(m1,m2)) > 0 || length(intersect(c(m1,m2),condition))) stop("Variable sets must be disjoint") else tmp <- margin(p, c(m1, m2, condition))/sum(p) d1 <- prod(dim(tmp)[seq_along(m1)]) d2 <- prod(dim(tmp)[seq_along(m2)+length(m1)]) d3 <- prod(dim(tmp))/(d1*d2) dim(tmp) <- c(d1,d2,d3) p13 <- conditionTable2(tmp, c(1,3), c()) p23 <- conditionTable2(tmp, c(2,3), c()) p3 <- conditionTable2(tmp, c(3), c()) out <- tmp*(log(tmp) - log(p13) - log(p23) + log(p3)) return(sum(out[tmp > 0])) } mutualInf.tables <- function(p, m1, m2, condition, ...) { if (missing(condition)) condition <- integer(0) if (length(intersect(m1,m2)) > 0 || length(intersect(c(m1,m2),condition))) stop("Variable sets must be disjoint") else tmp <- margin(p, c(m1, m2, condition)) tmp <- tmp/rowSums(tmp) ds <- tdim(tmp) d1 <- prod(ds[seq_along(m1)]) d2 <- prod(ds[seq_along(m2)+length(m1)]) d3 <- prod(ds)/(d1*d2) tdim(tmp) <- c(d1,d2,d3) p13 <- conditional2(tmp, c(1,3), c()) p23 <- conditional2(tmp, c(2,3), c()) p3 <- conditional2(tmp, c(3), c()) out <- tmp*(log(tmp) - log(p13) - log(p23) + log(p3)) out[is.nan(out)] = 0 return(rowSums(out)) } interactionInf <- function(p, ...) UseMethod("interactionInf") interactionInf.default <- function(p, ..., condition) { dots <- list(...) if (missing(condition)) condition=integer(0) if (length(dots) == 1) { return(-entropy(p, c(dots[[1]], condition)) + entropy(p, condition)) } else { args1 <- c(list(p=p), dots[-1], list(condition=condition)) args2 <- c(list(p=p), dots[-1], list(condition=c(dots[[1]], condition))) return(do.call(Recall, args2) - do.call(Recall, args1)) } } kl <- function(x, y, ...) { UseMethod("kl") } kl.default <- function(x, y, ...) { sum(x[y > 0]*log(x[y > 0]/y[y > 0])) } kl.tables <- function(x, y, ...) { if (!("tables" %in% class(y))) y <- as_tables(y) nx = ntables(x) ny = ntables(y) if (nx < ny) { if (ny %% nx != 0) warning("longer object length is not a multiple of shorter object length") x = x[rep.int(seq_len(nx), ny),,drop=FALSE] } else if (nx > ny) { if (nx %% ny != 0) warning("longer object length is not a multiple of shorter object length") y = y[rep.int(seq_len(ny), nx),,drop=FALSE] } tmp <- x*log(x/y) tmp[is.nan(tmp)] = 0 rowSums(tmp) }
session <- RevoIOQ:::saveRUnitSession() "ps.tests.stress" <- function() { testit <- function(family, encoding="default") { postscript("ps-tests.ps", height=7, width=7, family=family, encoding=encoding) plot(1:10, type="n") text(5, 9, "Some text") text(5, 8 , expression(italic("italic"))) text(5, 7 , expression(bold("bold"))) text(5, 6 , expression(bolditalic("bold & italic"))) text(8, 3, expression(paste(frac(1, sigma*sqrt(2*pi)), " ", plain(e)^{frac(-(x-mu)^2, 2*sigma^2)}))) dev.off() } testit("Helvetica") testit("AvantGarde") testit("Bookman") testit("Courier") testit("Helvetica-Narrow") testit("NewCenturySchoolbook") testit("Palatino") testit("Times") testit("URWGothic") testit("URWBookman") testit("NimbusMon") testit("NimbusSan") testit("NimbusSanCond") testit("CenturySch") testit("URWPalladio") testit("NimbusRom") testit("URWHelvetica") testit("URWTimes") testit("ComputerModern", "TeXtext.enc") unlink("ps-tests.ps") } "test.ps.tests.stress" <- function() { res <- try(ps.tests.stress()) checkTrue(!is(res, "try-error"), msg="ps.tests stress test failed") } "testzzz.restore.session" <- function() { checkTrue(RevoIOQ:::restoreRUnitSession(session), msg="Session restoration failed") }
pop_specificFST <- function(popdata, cov=FALSE){ numpop <- popdata$num_pop numloci <- popdata$num_loci ni <- popdata$pop_sizes fst.wg.num <- array(0, c(numloci,numpop)) fst.wg.den <- rep(0, numloci) message("Calculating population ", appendLF=FALSE) cstep.pop <- "" for(cl in 1:numloci){ message(paste0(rep("\b", nchar(cstep.pop)), collapse=""), appendLF=FALSE) cstep.pop <- paste0(cl, "/", numpop) caf.pop <- popdata$allele_freq[[cl]] cni <- popdata$ind_count[[cl]] cMwi <- 2*cni/(2*cni-1) * colSums(caf.pop^2,na.rm=TRUE) - 1/(2*cni-1) cMBii <- 0 for(cp1 in 1:(numpop-1)){ for(cp2 in (cp1+1):numpop){ cMBii <- cMBii + sum(caf.pop[,cp1] * caf.pop[,cp2], na.rm=TRUE) }} cMBii <- cMBii * 2 cMB <- 1/(numpop*(numpop-1)) * cMBii fst.wg.num[cl,] <- cMwi - cMB fst.wg.den[cl] <- 1 - cMB } popfst.wg <- colMeans(fst.wg.num) / mean(fst.wg.den) names(popfst.wg) <- popdata$pop_names xbar <- mean(fst.wg.den) ybar <- colMeans(fst.wg.num) V_popfst.wg <- (ybar^2)/(xbar^4)*var(fst.wg.den)/numloci + 1/(xbar^2) * apply(fst.wg.num,2,var)/numloci - (2*ybar)/(xbar^3) * as.numeric(cov(fst.wg.num,fst.wg.den))/numloci COV_popfst.wg <- NULL if(cov){ COV_popfst.wg <- array(NA, c(numpop,numpop)) for(cp1 in 1:(numpop-1)){ ybar1 <- ybar[cp1] for(cp2 in (cp1+1):numpop){ ybar2 <- ybar[cp2] COV_popfst.wg[cp1,cp2] <- COV_popfst.wg[cp2,cp1] <- ybar1*ybar2/(xbar^4)*var(fst.wg.den)/numloci - ybar1/(xbar^3) * cov(fst.wg.num[,cp1],fst.wg.den)/numloci - ybar2/(xbar^3) * cov(fst.wg.num[,cp2],fst.wg.den)/numloci }} diag(COV_popfst.wg) <- V_popfst.wg } message(paste0(rep("\b", nchar(cstep.pop)), collapse=""), appendLF=FALSE) message(" done.") return(list( fst=data.frame(FST=popfst.wg, SE=sqrt(V_popfst.wg)), cov=COV_popfst.wg )) }
tam_exp_overflow <- function(x, max=1E200 ) { x <- ifelse( is.na(x), -max, x ) x <- ifelse( x > max, max, x) y <- exp(x) return(y) }
grid = 10^seq(-4, log10(1), length.out=10) tol = 1e-6 max_iterations = 10000 for (family in c("gaussian", "binomial")){ for (seed in 2:2) { cat("---", seed, family, "\n") data = data.gen(sample_size=200, p=50, n_g_non_zero=10, n_gxe_non_zero=4, seed=seed, family=family, normalize=TRUE) file_name = paste0("tests/testthat/testdata/", seed, "_", family, "_data.rds") saveRDS(data, file_name) start = Sys.time() fit = gesso.fit(data$G_train, data$E_train, data$Y_train, tolerance=tol, grid=grid, family=family, normalize=FALSE, max_iterations=max_iterations) print(Sys.time() - start) cat("-- gesso.fit done in ", Sys.time() - start, " seconds. num not converged ", sum(1 - fit$has_converged), "\n") cvxr_fit = hierNetGxE.cvxr(data$G_train, data$E_train, data$GxE_train, data$Y_train, grid=grid, tol=tol, family=family) print(max(fit$objective_value - cvxr_fit$objective_value) < tol) file_name = paste0("tests/testthat/testdata/", seed, "_", family, "_cvxr_results.rds") saveRDS(cvxr_fit$objective_value, file_name) } }
NULL .impl_inner.OptimalMatch <- function(x, y, inner_comparator, agg_function, maximize, insertion, deletion, substitution) { seq_x <- seq_along(x) seq_y <- seq_along(y) nx <- length(x) ny <- length(y) ins_id <- seq(from=nx+1, length.out = ny) del_id <- seq(from=ny+1, length.out = nx) x[ins_id] <- "" y[del_id] <- "" scores <- pairwise(inner_comparator, x, y) scores <- as.matrix(scores) scores[seq_x,del_id] <- deletion * scores[seq_x,del_id] scores[ins_id,seq_y] <- insertion * scores[ins_id,seq_y] scores[seq_x,seq_y] <- substitution * scores[seq_x,seq_y] scores[ins_id,del_id] <- substitution * scores[ins_id,del_id] if (anyNA(scores)) return(NA) assignments <- solve_LSAP(scores, maximum = maximize) sel_x <- union(seq_x, which(assignments <= ny)) sel_y <- assignments[sel_x] scores <- scores[cbind(sel_x, sel_y)] agg_function(scores) } setClass("FuzzyTokenSet", contains = "StringComparator", slots = c(inner_comparator = "StringComparator", agg_function = "function", deletion = "numeric", insertion = "numeric", substitution = "numeric"), prototype = structure( .Data = function(x, y, ...) elementwise(sys.function(), x, y, ...), inner_comparator = Levenshtein(), agg_function = base::mean, deletion = 1.0, insertion = 1.0, substitution = 1.0, symmetric = TRUE, distance = TRUE, ordered = FALSE ), validity = function(object) { errs <- character() if (object@deletion < 0 | length(object@deletion) != 1) errs <- c(errs, "`deletion` must be a non-negative numeric vector of length 1") if (object@insertion < 0 | length(object@insertion) != 1) errs <- c(errs, "`insertion` must be a non-negative numeric vector of length 1") if (object@substitution < 0 | length(object@substitution) != 1) errs <- c(errs, "`substitution` must be a non-negative numeric vector of length 1") symmetric_weights <- object@deletion == object@insertion if (!object@symmetric & symmetric_weights & object@inner_comparator@symmetric) errs <- c(errs, "`symmetric` must be TRUE when `deletion==insertion` and `inner_comparator` is symmetric") if (object@symmetric & (!symmetric_weights | !object@inner_comparator@symmetric)) errs <- c(errs, "`symmetric` must be FALSE when `deletion!=insertion` or `inner_comparator` is not symmetric") if (object@tri_inequal) errs <- c(errs, "`tri_inequal` must be FALSE") if (object@ordered) errs <- c(errs, "`ordered` must be FALSE") ifelse(length(errs) == 0, TRUE, errs) }) FuzzyTokenSet <- function(inner_comparator = Levenshtein(normalize = TRUE), agg_function = base::mean, deletion = 1, insertion = 1, substitution = 1) { distance <- inner_comparator@distance similarity <- inner_comparator@similarity symmetric <- inner_comparator@symmetric & deletion == insertion arguments <- c(as.list(environment())) do.call("new", append("FuzzyTokenSet", arguments)) } setMethod(elementwise, signature = c(comparator = "FuzzyTokenSet", x = "list", y = "list"), function(comparator, x, y, ...) { if (length(x) < length(y)) { x <- rep(x, times = length(y)) } else if (length(y) < length(x)) { y <- rep(y, times = length(x)) } out <- vector(mode = "numeric", length = length(x)) for (i in seq_along(x)) { out[i] <- .impl_inner.OptimalMatch(x[[i]], y[[i]], comparator@inner_comparator, comparator@agg_function, !comparator@distance, comparator@insertion, comparator@deletion, comparator@substitution) } out } ) setMethod(pairwise, signature = c(comparator = "FuzzyTokenSet", x = "list", y = "list"), function(comparator, x, y, return_matrix, ...) { scores <- matrix(0.0, nrow = length(x), ncol = length(y)) for (i in seq_len(length(x))) { for (j in seq_len(length(y))) { scores[i,j] <- .impl_inner.OptimalMatch(x[[i]], y[[j]], comparator@inner_comparator, comparator@agg_function, !comparator@distance, comparator@insertion, comparator@deletion, comparator@substitution) } } if (!return_matrix) scores <- as.PairwiseMatrix(scores) scores } ) setMethod(pairwise, signature = c(comparator = "FuzzyTokenSet", x = "vector", y = "NULL"), function(comparator, x, y, return_matrix, ...) { if (!return_matrix) warning("`return_matrix = FALSE` is not supported") pairwise(comparator, x, x, return_matrix) } )
NULL StatBezier <- ggproto('StatBezier', Stat, compute_layer = function(self, data, params, layout) { if (is.null(data)) return(data) data <- remove_missing(data, params$na.rm, c(self$required_aes, self$non_missing_aes), snake_class(self), finite = TRUE ) params <- params[intersect(names(params), self$parameters())] args <- c(list(data = quote(data), scales = quote(scales)), params) dapply(data, "PANEL", function(data) { scales <- layout$get_scales(data$PANEL[1]) tryCatch(do.call(self$compute_panel, args), error = function(e) { warning("Computation failed in `", snake_class(self), "()`:\n", e$message, call. = FALSE) new_data_frame() }) }) }, compute_panel = function(data, scales, n = 100) { if (is.null(data)) return(data) nControls <- table(data$group) controlRange <- range(nControls) if (min(controlRange) < 3 || max(controlRange) > 4) { stop('Only support for quadratic and cubic beziers') } data <- data[order(data$group), ] groups <- unique(data$group) paths <- getBeziers(data$x, data$y, match(data$group, groups), n) paths <- data.frame( x = paths$paths[, 1], y = paths$paths[, 2], group = groups[paths$pathID] ) paths$index <- rep(seq(0, 1, length.out = n), length(nControls)) dataIndex <- rep(match(unique(data$group), data$group), each = n) cbind( paths, data[dataIndex, !names(data) %in% c('x', 'y', 'group'), drop = FALSE] ) }, required_aes = c('x', 'y'), extra_params = c('na.rm', 'n') ) stat_bezier <- function(mapping = NULL, data = NULL, geom = 'path', position = 'identity', na.rm = FALSE, show.legend = NA, n = 100, inherit.aes = TRUE, ...) { layer( stat = StatBezier, data = data, mapping = mapping, geom = geom, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list(na.rm = na.rm, n = n, ...) ) } geom_bezier <- function(mapping = NULL, data = NULL, stat = 'bezier', position = 'identity', arrow = NULL, lineend = 'butt', na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, n = 100, ...) { layer( data = data, mapping = mapping, stat = stat, geom = GeomPath, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list( arrow = arrow, lineend = lineend, na.rm = na.rm, n = n, ... ) ) } StatBezier2 <- ggproto('StatBezier2', Stat, compute_layer = function(self, data, params, panels) { if (is.null(data)) return(data) data <- data[order(data$group), ] nControls <- table(data$group) controlRange <- range(nControls) if (min(controlRange) < 3 || max(controlRange) > 4) { stop('Only support for quadratic and cubic beziers') } groups <- unique(data$group) paths <- getBeziers(data$x, data$y, match(data$group, groups), params$n) paths <- data.frame( x = paths$paths[, 1], y = paths$paths[, 2], group = groups[paths$pathID] ) paths$index <- rep(seq(0, 1, length.out = params$n), length(nControls)) dataIndex <- rep(match(unique(data$group), data$group), each = params$n) paths <- cbind(paths, data[dataIndex, 'PANEL', drop = FALSE]) extraCols <- !names(data) %in% c('x', 'y', 'group', 'PANEL') startIndex <- c(1, cumsum(nControls) + 1)[-(length(nControls) + 1)] endIndex <- c(startIndex[-1] - 1, nrow(data)) dataIndex <- c(startIndex, endIndex) pathIndex <- match(unique(data$group), paths$group) pathIndex <- c(pathIndex, pathIndex + 1) paths$.interp <- TRUE paths$.interp[pathIndex] <- FALSE if (any(extraCols)) { for (i in names(data)[extraCols]) { paths[[i]] <- data[[i]][1] paths[[i]][pathIndex] <- data[dataIndex, i] } } paths }, required_aes = c('x', 'y'), extra_params = c('na.rm', 'n') ) stat_bezier2 <- function(mapping = NULL, data = NULL, geom = 'path_interpolate', position = 'identity', na.rm = FALSE, show.legend = NA, n = 100, inherit.aes = TRUE, ...) { layer( stat = StatBezier2, data = data, mapping = mapping, geom = geom, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list(na.rm = na.rm, n = n, ...) ) } geom_bezier2 <- function(mapping = NULL, data = NULL, stat = 'bezier2', position = 'identity', arrow = NULL, lineend = 'butt', na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, n = 100, ...) { layer( data = data, mapping = mapping, stat = stat, geom = GeomPathInterpolate, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list( arrow = arrow, lineend = lineend, na.rm = na.rm, n = n, ... ) ) } StatBezier0 <- ggproto('StatBezier0', Stat, compute_layer = function(self, data, params, layout) { if (is.null(data)) return(data) data <- remove_missing(data, params$na.rm, c(self$required_aes, self$non_missing_aes), snake_class(self), finite = TRUE ) params <- params[intersect(names(params), self$parameters())] args <- c(list(data = quote(data), scales = quote(scales)), params) dapply(data, "PANEL", function(data) { scales <- layout$get_scales(data$PANEL[1]) tryCatch(do.call(self$compute_panel, args), error = function(e) { warning("Computation failed in `", snake_class(self), "()`:\n", e$message, call. = FALSE) new_data_frame() }) }) }, compute_panel = function(data, scales) { if (is.null(data)) return(data) data <- data[order(data$group), ] nControls <- table(data$group) controlRange <- range(nControls) if (min(controlRange) < 3 || max(controlRange) > 4) { stop('Only support for quadratic and cubic beziers') } quadratic <- nControls == 3 if (any(quadratic)) { controlIndex <- c(1, cumsum(nControls) + 1)[-(length(nControls) + 1)] extraRows <- controlIndex[quadratic] + 1 extraRows <- sort(c(seq_len(nrow(data)), extraRows)) data <- data[extraRows, ] } data }, required_aes = c('x', 'y') ) GeomBezier0 <- ggproto('GeomBezier0', GeomPath, draw_panel = function(data, panel_scales, coord, arrow = NULL, lineend = 'butt', linejoin = 'round', linemitre = 1, na.rm = FALSE) { coords <- coord$transform(data, panel_scales) if (!is.integer(coords$group)) { coords$group <- match(coords$group, unique(coords$group)) } startPoint <- match(unique(coords$group), coords$group) bezierGrob(coords$x, coords$y, id = coords$group, default.units = 'native', arrow = arrow, gp = gpar( col = alpha(coords$colour[startPoint], coords$alpha[startPoint]), lwd = coords$size[startPoint] * .pt, lty = coords$linetype[startPoint], lineend = lineend, linejoin = linejoin, linemitre = linemitre ) ) } ) stat_bezier0 <- function(mapping = NULL, data = NULL, geom = 'bezier0', position = 'identity', na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, ...) { layer( stat = StatBezier0, data = data, mapping = mapping, geom = geom, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list(na.rm = na.rm, ...) ) } geom_bezier0 <- function(mapping = NULL, data = NULL, stat = 'bezier0', position = 'identity', arrow = NULL, lineend = 'butt', na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, ...) { layer( data = data, mapping = mapping, stat = stat, geom = GeomBezier0, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list(arrow = arrow, lineend = lineend, na.rm = na.rm, ...) ) }
eigenPCA <- function(data,tol=.Machine$double.eps) { center1 <- colMeans(data,2,mean) datascale <- scale(data,2,scale=FALSE) eigData <- eigen(cov(datascale),symmetric=TRUE) eigData$values <- eigData$values[which(eigData$values > tol)] sdev <- sqrt(eigData$values) rotation <- eigData$vectors[,1:length(sdev)] x <- t(t(rotation)%*%t(datascale)) return(list(x=x,rotation=rotation,sdev=sdev,center=center1)) }
library(bfast) library(Rwtss) server <- "http://www.esensing.dpi.inpe.br/wtss" coverages <- Rwtss::list_coverages(server) cv <- Rwtss::describe_coverage(server,c("MOD13Q1")) ndvi_wtss <- Rwtss::time_series(server, "MOD13Q1", attributes = c("ndvi"), latitude = -10.408, longitude = -53.495) plot(ndvi_wtss) ndvi_ts <- Rwtss::wtss_to_ts(ndvi_wtss) one_break <- bfast::bfast01(ndvi_ts) plot(one_break)
"daughterSire"
BayesCPH = function(y, t, x, steps = 1000, priorMean = NULL, priorVar = NULL, mleMean = NULL, mleVar, startValue = NULL, randomSeed = NULL, plots = FALSE){ if(!is.null(randomSeed)) set.seed(randomSeed) nObs = length(y) if(is.vector(x)) x = as.matrix(x, ncol = 1) nParameters = ncol(x) + 1 if(!is.null(startValue)){ if(length(startValue) < nParameters){ stop("You must have as many starting values as you have model parameters") } } if(is.null(mleMean)) mleMean = c(log(mean(y)), rep(0, nParameters - 1)) X = cbind(rep(1 , nObs) , x) Xt = t(X) calcMatchedCurvatureNormLike = function(){ betaX = X %*% mleMean Mu = t * exp(betaX) Vdiag = Mu Y = betaX + (y - Mu) / Mu Vyinv = matrix(0, nrow = nObs, ncol = nObs) diag(Vyinv) = Vdiag XtV = Xt %*% Vyinv VLinv = XtV %*% X VL = solve(VLinv) w1 = VL %*% XtV mleMean = w1 %*% Y for(k in 1:20){ betaX = X %*% mleMean Mu = t * exp(betaX) Vdiag = Mu Y = betaX + (y - Mu) / Mu Vyinv = matrix(0, nrow = nObs, ncol = nObs) diag(Vyinv) = Vdiag XtV = Xt %*% Vyinv VLinv = XtV %*% X VL = solve(VLinv) w1 = VL %*% XtV mleMean = w1 %*% Y } return(list(mleMean = mleMean, mleVar = VL)) } normApproxPosterior = function(){ result = list(postMean = rep(0, nParameters), postVar = matrix(0, ncol = nParameters, nrow = nParameters)) if(is.null(priorMean) & is.null(priorVar)){ result$postMean = mleMean result$postVar = mleVar }else{ mleVarInv = solve(mleVar) priorVarInv = solve(priorVar) postPrec = mleVarInv + priorVarInv result$postVar = solve(postPrec) w2 = postVar %*% priorVarInv w4 = w2 * priorMean w3 = postVar %*% mleVarInv w5 = w3 * mleMean result$postMean = w4 + w5 } return(result) } mleParams = calcMatchedCurvatureNormLike() mleMean = mleParams$mleMean mleVar = mleParams$mleVar posterior = normApproxPosterior() postMean = posterior$postMean postVar = posterior$postVar U = chol(postVar) candBeta = matrix(rt(steps * nParameters, df = 4), ncol = nParameters) if(!is.null(startValue)) candBeta[1,]=startValue WM2 = candBeta %*% U WM3 = matrix(rep(postMean , rep(steps,nParameters)),ncol = nParameters) WM4 = WM2 + WM3 V2 = cov(WM4) ft0 = apply(dt(candBeta, df = 4), 1, prod) ftn = apply(dnorm(candBeta), 1, prod) q1 = ft0 / 1 BetaXt = WM4 %*% Xt BetaXt = exp(BetaXt) for(j in 1:nObs) BetaXt[ , j] = -t[j] * BetaXt[,j] + y[j] * log(t[j] * BetaXt[,j]) logg1 = rowSums(BetaXt) logg1 = logg1 - max(logg1) logq1 = log(q1) u = runif(steps) i1 = 1 betaSample = WM4 for(n in 2:steps){ alpha = exp(logq1[i1] + logg1[n] - logq1[n] - logg1[i1]) alpha = ifelse(alpha>1, 1, alpha) if(u[n] >= alpha){ betaSample[n,] = WM4[i1,] }else{ betaSample[n,] = WM4[n,] i1 = n } } beta.df = data.frame(betaSample) names(beta.df) = paste("b",0:(ncol(beta.df) - 1),sep = "") describe(beta.df) Mean.beta = sapply(beta.df,mean) StdDev.beta = sapply(beta.df,sd) Z.beta = Mean.beta / StdDev.beta print(data.frame(Mean.beta,StdDev.beta,Z.beta)) if(plots){ nRows = nParameters nCols = 2 oldPar = par(mfrow = c(nRows, nCols)) nms = names(beta.df) for(i in 1:nParameters){ plot(ts(beta.df[,i]), main = paste("Time series plot of",nms[i]), ylab = nms[i]) plot(acf(beta.df[,i], plot = FALSE), main = paste("Autocorrelation plot of", nms[i])) } par(oldPar) } invisible(list(beta = beta.df, mleMean = mleMean, mleVar = mleVar)) }
get_publication <- function(resource, limit = 20L, verbose = FALSE, warnings = TRUE, progress_bar = TRUE) { tbl_json <- get(resource_url = resource, limit = limit, verbose = verbose, warnings = warnings, progress_bar = progress_bar) tidy_tbls <- as_tidy_tables_publications(tbl_json) return(tidy_tbls) } get_publication_all <- function(limit = 20L, verbose = FALSE, warnings = TRUE, progress_bar = TRUE) { resource <- '/rest/publication/all' get_publication(resource = resource, limit = limit, verbose = verbose, warnings = warnings, progress_bar = progress_bar) } get_publication_by_pgp_id <- function(pgp_id, limit = 20L, verbose = FALSE, warnings = TRUE, progress_bar = TRUE) { resource <- '/rest/publication' resource_urls <- sprintf("%s/%s", resource, pgp_id) purrr::map( resource_urls, get_publication, limit = limit, warnings = warnings, verbose = verbose, progress_bar = progress_bar ) %>% purrr::pmap(dplyr::bind_rows) } get_publication_by_pgs_id <- function(pgs_id, limit = 20L, verbose = FALSE, warnings = TRUE, progress_bar = TRUE) { resource <- '/rest/publication/search' resource_urls <- sprintf("%s?pgs_id=%s", resource, pgs_id) purrr::map( resource_urls, get_publication, limit = limit, warnings = warnings, verbose = verbose, progress_bar = progress_bar ) %>% purrr::pmap(dplyr::bind_rows) } get_publication_by_pubmed_id <- function(pubmed_id, limit = 20L, verbose = FALSE, warnings = TRUE, progress_bar = TRUE) { resource <- '/rest/publication/search' resource_urls <- sprintf("%s?pmid=%s", resource, pubmed_id) purrr::map( resource_urls, get_publication, limit = limit, warnings = warnings, verbose = verbose, progress_bar = progress_bar ) %>% purrr::pmap(dplyr::bind_rows) } get_publication_by_author <- function(author, limit = 20L, verbose = FALSE, warnings = TRUE, progress_bar = TRUE) { author <- purrr::map_chr(author, utils::URLencode, reserved = TRUE) resource <- '/rest/publication/search' resource_urls <- sprintf("%s?author=%s", resource, author) purrr::map( resource_urls, get_publication, limit = limit, warnings = warnings, verbose = verbose, progress_bar = progress_bar ) %>% purrr::pmap(dplyr::bind_rows) } get_publications <- function(pgp_id = NULL, pgs_id = NULL, pubmed_id = NULL, author = NULL, set_operation = 'union', interactive = TRUE, verbose = FALSE, warnings = TRUE, progress_bar = TRUE) { if(!(rlang::is_scalar_character(set_operation) && set_operation %in% c('union', 'intersection'))) stop("set_operation must be either 'union' or 'intersection'") if(!(rlang::is_scalar_logical(verbose) && verbose %in% c(TRUE, FALSE))) stop("verbose must be either TRUE or FALSE") if(!(rlang::is_scalar_logical(warnings) && warnings %in% c(TRUE, FALSE))) stop("warnings must be either TRUE or FALSE") list_of_publications <- list() if (!rlang::is_null(pgp_id)) list_of_publications[['get_publication_by_pgp_id']] <- get_publication_by_pgp_id( pgp_id = pgp_id, verbose = verbose, warnings = warnings, progress_bar = progress_bar ) %>% coerce_to_s4_publications() if (!rlang::is_null(pgs_id)) list_of_publications[['get_publication_by_pgs_id']] <- get_publication_by_pgs_id(pgs_id = pgs_id, verbose = verbose, warnings = warnings, progress_bar = progress_bar) %>% coerce_to_s4_publications() if (!rlang::is_null(pubmed_id)) list_of_publications[['get_publication_by_pubmed_id']] <- get_publication_by_pubmed_id(pubmed_id = pubmed_id, verbose = verbose, warnings = warnings, progress_bar = progress_bar) %>% coerce_to_s4_publications() if (!rlang::is_null(author)) list_of_publications[['get_publication_by_author']] <- get_publication_by_author(author = author, verbose = verbose, warnings = warnings, progress_bar = progress_bar) %>% coerce_to_s4_publications() if(rlang::is_empty(list_of_publications)) { msg1 <- "You are about to download all publications from the PGS Catalog.\nThis might take a while." msg2 <- 'Returning an empty publications object!' msg3 <- 'OK! Getting all publications then. This is going to take a while...' if(interactive) default_answer = NULL else default_answer = 'y' if (sure( before_question = msg1, after_saying_no = msg2, after_saying_yes = msg3, default_answer = default_answer )) return(coerce_to_s4_publications( get_publication_all( verbose = verbose, warnings = warnings, progress_bar = progress_bar ) )) else return(coerce_to_s4_publications(NULL)) } else { if (identical(set_operation, "union")) { return(purrr::reduce(list_of_publications, union)) } if (identical(set_operation, "intersection")) { return(purrr::reduce(list_of_publications, intersect)) } } }
surv_reg <- function(mode = "regression", engine = "survival", dist = NULL) { lifecycle::deprecate_soft("0.1.6", "surv_reg()", "survival_reg()") args <- list( dist = enquo(dist) ) new_model_spec( "surv_reg", args = args, eng_args = NULL, mode = mode, method = NULL, engine = engine ) } print.surv_reg <- function(x, ...) { cat("Parametric Survival Regression Model Specification (", x$mode, ")\n\n", sep = "") model_printer(x, ...) if(!is.null(x$method$fit$args)) { cat("Model fit template:\n") print(show_call(x)) } invisible(x) } update.surv_reg <- function(object, parameters = NULL, dist = NULL, fresh = FALSE, ...) { eng_args <- update_engine_parameters(object$eng_args, ...) if (!is.null(parameters)) { parameters <- check_final_param(parameters) } args <- list( dist = enquo(dist) ) args <- update_main_parameters(args, parameters) if (fresh) { object$args <- args object$eng_args <- eng_args } else { null_args <- map_lgl(args, null_value) if (any(null_args)) args <- args[!null_args] if (length(args) > 0) object$args[names(args)] <- args if (length(eng_args) > 0) object$eng_args[names(eng_args)] <- eng_args } new_model_spec( "surv_reg", args = object$args, eng_args = object$eng_args, mode = object$mode, method = NULL, engine = object$engine ) } translate.surv_reg <- function(x, engine = x$engine, ...) { if (is.null(engine)) { message("Used `engine = 'survival'` for translation.") engine <- "survival" } x <- translate.default(x, engine, ...) x } check_args.surv_reg <- function(object) { if (object$engine == "flexsurv") { args <- lapply(object$args, rlang::eval_tidy) if (all(names(args) != "dist") || is.null(args$dist)) object$args$dist <- "weibull" } invisible(object) } survreg_quant <- function(results, object) { pctl <- object$spec$method$pred$quantile$args$p n <- nrow(results) p <- ncol(results) colnames(results) <- names0(p) results <- results %>% as_tibble() %>% mutate(.row = 1:n) %>% gather(.label, .pred, -.row) %>% arrange(.row, .label) %>% mutate(.quantile = rep(pctl, n)) %>% dplyr::select(-.label) .row <- results[[".row"]] results <- results %>% dplyr::select(-.row) results <- split(results, .row) names(results) <- NULL tibble(.pred = results) } flexsurv_mean <- function(results, object) { results <- unclass(results) results <- bind_rows(results) results$est } flexsurv_quant <- function(results, object) { results <- map(results, as_tibble) names(results) <- NULL results <- map(results, setNames, c(".quantile", ".pred", ".pred_lower", ".pred_upper")) }
"envspace.test" <- function(spe, env, coord, MEM.spe, listw.env, MEM.autocor = c("positive", "negative", "all"), regular = FALSE, nperm = 999, MSR.method = "singleton", alpha = 0.05) { spe <- as.data.frame(spe) coord <- as.matrix(coord) if (any(is.na(spe)) | any(is.na(coord))) stop("NA entries in spe or coord") if (nrow(spe) != nrow(coord)) stop("different number of rows") if (inherits(listw.env, what = "listw") == FALSE) stop("listw.env is not an object of class 'listw'") if (is.vector(MEM.spe) == FALSE) { if (ncol(MEM.spe) == nrow(coord) - 1) stop("n-1 MEM variables in 'MEM.spe'. Select a subset to avoid saturated model issues.") } nspe <- ncol(spe) if (is.vector(env) == "TRUE") nenv <- 1 else nenv <- ncol(env) M <- as.data.frame(matrix(0, ncol = (ncol(coord) + nspe + nenv), nrow = nrow(cbind(spe, env)))) M[, c(1:2)] <- coord M[, c(3:(2 + nspe))] <- spe M[, c((3 + nspe):ncol(M))] <- env MEM.autocor <- match.arg(MEM.autocor) global <- mem.select(env, listw.env, method = "global", MEM.autocor = MEM.autocor, alpha = alpha)$global.test if (MEM.autocor != "all") pval <- global$pvalue else pval <- c(global$positive$pvalue, global$negative$pvalue) if (length(which(pval <= alpha)) == 0) { message("No significant spatial structure detected in 'env'; the test was not performed") return() } test.spe <- anova.cca(rda(spe, MEM.spe)) if (test.spe$Pr[1] > alpha) { message("No significant spatial structure detected in 'spe'; the test was not performed") return() } test.env <- anova.cca(rda(spe, env)) if (test.env$Pr[1] > alpha) { message("No significant relation between 'spe' and 'env'; the test was not performed") return() } SSEF.unadj <- RsquareAdj(rda(spe, env))$r.squared - RsquareAdj(rda(spe, env, MEM.spe))$r.squared alternative <- ifelse(SSEF.unadj < 0, "less", "greater") R2.b <- varpart(M[, c(3:(2 + nspe))], env, MEM.spe)$part$indfract$Adj.R.square[2] E.b <- c() if (regular == "TRUE") { for (k in 1:nperm) { M2 <- M sens <- runif(1, min = 0, max = 1) rx <- ceiling(runif(1, 0.01, 0.99) * 50) ry <- ceiling(runif(1, 0.01, 0.99) * 25) if (sens <= 0.5) { M2[, 1] <- (M2[, 1] + rx) %% max(M2[, 1]) M2[, 2] <- (M2[, 2] + ry) %% max(M2[, 2]) } else { M2[, 1] <- max(M2[, 1]) - (M2[, 1] + rx) %% max(M2[, 1]) M2[, 2] <- max(M2[, 2]) - (M2[, 2] + ry) %% max(M2[, 2]) } M3 <- M M2 <- M2[order(M2[, 2]), ] M2 <- M2[order(M2[, 1]), ] M3[, c((3 + nspe):ncol(M))] <- M2[, c((3 + nspe):ncol(M))] E.toro <- M3[, c((3 + nspe):(3 + nenv))] E.b <- c(E.b, varpart(M[, c(3:(2 + nspe))], E.toro, MEM.spe)$part$indfract$Adj.R.square[2]) } } else { MSR.ENV <- msr(env, listw.env, nrepet = nperm, method = MSR.method, simplify = FALSE) for (k in 1:nperm) { E.b <- c(E.b, varpart(M[, c(3:(2 + nspe))], MSR.ENV[[k]], MEM.spe)$part$indfract$Adj.R.square[2]) } } return(as.randtest(obs = R2.b, sim = E.b, alter = alternative)) }
gesdTest <- function(x, maxr){ x <- na.omit(x) n <- length(x) if (n < 25 & n >=15) { warning("Due to sample-size, results are 'reasonable'") } else if (n <15) { warning("Due to sample-size, results are 'not reasonable'") } if(maxr > n){ stop("Number of potential outliers > sample-size. Reduce 'maxr'") } oldx <- x ix <- rep(NA, maxr) PVAL <- rep(NA, maxr) R <- rep(NA, maxr) for (i in (1:maxr)){ out <- grubbsTest(x, alternative = "two.sided") o <- out$estimate[1] ix[i] <- which(out$estimate[2] == oldx) PVAL[i] <- out$p.value R[i] <- out$statistic x <- x[-o] } ans <- list(method = "GESD multiple outlier test", statistic = R, p.value = PVAL, ix = ix, alternative = "two.sided") class(ans) <- "gesdTest" return(ans) } print.gesdTest <- function(x, ...) { cat("\n\t", x$method, "\n\n") n <- length(x$p.value) mat <- matrix(x$p.value, ncol=1, nrow= n, dimnames = list(c(1:n), c("p-value"))) cat("Nr. of outliers tested:\n") print(mat) cat("\nalternative hypothesis: ", x$alternative, "\n\n") invisible(x) } summary.gesdTest <- function(object, ...) { cat("\n\t", object$method, "\n\n") n <- length(object$p.value) symp <- symnum(object$p.value, corr=FALSE, cutpoints = c(0, .001,.01,.05, .1, 1), symbols = c("***","**","*","."," ")) outl <- character(n) for (i in 1:n){ tmp <- "" for (j in 1:i){ tmp <- paste0(tmp, " ", object$ix[j]) } outl[i] <- tmp } df <- data.frame(outl, object$statistic, format.pval(object$p.value), symp) colnames(df) <- c("i", "R", "Pr(>|R|)", "") cat("Outliers tested:\n") print(df) cat("\nalternative hypothesis: ", object$alternative, "\n") cat("---") cat("\nSignif. codes: ", attr(symp, 'legend'), "\n\n") invisible(object) }
compare.pls <- function(..., two.tailed = TRUE){ dots <- list(...) tails <- if(two.tailed) 2 else 1 if(length(dots) == 1) n <- length(dots[[1]]) else n <- length(dots) if(n == 1) stop("At least two objects of class pls are needed") if(length(dots) == 1) { list.names <- names(dots[[1]]) dots <- lapply(1:n, function(j) dots[[1]][[j]]) names(dots) <- list.names } else list.names <- names(dots) if(length(dots) < 2) stop("At least two objects of class pls are needed") is.pls <- function(x) inherits(x, "pls") sdn <- function(x) sqrt(sum((x-mean(x))^2)/length(x)) list.check <- sapply(1:length(dots), function(j) any(is.pls(dots[[j]]))) if(any(list.check == FALSE)) stop("Not all objects are class pls") k <- length(list.check) if(is.null(list.names)) list.names <- as.list(substitute(list(...)))[-1L] k.combn <- combn(k,2) bct <- lapply(dots, function(x) box.cox(x$random.r)$transformed) list.drs <- sapply(1:k, function(j) bct[[j]][1] - mean(bct[[j]])) list.sds <- sapply(1:k, function(j) sdn(bct[[j]])) list.zs <- sapply(1:k, function(j) effect.size(dots[[j]]$random.r, center=TRUE)) z12 <- sapply(1:ncol(k.combn), function(j){ a <- k.combn[1,j]; b <- k.combn[2,j] r1 <- list.drs[a]; r2 <- list.drs[b] sd1 <- list.sds[a]; sd2 <- list.sds[b] (r1-r2)/sqrt(sd1^2+sd2^2) }) z12.p <- sapply(1:length(z12), function(j) pnorm(abs(z12[[j]]), lower.tail = FALSE) * tails) d <- rep(0,k); names(d) <- list.names D <-dist(d) z12.pw <- p12.pw <- D for(i in 1:length(z12)) z12.pw[i] <-z12[i] for(i in 1:length(z12)) p12.pw[i] <-z12.p[i] names(list.zs) <- names(list.sds) <-list.names pairwise.z <- as.matrix(z12.pw) pairwise.P <- as.matrix(p12.pw) diag(pairwise.P) <- 1 out <- list(sample.z = list.zs, sample.r.sd = list.sds, pairwise.z = abs(pairwise.z), pairwise.P = pairwise.P) class(out) <- "compare.pls" out }
.assemble_tour <- function(se, memory) { element <- intro <- character(0) all_encs <- vapply(memory, .getEncodedName, "") check <- !is.null(se) && !is.null(memory) element <- c(element, " intro <- c(intro, "Welcome to the interactive tour for iSEE - the Interactive SummarizedExperiment Explorer.<br/><br/>You will be shown around the different components of iSEE and learn the basic usage mechanisms by doing. Highlighted elements will respond to the user's actions, while the rest of the UI will be shaded. You will be prompted at particular spots to perform some actions, which will be marked with \"<strong>Action:</strong>\" text. Please take care to follow these instructions, since later parts of the tour may assume that all the actions from previous steps have been performed.<br/><br/><strong>Action:</strong> now, click on the 'Next' button or use the right arrow of your keyboard to proceed into your tour.") element <- c(element, " intro <- c(intro, "iSEE provides a Shiny interface that allows you to generate a series of panels for exploring <code>SummarizedExperiment</code> objects. Here, we use single-cell RNA sequencing data from the <a href=\"https://doi.org/doi:10.18129/B9.bioc.scRNAseq\"><i>scRNAseq</i> package</a>, specifically a subset of gene expression profiles from cells in the mouse visual cortex <a href=\"https://doi.org/10.1038/nn.4216\">(Tasic <i>et al.</i>, 2016)</a>. Each column of the <code>SummarizedExperiment</code> corresponds to a cell, while each row corresponds to a gene.<br/><br/>Using iSEE, you can generate a variety of different panel types to visualize the data. These are described in more detail in the following steps.") enc_rdp <- "ReducedDimensionPlot1" if (check && !enc_rdp %in% all_encs) { return(.truncated_tour) } element <- c(element, paste0(" intro <- c(intro, "For example, you can construct a <font color=\" element <- c(element, paste0(" intro <- c(intro, "For each plot panel, a variety of parameters are available to control the appearance and behaviour of the plot. These parameters are located in these collapsible boxes, such as the <font color=\" if (check && (!is(se, "SingleCellExperiment") || !all(c("PCA", "TSNE") %in% reducedDimNames(se)))) { return(.truncated_tour) } element <- c(element, paste0(" intro <- c(intro, "<strong>Action:</strong> change this to <code>TSNE</code> to see the two-dimensional <i>t</i>-SNE representation.") element <- c(element, paste0(" intro <- c(intro, "You can see how the panel immediately switched to the requested dimensionality reduction result.") element <- c(element, paste0(" intro <- c(intro, "The <font color=\" element <- c(element, paste0(" intro <- c(intro, "By default, the points (cells) are not colored.<br/><br/><strong>Action:</strong> select <code>Column data</code> to colour the cells by a column metadata variable.") if (check && !"passes_qc_checks_s" %in% colnames(colData(se))) { return(.truncated_tour) } element <- c(element, paste0(" intro <- c(intro, "Currently, the points are colored by the first available column in the <code>colData</code> slot.<br/><br/><strong>Action:</strong> choose <code>passes_qc_checks_s</code> to colour cells based on whether they passed quality control (QC) checks.") element <- c(element, paste0(" intro <- c(intro, "You can now see that all cells that passed QC (<code>Y</code>) are colored differently from those that did not (<code>N</code>).") enc_cdp <- "ColumnDataPlot1" if (check && !enc_cdp %in% all_encs) { return(.truncated_tour) } element <- c(element, paste0(" intro <- c(intro, "You can construct a <font color=\" element <- c(element, paste0(" intro <- c(intro, "The plotting behaviour will also change depending on the type of data being plotted. This is best illustrated with <font color=\" element <- c(element, paste0(" intro <- c(intro, "Currently, there is only one violin plot.<br/><br/><strong>Action:</strong> click on <code>Column data</code>.") element <- c(element, paste0(" intro <- c(intro, "You can see how this now changes to a scatter plot when plotting two continuous variables against each other.") if (check && !"driver_1_s" %in% colnames(colData(se))) { return(.truncated_tour) } element <- c(element, paste0(" intro <- c(intro, "<strong>Action:</strong> click on (or type) <code>driver_1_s</code>.") element <- c(element, paste0(" intro <- c(intro, "The plot now changes to a grouped violin plot for a categorical variable on the x-axis. Note that a horizontal violin plot can also be generated if the categorical variable is assigned to the y-axis.") if (check && !"dissection_s" %in% colnames(colData(se))) { return(.truncated_tour) } element <- c(element, paste0(" intro <- c(intro, "<strong>Action:</strong> click on (or type) <code>dissection_s</code>.") element <- c(element, paste0(" intro <- c(intro, "The plot now changes to a Hinton plot for two categorical variables. The size of each rectangle corresponds to the number of points in each combination of covariate levels.") enc_fap <- "FeatureAssayPlot1" if (check && !enc_fap %in% all_encs) { return(.truncated_tour) } element <- c(element, paste0(" intro <- c(intro, "A <font color=\" enc_cdt <- "ColumnDataTable1" if (check && !enc_cdt %in% all_encs) { return(.truncated_tour) } element <- c(element, paste0(" intro <- c(intro, "A <font color=\" enc_rdt <- "RowDataTable1" if (check && !enc_rdt %in% all_encs) { return(.truncated_tour) } element <- c(element, paste0(" intro <- c(intro, "Similarly, a <font color=\" enc_rop <- "RowDataPlot1" if (check && !enc_rop %in% all_encs) { return(.truncated_tour) } element <- c(element, paste0(" intro <- c(intro, "You can also plot the <code>rowData</code> values against each other with a <font color=\" enc_sap <- "SampleAssayPlot1" if (check && !enc_sap %in% all_encs) { return(.truncated_tour) } element <- c(element, paste0(" intro <- c(intro, "A <font color=\" enc_chm <- "ComplexHeatmapPlot1" if (check && !enc_chm %in% all_encs) { return(.truncated_tour) } element <- c(element, paste0(" intro <- c(intro, "You can produce a <font color=\" element <- c(element, paste0(" intro <- c(intro, 'The <font color=" element <- c(element, paste0(" intro <- c(intro, "<strong>Action:</strong> select <font color=\" element <- c(element, paste0(" intro <- c(intro, "<strong>Action:</strong> make a brush on this plot by click-and-dragging a rectangular region over some points.") element <- c(element, paste0(" intro <- c(intro, "The points selected in the <font color=\" element <- c(element, paste0(" intro <- c(intro, 'If <font color=" element <- c(element, paste0(" intro <- c(intro, "Some information on the number of selected points is displayed in this element.") element <- c(element, paste0(" intro <- c(intro, "Similarly, a summary of the relationships between panels is displayed here.") element <- c(element, paste0(" intro <- c(intro, 'Even though this panel is receiving a selection, it is still able to transmit a selection to other panels. In this manner, we can construct arbitrarily complex (non-circular) networks between panels to display only a subset of points that match a certain criteria. This is equivalent to multi-step gating schemes in flow cytometry, provided the selection effect is set to <font color=" element <- c(element, paste0(" intro <- c(intro, 'Certain parameters can also respond to single selections from other panels, which we will demonstrate with the <font color=" element <- c(element, paste0(" intro <- c(intro, '<strong>Action:</strong> select <font color=" element <- c(element, paste0(" intro <- c(intro, '<strong>Action:</strong> click on another row.') element <- c(element, paste0(" intro <- c(intro, 'You can see that the y-axis has now changed to reflect the new row selection in <font color=" element <- c(element, paste0(" intro <- c(intro, 'A zooming functionality is also available by first brushing, then double-clicking on the brushed area.<br /><br /><strong>Action:</strong> click and drag to brush over an area. Now, double click inside the marked area to zoom in. To zoom out to the original plot, double-click on the plot.') element <- c(element, paste0(" intro <- c(intro, "The <font color=\" element <- c(element, paste0(" intro <- c(intro, "The assay displayed can be changed here.") element <- c(element, paste0(" intro <- c(intro, "This checkbox switches the selection of features between two modes:<ul><li>A manual selection using a text editor to paste and edit a custom list of features.</li><li>The same dynamic selection mechanism used for other row-based panels.</li></ul><strong>Action:</strong> untick the box to enable dynamic selection (i.e. disable the custom list of features).") element <- c(element, paste0(" intro <- c(intro, "The <font color=\" element <- c(element, paste0(" intro <- c(intro, "Column-level metadata can be selected and displayed above the heatmap.<br/><br/><strong>Action:</strong> Select a few metadata fields. Note how items can be reordered by drag-and-drop.") element <- c(element, paste0(" intro <- c(intro, "The same can be done to display row-level metadata on the left of the heatmap.<br/><br/><strong>Action:</strong> Select a few metadata fields.") element <- c(element, paste0(" intro <- c(intro, "Data transformation can also be applied to rows of the matrix, to facilitate intepretation without the need to store additional assay matrices.<br/><br/><strong>Action:</strong> tick the 'Transform' box. You may also untick the 'Annotations' box to free up space in the Visual parameters box.") element <- c(element, paste0(" intro <- c(intro, "Row values can be centered using this checkbox.<br/><br/><strong>Action:</strong> tick the box.") element <- c(element, paste0(" intro <- c(intro, "Once centered, row values can additional be scaled using this checkbox.<br/><br/><strong>Action:</strong> tick this box.") element <- c(element, paste0(" intro <- c(intro, "Similarly, if rows are centered, a colormap suitable for centered values can be selected in this menu.<br/><br/><strong>Action:</strong> choose any colormap.") element <- c(element, paste0(" intro <- c(intro, "The two-dimensional nature of the <font color=\" element <- c(element, paste0(" intro <- c(intro, "The source of incoming row selections (i.e., features) can be selected here.<br/><br/><strong>Action:</strong> Select the panel <font color=\" element <- c(element, paste0(" intro <- c(intro, "Similarly, the source of incoming column selections (i.e., samples) can be selected here.<br/><br/><strong>Action:</strong> Select the panel <font color=\" element <- c(element, paste0(" intro <- c(intro, "<strong>Action:</strong> Select data points representing features in this <font color=\" element <- c(element, paste0(" intro <- c(intro, "<strong>Action:</strong> Select samples representing samples in this <font color=\" element <- c(element, paste0(" intro <- c(intro, "You can see the result of our interactions so far, including the selections applied to both rows and columns of this plot.") element <- c(element, paste0(" intro <- c(intro, "By default, all samples are shown in the heatmap and column selections are marked by a separate colored annotation bar. Alternatively, the heatmap can be restricted to show only the selected samples.<br/><br/><strong>Action:</strong> enable the 'Restrict' option.") element <- c(element, paste0(" intro <- c(intro, "Having seleted features of interest, it is often helpful to cluster them by expression profile.<br/><br/><strong>Action:</strong> tick this box.") element <- c(element, paste0(" intro <- c(intro, "A number of clustering distances are available to choose from.") element <- c(element, paste0(" intro <- c(intro, "So are clustering methods.") element <- c(element, paste0(" intro <- c(intro, "At this point, we have constructed a rich heatmap that combines assay data with column and row metadata for a selection of features and samples, with features clustered by expression profile.") element <- c(element, ".navbar-static-top") intro <- c(intro, "A number of useful features are available from the dashboard header.<br /><br /><strong>Action:</strong> click on the panels icon to open the Panel Organization menu.<br /><br />Clicking on the <i>Organize panels</i> button opens a modal window, which contains a multi-selectize input widget to add, remove, resize, and reorder panels in the main interface. You can see how the boxes below this control mirror the order of the panels in the main body of the app.") element <- c(element, ".navbar-static-top") intro <- c(intro, "<strong>Action:</strong> click on the download icon to open the Export dropdown.<br /><br />In this dropdown menu, you can access a graph representation of the existing links between panels, the code required to reproduce all of the plots, and the code required to reproduce the current app state.") element <- c(element, ".navbar-static-top") intro <- c(intro, "<strong>Action:</strong> click on the question mark icon to open the Documentation dropdown.<br/><br/> This contains the button to start the <code>introjs</code>-based tour, which you are currently taking, as well as a link to the vignette for the iSEE package, in case you want to consult it while running the app.") element <- c(element, ".navbar-static-top") intro <- c(intro, "<strong>Action:</strong> click on the info icon.<br/><br/>This reports the session information from which you are running iSEE (which you should report in case of issues or bugs), the appropriate citation if you use iSEE in your work, as well as information on how to contact the iSEE development team.") element <- c(element, " intro <- c(intro, "Thank you for taking the tour of iSEE!") data.frame(element=element, intro=intro, stringsAsFactors=FALSE) } .truncated_tour <- data.frame( element=" intro="The default tour is only enabled for the default Allen example in <code>?iSEE</code>. For all other configurations, maintainers of the iSEE instance should define their own tours.", stringsAsFactors=FALSE ) defaultTour <- function() .assemble_tour(NULL, NULL)
context("Function updateInputSettings") sapply(studies, function(study) { setup_study(study, sourcedir) opts <- antaresRead::setSimulationPath(studyPath, "input") test_that("Update input settings", { updateInputSettings(import = c("hydro", "thermal")) expect_identical(getOption("antares")$parameters$input$import, c("hydro, thermal")) }) test_that("Dont update input settings if renewables", { expect_warning(updateInputSettings(import = "renewables")) expect_identical(getOption("antares")$parameters$input$import, NA) }) unlink(x = file.path(pathstd, "test_case"), recursive = TRUE) })
knitr::opts_chunk$set( collapse = TRUE, comment = " fig.width = 4, fig.height = 4 ) library(rosm) library(prettymapr) altalake <- searchbbox("alta lake, BC") altalake <- makebbox(50.1232, -122.9574, 50.1035, -123.0042) osm.plot(altalake) osm.types() osm.plot(altalake, type="stamenbw") bmaps.types() bmaps.plot(altalake, type="AerialWithLabels") bmaps.plot(altalake, zoomin=1) osm.plot(altalake) osm.points(c(-122.9841, -122.9812), c(50.11055, 50.11765), pch=15, cex=0.6) osm.text(c(-122.9841, -122.9812), c(50.11055, 50.11765), labels=c("GC6", "GC2"), adj=c(-0.2, 0.5), cex=0.5) altalake <- makebbox(50.1232, -122.9574, 50.1035, -123.0042) prettymap({ bmaps.plot(altalake) osm.points(c(-122.9841, -122.9812), c(50.11055, 50.11765), pch=15, cex=0.6, col="white") osm.text(c(-122.9841, -122.9812), c(50.11055, 50.11765), labels=c("GC6", "GC2"), adj=c(-0.2, 0.5), cex=0.7, col="white") }, scale.label.col = "white")
distinctAb <- function(comm, disORtree, method = c("Q", "KY", "KstarI"), palpha = 2, option = c("asymmetric", "symmetric"), tol = 1e-10){ option <- option[1] method <- method[1] palpha <- palpha[1] if (!method %in% c("Q", "KY", "KstarI")) stop("unconvenient method") if (any(comm < 0)) stop("comm should contain nonnegative values") commgardees <- (1:nrow(comm))[rowSums(comm) >= tol] commdiv <- comm[commgardees, ] ncommdiv <- nrow(commdiv) nsp <- ncol(comm) if(inherits(disORtree, "phylo") | inherits(disORtree, "phylo4") | inherits(disORtree, "hclust")){ arg.phyl <- .checkphyloarg(disORtree) phyl.phylo <- arg.phyl$phyl.phylo tre4 <- arg.phyl$phyl if (!hasEdgeLength(tre4)) phyl.phylo <- compute.brlen(phyl.phylo, 1) if(is.ultrametric(phyl.phylo) | option == c("symmetric")) dis <- cophenetic.phylo(phyl.phylo)/2 else dis <- matrix(rep(diag(vcv.phylo(phyl.phylo))), nsp, nsp)-vcv.phylo(phyl.phylo) commdiv <- commdiv[, phyl.phylo$tip.label] } else if(inherits(disORtree, "matrix") | inherits(disORtree, "dist") ) dis <- as.matrix(disORtree) else stop("uncovenient definition of disORtree") if (is.null(colnames(comm))) stop("comm must have names for columns") if (any(!colnames(comm) %in% colnames(dis))) stop("comm contains species names that are not available in disORtree") commdiv <- commdiv[, colnames(dis)] Freq <- sweep(commdiv, 1, rowSums(commdiv), "/") funi <- function(i){ if(method == "Q"){ commi <- as.vector(unlist(Freq[i,])) Matdis <- as.matrix(dis) ooi <- colSums(Matdis*commi) } if(method == "KY"){ dis01 <- dis/max(dis) commi <- as.vector(unlist(Freq[i,])) Matdis <- as.matrix(dis01) ordii <- 1-colSums(Matdis*commi) if(abs(palpha-1) > tol){ ooi <- (1-ordii^(palpha-1))/(palpha-1) ooi[abs(ordii)<tol] <- 1/(palpha-1) } else{ ordii[abs(ordii) < tol] <- 1 ooi <- log(1/ordii) } } if(method == "KstarI"){ dissort <- apply(dis, 1, sort) dissort <- t(apply(dissort, 2, diff)) Freqord <- sapply(1:nsp, function(x) Freq[i, order(dis[x,])]) Freqord <- apply(Freqord, 2, cumsum) Freqord <- Freqord[-nrow(Freqord), ] if(abs(palpha-1)<1e-10){ Freqord[abs(Freqord) < tol] <- 1 ooi <- colSums(t(dissort)*(log(1/Freqord))) } else{ ooi <- colSums( (t(dissort)*(1 - (Freqord)^(palpha-1) ))/(palpha-1)) } } return(ooi) } RESoo <- sapply(1:ncommdiv, funi) colnames(RESoo) <- rownames(comm) PA <- commdiv PA[PA>0] <- 1 RESoop <- t(RESoo) RESoop[PA<1] <- NA Contr <- t(RESoo)*Freq Contr[PA<1] <- 0 if(method == "Q") AbRare <- 1-Freq else{ if(abs(palpha-1)<1e-10) AbRare <- log(1/Freq) else{ AbRare <- (1-Freq^(palpha-1))/(palpha-1) AbRare[Freq<tol] <- 1/(palpha-1) } } FunPhyRare <- t(RESoo) / AbRare FunPhyRarep <- FunPhyRare FunPhyRarep[PA<1] <- NA RESoop[PA<1] <- NA if(method == "Q" | palpha > 1 + tol) RES <- list(TotContr = Contr, EffOriPres = RESoop, EffOriAll = t(RESoo), DistinctPres = FunPhyRarep, DistinctAll = FunPhyRare, Rarity = AbRare) else { AbRare[PA<1] <- NA RES <- list(TotContr = Contr, EffOriPres = RESoop, DistinctPres = FunPhyRarep, Rarity = AbRare) } return(RES) }
display_ease <- function(ease) { easepoints <- tween_numeric(c(0, 1), 100, ease)[[1]] progress <- seq(0, 1, length.out = 100) plot(progress, easepoints, type = 'l', main = ease, xlab = 'In', ylab = 'Out', bty = 'n') }
sipsanalysis <- function(Ce, Qe){ x <- Ce y <- Qe dat <- data.frame(x,y) n<- nrow(na.omit(dat)) fit259 <- (y ~ ((Qm*Ks*x^n)/(1 + Ks*x^n))) print("Sips Analysis") start <- data.frame(Qm = c(0, 100), Ks = c(0, 100), n = c(0, 10)) set.seed(511) suppressWarnings(fit260 <- nls2(fit259, start = start, control = nls.control(maxiter = 30, warnOnly = TRUE), algorithm = "port")) print(summary(fit260)) predict(fit260) error <- function(y){ pv <- (predict(fit260)) rmse<- (rmse(y,predict(fit260))) mae <- (mae(y,predict(fit260))) mse <- (mse(y,predict(fit260))) rae <- (rae(y,predict(fit260))) PAIC <- AIC(fit260) PBIC <- BIC(fit260) SE <-(sqrt(sum(predict(fit260)-x)^2)/(n-2)) colnames(y) <- rownames(y) <- colnames(y) list("Predicted Values" = pv, "Relative Mean Square Error" = rmse, "Mean Absolute Error" = mae, "Mean Squared Error" = mse, "Relative Absolute Error" = rae, "AIC" = PAIC, "BIC" = PBIC, "Standard Error Estimate" = SE) } e <- error(y) print(e) nplot <- function(Ce, Qe) { x <- (Ce); y <- (Qe) plot(x, y, main = "Sips Isotherm", xlab = "Ce", ylab = "Qe") lines(smooth.spline(Ce, predict(fit260)), col = "black") } nplot(Ce, Qe) rsqq <- lm(Qe~predict(fit260)) print(summary(rsqq)) }
percent_vol <- function(x, percent = 100){ y <- sort(x[!is.na(x)], decreasing = TRUE) z <- cumsum(as.numeric(y)) if(any(z <= percent/100)){ m <- max(z[z <= percent/100]) i <- which(z == m)[1] if(m < 1){ d <- ifelse(x >= y[i], x, 0) } else { d <- ifelse(x > y[i], x, 0) } return(d) } else { stop(paste0("cannot calculate ", percent, "% UD. Increase the resolution of the UDs (i.e. use smaller grid cells)."), call. = FALSE) } }
ij2k <- function(i, j, n) (j - 1) * n + i
gauss_loss <- function(W, y, sigmaUU, beta){ n <- nrow(W) loss <- numeric(ncol(beta)) for(i in seq(ncol(beta))) loss[i] <- (1/n) * sum( (y - W %*% beta[, i] ) ^2 ) - t(beta[, i]) %*% sigmaUU %*% beta[, i] return(loss) }
getTimeSeriesVintages <- function(series, con, tbl_vintages = "timeseries_vintages", schema = "timeseries") { in_clause <- paste0("('", paste(series, collapse = "','"), "')") query <- sprintf("SELECT ts_key, lower(ts_validity) as lower_bound, upper(ts_validity) as upper_bound FROM %s.%s WHERE ts_key in %s ORDER BY lower(ts_validity)", schema, tbl_vintages, in_clause) class(query) <- "SQL" db_return <- runDbQuery(con, query) db_keys <- db_return$ts_key db_return$ts_key <- NULL db_return[is.na(db_return)] <- structure(Inf, class = "Date") vintages <- split(db_return, db_keys) vintages[setdiff(series, db_keys)] <- NA vintages }
geom_superberrorbar <- function( mapping = NULL, data = NULL, stat = "identity", position = "identity", direction = "both", tipformat = "single", tipgap = 0.1, ..., na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE ) { layer( data = data, mapping = mapping, stat = stat, geom = GeomsuperbErrorbar, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list( na.rm = na.rm, orientation = orientation, direction = direction, tipformat = tipformat, tipgap = tipgap, ... ) ) } `%||%` <- function(x, y) {if (is.null(x)) y else x } GeomsuperbErrorbar <- ggproto("GeomsuperbErrorbar", Geom, default_aes = aes( colour = "black", vcolour = NULL, size = 0.5, linetype = 1, width = 0.5, alpha = NA ), draw_key = draw_key_path, required_aes = c("x|y", "ymin|xmin", "ymax|xmax"), setup_params = function(data, params) {GeomLinerange$setup_params(data, params) }, extra_params = c("na.rm", "orientation", "direction", "tipformat", "tipgap"), setup_data = function(data, params) { lefmul <- 1; rigmul <- 1; if (params$direction == "left") {rigmul <- 0} if (params$direction == "right") {lefmul <- 0} data$flipped_aes <- params$flipped_aes data <- flip_data(data, params$flipped_aes) data$width <- data$width %||% params$width %||% (resolution(data$x, FALSE) * 0.9) data3 <- data2 <- data data <- transform(data, xmin = x - lefmul*width/2, xmax = x + rigmul*width/2, width = NULL ) if ((params$tipformat == "double")|(params$tipformat == "triple")) { data2 <- transform(data2, ymin = ymin + params$tipgap, ymax = ymax - params$tipgap, xmin = x - lefmul*width/2, xmax = x + rigmul*width/2, width = NULL ) data <- rbind(data, data2) } if (params$tipformat == "triple") { data3 <- transform(data3, ymin = ymin + 2*params$tipgap, ymax = ymax - 2*params$tipgap, xmin = x - lefmul*width/2, xmax = x + rigmul*width/2, width = NULL ) data <- rbind(data, data3) } flip_data(data, params$flipped_aes) }, draw_panel = function(data, panel_params, coord, width = NULL, flipped_aes = FALSE) { data <- flip_data(data, flipped_aes) x <- as.vector(rbind(data$xmin, data$xmax, NA, data$x, data$x, NA, data$xmin, data$xmax)) y <- as.vector(rbind(data$ymax, data$ymax, NA, data$ymax, data$ymin, NA, data$ymin, data$ymin)) data$vcolour <- data$vcolour %||% data$colour %||% params$colour collist = c() for (i in 1:length(data$colour)) { collist = c(collist, rep(data$colour[i],3),rep(data$vcolour[i],2),rep(data$colour[i],3)) } data <- vctrs::new_data_frame(list( x = x, y = y, colour = collist, alpha = rep(data$alpha, each = 8), size = rep(data$size, each = 8), linetype = rep(data$linetype, each = 8), group = rep(1:(nrow(data)), each = 8), row.names = 1:(nrow(data) * 8) )) data <- flip_data(data, flipped_aes) GeomPath$draw_panel(data, panel_params, coord) } )
make_colors <- function( dat, categorical = FALSE, color_map = grDevices::hcl.colors ) { if (!categorical) { if (!is.numeric(dat)) stop("The selected variable is not numeric.", call. = FALSE) dat <- (dat - min(dat))/(diff(range(dat, na.rm = TRUE)) + 1e-15) color_map <- grDevices::colorRamp(color_map(20)) color <- grDevices::rgb(color_map(dat), maxColorValue = 255) } else { dat <- as.factor(dat) color_map <- structure(color_map(nlevels(dat)), names= levels(dat)) color <- color_map[as.integer(dat)] } structure( .Data = color, color_map = color_map ) } make_edges_colors <- function( x, eattr, ... ) { make_colors(dat = get_edge_attr(x, eattr), ...) } make_vertex_colors <- function( x, vattr, ... ) { if (!missing(vattr)) { vattr <- get_vertex_attr(x, vattr) } else vattr <- calc_degree(x, mode. = "in") make_colors(dat = vattr, ...) }
library(VGAM) tdata <- data.frame(x = runif(nn <- 1000)) tdata <- transform(tdata, y = rt(nn, df = exp(exp(0.5 - x)))) fit_vglm <- vglm(y ~ x, studentt3, data = tdata) fit_ib <- ib(fit_vglm) summary(fit_ib)
test_that("trivariate entropy works", { data(lawdata) df.att <- lawdata[[4]] df.att.ed <- data.frame( status = df.att$status, gender = df.att$gender, office = df.att$office-1, years = ifelse(df.att$years<=3,0, ifelse(df.att$years<=13,1,2)), age = ifelse(df.att$age<=35,0, ifelse(df.att$age<=45,1,2)), practice = df.att$practice, lawschool= df.att$lawschool-1) H.tri <- entropy_trivar(df.att.ed) result <- c(2.745, 2.63, 2.897, 2.67, 3.123, 2.995, 3.194, 3.032, 3.448, 3.079) expect_identical(H.tri[["H(V1,V2,V3)"]][1:10],result) })
library(knitr) library(rgl) rgl::setupKnitr() options(rgl.useNULL=TRUE) opts_chunk$set( collapse = TRUE, comment = " fig.show = "asis", warning=FALSE, message=FALSE, include = TRUE, out.width = "99%", fig.width = 8, fig.align = "center", fig.asp = 0.62 ) if (!requireNamespace("rmarkdown", quietly = TRUE) || !rmarkdown::pandoc_available("1.14")) { warning(call. = FALSE, "These vignettes assume rmarkdown and pandoc version 1.14 (or higher). These were not found. Older versions will not work.") knitr::knit_exit() } library(gMOIP) plotSol <- function(A, b, type = rep("c", ncol(A)), faces = rep("c", ncol(A)), plotFaces = TRUE, labels = "numb") { plotPolytope(A, b, type = type, faces = faces, labels = labels, plotFaces = plotFaces, argsTitle3d = list(main = "Solution space")) } plotCrit <- function(A, b, obj, crit = "min", type = rep("c", ncol(A)), addTriangles = TRUE, labels = "numb") { plotCriterion2D(A, b, obj, type = type, crit = crit, addTriangles = addTriangles, labels = labels) + ggplot2::ggtitle("Criterion space") } Ab <- matrix( c( 1, 1, 2, 5, 2, -1, 0, 3, -1, 2, 1, 3, 0, -3, 5, 2 ), nc = 4, byrow = TRUE) A <- Ab[,1:3] b <- Ab[,4] obj <- matrix(c(1, -6, 3, -4, 1, 6), nrow = 2) view <- matrix( c(-0.452365815639496, -0.446501553058624, 0.77201122045517, 0, 0.886364221572876, -0.320795893669128, 0.333835482597351, 0, 0.0986008867621422, 0.835299551486969, 0.540881276130676, 0, 0, 0, 0, 1), nc = 4) loadView(v = view) plotSol(A, b) plotCrit(A, b, obj, addTriangles = FALSE) plotSol(A, b, type = c("i","i","i")) plotCrit(A, b, obj, type = c("i","i","i")) plotSol(A, b, type = c("c","i","i")) plotCrit(A, b, obj, type = c("c","i","i")) plotSol(A, b, type = c("i","c","i")) plotCrit(A, b, obj, type = c("i","c","i")) plotSol(A, b, type = c("i","i","c")) plotCrit(A, b, obj, type = c("i","i","c")) plotSol(A, b, type = c("i","c","c"), plotFaces = F) plotCrit(A, b, obj, type = c("i","c","c")) plotSol(A, b, type = c("c","i","c"), plotFaces = F) plotCrit(A, b, obj, type = c("c","i","c")) plotSol(A, b, type = c("c","c","i"), plotFaces = F) plotCrit(A, b, obj, type = c("c","c","i")) rm(list = ls(all.names = TRUE))
library(data.table) library(disk.frame) setup_disk.frame() bench_disk.frame_data.table_group_by <- function(data1,n) { a.sharded.df = as.disk.frame(data1, shardby = c("year", "month", "day")) a.not_sharded.df = as.disk.frame(data1) a = copy(data1) setDT(a) data.table_timing = system.time(a[,.(mean_dep_time = mean(dep_time, na.rm=T)), .(year, month, day)])[3] disk.frame_sharded_timing = system.time( a.sharded.df[ , .(mean_dep_time = mean(dep_time, na.rm=TRUE)), .(year, month, day), keep = c("year", "month","day", "dep_time")])[3] disk.frame_not_sharded_timing = system.time( a.not_sharded.df[ , .( sum_dep_time = sum(dep_time, na.rm=TRUE), n = sum(!is.na(dep_time)) ), .(year, month, day), keep = c("year", "month","day", "dep_time")][ , .(mean_dep_time = sum(sum_dep_time)/sum(n)), .(year, month, day) ])[3] barplot( c(data.table_timing, disk.frame_sharded_timing, disk.frame_not_sharded_timing), names.arg = c("data.table", "sharded disk.frame", "not sharded disk.frame"), main = glue:glue("flights duplicated {n} times group-by year, month, day"), ylab = "Seconds") } system.time(flights_100 <- rbindlist(lapply(1:100, function(x) nycflights13::flights))) system.time(flights_1000 <- rbindlist(lapply(1:10, function(x) flights_100))) bench_disk.frame_data.table_group_by(flights_100, 100) bench_disk.frame_data.table_group_by(flights_1000, 1000)
library(sf) a = 0.95 b = 0.8 ang = 3 * pi / 180 rot = function(a) matrix(c(cos(a), sin(a), -sin(a), cos(a)), 2, 2) n = 12 drift = c(.12, .07) outer = rbind(c(-1,-1), c(1, -1), c(1, 1), c(-1, 1), c(-1, -1)) hole = a * outer[5:1,] p = st_sfc(lapply(0:n, function(i) { st_polygon(list(outer, hole)) * rot(0) * b^i + drift * i * b ^ i } )) plot(p, col = grey(0:n/n), border = 0) p = st_sfc(lapply(0:n, function(i) { st_polygon(list(outer, hole)) * rot(i * ang) * b ^ i + drift * i * b ^ i } )) p plot(p, col = grey(0:n/n), border = 0) g = st_geometrycollection(p) plot(g) mp = st_multipolygon(p) opar = par(mfrow = c(2,2), mar = rep(0,4)) plot(mp * rot(10)) plot(mp * rot(20)) plot(mp * rot(30)) plot(mp * rot(40)) par(opar)
context("test-g01-mosek_conif") MOSEK_AVAILABLE <- "MOSEK" %in% installed_solvers() TOL <- 1e-6 if (MOSEK_AVAILABLE) library("Rmosek") test_that("test MOSEK SOCP", { skip_on_cran() skip_if_not(MOSEK_AVAILABLE, "Skipping MOSEK test as it is not available.!") x <- Variable(3) y <- Variable(2) constraints <- list(p_norm(x, 2) <= y[1], p_norm(x, 2) <= y[2], x[1] + x[2] + 3 * x[3] >= 1.0, y <= 5) obj <- Minimize(3 * x[1] + 2 * x[2] + x[3]) prob <- Problem(obj, constraints) result_mosek <- solve(prob, solver = "MOSEK") x_mosek <- result_mosek$getValue(x) duals_mosek <- lapply(constraints, function(c) { result_mosek$getDualValue(c) }) result_ecos <- solve(prob, solver = "ECOS") x_ecos <- result_ecos$getValue(x) duals_ecos <- lapply(constraints, function(c) { result_ecos$getDualValue(c) }) expect_equal(x_mosek, x_ecos, tolerance = TOL) expect_equal(length(duals_ecos), length(duals_mosek)) for(i in seq_along(duals_mosek)) { expect_equal(duals_mosek[[i]], duals_ecos[[i]], tolerance = 1e-4) } }) test_that("test MOSEK SDP", { skip_on_cran() skip_if_not(MOSEK_AVAILABLE, "Skipping MOSEK test as it is not available.!") rho <- Variable(4, 4) constraints <- list(0.6 <= rho[1, 2], rho[1, 2] <= 0.9, 0.8 <= rho[1, 3], rho[1, 3] <= 0.9, 0.5 <= rho[2, 4], rho[2, 4] <= 0.7, -0.8 <= rho[3, 4], rho[3, 4] <= -0.4, rho[1, 1] == 1, rho[2, 2] == 1, rho[3, 3] == 1, rho[4, 4] == 1, rho %>>% 0) obj <- Minimize(rho[1, 4]) prob <- Problem(obj, constraints) result <- solve(prob, solver = "MOSEK") expect_equal(round(result$value, 2), -0.39) Y <- result$getDualValue(constraints[[length(constraints)]]) eigs <- eigen(Y, only.values = TRUE) expect_true(all(eigs$value >= 0)) complementary_slackness <- sum(diag(result$getValue(rho) %*% Y)) expect_equal(complementary_slackness, 0.0, tolereance = TOL) obj <- Maximize(rho[1, 4]) prob <- Problem(obj, constraints) result <- solve(prob, solver = "MOSEK") expect_equal(round(result$value, 2), 0.23) Y <- result$getDualValue(constraints[[length(constraints)]]) eigs <- eigen(Y, only.values = TRUE) expect_true(all(eigs$value >= 0)) complementary_slackness <- sum(diag(result$getValue(rho) %*% Y)) expect_equal(complementary_slackness, 0.0, tolerance = TOL) }) test_that("test MOSEK exponential cone", { skip_on_cran() skip_if_not(MOSEK_AVAILABLE, "Skipping MOSEK test as it is not available.!") x <- Variable(3, 1) constraints <- list(sum(x) <= 1.0, sum(x) >= 0.1, x >= 0.01, kl_div(x[2], x[1]) + x[2] - x[1] + x[3] <= 0) obj <- Minimize(3 * x[1] + 2 * x[2] + x[1]) prob <- Problem(obj, constraints) result_mosek <- solve(prob, solver = "MOSEK") val_mosek = result_mosek$value x_mosek = result_mosek$getValue(x) duals_mosek = lapply(constraints, function(c) { result_mosek$getDualValue(c) }) result_ecos <- solve(prob, solver = "ECOS") val_ecos = result_ecos$value x_ecos = result_ecos$getValue(x) duals_ecos = lapply(constraints, function(c) { result_ecos$getDualValue(c) }) expect_equal(val_mosek, val_ecos, tolerance = TOL) expect_equal(x_mosek, x_ecos, tolerance = 1e-4) expect_equal(length(duals_ecos), length(duals_mosek)) for(i in seq_along(duals_mosek)) expect_equal(duals_mosek[[i]], duals_ecos[[i]], tolerance = 1e-4) }) test_that("test MOSEK MI SOCP", { skip_on_cran() skip_if_not(MOSEK_AVAILABLE, "Skipping MOSEK test as it is not available.!") x <- Variable(3) y <- Variable(2, integer = TRUE) constraints <- list(p_norm(x, 2) <= y[1], p_norm(x, 2) <= y[2], x[1] + x[2] + 3 * x[3] >= 0.1, y <= 5) obj <- Minimize(3 * x[1] + 2 * x[2] + x[3] + y[1] + 2 * y[2]) prob <- Problem(obj, constraints) result <- solve(prob, solver = "MOSEK") expect_equal(result$getValue(y), as.matrix(c(1,1)), tolerance = TOL) }) test_that("test MOSEK LP solution selection", { skip_on_cran() skip_if_not(MOSEK_AVAILABLE, "Skipping MOSEK test as it is not available.!") x <- Variable(2) objective <- Minimize(-4 * x[1] - 5 * x[2]) constraints <- list(2 * x[1] + x[2] <= 3, x[1] + 2 * x[2] <= 3, x[1] >= 0, x[2] >= 0) prob <- Problem(objective, constraints) result <- solve(prob, solver = "MOSEK") expect_equal(result$value, -9, tolerance = TOL) expect_equal(result$getValue(x), as.matrix(c(1,1)), tolerance = 1e-5) })
is.bpairs <- function(y, family, trace, is.earth) { msg <- NULL is.bpairs <- FALSE is.nonneg <- TRUE is.binomial <- is.binomial(family) if(is.binomial) check.no.na.in.mat(y) if(is.binomial && NROW(y) > 1 && NCOL(y) == 2) { y1 <- y[, 1, drop=TRUE] y2 <- y[, 2, drop=TRUE] if(!(is.numeric(y1) || is.logical(y1)) || !(is.numeric(y2) || is.logical(y2))) { return(FALSE) } rowsums <- rowSums(y) is.int <- all((round(y1) == y1) & (round(y2) == y2)) is.nonneg <- all((y1 >= 0) & (y2 >= 0)) is.rowsums.greater.than.1 <- any(rowsums > 1) is.bpairs <- is.int && is.nonneg && is.rowsums.greater.than.1 msg <- bpairs.msg(is.bpairs, y, rowsums, is.earth, is.nonneg, is.int, is.rowsums.greater.than.1, trace) } if(is.binomial && !is.bpairs && (is.numeric(y) || is.logical(y)) && (!all(y >= 0 & y <= 1) || !is.nonneg)) { cat0("\nprint(head(y)):\n") print(head(y)) cat0("\n") stop0("Binomial response (see above): all values should be between 0 and 1, or a binomial pair", if(is.null(msg)) "" else paste0("\n ", msg)) } is.bpairs } bpairs.msg <- function(is.bpairs, y, rowsums, is.earth, is.nonneg, is.int, is.rowsums.greater.than.1, trace) { msg <- NULL if(!is.bpairs) { earth.msg <- if(!is.earth) "" else sprint("\nEarth will build two GLM models with responses \"%s\" and \"%s\"", colname(y, 1), colname(y, 2)) if(!is.int) { cat0("\nprint(head(y)):\n") print(head(y)) cat0("\n") msg <- "Response has two columns but is not a binomial pair because not all values are integers" printf("%s%s\n\n", msg, earth.msg) } else if(!is.nonneg) { msg <- "Response has two columns but is not a binomial pair because some values are negative" trace1(trace, "%s\n", msg) } else if(!is.rowsums.greater.than.1) { msg <- "Response has two columns but is not a binomial pair because no rows sum to greater than 1" trace1(trace, "%s%s\n\n", msg, earth.msg) } } else if(any(rowsums == 0)) trace1(trace, "Note: Both entries in row %d %sof the %s and %s response are zero\n", which(rowsums==0)[1], if(length(which(rowsums==0)) == 1) "" else "(and others) ", colname(y, 1), colname(y, 2)) msg } expand.bpairs <- function(...) { UseMethod("expand.bpairs") } expand.bpairs.formula <- function(formula=stop("no 'formula' argument"), data=NULL, sort=FALSE, ...) { stop.if.dots(...) call <- match.call(expand.dots=FALSE) imatch <- match(c("formula", "data"), names(call), 0) mf <- call[c(1, imatch)] Formula <- Formula::Formula(formula) mf[[1]] <- as.name("model.frame") mf$formula <- Formula mf$na.action <- na.pass mf <- eval.parent(mf) terms <- terms(Formula, data=data) varnames <- attr(terms, "term.labels") if(length(attr(Formula, "rhs")) > 1) stop0("invalid formula: too many terms on the right hand side") x <- model.part(Formula, data=mf, rhs=1) if(NCOL(x) == 0) stopf("expand.bpairs: the right side of the formula does not have any variables") x <- as.data.frame(x) if(length(attr(Formula, "lhs")) > 1) stop0("invalid formula: too many terms on the left hand side") y <- model.part(Formula, data=mf, lhs=1) if(NCOL(y[[1]]) > 1) y <- y[[1]] respname <- colnames(y)[1] if(is.null(respname) || length(respname) != 1 || nchar(respname) == 0) stop0("expand.bpairs: cannot get response from formula") if(NCOL(y) != 2) stopf("expand.bpairs: '%s' does not have two columns", respname) y <- as.data.frame(y) if(!is.bpairs(y, family="binomial", trace=1, is.earth=FALSE)) stopf("expand.bpairs: the left side of the formula is not a two-column matrix of binomial pairs") expand.bpairs.aux(x, y, sort) } expand.bpairs.default <- function(data = stop("no 'data' argument"), y = NULL, sort=FALSE, ...) { help.msg <- paste0( "The y argument should be one of:\n", "\n", " o Two column matrix or dataframe of binomial pairs.\n", "\n", " o Two-element numeric vector specifying the response columns in 'data'.\n", "\n", " o Two-element character vector specifying the response column names in 'data'.\n", " The full names must be used (partial matching isn't supported).") stop.if.dots(...) if(is.null(y)) stop0("expand.bpairs: no y argument\n\n", help.msg) stopifnot(is.vector(data) || is.matrix(data) || is.data.frame(data)) data.name <- trunc.deparse(substitute(data)) if(length(y) == 2 && is.numeric(y) && round(y[1]) == y[1] && round(y[2]) == y[2]) { ycolumns <- y check.index(ycolumns, "ycolumns", data, is.col.index=1, allow.negatives=FALSE) y <- data[, ycolumns, drop=FALSE] yarg.name <- sprint("%s[,c(%g,%g)]", data.name, ycolumns[1], ycolumns[2]) check.index(-ycolumns, "ycolumns", data, is.col.index=1, allow.negatives=TRUE) data <- data[, -ycolumns, drop=FALSE] if(ncol(data) < 1) stop0("expand.bpairs: x is empty after removing response columns") } else if(length(y) == 2 && is.character(y)) { ycolumns <- y check.index(ycolumns, "ycolumns", data, is.col.index=2, allow.negatives=FALSE) y <- data[, ycolumns, drop=FALSE] colnames <- colnames(data) i1 <- match(ycolumns[1], colnames) i2 <- match(ycolumns[2], colnames) if(length(i1) != 1 || length(i2) != 1 || anyNA(i1) || anyNA(i2)) stopf("expand.bpairs: cannot find '%s' or '%s' in colnames(data)", ycolumns[1], ycolumns[2]) yarg.name <- sprint("%s[,c(\"%s\",\"%s\")]", data.name, ycolumns[1], ycolumns[2]) ycolumns <- c(i1,i2) check.index(-ycolumns, "ycolumns", data, is.col.index=1, allow.negatives=TRUE) data <- data[, -ycolumns, drop=FALSE] if(ncol(data) < 1) stop0("expand.bpairs: x is empty after removing response columns") } else { yarg.name <- trunc.deparse(substitute(y)) if(NCOL(y) != 2 || NROW(y) < 2) stop0("expand.bpairs: bad y argument '", unquote(yarg.name), "'\n\n", help.msg) } data <- as.data.frame(data) y <- as.data.frame(y) if(!is.bpairs(y, family="binomial", trace=1, is.earth=FALSE)) stopf("expand.bpairs: %s is not a two-column matrix of binomial pairs", yarg.name) expand.bpairs.aux(data, y, sort) } expand.bpairs.aux <- function(x, y, sort) { sort <- check.boolean(sort) stopifnot(ncol(x) >= 1) if(nrow(x) != nrow(y)) stopf("expand.bpairs: x has %d row%s, but the response y has %d row%s", nrow(x), if(nrow(x)==1) "" else "s", nrow(y), if(nrow(y)==1) "" else "s") x <- possibly.delete.column(x, y, 1) x <- possibly.delete.column(x, y, 2) stopifnot(ncol(x) >= 1) colname.y1 <- colnames(y)[1] if(is.null(colname.y1) || nchar(colname.y1) == 0) colname.y1 <- "true" rowsums <- rowSums(y) rowsums[rowsums == 0] <- 1 n <- sum(rowsums) ylong <- logical(length=n) xlong <- x[FALSE, , drop=FALSE] rownames <- character(length=n) bpairs.index <- repl(0L, nrow(y)) i <- 1 for(ishort in 1:nrow(y)) { bpairs.index[ishort] <- as.integer(i) ntrue <- y[ishort, 1, drop=TRUE] nfalse <- y[ishort, 2, drop=TRUE] if(ntrue + nfalse == 0) nfalse <- 1 if(nfalse > 0) { i2 <- i + nfalse - 1 ylong[i:i2] <- FALSE xlong[i:i2,] <- x[ishort,] rownames[i:i2] <- sprint("row%d.%d", ishort, 1:(i2-i+1)) i <- i + nfalse } if(ntrue > 0) { i2 <- i + ntrue - 1 ylong[i:i2] <- TRUE xlong[i:i2,] <- x[ishort,] rownames[i:i2] <- sprint("row%d.%d", ishort, (nfalse+1):(nfalse+i2-i+1)) i <- i + ntrue } } ylong <- as.matrix(ylong) colnames(ylong) <- colname.y1 df <- data.frame(ylong, xlong) rownames(df) <- rownames if(sort) { stopifnot(ncol(df) >= 2) icol <- c(2:ncol(df), 1) df <- df[ do.call(order, df[,icol]), ] } else { attr(df, "bpairs.index") <- bpairs.index } attr(df, "ynames") <- colnames(y) df } possibly.delete.column <- function(x, y, icol) { stopifnot(is.data.frame(x) && is.data.frame(y)) stopifnot(icol >= 1 && icol <= 2 && ncol(y) == 2) colname.y <- colnames(y)[icol] if(!is.null(colname.y) && nchar(colname.y) > 0) { imatch <- match(colname.y, colnames(x), 0) if(length(imatch) > 1) stopf("multiple columns match '%s'", colname.y) if(imatch) { x[[imatch]] <- NULL } } x }
knitr::opts_chunk$set( collapse = TRUE, comment = " eval = FALSE ) knitr::include_graphics("images/capm_forecast.png") knitr::include_graphics("images/capm_smoothed.png") knitr::include_graphics("images/capm_filtered.png")
fnorm <- function(Y, mu, sigma){ classsize <- dim(mu)[2] samplesize <- dim(Y)[1] fnorm_value <- exp(-(matrix(Y,samplesize,classsize)-mu)^2/(2*sigma^2))/(sqrt(2*pi*sigma^2)) return(fnorm_value) }
options( prompt = "R> ", ctinue = "+ " ) library( "censReg" ) data( "Affairs", package = "AER" ) estResult <- censReg( affairs ~ age + yearsmarried + religiousness + occupation + rating, data = Affairs ) summary( estResult ) estResultMinus <- censReg( I( - affairs ) ~ age + yearsmarried + religiousness + occupation + rating, left = -Inf, right = 0, data = Affairs ) cbind( coef( estResult ), coef( estResultMinus ) ) set.seed( 123 ) pData <- data.frame( id = rep( paste( "F", 1:15, sep = "_" ), each = 4 ), time = rep( 1981:1984, 15 ) ) pData$mu <- rep( rnorm( 15 ), each = 4 ) pData$x1 <- rnorm( 60 ) pData$x2 <- runif( 60 ) pData$ys <- -1 + pData$mu + 2 * pData$x1 + 3 * pData$x2 + rnorm( 60 ) pData$y <- ifelse( pData$ys > 0, pData$ys, 0 ) library( plm ) pData <- pdata.frame( pData, c( "id", "time" ) ) system.time( panelResult <- censReg( y ~ x1 + x2, data = pData, method = "BHHH" ) ) summary( panelResult ) nGHQ <- 2^(2:6) times <- numeric( length( nGHQ ) ) results <- list() for( i in 1:length (nGHQ ) ) { times[i] <- system.time( results[[i]] <- censReg( y ~ x1 + x2, data = pData, method = "BHHH", nGHQ = nGHQ[i] ) )[1] } names(results)<-nGHQ round( rbind(sapply( results, coef ),times),4)
library(shiny) choices <- c("Select All", "choice 1", "choice 2", "choice 3") ui = fluidPage( h5("Demo example - Adding 'select All' option to the selectinput to select all the choices at once using updateSelectInput(). "), hr(), selectInput("myselect", "Select box", choices=choices, multiple = TRUE, selected = "choice 1"), verbatimTextOutput("selected") ) server = function (input, output, session) { observe({ if("Select All" %in% input$myselect) selected_choices=choices[-1] else selected_choices=input$myselect updateSelectInput(session, "myselect", selected = selected_choices) }) output$selected <- renderText({ paste(input$myselect, collapse = ",") }) } shinyApp(ui=ui, server=server)
na_values <- function(x) { UseMethod("na_values") } na_values.default <- function(x) { NULL } na_values.haven_labelled_spss <- function(x) { attr(x, "na_values", exact = TRUE) } na_values.data.frame <- function(x) { lapply(x, na_values) } `na_values<-` <- function(x, value) { UseMethod("na_values<-") } `na_values<-.default` <- function(x, value) { if (!is.null(value)) x <- labelled_spss(x, val_labels(x), na_values = value, na_range = attr(x, "na_range"), label = var_label(x)) x } `na_values<-.factor` <- function(x, value) { if (!is.null(value)) stop("`na_values()` cannot be applied to factors.") x %>% remove_attributes("na_values") } `na_values<-.haven_labelled` <- function(x, value) { if (is.null(value)) { attr(x, "na_values") <- NULL if (is.null(attr(x, "na_range"))) { x <- labelled(x, val_labels(x), label = var_label(x)) } } else { x <- labelled_spss(x, val_labels(x), na_values = value, na_range = attr(x, "na_range"), label = var_label(x)) } x } `na_values<-.data.frame` <- function(x, value) { if (!is.list(value)) { temp <- as.list(rep(1, ncol(x))) names(temp) <- names(x) value <- lapply(temp, function(x) { x <- value }) } if (!all(names(value) %in% names(x))) stop("some variables not found in x") for (var in names(value)) if (!is.null(value[[var]])) { if (mode(x[[var]]) != mode(value[[var]])) stop("`x` and `value` must be same type", call. = FALSE, domain = "R-labelled") if (typeof(x[[var]]) != typeof(value[[var]])) mode(value[[var]]) <- typeof(x[[var]]) } for (var in names(value)) na_values(x[[var]]) <- value[[var]] x } na_range <- function(x) { UseMethod("na_range") } na_range.default <- function(x) { NULL } na_range.haven_labelled_spss <- function(x) { attr(x, "na_range", exact = TRUE) } na_range.data.frame <- function(x) { lapply(x, na_range) } `na_range<-` <- function(x, value) { UseMethod("na_range<-") } `na_range<-.default` <- function(x, value) { if (!is.null(value)) x <- labelled_spss(x, val_labels(x), na_values = attr(x, "na_values"), na_range = value, label = var_label(x)) x } `na_range<-.factor` <- function(x, value) { if (!is.null(value)) stop("`na_range()` cannot be applied to factors.") x %>% remove_attributes("na_range") } `na_range<-.haven_labelled` <- function(x, value) { if (is.null(value)) { attr(x, "na_range") <- NULL if (is.null(attr(x, "na_values"))) { x <- labelled(x, val_labels(x), label = var_label(x)) } } else { x <- labelled_spss(x, val_labels(x), na_values = attr(x, "na_values"), na_range = value, label = var_label(x)) } x } `na_range<-.data.frame` <- function(x, value) { if (!is.list(value)) { temp <- as.list(rep(1, ncol(x))) names(temp) <- names(x) value <- lapply(temp, function(x) { x <- value }) } if (!all(names(value) %in% names(x))) stop("some variables not found in x") for (var in names(value)) if (!is.null(value[[var]])) { if (mode(x[[var]]) != mode(value[[var]])) stop("`x` and `value` must be same type", call. = FALSE, domain = "R-labelled") if (typeof(x[[var]]) != typeof(value[[var]])) mode(value[[var]]) <- typeof(x[[var]]) } for (var in names(value)) na_range(x[[var]]) <- value[[var]] x } set_na_values <- function(.data, ..., .values = NA, .strict = TRUE) { if (!identical(.values, NA)) { if (!.strict) .values <- .values[intersect(names(.values), names(.data))] na_values(.data) <- .values } values <- rlang::dots_list(...) if (.strict & !all(names(values) %in% names(.data))) stop("some variables not found in .data") for (v in intersect(names(values), names(.data))) na_values(.data[[v]]) <- values[[v]] .data } set_na_range <- function(.data, ..., .values = NA, .strict = TRUE) { if (!identical(.values, NA)) { if (!.strict) .values <- .values[intersect(names(.values), names(.data))] na_range(.data) <- .values } values <- rlang::dots_list(...) if (.strict & !all(names(values) %in% names(.data))) stop("some variables not found in .data") for (v in intersect(names(values), names(.data))) na_range(.data[[v]]) <- values[[v]] .data } test_if_user_na <- function(val, na_values = NULL, na_range = NULL) { if (inherits(val, "haven_labelled")) val <- unclass(val) miss <- rep.int(FALSE, length(val)) if (!is.null(na_values)) { miss <- miss | val %in% na_values } if (!is.null(na_range) & is.numeric(val)) { miss <- miss | (val >= na_range[1] & val <= na_range[2] & !is.na(val)) } miss } is_user_na <- function(x) { test_if_user_na(x, na_values(x), na_range(x)) } is_regular_na <- function(x) { is.na(x) & !is_user_na(x) & !is_tagged_na(x) } user_na_to_na <- function(x) { UseMethod("user_na_to_na") } user_na_to_regular_na <- user_na_to_na user_na_to_na.default <- function(x) { x } user_na_to_na.haven_labelled_spss <- function(x) { remove_user_na(x, user_na_to_na = TRUE) } user_na_to_na.data.frame <- function(x) { x[] <- lapply(x, user_na_to_na) x } user_na_to_tagged_na <- function(x) { UseMethod("user_na_to_tagged_na") } user_na_to_tagged_na.default <- function(x) { x } user_na_to_tagged_na.haven_labelled_spss <- function(x) { remove_user_na(x, user_na_to_tagged_na = TRUE) } user_na_to_tagged_na.data.frame <- function(x) { x[] <- lapply(x, user_na_to_tagged_na) x }
ptree_PCM <- function(info, item, params, X, cex.lines, cex.main, cex.branches, cex.coefs, title){ n_levels <- length(unique(info[,"level"])) n_splits <- nrow(info) hilfspunkte <- list() hilfspunkte[[1]] <- matrix(NA,nrow=2^n_levels,ncol=2) hilfspunkte[[1]][,1] <- 2^n_levels hilfspunkte[[1]][,2] <- rep(n_levels+1,2^n_levels) steps <- 2^((n_levels:1-1)) for(i in 1:n_levels){ hilfspunkte[[i+1]] <- hilfspunkte[[i]] hilfspunkte[[i+1]][,2] <- rep(n_levels+1-i,2^n_levels) help <- c(-steps[i],steps[i]) help1 <- rep(help,each=steps[i]) help2 <- rep(help1,length=2^n_levels) hilfspunkte[[i+1]][,1] <- hilfspunkte[[i]][,1]+help2 which_knots <- info[info[,"level"]==i,"node"] help3 <- seq(1,2^n_levels) help4 <- split(help3,rep(1:2^(i-1),each=2^n_levels/2^(i-1))) help5 <- unlist(lapply(which_knots, function(j) help4[[j]])) hilfspunkte[[i+1]][-help5,] <- hilfspunkte[[i]][-help5,] } plot.new() plot.window(ylim=c(0.5,n_levels+1),xlim=c(0,2^(n_levels+1))) for(j in length(hilfspunkte):2){ for(i in 1:(2^n_levels)){ lines(c(hilfspunkte[[j-1]][i,1],hilfspunkte[[j]][i,1]),c(hilfspunkte[[j-1]][i,2],hilfspunkte[[j]][i,2]), lwd=cex.lines) } } if(is.null(title)){ title <- paste("Item",item) } title(title,cex.main=cex.main) for(i in 1:nrow(info)){ help4 <- split(help3,rep(1:2^(info[i,"level"]-1),each=2^n_levels/2^(info[i,"level"]-1)))[[info[i,"node"]]] point_var <- unique(hilfspunkte[[info[i,"level"]]][help4,]) points(point_var[1],point_var[2],cex=cex.lines-1,pch=19) point_left <- c(point_var[1]-steps[info[i,"level"]],point_var[2]-0.5) point_right <- c(point_var[1]+steps[info[i,"level"]],point_var[2]-0.5) var <- info[i,"variable"] thres <- info[i,"threshold"] sort_values <- unique(sort(X[,var])) if(thres==min(sort_values)){ text(point_left[1],point_left[2],paste0(var,"=",round(thres,2)),cex=cex.branches,adj=c(1,0)) } else{ text(point_left[1],point_left[2],paste0(var,"<=",round(thres,2)),cex=cex.branches,adj=c(1,0)) } if(thres==max(sort_values[-length(sort_values)])){ text(point_right[1],point_right[2],paste0(var,"=",round(max(sort_values),2)),cex=cex.branches,adj=c(0,0)) } else{ text(point_right[1],point_right[2],paste0(var,">",round(thres,2)),cex=cex.branches,adj=c(0,0)) } } params <- matrix(params,byrow=TRUE,nrow=n_splits+1) yscale <- c(min(params)-1,max(params)+1) if(min(params) < -4){ yscale[1] <- -4 } if(max(params) > 4){ yscale[2] <- 4 } vps <- baseViewports() pushViewport(vps$plot) points_params <- unique(hilfspunkte[[n_levels+1]]) for(i in 1:nrow(points_params)){ window <- viewport(x=points_params[i,1],y=points_params[i,2], width=1,height=0.5, just=c("center","top"), xscale=c(0,ncol(params)+1),yscale=yscale, default.units="native") pushViewport(window) grid.rect() if(any(params[i,] < -4)){ params[i,which(params[i,]< -4)] <- -4 } if(any(params[i,] > 4)){ params[i,which(params[i,]> 4)] <- 4 } for(j in 1:ncol(params)){ if(-4 < params[i,j] & params[i,j] < 4){ grid.points(j,params[i,j],pch=19,gp=gpar(cex=cex.coefs)) } if(j < ncol(params)){ grid.lines(c(j,j+1),params[i,(j:(j+1))],default.units="native",gp=gpar(lwd=cex.coefs*3)) } } grid.yaxis(gp=gpar(cex=cex.branches)) upViewport() } }
DIMTESTS <- function(data, tests=c('EMPKC', 'HULL', 'RAWPAR'), corkind='pearson', Ncases=NULL, HULL_method='PAF', HULL_gof='CAF', HULL_cor_method='pearson', CD_cor_method='pearson', display = NULL) { cordat <- setupcormat(data, corkind=corkind, Ncases=Ncases) cormat <- cordat$cormat ctype <- cordat$ctype Ncases <- cordat$Ncases if (is.null(display)) display = 2 verbose <- ifelse(display == 2, TRUE, FALSE) dimtests <- matrix(-9999,length(tests),1) for (lupe in 1:length(tests)) { if (tests[lupe] == 'CD') { dimtests[lupe,1] <- EFAtools::CD(x=data, n_factors_max = NA, N_pop = 10000, N_samples = 500, alpha = 0.3, cor_method = c("pearson", "spearman", "kendall"), max_iter = 50)$n_factors if (verbose == TRUE) { message('\n\nCOMPARISON DATA') message('\nThe number of factors according to the Comparison Data test (from EFAtools) = ', dimtests[lupe,1], '\n') } } if (tests[lupe] == 'EMPKC') dimtests[lupe,1] <- EMPKC(cormat, Ncases=Ncases, verbose=verbose)$NfactorsEMPKC if (tests[lupe] == 'HULL') { hullOutput <- EFAtools::HULL(x=cormat, N = Ncases, method = HULL_method, gof = HULL_gof, eigen_type = c("PCA"), cor_method = HULL_cor_method, n_datasets = 500, percent = 50, decision_rule = c("means") ) if (HULL_method == 'PAF') dimtests[lupe,1] <- hullOutput$n_fac_CAF if ( (HULL_method == 'ML' | HULL_method == 'ULS') & HULL_gof=='CFI') dimtests[lupe,1] <- hullOutput$n_fac_CFI if ( (HULL_method == 'ML' | HULL_method == 'ULS') & HULL_gof=='CAF') dimtests[lupe,1] <- hullOutput$n_fac_CAF if ( (HULL_method == 'ML' | HULL_method == 'ULS') & HULL_gof=='RMSEA') dimtests[lupe,1] <- hullOutput$n_fac_RMSEA if (verbose == TRUE) { message('\n\nHULL METHOD') message('\nThe number of factors according to the Hull method test (from EFAtools) = ', dimtests[lupe,1], '\n') } } if (tests[lupe] == 'MAP') dimtests[lupe,1] <- MAP(cormat, Ncases=Ncases, verbose=verbose)$NfactorsMAP if (tests[lupe] == 'NEVALSGT1') dimtests[lupe,1] <- NEVALSGT1(cormat, Ncases=Ncases, verbose=verbose)$NfactorsNEVALSGT1 if (tests[lupe] == 'RAWPAR') dimtests[lupe,1] <- RAWPAR(cormat, Ncases=Ncases, verbose=verbose)$NfactorsPA if (tests[lupe] == 'SALIENT') dimtests[lupe,1] <- SALIENT(cormat, Ncases=Ncases, verbose=verbose)$NfactorsSALIENT if (tests[lupe] == 'SESCREE') dimtests[lupe,1] <- SESCREE(cormat, Ncases=Ncases, verbose=verbose)$NfactorsSESCREE if (tests[lupe] == 'SMT') dimtests[lupe,1] <- SMT(cormat, Ncases=Ncases, verbose=verbose)$NfactorsSMT } rownames(dimtests) <- tests colnames(dimtests) <- ' if (display > 0) { message('\n\nDIMTESTS results:\n') print(dimtests) } dimtestOutput <- list(dimtests=dimtests, NfactorsDIMTESTS = dimtests[1,1]) }
library("stsm") library("KFKSDS") library("numDeriv") m <- stsm::stsm.model(model = "llm+seas", y = JohnsonJohnson, pars = c("var1" = 2, "var2" = 15, "var3" = 30)) ss <- stsm::char2numeric(m) m@y[10] <- NA m@y[45] <- NA kf <- KF(m@y, ss, convergence = c(0.001, length(m@y))) kf$convit a <- KS(m@y, ss, kf) kf <- KF(m@y, ss, convergence = c(0.001, 10)) kf$convit b <- KS(m@y, ss, kf) kfd <- KF.deriv(m@y, ss) ksd <- KS.deriv(m@y, ss, kfd) all.equal(a$r, b$r) all.equal(a$N, b$N) all.equal(a$ahat, b$ahat) all.equal(a$varahat, b$varahat) all.equal(a$r, ksd$r) all.equal(a$N, ksd$N) all.equal(a$ahat, ksd$ahat) all.equal(a$varahat, ksd$varahat) kf <- KF(m@y, ss, convergence = c(0.001, length(m@y))) system.time(for(i in seq_len(10)) a <- KS(m@y, ss, kf)) kf <- KF(m@y, ss, convergence = c(0.001, 10)) system.time(for(i in seq_len(10)) b <- KS(m@y, ss, kf)) fcn <- function(x, model, type, i, j) { m <- stsm::set.pars(model, x) ss <- stsm::char2numeric(m) kf <- KF(m@y, ss) ks <- KS(m@y, ss, kf) switch(type, "ahat" = sum(ks$ahat[,i], na.rm = TRUE), "varahat" = sum(ks$varahat[i,j,], na.rm = TRUE), "r" = sum(ks$r[,i], na.rm = TRUE), "N" = sum(ks$N[i,j,], na.rm = TRUE)) } for (i in 1:4) { d <- numDeriv::grad(func = fcn, x = m@pars, model = m, type = "ahat", i = i) print(all.equal(d, colSums(ksd$dahat[,i,]), check.attributes = FALSE)) } for (i in 1:4) { d <- numDeriv::grad(func = fcn, x = m@pars, model = m, type = "r", i = i) print(all.equal(d, colSums(ksd$dr[,i,]), check.attributes = FALSE)) } for (i in 1:4) for (j in 1:4) { d <- numDeriv::grad(func = fcn, x = m@pars, model = m, type = "varahat", i = i, j = j) print(all.equal(d, colSums(ksd$dvarahat[,i,j,]), check.attributes = FALSE)) } for (i in 1:4) for (j in 1:4) { d <- numDeriv::grad(func = fcn, x = m@pars, model = m, type = "N", i = i, j = j) print(all.equal(d, colSums(ksd$dN[,i,j,]), check.attributes = FALSE)) }
util_equalizer <- function(n,elas,t1,t2,Tax,zstar) { if (n < 0 | zstar < 0) { stop("Ability and zstar need to be non-negative") } z <- n*((1-t1)^elas) if (z > zstar) { z <- n*((1-t2)^elas) } U_I <- util_calc(z,n,elas,t1,t2,Tax,zstar) U_N <- util_calc(zstar,n,elas,t1,t2,Tax,zstar) return(abs(U_I-U_N)) }
add_install_instructions <- function(base_dockerfile, pkgs, platform, soft, offline, versioned_libs, versioned_packages, filter_baseimage_pkgs, filter_deps_by_image = FALSE) { if (is.null(pkgs) || nrow(pkgs) < 1) { futile.logger::flog.debug("Input packages is %s - not adding any install instructions", toString(pkgs)) return(base_dockerfile) } package_reqs <- character(0) image_name <- base_dockerfile@image@image if (filter_baseimage_pkgs && !versioned_packages) { image <- docker_arguments(base_dockerfile@image) no_log <- capture.output(available_pkgs <- get_installed_packages(image = image)$pkg) futile.logger::flog.debug("Detected packages: %s", toString(no_log)) cran_packages <- pkgs[stringr::str_detect(string = pkgs$source, pattern = "CRAN"),] skipable <- cran_packages$name %in% available_pkgs skipped_str <- toString(stringr::str_sort((as.character(cran_packages[skipable,]$name)))) futile.logger::flog.info("Skipping packages for image %s (packages are unversioned): %s", image, skipped_str) if (any(skipable)) addInstruction(base_dockerfile) <- Comment(text = paste0("CRAN packages skipped because they are in the base image: ", skipped_str)) pkgs <- rbind(cran_packages[!skipable,], pkgs[pkgs$source != "CRAN",]) } if (nrow(pkgs[pkgs$source == "github",]) > 0 && !"remotes" %in% pkgs$name) { pkgs <- rbind(pkgs, remotes = data.frame(name = "remotes", version = "1.1.1", source = "CRAN")) futile.logger::flog.debug("Added package 'remotes' to package list to be able to install from GitHub") } if (is.null(platform)) { warning("Platform could not be detected, proceed at own risk.") } else if (!isTRUE(platform %in% .supported_platforms)) { warning("The determined platform '", platform, "' is currently not supported for handling system dependencies. Therefore, the created manifests might not work.") } if (nrow(pkgs) > 0) { package_reqs <- sapply(X = stringr::str_sort(as.character(unlist(pkgs$name))), FUN = .find_system_dependencies, platform = platform, soft = soft, offline = offline) package_reqs <- unlist(package_reqs) if (filter_deps_by_image) { skipable <- .skipable_deps(image_name) package_reqs <- package_reqs[!package_reqs %in% skipable] futile.logger::flog.info("Skipping deps for image %s: %s", image_name, toString(skipable)) } package_reqs <- stringr::str_sort(unique(package_reqs)) if (length(package_reqs) > 0) { if (platform == .debian_platform) { commands <- "export DEBIAN_FRONTEND=noninteractive; apt-get -y update" install_command <- paste("apt-get install -y", paste(package_reqs, collapse = " \\\n\t")) commands <- append(commands, install_command) addInstruction(base_dockerfile) <- Run_shell(commands) } else { warning("Platform ", platform, " not supported, cannot add installation commands for system requirements.") } } else { futile.logger::flog.debug("No system requirements found that must be installed") } if (versioned_packages) { futile.logger::flog.info("Versioned packages enabled, installing 'versions'") addInstruction(base_dockerfile) <- Run("install2.r", "versions") } pkgs_cran <- pkgs[stringr::str_detect(string = pkgs$source, pattern = "CRAN"),] if (nrow(pkgs_cran) > 0) { if (versioned_packages) { futile.logger::flog.info("Adding versioned CRAN packages: %s", toString(pkgs_cran$name)) addInstruction(base_dockerfile) <- versioned_install_instructions(pkgs_cran) } else { cran_packages <- stringr::str_sort(as.character(unlist(pkgs_cran$name))) futile.logger::flog.info("Adding CRAN packages: %s", toString(cran_packages)) addInstruction(base_dockerfile) <- Run("install2.r", cran_packages) } } else futile.logger::flog.debug("No CRAN packages to add.") pkgs_bioc <- pkgs[stringr::str_detect(string = pkgs$source, pattern = "Bioconductor"),] if (nrow(pkgs_bioc) > 0) { if (versioned_packages) { futile.logger::flog.warn("Adding versioned Bioconductor packages not supported: %s", toString(pkgs_bioc$name)) } bioc_packages <- stringr::str_sort(as.character(unlist(pkgs_bioc$name))) futile.logger::flog.info("Adding Bioconductor packages: %s", toString(bioc_packages)) repos = as.character(BiocManager::repositories()) addInstruction(base_dockerfile) <- Run("install2.r", params = c(sprintf("-r %s -r %s -r %s -r %s", repos[1], repos[2], repos[3], repos[4]), bioc_packages)) } else futile.logger::flog.debug("No Bioconductor packages to add.") pkgs_gh <- pkgs[stringr::str_detect(string = pkgs$source, stringr::regex("GitHub", ignore_case = TRUE)),] if (nrow(pkgs_gh) > 0) { github_packages <- stringr::str_sort(as.character(unlist(pkgs_gh$version))) futile.logger::flog.info("Adding GitHub packages: %s", toString(github_packages)) addInstruction(base_dockerfile) <- Run("installGithub.r", github_packages) } } else { futile.logger::flog.debug("No packages found that must be installed") } return(base_dockerfile) } versioned_install_instructions <- function(pkgs) { pkgs_sorted <- pkgs[order(pkgs$name),] installInstructions <- apply(X = pkgs_sorted, FUN = function(pkg) { ifelse(!is.na(pkg["version"]), paste0('versions::install.versions(\'', pkg["name"], '\', \'' , pkg["version"], '\')'), NA) }, MARGIN = 1) installInstructions <- installInstructions[!is.na(installInstructions)] params <- c(rbind(rep("-e", length(installInstructions)), installInstructions)) instructions <- list(Run(exec = "Rscript", params = params)) if (any(is.na(pkgs_sorted$version))) { unversioned <- pkgs_sorted[is.na(pkgs_sorted$version),] unversioned <- stringr::str_sort(as.character(unlist(unversioned$name))) futile.logger::flog.warn("No version information found for packages: %s", toString(unversioned)) instructions <- c(Run("install2.r", unversioned), instructions) } return(instructions) } .find_system_dependencies <- function(package, platform, soft = TRUE, offline = FALSE, package_version = as.character(utils::packageVersion(package))) { method = NA if (offline) method = "sysreq-package" else method = "sysreq-api" .dependencies <- NA futile.logger::flog.info("Going online? %s ... to retrieve system dependencies (%s)", !offline, method) futile.logger::flog.debug("Retrieving sysreqs for %s packages and platform %s: %s", length(package), platform, toString(package)) if (method == "sysreq-package") { .dependencies <- .find_by_sysreqs_pkg( package = package, package_version = package_version, platform = platform, soft = soft ) } if (method == "sysreq-api") { .dependencies <- .find_by_sysreqs_api(package = package, platform = platform) if (length(.dependencies) > 0) { .dependencies <- unique(unlist(.dependencies, use.names = FALSE)) .dependencies <- unlist(lapply(.dependencies, function(x) { unlist(strsplit(x, split = " ")) })) } } futile.logger::flog.debug("Found %s system dependencies: %s", length(.dependencies), toString(.dependencies)) return(.dependencies) } .find_by_sysreqs_pkg <- function(package, platform, soft = TRUE, package_version, localFirst = TRUE) { if (length(package) > 1) { out <- mapply(function(pkg, version) { .find_by_sysreqs_pkg(pkg, platform, soft, version, localFirst) }, pkg = package, version = package_version) return(out) } sysreqs <- character(0) if (localFirst) { futile.logger::flog.info( "Trying to determine system requirements for package '%s' from the local DESCRIPTION file", package ) path <- find.package(package, quiet = TRUE) if (is.null(path) || length(path) == 0 || utils::packageVersion(package) != package_version) { futile.logger::flog.warn( "No matching package DESCRIPTION found locally for package '", package, "', version '", package_version, "' ." ) } else{ sysreqs <- NA if (is.null(platform)) { futile.logger::flog.warn("Platform could not be determined, possibly because of unknown base image.", " Using '%s'", sysreqs::current_platform()) sysreqs <- sysreqs::sysreqs(file.path(path, "DESCRIPTION"), soft = soft) } else { sysreqs <- sysreqs::sysreqs(file.path(path, "DESCRIPTION"), platform = platform, soft = soft) } return(sysreqs) } } futile.logger::flog.info("Trying to determine system requirements for '%s' from the DESCRIPTION file on CRAN", package) con <- url(paste0("https://CRAN.R-project.org/package=", package, "/DESCRIPTION")) temp <- tempfile() success <- TRUE tryCatch({ desc <- readLines(con) writeLines(desc, temp) sysreqs <- sysreqs::sysreqs(temp, platform = platform, soft = soft) }, error = function(e) { success <- FALSE futile.logger::flog.debug("Error requesting system requirements from DESCRIPTION file on CRAN: %s", toString(e)) }, finally = { unlink(temp) close(con) }) if (!success) { warning("Could not package DESCRIPTION for package '", package, ", on CRAN. containerit failed to determine system requirements.") return(NULL) } else { return(sysreqs) } } .find_by_sysreqs_api <- function(package, platform) { if (length(package) > 0) { package = paste(package, collapse = ",") } futile.logger::flog.info("Trying to determine system requirements for the package(s) '%s' from sysreqs online DB", package) .url <- paste0("https://sysreqs.r-hub.io/pkg/", package, "/", platform) con <- url(.url) futile.logger::flog.debug("Accessing '%s'", .url) success <- TRUE desc <- NULL tryCatch({ desc <- readLines(con, warn = FALSE) futile.logger::flog.debug("Response: %s", toString(desc)) parser <- rjson::newJSONParser() parser$addData(desc) desc <- as.character(parser$getObject()) desc <- desc[!desc == "NULL"] }, error = function(e) { success <- FALSE futile.logger::flog.debug("Error requesting package info from sysreqs online DB: %s", toString(e)) }, finally = close(con)) if (!success) { warning("Containerit failed to determine system requriements for package ", package, "using sysreq online API") } futile.logger::flog.debug("Dependencies info from sysreqs online DB:\n%s", toString(desc)) return(desc) } getGitHubRef = function(pkg, pkgs = c(sessionInfo()$otherPkgs, sessionInfo()$loadedOnly)) { ref <- NA_character_ if (!is.null(pkgs[[pkg]]$GithubRepo)) repo <- pkgs[[pkg]]$GithubRepo else repo <- pkgs[[pkg]]$RemoteRepo if (!is.null(pkgs[[pkg]]$GithubUsername)) uname <- pkgs[[pkg]]$GithubUsername else uname <- pkgs[[pkg]]$RemoteUsername if (!is.null(pkgs[[pkg]]$GithubSHA1)) ghr <- pkgs[[pkg]]$GithubSHA1 else ghr <- pkgs[[pkg]]$RemoteSha if (any(sapply(X = c(repo, uname, ghr), FUN = is.null))) { futile.logger::flog.warn("Exact reference of GitHub package %s could not be determined from session info: %s %s %s", pkg, repo, uname, ghr) } else { ref = paste0(uname, "/", repo, "@", ghr) } if (is.na(ref)) { if (requireNamespace(pkg)) si_devtools <- devtools::session_info() ref_devtools <- si_devtools$packages$source[si_devtools$packages$package == pkg] futile.logger::flog.debug("Looking for references with devtools for package %s", ref_devtools) if (stringr::str_detect(ref_devtools, "(?i)^GitHub \\(.*/.*@| ref_devtools <- stringr::str_replace(ref_devtools, "(?i)^GitHub \\(", replacement = "") ref_devtools <- stringr::str_replace(ref_devtools, "\\)$", replacement = "") futile.logger::flog.debug("GitHub reference for %s found with devtools: %s", pkg, ref_devtools) ref <- ref_devtools } else futile.logger::flog.warn("GitHub ref is unknown, but package %s is not available locally, no fallback.", pkg) } return(ref) }
if(exists(".orig.enc")) options(encoding = .orig.enc) dir.create("plots", showWarnings=F) options(width=100, continue="+ ") options(useFancyQuotes = FALSE) set.seed(12345) pdf.options(onefile=F,family="Times",pointsize=12) x <- runif(1000, min = 0, max = 100) xf <- cut(x, breaks = c(-1, 20, 50, 80, 101), labels = c("cold", "luke", "warm", "hot")) xfdummies <- contrasts(xf, contrasts = FALSE )[xf,] colnames(xfdummies) <- paste("xf", c("cold", "luke", "warm", "hot"), sep="") rownames(xfdummies) <- names(x) dat <- data.frame(x, xf, xfdummies) head(dat)
tmat <- rbind(c(NA,1,2),c(NA,NA,NA),c(NA,NA,NA)) set.seed(1) bosms3$x <- rnorm(nrow(bosms3)) bweic <- bweim <- vector(2, mode="list") for (i in 1:2) { bweic[[i]] <- flexsurvreg(Surv(years, status) ~ x, subset=(trans==i), data = bosms3, dist = "weibull") bweim[[i]] <- flexsurvreg(Surv(years, status) ~ 1, subset=(trans==i), data = bosms3, dist = "weibull") } weic <- fmsm("Well-BOS"=bweic[[1]], "Well-Death"=bweic[[2]], trans=tmat) weim <- fmsm("Well-BOS"=bweim[[1]], "Well-Death"=bweim[[2]], trans=tmat) nd <- data.frame(x=c(0,0.01,-10,10)) test_that("pfinal_fmsm", { expect_equal(pfinal_fmsm(weim, fromstate="State 1")$val, c(0.717737627151196, 0.282262372848804)) expect_error(pfinal_fmsm(weim, fromstate="State 2"), "No destination states") expect_equal(pfinal_fmsm(weic, newdata=nd, fromstate="State 1")$val[1:2], c(0.715828147070156, 0.715333178039627)) expect_true(is.numeric(pfinal_fmsm(weim, fromstate="State 1", B=3)$lower)) expect_equal(pfinal_fmsm(weim, fromstate="State 1", maxt=100000)$val, pfinal_fmsm(weim, fromstate="State 1", maxt=10000000)$val, tol=1e-06) expect_error(pfinal_fmsm(weim, fromstate="1"), "not found") }) test_that("simfinal_fmsm",{ set.seed(1) sm <- simfinal_fmsm(weim) expect_equal(sm$val[sm$quantity=="prob"], c(0.71758, 0.28242)) expect_equal(sm$val[sm$quantity=="50%"], c(2.25618202292384, 4.67377970752349)) sm2 <- simfinal_fmsm(weim, probs=c(0.25, 0.75)) sm3 <- simfinal_fmsm(weim, probs=c(0.25, 0.75), t=10000) expect_equal(sm2$val[sm$quantity=="prob"], sm3$val[sm$quantity=="prob"], tol=0.1) sm2 <- simfinal_fmsm(weim, probs=c(0.25, 0.75), M=1000, B=10) expect_error(simfinal_fmsm(weic), "`newdata` should be supplied") nd <- data.frame(x=c(0, 0.01)) simfinal_fmsm(weic, newdata=nd) simfinal_fmsm(weic, newdata=nd, M=1000, B=10) })
"checkPackageVersion" <- function (pkg, ver) { RevoIOQ:::testPackageVersion(pkg, ver, lib.loc = .Library) } if (length(grep("Enterprise", Revo.version$version.string)) > 0){ if (!RevoIOQ:::isComputeNode()){ "test.revoide.pkgXMLBuilder.version" <- function() checkTrue("checkPackageVersion"(pkg = "pkgXMLBuilder", ver = "1.0")) "test.revoide.revoIpe.version" <- function() checkTrue("checkPackageVersion"(pkg = "revoIpe", ver = "1.1")) "test.revoide.XML.version" <- function() checkTrue("checkPackageVersion"(pkg = "XML", ver = "3.98-1.1")) } }
LASfile <- system.file("extdata", "example.laz", package = "rlas") las <- example ctg <- suppressMessages(readLAScatalog(c(LASfile, LASfile))) opt_progress(ctg) <- FALSE test_that("cloud_metrics works with LAS", { x = cloud_metrics(las, mean(Z)) expect_equal(x, 975.9, tol = 0.1) x = cloud_metrics(las, ~mean(Z)) expect_equal(x, 975.9, tol = 0.1) x = cloud_metrics(las, ~list(mean(Z), max(Z))) expect_is(x, "list") expect_equal(length(x), 2L) expect_equal(x[[1]], 975.9, tol = 0.1) expect_equal(x[[2]], 978.3, tol = 0.1) }) test_that("cloud_metrics works with catalog_apply", { x = catalog_apply(ctg, cloud_metrics, func = ~mean(Z)) expect_is(x, "list") expect_equal(length(x), 2L) expect_equal(x[[1]], 975.9, tol = 0.1) expect_equal(x[[2]], 975.9, tol = 0.1) x = catalog_apply(ctg, cloud_metrics, func = ~list(mean(Z), max(Z))) expect_is(x, "list") expect_equal(length(x), 2L) expect_is(x[[1]], "list") expect_is(x[[2]], "list") })
NULL setValidity( Class = "SparreAndersen", method = function(object) { initial_capital <- object@initial_capital premium_rate <- object@premium_rate claim_interarrival_generator <- object@claim_interarrival_generator claim_interarrival_parameters <- object@claim_interarrival_parameters claim_size_parameters <- object@claim_size_parameters claim_size_generator <- object@claim_size_generator errors <- character(0) if(isFALSE(length(initial_capital) == 1) || is.na(initial_capital) || initial_capital < 0) errors <- c(errors, paste0("initial_capital must be a numeric length 1", " non-negative vector containing no missing values.")) if(isFALSE(length(premium_rate) == 1) || is.na(premium_rate) || premium_rate < 0) errors <- c(errors, paste0("premium_rate must be a numeric length 1", " non-negative vector containing no missing values.")) if( isFALSE( all( names(claim_interarrival_parameters) %in% names(formals(claim_interarrival_generator)) ) ) ) errors <- c(errors, paste0("claim_interarrival_parameters must have the same", " names as formal argument of", " claim_interarrival_generator")) if( isFALSE( all( names(claim_size_parameters) %in% names(formals(claim_size_generator)) ) ) ) errors <- c(errors, paste0("claim_size_parameters must have the same names as", " formal argument of claim_size_generator.")) if(length(errors) == 0) { TRUE } else { errors } } ) SparreAndersen <- function(initial_capital = NULL, premium_rate = NULL, claim_interarrival_generator = NULL, claim_interarrival_parameters = NULL, claim_size_generator = NULL, claim_size_parameters = NULL) { if(is.null(initial_capital)) initial_capital <- 0 if(is.null(premium_rate)) premium_rate <- 1 if(is.null(claim_interarrival_generator)) claim_interarrival_generator <- stats::rexp if(is.null(claim_interarrival_parameters)) claim_interarrival_parameters <- list(rate = 1) if(is.null(claim_size_generator)) claim_size_generator <- stats::rexp if(is.null(claim_size_parameters)) claim_size_parameters <- list(rate = 1) model <- methods::new( Class = "SparreAndersen", initial_capital = initial_capital, premium_rate = premium_rate, claim_interarrival_generator = claim_interarrival_generator, claim_interarrival_parameters = claim_interarrival_parameters, claim_size_generator = claim_size_generator, claim_size_parameters = claim_size_parameters ) return(model) } setMethod( f = "simulate_path", signature = c(model = "SparreAndersen"), definition = function(model, max_time_horizon = NULL, max_simulation_time = NULL, seed = NULL) { if(is.null(max_time_horizon)) max_time_horizon <- Inf if(is.null(max_simulation_time)) max_simulation_time <- Inf if(is.null(seed)) { seed <- .Random.seed } else { assign(x = ".Random.seed", value = seed, envir = .GlobalEnv) } stopifnot( isS4(model), is.numeric(max_time_horizon) && length(max_time_horizon) == 1 && isFALSE(is.na(max_time_horizon)) && max_time_horizon > 0, is.numeric(max_simulation_time) && length(max_simulation_time) == 1 && isFALSE(is.na(max_simulation_time)) && max_simulation_time > 0, is.numeric(seed) ) if(is.infinite(max_time_horizon) && is.infinite(max_simulation_time)) warning(paste0("Setting both max_time_horizon and max_simulation_time", "to Inf might result in an infinite loop.")) u <- model@initial_capital pr <- model@premium_rate f_a <- model@claim_interarrival_generator param_a <- model@claim_interarrival_parameters f_s <- model@claim_size_generator param_s <- model@claim_size_parameters param_a[["n"]] <- 1 param_s[["n"]] <- 1 path <- matrix(NA, nrow = 1, ncol = 2) colnames(path) <- c("time", "X") path[1, ] <- c(0, u) add_jump_to_path <- function(path, arrival, size) { path <- rbind( path, c(arrival, path[nrow(path), 2] + (arrival - path[nrow(path), 1]) * pr) ) path <- rbind( path, c(arrival, path[nrow(path), 2] + size) ) path } s_neg <- numeric() a_neg <- numeric() ca_neg <- do.call(what = f_a, args = param_a) is_ruined <- FALSE start_time <- Sys.time() repeat{ if(as.numeric(difftime(time1 = Sys.time(), time2 = start_time, units = "secs")) < max_simulation_time) { if(ca_neg < max_time_horizon) { cs_neg <- do.call(what = f_s, args = param_s) path <- add_jump_to_path(path, ca_neg, -cs_neg) s_neg <- c(s_neg, cs_neg) a_neg <- c(a_neg, ca_neg) if(path[nrow(path), 2] < 0) { is_ruined <- TRUE break } ca_neg <- ca_neg + do.call(what = f_a, args = param_a) } else { path <- rbind( path, c(max_time_horizon, path[nrow(path), 2] + (max_time_horizon - path[nrow(path), 1]) * pr) ) break } } else { break } } end_time <- Sys.time() elapsed_time <- as.numeric(difftime(time1 = end_time, time2 = start_time, units = "secs")) process <- methods::new( Class = "PathSparreAndersen", model = model, path = path, claim_sizes = s_neg, claim_arrival_times = a_neg, time_horizon = path[nrow(path), 1], is_ruined = is_ruined, elapsed_time = elapsed_time, max_time_horizon = max_time_horizon, max_simulation_time = max_simulation_time, seed = seed ) return(process) } )
test_that("bhl_bioherlib", { skip_on_cran() vcr::use_cassette("bhl_bioherlib", { tt <- bhl_bioherlib(method='GetPageMetadata', pageid=1328690, ocr=TRUE, names=TRUE) uu <- bhl_bioherlib(method='GetPageMetadata', pageid=1328690, ocr=TRUE, names=TRUE, as="list") vv <- bhl_bioherlib(method='GetPageMetadata', pageid=1328690, ocr=TRUE, names=TRUE, as='xml') }) expect_is(tt, "data.frame") expect_is(uu$Status, "character") expect_is(uu$Result, "list") expect_is(uu$Result[[1]]$ItemID, "integer") expect_is(vv, "character") expect_is(xml2::read_xml(vv), "xml_document") expect_is(xml2::xml_find_all(xml2::read_xml(vv), '//Result'), "xml_nodeset") expect_equal(NROW(tt), 1) expect_equal(length(uu$Status), 1) expect_equal(length(uu), 3) expect_equal(length(vv), 1) })
darken_colour <- function(hex_colour, amount = 0.15) { rgb(t(col2rgb(hex_colour) * (1 - amount)), maxColorValue = 255) } lighten_colour <- function(hex_colour, amount = 0.15) { lighter <- t(col2rgb(hex_colour) * (1 + amount)) lighter[lighter > 255] <- 255 rgb(lighter, maxColorValue = 255) }
hellingerNorm <- function(X,X_dimensions,colTotal,rowTotal,grandTotal,weights=NULL,masses=NULL){ if(is.null(masses)){ masses = rowTotal/grandTotal } if(is.null(weights)){ weights <- c(matrix(1/ncol(X),1,ncol(X))) } rowProfiles <- rowNorms(X,type='hellinger') rowCenter <- c(t(as.matrix(masses)) %*% rowProfiles) deviations <- rowProfiles - matrix(rowCenter,X_dimensions[1],X_dimensions[2],byrow=TRUE) return(list(rowCenter=rowCenter,masses=masses,weights=weights,rowProfiles=rowProfiles,deviations=deviations)) }
context("multibytes source file") with_locale <- function(locale, locale_val, expr) { prev_locale_val <- Sys.getlocale(locale) Sys.setlocale(locale, locale_val) on.exit({ Sys.setlocale(locale, prev_locale_val) }) force(expr) } expect_utf8 <- function(x) { expect_equal(Encoding(x), "UTF-8") } test_that("support files with multibytes", { with_locale("LC_CTYPE", "C", { with_locale("LC_COLLATE", "C", { r <- pr(test_path("files/multibytes.R")) req <- make_req("GET", "/echo") out <- r$call(req)$body expected <- jsonlite::toJSON("\u4e2d\u6587\u6d88\u606f") expect_identical(Sys.getlocale("LC_CTYPE"), "C") expect_identical(Sys.getlocale("LC_COLLATE"), "C") expect_utf8(expected) expect_utf8(out) expect_identical(charToRaw(out), charToRaw(expected)) }) }) })
design_matrix_loglin <- function(J,H=1,main=c("LC","same","Rasch"), X=NULL,free_cov=c("no","class","resp","both"), biv=NULL,free_biv=c("no","class","int","both")){ if(J<2) stop("J must be at least 2") main = match.arg(main) free_cov = match.arg(free_cov) free_biv = match.arg(free_biv) if(is.null(X)){ S = 1; ncov = 0 }else{ if(is.vector(X)){ S = length(X); ncov = 1 covnames = "X1" X = array(X,c(S,1,J)) }else if(is.matrix(X)){ S = nrow(X); ncov = ncol(X) covnames = colnames(X) if(is.null(covnames)) covnames = paste("X",1:ncov,sep="") X = array(X,c(S,ncov,J)) }else{ S = dim(X)[1]; ncov = dim(X)[2] covnames = colnames(X) if(is.null(covnames)) covnames = paste("X",1:ncov,sep="") if(dim(X)[3]!=J) stop("wrong dimension of covariate array") } } if(is.null(biv)){ nbiv = 0 }else{ if(is.vector(biv)) biv = t(biv) nbiv = nrow(biv) } Main = sq(J) if(nbiv==0){ Int = NULL }else{ Int = matrix(0,2^J,nbiv) for(j in 1:nbiv) Int[,j] = Main[,biv[j,1]]*Main[,biv[j,2]] } if(main=="LC"){ np = J*H par_list = NULL if(H==1){ par_list = paste("main",1:J,sep="") }else{ for(h in 1:H) par_list = c(par_list,paste("class",h,".main",1:J,sep="")) } } if(main=="same"){ np = H par_list = NULL if(H==1){ par_list = "main" }else{ for(h in 1:H) par_list = c(par_list,paste("class",h,".main",sep="")) } } if(main=="Rasch"){ np = J+(H-1) if(H==1){ par_list = NULL }else{ par_list = paste("class",2:H,sep="") } par_list = c(par_list,paste("main",1:J,sep="")) } if(ncov>0){ if(free_cov=="no"){ np = np+ncov par_list = c(par_list,covnames) } if(free_cov=="class"){ np = np+H*ncov if(H==1){ par_list = c(par_list,covnames) }else{ for(h in 1:H) par_list = c(par_list,paste("class",h,".",covnames,sep="")) } } if(free_cov=="resp"){ np = np+J*ncov for(j in 1:J) par_list = c(par_list,paste("resp",j,".",covnames,sep="")) } if(free_cov=="both"){ np = np+H*J*ncov if(H==1){ for(j in 1:J) par_list = c(par_list,paste("resp",j,".",covnames,sep="")) }else{ for(h in 1:H) for(j in 1:J) par_list = c(par_list,paste("class",h,".resp",j,".",covnames,sep="")) } } } if(nbiv>0){ if(free_biv=="no"){ np = np+1 par_list = c(par_list,"biv") } if(free_biv=="class"){ np = np+H if(H==1){ par_list = c(par_list,"biv") }else{ for(h in 1:H) par_list = c(par_list,paste("class",h,".biv",sep="")) } } if(free_biv=="int"){ np = np+nbiv for(j in 1:nbiv) par_list = c(par_list,paste("biv",biv[j,1],"-",biv[j,2],sep="")) } if(free_biv=="both"){ np = np+H*nbiv if(H==1){ for(j in 1:nbiv) par_list = c(par_list,paste("biv",biv[j,1],"-",biv[j,2],sep="")) }else{ for(h in 1:H) for(j in 1:nbiv) par_list = c(par_list,paste("class",h,".biv",biv[j,1],"-",biv[j,2],sep="")) } } } M = array(0,c(2^J,np,H,S)) for(s in 1:S){ for(h in 1:H){ tmp = matrix(0,1,H); tmp[h] = 1 if(main=="LC") Tmp1 = tmp%x%Main if(main=="same") Tmp1 = tmp%x%as.matrix(rowSums(Main)) if(main=="Rasch") Tmp1 = cbind(rep(1,2^J)%o%c(tmp[-1]),Main) if(main=="Rasch") Tmp1 = cbind(rowSums(Main)%o%c(tmp[-1]),Main) Tmp2 = NULL if(ncov>0){ Xs = matrix(X[s,,],ncov,J) if(free_cov=="no") Tmp2 = Main%*%t(Xs) if(free_cov=="class") Tmp2 = tmp%x%(Main%*%t(Xs)) if(free_cov=="resp"){ Tmp2 = NULL for(j in 1:J) Tmp2 = cbind(Tmp2,Main[,j]%o%Xs[,j]) } if(free_cov=="both"){ Tmp2 = NULL for(j in 1:J) Tmp2 = cbind(Tmp2,Main[,j]%o%Xs[,j]) Tmp2 = tmp%x%Tmp2 } } Tmp4 = NULL if(nbiv>0){ if(free_biv=="no") Tmp4 = rowSums(Int) if(free_biv=="class") Tmp4 = tmp%x%rowSums(Int) if(free_biv=="int") Tmp4 = Int if(free_biv=="both") Tmp4 = tmp%x%Int } M[,,h,s] = cbind(Tmp1,Tmp2,Tmp4) } } colnames(M) = par_list out = list(M=M,par_list=par_list,Main=Main) }
expected <- eval(parse(text="c(-Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -4.17369555651928e+302, -2.72671165723473e+289, -2.21240023126594e+276, -2.24780296109123e+263, -2.88514442494869e+250, -4.72336572671053e+237, -9.96611412047338e+224, -2.74100158340596e+212, -9.94902790498679e+199, -4.83110332887119e+187, -3.18582547396557e+175, -2.90089508183654e+163, -3.71562599613334e+151, -6.83535188151783e+139, -1.84898368353639e+128, -7.55412056676629e+116, -4.80716085942859e+105, -4.9383857330861e+94, -8.54170618068872e+83, -2.61556777274611e+73, -1.5069799345972e+63, -1.76183826972506e+53, -4.60125024792566e+43, -3.04622557026196e+34, -6.08456909882282e+25, -473300382255715392, -21650982809.6744, -12820.0784261145, -1.12778377684043)")); test(id=0, code={ argv <- eval(parse(text="list(c(-Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -4.17369555651928e+302, -2.72671165723473e+289, -2.21240023126594e+276, -2.24780296109123e+263, -2.88514442494869e+250, -4.72336572671053e+237, -9.96611412047338e+224, -2.74100158340596e+212, -9.94902790498679e+199, -4.83110332887119e+187, -3.18582547396557e+175, -2.90089508183654e+163, -3.71562599613334e+151, -6.83535188151783e+139, -1.84898368353639e+128, -7.55412056676629e+116, -4.80716085942859e+105, -4.9383857330861e+94, -8.54170618068872e+83, -2.61556777274611e+73, -1.5069799345972e+63, -1.76183826972506e+53, -4.60125024792566e+43, -3.04622557026196e+34, -6.08456909882282e+25, -473300382255715392, -21650982809.6744, -12820.0784261145, -1.12778377684043), c(1L, 13L, 14L, 26L, 38L, 39L, 51L))")); .Internal(`psort`(argv[[1]], argv[[2]])); }, o=expected);
snowprofilePrf <- function(Filename, ProfileDate = NA, tz = "UTC") { readTabularProfile <- function(TabularProfile) { MetaIndex <- which(startsWith(TabularProfile[, 1], " Metadata <- read.csv(textConnection(TabularProfile[MetaIndex:(MetaIndex + 2), 1])) LayerIndex <- which(startsWith(TabularProfile[, 1], " startsWith(TabularProfile[, 1], " Layers <- read.csv(textConnection(TabularProfile[(LayerIndex + 1):nrow(TabularProfile), 1])) Metadata <- type.convert(Metadata[-1, ]) Layers <- type.convert(Layers[-1, ]) Layers[Layers == -999] <- NA Layers$gtype <- sapply(Layers$class, function(x) ifelse(substr(x, 3, 3) == "2", "MFcr", swisscode[as.integer(substr(x, 1, 1))])) Layers$gtype <- as.factor(Layers$gtype) Layers$ddate <- as.POSIXct(Layers$X.DepositionDate) Layers$height <- round(Layers$Hn, 2) Layers$temperature <- round(Layers$Tn, 1) Layers$density <- round(Layers$rho, 1) Layers$lwc <- round(Layers$theta_w * 100, 1) Layers$gsize <- round(Layers$gsz, 2) Layers$ogs <- round(Layers$ogs, 2) Layers$bond_size <- Layers$bz Layers$dendrictiy <- Layers$dd Layers$sphericity <- Layers$sp Layers$hardness <- round(as.numeric(Layers$hardness), 2) if ("ssi" %in% names(Layers)) Layers$ssi <- round(Layers$ssi, 2) Layers[c("X.DepositionDate", "DepositionJulianDate", "Hn", "Tn", "gradT", "rho", "theta_i", "theta_w", "bz", "dd", "gsz", "sp", "class", "mk")] <- NULL Layers <- snowprofileLayers(layerFrame = Layers) SP <- snowprofile(station = Metadata$station, station_id = Metadata$station, datetime = as.POSIXct(Metadata$X.Date, format = "%Y-%m-%dT%H:%M:%S"), angle = Metadata$slope, aspect = Metadata$aspect, hs = Metadata$hs, type = "modeled", layers = Layers) return(SP) } if (!(endsWith(Filename, ".prf") | endsWith(Filename, ".aprf"))) stop(paste(Filename, "needs .prf or .aprf extension")) Lines <- data.table::fread(Filename, sep = "~", data.table = FALSE) EmptyLines <- which(nchar(Lines[, ]) == 0) Lines <- as.data.frame(Lines[-(EmptyLines), 1], stringsAsFactors = FALSE) if (is.na(ProfileDate)) { DateLines <- which(startsWith(Lines[, 1], " Nrows <- c(diff(DateLines), nrow(Lines) - DateLines[length(DateLines)] + 1) ProfileIndex <- rep(1:length(DateLines), Nrows) TabularProfiles <- split(Lines, ProfileIndex) SP <- lapply(TabularProfiles, readTabularProfile) SP <- snowprofileSet(SP) } else { DateLines <- which(startsWith(Lines[, 1], " Dates <- sapply(Lines[DateLines, ], function(x) unlist(strsplit(x, ","))[1], USE.NAMES = FALSE) Dates <- as.POSIXct(Dates, format = "%Y-%m-%dT%H:%M", tz = tz) if (!(ProfileDate %in% Dates)) stop(paste("No profile with date", ProfileDate, "found in", Filename)) ProfileDate <- format(ProfileDate, format = "%Y-%m-%dT%H:%M", tz = tz) StartLine <- which(startsWith(Lines[, 1], ProfileDate))[1] - 2 EndLine <- StartLine + 1 nLines <- nrow(Lines) while (!startsWith(Lines[(EndLine + 1), ], " EndLine <- EndLine + 1 if (EndLine == nLines) break } TabularProfile <- data.frame(Lines[StartLine:EndLine, ], stringsAsFactors = FALSE) SP <- readTabularProfile(TabularProfile) } return(SP) }
item.reverse <- function(x, min = NULL, max = NULL, keep = NULL, as.na = NULL, table = FALSE, check = TRUE) { if (isTRUE(missing(x))) { stop("Please specify a numeric vector for the argument 'x'.", call. = FALSE) } if (isTRUE(is.null(x))) { stop("Input specified for the argument 'x' is NULL.", call. = FALSE) } if (ncol(data.frame(x)) != 1) { stop("More than one variable specified for the argument 'x'.",call. = FALSE) } x <- unlist(x, use.names = FALSE) if (isTRUE(is.null(min))) { min <- min(x, na.rm = TRUE) } if (isTRUE(is.null(max))) { max <- max(x, na.rm = TRUE) } if (isTRUE(!is.logical(check))) { stop("Please specify TRUE or FALSE for the argument 'check'.", call. = FALSE) } if (isTRUE(check)) { if (isTRUE(mode(x) != "numeric")) { stop("Please specify a numeric vector for the argument 'x'.") } if (isTRUE(length(min) != 1 || !is.numeric(min) || min %% 1 != 0)) { stop("Please specify a single integer value for the argument 'min'.") } if (isTRUE(length(max) != 1 || !is.numeric(max) || max %% 1 != 0)) { stop("Please specify a single integer value for the argument 'max'.") } keep.na <- !keep %in% x if (isTRUE(any(keep.na))) { warning(paste0("Values specified in the argument 'keep' were not found in 'x': ", paste(keep[keep.na], collapse = ", ")), call. = FALSE) } if (isTRUE(!is.logical(table))) { stop("Please specify TRUE or FALSE for the argument 'table'.", call. = FALSE) } } object <- x if (isTRUE(!is.null(as.na))) { object <- misty::as.na(object, na = as.na, check = check) } if (isTRUE(!is.null(keep))) { object[object %in% keep] <- NA } low <- min high <- max object <- sum(low, high) - object if (isTRUE(!is.null(keep))) { object[which(x %in% keep)] <- x[which(x %in% keep)] } if (isTRUE(table)) { print(table(x, object, dnn = c("item", "reverse coded"))) return(invisible(object)) } else { return(object) } }
cyclic_b_spline_basis <- function(x, nseg = 10, deg = 3, range.variables){ nseg <- nseg + 3 x_min <- min(range.variables) x_max <- max(range.variables) interval <- (x_max - x_min) /nseg knot_seq <- seq(x_min - deg * interval, x_max + deg * interval, by = interval) sparseBasis <- splineDesign(knots = knot_seq, x = x, ord = deg + 1, outer.ok = T, sparse = T) lastdegcols <- (ncol(sparseBasis) - deg + 1):ncol(sparseBasis) make_spam(cbind((sparseBasis[, 1:deg] + sparseBasis[, lastdegcols]), sparseBasis[, ((deg + 1):(ncol(sparseBasis) - deg)) ])) }
context("Check model_parts() function") mp_ranger <- model_parts(explainer_regr_ranger, N = 100) mp_lm <- model_parts(explainer_regr_lm, N = 100) mp_ranger_ratio <- model_parts(explainer_regr_ranger, N = 100, type = "ratio") test_that("Description prints properly", { des <- ingredients::describe(mp_ranger) expect_error(print(des), NA) }) test_that("y not provided",{ expect_error(model_parts(explainer_regr_ranger_wo_y, N = 100)) }) test_that("data not provided",{ expect_error(model_parts(explainer_wo_data, N = 100)) }) test_that("wrong type value",{ expect_error(model_parts(explainer_regr_ranger, type="anything")) }) test_that("Wrong object class (not explainer)", { expect_error(model_parts(c(1,1))) }) test_that("Output format",{ expect_is(mp_ranger, c("model_parts", "feature_importance_explainer")) expect_is(mp_lm, c("model_parts", "feature_importance_explainer")) expect_is(mp_ranger_ratio, c("model_parts", "feature_importance_explainer")) }) test_that("Output format - plot",{ expect_is(plot(mp_ranger_ratio), "gg") expect_is(plot(mp_ranger, mp_lm), "gg") expect_is(plot(mp_lm), "gg") }) test_that("Inverse sorting of bars",{ expect_is(plot(mp_ranger_ratio, desc_sorting = FALSE), "gg") expect_is(plot(mp_ranger, mp_lm, desc_sorting = FALSE), "gg") expect_is(plot(mp_ranger, desc_sorting = FALSE), "gg") }) fi_ranger <- feature_importance(explainer_regr_ranger, N = 100) fi_lm <- feature_importance(explainer_regr_lm, N = 100) fi_ranger_ratio <- feature_importance(explainer_regr_ranger, N = 100, type = "ratio") vi_ranger <- variable_importance(explainer_regr_ranger, N = 100) vi_lm <- variable_importance(explainer_regr_lm, N = 100) vi_ranger_ratio <- variable_importance(explainer_regr_ranger, N = 100, type = "ratio") test_that("Output format",{ expect_is(fi_ranger, c("model_parts", "feature_importance_explainer")) expect_is(fi_lm, c("model_parts", "feature_importance_explainer")) expect_is(fi_ranger_ratio, c("model_parts", "feature_importance_explainer")) expect_is(vi_ranger, c("model_parts", "feature_importance_explainer")) expect_is(vi_lm, c("model_parts", "feature_importance_explainer")) expect_is(vi_ranger_ratio, c("model_parts", "feature_importance_explainer")) }) test_that("Output format - plot",{ expect_is(plot(fi_ranger_ratio), "gg") expect_is(plot(fi_ranger, fi_lm), "gg") expect_is(plot(fi_lm), "gg") expect_is(plot(vi_ranger_ratio), "gg") expect_is(plot(vi_ranger, vi_lm), "gg") expect_is(plot(vi_lm), "gg") })
lbj_cells <- setRefClass("lbj_cells" , fields = list( cells = "array" , n = "numeric" , t = "POSIXct" , expr = "character" , verbose = "logical" , label = "character" ) , methods = list( initialize = function(..., verbose=TRUE, label=""){ "Create object. Optionally toggle verbosity." .self$n <- 0 .self$t <- .POSIXct(numeric(0)) .self$verbose = verbose .self$label = label } , add = function(meta, input, output){ "Add logging info based on in- and output" if (!identical(dim(input),dim(output))){ warnf("dimensions changed, not logging %s",meta$src) return() } cl <- cells(from = input, to = output) tm <- as.POSIXct(Sys.time()) if ( .self$n == 0 ){ .self$cells <- cl[,1,drop=FALSE] .self$t <- c(.self$t,tm) .self$expr <- "" } .self$n <- .self$n+1 .self$t <- c(.self$t, tm) .self$expr <- c(.self$expr, meta$src) .self$cells <- cbind(.self$cells, cl[,2,drop=FALSE]) } , dump = function(file=NULL,verbose=TRUE,...){ "Dump logging info to csv file. All arguments in '...' except row.names are passed to 'write.csv'" out <- .self$log_data() outf <- if( !is.null(file) ) file else if (.self$label == "" ) "lbj_cells.csv" else paste0(.self$label, "_lbj_cells.csv") write.csv(out, file=outf, row.names=FALSE,...) .self$fmsg("Dumped a log at %s", normalizePath(outf)) } , log_data = function(){ "Return logged data as a data.frame" out <- data.frame( step = if(.self$n > 0 ) 0:.self$n else integer(0) , time = .self$t , expression = .self$expr ) cl <- t(.self$cells) row.names(cl) <- NULL cbind(out, cl) } , show = function(){ "Print method" cat("Logging object of class lbj_cells with the following logging info\n") print(.self$log_data()) } , fmsg = function(fmt,...){ if (.self$verbose){ message(sprintf(fmt,...)) } } ) ) lbj_rules <- setRefClass("lbj_rules", fields = list( compare = "array" , rules = "validator" , n = "numeric" , t = "POSIXct" , expr = "character" , verbose = "logical" , label = "character" ) , methods = list( initialize = function(rules, verbose=TRUE, label=""){ "Create object. Optionally toggle verbosity." .self$n <- 0 .self$t <- .POSIXct(numeric(0)) .self$verbose <- verbose .self$rules <- rules$copy() .self$label <- label v <- validator(x>0) } , add = function(meta, input, output){ if (!identical(dim(input),dim(output))){ warnf("dimensions changed, not logging %s",meta$src) return() } tm <- as.POSIXct(Sys.time()) comp <- cbind(compare(.self$rules, input, output)) if ( .self$n == 0 ){ .self$compare <- comp[,1,drop=FALSE] .self$t <- c(.self$t,tm) .self$expr <- "" } .self$n <- .self$n+1 .self$t <- c(.self$t, tm) .self$expr <- c(.self$expr, meta$src) .self$compare <- cbind(.self$compare, comp[,2,drop=FALSE]) } , dump = function(file=NULL,...){ "Dump logging info to csv file. All arguments in '...' except row.names are passed to 'write.csv'" out <- .self$log_data() outf <- if( !is.null(file) ) file else if (.self$label == "" ) "lbj_rules.csv" else paste0(.self$label, "_lbj_rules.csv") write.csv(out, file=outf, row.names=FALSE,...) .self$fmsg("Dumped a log at %s", normalizePath(outf)) } , log_data = function(){ "Return logged data as a data.frame" out <- data.frame( step = if(.self$n > 0 ) 0:.self$n else integer(0) , time = .self$t , expression = .self$expr ) cm <- t(.self$compare) row.names(cm) <- NULL cbind(out, cm) } , show = function(){ "Print method" cat("Logging object of class lbj_rules with the following logging info\n") print(.self$log_data()) } , plot = function(){ "plot rule comparisons" pl <- getMethod("plot","validatorComparison") log <- .self$log_data() cmp <- t(log[-(1:3)]) class(cmp) <- c("validatorComparison", "array") x <- gsub("\\(.*","",log$expression) colnames(cmp) <- x pl(cmp) } , fmsg = function(fmt,...){ if (.self$verbose){ message(sprintf(fmt,...)) } } ) )
save_private_keys <- function ( api_var = NULL, key = NULL, name_of_outputted_object = "api_keys", file = "~/r_keychain.rds" ){ if (is.null(api_var) | is.null(key)) stop("Please fill in api_var and key") if (file.exists(file)) { keychain <- readRDS(file) } else { keychain <- data.frame( api_var = "identifier for key",key = "the key", stringsAsFactors = F ) } if (api_var %in% keychain$api_var) { keychain$key[keychain$api_var == api_var] <- key } else { keychain <- rbind( keychain, data.frame( api_var = api_var, key = key, stringsAsFactors = F ) ) } message( paste0( "Run this code: saveRDS(",name_of_outputted_object,", '",file,"')" ) ) return(keychain) }
if(FALSE){ library(gorica) library(lavaan) model1 <- ' A =~ Ab + Al + Af + An + Ar + Ac B =~ Bb + Bl + Bf + Bn + Br + Bc ' fit1 <- sem(model1, data = sesamesim, std.lv = TRUE) coef(fit1) hypotheses1 <- " A=~Ab > .6 & A=~Al > .6 & A=~Af > .6 & A=~An > .6 & A=~Ar > .6 & A=~Ac > .6 & B=~Bb > .6 & B=~Bl > .6 & B=~Bf > .6 & B=~Bn > .6 & B=~Br > .6 & B=~Bc > .6 " set.seed(100) out_c <- gorica(fit1, hypotheses1, comparison = "complement", standardize=TRUE) out_c out_u <- gorica(fit1, hypotheses1, standardize=TRUE) out_u library(restriktor) n <- 10 x1 <- rnorm(n) x2 <- rnorm(n) x3 <- rnorm(n) x4 <- rnorm(n) x5 <- rnorm(n) x6 <- rnorm(n) y <- 1 + x1 + x2 + x3 + x4 + x5 + x6 + rnorm(n) fit.lm <- lm(y ~ 1 + x1 + x2 + x3 + x4 + x5 + x6) h1 <- "x1 > 0; x2 > 0; x3 > 0; x4 > 0; x5 > 0; x6 > 0" h2 <- "x1 > 0.6; x2 > 0.6; x3 > 0.6; x4 > 0.6; x5 > 0.6; x6 > 0.6" out_1_u <- goric(fit.lm, h1) summary(out_1_u) out_1_c <- goric(fit.lm, h1, comparison = "complement") summary(out_1_c) out_2_u <- goric(fit.lm, h2) summary(out_2_u) out_2_c <- goric(fit.lm, h2, comparison = "complement") summary(out_2_c) }
"factor2cluster" <- function (loads,cut=.0,aslist=FALSE) { if (!is.matrix(loads) ) {l <-loads$loadings} else {l <- loads} l <- as.matrix(l) nrows <- dim(l)[1] ncols <- dim(l)[2] if (ncols ==1) {m1 <- matrix(rep(1,nrows),ncol=1) } else { m1 <- matrix(apply(t(apply(l, 1, abs)), 1, which.max), ncol = 1)} id <- matrix(c(1:nrows, m1), ncol = 2) factor2cluster <- matrix(rep(0, ncols * nrows), ncol = ncols) factor2cluster[id] <- sign(l[id])*( (abs(l[id]) >cut)+0) rownames(factor2cluster) <- rownames(l) colnames(factor2cluster) <- colnames(l) nitems <- colSums(abs(factor2cluster)) for (i in ncols:1) {if (nitems[i]<1) {factor2cluster <- factor2cluster[,-i,drop=FALSE]} } if(aslist) factor2cluster <- keys2list(factor2cluster) return(factor2cluster) }
context("Testing realtime functions") test_that("realtime_dd returns the correct data header", { skip_on_cran() expect_identical( colnames(realtime_dd(station_number = "08MF005", prov_terr_state_loc = "BC")), c("STATION_NUMBER", "PROV_TERR_STATE_LOC", "Date", "Parameter", "Value", "Grade", "Symbol", "Code") ) }) test_that("realtime_dd can download stations from a whole province using prov_terr_state_loc and stores query time", { skip_on_cran() expected_columns <- c("STATION_NUMBER", "PROV_TERR_STATE_LOC", "Date", "Parameter", "Value", "Grade", "Symbol", "Code") rldf <- realtime_dd(prov_terr_state_loc = "PE") expect_true(identical(expected_columns,colnames(rldf))) expect_is(attributes(rldf)$query_time, "POSIXct") }) test_that("realtime_dd can download stations from multiple provinces using station_number", { skip_on_cran() expect_error(realtime_dd(station_number = c("01CD005", "08MF005")), regexp = NA) }) test_that("When station_number is ALL there is an error", { skip_on_cran() expect_error(realtime_dd(station_number = "ALL")) }) test_that("realtime_dd works when station is not realtime",{ skip_on_cran() stns <- hy_stations(hydat_path = hy_test_db()) stn <- sample(stns$STATION_NUMBER[!stns$REAL_TIME & stns$HYD_STATUS == "DISCONTINUED"], 1) expect_s3_class(realtime_dd(stn), "realtime") })
rfeTerminator <- function(df, x_cols, y_cols, method="cv", kfolds=10, sizes = c(1:100), alter_df = TRUE, eval_funcs=rfFuncs, ...){ ctrl <- caret::rfeControl(functions=eval_funcs, method=method, number=kfolds) y_df <- df[y_cols] results <- caret::rfe(df[,x_cols], df[,y_cols], sizes=c(sizes), rfeControl = ctrl, ...) original <- df if(alter_df==TRUE){ message("[INFO] Removing features as a result of recursive feature enginnering. Expose rfe_reduced_data from returned list using $ selectors.") transformed <- df[, results$optVariables] merged <- cbind(transformed, y_df) colnames(merged) <- c(results$optVariables, names(y_df)) results_list <- list("rfe_model_fit_results"=results, "rfe_reduced_features"=transformed, "rfe_original_data"=original, "rfe_reduced_data"=merged ) message(paste0("[IVS SELECTED] Optimal variables are: ", as.character(results$optVariables), "\n")) return(results_list) } else if(alter_df==FALSE){ message("[INFO] Returning initial recursive feature engineering results and original data as a list()") results_list <- list("rfe_model_fit_results"=results, "rfe_original_data"=tibble(original) ) return(results_list) } }
c2s <- function(object, newname, env=.GlobalEnv) { if (missing(object)) { if (iam("local")) remoter_client_stop("must pass an object") return(invisible()) } test <- tryCatch(is.environment(env), error=identity) if (isFALSE(test) || inherits(test, "error")) { if (iam("local")) { if (isFALSE(test)) remoter_client_stop("invalid environment") else remoter_client_stop(gsub(test, pattern="(.*: |\\n)", replacement="")) } return(invisible()) } if (!missing(newname)) { if (!identical(make.names(newname), newname)) { if (iam("local")) remoter_client_stop("invalid 'newname'") return(invisible()) } } name <- as.character(substitute(object)) err <- ".__remoter_s2c_failure" if (iam("local")) { remoter_receive() value <- get0(name, ifnotfound=err) remoter_send(data=value) if (identical(value, err)) { cat(paste0("Error: object '", name, "' not found on the client\n")) return(invisible(FALSE)) } } else if (iam("remote")) { remoter_send(NULL) value <- remoter_receive() if (identical(value, err)) { remoter_send(FALSE) return(invisible(FALSE)) } if (!missing(newname)) name <- newname if (missing(env)) env <- sys.frame(-1) assign(x=name, value=value, envir=env) } return(invisible(TRUE)) }
require(FrF2) summary(FrF2(16,7),brief=TRUE) summary(FrF2(32,7,blocks=4),brief=TRUE) summary(FrF2(32,9,blocks=4,alias.block.2fis=TRUE),brief=TRUE) summary(FrF2(32,9,blocks=c("AB","AC"),alias.block.2fis=TRUE),brief=TRUE) summary(FrF2(64,7,blocks=4),brief=TRUE) summary(plan1 <- FrF2(32,7,estimable=c("AB","CD")),brief=TRUE) summary(plan2 <- FrF2(nruns= 64 ,nfactors= 10 , estimable= c( "AB","AC","AD","AE","AF", "AG","AH","AJ","AK","BC","BD","BE","BF","BG","BH","BJ","BK" ) ), brief=TRUE) C1 <- compromise(10, 1:2, msg=FALSE) summary(plan3 <- FrF2(nruns= 64 ,nfactors= 10 , estimable= C1$requirement, perms=C1$perms.full, clear=FALSE ), brief=TRUE) plan <- FrF2(64,15,blocks=16,alias.block.2fi=TRUE,block.old=TRUE) summary(plan,brief=TRUE) planfull <-FrF2(32,5,WPs=4,nfac.WP=2,factor.names=Letters[21:25]) summary(planfull, brief=TRUE) design.info(planfull)[-which(names(design.info(planfull))=="FrF2.version")] try(planfull <-FrF2(32,5,WPs=4,nfac.WP=3,factor.names=Letters[21:25])) plan0 <-FrF2(32,7,gen=c(6,15),WPs=4,WPfacs=c("B","C","F"),factor.names=Letters[19:25]) summary(plan0,brief=TRUE) design.info(plan0)[-which(names(design.info(plan0))=="FrF2.version")] plan <-FrF2(32,7,WPs=4,nfac.WP=3,factor.names=Letters[19:25]) summary(plan, brief=TRUE) generators(plan) design.info(plan)[-which(names(design.info(plan))=="FrF2.version")] plan2 <- FrF2(32,7,gen=c(6,15),WPs=4,nfac.WP=3,WPfacs=c(2,3,6),factor.names=Letters[19:25]) summary(plan2, brief=TRUE) generators(plan2) design.info(plan2)[-which(names(design.info(plan2))=="FrF2.version")]
context("BatchJobs mode") test_that("BatchJobs mode", { k = autodetectCpus(MODE_MULTICORE) expect_true(is.integer(k) && length(k) == 1L) })
test_that("gn_parse", { skip_on_cran() vcr::use_cassette("gn_parse", { tt <- gn_parse("Cyanistes caeruleus") }) expect_is(tt, "data.frame") expect_is(tt, "tbl") expect_is(tt$normalized, "character") expect_is(tt$canonicalName, "data.frame") expect_is(tt$details, "list") expect_is(tt$positions, "list") }) test_that("gn_parse fails well", { expect_error(gn_parse()) expect_error(gn_parse(5)) })
dest <- function(object,...) UseMethod("dest") dest.liu <- function(object,...) { x <- object$xs y <- object$y p <- ncol(x) n <- nrow(x) d <- object$d EVal <- eigen(t(x) %*% x)$values EVec <- eigen(t(x) %*% x)$vectors ols <- lm.fit(x, y) coefols <- ols$coef fittedols<- ols$fitted.values residols <- ols$residuals sigma2 <- sum(residols ^ 2) / (n - p) alphaols <- t(EVec) %*% coefols rownames(alphaols) <- colnames(x) diaghat <- lapply(hatl(object), function(x) { diag(x) }) diaghat <- do.call(cbind, diaghat) SSER<-lstats(object)$SSER GCV<-matrix(0,1,nrow=length(d) ) for(i in seq(length(d))){ GCV[i,]<-SSER[i]/(n-1-sum(diaghat[,i]))^2 } rownames(GCV) <- paste("d=", d, sep = "") colnames(GCV) <- c("GCV") if (length(GCV) > 0) { l <- seq_along(GCV)[GCV == min(GCV)] dGCV <- object$d[l] } EVal1<-EVal+1 dopt<-(sum((alphaols^2-sigma2)/EVal1^2))/(sum((sigma2+EVal*alphaols^2)/(EVal*EVal1^2))) numdmm <- 1 / (EVal * EVal1) dnumdmm <- (alphaols ^ 2) / (EVal1 ^ 2) dmm <- 1 - (sigma2 * sum(numdmm) / sum(dnumdmm) ) numdcl <- 1 / EVal1 dnumdcl <- (EVal * alphaols ^ 2) / (EVal1 ^ 2) dcl <- 1 - sigma2 * (sum(numdcl) / sum(dnumdcl)) xtx<-t(x)%*%x xty<-t(x)%*%y F1<-numeric(n) F2<-numeric(n) for(i in 1:n){ ehat<-y[i]-(t(x[i,])%*%solve(xtx-x[i,]%*%t(x[i,]))%*%(xty-x[i,]*y[i])) etild<-y[i]-(t(x[i,])%*%solve(xtx+diag(p)-x[i,]%*%t(x[i,])) %*% (xty-x[i,]*y[i])) H= (x%*%solve(xtx))%*%t(x) G=x%*%solve(xtx+diag(p))%*%t(x) F1[i] <- ((etild/(1-diag(G)[i])) * (etild/(1-diag(H)[i]) - ehat/(1-diag(H)[i]))) F2[i] <- (etild/(1-diag(G)[i]) - (ehat/(1-diag(H)[i]))) } dILE=sum(F1)/sum(F2) desti <- list( dmm = dmm, dcl = dcl, GCV = GCV, dGCV=dGCV, dopt=dopt, dILE=dILE ) class(desti) <- "dliu" desti } print.dliu <- function(x,...) { cat("Liu biasing parameter d\n") dest <- cbind( dmm=x$dmm, dcl=x$dcl, dopt=x$dopt, dILE=x$dILE, dGCV=x$dGCV ) rownames(dest) <- "d values" colnames(dest) <- c("dmm", "dcl", "dopt", "dILE", "min GCV at") print(t(round(dest,5)),...) }
date_y <- function(y){ stopifnot(is.numeric(y) || all(is.na(y))) date_xx(as.integer(y), "date_y") } is_date_y <- function(x){ inherits(x, "date_y") } as_date_y <- function(x){ UseMethod("as_date_y") } as_date_y.default <- function(x){ as_date_y.Date(as.Date(x)) } as_date_y.numeric <- function(x){ date_y(x) } as_date_y.Date <- function(x){ date_y(get_year(x)) } as.Date.date_y <- function( x, ... ){ make_date(x, 1, 1L) }
library(plm) data("Grunfeld", package = "plm") gi <- plm(inv ~ value + capital, data = Grunfeld, model = "within", effect = "individual") f_level_gi <- fixef(gi, type = "level") f_dmean_gi <- fixef(gi, type = "dmean") int_gi <- within_intercept(gi) mod_int_gi <- within_intercept(gi, return.model = TRUE) int_manual_gi <- mean(fixef(gi)) individual_intercepts_gi <- int_gi + f_dmean_gi if (!isTRUE(all.equal(individual_intercepts_gi, f_level_gi, check.attributes = FALSE))) stop("within_intercept: something is wrong") if (!isTRUE(all.equal(int_gi, int_manual_gi, check.attributes = FALSE))) stop("within_intercept: something is wrong") gt <- plm(inv ~ value + capital, data = Grunfeld, model = "within", effect = "time") f_level_gt <- fixef(gt, type = "level") f_dmean_gt <- fixef(gt, type = "dmean") int_gt <- within_intercept(gt) mod_int_gt <- within_intercept(gt, return.model = TRUE) int_manual_gt <- mean(fixef(gt)) individual_intercepts_gt <- int_gt + f_dmean_gt if(!isTRUE(all.equal(individual_intercepts_gt, f_level_gt, check.attributes = FALSE))) stop("within_intercept: something is wrong") if(!isTRUE(all.equal(int_gt, int_manual_gt, check.attributes = FALSE))) stop("within_intercept: something is wrong") gtw <- plm(inv ~ value + capital, data = Grunfeld, model = "within", effect = "twoways") f_level_tw_i <- fixef(gtw, type = "level", effect = "individual") f_dmean_tw_i <- fixef(gtw, type = "dmean", effect = "individual") f_level_tw_t <- fixef(gtw, type = "level", effect = "time") f_dmean_tw_t <- fixef(gtw, type = "dmean", effect = "time") int_tw <- within_intercept(gtw) mod_int_tw <- within_intercept(gtw, return.model = TRUE) int_manual_tw_i <- mean(f_level_tw_i) int_manual_tw_t <- mean(f_level_tw_t) individual_intercepts_tw_i <- int_tw + f_dmean_tw_i individual_intercepts_tw_t <- int_tw + f_dmean_tw_t Grunfeld_unbalanced <- Grunfeld[-c(200), ] gi_u <- plm(inv ~ value + capital, data = Grunfeld_unbalanced, model = "within", effect = "individual") f_level_gi_u <- fixef(gi_u, type = "level") f_dmean_gi_u <- fixef(gi_u, type = "dmean") int_gi_u <- within_intercept(gi_u) mod_int_gi_u <- within_intercept(gi_u, return.model = TRUE) individual_intercepts_gi_u <- int_gi_u + f_dmean_gi_u int_manual_gi_u <- weighted.mean(fixef(gi_u), as.numeric(table(index(gi_u)[[1]]))) mean(f_level_gi_u) if(!isTRUE(all.equal(individual_intercepts_gi_u, f_level_gi_u, check.attributes = FALSE))) stop("within_intercept, unbalanced: something is wrong") if(!isTRUE(all.equal(int_gi_u, int_manual_gi_u, check.attributes = FALSE))) stop("within_intercept, unbalanced: something is wrong") gt_u <- plm(inv ~ value + capital, data = Grunfeld_unbalanced, model = "within", effect = "time") f_level_gt_u <- fixef(gt_u, type = "level") f_dmean_gt_u <- fixef(gt_u, type = "dmean") int_gt_u <- within_intercept(gt_u) mod_int_gt_u <- within_intercept(gt_u, return.model = TRUE) individual_intercepts_gt_u <- int_gt_u + f_dmean_gt_u int_manual_gt_u <- weighted.mean(fixef(gt_u), as.numeric(table(index(gt_u)[[2]]))) mean(f_level_gt_u) int_gt_u <- within_intercept(gt_u) if(!isTRUE(all.equal(individual_intercepts_gt_u, f_level_gt_u, check.attributes = FALSE))) stop("within_intercept, unbalanced: something is wrong") if(!isTRUE(all.equal(int_gt_u, int_manual_gt_u, check.attributes = FALSE))) stop("within_intercept, unbalanced: something is wrong") gtw_u <- plm(inv ~ value + capital, data = Grunfeld_unbalanced, model = "within", effect = "twoways") f_level_tw_i_u <- fixef(gtw_u, type = "level", effect = "individual") f_level_tw_t_u <- fixef(gtw_u, type = "level", effect = "time") f_dmean_tw_i_u <- fixef(gtw_u, type = "dmean", effect = "individual") f_dmean_tw_t_u <- fixef(gtw_u, type = "dmean", effect = "time") int_tw_u <- within_intercept(gtw_u) int_manual_tw_i_u <- weighted.mean(f_level_tw_i_u, w = pdim(gtw_u)$Tint$Ti) int_manual_tw_t_u <- weighted.mean(f_level_tw_t_u, w = pdim(gtw_u)$Tint$nt) int_manual_tw_i_u + int_manual_tw_t_u all.equal(int_manual_tw_i_u, int_manual_tw_t_u) individual_intercepts_tw_i_u <- int_manual_tw_i_u + f_dmean_tw_i_u individual_intercepts_tw_t_u <- int_manual_tw_t_u + f_dmean_tw_t_u mod_lm <- lm(inv ~ value + capital + factor(firm) + factor(year), data = Grunfeld_unbalanced) if(!isTRUE(all.equal(individual_intercepts_tw_i_u, f_level_tw_i_u, check.attributes = FALSE))) stop("within_intercept twoways, individual: something is wrong") if(!isTRUE(all.equal(individual_intercepts_tw_t_u, f_level_tw_t_u, check.attributes = FALSE))) stop("within_intercept twoways, time: something is wrong") f_level_tw_u <- as.numeric(fixef(gtw_u, "twoways", "level")) f_level_tw_u_test <- int_tw_u + f_dmean_tw_i_u[index(gtw_u)[[1L]]] + f_dmean_tw_t_u[index(gtw_u)[[2L]]] if(!isTRUE(all.equal(f_level_tw_u, f_level_tw_u_test, check.attributes = FALSE))) stop("within_intercept twoways, individual, time: something is wrong") print(within_intercept(gi)) print(within_intercept(gi_u)) print(within_intercept(gt)) print(within_intercept(gt_u)) print(within_intercept(gtw)) print(within_intercept(gtw_u))
plotfit.fdSmooth <- function(y, argvals, fdSm, rng = NULL, index = NULL, nfine = 101, residual = FALSE, sortwrd = FALSE, titles=NULL, ylim=NULL, ask=TRUE, type=c("p", "l")[1+residual], xlab=NULL, ylab=NULL, sub=NULL, col=1:9, lty=1:9, lwd=1, cex.pch=1, axes=NULL, ...) { plotfit.fd(y, argvals, fdSm$fd, rng = rng, index = index, nfine = nfine, residual = residual, sortwrd = sortwrd, titles=titles, ylim=ylim, ask=ask, type=c("p", "l")[1+residual], xlab=xlab, ylab=ylab, sub=sub, col=1:9, lty=1:9, lwd=1, cex.pch=1, axes=axes, ...) } plotfit.fd <- function(y, argvals, fdobj, rng = NULL, index = NULL, nfine = 101, residual = FALSE, sortwrd = FALSE, titles=NULL, ylim=NULL, ask=TRUE, type=c("p", "l")[1+residual], xlab=NULL, ylab=NULL, sub=NULL, col=1:9, lty=1:9, lwd=1, cex.pch=1, axes=NULL, ...) { if (!(is.fd(fdobj) || is.fdPar(fdobj))) stop( "Third argument is neither a functional data nor a functional parameter object.") if (is.fdPar(fdobj)) fdobj <- fdobj$fd basisobj <- fdobj$basis if (is.null(rng)) rng <- basisobj$rangeval fdnames <- fdobj$fdnames yName <- substring(deparse(substitute(y)), 1, 33) fdName <- paste(substring(deparse(substitute(fdobj)), 1, 22), "$coef", sep='') defaultNms <- c(fdnames[2], fdnames[3], x='x') if((length(defaultNms[[2]])<2) && !is.null(names(defaultNms)) && !is.na(names(defaultNms)[2])) defaultNms[[2]] <- names(defaultNms)[2] subset <- checkDims3(y, fdobj$coef, defaultNames = defaultNms, xName=yName, yName=fdName) y <- subset$x fdobj$coef <- subset$y n <- dim(y)[1] nrep <- dim(y)[2] nvar <- dim(y)[3] curveno <- 1:nrep argname <- names(fdnames)[[1]] if (is.null(argname)) { if (is.null(fdnames[[1]])) argname <- "Argument Value" else argname <- fdnames[[1]] } if (is.null(xlab)) xlab <- argname casenames <- dimnames(y)[[2]] varnames <- dimnames(y)[[3]] if (is.null(axes)) { if (is.null(fdobj$basis$axes)) { Axes <- TRUE axFun <- FALSE } else { if (!inherits(fdobj$basis$axes, "list")) stop("fdobj$basis$axes must be a list; ", "class(fdobj$basis$axes) = ", class(fdobj$basis$axes)) if (!(inherits(fdobj$basis$axes[[1]], "character") || inherits(fdobj$basis$axes[[1]], "function"))) stop("fdobj$basis$axes[[1]] must be either a function or the ", "name of a function; class(fdobj$basis$axes[[1]]) = ", class(fdobj$basis$axes[[1]])) Axes <- FALSE axFun <- TRUE axList <- c(fdobj$basis$axes, ...) } } else { if (is.logical(axes)) { Axes <- axes axFun <- FALSE } else { if (!inherits(axes, "list")) stop("axes must be a logical or a list; class(axes) = ", class(axes)) if (!(inherits(axes[[1]], "character") || inherits(axes[[1]], "function"))) stop("axes[[1]] must be either a function or the ", "name of a function; class(axes[[1]]) = ", class(axes[[1]])) Axes <- FALSE axFun <- TRUE axList <- c(axes, ...) } } dots <- list(...) if (is.null(titles) && ("main" %in% names(dots))) titles <- dots$main yhat. <- eval.fd(argvals, fdobj) yhat <- as.array3(yhat.) res <- y - yhat MSE <- apply(res^2,c(2,3),mean) dimnames(MSE) <- list(casenames, varnames) MSEsum <- apply(MSE,1,sum) xfine <- seq(rng[1], rng[2], len=nfine) yfine <- array(eval.fd(xfine, fdobj),c(nfine,nrep,nvar)) if (sortwrd && nrep > 1) { MSEind <- order(MSEsum) y <- y [,MSEind,, drop=FALSE] yhat <- yhat [,MSEind,, drop=FALSE] yfine <- yfine[,MSEind,, drop=FALSE] res <- res [,MSEind,, drop=FALSE] MSE <- MSE [ MSEind,, drop=FALSE] casenames <- casenames[MSEind] titles <- titles[MSEind] } if (is.null(index)) index <- 1:nrep nrepi <- length(index) y <- y [,index,, drop=FALSE] yhat <- yhat [,index,, drop=FALSE] res <- res [,index,, drop=FALSE] yfine <- yfine[,index,, drop=FALSE] MSE <- MSE [ index,, drop=FALSE] casenames <- casenames[index] titles <- titles[index] nOnOne <- 1 if (ask & ((nvar*nrepi/nOnOne) > 1)) cat('Multiple plots: Click in the plot to advance to the next plot\n') col <- rep(col, length=nOnOne) lty <- rep(lty, length=nOnOne) lwd <- rep(lwd, length=nOnOne) cex.pch <- rep(cex.pch, length=nOnOne) argind <- ((argvals >= rng[1]) & (argvals <= rng[2])) argvals <- argvals[argind] casenames <- casenames[argind] y <- y [argind,,, drop=FALSE] yhat <- yhat[argind,,, drop=FALSE] res <- res [argind,,, drop=FALSE] n <- length(argvals) xfiind <- ((xfine >= rng[1]) & (xfine <= rng[2])) xfine <- xfine[xfiind] yfine <- yfine[xfiind,,, drop=FALSE] nfine <- length(xfine) ndigit = abs(floor(log10(min(c(MSE)))) - 1) if (is.null(sub)) sub <- paste(" RMS residual =", round(sqrt(MSE),ndigit)) if (length(sub) != length(MSE)){ warning('length(sub) = ', length(sub), ' != ', length(MSE), ' = ', length(MSE), '; forcing equality') sub <- rep(sub, length=length(MSE)) } if (is.null(dim(sub))){ dim(sub) <- dim(MSE) } if (!all(dim(sub)==dim(MSE))) { warning('dim(sub) = ', dim(sub), " != dim(MSE) = ", paste(dim(MSE), collapse=', '), '; forcing equality.') dim(sub) <- dim(MSE) } op <- par(ask=FALSE) on.exit(par(op)) iOnOne <- 0 if (residual) { if(is.null(ylim))ylim <- range(res) if(is.null(ylab))ylab=paste('Residuals for', varnames) for (j in 1:nvar) { for (i in 1:nrepi){ if(iOnOne %in% c(0, nOnOne)[1:(1+ask)]){ if(is.null(xlab))xlab <- argname plot(rng, ylim, type="n", xlab=xlab, ylab=ylab[j], axes=Axes, ...) if(axFun) do.call(axList[[1]], axList[-1]) par(ask=ask) abline(h=0, lty=4, lwd=2) if(nOnOne==1){ { if (is.null(titles)) title(main=casenames[i],sub=sub[i, j]) else title(main=titles[i], sub=sub[i, j]) } } iOnOne <- 0 } iOnOne <- iOnOne+1 lines(argvals, res[,i,j], type=type, col=col[iOnOne], lty=lty[iOnOne], lwd=lwd[iOnOne], cex=cex.pch[iOnOne]) } } } else { if(is.null(ylim))ylim <- range(c(c(y),c(yfine))) varname <- names(fdnames)[[3]] if (is.null(varname)) { if (is.null(fdnames[[3]])) rep("Function Value", nvar) else varname <- fdnames[[3]] } if(is.null(ylab))ylab <- varname if (nvar == 1) { for (i in 1:nrepi) { if(iOnOne %in% c(0, nOnOne)[1:(1+ask)]){ plot(rng, ylim, type="n", xlab=xlab, ylab=ylab, axes=Axes, ...) if(axFun) do.call(axList[[1]], axList[-1]) par(ask=ask) if(nOnOne==1){ if(is.null(titles)) title(main=casenames[i], sub=sub[i, 1]) else title(main=titles[i], sub=sub[i, 1]) } iOnOne <- 0 } iOnOne <- iOnOne+1 points(argvals, y[,i,1], type=type, xlab=xlab, ylab=varnames, col=col[iOnOne], lty=lty[iOnOne], lwd=lwd[iOnOne], cex=cex.pch[iOnOne]) lines(xfine, yfine[,i,1], col=col[iOnOne], lty=lty[iOnOne], lwd=lwd[iOnOne]) } } else { if (ask) { aski = FALSE for (i in 1:nrepi) { par(mfrow=c(nvar,1),ask=aski) for (j in 1:nvar) { plot(rng, ylim, type="n", xlab=xlab,ylab=varnames[j], axes=Axes) if (axFun) do.call(axList[[1]], axList[-1]) if (j == 1) { if (is.null(titles)) { title(paste("Record",i)) } else { title(main=titles[i], sub=sub[i, j]) } } points(argvals, y[,i,j], xlab=xlab, ylab=varnames[j]) lines(xfine, yfine[,i,j]) } aski = TRUE } } else { askj <- FALSE for (j in 1:nvar) { par(mfrow=c(1,1),ask=askj) matplot(argvals, y[,,j], type="p", pch="o", ylim=ylim, xlab=xlab, ylab=varnames[j]) if (axFun) do.call(axList[[1]], axList[-1]) matlines(xfine, yfine[,,j]) askj <- TRUE } } } } invisible(NULL) }
source("ESEUR_config.r") library("mgcv") lee=read.csv(paste0(ESEUR_dir, "regression/lee2006.csv.xz"), as.is=TRUE, sep="\t") lee$sec = 1.1 * lee$cycle * 18 / lee$depth lee$bips = lee$inst / lee$sec l_mod=gam(sqrt(bips) ~ benchmark + fix_lat + s(depth, k=4) + s(gpr_phys, k=10) + s(br_resv, k=6) + s(dmem_lat, k=10) + s(fpu_lat, k=6) + s(l2cache_size, k=5) + s(icache_size, k=3) + s(dcache_size, k=3) + s(depth, by=width, k=6) + s(depth, gpr_phys, k=10) + s(gpr_phys, by=width, k=10) , data=lee ) l_mod_a=gam(sqrt(bips) ~ benchmark + s(depth, k=4) + width + s(gpr_phys, k=10) + s(br_resv, k=6) + s(dmem_lat, k=10) + fix_lat + s(fpu_lat, k=6) + s(l2cache_size, k=5) + s(icache_size, k=3) + s(dcache_size, k=3) + s(gpr_phys, by=width, k=10) , select=TRUE , data=lee ) summary(l_mod_a) anova(l_mod, l_mod_a, test="F")
library(geojsonsf) data <- geojson_sf(geo_melbourne) text_style <- list( id = "text-layer", type = "symbol", source = "melbourne", layout = list( "text-field" = "{SA2_NAME}", "text-size" = 12 ), paint = list( "text-color" = "white" ) ) mapboxer() %>% set_view_state(lng = 144.9624, lat = -37.8105) %>% add_source(data, "melbourne") %>% add_layer(text_style)
trim_labels.item <- function(x,...){ l <- labels(x) lData <- [email protected] [email protected] <- gsub("[-+]?[0-9]+[.] ","",lData) labels(x) <- l x } trim_labels.data.set <- function(x,...){ for(i in seq_along(x)){ [email protected][[i]] <- trim_labels.item([email protected][[i]]) } x } setGeneric("trim_labels", function(x,...)standardGeneric("trim_labels")) setMethod("trim_labels","item.vector",trim_labels.item) setMethod("trim_labels","data.set",trim_labels.data.set)
split_and_join <- function(gbm_data_obj, train_params, rows_in_training, rows_in_fold) { check_if_gbm_data(gbm_data_obj) check_if_gbm_train_params(train_params) if(!is.atomic(rows_in_training) || any(!is.logical(rows_in_training))) { stop("rows_in_training must be a vector of logicals") } if(!is.atomic(rows_in_fold) || any(!is.logical(rows_in_fold)) || (length(rows_in_fold[rows_in_fold==FALSE]) != train_params$num_train_rows)) { stop("rows_in_fold must be a vector of logicals of length the number of training rows") } gbm_data_obj_train <- gbm_data_obj x_valid <- as.data.frame(gbm_data_obj$x[rows_in_training, ,drop=FALSE][rows_in_fold, ,drop=FALSE]) gbm_data_obj_train$x <- as.data.frame(gbm_data_obj$x[rows_in_training, ,drop=FALSE][!rows_in_fold, ,drop=FALSE]) y_valid <- as.data.frame(as.matrix(gbm_data_obj$y)[rows_in_training, ,drop=FALSE][rows_in_fold, ,drop=FALSE]) gbm_data_obj_train$y <- as.data.frame(as.matrix(gbm_data_obj$y)[rows_in_training, ,drop=FALSE][!rows_in_fold, ,drop=FALSE]) offset_valid <- gbm_data_obj$offset[rows_in_training][rows_in_fold] weights_valid <- gbm_data_obj$weights[rows_in_training][rows_in_fold] x_order_valid <- as.data.frame(subset(gbm_data_obj$x_order, rows_in_fold, drop=FALSE)) gbm_data_obj_train$offset <- gbm_data_obj$offset[rows_in_training][!rows_in_fold] gbm_data_obj_train$weights <- gbm_data_obj$weights[rows_in_training][!rows_in_fold] gbm_data_obj_train <- predictor_order(gbm_data_obj_train, train_params) colnames(y_valid) <- colnames(gbm_data_obj_train$y) gbm_data_obj$x <- rbind(gbm_data_obj_train$x, x_valid) gbm_data_obj$y <- rbind(gbm_data_obj_train$y, y_valid) gbm_data_obj$offset <- c(gbm_data_obj_train$offset, offset_valid) gbm_data_obj$weights <- c(gbm_data_obj_train$weights, weights_valid) gbm_data_obj$x_order <- as.matrix(gbm_data_obj_train$x_order) return(gbm_data_obj) }
fit_fun = function(ImpCov,SampCov,Areg,lambda,alpha,type,pen_vec){ m = dim(ImpCov)[1] IntCol = which(colnames(Areg) == "1") if(type=="none"){ fit = log(det(ImpCov)) + trace(SampCov %*% solve(ImpCov)) - log(det(SampCov)) - m } else if(type=="ridge"){ fit = log(det(ImpCov)) + trace(SampCov %*% solve(ImpCov)) - log(det(SampCov)) - m + 2*lambda * sum(pen_vec) } else if(type=="lasso"){ fit = log(det(ImpCov)) + trace(SampCov %*% solve(ImpCov)) - log(det(SampCov)) - m + 2*lambda * sum(abs(pen_vec)) } else if(type=="diff"){ fit = log(det(ImpCov)) + trace(SampCov %*% solve(ImpCov)) - log(det(SampCov)) - m + 2*lambda * sd(Areg[Areg != 0]) } else if(type=="diff_growth"){ fit = log(det(ImpCov)) + trace(SampCov %*% solve(ImpCov)) - log(det(SampCov)) - m + 2*lambda * sum(abs(Areg[,ncol(Areg)] - c(0,1,2,3,0,0,0))) } else if(type=="gLasso"){ imp_pen <- solve(ImpCov) diag(imp_pen) <- 0 imp_pen2 <- sum(abs(imp_pen)) fit = log(det(solve(ImpCov))) + trace(SampCov %*% solve(ImpCov)) + 2*lambda * imp_pen2 } else if(type=="gRidge"){ imp_pen <- solve(ImpCov) diag(imp_pen) <- 0 imp_pen2 <- sum(imp_pen %*% t(imp_pen)) fit = log(det(ImpCov)) + trace(SampCov %*% solve(ImpCov)) + 2*lambda * imp_pen2 } else if(type=="enet"){ fit = log(det(ImpCov)) + trace(SampCov %*% solve(ImpCov)) - log(det(SampCov)) + 2*lambda * sum(alpha*(Areg*Areg) + (1- alpha)*abs(Areg)) } else if(type=="ols_lasso"){ fit = 0.5 * trace((SampCov - ImpCov)^2) + 2*lambda * sum(abs(Areg)) } 0.5*fit }
provide_make_list <- function(type = c("minimal", "testing", "vignette"), prune = TRUE, clean_sink = FALSE) { type <- match.arg(type) ml <- switch(type, testing = , "minimal" = { name <- "Makefile" if (! is.null(type)) name <- paste0(name, "_", type) read_makefile(system.file("templates", name, package = "fakemake"), clean_sink) }, "vignette" = add_log(package_makelist()), throw(paste0("type ", type, " not known!")) ) if (isTRUE(prune)) ml <- prune_list(ml) check_makelist(ml) return(ml) } get_target <- function(makelist, alias) { index <- which(sapply(makelist, function(x) x["alias"] == alias)) return(makelist[[index]]) } remove_target <- function(makelist, target) { ml <- makelist index <- which(sapply(ml, function(x) x[["target"]] == target)) ml[[index]] <- NULL alternative <- paste0("file.path(\"", paste(unlist(strsplit(target, "/")), collapse = "\", \""), "\")") index <- which(sapply(ml, function(x) target %in% x[["prerequisites"]] || alternative %in% x[["prerequisites"]] )) if (length(index) > 0) { for (i in index) { j <- ml[[i]][["prerequisites"]] == alternative | ml[[i]][["prerequisites"]] == target ml[[i]][["prerequisites"]] <- ml[[i]][["prerequisites"]][!j] } } return(ml) } add_target <- function(makelist, target, code, prerequisites = NULL, prerequisite_to = NULL, sink = NULL, alias = sub("\\.(Rout|log)$", "", basename(target))) { ml <- makelist if (!is.null(prerequisite_to)) { if (isTRUE(prerequisite_to)) { add_to_all_targets <- function(x) { if (!identical(x[["target"]], target) && !any(target == x[["prerequisites"]])) { x[["prerequisites"]] <- c(x[["prerequisites"]], target) } return(x) } ml <- lapply(ml, add_to_all_targets) } else { index <- which(sapply(ml, function(x) x[["target"]] == prerequisite_to)) ml[[index]][["prerequisites"]] <- c(ml[[index]][["prerequisites"]], target) } } if (!any(sapply(ml, function(x) x[["target"]] == target))) { a <- list(alias = alias, target = target, code = code, sink = sink, prerequisites = prerequisites ) a <- a[sapply(a, function(x) !is.null(x))] a <- list(a) } else { a <- NULL } return(c(ml, a)) } visualize <- function(make_list, root = NULL) { g <- makelist2igraph(make_list, root = root) if (! is.null(root)) { graphics::plot(g, layout = igraph::layout.reingold.tilford(g, root = root)) } else { graphics::plot(g) } return(invisible(g)) }
test_that("initialize particles for one observation sequence", { expect_equal(particles(n_part = 2), tibble(weight = c(0.5, 0.5))) expect_equal(particles(data.frame(NA)[, FALSE], n_part = 2), tibble(weight = c(0.5, 0.5))) }) test_that("initialize particles for several observation sequences", { expect_equal(particles(data.frame(seq_1 = c(1, 1, 2), seq_2 = c(1, 2, 2)), n_part = 2), tibble(seq_1 = c(1, 1, 1, 1, 2, 2), seq_2 = c(1, 1, 2, 2, 2, 2), weight = c(0.5, 0.5, 0.5, 0.5, 0.5, 0.5))) }) test_that("initialize particles for duplicated observation sequences", { expect_equal(particles(data.frame(seq_1 = c(1, 1, 1), seq_2 = c(1, 2, 2)), n_part = 2), tibble(seq_1 = c(1, 1, 1, 1), seq_2 = c(1, 1, 2, 2), weight = c(0.5, 0.5, 0.5, 0.5))) })
dynamic_template <- function(sg_mail, template_id, template_data, force = FALSE){ if (!sg_mail_chk(sg_mail)) { stop("please check sg_mail class") } if (!force) { if (!template_id_chk(template_id)) { stop("please check template_id value.") } } sg_mail[["template_id"]] <- jsonlite::unbox(template_id) sg_mail$personalizations[["dynamic_template_data"]] <- template_data return(sg_mail) } template_id <- function(sg_mail, template_id, force = FALSE) { if (!sg_mail_chk(sg_mail)) { stop("please check sg_mail class") } if (!force) { if (!template_id_chk(template_id)) { stop("please check template_id value.") } } sg_mail[["template_id"]] <- jsonlite::unbox(template_id) return(sg_mail) } dynamic_template_data <- function(sg_mail, data) { if (!sg_mail_chk(sg_mail)) { stop("please check sg_mail class") } if (is.null(sg_mail[["template_id"]])) { stop("please set template_id first.\n use template_id() function before dynamic_template_data().") } sg_mail$personalizations[["dynamic_template_data"]] <- data return(sg_mail) } template_id_chk <- function(template_id) { grepl( "^d-[a-z0-9]{32}$", template_id ) }
RosenblattStudent <- function(u,rho,nu){ n=dim(u)[1]; d=dim(u)[2] if(d == 2 & length(rho)==1 ){ rho = matrix(c(1, rho, rho, 1),2) } R = matrix(0,n,d) R[,1]=u[,1] for(k in 2:d){ R11 = rho[1:(k-1),1:(k-1)] R21 = rho[k,1:(k-1)] R11inv = solve(R11) B = R21%*%R11inv tu = stats::qt(u, df = nu) x = tu[,1:(k-1)] y = tu[,k] Omega = 1-B%*%R11%*%t(B) mu = x%*%t(B) z = diag( nu + x%*%R11inv%*%t(x))/(nu+k-1) w = c(y-mu)/t(sqrt(Omega %*% z)) R[,k] = stats::pt(w, df= nu+k-1) } return(R) }
expected <- eval(parse(text="FALSE")); test(id=0, code={ argv <- eval(parse(text="list(FALSE, structure(1L, class = c(\"terminal\", \"connection\")), 69)")); .Internal(dput(argv[[1]], argv[[2]], argv[[3]])); }, o=expected);
inspect_space = function(paths,space,clue){ if(clue){ paths = lapply(paths,found_clue,space=space) } else { paths = lapply(paths,found_nothing,space=space) } return(plyr::compact(paths)) } found_clue = function(path,space){ if(!any(path %in% space)) return(NULL) return(path) } found_nothing = function(path,space){ if(any(path %in% space)) return(NULL) return(path) }
INVTR2 <- function(RR2, family, cc) { hh <- function(v, family, cc, z) return( rho(v/z, family=family, cc)*dnorm(v) ) TR2 <- function(R2, family, cc) { a <- Erhobic(family, cc, 1) b <- Erhobic(family, cc, sqrt(1-R2)) return( (b-a)/ (b*(1-a)) ) } Erhobic <- function(family, cc, zz) { if( family == 'bisquare') { dd <- cc * zz a0 <- 2*pnorm(dd)-1 a2 <- (-2)*dd*dnorm(dd)+a0 a4 <- (-2)*(dd^3)*dnorm(dd)+3*a2 a6 <- (-2)*(dd^5)*dnorm(dd)+5*a4 ee <- (a6/dd^6)+(3*a2/dd^2)-(3*a4/dd^4)+1-a0 } else { ee <- 2*(integrate(hh, 0, cc[3]*zz, family=family, cc=cc, z=zz)$value+1-pnorm(cc[3]*zz)) } return( ee ) } ff <- function(x, y, family, cc) return( TR2(x, family, cc) - y ) aa <- TR2(.99999, family, cc) bb <- TR2(.00001, family, cc) if( RR2 > .99 ) R2 <- 1 if ( RR2 < bb ) R2 <- 0 if( (RR2 <= .99) & (RR2 >= bb) ) R2 <- uniroot(ff, c(bb/2, aa+((1-aa)/2)), y=RR2, family=family, cc=cc)$root return(R2) }
calcprob <- function(ipar,theta,model="GRM"){ if (!(model %in% c("GRM","GPCM"))) { warning("model must be either \"GRM\" or \"GPCM\"; will be reset to default") model<-"GRM" } ni<-nrow(ipar) maxCat<-ncol(ipar) NCAT<-apply(ipar,1,function (x) sum(!is.na(x))) DISC<-ipar[,"a"] CB<-ipar[,paste0("cb",1:(maxCat-1)),drop=FALSE] pp<-array(NA,c(length(theta),ni,maxCat)) if (model=="GPCM"){ for (i in 1:ni) { pp[,i,1:(NCAT[i])]<-probgpcm(theta,DISC[i],CB[i,]) } } else { for (i in 1:ni) { pp[,i,1:(NCAT[i])]<-probgrm(theta,DISC[i],CB[i,]) } } return(pp) }
nettskjema_get_data <- function(form_id, information = NULL, use_codebook = TRUE, checkbox_type = c("string", "list", "columns"), checkbox_delim = ";", as_is = FALSE, from_date = "", from_submission = "", incremental = FALSE, token_name = "NETTSKJEMA_API_TOKEN", ...){ if(!use_codebook & !is.null(information)){ warning("Cannot combine `use_codebook` and `information`, setting `information = NULL`", call. = FALSE) information <- NULL } path = file.path("forms", form_id, "submissions") if(from_date != "" ){ from_date <- sprintf("fromDate=%s", from_date) } if(from_submission != "" ){ from_submission <- sprintf("fromSubmissionId=%s", from_submission) } opts <- paste0("?", from_date, from_submission) path_inc <- paste0(path, opts, "fields=submissionId") resp_inc <- nettskjema_api(path_inc, token_name = token_name, ...) api_catch_error(resp_inc) submissionIds <- unlist(content(resp_inc)) if(from_submission != "") submissionIds[submissionIds > from_submission] cat(sprintf("Form %s has %s responses to download.\n",form_id, length(submissionIds))) cont <- grab_data(incremental, submissionIds, token_name, path, opts, ...) if(as_is) return(cont) cb <- nettskjema_get_codebook(form_id = form_id, as_is = TRUE, token_name = token_name, ...) dt <- clean_form_submissions(cont, cb = cb, use_codebook = use_codebook, checkbox_type = checkbox_type, checkbox_delim = checkbox_delim) dt <- mutate(dt, form_id = form_id) if(!is.null(information)){ cb <- nettskjema_get_codebook(form_id = form_id, token_name = token_name) dt <- nettskjema_get_extra(data = dt, codebook = cb, information = information, use_codebook = use_codebook) } dt <- dt[,order(colnames(dt))] relocate(dt, form_id, submission_id) } nettskjema_get_extra <- function(data, codebook, information, use_codebook = TRUE, ...){ if(missing(information)){ stop("No argument passed to `information`, no extra data to add", call. = FALSE) } information <- validate_information(information) type <- ifelse(use_codebook, "question_codebook", "question") type_answ <- ifelse(use_codebook, "answer_codebook", "answer_option") cb <- codebook[!is.na(codebook[,type_answ]),] cb <- cb[!is.na(cb[,"question_order"]),] questions <- unname(unlist(unique(cb[,type]))) if(any(is.na(questions))) stop("The codebook is not set up correctly, or some questions do not have text.\n", "Adding extra information from the codebook is not possible in this situation.\n", "Try filling out the codebook, before downloading the data once more.\n", call. = FALSE) get_extra_data(questions, col, type, type_answ, data, information, cb) }
context("zeroin.h unit tests") expect_equal(hesim:::test_zeroin(), 1/3)
context("Just testing ENUCompositon functionality") test_that("Check whether ENUCompositon_DNA without overLAp works properly",{ enhancedNucCompos<-as.vector(ENUComposition_DNA(seqs = "ATAATCGCC",winSize = 3,overLap = FALSE)) nuc<-c("A","C","G","T") vect1<-vector(length = 4,mode = "numeric") names(vect1)<-nuc vect1["A"]=2 vect1["T"]=1 vect2<-vector(length = 4,mode = "numeric") names(vect2)<-nuc vect2["A"]=1 vect2["T"]=1 vect2["C"]=1 vect3<-vector(length = 4,mode = "numeric") names(vect3)<-nuc vect3["G"]=1 vect3["C"]=2 expected<-c(vect1,vect2,vect3) names(expected)<-NULL expect_equal(enhancedNucCompos,expected) }) test_that("Check whether ENUCompositon_DNA with overLAp works properly",{ enhancedNucCompos<-as.vector(ENUComposition_DNA(seqs = "ATAATCGCC",winSize = 7,overLap = TRUE)) nuc<-c("A","C","G","T") vect1<-vector(length = 4,mode = "numeric") names(vect1)<-nuc vect1["A"]=3 vect1["T"]=2 vect1["C"]=1 vect1["G"]=1 vect2<-vector(length = 4,mode = "numeric") names(vect2)<-nuc vect2["A"]=2 vect2["T"]=2 vect2["C"]=2 vect2["G"]=1 vect3<-vector(length = 4,mode = "numeric") names(vect3)<-nuc vect3["A"]=2 vect3["T"]=1 vect3["C"]=3 vect3["G"]=1 expected<-c(vect1,vect2,vect3) names(expected)<-NULL expect_equal(enhancedNucCompos,expected) }) test_that("Check whether ENUCompositon_DNA without overLAp works properly",{ enhancedNucCompos<-as.vector(ENUComposition_DNA(seqs = "ATAATCGC",winSize = 3,overLap = FALSE)) nuc<-c("A","C","G","T") vect1<-vector(length = 4,mode = "numeric") names(vect1)<-nuc vect1["A"]=2 vect1["T"]=1 vect2<-vector(length = 4,mode = "numeric") names(vect2)<-nuc vect2["A"]=1 vect2["T"]=1 vect2["C"]=1 vect3<-vector(length = 4,mode = "numeric") names(vect3)<-nuc vect3["G"]=1 vect3["C"]=1 expected<-c(vect1,vect2,vect3) names(expected)<-NULL expect_equal(enhancedNucCompos,expected) }) test_that("Check whether ENUCompositon_RNA without overLAp works properly",{ enhancedNucCompos<-as.vector(ENUComposition_RNA(seqs = "AUAAUCGCC",winSize = 3,overLap = FALSE)) nuc<-c("A","C","G","U") vect1<-vector(length = 4,mode = "numeric") names(vect1)<-nuc vect1["A"]=2 vect1["U"]=1 vect2<-vector(length = 4,mode = "numeric") names(vect2)<-nuc vect2["A"]=1 vect2["U"]=1 vect2["C"]=1 vect3<-vector(length = 4,mode = "numeric") names(vect3)<-nuc vect3["G"]=1 vect3["C"]=2 expected<-c(vect1,vect2,vect3) names(expected)<-NULL expect_equal(enhancedNucCompos,expected) })
library(pmledecon) sz=esz=30 set.seed(45217) truth=rnorm(sz,0,1) error=rnorm(esz,0,2) ob=truth+error error1=rnorm(esz,0,2) est=pmledecon(ob,error1) plot(density(ob,n=1000),col="red",lwd=2,lty=3,type="l",ylim=c(0,0.4), xlab="",main="unknown error") lines(seq(-10,10,length.out=1000),dnorm(seq(-10,10,length.out=1000),0,1), lwd=2,lty=4,col="green") lines(est$sup,est$f,lwd=2) legend("topright", lty=c(1,4,3),col=c("black","green","red"),lwd=2, legend=c("Pmle","true density","kernel density of data"))