code
stringlengths
1
13.8M
cen1way <- function(y1,y2, grp,mcomp.method = "BH",printstat=TRUE) { yname <- deparse(substitute(y1)) gname <- deparse(substitute(grp)) rho=1 fconst <- max(y1) + 1 flip <- fconst - y1 detect <- as.logical(1 - as.integer(y2)) Factor <- as.factor(grp) df <- length(levels(Factor))-1 CensData <- data.frame (flip, detect, Factor) Cen.stats <- matrix(0, nrow=df+1, ncol = 5) y.surv <- Surv(CensData$flip, CensData$detect, type="right") y.out<- survdiff(y.surv ~ CensData$Factor, rho=rho) pval = pchisq(y.out$chisq, df, lower.tail = FALSE) groupnames <- as.character(levels(Factor)) for (i in 1:nlevels(Factor)) { y1gp <- y1[Factor==groupnames[i]] y2gp <- y2[Factor==groupnames[i]] Cstats <- suppressWarnings(cfit(y1gp, as.logical(y2gp), printstat=FALSE, Cdf = FALSE)) Cstats <- Cstats[c(1:6)] Cstats <- Cstats[-3] Cstats <- data.frame(Cstats) Cstats$grp <- groupnames[i] rownames(Cstats) <-NULL if (i ==1) {Cen.stats <- Cstats cnames <- colnames(Cstats)}else {Cen.stats <- suppressWarnings(rbind(Cen.stats, Cstats))} if(sum(as.logical(y2gp))==0){warning("One or more group(s) do not have censored data.",call.=F)} } Cen.stats <- Cen.stats[,c(6,1:5)] colnames(Cen.stats) <- cnames[c(6,1:5)] if(printstat==TRUE){ print.data.frame(Cen.stats, print.gap = 3) cat('\n'," Oneway Peto-Peto test of CensData:", yname, " by Factor:", gname, '\n', " Chisq =", signif(y.out$chisq, 4), " on", df, "degrees of freedom", " p =", signif(pval,3), '\n') if (df >1) {mcomp <- pairwise_survdiff(Surv(flip, detect) ~ Factor, data=CensData, p.adjust.method = mcomp.method, rho=rho) print(mcomp)} } PetoPeto<-list(data.name=paste(yname, " by Factor:", gname,"\n"), ChiSq=signif(y.out$chisq, 4),df=df,p.value=signif(pval,3)) if(df>1){mcomp=mcomp}else{mcomp=NA} x<-list(SummaryStats=Cen.stats, PetoPeto=PetoPeto, mcomp=mcomp) invisible(x) }
has_component_in_attribute <- function(dend, component, the_attrib = "edgePar", ...) { if (!is.dendrogram(dend)) { return(FALSE) } list_of_names <- dend %>% get_nodes_attr(the_attrib, simplify = FALSE) %>% lapply(names) has_component_fun <- function(node_names) any(node_names %in% component) has_component <- list_of_names %>% lapply(has_component_fun) %>% unlist() %>% any() has_component } has_edgePar <- function(dend, component, the_attrib = "edgePar", ...) { has_component_in_attribute(dend, component, the_attrib, ...) } has_nodePar <- function(dend, component, the_attrib = "nodePar", ...) { has_component_in_attribute(dend, component, the_attrib, ...) }
getnumbs <- function(tree){ tipdepth <- age.tips(tree) branching <- branching.times.complete(tree) numbs <- numbspecies(tipdepth,branching) event <- c(0, 0, 0) numbs <- rbind(numbs,event) numbs }
baumwelchcont <- function(hmm) { NR<-nrow(hmm$Parameters) no<-length(hmm$Observations) hmm$B[,1]<-dnorm((hmm$Observations), mean=(hmm$Parameters[NR,7]), sd=sqrt(hmm$Parameters[NR,9])) hmm$B[,2]<-dnorm((hmm$Observations), mean=(hmm$Parameters[NR,8]), sd=sqrt(hmm$Parameters[NR,10])) Alphas<-matrix(NA, nrow=no, ncol=2) Alphas[1,1]<-(hmm$Parameters[NR,1])*hmm$B[1,1] Alphas[1,2]<-(hmm$Parameters[NR,2])*hmm$B[1,2] for(i in 2: (no)) { Alphas[i,1]<-(Alphas[(i-1),1]*(hmm$Parameters[NR,3])+Alphas[(i-1),2]*(hmm$Parameters[NR,5]))*hmm$B[i,1] Alphas[i,2]<-(Alphas[(i-1),1]*(hmm$Parameters[NR,4])+Alphas[(i-1),2]*(hmm$Parameters[NR,6]))*hmm$B[i,2] } Betas<-matrix(NA, nrow=no, ncol=2) Betas[(no),1]<-1 Betas[(no),2]<-1 for(j in ((no)-1):1) { Betas[j,1]<-(Betas[(j+1),1]*hmm$B[(j+1),1]*(hmm$Parameters[NR,3])+Betas[(j+1),2]*hmm$B[(j+1),2]*(hmm$Parameters[NR,4])) Betas[j,2]<-(Betas[(j+1),1]*hmm$B[(j+1),1]*(hmm$Parameters[NR,5])+Betas[(j+1),2]*hmm$B[(j+1),2]*(hmm$Parameters[NR,6])) } Preeps<-matrix(NA, nrow=((no)-1), ncol=5) for(i in 1:((no)-1)) { Preeps[i,1]<-Alphas[i,1]*(hmm$Parameters[NR,3])*hmm$B[i+1,1]*Betas[i+1,1] } for(i in 1:((no)-1)) { Preeps[i,2]<-Alphas[i,1]*(hmm$Parameters[NR,4])*hmm$B[i+1,2]*Betas[i+1,2] } for(i in 1:((no)-1)) { Preeps[i,3]<-Alphas[i,2]*(hmm$Parameters[NR,5])*hmm$B[i+1,1]*Betas[i+1,1] } for(i in 1:((no)-1)) { Preeps[i,4]<-Alphas[i,2]*(hmm$Parameters[NR,6])*hmm$B[i+1,2]*Betas[i+1,2] } Preeps[,5]<-Preeps[,1]+Preeps[,2]+Preeps[,3]+Preeps[,4] Xis<-matrix(NA, nrow=((no)-1), ncol=4) Xis<-Preeps[,1:4]/Preeps[,5] Gammas<-matrix(NA, nrow=((no)-1), ncol=2) Gammas[,1]<-Xis[,1]+Xis[,2] Gammas[,2]<-Xis[,3]+Xis[,4] hmm$Results[NR,1]<-Alphas[(no),1]+Alphas[(no),2] hmm$Results[NR,2]<-(Betas[1,1]*(hmm$Parameters[NR,1])*hmm$B[1,1])+(Betas[1,2]*(hmm$Parameters[NR,2])*hmm$B[1,2]) hmm$Results[NR,3]<-Preeps[1,5] hmm$Results[NR,4]<- -2*log(hmm$Results[NR,1])+20 hmm$Results[NR,5]<- -2*log(hmm$Results[NR,1])+20*log(no) hmm$Results[NR,6]<- -2*log(hmm$Results[NR,1])+20*log(log(no)) newrowres<-matrix(NA, ncol=6, nrow=1) hmm$Results<-rbind(hmm$Results, newrowres) newrowpar<-matrix(NA, ncol=10, nrow=1) newrowpar[1]<-Gammas[1,1] newrowpar[2]<-Gammas[1,2] newrowpar[3]<-(sum(Xis[,1]))/sum(Gammas[,1]) newrowpar[4]<-(sum(Xis[,2]))/sum(Gammas[,1]) newrowpar[5]<-(sum(Xis[,3]))/sum(Gammas[,2]) newrowpar[6]<-(sum(Xis[,4]))/sum(Gammas[,2]) newrowpar[7]<-sum(Gammas[,1]*hmm$Observations[-(no)]) / sum(Gammas[,1]) newrowpar[8]<-sum(Gammas[,2]*hmm$Observations[-(no)]) / sum(Gammas[,2]) newrowpar[9]<-sum(Gammas[,1] * (hmm$Observations[-(no)] - newrowpar[7]) * (hmm$Observations[-(no)] - newrowpar[7]) ) / sum(Gammas[,1]) newrowpar[10]<-sum(Gammas[,2] * (hmm$Observations[-(no)] - newrowpar[8]) * (hmm$Observations[-(no)] - newrowpar[8]) ) / sum(Gammas[,2]) hmm$Parameters<-rbind(hmm$Parameters, newrowpar) return(hmm) }
DA_PF <- function(Obs, Qsim, States, Param, StateNames, NbMbr, StatePert = NULL, VarThr) { NbState <- length(StateNames) MbrNames <- sprintf("Mbr_%s", seq_len(NbMbr)) Weights <- rep(0, times = NbMbr) names(Weights) <- MbrNames Indices <- rep(NA, times = NbMbr) CurrentState <- list() CurrentStatePert <- list() VarObs <- max(VarThr^2, (0.1*Obs)^2) Innov <- Obs - Qsim names(Innov) <- MbrNames Weights <- dnorm(Innov, mean = 0, sd = sqrt(VarObs)) Weights <- Weights/sum(Weights) if (!all(is.finite(Weights))) { Weights <- rep(1/NbMbr, times = NbMbr) } CdfW <- cumsum(Weights) A <- CdfW[1] B <- min(1, A + (1/(NbMbr+1))) Urand0 <- A + ((B - A)*(runif(1))) StepUrand <- (1-Urand0)/NbMbr Urand <- seq(from = Urand0, length.out = NbMbr, by = StepUrand) Indices <- findInterval(Urand, vec = CdfW, rightmost.closed = TRUE) + 1 if (!all(is.finite(Indices))) { Weights <- rep(1/NbMbr, times = NbMbr) CdfW <- cumsum(Weights) A <- CdfW[1] B <- min(1, A + (1/(NbMbr+1))) Urand0 <- A + ((B - A)*(runif(1))) StepUrand <- (1-Urand0)/NbMbr Urand <- seq(from = Urand0, length.out = NbMbr, by = StepUrand) Indices <- findInterval(Urand, vec = CdfW, rightmost.closed = TRUE) + 1 } Repeats <- as.data.frame(table(Indices)) if (!is.null(StatePert)) { EnsState <- matrix(data = NA, nrow = NbState, ncol = NbMbr, dimnames = list(StateNames, MbrNames)) EnsState["Prod", ] <- sapply(seq_along(States), function(x) States[[x]]$Store$Prod) EnsState["Rout", ] <- sapply(seq_along(States), function(x) States[[x]]$Store$Rout) EnsState["UH2" , ] <- sapply(seq_along(States), function(x) States[[x]]$UH$UH2[1L]) if ("UH1" %in% StateNames) { EnsState["UH1" , ] <- sapply(seq_along(States), function(x) States[[x]]$UH$UH1[1L]) } MuState <- rep(0, times = NbState) names(MuState) <- StateNames SdState <- pmin(3, pmax(1.2, apply(EnsState[, as.numeric(as.character(Repeats$Indices)), drop = FALSE], MARGIN = 1, sd, na.rm = TRUE), na.rm = TRUE)) names(SdState) <- StateNames } for (iPart in seq_len(nrow(Repeats))) { IndexParticle <- as.numeric(as.character(Repeats$Indices[iPart])) RepParticle <- as.numeric(as.character(Repeats$Freq[iPart])) TempState <- rep(States[IndexParticle], times = RepParticle) names(TempState) <- sprintf("Rep%s_Part%s", seq_len(RepParticle), IndexParticle) if (!is.null(StatePert)) { IndPert <- as.numeric(StateNames %in% StatePert) TempStatePert <- TempState if (RepParticle > 1) { StateRep <- matrix(data = NA, nrow = NbState, ncol = RepParticle, dimnames = list(StateNames, sprintf("Rep_%s", seq_len(RepParticle)))) StateRep["Prod", ] <- rep(States[[IndexParticle]]$Store$Prod, RepParticle) StateRep["Rout", ] <- rep(States[[IndexParticle]]$Store$Rout, RepParticle) StateRep["UH2" , ] <- rep(States[[IndexParticle]]$UH$UH2[1L], RepParticle) if ("UH1" %in% StateNames) { StateRep["UH1", ] <- rep(States[[IndexParticle]]$UH$UH1[1L], RepParticle) } NoiseState <- matrix(data = rnorm(RepParticle*NbState, mean = MuState, sd = SdState), nrow = NbState, ncol = RepParticle, byrow = FALSE, dimnames = list(StateNames, sprintf("Rep_%s", seq_len(RepParticle)))) NoiseState[IndPert == 0, ] <- 0 StateRepPert <- StateRep + NoiseState StateRepPert["Prod", StateRepPert["Prod", ] > Param[1]] <- Param[1] StateRepPert["Rout", StateRepPert["Rout", ] > Param[3]] <- Param[3] for (iRep in seq_len(RepParticle)) { TempStatePert[[iRep]]$Store$Prod <- StateRepPert["Prod", iRep] TempStatePert[[iRep]]$Store$Rout <- StateRepPert["Rout", iRep] TempStatePert[[iRep]]$UH$UH2[1L] <- StateRepPert["UH2" , iRep] if ("UH1" %in% StateNames) { TempStatePert[[iRep]]$UH$UH1[1L] <- StateRepPert["UH1", iRep] } } } CurrentStatePert <- c(CurrentStatePert, TempStatePert) } CurrentState <- c(CurrentState, TempState) rm(TempState) if (exists("TempStatePert")) { rm(TempStatePert) } } EnsStatePf <- CurrentState if (!is.null(StatePert)) { EnsStatePert <- CurrentStatePert } ans <- list(EnsStatePf = EnsStatePf) if (!is.null(StatePert)) { ans$EnsStatePert <- EnsStatePert } return(ans) }
plot.snowboot <- function(x, k = NULL, plotmu = TRUE, plotlegend = TRUE, col0 = "gray50", lwd0 = 1, colpt = "royalblue3", lwdpt = 2, pchpt = 4, coli = "palegreen3", colibg = "palegreen", length = 0.1, boxwex = 0.4, legendargs = list(x = "topright", cex = 0.9, bty = "n"), las = 1, ...){ if (is.null(k)) { k <- 0:(length(x$fk) - 1) } k <- sort(k) k <- k[k <= (length(x$fk) - 1)] if (length(k) == 0) {stop(paste("Specify k within the range from 0 to", (length(x$fk) - 1)))} ind <- is.element(0:(length(x$fk) - 1), k) YLIM <- c(0, max(x$fk[ind])) if (plotmu) YLIM[1] = -YLIM[2]/4 plotbp <- plotci <- FALSE inputlist <- names(x) legtext <- c("Point estimate") legcol <- c(colpt) legpch <- c(pchpt) leglwd <- c(lwdpt) if (is.element("fkb", inputlist)) { plotbp <- TRUE legtext <- c("Point estimate", "Bootstrapped estimates") legcol <- c(colpt, coli) legpch <- c(pchpt, 15) leglwd <- c(lwdpt, NA) YLIM[2] <- max(x$fkb[ind,]) } if (is.element("fk_ci", inputlist)) { plotci <- TRUE legtext <- c("Point estimate", paste(100*x$prob, "% confidence interval", sep = "")) legcol <- c(colpt, coli) legpch <- c(pchpt, NA) YLIM[2] <- max(x$fk_ci[,ind]) } plot(k, x$fk[ind], ylim = YLIM, las = las, type = "n", yaxt = "n", xlab = "k", ylab = "f(k)", ...) tmp <- axTicks(2) axis(2, at = tmp[tmp >= 0], las = las) abline(h = 0, col = col0, lwd = lwd0) if (plotbp) { if (sum(ind) == 1) { tmp <- x$fkb[ind,] } else { tmp <- t(x$fkb[ind,]) } boxplot(tmp, at = k, add = TRUE, xaxt = "n", yaxt = "n", boxwex = boxwex, col = colibg, border = coli) if (plotmu) { boxplot(x$mub, at = YLIM[1]/1.5, add = TRUE, xaxt = "n", yaxt = "n", boxwex = boxwex/4, col = colibg, border = coli, horizontal = TRUE) } } if (plotci) { suppressWarnings( arrows(x0 = k, y0 = x$fk_ci[1, ind], y1 = x$fk_ci[2, ind], length = length, code = 3, col = coli, angle = 90, lwd = lwdpt) ) if (plotmu) { arrows(x0 = x$mu_ci[1], y0 = YLIM[1]/1.5, x1 = x$mu_ci[2], length = length, code = 3, col = coli, angle = 90, lwd = lwdpt) } } lines(k, x$fk[ind], type = "o", pch = pchpt, lwd = lwdpt, col = colpt) if (plotmu) { axis(2, at = YLIM[1]/1.5, labels = expression(mu), las = las, cex.axis = 1.5) points(x$mu, YLIM[1]/1.5, pch = pchpt, lwd = lwdpt, col = colpt) } if (plotlegend) { do.call(legend, append(list(legend = legtext, col = legcol, pch = legpch, lwd = leglwd), legendargs)) } }
`MyReportEnd` <- function (file = "report.html" ) { cat("\n<hr size=1></body></html>", file = file, append = TRUE) }
"Woodsdat"
VP.CP.ZP.un <- function (Z_mat, fixed_effects, control) { persistence <- control$persistence gr.eta <- function(eta, X, Y, Z, ybetas, R_inv, G.inv) { gr.y <- crossprod(Z, R_inv) %*% (Y - X %*% ybetas - Z %*% eta) gr.p.eta <- -G.inv %*% eta - as.vector(gr.y + gr.p.eta) } H.eta <- function(G.inv, Z, R_inv) { h.eta <- G.inv h.y <- crossprod(Z, R_inv) %*% Z forceSymmetric(h.eta + h.y) } ltriangle <- function(x) { if (!is.null(dim(x)[2])) { resA <- as.vector(x[lower.tri(x, diag = TRUE)]) resA } else { nx <- length(x) d <- 0.5 * (-1 + sqrt(1 + 8 * nx)) resB <- .symDiagonal(d) resB[lower.tri(resB, diag = TRUE)] <- x if (nx > 1) { resB <- resB + t(resB) - diag(diag(resB)) } as(resB, "sparseMatrix") } } reduce.G <- function(G, nyear, nteacher) { if (!is.null(dim(G)[2])) { temp_mat <- G index1 <- 0 resA <- c(NULL) for (j in 1:nyear) { temp_mat_j <- as.numeric(temp_mat[(index1 + 1):(index1 + 1), (index1 + 1):(index1 + 1)]) resA <- c(resA, temp_mat_j) index1 <- index1 + nteacher[j] } resA } else { resB <- Matrix(0, 0, 0,doDiag=FALSE) for (j in 1:nyear) { resB <- bdiag(resB, suppressMessages(G[j] * Diagonal(nteacher[j]))) } rm(j) resB } } update.eta <- function(X, Y, Z, R_inv, ybetas, G, nyear, cons.logLik, Ny, nstudent, n_eta) { G.chol <- chol(G) G.inv <- chol2inv(G.chol) H <- symmpart(H.eta(G.inv, Z, R_inv)) chol.H <- chol(H) H.inv <- chol2inv(chol.H) c.temp <- crossprod(X, R_inv) %*% Z c.1 <- rbind(crossprod(X, R_inv) %*% X, t(c.temp)) c.2 <- rbind(c.temp, H) C_inv <- cbind(c.1, c.2) chol.C_inv <- chol(forceSymmetric(symmpart(C_inv))) cs <- chol2inv(chol.C_inv) C12 <- as.matrix(cs[1:n_ybeta, (n_ybeta + 1):ncol(cs)]) C.mat <- cs[-c(1:n_ybeta), -c(1:n_ybeta)] betacov <- as.matrix(cs[c(1:n_ybeta), c(1:n_ybeta)]) if (control$REML) { var.eta <- C.mat } else { var.eta <- H.inv } sign.mult <- function(det) { det$modulus * det$sign } eta <- H.inv %*% as.vector(crossprod(Z, R_inv) %*% (Y - X %*% ybetas)) log.p.eta <- -(n_eta/2) * log(2 * pi) - sign.mult(determinant(G.chol)) - 0.5 * crossprod(eta, G.inv) %*% eta log.p.y <- -(Ny/2) * log(2 * pi) + sign.mult(determinant(chol(R_inv))) - 0.5 * crossprod(Y - X %*% ybetas - Z %*% eta, R_inv) %*% (Y - X %*% ybetas - Z %*% eta) res <- var.eta if (control$REML) { attr(res, "likelihood") <- as.vector(cons.logLik + log.p.eta + log.p.y - sign.mult(determinant(chol.C_inv))) } else { attr(res, "likelihood") <- as.vector(cons.logLik + log.p.eta + log.p.y - sign.mult(determinant(chol.H))) } attr(res, "eta") <- eta attr(res, "betacov") <- betacov attr(res, "C12") <- C12 attr(res, "h.inv") <- H.inv res } Score <- function(thetas, eta = eta.hat, ybetas, X, Y, Z, year.count, n_ybeta, nyear, n_eta, nstudent, nteacher, Kg, cons.logLik, con = control, mis.list, pattern.parmlist2, pattern.count, pattern.length, pattern.Rtemplate, pattern.diag, pattern.key, Ny, pattern.sum = pattern.sum, persistence, P, alpha.diag, nalpha, alpha) { n_Rparm <- nyear * (nyear + 1) / 2 G <- thetas[(n_Rparm + 1):(n_Rparm + nyear)] G <- reduce.G(G = G, nyear = nyear, nteacher = nteacher) if (persistence == "VP") { alpha.parm <- thetas[(n_Rparm + nyear + 1):length(thetas)] alpha[!((1:nalpha) %in% alpha.diag)] <- alpha.parm Z <- Matrix(0, nrow(Z_mat), nteach_effects,doDiag=FALSE) for (i in 1:nalpha) { comp <- which(tril(ltriangle(1:nalpha)) == i, arr.ind = TRUE) Z <- Z + alpha[i] * P[[comp[1]]][[comp[2]]] } if (!huge.flag) { Z.dense <- as.matrix(Z) } for (p in unique(Z_mat$pat)) { if (!huge.flag) { Z.p[[p]] <- Z.dense[pat[[p]], , drop = FALSE] } else{ Z.p[[p]] <- Z[pat[[p]], , drop = FALSE] } } } R_i <- ltriangle(as.vector(thetas[1:n_Rparm])) R_i.parm <- as.vector(thetas[1:n_Rparm]) if (length(mis.list) > 0) { R <- symmpart(suppressMessages(kronecker(suppressMessages( Diagonal(nstudent) ), R_i)[-mis.list,-mis.list])) R_inv <- solve(R) } else { R <- symmpart(suppressMessages(kronecker(suppressMessages( Diagonal(nstudent) ), R_i))) R_inv <- symmpart(suppressMessages(kronecker( suppressMessages(Diagonal(nstudent)), chol2inv(chol(R_i)) ))) } new.eta <- update.eta( X = X, Y = Y, Z = Z, R_inv = R_inv, ybetas = ybetas, G = G, nyear = nyear, cons.logLik = cons.logLik, Ny = Ny, nstudent = nstudent, n_eta = n_eta ) eta.hat <- attr(new.eta, "eta") var.eta.hat <- new.eta temp_mat <- var.eta.hat + tcrossprod(eta.hat, eta.hat) pattern.sum <- list() for (p in unique(Z_mat$pat)) { pattern.sum[[p]] <- R_mstep2( invsqrtW_ = as.matrix(rep(1, Ny)), JYp_ = as.matrix(Y.p[[p]]), loopsize_ = pattern.count[[p]] / pattern.length[[p]], patternlength_ = pattern.length[[p]], rownumber_ = as.matrix(Y.p.rownumber[[p]]), ybetas_ = as.matrix(ybetas), etahat_ = as.matrix(eta.hat), tempmatR_ = as.matrix(temp_mat), JXpi_ = as.matrix(X.p[[p]]@i), JXpp_ = as.matrix(X.p[[p]]@p), JXpx_ = as.matrix(X.p[[p]]@x), JXpdim_ = as.matrix(X.p[[p]]@Dim), JZpi_ = as.matrix(Z.p[[p]]@i), JZpp_ = as.matrix(Z.p[[p]]@p), JZpx_ = as.matrix(Z.p[[p]]@x), JZpdim_ = as.matrix(Z.p[[p]]@Dim) ) } score.R <- -pattern.f.score( R_i.parm, nyear, pattern.parmlist2, pattern.count, pattern.length, pattern.Rtemplate, pattern.diag, pattern.key, pattern.sum ) temp_mat <- G gam_t <- list() sv_gam_t <- list() index1 <- 0 for (j in 1:nyear) { gam_t[[j]] <- matrix(0, Kg[j], Kg[j]) temp_mat_j <- temp_mat[(index1 + 1):(index1 + nteacher[j] * Kg[j]), (index1 + 1):(index1 + nteacher[j] * Kg[j])] gam_t[[j]] <- temp_mat_j[1:Kg[j], 1:Kg[j]] sv_gam_t[[j]] <- chol2inv(chol(gam_t[[j]])) index1 <- index1 + nteacher[j] * Kg[j] } rm(j) score_mat <- var.eta.hat + tcrossprod(eta.hat, eta.hat) gam_t_sc <- list() index1 <- 0 score.G <- Matrix(0, 0, 0,doDiag=FALSE) for (j in 1:nyear) { gam_t_sc[[j]] <- matrix(0, Kg[j], Kg[j]) score_mat_j <- score_mat[(index1 + 1):(index1 + nteacher[j] * Kg[j]), (index1 + 1):(index1 + nteacher[j] * Kg[j])] index2 <- c(1) for (k in 1:nteacher[j]) { gam_t_sc[[j]] <- gam_t_sc[[j]] + score_mat_j[(index2):(index2 + Kg[j] - 1), (index2):(index2 + Kg[j] - 1)] index2 <- index2 + Kg[j] } index1 <- index1 + nteacher[j] * Kg[j] der <- -0.5 * (nteacher[j] * sv_gam_t[[j]] - sv_gam_t[[j]] %*% gam_t_sc[[j]] %*% sv_gam_t[[j]]) if (is.numeric(drop(sv_gam_t[[j]]))) { score.eta.t <- der } else { score.eta.t <- 2 * der - diag(diag(der)) } for (k in 1:nteacher[j]) { score.G <- bdiag(score.G, score.eta.t) } } alpha.parm <- alpha[!((1:nalpha) %in% alpha.diag)] score.a <- alpha.score(alpha.parm, alpha, temp_mat = score_mat, nalpha, alpha.diag, P, R_inv, eta.hat, ybetas, X) rm(j, k) if (persistence == "CP" | persistence == "ZP") { -c(score.R, reduce.G( G = score.G, nyear = nyear, nteacher = nteacher )) } else if (persistence == "VP") { -c(score.R, reduce.G( G = score.G, nyear = nyear, nteacher = nteacher ), score.a) } } update.ybeta <- function(X, Y, Z, R_inv, eta.hat) { A.ybeta <- crossprod(X, R_inv) %*% X B.ybeta <- crossprod(X, R_inv) %*% (Y - Z %*% eta.hat) as.vector(solve(A.ybeta, B.ybeta)) } bin2dec <- function(s) sum(s * 2 ^ (rev(seq_along(s)) - 1)) dec2bin <- function(s) { L <- length(s) maxs <- max(s) digits <- floor(logb(maxs, base = 2)) + 1 res <- array(NA, dim = c(L, digits)) for (i in 1:digits) { res[, digits - i + 1] <- (s %% 2) s <- (s %/% 2) } if (L == 1) res[1,] else res } alpha.score <- function(alpha.parm, alpha, temp_mat, nalpha, alpha.diag, P, R_inv, eta.hat, ybetas, X) { score.a <- c(NULL) alpha.s <- alpha alpha.s[!((1:nalpha) %in% alpha.diag)] <- alpha.parm alpha.set <- (1:nalpha)[!((1:nalpha) %in% alpha.diag)] Z.a <- Matrix(0, nrow(Z_mat), nteach_effects,doDiag=FALSE) for (i in 1:nalpha) { comp <- which(tril(ltriangle(1:nalpha)) == i, arr.ind = TRUE) Z.a <- Z.a + alpha.s[i] * P[[comp[1]]][[comp[2]]] } for (i in alpha.set) { comp <- which(tril(ltriangle(1:nalpha)) == i, arr.ind = TRUE) score.a <- c(score.a, as.numeric((t(Y) - t(ybetas) %*% t(X)) %*% R_inv %*% P[[comp[1]]][[comp[2]]] %*% eta.hat - sum(diag( crossprod(Z.a, R_inv %*% P[[comp[1]]][[comp[2]]] %*% temp_mat) )))) } score.a } pattern.f.score <- function(R_i.parm, nyear, pattern.parmlist2, pattern.count, pattern.length, pattern.Rtemplate, pattern.diag, pattern.key, pattern.sum) { R_i <- as.matrix(ltriangle(as.vector(R_i.parm))) pattern.score <- numeric(nyear / 2 * (nyear + 1)) for (p in nonempty.patterns) { pattern.y <- solve(pattern.f.R(R_i, p, nyear, pattern.key)) YSY <- pattern.y %*% pattern.sum[[p]] %*% pattern.y PCL <- pattern.countoverlength[[p]] for (r.parm in 1:(nyear / 2 * (nyear + 1))) { if (is.null(pat.coord <- pat.coord.guide[[r.parm]][[p]])) next pattern.yc <- pattern.y[pat.coord] pattern.score[r.parm] <- pattern.score[r.parm] - (PCL * pattern.yc - YSY[pat.coord]) } } pattern.score[1:(nyear / 2 * (nyear + 1)) %in% pattern.diag] <- 0.5 * pattern.score[1:(nyear / 2 * (nyear + 1)) %in% pattern.diag] - pattern.score } pattern.f.R <- function(R, p, nyear, pattern.key) { R[pattern.key[p,] * (1:nyear), pattern.key[p,] * (1:nyear), drop = FALSE] } Z_mat$year <- as.numeric(Z_mat$year) nyear <- length(unique(Z_mat$year)) Z_mat$mis <- rep(0, dim(Z_mat)[1]) student_list <- unique(Z_mat$student) Z_mat[is.na(Z_mat$y),]$mis <- rep(1, dim(Z_mat[is.na(Z_mat$y),])[1]) for (g in 1:nyear) { mis_stu <- student_list[!(student_list %in% unique(Z_mat[Z_mat$year == g,]$student))] le <- length(mis_stu) if (le > 0) { temp.exp <- Z_mat[1:le,] temp.exp$year <- rep(g, le) temp.exp$mis <- rep(1, le) temp.exp$student <- mis_stu temp.exp$teacher <- rep(NA, le) temp.exp$y <- rep(NA, le) Z_mat <- rbind(Z_mat, temp.exp) } } rm(g, le) Z_mat.full <- Z_mat Z_mat <- Z_mat[!is.na(Z_mat$y),] Z_mat.full <- Z_mat.full[which((Z_mat.full$student %in% Z_mat$student)),] Ny <- sum(Z_mat$mis == 0) nstudent <- length(unique(Z_mat$student)) year.count <- numeric(nyear) for (j in 1:nyear) { year.count[j] <- sum(Z_mat[Z_mat$year == j,]$mis == 0) } rm(j) RE_s_start_pos <- 1 Kg <- rep(1, nyear) Z_mat <- Z_mat[order(Z_mat$year, Z_mat$teacher),] Z_mat.full <- Z_mat.full[order(Z_mat.full$year, Z_mat.full$teacher),] na_list <- grep("^NA", Z_mat$teacher) if (length(na_list) > 0) { teachyearcomb <- unique(cbind(Z_mat[-na_list,]$year, Z_mat[-na_list,]$teacher)) } else { teachyearcomb <- unique(cbind(Z_mat$year, Z_mat$teacher)) } Z_mat <- Z_mat[order(Z_mat$student, Z_mat$year, Z_mat$teacher), , drop = FALSE] Z_mat.full <- Z_mat.full[order(Z_mat.full$student, Z_mat.full$year, Z_mat.full$teacher),] nteach_effects <- dim(teachyearcomb)[1] teacheffZ_mat <- Matrix(0, nrow = nrow(Z_mat), ncol = nteach_effects,doDiag=FALSE) t_effects <- rep(NA, nteach_effects) indx <- 1 eblup.tracker <- matrix(0, 0, 3) dP <- list() for (i in 1:nyear) { dP[[i]] <- list() for (j in 1:i) dP[[i]][[j]] <- matrix(0, 0, 2) } nalpha <- nyear / 2 * (nyear + 1) if (persistence == "ZP" | persistence == "VP") { alpha <- ltriangle(diag(nyear)) } else if (persistence == "CP") { alpha <- rep(1, nalpha) } alpha_key <- tril(ltriangle(1:nalpha)) alpha.diag <- diag(alpha_key) alpha.parm <- alpha[!((1:nalpha) %in% alpha.diag)] for (k in 1:nrow(teachyearcomb)) { student_subset <- Z_mat.full$student[Z_mat.full$year == teachyearcomb[k, 1] & Z_mat.full$teacher == teachyearcomb[k, 2]] t_effects[k] <- paste(teachyearcomb[k, 1], "_", teachyearcomb[k, 2], sep = "") eblup.tracker <- rbind(eblup.tracker, c(teachyearcomb[k,], teachyearcomb[k, 1])) for (yr in as.numeric(teachyearcomb[k, 1]):nyear) { if (sum(is.element(Z_mat$student, student_subset) & Z_mat$year == yr) != 0) { q1 <- (1:nrow(Z_mat))[is.element(Z_mat$student, student_subset) & Z_mat$year == yr & !is.na(Z_mat$y)] q2 <- rep(k, length(q1)) dP[[yr]][[as.numeric(teachyearcomb[k, 1])]] <- rbind(dP[[yr]][[as.numeric(teachyearcomb[k, 1])]], cbind(q1, q2)) } } } P <- list() for (i in 1:nyear) { P[[i]] <- list() for (j in 1:i) P[[i]][[j]] <- as(sparseMatrix( i = dP[[i]][[j]][, 1], j = dP[[i]][[j]][, 2], dims = c(nrow(Z_mat), nteach_effects) ), "dgCMatrix") } Z <- Matrix(0, nrow(Z_mat), nteach_effects,doDiag=FALSE) for (i in 1:nalpha) { comp <- which(tril(ltriangle(1:nalpha)) == i, arr.ind = TRUE) Z <- Z + alpha[i] * P[[comp[1]]][[comp[2]]] } mis.list <- which(Z_mat.full$mis == 1) nteacher <- as.vector(tapply(teachyearcomb[, 2], teachyearcomb[, 1], length)) colnames(Z) <- t_effects X_mat <- sparse.model.matrix(fixed_effects, Z_mat, drop.unused.levels = TRUE) X_mat <- X_mat[,!(colSums(abs(X_mat)) == 0), drop = FALSE] if (rankMatrix(X_mat, method = 'qrLINPACK')[1] != dim(X_mat)[2]) { stop("WARNING: Fixed-effects design matrix not full-rank") } n_eta <- nteach_effects n_ybeta <- dim(X_mat)[2] Y <- as.vector(Z_mat$y) X <- Matrix(X_mat,doDiag=FALSE) huge.flag <- TRUE if (!huge.flag) { Z.dense <- as.matrix(Z) X.dense <- as.matrix(X) } Z_mat.full$r <- 1 - Z_mat.full$mis pattern.student <- matrix(Z_mat.full$r, nstudent, nyear, byrow = TRUE) Z_mat.full$pat <- rep(apply(pattern.student, 1, bin2dec), each = nyear) Z_mat$pat <- Z_mat.full[Z_mat.full$r == 1,]$pat pat <- list() pattern.count <- list() pattern.length <- list() X.p <- list() Y.p <- list() Z.p <- list() Y.p.rownumber <- list() pattern.countoverlength <- list() rownumber <- 1:Ny pattern.key <- dec2bin(1:(2 ^ nyear - 1)) X <- as(X, "sparseMatrix") for (p in unique(Z_mat$pat)) { pat[[p]] <- which(Z_mat$pat == p) if (!huge.flag) { X.p[[p]] <- X.dense[pat[[p]], , drop = FALSE] Z.p[[p]] <- Z.dense[pat[[p]], , drop = FALSE] } else{ X.p[[p]] <- X[pat[[p]], , drop = FALSE] Z.p[[p]] <- Z[pat[[p]], , drop = FALSE] } Y.p.rownumber[[p]] <- rownumber[pat[[p]]] Y.p[[p]] <- Y[pat[[p]]] pattern.count[[p]] <- length(Y.p[[p]]) pattern.length[[p]] <- sum(pattern.key[p,]) pattern.countoverlength[[p]] <- pattern.count[[p]] / pattern.length[[p]] } pattern.yguide <- list() for (g in 1:nyear) { pattern.yguide[[g]] <- which(pattern.key[, g] == 1) } pattern.Rtemplate <- ltriangle(1:(nyear / 2 * (nyear + 1))) pattern.diag <- diag(pattern.Rtemplate) pattern.Rtemplate <- ltriangle(1:(nyear / 2 * (nyear + 1))) pattern.parmlist1 <- list() pattern.parmlist2 <- list() for (p in unique(Z_mat$pat)) { pattern.parmlist1[[p]] <- sort(unique(as.vector( pattern.f.R(pattern.Rtemplate, p, nyear, pattern.key) ))) } for (r.parm in 1:(nyear / 2 * (nyear + 1))) { pattern.parmlist2[[r.parm]] <- which(sapply(pattern.parmlist1, f <- function(x) r.parm %in% x)) } eta.hat <- numeric(n_eta) var.eta.hat <- Matrix(0, n_eta, n_eta,doDiag=FALSE) R.temp.comp <- numeric(nyear) for (g in 1:nyear) { R.temp.comp[g] <- var(Z_mat[Z_mat$year == g,]$y) / 4 } R_i <- diag(R.temp.comp) if (length(mis.list) > 0) { R <- symmpart(suppressMessages(kronecker(suppressMessages( Diagonal(nstudent) ), R_i)[-mis.list,-mis.list])) R_inv <- solve(R) } else { R <- symmpart(suppressMessages(kronecker(suppressMessages( Diagonal(nstudent) ), R_i))) R_inv <- symmpart(suppressMessages(kronecker( suppressMessages(Diagonal(nstudent)), chol2inv(chol(R_i)) ))) } pat.coord.guide <- list() for (r.parm in 1:(nyear / 2 * (nyear + 1))) { pat.coord.guide[[r.parm]] <- list() for (p in pattern.parmlist2[[r.parm]]) { pat.coord.guide[[r.parm]][[p]] <- which(tril(pattern.f.R( pattern.Rtemplate, p, nyear, pattern.key )) == r.parm) } } nonempty.patterns <- NULL for (p in 1:length(pat.coord.guide[[1]])) { if (is.null(retrieve.parm <- pattern.parmlist1[[p]])) next nonempty.patterns <- c(nonempty.patterns, p) } ybetas <- update.ybeta(X, Y, Z, R_inv, eta.hat) names(ybetas) <- colnames(X_mat) G <- 100 * .symDiagonal(n_eta) if (control$REML) { cons.logLik <- 0.5 * (n_eta + n_ybeta) * log(2 * pi) } else { cons.logLik <- 0.5 * (n_eta) * log(2 * pi) } iter <- control$max.iter.EM Y.mat <- Matrix(0, iter, n_ybeta) G.mat <- Matrix(0, iter, length(reduce.G( G = G, nyear = nyear, nteacher = nteacher )),doDiag=FALSE) R.mat <- Matrix(0, iter, nyear * (nyear + 1) / 2,,doDiag=FALSE) lgLik <- numeric(iter) conv <- FALSE if (control$verbose) cat("Beginning EM algorithm\n") flush.console() for (it in 1:iter) { ptm <- proc.time()[3] suppressWarnings(rm(var.eta.hat, temp_mat)) mresid <- as.numeric(Y - X %*% ybetas) cresid <- as.numeric(mresid - Z %*% eta.hat) yhat <- as.numeric(X %*% ybetas + Z %*% eta.hat) yhat.m <- as.numeric(X %*% ybetas) new.eta <- update.eta( X = X, Y = Y, Z = Z, R_inv = R_inv, ybetas = ybetas, G = G, nyear = nyear, cons.logLik = cons.logLik, Ny = Ny, nstudent = nstudent, n_eta = n_eta ) eta.hat <- attr(new.eta, "eta") C12 <- attr(new.eta, "C12") betacov <- matrix(attr(new.eta, "betacov"), nrow = length(ybetas)) var.eta.hat <- new.eta temp_mat <- var.eta.hat + tcrossprod(eta.hat, eta.hat) temp_mat_R <- attr(new.eta, "h.inv") + tcrossprod(eta.hat, eta.hat) lgLik[it] <- attr(new.eta, "likelihood") rm(new.eta) thets1 <- c(Y.mat[it - 1,], R.mat[it - 1,], G.mat[it - 1,]) thets2 <- c(Y.mat[it,], R.mat[it,], G.mat[it,]) if (it > 5) { check.lik <- abs(lgLik[it] - lgLik[it - 1]) / abs(lgLik[it] + control$tol1) < control$tol1 if (check.lik) { conv <- TRUE if (control$verbose) { cat("\n\n Algorithm converged.\n") cat("\n\niter:", it, "\n") cat("log-likelihood:", sprintf("%.7f", lgLik[it]), "\n") cat("change in loglik:", sprintf("%.7f", lgLik[it] - lgLik[it - 1]), "\n") cat("fixed effects:", round(ybetas, 4), "\n") cat("R_i:\n") print(round(as.matrix(R_i), 4)) cat("\n") print(round(cov2cor(as.matrix(R_i)), 4)) cat("\n") for (j in 1:nyear) { cat("\ngamma_teach_year", j, "\n") print(round(reduce.G(G, nyear, nteacher)[j], 4)) cat("\n") flush.console() } rm(j) } break } if (it == iter) { conv <- TRUE if (control$verbose) { cat("\n\n Algorithm converged.\n") cat("\n\niter:", it, "\n") cat("log-likelihood:", sprintf("%.7f", lgLik[it]), "\n") cat("change in loglik:", sprintf("%.7f", lgLik[it] - lgLik[it - 1]), "\n") cat("fixed effects:", round(ybetas, 4), "\n") cat("R_i:\n") print(round(as.matrix(R_i), 4)) cat("\n") print(round(cov2cor(as.matrix(R_i)), 4)) cat("\n") cat("G:\n") print(round(reduce.G(G, nyear, nteacher), 4)) cat("\n") cat("alphas:\n") print(round(alpha, 4)) rm(j) } break } } if ((control$verbose) & (it > 1)) { cat("\n\niter:", it, "\n") cat("log-likelihood:", sprintf("%.7f", lgLik[it]), "\n") cat("change in loglik:", sprintf("%.7f", lgLik[it] - lgLik[it - 1]), "\n") cat("fixed effects:", round(ybetas, 4), "\n") cat("R_i:\n") print(round(as.matrix(R_i), 4)) cat("\n") print(round(cov2cor(as.matrix(R_i)), 4)) cat("\n") cat("G:\n") print(round(reduce.G(G, nyear, nteacher), 4)) cat("\n") cat("alphas:\n") print(round(alpha, 4)) rm(j) } if (persistence == "VP") { alpha.parm <- alpha[!((1:nalpha) %in% alpha.diag)] alpha.cc <- 1 hes.count <- 1 alpha.parm.old <- alpha.parm s.prev <- numeric(length(alpha.parm)) s <- alpha.score( alpha.parm, alpha = alpha, temp_mat = temp_mat, nalpha = nalpha, alpha.diag = alpha.diag, P = P, R_inv = R_inv, eta.hat = eta.hat, ybetas = ybetas, X = X ) j <- jacobian( alpha.score, alpha.parm, method = "simple", alpha = alpha, temp_mat = temp_mat, nalpha = nalpha, alpha.diag = alpha.diag, P = P, R_inv = R_inv, eta.hat = eta.hat, ybetas = ybetas, X = X ) hesprod <- solve(j, s) alpha.cc <- s %*% s alpha.parm <- alpha.parm - hesprod hes.count <- hes.count + 1 s.prev <- s alphan <- alpha alphan[!((1:nalpha) %in% alpha.diag)] <- alpha.parm } d.temp <- diag(temp_mat) indx <- 0 Gn <- c(NULL) for (i in 1:nyear) { Gn <- c(Gn, mean(d.temp[(indx + 1):(indx + nteacher[i])])) indx <- indx + nteacher[i] } rm(indx, i, d.temp) ybetasn <- numeric(n_ybeta) ybetasn <- update.ybeta(X, Y, Z, R_inv, eta.hat) pattern.sum <- list() for (p in unique(Z_mat$pat)) { if (control$REML) { pattern.sum[[p]] <- Matrix(REML_Rm(invsqrtW_ =as.matrix(rep(1, Ny)), betacov_ = betacov, C12_ = C12, JYp_ = as.matrix(Y.p[[p]]), loopsize_ = pattern.count[[p]]/pattern.length[[p]], patternlength_ = pattern.length[[p]], rownumber_ = as.matrix(Y.p.rownumber[[p]]), ybetas_ = as.matrix(ybetas), etahat_ = as.matrix(eta.hat), tempmatR_ = as.matrix(temp_mat), JXpi_ = as.matrix(X.p[[p]]@i), JXpp_ = as.matrix(X.p[[p]]@p), JXpx_ = as.matrix(X.p[[p]]@x), JXpdim_ = as.matrix(X.p[[p]]@Dim), JZpi_ = as.matrix(Z.p[[p]]@i), JZpp_ = as.matrix(Z.p[[p]]@p), JZpx_ = as.matrix(Z.p[[p]]@x), JZpdim_ = as.matrix(Z.p[[p]]@Dim)),doDiag=FALSE) } else { pattern.sum[[p]] <- R_mstep2( invsqrtW_ = as.matrix(rep(1, Ny)), JYp_ = as.matrix(Y.p[[p]]), loopsize_ = pattern.count[[p]] / pattern.length[[p]], patternlength_ = pattern.length[[p]], rownumber_ = as.matrix(Y.p.rownumber[[p]]), ybetas_ = as.matrix(ybetas), etahat_ = as.matrix(eta.hat), tempmatR_ = as.matrix(temp_mat), JXpi_ = as.matrix(X.p[[p]]@i), JXpp_ = as.matrix(X.p[[p]]@p), JXpx_ = as.matrix(X.p[[p]]@x), JXpdim_ = as.matrix(X.p[[p]]@Dim), JZpi_ = as.matrix(Z.p[[p]]@i), JZpp_ = as.matrix(Z.p[[p]]@p), JZpx_ = as.matrix(Z.p[[p]]@x), JZpdim_ = as.matrix(Z.p[[p]]@Dim) ) } } R_i.parm <- ltriangle(as.matrix(R_i)) R.cc <- 1 hes.count <- 1 R_i.parm.old <- R_i.parm s.prev <- numeric(length(R_i.parm)) while (R.cc > 1e-04) { s <- pattern.f.score( R_i.parm = R_i.parm, nyear = nyear, pattern.parmlist2 = pattern.parmlist2, pattern.count = pattern.count, pattern.length = pattern.length, pattern.Rtemplate = pattern.Rtemplate, pattern.diag = pattern.diag, pattern.key = pattern.key, pattern.sum = pattern.sum ) j <- jacobian( pattern.f.score, c(R_i.parm), method = "simple", nyear = nyear, pattern.parmlist2 = pattern.parmlist2, pattern.count = pattern.count, pattern.length = pattern.length, pattern.Rtemplate = pattern.Rtemplate, pattern.diag = pattern.diag, pattern.key = pattern.key, pattern.sum = pattern.sum ) if (it == 1 & (hes.count < 10)) { hesprod <- solve(j + max(c(diag(j), 5)) * diag(length(R_i.parm)), s) R.cc <- s %*% s if (hes.count == 9) R.cc <- 0 } else if ((it <= 4) & (hes.count < 30)) { hesprod <- solve(j + max(c(diag(j), 5) * (( 1 - hes.count / 31 ) ^ 2)) * diag(length(R_i.parm)), s) R.cc <- s %*% s if (hes.count == 29) R.cc <- 0 } else { hesprod <- solve(j, s) R.cc <- s %*% s } R_i.parm <- R_i.parm - hesprod hes.count <- hes.count + 1 s.prev <- s } R_i <- ltriangle(R_i.parm) rm(R_i.parm) dimnames(R_i) <- list(NULL, NULL) if (length(mis.list) > 0) { R <- symmpart(suppressMessages(kronecker(Diagonal(nstudent), R_i))[-mis.list,-mis.list]) R_inv <- suppressMessages(solve(R)) } else { R <- symmpart(suppressMessages(kronecker(Diagonal(nstudent), R_i))) R_inv <- symmpart(suppressMessages(kronecker(Diagonal(nstudent), solve(R_i)))) } G <- reduce.G(Gn, nyear, nteacher) if (persistence == "VP") { alpha <- alphan Z <- Matrix(0, nrow(Z_mat), nteach_effects,doDiag=FALSE) for (i in 1:nalpha) { comp <- which(tril(ltriangle(1:nalpha)) == i, arr.ind = TRUE) Z <- Z + alpha[i] * P[[comp[1]]][[comp[2]]] } if (!huge.flag) { Z.dense <- as.matrix(Z) } for (p in unique(Z_mat$pat)) { if (!huge.flag) { Z.p[[p]] <- Z.dense[pat[[p]], , drop = FALSE] } else{ Z.p[[p]] <- Z[pat[[p]], , drop = FALSE] } } } if(it<=4){ ybetas <- ybetasn }else{ G.chol <- chol(G) G.inv <- chol2inv(G.chol) R.inv.Z <- R_inv %*% Z V.1 <- chol2inv(chol(G.inv + t(Z) %*% R.inv.Z)) tX.Rinv.Z <- t(X) %*% R.inv.Z tX.Rinv.X <- t(X) %*% R_inv %*% X ybetas <- as.vector(chol2inv(chol(forceSymmetric(symmpart(tX.Rinv.X - tX.Rinv.Z %*% V.1 %*% t(tX.Rinv.Z))))) %*% (t(X) %*% R_inv - tX.Rinv.Z %*% V.1 %*% t(R.inv.Z)) %*% Y) } if (control$verbose) cat("Iteration Time: ", proc.time()[3] - ptm, " seconds\n") flush.console() } names(ybetas) <- colnames(X_mat) if (persistence == "CP" | persistence == "ZP") { thetas <- c(ltriangle(as.matrix(R_i)), reduce.G( G = G, nyear = nyear, nteacher = nteacher )) } else if (persistence == "VP") { thetas <- c(ltriangle(as.matrix(R_i)), reduce.G( G = G, nyear = nyear, nteacher = nteacher ), alpha[!((1:nalpha) %in% alpha.diag)]) } lgLik.hist <- lgLik lgLik <- lgLik[it] Hessian <- NA std_errors <- c(rep(NA, length(thetas))) if (control$hessian == TRUE) { if (control$verbose) cat("Calculating Hessian of the variance components...") flush.console() pattern.sum <- list() for (p in unique(Z_mat$pat)) { pattern.sum[[p]] <- R_mstep2( invsqrtW_ = as.matrix(rep(1, Ny)), JYp_ = as.matrix(Y.p[[p]]), loopsize_ = pattern.count[[p]] / pattern.length[[p]], patternlength_ = pattern.length[[p]], rownumber_ = as.matrix(Y.p.rownumber[[p]]), ybetas_ = as.matrix(ybetas), etahat_ = as.matrix(eta.hat), tempmatR_ = as.matrix(temp_mat), JXpi_ = as.matrix(X.p[[p]]@i), JXpp_ = as.matrix(X.p[[p]]@p), JXpx_ = as.matrix(X.p[[p]]@x), JXpdim_ = as.matrix(X.p[[p]]@Dim), JZpi_ = as.matrix(Z.p[[p]]@i), JZpp_ = as.matrix(Z.p[[p]]@p), JZpx_ = as.matrix(Z.p[[p]]@x), JZpdim_ = as.matrix(Z.p[[p]]@Dim) ) } if (control$hes.method == "richardson") { Hessian <- ltriangle(ltriangle( jacobian( Score, thetas, eta = eta.hat, ybetas = ybetas, X = X, Y = Y, Z = Z, pattern.sum = pattern.sum, con = control, year.count = year.count, n_ybeta = n_ybeta, nyear = nyear, n_eta = n_eta, nstudent = nstudent, nteacher = nteacher, Kg = Kg, cons.logLik = cons.logLik, mis.list = mis.list, pattern.parmlist2 = pattern.parmlist2, pattern.count = pattern.count, pattern.length = pattern.length, pattern.Rtemplate = pattern.Rtemplate, pattern.diag = pattern.diag, pattern.key = pattern.key, Ny = Ny, persistence = persistence, P = P, alpha.diag = alpha.diag, nalpha = nalpha, alpha = alpha ) )) } else { Hessian <- ltriangle(ltriangle( jacobian( Score, thetas, method = "simple", eta = eta.hat, ybetas = ybetas, X = X, Y = Y, Z = Z, pattern.sum = pattern.sum, con = control, year.count = year.count, n_ybeta = n_ybeta, nyear = nyear, n_eta = n_eta, nstudent = nstudent, nteacher = nteacher, Kg = Kg, cons.logLik = cons.logLik, mis.list = mis.list, pattern.parmlist2 = pattern.parmlist2, pattern.count = pattern.count, pattern.length = pattern.length, pattern.Rtemplate = pattern.Rtemplate, pattern.diag = pattern.diag, pattern.key = pattern.key, Ny = Ny, persistence = persistence, P = P, alpha.diag = alpha.diag, nalpha = nalpha, alpha = alpha ) )) } std_errors <- try(c(sqrt(diag(solve(Hessian)))), silent = TRUE) hes.warn <- FALSE Hessian <- round(Hessian, 4) if (any(eigen(Hessian)$values <= 0)) { if (control$verbose) cat("Warning: Hessian not PD", "\n") std_errors <- c(rep(NA, length(thetas))) hes.warn <- TRUE } } c.temp <- crossprod(X, R_inv) %*% Z c.1 <- rbind(crossprod(X, R_inv) %*% X, t(c.temp)) G.inv <- chol2inv(chol(G)) c.2 <- rbind(c.temp, H.eta(G.inv, Z, R_inv)) C_inv <- cbind(c.1, c.2) C <- solve(C_inv) eblup_stderror <- sqrt(diag(C)[-c(1:n_ybeta)]) ybetas_stderror <- sqrt(diag(C)[1:n_ybeta]) rm(C, C_inv, c.2, c.1, c.temp) eblup <- as.matrix(cbind(eta.hat, eblup_stderror)) eblup <- as.data.frame(eblup) eblup.tracker <- as.data.frame(eblup.tracker) eblup <- as.data.frame(cbind(eblup.tracker, eblup)) colnames(eblup) <- c("teacher_year", "teacher", "effect_year", "EBLUP", "std_error") eblup$teacher <- as.character(eblup$teacher) t_lab <- as.vector(NULL) r_lab <- as.vector(NULL) for (j in 1:nyear) { ne <- (Kg[j] * (Kg[j] + 1)) / 2 y <- c(NULL) x <- c(NULL) for (k in 1:Kg[j]) { x <- c(x, k:Kg[j]) y <- c(y, rep(k, (Kg[j] - k + 1))) } t_lab <- c(t_lab, paste("teacher effect from year", rep(j, ne), sep = "")) } ne <- nyear * (nyear + 1) / 2 y <- c(NULL) x <- c(NULL) for (k in 1:nyear) { x <- c(x, k:nyear) y <- c(y, rep(k, (nyear - k + 1))) } r_lab <- paste("error covariance", ":[", x, ",", y, "]", sep = "") rm(j, ne) alpha.label <- c(NULL) for (i in 1:(nyear - 1)) { for (j in (i + 1):(nyear)) { alpha.label <- c(alpha.label, paste("alpha_", j, i, sep = "")) } } if (persistence == "CP" | persistence == "ZP") { effect_la <- c(names(ybetas), r_lab, t_lab) } else if (persistence == "VP") { effect_la <- c(names(ybetas), r_lab, t_lab, alpha.label) } if (control$hessian == TRUE) { parameters <- round(cbind(c(ybetas, thetas), c(ybetas_stderror, std_errors)), 4) colnames(parameters) <- c("Estimate", "Standard Error") rownames(parameters) <- as.character(effect_la) } if (control$hessian == FALSE) { parameters <- round(cbind(c(ybetas, thetas), c(ybetas_stderror, rep( NA, length(thetas) ))), 4) colnames(parameters) <- c("Estimate", "Standard Error") rownames(parameters) <- as.character(effect_la) } R_i <- round(R_i, 4) if (control$verbose) cat("done.\n") mresid <- as.numeric(Y - X %*% ybetas) cresid <- as.numeric(mresid - Z %*% eta.hat) yhat <- as.numeric(X %*% ybetas + Z %*% eta.hat) yhat.m <- as.numeric(X %*% ybetas) Hessian <- round(Hessian, 5) R_i <- round(R_i, 4) gam_t <- list() for (i in 1:nyear) { gam_t[[i]] <- round(as.matrix(reduce.G( G, nyear = nyear, nteacher = nteacher )[i]), 4) colnames(gam_t[[i]]) <- paste("year", i, sep = "") rownames(gam_t[[i]]) <- colnames(gam_t[[i]]) } rchol <- try(chol(R_inv)) yhat.s <- try(as.vector(rchol %*% (yhat))) sresid <- try(as.vector(rchol %*% Y - yhat.s)) teach.cov <- lapply(gam_t, function(x) round(x, 4)) L <- list( loglik = lgLik, teach.effects = eblup, parameters = parameters, Hessian = Hessian, R_i = as.matrix(R_i), teach.cov = gam_t, mresid = mresid, cresid = cresid, y = Y, yhat = yhat, stu.cov = NA, num.obs = Ny, num.student = nstudent, num.year = nyear, num.teach = nteacher, yhat.m = yhat.m, sresid = sresid, yhat.s = yhat.s, iter = it, persistence = control$persistence, betacov=betacov ) }
create_output_table <- function(comparison_output, output_type = 'html', file_name = NULL, limit = 100, color_scheme = c("addition" = " "unchanged_cell" = " headers = NULL, change_col_name = "chng_type", group_col_name = "grp"){ headers_all = get_headers_for_table(headers, change_col_name, group_col_name, comparison_output$comparison_table_diff) comparison_output$comparison_table_ts2char$chng_type = comparison_output$comparison_table_ts2char$chng_type %>% replace_numbers_with_change_markers(comparison_output$change_markers) if (limit == 0 || nrow(comparison_output$comparison_table_diff) == 0 || nrow(comparison_output$comparison_df) == 0) return(NULL) output = switch(output_type, 'html' = create_html_table(comparison_output, file_name, limit, color_scheme, headers_all), 'xlsx' = create_xlsx_document(comparison_output, file_name, limit, color_scheme, headers_all) ) output } message_compareDF <- function(msg){ if ("futile.logger" %in% rownames(utils::installed.packages())) { futile.logger::flog.trace(stringr::str_interp(msg, env = parent.frame())) } else { message(msg) } } create_html_table <- function(comparison_output, file_name, limit_html, color_scheme, headers_all){ comparison_table_diff = comparison_output$comparison_table_diff_numbers comparison_table_ts2char = comparison_output$comparison_table_ts2char group_col = comparison_output$group_col if (limit_html > 1000 & comparison_table_diff %>% nrow > 1000) warning("Creating HTML diff for a large dataset (>1000 rows) could take a long time!") if (limit_html < nrow(comparison_table_diff)) message_compareDF("Truncating HTML diff table to ${limit_html} rows...") requireNamespace("htmlTable") comparison_table_color_code = comparison_table_diff %>% do(.colour_coding_df(., color_scheme)) %>% as.data.frame shading = ifelse(sequence_order_vector(comparison_table_ts2char[[group_col]]) %% 2, " table_css = lapply(comparison_table_color_code, function(x) paste0("padding: .2em; color: ", x, ";")) %>% data.frame %>% head(limit_html) %>% as.matrix() colnames(comparison_table_ts2char) <- headers_all message_compareDF("Creating HTML table for first ${limit_html} rows") html_table = htmlTable::htmlTable(comparison_table_ts2char %>% head(limit_html), col.rgroup = shading, rnames = F, css.cell = table_css, padding.rgroup = rep("5em", length(shading)) ) if (!is.null(file_name)){ cat(html_table, file = file_name) return(file_name) } return(html_table) } .colour_coding_df <- function(df, color_scheme){ if(nrow(df) == 0) return(df) df[df == 2] = color_scheme[['addition']] df[df == 1] = color_scheme[['removal']] df[df == 0] = color_scheme[['unchanged_cell']] df[df == -1] = color_scheme[['unchanged_row']] df } .convert_to_row_column_format <- function(x, n){ list( rows = ((x - 1) %% n) + 1, cols = ((x - 1) %/% n) + 1 ) } .get_color_coding_indices <- function(df){ output = list( 'addition' = which(df == 2), 'removal' = which(df == 1), 'unchanged_cell' = which(df == 0), 'unchanged_row' = which(df == -1) ) %>% Filter(function(x) length(x) > 0, .) %>% lapply(.convert_to_row_column_format, nrow(df)) } .adjust_colors_for_excel <- function(types){ for(type in names(types)){ types[[type]][['rows']] = types[[type]][['rows']] + 1 } types } create_xlsx_document <- function(comparison_output, file_name, limit, color_scheme, headers_all){ if(is.null(file_name)) stop("file_name cannot be null if output format is xlsx") comparison_table_diff = comparison_output$comparison_table_diff_numbers comparison_table_ts2char = comparison_output$comparison_table_ts2char group_col = comparison_output$group_col requireNamespace("openxlsx") comparison_table_color_code = comparison_table_diff %>% .get_color_coding_indices() %>% .adjust_colors_for_excel() wb <- openxlsx::createWorkbook("Compare DF Output") openxlsx::addWorksheet(wb, "Sheet1", gridLines = FALSE) openxlsx::writeData(wb, sheet = 1, comparison_table_ts2char, rowNames = FALSE) for(i in seq_along(comparison_table_color_code)){ openxlsx::addStyle(wb, sheet = 1, openxlsx::createStyle(fontColour = color_scheme[[names(comparison_table_color_code)[i]]]), rows = comparison_table_color_code[[i]]$rows, cols = comparison_table_color_code[[i]]$cols, gridExpand = FALSE) } even_rows = which(sequence_order_vector(comparison_table_ts2char[[group_col]]) %% 2 == 0) + 1 openxlsx::addStyle(wb, sheet = 1, openxlsx::createStyle(fgFill = 'lightgray'), rows = even_rows, cols = 1:ncol(comparison_table_ts2char), gridExpand = T, stack = TRUE) openxlsx::saveWorkbook(wb, file_name, overwrite = T) } create_wide_output <- function(comparison_output, suffix = c("_new", "_old")){ dplyr::full_join( comparison_output$comparison_df %>% filter(chng_type == comparison_output$change_markers[1]), comparison_output$comparison_df %>% filter(chng_type == comparison_output$change_markers[2]), by = comparison_output$group_col, suffix = suffix, ) %>% select(-starts_with("chng_type")) %>% select(comparison_output$group_col, one_of(sort(names(.), decreasing = TRUE))) } view_html <- function(comparison_output){ temp_dir = tempdir() temp_file <- paste0(temp_dir, "/temp.html") cat(create_output_table(comparison_output), file = temp_file) getOption("viewer")(temp_file) unlink("temp.html") }
KFadvanceAR2 <- function(obs,oldmean,oldermean,oldvar,oldervar,A,A1,B,C,D,E,F,W,V,marglik=FALSE,log=TRUE,na.rm=FALSE){ if(na.rm){ if(any(is.na(obs))){ if(all(is.na(obs))){ if(log){ return(list(mean=A%*%oldmean + A1%*%oldermean + B,var=A%*%oldvar%*%t(A) + A1%*%oldervar%*%t(A1) + C%*%W%*%t(C),mlik=0)) } else{ return(list(mean=A%*%oldmean + A1%*%oldermean + B,var=A%*%oldvar%*%t(A) + A1%*%oldervar%*%t(A1) + C%*%W%*%t(C),mlik=1)) } } else{ M <- diag(length(obs)) M <- M[-which(is.na(obs)),] obs <- obs[which(!is.na(obs))] D <- M%*%D E <- M%*%E F <- M%*%F } } } T <- A%*%oldmean + A1%*%oldermean + B S <- A%*%oldvar%*%t(A) + A1%*%oldervar%*%t(A1) + C%*%W%*%t(C) K <- D%*%S%*%t(D) + F%*%V%*%t(F) if (marglik==TRUE){ margmean <- D %*% T + E if (all(dim(K)==1)){ newmean <- T + as.numeric(1/K)*S%*%t(D)%*%(obs-margmean) newvar <- S - as.numeric(1/K)*S%*%t(D)%*%D%*%S marginal <- dnorm(obs,as.numeric(margmean),sqrt(as.numeric(K)),log=log) } else{ Kinv <- solve(K) newmean <- T + S%*%t(D)%*%Kinv%*%(obs-margmean) newvar <- S - S%*%t(D)%*%Kinv%*%D%*%S marginal <- dmvnorm(as.vector(obs),as.vector(margmean),K,log=log) } return(list(mean=newmean,var=newvar,mlik=marginal)) } else{ if (all(dim(K)==1)){ newmean <- T + as.numeric(1/K)*S%*%t(D)%*%(obs-D%*%T-E) newvar <- S - as.numeric(1/K)*S%*%t(D)%*%D%*%S } else{ Kinv <- solve(K) newmean <- T + S%*%t(D)%*%Kinv%*%(obs-D%*%T-E) newvar <- S - S%*%t(D)%*%Kinv%*%D%*%S } return(list(mean=newmean,var=newvar)) } }
`PsiTildeCalc` <- function(u,H,test,omega,vm,vminv,p,K){ PsiHatSum<-array(0,c(p,p)) r<-dim(test)[[1]] w<-matrix(NA,K,r) PsiTilde<-array(NA,c(r,K,p,p)) HU<-H*u for (i in 1:K){ PsiHatSum<-PsiHatSum + matrix(HU[i,],ncol=1) %*% matrix(HU[i,],nrow=1) w[i,]<- diag( test %*% ( solve( vminv - omega[i,,]) -vm ) %*% t(test) ) } wstandardized<-t( t(w)/apply(w,2,sum)) for (i in 1:K){ for (j in 1:r){ PsiTilde[j,i,,]<-w[i,j]*PsiHatSum } } PsiTilde }
context(" Included distances") ols <- ls() functions <- c("lb_keogh", "lb_improved", "SBD", "dtw_basic", "GAK", "sdtw") needs_window <- c("lb_keogh", "lb_improved") enlist <- function(...) { dots <- list(...) if (get("foo", parent.frame()) %in% needs_window) { dots <- c(dots, list(window.size = 1L)) } dots } supports_mv <- c("dtw_basic", "GAK", "sdtw") supports_diff_lengths <- c("SBD", "dtw_basic", "GAK", "sdtw") args <- list( lb_keogh = list( list(window.size = 15L, norm = "L1", force.symmetry = FALSE), list(window.size = 15L, norm = "L1", force.symmetry = TRUE), list(window.size = 15L, norm = "L2", force.symmetry = FALSE), list(window.size = 15L, norm = "L2", force.symmetry = TRUE) ), lb_improved = list( list(window.size = 15L, norm = "L1", force.symmetry = FALSE), list(window.size = 15L, norm = "L1", force.symmetry = TRUE), list(window.size = 15L, norm = "L2", force.symmetry = FALSE), list(window.size = 15L, norm = "L2", force.symmetry = TRUE) ), SBD = list( list(znorm = FALSE), list(znorm = TRUE) ), dtw_basic = list( list(window.size = 15L, norm = "L1", step.pattern = dtw::symmetric1), list(window.size = 15L, norm = "L1", step.pattern = dtw::symmetric2), list(window.size = 15L, norm = "L2", step.pattern = dtw::symmetric1), list(window.size = 15L, norm = "L2", step.pattern = dtw::symmetric2), list(window.size = 15L, norm = "L1", step.pattern = dtw::symmetric2, normalize = TRUE), list(window.size = 15L, norm = "L2", step.pattern = dtw::symmetric2, normalize = TRUE) ), GAK = list( list(sigma = 100, window.size = 15L), list(sigma = 100, window.size = NULL), list(sigma = 100, normalize = FALSE) ), sdtw = list( list() ) ) x_uv <- data[[1L]] y_uv_same_length <- data[[2L]] y_uv_diff_length <- data[[100L]] x_mv <- data_multivariate[[1L]] y_mv_same_length <- data_multivariate[[2L]] y_mv_diff_length <- data_multivariate[[20L]] invalid_inputs <- list( "NA" = NA, "NULL" = NULL, "char" = "1", "bool" = TRUE, "empty" = numeric(), "miss" = c(1, NA) ) test_that("Invalid inputs are detected correctly in the distance functions.", { for (foo in functions) { for (input in names(invalid_inputs)) { expect_error(do.call(foo, enlist(x = invalid_inputs[[input]], y = x_uv)), info = paste("function", foo, "with", input, "input in x")) expect_error(do.call(foo, enlist(x = x_uv, y = invalid_inputs[[input]])), info = paste("function", foo, "with", input, "input in y")) } if (!(foo %in% supports_mv)) { expect_error(do.call(foo, enlist(x = x_mv, y = x_mv)), "multivariate", info = paste("function", foo, "with multivariate input")) expect_error(do.call(foo, enlist(x = x_uv, y = x_mv)), info = paste("function", foo, "with multivariate y")) expect_error(do.call(foo, enlist(x = x_mv, y = x_uv)), info = paste("function", foo, "with multivariate x")) } else { expect_error(do.call(foo, enlist(x = x_mv, y = x_uv)), info = paste("function", foo, "with mismatched multivariate input")) } if (!(foo %in% supports_diff_lengths)) { expect_error(do.call(foo, enlist(x = x_uv, y = y_uv_diff_length)), "length", info = paste("function", foo, "with different-length input")) } } }) test_that("Valid inputs provide a result different than zero", { for (foo in functions) { for (arg in args[[foo]]) { distance_value <- do.call(foo, c(list(x = x_uv, y = y_uv_same_length), arg)) if (foo %in% c("lb_keogh", "SBD")) distance_value <- distance_value$d expect_true(distance_value != 0, label = paste0("distance with ", foo)) if (mv <- foo %in% supports_mv) { distance_value <- do.call(foo, c(list(x = x_mv, y = y_mv_same_length), arg)) expect_true(distance_value != 0, label = paste0("multivariate distance with ", foo)) } if (dl <- foo %in% supports_diff_lengths) { distance_value <- do.call(foo, c(list(x = x_uv, y = y_uv_diff_length), arg)) if (foo %in% c("SBD")) distance_value <- distance_value$d expect_true(distance_value != 0, label = paste0("distance with different lengths with ", foo)) } if (mv && dl) { distance_value <- do.call(foo, c(list(x = x_mv, y = y_mv_diff_length), arg)) expect_true(distance_value != 0, label = paste0("multivariate distance with different lengths with ", foo)) } } } }) test_that("Passing pre-computed envelopes to the lower bounds works correctly.", { envelopes <- compute_envelope(y_uv_diff_length, window.size = 15L) wrong_lower_envelope <- envelopes$lower wrong_upper_envelope <- envelopes$upper envelopes <- compute_envelope(y_uv_same_length, window.size = 15L) correct_lower_envelope <- envelopes$lower correct_upper_envelope <- envelopes$upper expect_error(lb_keogh(x_uv, lower.env = wrong_lower_envelope, upper.env = correct_upper_envelope), regexp = "mismatch.*envelope") expect_error(lb_keogh(x_uv, lower.env = correct_lower_envelope, upper.env = wrong_upper_envelope), regexp = "mismatch.*envelope") expect_gt(lb_keogh(x_uv, lower.env = correct_lower_envelope, upper.env = correct_upper_envelope)$d, 0) expect_error(lb_improved(x_uv, y_uv_same_length, window.size = 15L, lower.env = wrong_lower_envelope, upper.env = correct_upper_envelope), regexp = "mismatch.*envelope") expect_error(lb_improved(x_uv, y_uv_same_length, window.size = 15L, lower.env = correct_lower_envelope, upper.env = wrong_upper_envelope), regexp = "mismatch.*envelope") expect_gt(lb_improved(x_uv, y_uv_same_length, window.size = 15L, lower.env = correct_lower_envelope, upper.env = correct_upper_envelope), 0) }) test_that("dtw_lb gives the same result regardless of dtw.func.", { distmat_with_dtwbasic <- dtw_lb(data_reinterpolated[1L:50L], data_reinterpolated[51L:100L], window.size = 15L, step.pattern = dtw::symmetric1) distmat_with_dtw <- dtw_lb(data_reinterpolated[1L:50L], data_reinterpolated[51L:100L], window.size = 15L, step.pattern = dtw::symmetric1, dtw.func = "dtw") expect_equal(distmat_with_dtwbasic, distmat_with_dtw, check.attributes = FALSE) }) test_that("dtw_lb gives the same result for different nn.margin and corresponding inputs.", { d <- dtw_lb(data_reinterpolated[1:5], data_reinterpolated[6:50], window.size = 20L) NN1 <- apply(d, 1L, which.min) d2 <- dtw_lb(data_reinterpolated[6:50], data_reinterpolated[1:5], window.size = 20L, nn.margin = 2L) NN2 <- apply(d2, 2L, which.min) expect_identical(NN1, NN2, info = "Indices of nearest neighbors") }) test_that("Backtracking in dtw_basic() works.", { univariate_result <- dtw_basic(x_uv, x_uv, backtrack = TRUE) expect_identical(univariate_result$index1, univariate_result$index2) multivariate_result <- dtw_basic(x_mv, x_mv, backtrack = TRUE) expect_identical(multivariate_result$index1, multivariate_result$index2) }) test_that("Inconsistencies in parameters for dtw_basic() are detected.", { expect_error(dtw_basic(x_uv, x_uv, step.pattern = dtw::asymmetric), "step.pattern") expect_error(dtw_basic(x_uv, x_uv, step.pattern = dtw::symmetric1, normalize = TRUE), "normalize") }) test_that("dtw_basic can behave like dtw::dtw for multivariate series and squared L2 norm.", { a <- data_multivariate[[1L]] b <- data_multivariate[[2L]] dm <- proxy::dist(a, b, method = "L2") ^ 2 dtw_dist <- dtw::dtw(dm) dtw_basic_dist <- dtw_basic(a, b, norm = "L2", sqrt.dist = FALSE) expect_equal(dtw_basic_dist, dtw_dist$distance) normalized_dtw_basic_dist <- dtw_basic(a, b, norm = "L2", sqrt.dist = FALSE, normalize = TRUE) expect_equal(normalized_dtw_basic_dist, dtw_dist$normalizedDistance) }) test_that("GAK can estimate sigma.", { expect_error(GAK(1, 2, sigma = -1)) gak_distance <- GAK(data[[1L]], data[[100L]]) expect_gt(attr(gak_distance, "sigma"), 0) }) test_that("Inconsistencies in parameters for sdtw() are detected.", { expect_error(sdtw(x_uv, x_uv, gamma = -0.01), "gamma.*positive") }) rm(list = setdiff(ls(), ols))
id <- function(x, ...) { deprecate_soft("1.0.0", "gmailr::id()", "gm_id()") gm_id(x, ...) } to <- function(x, ...) { deprecate_soft("1.0.0", "gmailr::to()", "gm_to()") gm_to(x, ...) } from <- function(x, ...) { deprecate_soft("1.0.0", "gmailr::from()", "gm_from()") gm_from(x, ...) } cc <- function(x, ...) { deprecate_soft("1.0.0", "gmailr::cc()", "gm_cc()") gm_cc(x, ...) } bcc <- function(x, ...) { deprecate_soft("1.0.0", "gmailr::bcc()", "gm_bcc()") gm_bcc(x, ...) } date <- function(x, ...) { deprecate_soft("1.0.0", "gmailr::date()", "gm_date()") gm_date(x, ...) } subject <- function(x, ...) { deprecate_soft("1.0.0", "gmailr::subject()", "gm_subject()") gm_subject(x, ...) } body <- function(x, ...) { deprecate_soft("1.0.0", "gmailr::body()", "gm_body()") gm_body(x, ...) } last_response <- function() { deprecate_soft("1.0.0", "gmailr::last_response()", "gm_last_response()") gm_last_response() } message <- function(...) { deprecate_soft("1.0.0", "gmailr::message()", "gm_message()") gm_message(...) } messages <- function(...) { deprecate_soft("1.0.0", "gmailr::messages()", "gm_messages()") gm_messages(...) } trash_message <- function(...) { deprecate_soft("1.0.0", "gmailr::trash_message()", "gm_trash_message()") gm_trash_message(...) } untrash_message <- function(...) { deprecate_soft("1.0.0", "gmailr::trash_message()", "gm_trash_message()") gm_untrash_message(...) } delete_message <- function(...) { deprecate_soft("1.0.0", "gmailr::delete_message()", "gm_delete_message()") gm_delete_message(...) } modify_message <- function(...) { deprecate_soft("1.0.0", "gmailr::modify_message()", "gm_modify_message()") gm_modify_message(...) } attachment <- function(...) { deprecate_soft("1.0.0", "gmailr::attachment()", "gm_attachment()") gm_attachment(...) } save_attachment <- function(...) { deprecate_soft("1.0.0", "gmailr::save_attachment()", "gm_save_attachment()") gm_save_attachment(...) } save_attachments <- function(...) { deprecate_soft("1.0.0", "gmailr::save_attachments()", "gm_save_attachments()") gm_save_attachments(...) } insert_message <- function(...) { deprecate_soft("1.0.0", "gmailr::insert_message()", "gm_insert_message()") gm_insert_message(...) } import_message <- function(...) { deprecate_soft("1.0.0", "gmailr::import_message()", "gm_import_message()") gm_import_message(...) } send_message <- function(...) { deprecate_soft("1.0.0", "gmailr::send_message()", "gm_send_message()") gm_send_message(...) } threads <- function(...) { deprecate_soft("1.0.0", "gmailr::threads()", "gm_threads()") gm_threads(...) } thread <- function(...) { deprecate_soft("1.0.0", "gmailr::thread()", "gm_thread()") gm_thread(...) } trash_thread <- function(...) { deprecate_soft("1.0.0", "gmailr::trash_thread()", "gm_trash_thread()") gm_trash_thread(...) } untrash_thread <- function(...) { deprecate_soft("1.0.0", "gmailr::untrash_thread()", "gm_untrash_thread()") gm_untrash_thread(...) } delete_thread <- function(...) { deprecate_soft("1.0.0", "gmailr::delete_thread()", "gm_delete_thread()") gm_delete_thread(...) } modify_thread <- function(...) { deprecate_soft("1.0.0", "gmailr::modify_thread()", "gm_modify_thread()") gm_modify_thread(...) } draft <- function(...) { deprecate_soft("1.0.0", "gmailr::draft()", "gm_draft()") gm_draft(...) } drafts <- function(...) { deprecate_soft("1.0.0", "gmailr::drafts()", "gm_drafts()") gm_drafts(...) } create_draft <- function(...) { deprecate_soft("1.0.0", "gmailr::create_draft()", "gm_create_draft()") gm_create_draft(...) } send_draft <- function(...) { deprecate_soft("1.0.0", "gmailr::send_draft()", "gm_send_draft()") gm_send_draft(...) } labels <- function(...) { deprecate_soft("1.0.0", "gmailr::labels()", "gm_labels()") gm_labels(...) } label <- function(...) { deprecate_soft("1.0.0", "gmailr::label()", "gm_label()") gm_label(...) } update_label <- function(...) { deprecate_soft("1.0.0", "gmailr::update_label()", "gm_update_label()") gm_update_label(...) } update_label_patch <- function(...) { deprecate_soft("1.0.0", "gmailr::update_label_patch()", "gm_update_label_patch()") gm_update_label_patch(...) } delete_label <- function(...) { deprecate_soft("1.0.0", "gmailr::delete_label()", "gm_delete_label()") gm_delete_label(...) } create_label <- function(...) { deprecate_soft("1.0.0", "gmailr::create_label()", "gm_create_label()") gm_create_label(...) } history <- function(...) { deprecate_soft("1.0.0", "gmailr::history()", "gm_history()") gm_history(...) } mime <- function(...) { deprecate_soft("1.0.0", "gmailr::mime()", "gm_mime()") gm_mime(...) } text_body <- function(...) { deprecate_soft("1.0.0", "gmailr::text_body()", "gm_text_body()") gm_text_body(...) } html_body <- function(...) { deprecate_soft("1.0.0", "gmailr::html_body()", "gm_html_body()") gm_html_body(...) } attach_part <- function(...) { deprecate_soft("1.0.0", "gmailr::attach_part()", "gm_attach_part()") gm_attach_part(...) } attach_file <- function(...) { deprecate_soft("1.0.0", "gmailr::attach_file()", "gm_attach_file()") gm_attach_file(...) } gm_convert_file <- function(file) { gm_funs <- get_deprecated_funs() lines <- readLines(file) for (i in seq_len(NROW(gm_funs))) { find <- paste0("(?<![[:alnum:]_:])", gm_funs$old[[i]], "[(]") replace <- gm_funs$new[[i]] lines <- gsub(find, replace, lines, perl = TRUE) } writeLines(lines, file) } get_deprecated_funs <- function() { file <- system.file(package = "gmailr", "R", "deprecated.R") lines <- readLines(file) res <- rematch2::re_match(lines, 'deprecate_.*gmailr::(?<old>[^(]+).*(?<new>gm_[^(]+)') stats::na.omit(res)[c("old", "new")] }
`%nin%` <- function (x, table) is.na(match(x, table)) log.q1pm <- function(r) log1p(2*r/(1-r)) indTri <- function(n, upper = TRUE, diag = FALSE) { stopifnot(length(n) == 1, n == (n. <- as.integer(n)), (n <- n.) >= 0) if(n <= 2) { if(n == 0) return(integer(0)) if(n == 1) return(if(diag) 1L else integer(0)) v <- if(upper) 3L else 2L return(if(diag) c(1L, v, 4L) else v) } n. <- if(diag) n else n - 1L n1 <- n. - 1L r <- rep.int(1L, choose(n.+1, 2) - 1) tt <- if(diag) 2L else 3L r[cumsum(if(upper) 1:n1 else n.:2)] <- if(upper) n:tt else tt:n cumsum(c(if(diag) 1L else if(upper) n+1L else 2L, r)) } numGedges <- function(amat) { dimnames(amat) <- NULL A <- (amat + t(amat)) != 0 n <- nrow(A) if(n <= 40) sum(A[lower.tri(A)]) else sum(A[indTri(n)]) } check.Rgraphviz <- function() { if(!requireNamespace("Rgraphviz")) stop("Package 'Rgraphviz' (from Bioconductor) must be installed for plotting graphs!") }
staple = function( x, ..., set_orient = FALSE) { UseMethod("staple") } staple.default = function( x, ..., set_orient = FALSE){ res = staple_multi_mat(x, ...) return(res) } staple.list = function( x, ..., set_orient = FALSE){ res = staple_multi_img(x, set_orient = set_orient, ...) if (length(res$probability) == 2) { res$probability = res$probability[[2]] res$prior = res$prior[[2]] res$sensitivity = res$sensitivity[, 2] res$specificity = res$specificity[, 2] } return(res) } staple.character = function( x, ..., set_orient = FALSE){ res = staple_multi_img(x, set_orient = set_orient, ...) if (length(res$probability) == 2) { res$probability = res$probability[[2]] res$prior = res$prior[[2]] res$sensitivity = res$sensitivity[, 2] res$specificity = res$specificity[, 2] } return(res) } staple.array = function( x, ..., set_orient = FALSE){ ndim = length(dim(x)) if (ndim > 2) { stop(paste0("Array of more than 2 dimensions given. ", "If 4D array (such as images), convert to list of ", "3D images")) } res = staple_multi_mat(x, ...) if (ncol(res$probability) == 2) { res$probability = res$probability[,2] res$prior = res$prior[,2] res$sensitivity = res$sensitivity[, 2] res$specificity = res$specificity[, 2] } return(res) }
simLNIRT <- function(N, K, rho, td = FALSE, WL = FALSE, kpa, kpt, kia, kit) { if (missing(kpa)) { kpa <- 0 XPA <- NULL Ba <- NULL } else if (kpa == 0) { XPA <- NULL Ba <- NULL } else { XPA <- matrix(rnorm(kpa * N, sd = .5), ncol = kpa, nrow = N) XPA <- matrix(XPA, ncol = ncol(XPA), nrow = N) - matrix( apply(XPA, 2, mean), ncol = ncol(XPA), nrow = N, byrow = T ) Ba <- matrix(rnorm(kpa), ncol = 1, nrow = kpa) } if (missing(kpt)) { kpt <- 0 XPT <- NULL Bt <- NULL } else if (kpt == 0) { XPT <- NULL Bt <- NULL } else { XPT <- matrix(rnorm(kpt * N, sd = .5), ncol = kpt, nrow = N) XPT <- matrix(XPT, ncol = ncol(XPT), nrow = N) - matrix( apply(XPT, 2, mean), ncol = ncol(XPT), nrow = N, byrow = T ) Bt <- matrix(rnorm(kpt), ncol = 1, nrow = kpt) } if (kpa != 0) { XBa <- XPA %*% Ba } else{ XBa <- rep(0, N) } if (kpt != 0) { XBt <- XPT %*% Bt } else{ XBt <- rep(0, N) } mutheta <- rep(0, 2) covtheta <- diag(2) covtheta[1, 2] <- covtheta[2, 1] <- rho theta <- MASS::mvrnorm(N, mutheta, covtheta, empirical = TRUE) theta[, 1] <- theta[, 1] + XBa theta[, 2] <- theta[, 2] + XBt if (missing(kia)) { kia <- 0 XIA <- NULL Bia <- NULL } else if (kia == 0) { XIA <- NULL Bia <- NULL } else { XIA <- matrix(rnorm(kia * K, sd = .25), ncol = kia, nrow = N) XIA <- matrix(XIA, ncol = ncol(XIA), nrow = K) - matrix( apply(XIA, 2, mean), ncol = ncol(XIA), nrow = K, byrow = T ) Bia <- matrix(rnorm(kia, sd = .75), ncol = 1, nrow = kia) } if (missing(kit)) { kit <- 0 XIT <- NULL Bit <- NULL } else if (kit == 0) { XIT <- NULL Bit <- NULL } else { XIT <- matrix(rnorm(kit * K, sd = .25), ncol = kit, nrow = K) XIT <- matrix(XIT, ncol = ncol(XIT), nrow = K) - matrix( apply(XIT, 2, mean), ncol = ncol(XIT), nrow = K, byrow = T ) Bit <- matrix(rnorm(kit, sd = .75), ncol = 1, nrow = kit) } if (kia != 0) { XBIa <- XIA %*% Bia } else{ XBIa <- rep(0, K) } if (kit != 0) { XBIt <- XIT %*% Bit } else{ XBIt <- rep(0, K) } if (kia != 0 & kit != 0) { covitem <- diag(c(.05, .3, .05, .3)) } if (kia != 0 & kit == 0) { covitem <- diag(c(.05, .3, .05, 1)) } if (kia == 0 & kit != 0) { covitem <- diag(c(.05, 1, .05, .3)) } if (kia == 0 & kit == 0) { covitem <- diag(c(.05, 1, .05, 1)) } muitem <- rep(c(1, 0), 2) sigma2 <- rlnorm(K, meanlog = 0, sdlog = 0.3) if (td && !WL) { ab <- MASS::mvrnorm(K, muitem, covitem) ab[, 3] <- rep(1, K) abn <- MASS::mvrnorm(K, muitem[-3], covitem[-3,-3]) ab[, c(2, 4)] <- abn[, c(2, 3)] - t(matrix(colMeans(abn[, c(2, 3)]), 2, K)) ab[, 1] <- abs(ab[, 1]) ab[, 1] <- ab[, 1] / (prod(ab[, 1]) ^ (1 / K)) } if (WL) { muitem <- c(1, 0, 1, 0) ab <- MASS::mvrnorm(K, muitem, covitem) sigma2 <- 1 / ab[, 3] ^ 2 ab[, 1] <- abs(ab[, 1]) ab[, 1] <- ab[, 1] / (prod(ab[, 1]) ^ (1 / K)) } if (!td && !WL) { ab <- MASS::mvrnorm(K, muitem, covitem) ab[, c(2, 4)] <- ab[, c(2, 4)] - t(matrix(colMeans(ab[, c(2, 4)]), 2, K)) ab[, 1] <- abs(ab[, 1]) ab[, 1] <- ab[, 1] / (prod(ab[, 1]) ^ (1 / K)) ab[, 3] <- abs(ab[, 3]) ab[, 3] <- ab[, 3] / (prod(ab[, 3]) ^ (1 / K)) } ab[, 2] <- ab[, 2] + XBIa ab[, 4] <- ab[, 4] + XBIt par <- theta[, 1] %*% matrix(ab[, 1], nrow = 1, ncol = K) - t(matrix(ab[, 2], nrow = K, ncol = N)) probs <- matrix(pnorm(par), ncol = K, nrow = N) Y <- matrix(runif(N * K), nrow = N, ncol = K) Y <- ifelse(Y < probs, 1, 0) quess <- rep(0.1, K) S <- matrix(0, ncol = K, nrow = N) Y1g <- Yg <- matrix(0, ncol = K, nrow = N) for (kk in 1:K) { S[, kk] <- rbinom(N, 1, quess[kk]) } Yg[S == 1] <- 1 Yg[S == 0 & Y == 1] <- 1 par <- matrix(ab[, 1], ncol = K, nrow = N, byrow = T) * (matrix(theta[, 1], ncol = K, nrow = N) - matrix( ab[, 2], ncol = K, nrow = N, byrow = T )) probs <- matrix(pnorm(par), ncol = K, nrow = N) Y1 <- matrix(runif(N * K), nrow = N, ncol = K) Y1 <- ifelse(Y1 < probs, 1, 0) Y1g[S == 1] <- 1 Y1g[S == 0 & Y1 == 1] <- 1 RT <- RT1 <- matrix(0, ncol = K, nrow = N) for (kk in 1:K) { time <- matrix(rnorm(N, sd = sqrt(sigma2[kk])), nrow = N, ncol = 1) RT1[1:N, kk] <- (ab[kk, 4] - theta[, 2]) + time[1:N] RT[1:N, kk] <- ab[kk, 4] - ab[kk, 3] * theta[, 2] + time[1:N] } out <- list( Y = Y, Yg = Yg, Y1 = Y1, Y1g = Y1g, RT = RT, RT1 = RT1, theta = theta, ab = ab, sigma2 = sigma2, quess = quess, XPA = XPA, XPT = XPT, Ba = Ba, Bt = Bt, XIA = XIA, XIT = XIT, Bia = Bia, Bit = Bit ) class(out) <- c("simLNIRT", "list") return(out) }
context("get_recently_candidates") test_that("expected errors", { expect_warning(expect_error(get_recently_candidates(16), "Incorrect cycle"), "Cycle should be four-digit year") expect_error(get_recently_candidates(1996), "Cycle should be four-digit even-numbered year between 2010 and 2018") expect_error(get_recently_candidates(2008), "Cycle should be four-digit even-numbered year between 2010 and 2018") expect_warning(expect_error(get_recently_candidates(1995), "Incorrect cycle"), "Cycle should be four-digit year larger than 1996") expect_warning(expect_error(get_recently_candidates(2007), "Incorrect cycle"), "Cycle should be even-numbered year larger than 1996") }) test_that("expected lengths", { expect_length(get_recently_candidates(2016), 5) })
probitInverse <- function(mu, sigma, fittedModel=NULL){ probitInverseVec <- Vectorize( function(mu, sigma){ mp <- vp <- NA try({ mp <- integrate(function(x) pnorm(x)*dnorm(x, mu, sigma), mu-5*sigma, mu+5*sigma)$value vp <- integrate(function(x) (pnorm(x)-mp)^2*dnorm(x, mu, sigma), mu-5*sigma, mu+5*sigma)$value }) if(!is.na(vp) && vp<0){ vp <- NA }else if(is.na(vp)){ mp <- NA } return(c(mean=mp, sd = sqrt(vp))) }, c("mu","sigma")) if(missing(fittedModel) || is.null(fittedModel)){ res <- t(probitInverseVec(mu, sigma)) if(any(is.na(res))) { cat("Transformation resulted in NAs for:\n") print(cbind(mu=mu, sigma=sigma, res)[apply(is.na(res),1,any),]) } return(res) }else{ if(!inherits(fittedModel, "traitMPT")) stop("'fittedModel' must be a latent-trait MPT model.") samp <- fittedModel$runjags$mcmc[,c()] thetaNames <- fittedModel$mptInfo$thetaUnique sel.mu <- grep("mu", varnames(fittedModel$runjags$mcmc)) sel.sig <- grep("sigma", varnames(fittedModel$runjags$mcmc)) s.mu <- fittedModel$runjags$mcmc[,sel.mu] s.sig <- fittedModel$runjags$mcmc[,sel.sig] for(cc in 1:length(s.mu)){ for(s in 1:ncol(s.mu[[cc]])){ res <- probitInverseVec(mu = s.mu[[cc]][,s], sigma=s.sig[[cc]][,s]) rownames(res) <- paste0(c("mean_","sd_"), thetaNames[s]) samp[[cc]] <- cbind(samp[[cc]], t(res)) } samp[[cc]] <- mcmc(samp[[cc]]) attr(samp[[cc]], "mcpar") <- attr(fittedModel$runjags$mcmc[[cc]], "mcpar") } return(as.mcmc.list(samp)) } }
compute_sel1_trapez <- function(gam, knots, t.alpha, nodes, weights, s.spl, wvec, psinu.zvec, h1, cons, exp.w){ ISEL1.zvec <- rep(0, length(wvec)) for(i in 1:length(wvec)){ w <- wvec[i] ISEL1.zvec[i] <- ISEL_legendre(gam, w, knots, t.alpha, nodes, weights, s.spl) } out.int <- h1 * PreciseSums::kahanSum(ISEL1.zvec * psinu.zvec) sel1 <- 1 + (cons * out.int) / (t.alpha * exp.w) }
model.importance.plot<-function( model.obj.1=NULL, model.obj.2=NULL, model.name.1="Model 1", model.name.2="Model 2", imp.type.1=NULL, imp.type.2=NULL, type.label=TRUE, class.1=NULL, class.2=NULL, quantile.1=NULL, quantile.2=NULL, col.1="grey", col.2="black", scale.by="sum", sort.by="model.obj.1", cf.mincriterion.1 = 0, cf.conditional.1 = FALSE, cf.threshold.1 = 0.2, cf.nperm.1 = 1, cf.mincriterion.2 = 0, cf.conditional.2 = FALSE, cf.threshold.2 = 0.2, cf.nperm.2 = 1, predList=NULL, folder=NULL, PLOTfn=NULL, device.type=NULL, res=NULL, jpeg.res=72, device.width=7, device.height=7, units="in", pointsize=12, cex=par()$cex, ...){ if(.Platform$OS.type=="windows"){ Filters<-rbind(Filters,img=c("Imagine files (*.img)", "*.img")) Filters<-rbind(Filters,csv=c("Comma-delimited files (*.csv)", "*.csv"))} device.type<-check.device.type(device.type) if(is.null(res)){res<-jpeg.res} if(is.null(folder)){ if(any(device.type%in%c("jpeg","pdf","postscript"))){ if(.Platform$OS.type=="windows"){ folder<-choose.dir(default=getwd(), caption="Select directory") }else{ folder<-getwd()} } } if(is.null(PLOTfn)){PLOTfn<- paste(model.name.1,"_",model.name.2,sep="")} if(identical(basename(PLOTfn),PLOTfn)){ PLOTfn<-file.path(folder,PLOTfn)} if(is.null(model.obj.1)){ if(is.null(MODELfn)){ if(.Platform$OS.type=="windows"){ MODELfn <- choose.files(caption="Select first model", filters = Filters["All",], multi = FALSE) if(is.null(MODELfn)){stop("must provide a model object")} }else{stop("must provide a model object")} } modelname<-load(MODELfn) if(length(modelname)!= 1){ stop("file must contain single model object")} assign("model.obj.1",get(modelname)) } if(is.null(model.obj.2)){ if(is.null(MODELfn)){ if(.Platform$OS.type=="windows"){ MODELfn <- choose.files(caption="Select second model", filters = Filters["All",], multi = FALSE) if(is.null(MODELfn)){stop("must provide a model object")} }else{stop("must provide a model object")} } modelname<-load(MODELfn) if(length(modelname)!= 1){ stop("file must contain single model object")} assign("model.obj.2",get(modelname)) } model.type.1<-check.model.type(model.obj.1) model.type.2<-check.model.type(model.obj.2) if(model.type.1=="QRF"){ stop("Importance not currently available for QRF models") if("QRF"%in%names(model.obj.1)){model.obj.1<-model.obj.1$QRF}} if(model.type.2=="QRF"){ stop("Importance not currently available for QRF models") if("QRF"%in%names(model.obj.2)){model.obj.2<-model.obj.2$QRF}} if(model.type.1=="CF" || model.type.2=="CF"){REQUIRE.party()} if(model.type.1=="QRF" || model.type.2=="QRF"){REQUIRE.quantregForest()} if(model.type.1=="CF" || model.type.2=="CF"){ WARN.IM<-TRUE }else{ WARN.IM<-FALSE } predList.1<-check.predList(model.obj=model.obj.1,model.type=model.type.1) predList.2<-check.predList(model.obj=model.obj.2,model.type=model.type.2) if(!identical(sort(predList.1),sort(predList.2))){ stop("'model.obj.1' contains different predictors than 'model.obj.2'") } if(!is.null(predList)){ if(!identical(sort(predList),sort(predList.1))){ stop("predList contains different predictors than models") } } response.type.1<-check.response.type(model.obj=model.obj.1,model.type=model.type.1,ONEorTWO="model.obj.1") response.type.2<-check.response.type(model.obj=model.obj.2,model.type=model.type.2,ONEorTWO="model.obj.2") if(model.type.1=="RF"){ if(is.null(imp.type.1)){imp.type.1<-1} if(!is.null(class.1) && imp.type.1==2){ warning("no class specific measure for 'imp.type.1=2' therefore importance type changed to 'imp.type.1=1'",immediate.=WARN.IM) imp.type.1<-1} IMP.1<-imp.extract.rf(model.obj.1,imp.type=imp.type.1,class=class.1) } if(model.type.1=="QRF"){ if(is.null(imp.type.1)){imp.type.1<-1} if(!is.null(class.1)){ warning("no class specific measure for QRF therefore 'class.1' ignored",immediate.=WARN.IM) class.1<-NULL} if(!"quantiles"%in%names(model.obj.1)){stop("QRF 'model.obj.1' was built with 'importance=FALSE' therefore no importances available")} quantile.names.1<-paste("quantile=",model.obj.1$quantiles) if(is.numeric(quantile.1)){quantile.1<-paste("quantile=",quantile.1)} if(!quantile.1%in%quantile.names.1){ warning("quantile.1 (", quantile.1, ") not found in model.obj.1",immediate.=TRUE) quantile.1<-NULL} if(is.null(quantile.1)){quantile.1 <- select.list(quantile.names.1, title="Model 1", multiple = FALSE)} if(length(quantile.1)==0 || is.null(quantile.1) || !quantile.1%in%quantile.names.1){ stop("must provide valid quantile for model.obj.1")} IMP.1<-imp.extract.qrf(model.obj.1,imp.type=imp.type.1,ONEorTWO="model.obj.1") IMP.1<-IMP.1[,c("pred",quantile.1)] names(IMP.1)<-c("pred","imp") IMP.1<-IMP.1[order(IMP.1$imp),] } if(model.type.1=="CF"){ if(is.null(imp.type.1)){imp.type.1<-1} if(!is.null(class.1)){ warning("no class specific measure for CF models therefore 'class.1' ignored",immediate.=WARN.IM) class.1<-NULL} if(imp.type.1==2 && response.type.1!="binary"){ warning("AUC-based variables importances only available for binary response models therefor importance type changed to 'imp.type.1=1'",immediate.=WARN.IM) imp.type.1<-1} IMP.1<-imp.extract.cf( model.obj.1,imp.type=imp.type.1,mincriterion=cf.mincriterion.1, conditional=cf.conditional.1,threshold=cf.threshold.1,nperm=cf.nperm.1) } if(model.type.2=="RF"){ if(is.null(imp.type.2)){imp.type.2<-1} if(!is.null(class.2) && imp.type.2==2){ warning("no class specific measure for 'imp.type.2=2' therefore importance type changed to 'imp.type.2=1'",immediate.=WARN.IM) imp.type.2<-1} IMP.2<-imp.extract.rf(model.obj.2,imp.type=imp.type.2,class=class.2) } if(model.type.2=="QRF"){ if(is.null(imp.type.2)){imp.type.2<-1} if(!is.null(class.2)){ warning("no class specific measure for QRF therefore 'class.2' ignored",immediate.=WARN.IM) class.2<-NULL} if(!"quantiles"%in%names(model.obj.2)){stop("QRF 'model.obj.2' was built with 'importance=FALSE' therefore no importances available")} quantile.names.2<-paste("quantile=",model.obj.2$quantiles) if(is.numeric(quantile.2)){quantile.2<-paste("quantile=",quantile.2)} if(!quantile.2%in%quantile.names.2){ warning("quantile.2 (", quantile.2, ") not found in model.obj.2",immediate.=TRUE) quantile.2<-NULL} if(is.null(quantile.2)){quantile.2 <- select.list(quantile.names.2, title="Model 2", multiple = FALSE)} if(length(quantile.2)==0 || is.null(quantile.2) || !quantile.2%in%quantile.names.2){ stop("must provide valid quantile for model.obj.2")} IMP.2<-imp.extract.qrf(model.obj.2,imp.type=imp.type.2,ONEorTWO="model.obj.2") IMP.2<-IMP.2[,c("pred",quantile.2)] names(IMP.2)<-c("pred","imp") IMP.2<-IMP.2[order(IMP.2$imp),] } if(model.type.2=="CF"){ if(is.null(imp.type.2)){imp.type.2<-1} if(!is.null(class.2)){ warning("no class specific measure for CF models therefore 'class.2' ignored",immediate.=WARN.IM) class.2<-NULL} if(imp.type.2==2 && response.type.2!="binary"){ warning("AUC-based variables importances only available for binary response models therefor importance type changed to 'imp.type.2=1'",immediate.=WARN.IM) imp.type.2<-1} IMP.2<-imp.extract.cf( model.obj.2,imp.type=imp.type.2,mincriterion=cf.mincriterion.2, conditional=cf.conditional.2,threshold=cf.threshold.2,nperm=cf.nperm.2) } IMP<-list(IMP1=IMP.1,IMP2=IMP.2) if(is.null(class.1)){ CLASS.1<-"Overall" }else{ CLASS.1<-paste("Class",class.1) } if(is.null(class.2)){ CLASS.2<-"Overall" }else{ CLASS.2<-paste("Class",class.2) } if(model.type.1=="RF"){ if(response.type.1%in%c("continuous")){ if(imp.type.1==1){ print(paste("model.obj.1 is a continuous RF model with", CLASS.1, "Importance measured by %IncMSE")) IMP.MEASURE.1<-"%IncMSE"} if(imp.type.1==2){ print(paste("model.obj.1 is a continuous RF model with", CLASS.1, "Importance measured by IncNodePurity")) IMP.MEASURE.1<-"IncNodePurity"} } if(response.type.1%in%c("binary","categorical")){ if(imp.type.1==1){ print(paste("model.obj.1 is a", response.type.1, "RF model with", CLASS.1, "Importance measured by MeanDecreaseAccuracy")) IMP.MEASURE.1<-"MeanDecAccuracy"} if(imp.type.1==2){ print(paste("model.obj.1 is a", response.type.1, "RF model with", CLASS.1, "Importance measured by MeanDecreaseGini")) IMP.MEASURE.1<-"MeanDecGini"} } } if(model.type.1=="QRF"){ IMP.MEASURE.1<-paste(quantile.1) print(paste("model.obj.1 is continuous response QRF model with",IMP.MEASURE.1))} if(model.type.1=="CF"){ if(imp.type.1==1){ if(cf.conditional.1 == FALSE){ print(paste("model.obj.1 is a", response.type.1, "CF model with unconditional importance measured by MeanDecreaseAccuracy"))} if(cf.conditional.1 == TRUE){ print(paste("model.obj.1 is a", response.type.1, "CF model with conditional importance measured by MeanDecreaseAccuracy"))} IMP.MEASURE.1<-"MeanDecAccuracy" } if(imp.type.1==2){ if(cf.conditional.1 == FALSE){ print(paste("model.obj.1 is a", response.type.1, "CF model with unconditional importance measured by mean decrease in AUC"))} if(cf.conditional.1 == TRUE){ print(paste("model.obj.1 is a", response.type.1, "CF model with conditional importance measured by mean decrease in AUC"))} IMP.MEASURE.1<-"MeanDecAUC" } } if(model.type.2=="RF"){ if(response.type.2%in%c("continuous")){ if(imp.type.2==1){ print(paste("model.obj.2 is a continuous RF model with", CLASS.2, "Importance measured by %IncMSE")) IMP.MEASURE.2<-"%IncMSE"} if(imp.type.2==2){ print(paste("model.obj.2 is a continuous RF model with", CLASS.2, "Importance measured by IncNodePurity")) IMP.MEASURE.2<-"IncNodePurity"} } if(response.type.2%in%c("binary","categorical")){ if(imp.type.2==1){ print(paste("model.obj.2 is a", response.type.2, "RF model with", CLASS.2, "Importance measured by MeanDecreaseAccuracy")) IMP.MEASURE.2<-"MeanDecAccuracy"} if(imp.type.2==2){ print(paste("model.obj.2 is a", response.type.2, "RF model with", CLASS.2, "Importance measured by MeanDecreaseGini")) IMP.MEASURE.2<-"MeanDecGini"} } } if(model.type.2=="QRF"){ IMP.MEASURE.2<-paste(quantile.2) print(paste("model.obj.2 is continuous response QRF model with",IMP.MEASURE.2))} if(model.type.2=="CF"){ if(imp.type.2==1){ if(cf.conditional.2 == FALSE){ print(paste("model.obj.2 is a", response.type.2, "CF model with unconditional importance measured by MeanDecreaseAccuracy"))} if(cf.conditional.2 == TRUE){ print(paste("model.obj.2 is a", response.type.2, "CF model with conditional importance measured by MeanDecreaseAccuracy"))} IMP.MEASURE.2<-"MeanDecAccuracy" } if(imp.type.2==2){ if(cf.conditional.2 == FALSE){ print(paste("model.obj.1 is a", response.type.2, "CF model with unconditional importance measured by mean decrease in AUC"))} if(cf.conditional.2 == TRUE){ print(paste("model.obj.1 is a", response.type.2, "CF model with conditional importance measured by mean decrease in AUC"))} IMP.MEASURE.2<-"MeanDecAUC" } } if(!scale.by %in% c("max","sum")){ stop("scale.by must be either max or sum")} IMP.1<-imp.scale(IMP.1,scale.by=scale.by) IMP.2<-imp.scale(IMP.2,scale.by=scale.by) if(scale.by=="sum"){ MAX.IMP<-max(IMP.1$imp,IMP.2$imp) IMP.1$imp<-IMP.1$imp/MAX.IMP IMP.2$imp<-IMP.2$imp/MAX.IMP } if(!identical(sort(as.character(IMP.1$pred)),sort(as.character(IMP.2$pred)))){ stop("models contain different predictors") } if(!sort.by %in% c("predList","model.obj.1","model.obj.2")){ stop("sort.by must be 'model.obj.1' or 'model.obj.2' or 'predList'")} if(sort.by=="model.obj.1"){ sort.by=IMP.1$pred }else{ if(sort.by=="model.obj.2"){ sort.by=IMP.2$pred }else{ if(sort.by=="predList"){ sort.by=rev(predList) } } } IMP.1<-IMP.1[match(sort.by,IMP.1$pred),] IMP.2<-IMP.2[match(sort.by,IMP.2$pred),] names.arg=IMP.1$pred NCHAR<-max(nchar(as.character(names.arg))) for(i in 1:length(device.type)){ initialize.device( PLOTfn=PLOTfn,DEVICE.TYPE=device.type[i], res=res,device.width=device.width,device.height=device.height, units=units,pointsize=pointsize,cex=cex) op<-par(mar=par()$mar+c(0,(2*NCHAR/3)-2,0,0),cex=cex) barplot(-IMP.1$imp,horiz=TRUE,xlim=c(-1,1),las=1,col=col.1,axes=F,names.arg=names.arg,...) barplot(IMP.2$imp,horiz=TRUE,xlim=c(-1,1),las=1,col=col.2,add=TRUE,axes=F,...) IMP.TEXT<-paste(IMP.MEASURE.1," ",IMP.MEASURE.2) if(type.label){ mtext(IMP.MEASURE.1,side=1, line=0, adj=0, cex=1*cex) mtext(IMP.MEASURE.2,side=1, line=0, adj=1, cex=1*cex)} mtext(model.name.1,side=1, line=1.5, adj=0, cex=1.3*cex) mtext(model.name.2,side=1, line=1.5, adj=1, cex=1.3*cex) par(op) if(!device.type[i]%in%c("default","none")){dev.off()} } return(IMP) }
NonlinearityTests <-function(HRVData, indexNonLinearAnalysis =length(HRVData$NonLinearAnalysis)){ CheckAnalysisIndex(indexNonLinearAnalysis, length(HRVData$NonLinearAnalysis),"nonlinear") CheckNIHR(HRVData) VerboseMessage(HRVData$Verbose, "Performing nonlinearity tests") tseries = HRVData$Beat$RR HRVData$NonLinearAnalysis[[indexNonLinearAnalysis]]$NonlinearityTests = nonlinearityTest(time.series = tseries, verbose = HRVData$Verbose) return(HRVData) } SurrogateTest <- function(HRVData, indexNonLinearAnalysis = length(HRVData$NonLinearAnalysis), significance = 0.05, oneSided=FALSE, alternative = c("smaller","larger"), K=1, useFunction, xlab="Values of the statistic", ylab="", main="Surrogate data testing on the RR intervals", doPlot = TRUE, ...){ CheckAnalysisIndex(indexNonLinearAnalysis, length(HRVData$NonLinearAnalysis),"nonlinear") CheckNIHR(HRVData) tseries = HRVData$Beat$RR HRVData$NonLinearAnalysis[[indexNonLinearAnalysis]]$SurrogateTest = surrogateTest(time.series = tseries, significance = significance, one.sided = oneSided,alternative = alternative, K = K, xlab = xlab, ylab = ylab, main = main, verbose = HRVData$Verbose, do.plot = doPlot, FUN = useFunction, ...) return(HRVData) }
.scagnostics.names <- c("Outlying", "Skewed", "Clumpy", "Sparse", "Striated", "Convex", "Skinny", "Stringy", "Monotonic") scagnostics <- function(x, ...) UseMethod("scagnostics", x) .scagnostics.for.data <- function(data, bins, maxBins, names=NULL) { results <- .jcall("scagnostics/Main","[[D","computeScagnostics",data,as.integer(bins)[1],as.integer(maxBins)[1]) r <- lapply(results, .jevalArray) n <- length(r) s <- length(r[[1]]) if (n == 1) { r <- r[[1]] names(r) <- .scagnostics.names } else { r <- matrix(unlist(r), s) rownames(r) <- .scagnostics.names if (!is.null(names)) { dn <- length(names) l <- data.frame(x=rep(1:dn,dn),y=rep(1:dn,each=dn)) l <- l[l$x < l$y,] colnames(r) <- paste(names[l$x], "*", names[l$y]) } } class(r) <- "scagnostics" r } scagnostics.default <- function(x, y, bins=50, maxBins=1000, ...) { if (length(x) != length(y)) stop("x and y must have the same length") complete <- !is.na(x) & !is.na(y) x <- as.double(x[complete]) y <- as.double(y[complete]) data <- .jarray(list(.jarray(x),.jarray(y)),"[D") .scagnostics.for.data(data, bins, maxBins) } scagnostics.data.frame <- function(x, bins=50, maxBins=1000, ...) { if (dim(x)[2] < 1) stop("need at least two variables") data <- .jarray(lapply(x, function(x) .jarray(as.double(x))), "[D") .scagnostics.for.data(data, bins, maxBins, names(x)) } scagnostics.list <- function(x, bins=50, maxBins=1000, ...) { if (length(x) < 2) stop("need at least two variables") n <- unlist(lapply(x, length)) if (!all(n == n[1])) stop("all variables must have the same length") data <- .jarray(lapply(x, function(x) .jarray(as.double(x))), "[D") nam <- names(x) if (is.null(nam)) nam <- as.character(1:length(x)) .scagnostics.for.data(data, bins, maxBins, nam) } scagnostics.matrix <- function(x, bins=50, maxBins=1000, ...) { if (dim(x)[2] < 1) stop("need at least two variables") data <- .jarray(lapply(1:(dim(x)[2]), function(i) .jarray(as.double(x[,i]))), "[D") nam <- colnames(x) if (is.null(nam)) nam <- as.character(1:length(x)) .scagnostics.for.data(data, bins, maxBins, nam) } scagnosticsOutliers <- function(scagnostics) { if (!inherits(scagnostics, "scagnostics")) stop("scagnostics must be of the class `scagnostics'") js <- if (!is.matrix(scagnostics)) .jarray(.jarray(scagnostics), "[D") else .jarray(lapply(1:(dim(scagnostics)[2]), function(i) .jarray(as.double(scagnostics[,i]))), "[D") result <- .jcall("scagnostics.Scagnostics", "[Z", "computeScagnosticsOutliers", js) if (!is.null(colnames(scagnostics))) names(result) <- colnames(scagnostics) result } scagnosticsExemplars <- function(scagnostics) { if (!inherits(scagnostics, "scagnostics")) stop("scagnostics must be of the class `scagnostics'") js <- if (!is.matrix(scagnostics)) .jarray(.jarray(scagnostics), "[D") else .jarray(lapply(1:(dim(scagnostics)[2]), function(i) .jarray(as.double(scagnostics[,i]))), "[D") result <- .jcall("scagnostics.Scagnostics", "[Z", "computeScagnosticsExemplars", js) if (!is.null(colnames(scagnostics))) names(result) <- colnames(scagnostics) result } scagnosticsGrid <- function(scagnostics) { if (!inherits(scagnostics, "scagnostics")) stop("scagnostics must be of the class `scagnostics'") n <- as.integer(sqrt(2 * dim(scagnostics)[2] + 0.25) + 1) l <- data.frame(x=rep(1:n,n), y=rep(1:n, each=n)) l[l$x < l$y,] } .onLoad <- function(libname, pkgname) .jpackage("scagnostics", "scagnostics.jar")
nmm <- function(data, eq_type = c("joint", "cont", "disc"), eq_d = NULL, eq_c = NULL, par_c = NULL, par_d = NULL, start_v = NULL, check_hess = TRUE, corrl = TRUE, weight_paths = TRUE, weight_paths_cont = FALSE, data_weight = NULL, estimate = TRUE, fixed_term = FALSE, best_method = FALSE, DEoptim_run = FALSE, hessian = "joint_hess", print_out = FALSE, diff_hessian = FALSE, bayesian_random = FALSE, DEoptim_run_main = FALSE, deconst = 2, numerical_deriv = FALSE, best_method4start = FALSE, eqsys = "sur", miterlim = 10000, opt_method = "BFGS", try_last_DEoptim = TRUE, transform=NULL, MNtypef = "logit", nmm_object = NULL) { . <- NULL PeID <- NULL mutate <- NULL WeID <- NULL objm <- NULL mnp <- NULL if(MNtypef=="dogit"&eq_type!="cont"){ pardogit <- paste0("capt", 1:length(eq_d)) }else{ pardogit <- NULL } if(eq_type=="cont"){ pardogit <- NULL } if(eq_type!="joint"){ corrl <- FALSE } data %<>% data.frame(.) data %<>% replace(., is.na(.), 0) if(any(unlist(data)%in%c(NA, Inf, -Inf, NaN))){ indx <- apply(data, 1, function(x) any(x%in%c(NA, Inf, -Inf, NaN)) ) %>% which nindx <- length(indx) indx <- sample(indx, min(6, nindx)) print(paste0("Rows (sampled, in total ", nindx," rows): ", paste0(indx, collapse = ", "), " have non-normal values! Stopping.")) stop() } if(!is.null(eq_c)){ par_c %<>% sort para_cont <- get_par(par_c, eq_c) cheqs0 <- para_cont$cheqs0 }else{ cheqs0 <- NULL } if(!is.null(eq_d)){ par_d %<>% sort ffor <- get_par(par_d, eq_d)$cheqs0 }else{ ffor <- NULL } if(is.null(transform)){ transform <- if(eq_type == "joint") TRUE else FALSE } indp <- eq_type!="cont" indc <- eq_type!="disc" data <- prepare_data(data, avl = indp, chc = indp, wd = indp, nc = length(cheqs0), wc = indc, weights = data_weight, weight_paths = weight_paths, weight_paths_cont = weight_paths_cont) if(!is.null(start_v)){ start_v <- check_names_start(start_v) start_v <- start_v[c(par_c,par_d[-1])] } if(is.null(start_v)&estimate&MNtypef=="dogit"){ mc <- match.call() mc[["MNtypef"]] <- "logit" start_v <- eval(mc)$estimate stp <- rep(1/length(pardogit), length(pardogit)) names(stp) <- pardogit start_v <- c(start_v,stp) }else{ if(is.null(start_v)&estimate){ start_v <- get_start(eq_c = eq_c, par_c = par_c, par_d = par_d, eq_d = eq_d, data = data, datan="data", part = eq_type, DEoptim_run = DEoptim_run, hessian = NULL, best_method = best_method4start, transform=transform, MNtypef=MNtypef, pardogit=pardogit, opt_method = opt_method, numerical_deriv=numerical_deriv) } } methodopt <- opt_method data_name <- "data" separatenmm <- FALSE if(diff_hessian==TRUE){ datan <- copy(data) wnames <- c(paste0('wd_', 1:length(ffor)), paste0('wc_', 1:length(cheqs0))) data_weightn <- data.frame(matrix(1, ncol=length(wnames), nrow=nrow(datan)), stringsAsFactors = FALSE) names(data_weightn) <- wnames datan <- add_variable(data = datan, dname = "weights", weights = data_weightn) datan <- ddply(datan, .(PeID), mutate, npaths = length(WeID)) datan$npaths_cont <- 1 data_name <- "datan" } if(is.null(nmm_object)){ if(is.null(start_v)){ start_v <- rep(0, length(c(par_c, par_d))) } cdmr <- get_nmm_functions(corrl, eq_type, cheqs0, ffor, objm, print_out, bayesian_random, fixed_term, mnp, start_v, data_name, check_hess, hessian, eqsys, diff_hessian, MNtypef=MNtypef) }else{ cdmr <- attributes(nmm_object)$functions nn_cdmr <- c(paste0(rep(c("joint_", "cont_","text_"), rep(3, 3)), c("func", "grad", "hess")),paste0("text_", c("bd", "gd", "edd"))) names(cdmr) <- nn_cdmr[1:length(names(cdmr))] } joint_func <- cdmr$joint_func joint_grad <- cdmr$joint_grad joint_hess <- cdmr$joint_hess separatenmm <- cdmr$separatenmm if(corrl==TRUE&any(eq_type=="joint")){ cont_func <- cdmr$cont_func cont_grad <- cdmr$cont_grad cont_hess <- cdmr$cont_hess text_func <- cdmr$text_func text_grad <- cdmr$text_grad text_hess <- cdmr$text_hess text_bd <- cdmr$text_bd text_gd <- cdmr$text_gd text_edd <- cdmr$text_edd environment(cont_func) <- environment(cont_grad) <- environment(cont_hess) <- environment() } if(corrl==FALSE){ separatenmm <- FALSE } environment(joint_func) <- environment(joint_grad) <- environment(joint_hess) <- environment() functionsl <- if(corrl == TRUE&any(eq_type == "joint")){ list(jfunc = joint_func, jgrad = joint_grad, jhess = joint_hess, cfunc = cont_func, cgrad = cont_grad, chess = cont_hess, text_func = text_func, text_grad = text_grad, text_hess=text_hess, text_bd=text_bd, text_gd=text_gd, text_edd=text_edd) } else{ list(jfunc = joint_func, jgrad = joint_grad, jhess = joint_hess) } if(estimate == TRUE){ if(numerical_deriv){ joint_grad <- NULL joint_hess <- NULL check_hess <- FALSE } possible_m <- c("BFGS", "NR", "CG", "NM", "SANN", "BHHH") if(best_method == TRUE){ res <- nmm_best(joint_func, joint_grad, joint_hess, start_v, "NA", miterlim, possible_m, eq_type, corrl) resif <- try_if(res) }else{ if(DEoptim_run_main){ res <- nmm_DEoptim(joint_func, joint_grad, joint_hess, start_v, "NA", miterlim, possible_m, deconst, eq_type, corrl) resif <- try_if(res) MLerror <- resif }else{ MLerror <- FALSE } if(DEoptim_run_main == FALSE|MLerror){ res <- nmm_1good(joint_func, joint_grad, joint_hess, start_v, "NA", miterlim, possible_m, methodopt, eq_type, corrl) } resif <- try_if(res) } resif <- try_if(res) if(resif&try_last_DEoptim){ stde <- if(is.null(res$estimate)) start_v stde <- if (is.na(sum(joint_func(start_v)))) stde else start_v if(!is.na(sum(joint_func(start_v)))&!is.na(sum(joint_func(res$estimate)))){ stde <- if(joint_func(start_v)>joint_func(res$estimate)) start_v else res$estimate } res <- nmm_lastDEoptim(joint_func, joint_grad, joint_hess, stde, "NA", miterlim, possible_m, deconst, eq_type, corrl) resif <- try_if(res) } estj <- joint_func(res$estimate) estja <- attributes(estj)[[1]] if(length(estja)>0){ names(estja) <- paste0('eq_', 1:length(estja)) }else{ estja <- estj } res$gradient <- gradient.nmm(res) res$hessian <- hessian.nmm(res) }else{ res <- "object" estja <- NA } a <- c(attributes(res), list(functions = functionsl, data = data, LL = estja, type = eq_type, cont_e = cheqs0, disc_e = ffor, eq_c = eq_c, eq_d = eq_d, par_c = par_c, par_d = par_d, corr_joint=corrl)) if(any(class(res)%in%"maxLik")){ res <- res }else{ res <- list(res) } attributes(res) <- a class(res) <- c("nmm", class(res)) res$call$data <- "data" if(data %>% dplyr::select(dplyr::starts_with("chc")) %>% ncol>0){ res$freq <- try(data %>% dplyr::select(dplyr::starts_with("chc")) %>% colSums, silent = TRUE) }else{ res$freq <- NULL } res } check_names_start <- function(start_v){ nstv <- names(start_v) if(is.null(nstv)){ print("Provide names for `start_v`!") stop() }else{ start_v[order(names(start_v))] } } nmm_best <- function(joint_func, joint_grad, joint_hess, start_v, method = NULL, miterlim, possible_m, eq_type, corrl) { . <- NULL print('optimization searches for the best result.') if(is.null(joint_hess)){ reslist <- lapply(possible_m, function(x) try(maxLik(joint_func, start = start_v, method = x, iterlim = miterlim), silent=TRUE)) }else{ reslist <- lapply(possible_m, function(x) try(maxLik(joint_func, grad = joint_grad, hess = joint_hess, start = start_v, method = x, iterlim = miterlim), silent=TRUE)) } res <- reslist[[1]] indr <- sapply(reslist, try_if) reslist <- reslist[!indr] if(length(reslist)>0){ indr <- sapply(reslist, function(x)x$maximum) res <- reslist[[which.max(indr)[1]]] } return(res) } nmm_1good <- function(joint_func, joint_grad, joint_hess, start_v, method = NULL, miterlim, possible_m, methodopt = "BFGS", eq_type, corrl) { . <- NULL res <- try(try_alg(joint_func, joint_grad, joint_hess, methodim = methodopt, miterlim, start_v, ki = 1, k = 2, eq_type=eq_type, corrl=corrl), silent = TRUE) im <- 1 resif <- try_if(res) possible_m <- possible_m[!possible_m%in%methodopt] while(resif&im <= length(possible_m)){ print(paste0("Algorithm ", ifelse(im == 1, methodopt, possible_m[im-1]), " produced an error. Trying out next algorithm.")) res <- try(try_alg(joint_func, joint_grad, joint_hess, methodim=possible_m[im], miterlim, start_val = start_v, ki = 1, k = 2, eq_type=eq_type, corrl=corrl), silent=TRUE) resif <- try_if(res) if(resif){ res <- try(try_alg(joint_func, joint_grad, joint_hess, methodim=possible_m[im], miterlim, start_v, ki = 1, k = 1, eq_type=eq_type, corrl=corrl), silent=TRUE) resif <- try_if(res) } im <- im+1 } return(res) } nmm_DEoptim <- function(joint_func, joint_grad, joint_hess, start_v = NULL, method = NULL, miterlim, possible_m, deconst = 2, eq_type, corrl) { . <- NULL print('DEoptim is used for optimization. This may take a while.') res <- nmm_1good(joint_func = joint_func, joint_grad=joint_grad, joint_hess=joint_hess, start_v=start_v, method="NA", miterlim=miterlim, possible_m=possible_m, eq_type=eq_type, corrl=corrl, methodopt=method) res1 <- nmm_1good(joint_func = joint_func, joint_grad=joint_grad, joint_hess=joint_hess, start_v=res$estimate, method="NA", miterlim=1000000, possible_m=possible_m, eq_type=eq_type, corrl=corrl, methodopt="NM") resif <- try_if(res) initialpop <- matrix(c(res1$estimate ) %>% rep(.,length(start_v)), ncol = length(start_v), byrow = TRUE) initialpop <- rbind(initialpop - rep(-0.0001, length(start_v)) %>% diag, initialpop + rep(-0.0001, length(start_v)) %>% diag) initialpop <- rbind(res$estimate,res1$estimate,initialpop) jj_f <- function(par){ res <- joint_func(par) -res } environment(jj_f) <- environment() deconst <- max(ceiling(max(abs(res$estimate))), deconst) reso <- DEoptim(jj_f, lower = rep(-deconst, length(start_v)), upper = rep(deconst, length(start_v)), control = list(trace = TRUE, initialpop = initialpop, itermax=1000)) st_new <- reso$optim$bestmem names(st_new) <- names(start_v) if(is.null(joint_hess)){ res <- try(maxLik(joint_func, start = st_new, iterlim = miterlim, method = "BFGS"), silent = TRUE) resnm <- try(maxLik(joint_func, start = res$estimate, iterlim = 1000000, method = "NM"), silent = TRUE) }else{ res <- try(maxLik(joint_func, grad = joint_grad, hess = joint_hess, start = st_new, iterlim = miterlim, method = "BFGS"), silent = TRUE) resnm <- try(maxLik(joint_func, grad = joint_grad, hess = joint_hess, start = res$estimate, iterlim = 1000000, method = "NM"), silent = TRUE) } if(res$maximum<resnm$maximum){ res <- resnm } resif <- try_if(res) if(resif){ reso <- DEoptim(jj_f, lower = res$estimate-0.5, upper = res$estimate + 0.5, control = list(trace = FALSE)) st_new <- reso$optim$bestmem names(st_new) <- names(start_v) res$estimate <- st_new res$gradient <- joint_grad(st_new) res$hessian <- joint_hess(st_new) res$type <- "DEoptim" res$maximum <- joint_func(st_new) } return(res) } nmm_lastDEoptim <- function(joint_func, joint_grad, joint_hess, start_v = NULL, method = NULL, miterlim, possible_m, deconst = 2, eq_type, corrl) { . <- NULL paste0("All maxLik algorithms produced errors. Trying out DEoptim. This may take a while.") jj_f <- function(par){ res <- joint_func(par) -res } environment(jj_f) <- environment() if(!is.null(start_v)){ if(any(is.na(start_v))){ start_v[is.na(start_v)] <- 0 } initialpop <- matrix(c(start_v + rnorm(length(start_v) * 1000, sd = 0.01)), ncol = length(start_v), byrow = TRUE) deconst <- start_v %>% abs %>% max + 1 reso <- try(DEoptim(jj_f, lower = rep(-deconst, length(start_v)), upper = rep(deconst, length(start_v)), control = list(trace = FALSE, itermax = 1000, VTR = 10000000, initialpop = initialpop)), silent = TRUE) if(any(class(reso)%in%"try-error")){ vals_pop <- apply(initialpop, 1, jj_f) initialpop <- initialpop[!is.nan(vals_pop),] if(nrow(initialpop)==0){ stop("No initial population values for DEoptim found!") }else{ reso <- DEoptim(jj_f, lower = rep(-deconst, length(start_v)), upper = rep(deconst, length(start_v)), control = list(trace = FALSE, itermax = 1000, VTR = 10000000, initialpop = initialpop)) } } st_new <- reso$optim$bestmem names(st_new) <- names(start_v) if(is.null(joint_hess)){ res <- try(maxLik(joint_func, start = st_new, iterlim = miterlim, method = "BFGS"), silent = TRUE) resnm <- try(maxLik(joint_func, start = res$estimate, iterlim = 1000000, method = "NM"), silent = TRUE) }else{ res <- try(maxLik(joint_func, grad = joint_grad, hess = joint_hess, start = st_new, iterlim = miterlim, method = "BFGS"), silent = TRUE) resnm <- try(maxLik(joint_func, grad = joint_grad, hess = joint_hess, start = res$estimate, iterlim = 1000000, method = "NM"), silent = TRUE) } if(res$maximum<resnm$maximum){ res <- resnm } resif <- try_if(res) if(resif){ reso <- try(DEoptim(jj_f, lower = rep(-deconst, length(start_v)), upper = rep(deconst, length(start_v)), control = list(trace = FALSE, VTR = 10000000)), silent = TRUE) } }else{ reso <- try(DEoptim(jj_f, lower = rep(-deconst, length(start_v)), upper = rep(deconst, length(start_v)), control = list(trace = FALSE, VTR = 10000000)), silent = TRUE) } if(!any(class(reso)%in%"try-error")){ st_new <- reso$optim$bestmem names(st_new) <- names(start_v) } if(is.null(joint_hess)){ res <- try(maxLik(joint_func, start = st_new, iterlim = miterlim, method = "BFGS"), silent = TRUE) resnm <- try(maxLik(joint_func, start = res$estimate, iterlim = 1000000, method = "NM"), silent = TRUE) }else{ res <- try(maxLik(joint_func, grad = joint_grad, hess = joint_hess, start = st_new, iterlim = miterlim, method = "BFGS"), silent = TRUE) resnm <- try(maxLik(joint_func, grad = joint_grad, hess = joint_hess, start = res$estimate, iterlim = 1000000, method = "NM"), silent = TRUE) } if(res$maximum<resnm$maximum){ res <- resnm } resif <- try_if(res) if(resif){ res$estimate <- st_new if(!is.null(joint_grad)) res$gradient <- joint_grad(st_new) if(!is.null(joint_hess)) res$hessian <- joint_hess(st_new) res$type <- "DEoptim" res$maximum <- joint_func(st_new) } return(res) } try_if <- function(res) { . <- NULL sumstat <- try(res%>%summary_check, silent = TRUE) tester <- ifelse(any(class(res)%in%"try-error"), TRUE, ifelse(res$code == 100, TRUE, FALSE)) ststats <- if(any(sumstat%>%class%in%"try-error")|tester) TRUE else all(summary_check(res)$estimate[, 4]%>%na.omit %>% round(., 4)>0.999)|any(is.nan(summary_check(res)$estimate[, 4])) return(tester|any(sumstat%>%class%in%"try-error")|ststats) } try_alg <- function(joint_func, joint_grad, joint_hess, methodim, miterlim, start_val, ki = 1, k = 1, eq_type, corrl = FALSE) { . <- NULL env_org <- environment(joint_func) method_org <- env_org$methodopt env_org$methodopt <- methodim if(is.null(joint_hess)){ res <- try(maxLik(joint_func, start = start_val, method = methodim, iterlim = miterlim), silent = TRUE) }else{ res <- try(maxLik(joint_func, grad = joint_grad, hess = joint_hess, start = start_val, method = methodim, iterlim = miterlim), silent = TRUE) } env_org$methodopt <- method_org if(eq_type=="joint"&corrl==FALSE&!is.null(joint_hess)){ h <- joint_hess(res$estimate) if(methodim=="BHHH"){ h %<>% apply(., 3, function(x) colSums(x, na.rm = FALSE)) } res$hessian <- h } resif <- try_if(res) if(resif&ki<k){ ki <- ki+1 res <- try_alg(joint_func, joint_grad, joint_hess, methodim, miterlim, start_val = res$estimate, ki, k, eq_type=eq_type, corrl=corrl) return(res) } return(res) } get_nmm_functions <- function(corrl, eq_type, cheqs0, ffor, objm, print_out, bayesian_random, fixed_term, mnp, start_v, data_name, check_hess, hessian, eqsys, diff_hessian, MNtypef = NULL) { . <- NULL separatenmm <- FALSE if(corrl == TRUE&any(eq_type == "joint")){ objm <- cond_mean_cov_expr(neqt = length(cheqs0), kk = length(ffor)) joint_obj <- LL_joint(ffor, cheqs0, objm, check_hess = TRUE , cfunc='cont_func', chess = "cont_hess", cgrad = "cont_grad", gfunc = 'joint_grad', hfunc = 'joint_hess', print_out = print_out, bayesian_random = bayesian_random, MNtypef=MNtypef) text_func <- joint_obj$text_func text_grad <- joint_obj$text_grad text_hess <- joint_obj$text_hess text_bd <- joint_obj$text_bd text_gd <- joint_obj$text_gd text_edd <- joint_obj$text_edd joint_func <- joint_obj$func joint_grad <- joint_obj$grad joint_hess <- joint_obj$hessian npar <- get_npar(cheqs0)+1 add_pars <- paste0("par[", npar:(length( start_v)+1), "]") cont_obj <- LL_joint_no_corr(cheqs0=cheqs0, datan="data", eq_type = "cont", fixed_term = fixed_term, bayesian_random = bayesian_random, eqsys = eqsys, add_pars = add_pars) mod_act <- .%>% deparse %>% gsub("npaths_cont", "1", ., fixed = TRUE) %>% gsub("npaths", "1", ., fixed = TRUE) cf <- cont_obj$func %>% mod_act intr <- cf %>% grep("separatenmm", .)-1 if(length(intr)>0){ cf <- cf[-c(intr:(length(cf)-2))] } cont_func <- function(par){} body(cont_func)<- parse(text=cf[-c(1)] ) cf <- cont_obj$grad %>% mod_act cont_grad <- function(par){} body(cont_grad)<- parse(text=cf[-c(1)] ) cf <- cont_obj$hess %>% mod_act cont_hess<- function(par){} body(cont_hess)<- parse(text=cf[-c(1)] ) if(bayesian_random == TRUE){ actbr <- .%>%gsub("par\\[\\[(\\d{1,10})\\]\\]", "par[,\\1]", .)%>%gsub("par\\[(\\d{1,10})", "par[,\\1",.)%>% gsub("par\\[\\((\\d{1,10})", "par[,(\\1",.)%>% gsub("par <- c(", "par <- cbind(", ., fixed = TRUE)%>% gsub("length(par)", "ncol(par)", ., fixed = TRUE) dpactbr <- . %>% deparse %>% actbr ffj <- cont_func %>% dpactbr ffj <- ffj[-c(1)] %>% parse(text = .) cont_func <- function(par) {} body(cont_func) <- ffj gf1 <- cont_grad %>% dpactbr gf1 <- gf1[-c(1)] %>% parse(text = .) cont_grad <- function(par){} body(cont_grad) <- gf1 hf1 <- cont_hess %>% dpactbr hf1 <- hf1[-c(1)] %>% parse(text = .) cont_hess <- function(par){} body(cont_hess) <- hf1 } if(diff_hessian == TRUE){ joint_obj <- LL_joint(ffor, cheqs0, objm, check_hess = TRUE, cfunc='cont_func', chess = "cont_hess", cgrad = "cont_grad", gfunc = 'joint_grad', hfunc = 'joint_hess', datan = data_name, print_out = print_out, bayesian_random = bayesian_random, MNtypef=MNtypef) joint_grad <- joint_obj$grad joint_hess <- joint_obj$hessian } }else{ joint_obj <- LL_joint_no_corr(ffor, cheqs0, datan="data", eq_type = eq_type, fixed_term = fixed_term, hessian = hessian, bayesian_random = bayesian_random, eqsys = eqsys, MNtypef=MNtypef) joint_func <- joint_obj$func joint_grad <- joint_obj$grad joint_hess <- joint_obj$hessian } if(bayesian_random == TRUE){ tjf <- joint_func %>% deparse istart <- grep("methodopt", tjf)[1] if(corrl == TRUE){ iend <- grep("joint_hess", tjf)[1]+1 tjf <- tjf[-c(istart:iend)] istart <- grep(" res <- if ", tjf) iend <- grep("attributes\\(res\\)", tjf) tjf <- tjf[-c(istart:iend)] tjf <- gsub("contpart <- cbind\\(contpart", "res <- cbind(contpart", tjf) body(joint_func) <- parse(text = tjf[-1]) cjf <- cont_func %>% deparse istart <- grep("methodopt", cjf)[1] iend <- grep("res <- cbind", cjf)-1 cjf <- cjf[-c(istart:iend)] body(cont_func) <- parse(text = cjf[-1]) }else{ iend <- grep("attributes\\(res\\)", tjf) ires <- grep("res <- cbind", tjf, value = TRUE) tjf <- tjf[-c(istart:iend)] body(joint_func) <- parse(text = c(tjf[2:(length(tjf)-2)], ires, tjf[(length(tjf)-1):length(tjf)])) } } if(corrl==TRUE&any(eq_type=="joint")){ res <- list( joint_func = joint_func, joint_grad = joint_grad, joint_hess = joint_hess, separatenmm = separatenmm, cont_func = cont_func, cont_grad = cont_grad, cont_hess = cont_hess, text_func = text_func, text_grad = text_grad, text_hess = text_hess, text_bd = text_bd, text_gd = text_gd, text_edd = text_edd ) }else{ res <- list( joint_func = joint_func, joint_grad = joint_grad, joint_hess = joint_hess, separatenmm = separatenmm ) } res } summary.nmm <- function(object, type = "normal", new_coef = NULL, ...) { . <- NULL new_coef <- new_coef[names(new_coef) %>% sort] estimate <- if(!is.null(new_coef)) new_coef else object$estimate breadd <- bread.nmm(object, type = type, new_coef = new_coef) sde <- breadd %>% diag %>% sqrt t <- estimate / sde p <- 2 * pnorm(-abs(t)) results <- cbind(Estimate = estimate, `Std. error` = sde, `t value` = t, `Pr(> t)` = p) results <- apply(results, 2, function(x)round(x, 7)) ll <- logLik.nmm(object, new_coef = new_coef) summary <- list(maximType = object$type, iterations = object$iterations, returnCode = object$code, returnMessage = object$message, loglik = ll, estimate = results, constraints = object$constraints, vcov = breadd) if(!is.null(new_coef)){ summary[["maximType"]] <- "New" summary[["iterations"]] <- "NA" summary[["returnCode"]] <- "NA" summary[["returnMessage"]] <- "New coefficients" } class(summary) <- "summary.maxLik" return(summary) } stats_function <- function(eq_c = NULL, eq_d = NULL, par_c = NULL, par_d = NULL, fixed = 0) { . <- NULL if(!is.null(eq_c)){ para_cont <- get_par(par_c, eq_c) npar <- length(par_c) cheqs0 <- para_cont$cheqs0 cheqs0n <- cheqs0%>%sub('^[^-]*-', '', .) endog <- cheqs0 %>% sub('-.*', '', .) %>% trimws fixed <- if(!is.null(eq_d)) npar + 1 else 0 cont_func <- f_create(cheqs0n, data = 'data', fixed = fixed, transform = FALSE, cheqs0 = cheqs0n) }else{ cont_func <- NULL endog <- NULL npar <- 0 fixed <- if(!is.null(eq_d)) npar+1 else 1 } if(!is.null(eq_d)){ disc_par <- get_par(par_d, eq_d) ffor <- disc_par$cheqs0 fforn <- gsubfn('(par\\[)(\\d{1,10})(\\])', function(x, y, z) paste0(x, as.numeric(y) + npar, z), ffor) mnf1 <- MNlogitf(fforn, transform = TRUE, separatenmm = TRUE, weight_disc = TRUE) probexpr <- mnf1$probte %>% gsub('qnorm\\(|\\)$', '', .) prob_func <- f_create(probexpr, data = 'data', fixed = fixed, transform = FALSE) }else{ prob_func <- NULL } list(prob = prob_func, cont = cont_func, endog = endog) }
fbed.g2 <- function(y, x, alpha = 0.05, univ = NULL, K = 0, backward = TRUE) { p <- dim(x)[2] ind <- 1:p sig <- log(alpha) sela <- NULL card <- 0 sa <- NULL pva <- NULL runtime <- proc.time() x <- as.matrix(x) y <- as.numeric(y) z <- cbind(x, y) all.dc <- Rfast::colrange(z, cont = FALSE) if ( is.null(univ) ) { a <- Rfast::g2tests(data = z, x = 1:p, y = p + 1, dc = all.dc) stat <- a$statistic pval <- pchisq(stat, a$df, lower.tail = FALSE, log.p = TRUE) univ$stat <- stat univ$pvalue <- pval n.tests <- p } else { stat <- univ$stat pval <- univ$pvalue n.tests <- 0 } s <- which(pval < sig) if ( length(s) > 0 ) { sel <- which.min(pval) sela <- sel s <- s[ - which(s == sel) ] sa <- stat[sel] pva <- pval[sel] stat <- numeric(p) pval <- numeric(p) while ( sum(s>0) > 0 ) { for ( i in ind[s] ) { zz <- cbind(y, x[, c(i, sela)] ) k <- length(sela) dc <- all.dc[c(p + 1, i, sela)] mod <- Rfast::g2Test(zz, x = 1, y = 2, cs = 3:(2 + k), dc = dc) stat[i] <- mod$statistic pval[i] <- pchisq(mod$statistic, mod$df, lower.tail = FALSE, log.p = TRUE) } n.tests <- n.tests + length( ind[s] ) s <- which(pval < sig) sel <- which.min(pval) * ( length(s)>0 ) sa <- c(sa, stat[sel]) pva <- c(pva, pval[sel]) sela <- c(sela, sel[sel > 0] ) s <- s[ - which(s == sel) ] if (sel > 0) { stat <- numeric(p) pval <- numeric(p) } } card <- sum(sela > 0) if (K == 1) { stat <- numeric(p) pval <- numeric(p) for ( i in ind[-sela] ) { zz <- cbind(y, x[, c(i, sela)] ) k <- length(sela) dc <- all.dc[c(p + 1, i, sela)] mod <- Rfast::g2Test(zz, x = 1, y = 2, cs = 3:(2 + k), dc = dc) stat[i] <- mod$statistic pval[i] <- pchisq(mod$statistic, mod$df, lower.tail = FALSE, log.p = TRUE) } n.tests[2] <- length( ind[-sela] ) s <- which(pval < sig) sel <- which.min(pval) * ( length(s)>0 ) sa <- c(sa, stat[sel]) pva <- c(pva, pval[sel]) sela <- c(sela, sel[sel > 0] ) s <- s[ - which(s == sel) ] if (sel > 0) { stat <- numeric(p) pval <- numeric(p) } while ( sum(s>0) > 0 ) { for ( i in ind[s] ) { zz <- cbind(y, x[, c(i, sela)] ) k <- length(sela) dc <- all.dc[c(p + 1, i, sela)] mod <- Rfast::g2Test(zz, x = 1, y = 2, cs = 3:(2 + k), dc = dc) stat[i] <- mod$statistic pval[i] <- pchisq(mod$statistic, mod$df, lower.tail = FALSE, log.p = TRUE) } n.tests[2] <- n.tests[2] + length( ind[s] ) s <- which(pval < sig) sel <- which.min(pval) * ( length(s)>0 ) sa <- c(sa, stat[sel]) pva <- c(pva, pval[sel]) sela <- c(sela, sel[sel > 0] ) s <- s[ - which(s == sel) ] if (sel > 0) { stat <- numeric(p) pval <- numeric(p) } } card <- c(card, sum(sela>0) ) } if ( K > 1) { for ( i in ind[-sela] ) { zz <- cbind(y, x[, c(i, sela)] ) k <- length(sela) dc <- all.dc[c(p + 1, i, sela)] mod <- Rfast::g2Test(zz, x = 1, y = 2, cs = 3:(2 + k), dc = dc) stat[i] <- mod$statistic pval[i] <- pchisq(mod$statistic, mod$df, lower.tail = FALSE, log.p = TRUE) } n.tests[2] <- length( ind[-sela] ) s <- which(pval < sig) sel <- which.min(pval) * ( length(s)>0 ) sa <- c(sa, stat[sel]) pva <- c(pva, pval[sel]) sela <- c(sela, sel[sel > 0] ) s <- s[ - which(s == sel) ] if (sel > 0) { stat <- numeric(p) pval <- numeric(p) } while ( sum(s > 0) > 0 ) { for ( i in ind[s] ) { zz <- cbind(y, x[, c(i, sela)] ) k <- length(sela) dc <- all.dc[c(p + 1, i, sela)] mod <- Rfast::g2Test(zz, x = 1, y = 2, cs = 3:(2 + k), dc = dc) stat[i] <- mod$statistic pval[i] <- pchisq(mod$statistic, mod$df, lower.tail = FALSE, log.p = TRUE) } n.tests[2] <- n.tests[2] + length( ind[s] ) s <- which(pval < sig) sel <- which.min(pval) * ( length(s)>0 ) sa <- c(sa, stat[sel]) pva <- c(pva, pval[sel]) sela <- c(sela, sel[sel > 0] ) s <- s[ - which(s == sel) ] if (sel > 0) { stat <- numeric(p) pval <- numeric(p) } } card <- c(card, sum(sela > 0) ) vim <- 1 while ( vim < K & card[vim + 1] - card[vim] > 0 ) { vim <- vim + 1 for ( i in ind[-sela] ) { zz <- cbind(y, x[, c(i, sela)] ) k <- length(sela) dc <- all.dc[c(p + 1, i, sela)] mod <- Rfast::g2Test(zz, x = 1, y = 2, cs = 3:(2 + k), dc = dc) stat[i] <- mod$statistic pval[i] <- pchisq(mod$statistic, mod$df, lower.tail = FALSE, log.p = TRUE) } n.tests[vim + 1] <- length( ind[-sela] ) s <- which(pval < sig) sel <- which.min(pval) * ( length(s)>0 ) sa <- c(sa, stat[sel]) pva <- c(pva, pval[sel]) sela <- c(sela, sel[sel > 0] ) s <- s[ - which(s == sel) ] if (sel > 0) { stat <- numeric(p) pval <- numeric(p) } while ( sum(s > 0) > 0 ) { for ( i in ind[s] ) { zz <- cbind(y, x[, c(i, sela)] ) k <- length(sela) dc <- all.dc[c(p + 1, i, sela)] mod <- Rfast::g2Test(zz, x = 1, y = 2, cs = 3:(2 + k), dc = dc) stat[i] <- mod$statistic pval[i] <- pchisq(mod$statistic, mod$df, lower.tail = FALSE, log.p = TRUE) } n.tests[vim + 1] <- n.tests[vim + 1] + length( ind[s] ) s <- which(pval < sig) sel <- which.min(pval) * ( length(s)>0 ) sa <- c(sa, stat[sel]) pva <- c(pva, pval[sel]) sela <- c(sela, sel[sel > 0] ) s <- s[ - which(s == sel) ] if (sel > 0) { stat <- numeric(p) pval <- numeric(p) } } card <- c(card, sum(sela>0) ) } } } runtime <- proc.time() - runtime len <- sum( sela > 0 ) if (len > 0) { res <- cbind(sela[1:len], sa[1:len], pva[1:len] ) info <- matrix(nrow = length(card), ncol = 2) info[, 1] <- card info[, 2] <- n.tests } else { res <- matrix(c(0, 0, 0), ncol = 3) info <- matrix(c(0, p), ncol = 2) } colnames(res) <- c("Vars", "stat", "log p-value") rownames(info) <- paste("K=", 1:length(card)- 1, sep = "") colnames(info) <- c("Number of vars", "Number of tests") result <- list(univ = univ, res = res, info = info, runtime = runtime) result$back.rem <- 0 result$back.n.tests <- 0 if ( backward ) { if (result$info[1, 1] > 0) { a <- bs.g2(y, x[, result$res[, 1], drop = FALSE], threshold = alpha) if ( typeof(a) == "list" ) { result$back.rem <- result$res[a$info[, 1], 1] back.n.tests <- sum( dim(result$res)[1] : (dim(a$mat)[1] - 1) ) sel <- result$res[a$mat[, 1], 1] stat <- a$mat[, 3] pval <- a$mat[, 2] result$res <- cbind(sel, stat, pval) result$back.n.tests <- back.n.tests result$runtime <- result$runtime + a$runtime } else { back.rem <- 0 back.n.tests <- 0 result$back.rem <- back.rem result$back.n.tests <- back.n.tests result$runtime <- result$runtime } } } result }
select_n_to_m.cluster_pairs <- function(pairs, variable, score, threshold, preselect = NULL, id_x = NULL, id_y = NULL, ...) { stop("select_n_to_m is not implemented for cluster_pairs. First use select_threshold to ", "select a subset of the records. Then call cluster_collect with the selection to ", "get the relevant pairs locally. Then call select_n_to_m on those pairs.") }
GeneticAlg.int <- function(genomeLen, codonMin, codonMax, genomeMin=rep.int(codonMin, genomeLen), genomeMax=rep.int(codonMax, genomeLen), suggestions=NULL, popSize=50, iterations=100, terminationCost=NA, mutationChance=1/(genomeLen+1), elitism=floor(popSize/10), geneCrossoverPoints=NULL, monitorFunc=NULL, evalFunc, allowrepeat = TRUE, showSettings=FALSE, verbose=FALSE, plapply = lapply) { is.verbose = verbose verbose = function(...) { if (is.verbose) cat(...)} if (is.null(evalFunc)) { stop("A evaluation function must be provided. See the evalFunc parameter."); } stopifnot(genomeLen > 1) verbose("Testing the sanity of parameters...\n"); if (length(genomeMin) != length(genomeMax)) { stop("The vectors genomeMin and genomeMax must be of equal length."); } if (popSize < 5) { stop("The population size must be at least 5."); } if (iterations < 1) { stop("The number of iterations must be at least 1."); } if (!(elitism < popSize)) { stop("The population size must be greater than the elitism."); } if (elitism < 0) { stop("elitism must be at least 0."); } if ((mutationChance < 0) | (mutationChance > 1)) { stop("mutationChance must be between 0 and 1."); } if (!is.null(geneCrossoverPoints)) { if (!is.numeric(geneCrossoverPoints) | length(geneCrossoverPoints) != genomeLen) { stop("Invalid geneCrossoverPoints."); } } if (showSettings) { verbose("The start conditions:\n"); result = list(genomeMin=genomeMin, genomeMax=genomeMax, suggestions=suggestions, popSize=popSize, iterations=iterations, elitism=elitism, mutationChance=mutationChance); class(result) = "rbga"; cat(summary(result)); } else { verbose("Not showing GA settings...\n"); } population = matrix(nrow=popSize, ncol=genomeLen); if (!is.null(suggestions)) { verbose("Adding suggestions to first population...\n"); if ("list" %in% class(suggestions)) { verbose("Suggestions given as a list.\n"); suggestions = do.call(rbind, suggestions) } if (ncol(suggestions) != genomeLen) { stop("suggestions must be a list of chromosomes or a matrix of 'nrow=numSuggestions X ncol=genomeLen'") } suggestionCount = nrow(suggestions) population[1:suggestionCount, ] <- suggestions verbose("Filling others with random values in the given domains...\n"); } else { verbose("Starting with random values in the given domains...\n"); suggestionCount = 0 } for (i in (suggestionCount+1):popSize) { population[i,] = ga.new.chromosome(genomeLen, genomeMin, genomeMax, allowrepeat) } bestEvals = rep(NA, iterations); meanEvals = rep(NA, iterations); evalVals = rep(NA, popSize); for (iter in 1:iterations) { verbose(paste("Starting iteration", iter, "\n")); verbose("Calucating evaluation values... "); to.eval.Ids = which(is.na(evalVals)) evalVals[to.eval.Ids] = unlist(plapply(to.eval.Ids, function(i, population, evalFunc) evalFunc(population[i, ]), population, evalFunc)) if ((!all(is.numeric(evalVals))) | any(is.na(evalVals)) | any(is.nan(evalVals))) { stop("Invalid cost function return value (NA or NaN).") } bestEvals[iter] = min(evalVals); meanEvals[iter] = mean(evalVals); bestInd = which.min(evalVals) verbose(" done.\n"); collect.results <- function() { settings = list(genomeMin=genomeMin, genomeMax=genomeMax, popSize=popSize, elitism=elitism, geneCrossoverPoints = geneCrossoverPoints, iterations=iterations, suggestions=suggestions, mutationChance=mutationChance) pop.info = list(population=population, evaluations=evalVals, best=bestEvals, mean=meanEvals, currentIteration=iter) best = list(genome=population[bestInd,], cost = evalVals[bestInd]); ret = list(settings = settings, population = pop.info, best = best) class(ret) = "GeneticAlg.int"; return (ret) } if (!is.null(monitorFunc)) { verbose("Sending current state to rgba.monitor()...\n"); monitorFunc(collect.results()); } if (iter == iterations) { verbose("End of generations iteration reached.\n"); break } if (!is.na(terminationCost)) { if (bestEvals[iter] <= terminationCost) { verbose("Cost better than termination cost reached.\n"); break } } verbose("Creating next generation...\n"); newPopulation = matrix(nrow=popSize, ncol=genomeLen); newEvalVals = rep(NA, popSize); verbose(" sorting results...\n"); sortedEvaluations = sort(evalVals, index=TRUE); sortedPopulation = matrix(population[sortedEvaluations$ix,], ncol=genomeLen); if (elitism > 0) { verbose(" applying elitism...\n"); newPopulation[1:elitism,] = sortedPopulation[1:elitism,]; newEvalVals[1:elitism] = sortedEvaluations$x[1:elitism] } verbose(" applying crossover...\n"); for (child in (elitism+1):popSize) { parentProb = dnorm(1:popSize, mean=0, sd=(popSize/3)) parentIDs = sample(1:popSize, 2, prob=parentProb) parents = sortedPopulation[parentIDs,] if (is.null(geneCrossoverPoints)) { crossOverPoint = sample(0:genomeLen,1) if (crossOverPoint == 0) { newPopulation[child, ] = parents[2,] newEvalVals[child] = sortedEvaluations$x[parentIDs[2]] } else if (crossOverPoint == genomeLen) { newPopulation[child, ] = parents[1,] newEvalVals[child] = sortedEvaluations$x[parentIDs[1]] } else { newPopulation[child, ] = c(parents[1, 1:crossOverPoint], parents[2, (crossOverPoint+1):genomeLen]) } } else { p2.indices = which(geneCrossoverPoints %% 2 != 0) newPopulation[child, ] = parents[1,] newPopulation[child, p2.indices] = parents[2, p2.indices] } } if (!allowrepeat) { for (i in (elitism+1):popSize) { population[i,] = ga.unique.maker(population[i,], genomeMin, genomeMax) } } population = newPopulation; evalVals = newEvalVals; if (mutationChance > 0) { verbose(" applying mutations... "); mutationCount = 0; for (object in (elitism+1):popSize) { dampeningFactor = (iterations-iter)/iterations mutResult <- ga.mutation(population[object,], mutationChance, genomeLen, genomeMin, genomeMax, allowrepeat, dampeningFactor) population[object, ] = mutResult$newGenome; evalVals[object] = NA; mutationCount = mutationCount + 1; } verbose(paste(mutationCount, "mutations applied\n")); } } result = collect.results() return(result); }
context("Testing telemetry functions") remove_logfiles <- function() { txt_files <- list.files(pattern = "txt$", full.names = TRUE, recursive = FALSE) file.remove(txt_files) } remove_logfiles() if (file.exists("telemetry_test_prediction_log.txt")) file.remove("telemetry_test_prediction_log.txt") if (file.exists("telemetry_test.RDS")) file.remove("telemetry_test.RDS") m <- machine_learn(pima_diabetes[1:50, 6:10], outcome = diabetes, models = "rf", model_name = "telemetry_test") p <- predict(object = m, newdata = pima_diabetes[1:50, 6:10], write_log = TRUE) save_models(m, "telemetry_test.RDS") m_reloaded <- load_models("telemetry_test.RDS") p_reloaded <- predict(object = m_reloaded, newdata = pima_diabetes[1:50, 6:10], write_log = TRUE) test_that("log_predictions writes info to file correctly", { d <- readLines("telemetry_test_prediction_log.txt") expect_true(any(grepl("name: telemetry_test", d))) expect_true(any(grepl("predicted: diabetes", d))) expect_true(any(grepl("missingness in new data", d))) }) test_that("log_predictions returns data correctly", { d_pred <- attr(p_reloaded, "prediction_log") expect_equal(dim(d_pred), c(1, 23)) expect_equal(d_pred$loaded_from, "telemetry_test.RDS") expect_equal(d_pred$model_name, "telemetry_test") expect_equal(d_pred$n_predictions, 50) expect_equal(d_pred$outcome_variable, "diabetes") expect_equal(class(d_pred$run_time), "numeric") }) test_that("log_predictions works without loading from file", { d_pred <- attr(p, "prediction_log") expect_equal(dim(d_pred), c(1, 23)) expect_equal(d_pred$loaded_from, "trained_in_memory") expect_equal(d_pred$model_name, "telemetry_test") expect_equal(d_pred$n_predictions, 50) expect_equal(d_pred$outcome_variable, "diabetes") expect_equal(class(d_pred$run_time), "numeric") remove_logfiles() }) test_that("Errors are put in log file properly", { expect_error( expect_warning( predict(object = m, newdata = pima_diabetes[1:50, 7:10], write_log = FALSE) ) ) expect_error( expect_warning( predict(object = m_reloaded, newdata = pima_diabetes[1:50, 7:10], write_log = FALSE) ) ) expect_warning(p <- predict(object = m, newdata = pima_diabetes[1:50, 7:10], write_log = TRUE), "insulin") e <- readLines("telemetry_test_prediction_log.txt") expect_true(any(grepl("insulin", e))) }) test_that("Warnings are parsed correctly", { nd <- pima_diabetes[1:50, 6:10] nd$weight_class[1] <- "jabba" expect_warning(p <- predict(object = m, newdata = nd, write_log = TRUE), "jabba") expect_true(any(grepl("jabba", attr(p, "prediction_log")$warnings))) }) test_that("Failure returns warning, blank df, and error info", { expect_warning(pe <- predict(object = m_reloaded, newdata = pima_diabetes[1:50, 7:10], write_log = TRUE, prepdata = TRUE), "insulin") d_log <- attr(pe, "prediction_log") expect_equal(dim(pe), c(0, 6)) expect_true(attr(pe, "failed")) expect_equal(d_log$outcome_variable, "diabetes") expect_false(d_log$predictions_made) expect_equal(d_log$n_predictions, 0) expect_equal(names(pe), names(p)) expect_equal(class(d_log$run_time), "numeric") }) test_that("Set and update telemetry functions work", { d <- set_inital_telemetry(extract_model_info(m)) expect_equal(dim(d), c(1, 23)) expect_equal(d$outcome_variable, "diabetes") expect_false(d$predictions_made) expect_equal(d$n_predictions, 0) d_up <- update_telemetry(d, p) expect_equal(dim(d_up), c(1, 23)) expect_equal(d_up$error_message, NA) expect_true(is.numeric(d_up$prediction_mean)) expect_true(is.numeric(d_up$missingness_mean)) }) test_that("parse safe and quiet works", { mi <- extract_model_info(m) x <- list(result = p, error = NULL, warnings = NULL) expect_equal(class(parse_safe_n_quiet(x, mi, m))[1], "predicted_df") expect_equal(dim(parse_safe_n_quiet(x, mi, m)), c(50, 6)) x <- list(result = p, error = NULL, warnings = "grrrr") expect_warning(res <- parse_safe_n_quiet(x, mi, m), "grrr") expect_equal(class(res)[1], "predicted_df") expect_equal(dim(res), c(50, 6)) x <- list(result = NULL, error = list(message = "ARHT!", call = "this spot"), warnings = NULL) expect_warning(res <- parse_safe_n_quiet(x, mi, m), "ARHT") expect_equal(class(res)[1], "tbl_df") expect_equal(dim(res), c(0, 6)) }) file.remove("telemetry_test_prediction_log.txt") file.remove("telemetry_test.RDS")
dateTimeFormats2 <- function() { dateTimeFormat <- c("ymd_HMS", "mdy_HMS", "dmy_HMS", "ymd_HM", "mdy_HM", "dmy_HM") return(dateTimeFormat) }
DataModel.default = function(...) { args = list(...) if (length(args) > 0) { stop("Data Model doesn't know how to deal with the parameters") } else { datamodel = structure(list(general = list(outcome.dist = NULL, outcome.type = NULL, sample.size = NULL, event = NULL, rando.ratio = NULL, design = NULL), samples = NULL), class = "DataModel") } return(datamodel) }
segmentCN <- function(strwords, analyzer = c("default", "hmm", "jiebaR", "fmm", "coreNLP"), nature = FALSE, nosymbol = TRUE, returnType = c("vector", "tm"), ...) { if (!is.character(strwords)) stop("Please input character!") analyzer <- match.arg(analyzer) returnType <- match.arg(returnType) if (analyzer == "default") { analyzer <- getOption("RwordsegAnalyzer") } if (nosymbol) strwords <- gsub("[^\u4e00-\u9fa5a-zA-Z0-9]", " ", strwords) strwords <- gsub("^\\s+|\\s+$", "", gsub("\\s+", " ", strwords)) OUT <- do.call(paste0(".seg", analyzer), list(strwords = strwords, nature = nature)) if (returnType == "tm") OUT <- sapply(OUT, paste, collapse = " ") if (length(OUT) == 1 && analyzer != "fmm") OUT <- OUT[[1]] return(OUT) } .segjiebaR <- function(strwords, nature = FALSE) { if (!suppressWarnings(requireNamespace("jiebaR", quietly = TRUE))) { stop("Package \"jiebaR\" is required!") } .loadModels("jiebaR") .RwordsegEnv <- .verifyRwordsegEnv() jiebaAnalyzer <- get("jiebaAnalyzer", envir = .RwordsegEnv) OUT <- jiebaR::segment(strwords, jiebaAnalyzer) OUT <- lapply(OUT, paste0, "") if (nature) OUT <- lapply(OUT, jiebaR::vector_tag, jiebaAnalyzer) return(OUT) } .segfmm <- function(strwords, nature = FALSE) { if (length(strwords) > 1) return(lapply(strwords,.segfmm, nature)) .loadModels("fmm") .RwordsegEnv <- .verifyRwordsegEnv() nmax <- min(nchar(strwords), 8) if (nmax <= 1) { n1 <- try(get(strwords, envir = get("fmmAnalyzer", envir = .RwordsegEnv)), silent = TRUE) if (nature) { if (inherits(n1, "try-error")) n1 <- "x" names(strwords) <- n1 } return(strwords) } else { for (i in nmax:1) { s1 <- substr(strwords, 1, i) n1 <- try(get(s1, envir = get("fmmAnalyzer", envir = .RwordsegEnv)), silent = TRUE) if (nchar(s1) == 1 || inherits(n1, "character")) { s2 <- substr(strwords, i + 1, nchar(strwords)) if (nchar(s2) == 0) { if (nature) { if (inherits(n1, "try-error")) n1 <- "x" names(s1) <- n1 } return(s1) } if (s1 == " ") { return(.segfmm(s2, nature)) } else { if (nature) { if (inherits(n1, "try-error")) n1 <- "x" names(s1) <- n1 } return(c(s1, .segfmm(s2, nature))) } } } } } .seghmm <- function(strwords, nature = FALSE) { .loadModels("hmm") .RwordsegEnv <- .verifyRwordsegEnv() hmmAnalyzer <- get("hmmAnalyzer", envir = .RwordsegEnv) s1 <- strsplit(strwords, split = "") sr <- lapply(s1, FUN = function(X) gsub("\\s+", " ", gsub("[^\u4e00-\u9fa5a-zA-Z0-9]", " ", X))) s2 <- lapply(sr, FUN = function(X) if (length(X) > 1) viterbi(hmm = hmmAnalyzer, X) else X) OUT <- lapply(1:length(s1), FUN = function(X) .decodechar(s1[[X]], s2[[X]])) if (nature) { .loadModels("fmm") OUT <- lapply(OUT, FUN = function(X) {names(X) <- .getNature(X);X}) } return(OUT) } .segcoreNLP <- function(strwords, nature = FALSE) { .loadModels("coreNLP") outlist <- lapply(strwords, FUN = function(X) if (nzchar(strstrip(X))) coreNLP::annotateString(X) else "") OUT <- lapply(outlist, FUN = function(X) if (nzchar(strstrip(X))) toUTF8(X$token$token) else "") if (nature) { POS <- lapply(outlist, FUN = function(X) if (nzchar(strstrip(X))) X$token$POS else "JJ") OUT <- lapply(1:length(OUT), FUN = function(X) {Y <- OUT[[X]]; names(Y) <- POS[[X]]; Y}) } return(OUT) }
library(dplyr) test_that("vanilla stat_slabinterval works", { skip_if_no_vdiffr() set.seed(1234) p = tribble( ~dist, ~x, "norm", rnorm(100), "t", rt(100, 3) ) %>% unnest(x) %>% ggplot() + scale_slab_alpha_continuous(range = c(0,1)) vdiffr::expect_doppelganger("vanilla stat_slabinterval", p + stat_slabinterval(aes(x = dist, y = x), n = 10, slab_function = sample_slab_function) ) }) test_that("gradientinterval works", { skip_if_no_vdiffr() set.seed(1234) p = tribble( ~dist, ~x, "norm", rnorm(100), "t", rt(100, 3) ) %>% unnest(x) %>% ggplot() + scale_slab_alpha_continuous(range = c(0,1)) vdiffr::expect_doppelganger("gradientinterval with two groups", p + stat_gradientinterval(aes(x = dist, y = x), n = 15, fill_type = "segments") ) vdiffr::expect_doppelganger("gradientintervalh with two groups", p + stat_gradientinterval(aes(y = dist, x = x), n = 15, fill_type = "segments") ) skip("linearGradient not supported in vdiffr yet") vdiffr::expect_doppelganger("fill_type = gradient with two groups", p + stat_gradientinterval(aes(x = dist, y = x), n = 15, fill_type = "gradient") ) vdiffr::expect_doppelganger("fill_type = gradient with two groups, h", p + stat_gradientinterval(aes(y = dist, x = x), n = 15, fill_type = "gradient") ) }) test_that("histinterval and slab work", { skip_if_no_vdiffr() set.seed(1234) p = tribble( ~dist, ~x, "norm", rnorm(100), "t", rt(100, 3) ) %>% unnest(x) %>% ggplot() vdiffr::expect_doppelganger("histinterval with outline", p + stat_histinterval(aes(x = dist, y = x), slab_color = "black") ) vdiffr::expect_doppelganger("histintervalh with outline", p + stat_histinterval(aes(y = dist, x = x), slab_color = "black") ) vdiffr::expect_doppelganger("histinterval with outlines bw bars", p + stat_histinterval(aes(x = dist, y = x), slab_color = "black", outline_bars = TRUE) ) vdiffr::expect_doppelganger("slab with outline", p + stat_slab(aes(x = dist, y = x), n = 20, slab_color = "black") ) }) test_that("scale transformation works", { skip_if_no_vdiffr() p_log = data.frame(x = qlnorm(ppoints(200), log(10), 2 * log(10))) %>% ggplot(aes(y = "a", x = x)) + scale_x_log10(breaks = 10^seq(-5,7, by = 2)) vdiffr::expect_doppelganger("halfeyeh log scale transform", p_log + stat_halfeye(point_interval = mode_hdci, n = 20) ) vdiffr::expect_doppelganger("ccdfintervalh log scale transform", p_log + stat_ccdfinterval(point_interval = mean_hdi, n = 20) ) vdiffr::expect_doppelganger("cdfintervalh log scale transform", p_log + stat_cdfinterval(point_interval = mean_hdi, n = 20) ) vdiffr::expect_doppelganger("histintervalh log scale transform", p_log + stat_histinterval(point_interval = median_qi, n = 20) ) }) test_that("pdf and cdf aesthetics work", { skip_if_no_vdiffr() p = data.frame( x = c("a", "b"), y = qnorm(ppoints(100), c(1, 2), 2) ) %>% ggplot(aes(x = x, y = y)) vdiffr::expect_doppelganger("pdf and cdf on a sample slabinterval", p + stat_sample_slabinterval(aes(fill = x, thickness = stat(pdf), slab_alpha = stat(cdf)), n = 15) ) expect_error(weighted_ecdf(NULL), "Need at least 1 or more values") }) test_that("constant distributions work", { skip_if_no_vdiffr() p = data.frame( x = c("constant = 1", "normal(2,1)"), y = qnorm(ppoints(100), mean = c(1, 2), sd = c(0, 1)) ) %>% ggplot(aes(x = x, y = y)) vdiffr::expect_doppelganger("constant dist on halfeye", p + stat_sample_slabinterval(n = 15) ) vdiffr::expect_doppelganger("constant dist on ccdf", p + stat_ccdfinterval() ) p = data.frame( x = c("constant = 1", rep("normal(2,1)", 50)), y = qnorm(c(0.5, ppoints(50)), mean = c(1, rep(2, 50)), sd = c(0, rep(1, 50))) ) %>% ggplot(aes(x = x, y = y)) vdiffr::expect_doppelganger("constant dist on halfeye with n = 1", p + stat_sample_slabinterval(n = 15) ) vdiffr::expect_doppelganger("constant dist on ccdf with n = 1", p + stat_ccdfinterval() ) }) test_that("side and justification can vary", { skip_if_no_vdiffr() vdiffr::expect_doppelganger("varying side and just", mtcars %>% ggplot(aes(x = mpg, y = cyl, side = case_when(cyl == 4 ~ "top", cyl == 6 ~ "both", cyl == 8 ~ "bottom"), justification = case_when(cyl == 4 ~ 0, cyl == 6 ~ 0.5, cyl == 8 ~ 1), scale = case_when(cyl == 4 ~ 0.5, cyl == 6 ~ 1, cyl == 8 ~ 0.5) )) + stat_sample_slabinterval(orientation = "horizontal", normalize = "groups", n = 15) ) }) test_that("n is calculated correctly", { skip_if_no_vdiffr() set.seed(1234) df = data.frame( g = c("a","a","a","b","c"), x = rnorm(120, c(1,1,1,2,3)) ) vdiffr::expect_doppelganger("pdf*n for different-sized groups", df %>% ggplot(aes(x = x, y = g, thickness = stat(pdf*n), fill = stat(n))) + stat_sample_slabinterval(n = 15) ) }) test_that("NAs are handled correctly", { skip_if_no_vdiffr() p = data.frame(x = c(1:10, NA)) %>% ggplot(aes(x = x, y = "a")) expect_warning( vdiffr::expect_doppelganger("NAs with na.rm = FALSE", p + stat_halfeye(na.rm = FALSE, n = 15) ), "Removed 1 rows" ) vdiffr::expect_doppelganger("NAs with na.rm = TRUE", p + stat_halfeye(na.rm = TRUE, n = 15) ) })
getPDEscreen<-function(pde = '/home/lees/Site/Santiaguito/pdq.eqs') { spde = scan(file=pde, what="", sep="\n") kpde = list() for(i in 1:length(spde)) { kpde[[i]] = parse.pde(spde[i]) } invisible(kpde) }
initial.TAG <- function(y, X, Candi.lambda= seq(from=-2, to=2,by=0.5), Adj.omega = TRUE, nug=0.001, nbasis=10, rannum=20, big=FALSE, nsub=31, method.1d = "DiceKriging"){ d <- ncol(X) n <- nrow(X) parini <- matrix(0, ncol=2, nrow=ncol(X)) dat <- data.frame(y,X) colnames(dat) <- c("Y.t", paste0("x",1:d)) nbasis.v <- as.vector(apply(X, 2, function(vec){ length(unique(vec)) })) if(sum(nbasis.v == 2) >= 1 || sum(nbasis.v == 1) >= 1){ print("Warning: The number of levels for some factors is less than 3, which cannot be used for fitting a nonlinear additive model") } index.discrete <- (nbasis.v <= nbasis) nbasis.v[!index.discrete] <- nbasis df.for.continuous <- n - sum(nbasis.v[index.discrete]) if(sum(nbasis.v[!index.discrete]) > df.for.continuous){ if(round(df.for.continuous/sum(!index.discrete)) >= 3){ nbasis.v[!index.discrete] <- round(df.for.continuous/sum(!index.discrete)) }else{ print("Warning: No Enough degrees of freedom.") } } ntemp=nsub score.v <- rep(0, length=length(Candi.lambda)) if(sum(y <= 0) != 0){ Candi.lambda = c(1) score.v <- rep(0, length=length(Candi.lambda)) } for(ind in 1:length( Candi.lambda)){ lam = Candi.lambda[ind] if(lam == 0){ Y.t <- log(y) J <- sum(log(1/y)) }else{ Y.t <- (y^(lam) - 1)/lam J <- sum(log(y^(lam - 1))) } dat[,1] <- Y.t if(big == TRUE){ b <- bam(as.formula(paste("Y.t ~ ",paste0("s(x",1:d,", k=",nbasis.v,")", collapse="+"))), data=dat) }else{ b <- gam(as.formula(paste("Y.t ~ ",paste0("s(x",1:d,", k=",nbasis.v,")", collapse="+"))), data=dat) } score.v[ind] <- b$gcv.ubre sigma.v <- sqrt(mean((b$residuals)^2)) score.v[ind] <- -J + n*log(sigma.v) } lam <- Candi.lambda[which.min(score.v)] if(lam == 0){ Y.t <- log(y) }else{ Y.t <- (y^(lam) - 1)/lam } ntemp <- ntemp - 1 dat[,1] <- Y.t b <- bam(as.formula(paste("Y.t ~ ",paste0("s(x",1:d,", k=",nbasis.v,")", collapse="+"))),data=dat) Mat <- predict.gam(b, type = "terms") parini[, 1] <- apply(Mat,2,var) newd <- matrix(rep(c(0:ntemp)/ntemp,d), byrow=FALSE, ncol=d,nrow=(ntemp+1)) newd <- as.data.frame(newd) colnames(newd) <- paste0("x",1:d) pred <- predict.gam(b, newd, type="terms") omega.new <- parini[,1]/sum(parini[,1]) if(Adj.omega == TRUE){ eta <- 1-(1/n) for(ind in 1:d){ omega.new[ind] <- eta*omega.new[ind] + (1-eta)*(1/d) } } if(method.1d == "DiceKriging"){ for(ind in 1:d){ temp.m <- km(formula=~1, design=as.matrix(newd[,ind]), response=pred[,ind], covtype="gauss", nugget = nug, multistart = rannum, control = list(trace = FALSE, verbose = FALSE)) parini[ind,2] <- sqrt(2*(coef(temp.m)$range^2)) } }else if(method.1d == "mlegp"){ for(ind in 1:d){ parini[ind,2] <- 1/sqrt(mlegp(newd[,ind], pred[,ind], nugget=nug, nugget.known = 0)$beta) } }else{ stop("Please Specify method.1d = 'DiceKriging' or 'mlegp'") } if(summary(b)$r.sq < 0){ rsq <- 1 - sum(b$residuals^2)/(sum((log(y)-mean(log(y)))^2)) }else{ rsq <- summary(b)$r.sq } obj <- list(omega = omega.new, s = parini[,2], lambda=lam, delta = log(((1/rsq) - 1), base=10), y = y, X = X, nbases = nbasis.v) class(obj) <- "initial.TAG" if(sum(y <= 0) != 0){print("Warning: Part of the response is negative, so no transformation is used.")} return(obj) }
simpleNetwork <- function(Data, Source = 1, Target = 2, height = NULL, width = NULL, linkDistance = 50, charge = -30, fontSize = 7, fontFamily = "serif", linkColour = " nodeColour = " opacity = 0.6, zoom = F) { if (!is.data.frame(Data)) stop("data must be a data frame class object.") sources <- Data[[Source]] targets <- Data[[Target]] check_zero(sources, targets) node_names <- factor(sort(unique(c(as.character(sources), as.character(targets))))) nodes <- data.frame(name = node_names, group = 1, size = 8) links <- data.frame(source = match(sources, node_names) - 1, target = match(targets, node_names) - 1, value = 1) options = list( Links = links, Nodes = nodes, Source = 'source', Target = 'target', Value = 'value', NodeID = 'name', Group = 'group', linkDistance = linkDistance, charge = charge, fontSize = fontSize, fontFamily = fontFamily, linkColour = linkColour, colourScale = JS(paste0("d3.scaleOrdinal(['", nodeColour, "'])")), opacity = opacity, zoom = zoom, radiusCalculation = JS("d.nodesize"), Nodesize = 'size', linkWidth = "'1.5px'.toString()", opacityNoHover = 1 ) do.call(forceNetwork, options) } simpleNetworkOutput <- function(outputId, width = "100%", height = "500px") { shinyWidgetOutput(outputId, "forceNetwork", width, height, package = "networkD3") } renderSimpleNetwork <- function(expr, env = parent.frame(), quoted = FALSE) { if (!quoted) { expr <- substitute(expr) } shinyRenderWidget(expr, simpleNetworkOutput, env, quoted = TRUE) }
gfunction.the.lo <- function(para, map, data){ nmodel <- length(map$bet) the <- para[map$the] fx <- as.matrix(data[, names(the), drop = FALSE]) g.the <- list() nthe <- length(the) n <- nrow(data) nlam <- max(map$lam) offset <- max(map$the) for(j in 1:nthe){ gt <- matrix(0, nrow = n, ncol = nlam) fx0 <- fx[, names(the)[j]] for(i in 1:nmodel){ id.a <- alp.index.lo(map, i) alp.exist <- !is.null(id.a) if(alp.exist){ alp <- para[id.a] }else{ alp <- NULL } id.b <- map$bet[[i]] bet <- para[id.b] gam <- c(alp, bet) rx <- as.matrix(data[, names(gam), drop = FALSE]) tmp <- as.vector(exp(fx %*% the)) yh <- tmp/(1+tmp) id <- c(id.a, id.b) gt[, id - offset] <- rx[, names(para)[id], drop = FALSE] * (fx0 * yh * (1-yh)) rm(id.a, id.b, alp.exist) } g.the[[j]] <- gt rm(gt) } g.the }
comp_cluster_pval <- function(x, y, clvar, test.func, arg.all, arg.all.fix, colnames.cluster, minimal.pval, agg.method, hier.adj, mt.adj, MD.factor = NULL, mod.large, mod.small = NULL, stouffer.weights) { pvals.data <- mapply(test.func, x = x, y = y, clvar = clvar, arg.all = arg.all, mod.large = mod.large, mod.small = mod.small, MoreArgs = list(colnames.cluster = colnames.cluster, arg.all.fix = arg.all.fix)) pvals.only <- do.call(c, pvals.data["pval", ]) if (any(is.na(pvals.only)) | any(is.null(pvals.only)) | length(pvals.only) == 0) { stop("The group test function returned an invalid p-value (NA, NULL, or an object of length 0 like integer(0)). The problem occured for the cluster / group of size ", length(colnames.cluster), " containing the following variables: ", paste(colnames.cluster, collapse = ", ")) } pvals.adj <- if (mt.adj == "none") { pvals.only } else if (mt.adj == "SBH") { pmin(pvals.only / MD.factor, 1) } else if (mt.adj == "dpBF") { p.x <- vapply(X = x, FUN = ncol, FUN.VALUE = 1L) pmin(pvals.only * p.x / length(colnames.cluster), 1) } pval <- if (length(pvals.adj) == 1) { pvals.adj } else if (agg.method == "Tippett") { max(1 - (1 - min(pvals.adj))^(length(x)), .Machine$double.neg.eps) } else if (agg.method == "Stouffer") { stats::pnorm(sum(stouffer.weights * stats::qnorm(pvals.adj))) } if (hier.adj) { pval <- max(pval, minimal.pval) } return(list("cluster" = list(colnames.cluster = colnames.cluster, pval = pval), "mod.small" = pvals.data["mod.small", ], "MD.factor" = MD.factor)) }
termlist <- function(x) { is.plus <- function(x) is.call(x) && x[[1L]] == "+" intr <- function(x) { is.intr <- function(x) is.call(x) && x[[1L]] == ":" if(is.intr(x)) { res <- list() repeat { res <- c(x[[3L]], res) x <- x[[2L]] if(!is.intr(x)) break } list(c(x, res)) } else x } if(x[[1L]] == "~") x <- x[[length(x)]] res <- list() while(is.plus(x)) { res <- c(intr(x[[3L]]), res) x <- x[[2L]] } res <- c(intr(x), res) res } expandintr <- function(x) { asstr <- function(x) asChar(x, backtick = TRUE) if(!is.language(x)) { a <- sapply(x, asstr) k <- length(a) vapply(seq.int(2L^k - 1L), function(y) paste0(a[as.logical(intToBits(y)[1L:k])], collapse = ":"), "") } else asstr(x) } termdepmat <- function(f) { trm <- terms(f, simplify = TRUE) tl <- termlist(trm) v <- attr(trm, "term.labels") n <- length(v) mat <- matrix(FALSE, n, n, dimnames = list(v, v)) for(i in seq.int(n)) mat[match(expandintr(tl[[i]]), v), i] <- TRUE mat } termdepmat2 <- function(f) { filist <- formula2idx(f, asCall = FALSE) n <- length(filist) v <- vapply(filist, paste0, "", collapse = ":") mat <- matrix(FALSE, n, n, dimnames = list(v, v)) for(i in seq.int(n)) mat[match(expandintr(filist[[i]]), v), i] <- TRUE mat } termdepmat_combine <- function(x) { dm <- sum(vapply(x, nrow, 1L)) mat <- matrix(FALSE, dm, dm) j <- 1L for(i in seq_along(x)) { n <- nrow(x[[i]]) k <- seq.int(j, length.out = n) mat[k, k] <- x[[i]] j <- j + n } dn <- unlist(lapply(x, rownames)) dimnames(mat) <- list(dn, dn) mat } formula2idx <- function(x, asCall = TRUE) { if(!is.call(x) || !inherits(x, "formula")) stop("'x' is not a formula") fac <- attr(delete.response(terms(x)), "factors") dimnames(fac) <- NULL ret <- apply(fac > 0L, 2L, which) if(asCall) as.call(c(as.name("list"), ret)) else ret } formula_margin_check <- function(j, m) { stopifnot(is.logical(j)) !any(m[!j, j], na.rm = TRUE) }
dprint_simp <- function(tbl.obj, init = c(0, 6.9), style, char.dim.obj, size.simp.obj ) { y.loc <- y.rem <- init[2] main.nrw <- ifelse(is.na(tbl.obj$main.nrw), 0, tbl.obj$main.nrw) if (!is.na(tbl.obj$main.nrw)) { if (!is.null(tbl.obj$cond.txt)) {tbl.obj$main[tbl.obj$main.nrw] <- paste(tbl.obj$main[tbl.obj$main.nrw], tbl.obj$cond.txt, sep="")} for (main.dx in 1:tbl.obj$main.nrw) { y.loc <- y.rem - char.dim.obj$linespace.main*(main.dx-.5) + .25*char.dim.obj$linespace.col grid.text(tbl.obj$main[main.dx], just = "left", gp = gpar(fontfamily = style$frmt.main$fontfamily, fontface = style$frmt.main$fontface, fontsize = style$frmt.main$fontsize, cex = style$cex, col = style$frmt.main$col), x = unit(init[1], "inches"), y = unit(y.loc, "inches")) } y.rem <- y.rem - char.dim.obj$linespace.main*(main.dx-.5) } else {y.rem <- y.rem + .5*char.dim.obj$linespace.col} for (y.dx in 1:tbl.obj$nrw) { y.loc <- y.rem - char.dim.obj$linespace.col*(tbl.obj$nrw.colhead + .25) - char.dim.obj$linespace.bdy*y.dx if (!is.null(row.hl)) { if (y.dx %in% tbl.obj$row.hl$dx) { grid.rect(x = unit(init[1],"inches"), y = unit(y.loc, "inches"), height = unit(char.dim.obj$linespace.bdy, "inches"), width = unit(size.simp.obj$tbl.width, "inches"), just = "left", gp = gpar(col = tbl.obj$row.hl$col, fill = tbl.obj$row.hl$col, fontsize = style$frmt.bdy$fontsize, cex = style$cex)) } } } grid.rect(x = unit(init[1],"inches"), y = unit(init[2]-(main.nrw)*char.dim.obj$linespace.main-.5*char.dim.obj$linespace.col*(tbl.obj$nrw.colhead-.25), "inches"), height = unit(char.dim.obj$linespace.col*(tbl.obj$nrw.colhead+.125), "inches"), width = unit(size.simp.obj$tbl.width, "inches"), just = "left", gp = gpar(col = style$frmt.col$bg, fill = style$frmt.col$bg, fontsize = style$frmt.col$fontsize, cex = style$cex)) for (col.dx in 1:nrow(tbl.obj$colhead)) { col.y.loc <- y.rem - char.dim.obj$linespace.col*tbl.obj$colhead[col.dx, "row"] if (tbl.obj$colhead[col.dx, "col.logical.row"]==1) { col.x.loc <- init[1] + char.dim.obj$cw.row.u + char.dim.obj$bdy.xloc[tbl.obj$colhead[col.dx, "span.beg"]] + .5*(char.dim.obj$bdy.xloc[tbl.obj$colhead[col.dx, "span.end"]]-char.dim.obj$bdy.xloc[tbl.obj$colhead[col.dx, "span.beg"]]) j <- style$justify } else { col.x.loc <- init[1] + char.dim.obj$cw.row.u + char.dim.obj$colhead.xloc[tbl.obj$colhead[col.dx, "span.beg"]] + .5*(char.dim.obj$colhead.xloc[tbl.obj$colhead[col.dx, "span.end"]]-char.dim.obj$colhead.xloc[tbl.obj$colhead[col.dx, "span.beg"]]) j <- "center" if (style$frmt.colh$bty%in%c("o")) { dborder(c(init[1]+char.dim.obj$cw.row.u+char.dim.obj$colhead.xloc[tbl.obj$colhead[col.dx, "span.beg"]]-.5*char.dim.obj$cw.bdy.u[tbl.obj$colhead[col.dx, "span.beg"]], col.y.loc+.625*char.dim.obj$linespace.col), c(init[1]+char.dim.obj$cw.row.u+char.dim.obj$colhead.xloc[tbl.obj$colhead[col.dx, "span.end"]]+.5*char.dim.obj$cw.bdy.u[tbl.obj$colhead[col.dx, "span.end"]], init[2]-size.simp.obj$tbl.height.m-.25*char.dim.obj$linespace.col), frmt=style$frmt.colh) } if (style$frmt.colh$bty=="_") { dborder(c(init[1]+char.dim.obj$cw.row.u+char.dim.obj$colhead.xloc[tbl.obj$colhead[col.dx, "span.beg"]], col.y.loc+.5*char.dim.obj$linespace.col), c(init[1]+char.dim.obj$cw.row.u+char.dim.obj$colhead.xloc[tbl.obj$colhead[col.dx, "span.end"]], col.y.loc-.5*char.dim.obj$linespace.col), frmt=style$frmt.colh) } } grid.text(tbl.obj$colhead[col.dx, "cname"], just = j, gp = gpar(fontfamily = style$frmt.col$fontfamily, fontface = style$frmt.col$fontface, fontsize = style$frmt.col$fontsize, cex = style$cex, col = style$frmt.col$col), x = unit(col.x.loc, "inches"), y = unit(col.y.loc, "inches")) } y.rem <- y.rem - char.dim.obj$linespace.col*(tbl.obj$nrw.colhead + .25) dborder(c(init[1], init[2]-main.nrw*char.dim.obj$linespace.main + .25*char.dim.obj$linespace.col), c(init[1]+size.simp.obj$tbl.width, y.rem-.375*char.dim.obj$linespace.col), frmt=style$frmt.col) for (y.dx in 1:tbl.obj$nrw) { y.loc <- y.rem - char.dim.obj$linespace.bdy*y.dx if (y.dx != tbl.obj$nrw) { dborder(c(init[1], y.loc-.5*char.dim.obj$linespace.bdy), c(init[1]+size.simp.obj$tbl.width, y.loc-.5*char.dim.obj$linespace.bdy), frmt=style$frmt.bdy)} if (!is.null(tbl.obj$group[1])) { if (!is.na(tbl.obj$group[y.dx])) { grid.text(tbl.obj$group[y.dx], just = "left", gp = gpar(fontfamily = style$frmt.grp$fontfamily, fontface = style$frmt.grp$fontface, fontsize = style$frmt.grp$fontsize, cex = style$cex, col = style$frmt.grp$col), x = unit(init[1], "inches"), y = unit(y.loc, "inches")) } if (tbl.obj$lastofgroup[y.dx] & (y.dx != tbl.obj$nrw)) { dborder(c(init[1], y.loc-.5*char.dim.obj$linespace.bdy), c(init[1]+size.simp.obj$tbl.width, y.loc-.5*char.dim.obj$linespace.bdy), frmt=style$frmt.grp) } } if (!is.null(tbl.obj$label[1])) { if (!is.na(tbl.obj$label[y.dx])) { grid.text(tbl.obj$label[y.dx], just = "left", gp = gpar(fontfamily = style$frmt.bdy$fontfamily, fontface = style$frmt.bdy$fontface, fontsize = style$frmt.bdy$fontsize, cex = style$cex, col = style$frmt.bdy$col), x = unit(init[1]+char.dim.obj$lbl.indent, "inches"), y = unit(y.loc, "inches")) } } for (x.dx in 1:tbl.obj$ncl) { x.loc <- init[1] + char.dim.obj$cw.row.u + char.dim.obj$bdy.xloc[x.dx] if (!is.na(tbl.obj$bdy[y.dx , x.dx])) { grid.text(tbl.obj$bdy[y.dx , x.dx], just = style$justify, gp = gpar(fontfamily = style$frmt.bdy$fontfamily, fontface = style$frmt.bdy$fontface, fontsize = style$frmt.bdy$fontsize, cex = style$cex, col = style$frmt.bdy$col), x = unit(x.loc, "inches"), y = unit(y.loc, "inches")) } } } y.rem <- y.loc dborder(c(init[1], init[2]-main.nrw*char.dim.obj$linespace.main+.25*char.dim.obj$linespace.col), c(init[1]+size.simp.obj$tbl.width, init[2]-size.simp.obj$tbl.height.m-.25*char.dim.obj$linespace.col), frmt=style$frmt.tbl) if (!is.na(tbl.obj$footnote.nrw)) { for (footnote.dx in 1:tbl.obj$footnote.nrw) { y.loc <- y.rem - char.dim.obj$linespace.ftn*.25 - char.dim.obj$linespace.ftn*footnote.dx grid.text(tbl.obj$footnote[footnote.dx], just = "left", gp = gpar(fontfamily = style$frmt.ftn$fontfamily, fontface = style$frmt.ftn$fontface, fontsize = style$frmt.ftn$fontsize, cex = style$cex, col = style$frmt.ftn$col), x = unit(init[1], "inches"), y = unit(y.loc, "inches")) } y.rem <- y.loc } y.rem <- y.loc return( list(cord1=c(init[1], init[2]), cord2=c(init[1] + char.dim.obj$cw.row.u + char.dim.obj$bdy.xloc[length(char.dim.obj$bdy.xloc)], y.rem-.5*char.dim.obj$linespace.bdy) )) }
require(RSelenium) remDr <- remoteDriver() remDr$open() remDr$setImplicitWaitTimeout(3000) remDr$navigate("http://www.spp.org/LIP.asp") remDr$switchToFrame("content_frame") dateElem <- remDr$findElement(using = "id", "txtLIPDate") dateRequired <- "01/14/2014" dateElem$clearElement() dateElem$sendKeysToElement(list("01/14/2014", key = "enter")) hourElem <- remDr$findElement(using = "css selector", ' hourElem$clickElement() buttonElem <- remDr$findElement(using = "id", "cmdView") buttonElem$clickElement() tableElem <- remDr$findElement(using = "id", "dgLIP") readHTMLTable(htmlParse(tableElem$getElementAttribute("outerHTML")[[1]]))
lc_qol <- function(x){ d <- as.matrix(select(x,'LC_Q31':'LC_Q42')) for(j in 1:ncol(d)){ for(i in 1:nrow(d)){ if(is.na(d[i,j])==TRUE || d[i,j]==9 || d[i,j]==99){ d[i,j] <- min(d[,j],na.rm = TRUE) } } } RS <- function(a){ nr <- nrow(a) rs <- rep(0, nr) for(i in 1:nr){ rs[i] <- mean(a[i,]) } return(rs) } SS <- function(a,b){ nr <- length(a) ss <- rep(0, nr) for(i in 1:nr){ ss[i] <- ((a[i]-1)/diff(range(b)))*100 } return(ss) } RS_data <- data.frame(RS_LCDY = RS(d[,3:5]), RS_LCCO = d[,1], RS_LCHA = d[,2], RS_LCSM = d[,6], RS_LCDS = d[,7], RS_LCPN = d[,8], RS_LCHR = d[,9], RS_LCPC = d[,10], RS_LCPA = d[,11], RS_LCPO = d[,12]) score_data <- data.frame(LCDY = SS(RS_data$RS_LCDY,d[,3:5]), LCCO = SS(RS_data$RS_LCCO,d[,1]), LCHA = SS(RS_data$RS_LCHA,d[,2]), LCSM = SS(RS_data$RS_LCSM,d[,6]), LCDS = SS(RS_data$RS_LCDS,d[,7]), LCPN = SS(RS_data$RS_LCPN,d[,8]), LCHR = SS(RS_data$RS_LCHR,d[,9]), LCPC = SS(RS_data$RS_LCPC,d[,10]), LCPA = SS(RS_data$RS_LCPA,d[,11]), LCPO = SS(RS_data$RS_LCPO,d[,12])) new_data <- select(x,-('LC_Q31':'LC_Q42')) final_data <- data.frame(new_data,score_data) return(final_data) }
treatment.effect <- function(ipd = NULL, samples = NULL, newpatient = NULL, reference = NULL, quantiles = c(0.025, 0.5, 0.975)){ if(class(ipd) == "ipdma.onestage"){ newpatient <- (newpatient - ipd$scale_mean)/ipd$scale_sd index0 <- which(colnames(samples[[1]]) == "delta[2]") index1 <- grep("gamma", colnames(samples[[1]])) index <- c(index0, index1) samples2 <- samples[,index] merged <- samples2[[1]] for(i in 2:length(samples2)){ merged <- rbind(merged, samples2[[i]]) } pred <- merged %*% c(1, newpatient) if(ipd$response == "normal"){ CI <- quantile(pred, probs = quantiles) } else if(ipd$response == "binomial"){ CI <- exp(quantile(pred, probs = quantiles)) } names(CI) <- quantiles } else if (class(ipd) == "ipdma.onestage.deft"){ if(is.null(reference)){ stop("Need to specify reference group for deft approach") } newpatient <- newpatient - reference index0 <- which(colnames(samples[[1]]) == "delta[2]") index1 <- grep("gamma.within", colnames(samples[[1]])) index <- c(index0, index1) samples2 <- samples[,index] merged <- samples2[[1]] for(i in 2:length(samples2)){ merged <- rbind(merged, samples2[[i]]) } pred <- merged %*% c(1, newpatient) if(ipd$response == "normal"){ CI <- quantile(pred, probs = quantiles) } else if(ipd$response == "binomial"){ CI <- exp(quantile(pred, probs = quantiles)) } names(CI) <- quantiles } else{ stop("Calculating patient specific treatment effect is not yet implemented for this method") } return(CI) }
context("Quantile Lambda4") test_that('Quantile Lambda4 and population covariance matrices',{ par.1f<-as.numeric(round(quant.lambda4(par1f)[[1]][[1]],6)) expect_that(par.1f, equals(.888889)) tau.1f<-as.numeric(round(quant.lambda4(tau1f)[[1]][[1]],6)) expect_that(tau.1f, equals(.833575)) par.3f<-as.numeric(round(quant.lambda4(par3f)[[1]][[1]],6)) expect_that(par.3f, equals(.864865)) tau.3f<-as.numeric(round(quant.lambda4(tau3f)[[1]][[1]],6)) expect_that(tau.3f, equals(.800278)) par.5f<-as.numeric(round(quant.lambda4(par5f)[[1]][[1]],6)) expect_that(par.5f, equals(.897959)) tau.5f<-as.numeric(round(quant.lambda4(tau5f)[[1]][[1]],6)) expect_that(tau.5f, equals(.846380)) })
setMethod("getInfRobIC", signature(L2deriv = "UnivariateDistribution", risk = "asGRisk", neighbor = "UncondNeighborhood"), function(L2deriv, risk, neighbor, symm, Finfo, trafo, upper, maxiter, tol, warn){ radius <- neighbor@radius if(identical(all.equal(radius, 0), TRUE)){ if(warn) cat("'radius == 0' => (classical) optimal IC\n", "in sense of Cramer-Rao bound is returned\n") res <- getInfRobIC(L2deriv = L2deriv, risk = asCov(), neighbor = neighbor, Finfo = Finfo, trafo = trafo) Risk <- getAsRisk(risk = risk, L2deriv = L2deriv, neighbor = neighbor, clip = res$b, cent = res$a, stand = res$A, trafo = trafo) res$risk <- c(Risk, res$risk) return(res) } z <- 0 c0 <- 0 iter <- 0 if(is(symm, "SphericalSymmetry")) S <- symm@SymmCenter == 0 else S <- FALSE repeat{ iter <- iter + 1 z.old <- z c0.old <- c0 c0 <- try(uniroot(getInfClip, lower = .Machine$double.eps^0.75, upper = upper, tol = tol, L2deriv = L2deriv, risk = risk, neighbor = neighbor, cent = z, symm = S, trafo = trafo)$root, silent = TRUE) if(!is.numeric(c0)){ if(warn) cat("The IC algorithm did not converge!\n", "'radius >= maximum radius' for the given risk?\n", "=> the minimum asymptotic bias (lower case) solution is returned\n") res <- getInfRobIC(L2deriv = L2deriv, risk = asBias(), neighbor = neighbor, Finfo = Finfo, symm = symm, trafo = trafo, upper = upper, maxiter = maxiter, tol = tol, warn = warn) Risk <- getAsRisk(risk = risk, L2deriv = L2deriv, neighbor = neighbor, clip = res$b, cent = res$a, stand = res$A, trafo = trafo) res$risk <- c(Risk, res$risk) return(res) } z <- getInfCent(L2deriv = L2deriv, neighbor = neighbor, clip = c0, cent = z, symm = S, trafo = trafo, tol.z = tol) if(S) break if(max(abs(z - z.old), abs(c0-c0.old)) < tol) break if(iter > maxiter){ cat("maximum iterations reached!\n", "achieved precision:\t", abs(c0 - c0.old), "\n") break } } info <- paste("optimally robust IC for", sQuote(class(risk)[1])) A <- getInfStand(L2deriv = L2deriv, neighbor = neighbor, clip = c0, cent = z, trafo = trafo) a <- as.vector(A)*z b <- abs(as.vector(A))*c0 Risk <- getAsRisk(risk = risk, L2deriv = L2deriv, neighbor = neighbor, clip = b, cent = a, stand = A, trafo = trafo) Risk <- c(Risk, list(asBias = b)) return(list(A = A, a = a, b = b, d = NULL, risk = Risk, info = info)) }) setMethod("getInfRobIC", signature(L2deriv = "RealRandVariable", risk = "asGRisk", neighbor = "ContNeighborhood"), function(L2deriv, risk, neighbor, Distr, DistrSymm, L2derivSymm, L2derivDistrSymm, Finfo, trafo, z.start, A.start, upper, maxiter, tol, warn){ if(is.null(z.start)) z.start <- numeric(ncol(trafo)) if(is.null(A.start)) A.start <- trafo radius <- neighbor@radius if(identical(all.equal(radius, 0), TRUE)){ if(warn) cat("'radius == 0' => (classical) optimal IC\n", "in sense of Cramer-Rao bound is returned\n") res <- getInfRobIC(L2deriv = L2deriv, risk = asCov(), neighbor = neighbor, Distr = Distr, Finfo = Finfo, trafo = trafo) Risk <- getAsRisk(risk = risk, L2deriv = L2deriv, neighbor = neighbor, clip = res$b, cent = res$a, stand = res$A, trafo = trafo) res$risk <- c(Risk, res$risk) return(res) } nrvalues <- length(L2deriv) z.comp <- rep(TRUE, nrvalues) A.comp <- matrix(TRUE, ncol = nrvalues, nrow = nrvalues) for(i in 1:nrvalues){ if(is(L2derivDistrSymm[[i]], "SphericalSymmetry")) if(L2derivDistrSymm[[i]]@SymmCenter == 0) z.comp[i] <- FALSE } for(i in 1:(nrvalues-1)) for(j in (i+1):nrvalues){ if(is(DistrSymm, "SphericalSymmetry")){ if((is(L2derivSymm[[i]], "OddSymmetric") & is(L2derivSymm[[j]], "EvenSymmetric")) | (is(L2derivSymm[[j]], "OddSymmetric") & is(L2derivSymm[[i]], "EvenSymmetric"))) if((L2derivSymm[[i]]@SymmCenter == L2derivSymm[[j]]@SymmCenter) & (L2derivSymm[[i]]@SymmCenter == DistrSymm@SymmCenter)) A.comp[i,j] <- FALSE } } A.comp[col(A.comp) < row(A.comp)] <- A.comp[col(A.comp) > row(A.comp)] z <- z.start A <- A.start b <- 0 iter <- 0 repeat{ iter <- iter + 1 z.old <- z b.old <- b A.old <- A b <- try(uniroot(getInfClip, lower = .Machine$double.eps^0.75, upper = upper, tol = tol, L2deriv = L2deriv, risk = risk, Distr = Distr, neighbor = neighbor, stand = A, cent = z, trafo = trafo)$root, silent = TRUE) if(!is.numeric(b)){ if(warn) cat("Could not determine optimal clipping bound!\n", "'radius >= maximum radius' for the given risk?\n", "=> the minimum asymptotic bias (lower case) solution is returned\n", "If 'no' => Try again with modified starting values ", "'z.start' and 'A.start'\n") res <- getInfRobIC(L2deriv = L2deriv, risk = asBias(), neighbor = neighbor, Distr = Distr, DistrSymm = DistrSymm, L2derivSymm = L2derivSymm, L2derivDistrSymm = L2derivDistrSymm, z.start = z.start, A.start = A.start, trafo = trafo, upper = upper, maxiter = maxiter, tol = tol, warn = warn) Risk <- getAsRisk(risk = risk, L2deriv = L2deriv, neighbor = neighbor, clip = res$b, cent = res$a, stand = res$A, trafo = trafo) res$risk <- c(Risk, res$risk) return(res) } z <- getInfCent(L2deriv = L2deriv, neighbor = neighbor, Distr = Distr, z.comp = z.comp, stand = A, cent = z, clip = b) A <- getInfStand(L2deriv = L2deriv, neighbor = neighbor, Distr = Distr, A.comp = A.comp, stand = A, clip = b, cent = z, trafo = trafo) prec <- max(abs(b-b.old), max(abs(A-A.old)), max(abs(z-z.old))) cat("current precision in IC algo:\t", prec, "\n") if(prec < tol) break if(iter > maxiter){ cat("maximum iterations reached!\n", "achieved precision:\t", prec, "\n") break } } a <- as.vector(A %*% z) info <- paste("optimally robust IC for", sQuote(class(risk)[1])) Risk <- getAsRisk(risk = risk, L2deriv = L2deriv, neighbor = neighbor, clip = b, cent = a, stand = A, trafo = trafo) Risk <- c(Risk, list(asBias = b)) return(list(A = A, a = a, b = b, d = NULL, risk = Risk, info = info)) })
expand.grid <- function(..., KEEP.OUT.ATTRS = TRUE, stringsAsFactors = TRUE) { nargs <- length(args <- list(...)) if(!nargs) return(as.data.frame(list())) if(nargs == 1L && is.list(a1 <- args[[1L]])) nargs <- length(args <- a1) if(nargs == 0L) return(as.data.frame(list())) cargs <- vector("list", nargs) iArgs <- seq_len(nargs) nmc <- paste0("Var", iArgs) nm <- names(args) if(is.null(nm)) nm <- nmc else if(any(ng0 <- nzchar(nm))) nmc[ng0] <- nm[ng0] names(cargs) <- nmc rep.fac <- 1L d <- lengths(args) if(KEEP.OUT.ATTRS) { dn <- vector("list", nargs) names(dn) <- nmc } orep <- prod(d) if(orep == 0L) { for(i in iArgs) cargs[[i]] <- args[[i]][FALSE] } else { for(i in iArgs) { x <- args[[i]] if(KEEP.OUT.ATTRS) dn[[i]] <- paste0(nmc[i], "=", if(is.numeric(x)) format(x) else x) nx <- length(x) orep <- orep/nx if(stringsAsFactors && is.character(x)) x <- factor(x, levels = unique(x)) x <- x[rep.int(rep.int(seq_len(nx), rep.int(rep.fac, nx)), orep)] cargs[[i]] <- x rep.fac <- rep.fac * nx } } if(KEEP.OUT.ATTRS) attr(cargs, "out.attrs") <- list(dim=d, dimnames=dn) rn <- .set_row_names( as.integer(prod(d)) ) structure(cargs, class = "data.frame", row.names = rn) }
dggamma <- function(x,shape1,rate1,shape2){ shape2 <- as.integer(shape2) if(sum(c(x,shape1,rate1,shape2)<=0)>0){ stop("All parameters and values of x must be positive.") } out <- ((rate1^shape1)/gamma(shape1))*(gamma(shape1+shape2)/gamma(shape2))* ((x^(shape2-1))/((rate1+x)^(shape1+shape2))) return(out) }
NULL setClass('NMFns' , representation( theta = 'numeric' ) , contains = 'NMFstd' , prototype = prototype( theta = 0.5 ) , validity = function(object){ if( object@theta < 0 || object@theta > 1 ) return(paste("Invalid value for theta (",object@theta,"): must be between 0 and 1", sep='')) TRUE } ) setMethod('show', 'NMFns', function(object) { callNextMethod() cat("theta:", object@theta, "\n") } ) setMethod('fitted', signature(object='NMFns'), function(object, W, H, S, ...){ if( missing(W) ) W <- object@W if( missing(H) ) H <- object@H if( missing(S) ) S <- smoothing(object, ...) W %*% (S %*% H) } ) smoothing <- function(x, theta=x@theta, ...){ if( theta < 0 || theta > 1 ) stop("Invalid smoothing parameter theta [",theta,"]: theta must be susch that 0 <= theta <=1") diag(1-theta, nbasis(x)) + theta / nbasis(x) }
MFM_optimal_n <- function(cvec, pivec, Rvec, thres_CR){ n <- sum(cvec) + 1 CR <- MFM_consumerrisk(n, cvec, pivec, Rvec) while (CR > thres_CR){ n <- n + 1 CR <- MFM_consumerrisk(n, cvec, pivec, Rvec) } return(n) }
ols_test_breusch_pagan <- function(model, fitted.values = TRUE, rhs = FALSE, multiple = FALSE, p.adj = c("none", "bonferroni", "sidak", "holm"), vars = NA) UseMethod("ols_test_breusch_pagan") ols_test_breusch_pagan.default <- function(model, fitted.values = TRUE, rhs = FALSE, multiple = FALSE, p.adj = c("none", "bonferroni", "sidak", "holm"), vars = NA) { check_model(model) check_logic(fitted.values) check_logic(rhs) check_logic(multiple) suppressWarnings( if (!is.na(vars[1])) { check_modelvars(model, vars) fitted.values <- FALSE } ) method <- match.arg(p.adj) p.adj <- match.arg(p.adj) check_options(p.adj) l <- ols_prep_avplot_data(model) n <- nrow(l) response <- names(l)[1] predictors <- names(l)[-1] if (fitted.values) { vars <- NA if (rhs) { if (multiple) { start <- bp_case_one(l, model) loops <- bp_case_loop(start$np, start$nam, start$l) inter <- bp_case_inter(start$l, start$np, loops$tstat) bp <- inter$bp p <- bp_case_adj(method, loops$pvals, start$np, inter$ps) } else { result <- bp_case_2(l, model) bp <- result$bp p <- pchisq(bp, df = result$df, lower.tail = FALSE) } } else { bp <- bp_case_3(model) p <- pchisq(bp, df = 1, lower.tail = FALSE) } } else { if (multiple) { if (rhs) { start <- bp_case_one(l, model) loops <- bp_case_loop(start$np, start$nam, start$l) inter <- bp_case_inter(start$l, start$np, loops$tstat) bp <- inter$bp p <- bp_case_adj(method, loops$pvals, start$np, inter$ps) } else { len_vars <- length(vars) if (len_vars > 1) { start <- bp_case_one(l, model) len_var <- length(vars) loops <- bp_case_loop(len_var, vars, start$l) inter <- bp_case_5_inter(l, model, vars, loops$tstat) bp <- inter$bp p <- bp_case_adj(method, loops$pvals, inter$np, inter$ps) } else { result <- bp_case_7(l, model, vars) bp <- result$bp p <- pchisq(bp, df = result$df, lower.tail = FALSE) } } } else { if (rhs) { result <- bp_case_6(l, model) bp <- result$bp p <- pchisq(bp, df = result$df, lower.tail = FALSE) } else { result <- bp_case_7(l, model, vars) bp <- result$bp p <- pchisq(bp, df = result$df, lower.tail = FALSE) } } } out <- list( bp = bp, p = p, fv = fitted.values, rhs = rhs, multiple = multiple, padj = method, vars = vars, resp = response, preds = predictors ) class(out) <- "ols_test_breusch_pagan" return(out) } ols_bp_test <- function(model, fitted.values = TRUE, rhs = FALSE, multiple = FALSE, p.adj = c("none", "bonferroni", "sidak", "holm"), vars = NA) { .Deprecated("ols_test_breusch_pagan()") } print.ols_test_breusch_pagan <- function(x, ...) { print_bp_test(x) } bp_case_2 <- function(l, model) { n <- model_rows(model) var_resid <- residual_var(model, n) ind <- ind_bp(model, var_resid) df <- ncol(l[, -1]) l <- cbind(l[, -1], ind) bp <- bp_model(l) list(bp = bp, df = df) } bp_case_3 <- function(model) { `Sum Sq` <- NULL pred <- fitted(model) scaled_resid <- resid_scaled(model, pred) (anova(lm(scaled_resid ~ pred))$`Sum Sq`[1]) / 2 } bp_case_6 <- function(l, model) { n <- nrow(l) var_resid <- residual_var(model, n) ind <- ind_bp(model, var_resid) np <- length(names(l)[-1]) bp <- bp_model(cbind(l, ind)[, -1]) list(bp = bp, df = np) } bp_case_7 <- function(l, model, vars) { n <- nrow(l) var_resid <- residual_var(model, n) ind <- ind_bp(model, var_resid) l <- cbind(l[, vars], ind) bp <- bp_model(l) nd <- ncol(l) - 1 list(bp = bp, df = nd) } bp_model <- function(l) { bp_fit(lm(ind ~ ., data = l)) } bp_fit <- function(l) { (sum(fitted(l) ^ 2)) / 2 } ind_bp <- function(model, var_resid) { data.frame(ind = ((residuals(model) ^ 2) / var_resid) - 1) } bp_case_one <- function(l, model) { nam <- names(l)[-1] np <- length(nam) n <- nrow(l) var_resid <- residual_var(model, n) ind <- ind_bp(model, var_resid) l <- cbind(l, ind) list(np = np, nam = nam, l = l) } bp_case_loop <- function(np, nam, l) { tstat <- c() pvals <- c() for (i in seq_len(np)) { form <- as.formula(paste("ind ~", nam[i])) tstat[i] <- bp_fit(lm(form, data = l)) pvals[i] <- pchisq(tstat[i], df = 1, lower.tail = FALSE) } list(tstat = tstat, pvals = pvals) } bp_case_inter <- function(l, np, tstat) { comp <- bp_fit(lm(ind ~ ., data = l[, -1])) ps <- pchisq(comp, df = np, lower.tail = FALSE) bp <- c(tstat, comp) list(bp = bp, ps = ps) } bp_case_adj <- function(method, pvals, np, ps) { if (method == "bonferroni") { bpvals <- pmin(1, pvals * np) p <- c(bpvals, ps) } else if (method == "sidak") { spvals <- pmin(1, 1 - (1 - pvals) ^ np) p <- c(spvals, ps) } else if (method == "holm") { j <- rev(seq_len(length(pvals))) h <- order(order(pvals)) pvals_sort <- sort(pvals) * j pholms <- pmin(1, pvals_sort)[h] p <- c(pholms, ps) } else { p <- c(pvals, ps) } return(p) } bp_case_5_inter <- function(l, model, vars, tstat) { n <- nrow(l) var_resid <- residual_var(model, n) ind <- ind_bp(model, var_resid) l <- cbind(l[, -1][, vars], ind) np <- ncol(l) - 1 ps <- pchisq(q = bp_model(l), df = np, lower.tail = FALSE) bp <- c(tstat, bp_model(l)) list(bp = bp, ps = ps, np = np) }
ploteach <- function(pred_levels, plotdat, cov_name, args, col) { dfs = args_new = list() for (p in 1:length(pred_levels)) { parameters <- plotdat[which(plotdat[ ,6] == pred_levels[p]), 1:5] new_main = paste(cov_name, " = ", pred_levels[p], sep="") unik_ids <- unique(parameters$id) nsubject2 <- length(unik_ids) parameters$id2 <- rep(NA, nrow(parameters)) for (i in 1:nsubject2){ index <- which(parameters$id == unik_ids[i]) parameters$id2[index]=rep(i, length(index)) } parameters2 <- cbind(parameters[,6], parameters[,2:5]) colnames(parameters2) <- c("id", "episode", "xij", "yij", "ci") dfs[[p]] <- data.frame(parameters2) args2 = args args2[1] = new_main args_new[[p]] <- args2 } rdim <- ceiling(length(pred_levels)/2) + 1 layoutvect <- c(seq(1, length(pred_levels)), rep(length(pred_levels)+1, 2)) layout(matrix(layoutvect, nrow=rdim, byrow=TRUE), heights = (c(rep(4,rdim-1), 1))) par(mar=c(5,4,4,2)+0.1) for (p_iter in 1:length(pred_levels)) { basicplot(parameters = dfs[[p_iter]], ctimes = unique(dfs[[p_iter]]$ci), nsubject=max(unique(dfs[[p_iter]]$id)), temp=NULL, args = args_new[[p_iter]], col=col, c=0.75, cm=0.9, byp=TRUE) } legendtext = c(args[4], args[5]) par(mar=c(1,1,1,1)+0.1) plot(0:1, 0:1, xaxt='n',yaxt='n',bty='n',ylab='',xlab='', col="white") legend("center", legend=legendtext, col = col, lty = 1, bg = "white", bty='n', horiz=TRUE) } plotBy <- function(df, args, col) { num_levs <- apply(df[, 6:ncol(df)], 2, function(x) length(unique(x))) to_delete <- which(num_levs > 6) + 5 if(length(to_delete)>0){ message1 <- paste(colnames(df)[to_delete], " not used - either continuous or had more than 6 levels.", sep="") print(message1) df <- df[, -to_delete] } if (ncol(df)==5) {stop("Cannot break by covariate. All covariates are continuous or have more than 6 levels.")} cov_names <- colnames(df)[6:ncol(df)] nsubject <-length(unique(df$id)) message <- paste("Subjects for plots: ", nsubject, ".", sep="") print(message) if (length(cov_names)==1) { pred_levels = unique(df[,6]) plotdat = na.omit(df[ , 1:6]) ploteach(pred_levels, plotdat, cov_name = cov_names, args, col = col) } else { for (k in 1:length(cov_names)) { pred_levels = unique(df[ ,5+k]) plotdat = na.omit(df[, c(1:5, 5+k)]) ploteach(pred_levels, plotdat, cov_name = cov_names[k], args, col=col) } } par(mfrow=c(1, 1)) }
"subPed"<-function(Pedig, keep, prevGen=3, succGen=0){ PedigAsDataTable <- "data.table" %in% class(Pedig) Pedig <- as.data.frame(Pedig) if(PedigAsDataTable){setDF(Pedig)} colnames(Pedig)[1:3]<-c("Indiv", "Sire", "Dam") if(is.logical(keep)){keep<-Pedig$Indiv[keep]} Pedig<-prePed(Pedig, lastNative=1234567) selected <- Pedig$Indiv %in% keep inPrevGen <- selected if(prevGen>0){ for(i in 1:prevGen){ inPrevGen <- inPrevGen | Pedig$Indiv %in% Pedig$Sire[inPrevGen] | Pedig$Indiv %in% Pedig$Dam[inPrevGen] } } inSuccGen <- selected if(succGen>0){ for(i in 1:succGen){ inSuccGen <- inSuccGen | Pedig$Sire %in% Pedig$Indiv[inSuccGen] | Pedig$Dam %in% Pedig$Indiv[inSuccGen] } Sires <- Pedig$Sire[inSuccGen & !selected] Dams <- Pedig$Dam[inSuccGen & !selected] inSuccGen <- inSuccGen | Pedig$Indiv %in% Sires | Pedig$Indiv %in% Dams } Pedig <- Pedig[selected | inPrevGen | inSuccGen, ] Pedig[!(Pedig$Sire %in% Pedig$Indiv), "Sire"] <- NA Pedig[!(Pedig$Dam %in% Pedig$Indiv), "Dam"] <- NA Pedig<-prePed(Pedig, lastNative=1234567) Pedig$keep<-Pedig$Indiv %in% keep if(PedigAsDataTable){setDT(Pedig)} Pedig }
fix.names<-function(nam, upper=FALSE, lower=FALSE) { if(missing(upper)) upper=FALSE if(missing(lower)) lower=FALSE gnam = nam gnam= gsub(" ", "_", gnam) gnam=gsub("\'", "_", gnam) gnam= gsub("\"", "_", gnam) if(lower)gnam = tolower(gnam) if(upper) gnam = toupper(gnam) return(gnam) }
variance_draws <- function(model, value = ".sigma_sq", ...) { UseMethod("variance_draws") } variance_draws.wbart <- function(model, value = ".sigma_sq", ...) { sigma_draws <- model$sigma dplyr::tibble( .chain = NA_integer_, .iteration = NA_integer_, .draw = 1:length(sigma_draws), !!value := sigma_draws^2 ) } variance_draws.bartMachine <- function(model, value = ".sigma_sq", ...) { sigma2_draws <- bartMachine::get_sigsqs(model) dplyr::tibble( .chain = NA_integer_, .iteration = NA_integer_, .draw = 1:length(sigma2_draws), !!value := sigma2_draws ) }
testthat::context("CRAN_watchdog - T1. Our codebase doesn't violate CRAN style-guidelines.") testthat::test_that("T1.1 TRUE/FALSE are used instead of T/F.", { test_files <- .get_visR_files(functions = TRUE, tests = TRUE, documentation = TRUE, vignettes = TRUE) patterns <- list("=T,", "=T ", "=T)", "=F,", "=F ", "=F)", "= T,", "= T ", "= T)", "= F,", "= F ", "= F)") CRAN_incompabilities <- data.frame() for (test_file in test_files) { for (pattern in patterns) { hits <- base::grep(pattern, base::readLines(test_file, warn = FALSE)) if (base::length(hits) > 0) { tmp <- data.frame("line" = hits) tmp[["file"]] <- test_file tmp[["issue"]] <- pattern CRAN_incompabilities <- base::rbind(CRAN_incompabilities, tmp) } } } if (base::nrow(CRAN_incompabilities) > 0) { cat(paste0(CRAN_incompabilities, collapse = ";")) } testthat::expect_true(base::nrow(CRAN_incompabilities) == 0) }) testthat::test_that("T1.2 Each function documentation contains a \\value{} tag.", { test_files <- .get_visR_files(documentation = TRUE) exceptions <- list("adtte.Rd", "brca_cohort.Rd", "visR-Global.Rd", "visR-package.Rd", "reexports.Rd") exceptions_collapsed <- paste(exceptions, collapse = "|") CRAN_incompabilities <- data.frame() for (test_file in test_files) { if (sum(grepl(exceptions_collapsed, test_file)) == 0) { name_hits <- base::grep("\\\\name\\{", base::readLines(test_file, warn = FALSE)) value_hits <- base::grep("\\\\value\\{", base::readLines(test_file, warn = FALSE)) if (length(name_hits) != length(value_hits)) { name_hits <- base::ifelse(length(name_hits) == 0, NA, name_hits) value_hits <- base::ifelse(length(name_hits) == 0, NA, value_hits) tmp <- data.frame("name_line" = name_hits) tmp[["value_line"]] <- value_hits tmp[["file"]] <- test_file CRAN_incompabilities <- base::rbind(CRAN_incompabilities, tmp) } } } if (base::nrow(CRAN_incompabilities) > 0) { print(CRAN_incompabilities) } testthat::expect_true(base::nrow(CRAN_incompabilities) == 0) }) testthat::test_that("T1.3 The existence of packages is not checked through 'installed.packages()'.", { test_files <- .get_visR_files(functions = TRUE, tests = TRUE, documentation = TRUE, vignettes = TRUE) CRAN_incompabilities <- data.frame() for (test_file in test_files) { hits <- base::grep("\\\\installed.packages", base::readLines(test_file, warn = FALSE)) if (length(hits) > 0) { tmp <- data.frame("line" = hits) tmp[["file"]] <- test_file CRAN_incompabilities <- base::rbind(CRAN_incompabilities, tmp) } } if (base::nrow(CRAN_incompabilities) > 0) { print(CRAN_incompabilities) } testthat::expect_true(base::nrow(CRAN_incompabilities) == 0) }) testthat::test_that("T1.4 No \\dontrun{} tags unless the code actually takes a long time.", { test_files <- .get_visR_files(documentation = TRUE) exceptions <- list("adtte.Rd", "brca_cohort.Rd", "visR-Global.Rd") exceptions_collapsed <- paste(exceptions, collapse = "|") CRAN_incompabilities <- data.frame() for (test_file in test_files) { if (sum(grepl(exceptions_collapsed, test_file)) == 0) { hits <- base::grep("\\\\dontrun\\{", base::readLines(test_file, warn = FALSE)) if (length(hits) > 0) { tmp <- data.frame("line" = hits) tmp[["file"]] <- test_file CRAN_incompabilities <- base::rbind(CRAN_incompabilities, tmp) } } } if (base::nrow(CRAN_incompabilities) > 0) { print(CRAN_incompabilities) } testthat::expect_true(base::nrow(CRAN_incompabilities) == 0) }) testthat::test_that("T1.5 The use of 'options()' is immediately preemptively reverted.", { test_files <- .get_visR_files(functions = TRUE, tests = TRUE, documentation = TRUE, vignettes = TRUE) exceptions <- list("Time_to_event_analysis.Rmd", "CDISC_ADaM.Rmd") exceptions_collapsed <- paste(exceptions, collapse = "|") CRAN_incompabilities <- data.frame() for (test_file in test_files) { if (sum(grepl(exceptions_collapsed, test_file)) == 0) { hits <- base::grep("^options\\(", base::readLines(test_file, warn = FALSE)) if (length(hits) > 0) { tmp <- data.frame("line" = hits) tmp[["file"]] <- test_file CRAN_incompabilities <- base::rbind(CRAN_incompabilities, tmp) } } } if (base::nrow(CRAN_incompabilities) > 0) { print(CRAN_incompabilities) } testthat::expect_true(base::nrow(CRAN_incompabilities) == 0) })
context("test_precomputed.R") muffled_chol = function(x, ...) withCallingHandlers(chol(x, ...), warning = function(w) { if (grepl("the matrix is either rank-deficient or indefinite", w$message)) invokeRestart("muffleWarning") } ) test_that("Precomputed precision matrix agrees with regular computations for logliklihood", { skip("Cannot test it due to numerical differences between chol in armadillo and R ...") set.seed(1) simdata = simple_sims(500,5,1) data = mash_set_data(simdata$Bhat, simdata$Shat, alpha = 0) U.c = cov_canonical(data) grid = autoselect_grid(data,sqrt(2)) Ulist = normalize_Ulist(U.c) xUlist = expand_cov(Ulist,grid,TRUE) loglik1 = calc_lik_rcpp(t(data$Bhat),t(data$Shat),data$V, matrix(0,0,0), simplify2array(xUlist),F,T)$data svs = data$Shat[1,] * t(data$V * data$Shat[1,]) sigma_rooti = list() for (i in 1:length(xUlist)) sigma_rooti[[i]] = backsolve(muffled_chol(svs + xUlist[[i]], pivot=T), diag(nrow(svs))) loglik2 = calc_lik_common_rcpp(t(data$Bhat), simplify2array(sigma_rooti), F)$data expect_equal(loglik1, loglik2, tolerance = 1e-4) })
library(janitor) context("remove empty rows or columns") dat <- data.frame( a = c(NA, NA, 1), b = c(NA, 1, NA), c = c(NA, NA, NA) ) test_that("empty rows are removed", { expect_equal(remove_empty(dat, "rows"), dat[2:3, ]) }) test_that("empty cols are removed", { expect_equal(remove_empty(dat, "cols"), dat[, 1:2]) }) test_that("bad argument to which throws error", { expect_error(mtcars %>% remove_empty("blargh"), paste0('"which" must be one of "rows", "cols", or c("rows", "cols")'), fixed = TRUE ) }) test_that("missing argument to which defaults to both, printing a message", { expect_message(dat %>% remove_empty(), "value for \"which\" not specified, defaulting to c(\"rows\", \"cols\")", fixed = TRUE ) expect_equal(dat %>% remove_empty, dat %>% remove_empty(c("rows", "cols"))) }) test_that("missing data.frame input throws its error before messages about 'which' arg", { expect_error(remove_empty(), "argument \"dat\" is missing, with no default", fixed = TRUE) }) test_that("remove_empty leaves matrices as matrices", { mat <- matrix(c(NA, NA, NA, rep(0, 3)), ncol = 2, byrow = TRUE) expect_equal(remove_empty(mat), matrix(c(NA, rep(0, 3)), ncol=2), info="remove_empty with a matrix returns a matrix") }) test_that("remove_empty leaves single-column results as the original class", { mat <- matrix(c(NA, NA, NA, 0), ncol = 2, byrow = FALSE) expect_equal(remove_empty(mat), matrix(0, ncol=1), info="remove_empty with a matrix that should return a single row and column still returns a matrix") df <- data.frame(A=NA, B=c(NA, 0)) expect_equal(remove_empty(df), data.frame(B=0, row.names=2L), info="remove_empty with a data.frame that should return a single row and column still returns a data.frame") }) test_that("remove_empty single-column input results as the original class", { mat <- matrix(c(NA, NA, NA, 0), ncol = 1, byrow = FALSE) expect_equal(remove_empty(mat), matrix(0, ncol=1), info="remove_empty with a matrix that should return a single row and column still returns a matrix") df <- data.frame(B=c(NA, 0)) expect_equal(remove_empty(df), data.frame(B=0, row.names=2L), info="remove_empty with a data.frame that should return a single row and column still returns a data.frame") }) test_that("remove_constant", { expect_equal( remove_constant(data.frame(A=1:2, B=1:2)), data.frame(A=1:2, B=1:2), info="Everything kept." ) expect_equal( remove_constant(data.frame(A=c(1, 1), B=c(2, 2))), data.frame(A=1:2)[,-1], info="All rows are kept, all columns are removed." ) expect_equal( remove_constant(data.frame(A=c(1, 1), B=c(2, 3))), data.frame(B=2:3), info="One column kept (not accidentally turned into a vector)" ) expect_equal( remove_constant(data.frame(A=NA, B=1:2)), data.frame(B=1:2), info="NA is dropped" ) expect_equal( remove_constant(data.frame(A=NA, B=c(NA, 1), C=c(1, NA), D=c(1, 1))), data.frame(B=c(NA, 1), C=c(1, NA)), info="NA with other values is kept" ) expect_equal( remove_constant(data.frame(A=NA, B=c(NA, 1, 2), C=c(1, 2, NA), D=c(1, 1, 1), E=c(1, NA, NA), F=c(NA, 1, 1), G=c(1, NA, 1)), na.rm=FALSE), data.frame(B=c(NA, 1, 2), C=c(1, 2, NA), E=c(1, NA, NA), F=c(NA, 1, 1), G=c(1, NA, 1)), info="NA with other values is kept without na.rm" ) expect_equal( remove_constant(data.frame(A=NA, B=c(NA, 1, 2), C=c(1, 2, NA), D=c(1, 1, 1), E=c(1, NA, NA), F=c(NA, 1, 1), G=c(1, NA, 1)), na.rm=TRUE), data.frame(B=c(NA, 1, 2), C=c(1, 2, NA)), info="NA with other values is kept with na.rm" ) expect_equal( remove_constant(tibble(A=NA, B=c(NA, 1, 2), C=1)), tibble(B=c(NA, 1, 2)), info="tibbles are correctly handled" ) }) test_that("Messages are accurate with remove_empty and remove_constant", { expect_message( remove_empty(data.frame(A=NA, B=1), which="cols", quiet=FALSE), regexp="Removing 1 empty columns of 2 columns total (Removed: A).", fixed=TRUE ) expect_message( remove_empty(data.frame(A=NA, B=1, C=NA), which="cols", quiet=FALSE), regexp="Removing 2 empty columns of 3 columns total (Removed: A, C).", fixed=TRUE ) expect_message( remove_empty(data.frame(A=NA, B=c(1, NA)), which="rows", quiet=FALSE), regexp="Removing 1 empty rows of 2 rows total (50%).", fixed=TRUE ) expect_message( remove_empty(matrix(c(NA, NA, 1, NA), nrow=2), which="cols", quiet=FALSE), regexp="Removing 1 empty columns of 2 columns total (50%).", fixed=TRUE ) expect_message( remove_constant(matrix(c(NA, NA, 1, NA), nrow=2), quiet=FALSE), regexp="Removing 1 constant columns of 2 columns total (50%).", fixed=TRUE, info="Unnamed, constant columns" ) expect_silent( remove_empty(data.frame(A=NA, B=1), which="cols", quiet=TRUE) ) expect_silent( remove_empty(data.frame(A=NA, B=c(1, NA)), which="rows", quiet=TRUE) ) expect_message( remove_constant(mtcars, quiet = FALSE), regexp="No constant columns to remove.", fixed=TRUE, info="No constant columns to remove" ) expect_message( remove_empty(mtcars, quiet = FALSE), regexp="No empty columns to remove.", fixed=TRUE, info="No empty columns to remove" ) })
NULL sw_tidy.nnetar <- function(x, ...) { terms <- c("m", "p", "P", "size") estimates <- c(x$m, x$p, x$P, x$size) ret <- tibble::tibble(term = terms, estimate = estimates) return(ret) } sw_glance.nnetar <- function(x, ...) { ret_1 <- tibble::tibble(model.desc = x$method) ret_2 <- tibble::tibble(sigma = sqrt(mean((x$residuals)^2, na.rm = TRUE)), logLik = NA, AIC = NA, BIC = NA) ret_3 <- tibble::as_tibble(forecast::accuracy(x)) ret <- dplyr::bind_cols(ret_1, ret_2, ret_3) return(ret) } sw_augment.nnetar <- function(x, data = NULL, timetk_idx = FALSE, rename_index = "index", ...) { if (timetk_idx) { if (!has_timetk_idx(x)) { warning("Object has no timetk index. Using default index.") timetk_idx = FALSE } } ret <- tk_tbl(cbind(.actual = x$x, .fitted = x$fitted, .resid = x$residuals), rename_index = rename_index, silent = TRUE) if (timetk_idx) { idx <- tk_index(x, timetk_idx = TRUE) ret[, rename_index] <- idx } ret <- sw_augment_columns(ret, data, rename_index, timetk_idx) return(ret) }
msk.fish.2004.create <- function(language="English",dictionaries=NA,col="black") { dict <- ecoval.dict(language,dictionaries) pnt2val <- function(p,s=4) { return(approx(x = c(0.0,1.5,5.5,9.5,13.5,16)/(16/s), y = c(1.0,0.8,0.6,0.4,0.2,0.0), xout = p)$y) } comb <- data.frame(spec_div=c(ecoval.translate("L_fish_species_class_natural",dict), ecoval.translate("L_fish_species_class_modified",dict), ecoval.translate("L_fish_species_class_atypical",dict))) colnames(comb) <- ecoval.translate("A_fish_species_class",dict) species <- utility.endnode.discrete.create( name.node = ecoval.translate("N_fish_species",dict), attrib.levels = comb, u = c(pnt2val(0,2), pnt2val(1,2), pnt2val(2,2)), required = FALSE, utility = FALSE, col = col) comb <- data.frame(dom_spe=c(ecoval.translate("L_fish_dominance_class_typical",dict), ecoval.translate("L_fish_dominance_class_tolerant",dict), ecoval.translate("L_fish_dominance_class_atypical",dict))) colnames(comb) <- ecoval.translate("A_fish_dominance_class",dict) dominance <- utility.endnode.discrete.create( name.node = ecoval.translate("N_fish_dominance",dict), attrib.levels = comb, u = c(pnt2val(0,2), pnt2val(1,2), pnt2val(2,2)), required = FALSE, utility = FALSE, col = col) popstrucind_popstrucbt_agecoh <- utility.endnode.intpol1d.create( name.node = ecoval.translate("N_fish_popstruct_trout_agestructure",dict), name.attrib = ecoval.translate("A_fish_popstruct_trout_ratiozeroplustoolder",dict), range = c(0,10), x = c(0,0.4,0.8,1.2,1.59,2.5,10), u = c(pnt2val(4), pnt2val(3.5), pnt2val(2.5), pnt2val(1.5), pnt2val(0.5), pnt2val(0), pnt2val(0)), required = FALSE, utility = FALSE, col = col) popstrucind_popstrucbt_0plusdens_pla <- utility.endnode.intpol1d.create( name.node = ecoval.translate("N_fish_popstruct_trout_zeroplusdensity_plateau",dict), name.attrib = ecoval.translate("A_fish_popstruct_trout_zeroplusdensity_perha",dict), range = c(0,3500), x = c(0,250,1000,1500,2500,3500), u = c(pnt2val(4), pnt2val(3.5), pnt2val(2.5), pnt2val(1.5), pnt2val(0.5), pnt2val(0)), required = FALSE, utility = FALSE, col = col) popstrucind_popstrucbt_0plusdens_ju <- utility.endnode.intpol1d.create( name.node = ecoval.translate("N_fish_popstruct_trout_zeroplusdensity_jura",dict), name.attrib = ecoval.translate("A_fish_popstruct_trout_zeroplusdensity_perha",dict), range = c(0,3500), x = c(0,250,1000,1500,2500,3500), u = c(pnt2val(4), pnt2val(3.5), pnt2val(2.5), pnt2val(1.5), pnt2val(0.5), pnt2val(0)), required = FALSE, utility = FALSE, col = col) popstrucind_popstrucbt_0plusdens_preal <- utility.endnode.intpol1d.create( name.node = ecoval.translate("N_fish_popstruct_trout_zeroplusdensity_prealps",dict), name.attrib = ecoval.translate("A_fish_popstruct_trout_zeroplusdensity_perha",dict), range = c(0,3000), x = c(0,250,500,1000,2000,3000), u = c(pnt2val(4), pnt2val(3.5), pnt2val(2.5), pnt2val(1.5), pnt2val(0.5), pnt2val(0)), required = FALSE, utility = FALSE, col = col) popstrucind_popstrucbt_0plusdens_al <- utility.endnode.intpol1d.create( name.node = ecoval.translate("N_fish_popstruct_trout_zeroplusdensity_alps",dict), name.attrib = ecoval.translate("A_fish_popstruct_trout_zeroplusdensity_perha",dict), range = c(0,500), x = c(0,100,200,300,400,500), u = c(pnt2val(4), pnt2val(3.5), pnt2val(2.5), pnt2val(1.5), pnt2val(0.5), pnt2val(0)), required = FALSE, utility = FALSE, col = col) comb <- data.frame(c(ecoval.translate("L_region_class_swissplateau",dict), ecoval.translate("L_region_class_swissjura",dict), ecoval.translate("L_region_class_swissprealps",dict), ecoval.translate("L_region_class_swissalps",dict))) colnames(comb) <- ecoval.translate("A_region_class",dict) popstrucind_popstrucbt_0plusdens <- utility.endnode.cond.create( name.node = ecoval.translate("N_fish_popstruct_trout_zeroplusdensity",dict), attrib.levels = comb, nodes = list(popstrucind_popstrucbt_0plusdens_pla, popstrucind_popstrucbt_0plusdens_ju, popstrucind_popstrucbt_0plusdens_preal, popstrucind_popstrucbt_0plusdens_al), required = FALSE, utility = FALSE, col = col) comb <- data.frame(c(ecoval.translate("L_fish_popstruct_keyspecies2_class_present",dict), ecoval.translate("L_fish_popstruct_keyspecies2_class_notpresent",dict))) colnames(comb) <- ecoval.translate("A_fish_popstruct_keyspecies2_class",dict) popstrucind_popstrucind2 <- utility.endnode.discrete.create( name.node = ecoval.translate("N_fish_popstruct_keyspecies2",dict), attrib.levels = comb, u = c(1,0), required = FALSE, utility = FALSE, col = col) comb <- data.frame(c(ecoval.translate("L_fish_popstruct_keyspecies3_class_present",dict), ecoval.translate("L_fish_popstruct_keyspecies3_class_notpresent",dict))) colnames(comb) <- ecoval.translate("A_fish_popstruct_keyspecies3_class",dict) popstrucind_popstrucind3 <- utility.endnode.discrete.create( name.node = ecoval.translate("N_fish_popstruct_keyspecies3",dict), attrib.levels = comb, u = c(1,0), required = FALSE, utility = FALSE, col = col) comb <- data.frame(c(ecoval.translate("L_fish_popstruct_keyspecies4_class_present",dict), ecoval.translate("L_fish_popstruct_keyspecies4_class_notpresent",dict))) colnames(comb) <- ecoval.translate("A_fish_popstruct_keyspecies4_class",dict) popstrucind_popstrucind4 <- utility.endnode.discrete.create( name.node = ecoval.translate("N_fish_popstruct_keyspecies4",dict), attrib.levels = comb, u = c(1,0), required = FALSE, utility = FALSE, col = col) comb <- data.frame(c(ecoval.translate("L_fish_popstruct_keyspecies5_class_present",dict), ecoval.translate("L_fish_popstruct_keyspecies5_class_notpresent",dict))) colnames(comb) <- ecoval.translate("A_fish_popstruct_keyspecies5_class",dict) popstrucind_popstrucind5 <- utility.endnode.discrete.create( name.node = ecoval.translate("N_fish_popstruct_keyspecies5",dict), attrib.levels = comb, u = c(1,0), required = FALSE, utility = FALSE, col = col) denskeysp_densbt_pla <- utility.endnode.intpol1d.create( name.node = ecoval.translate("N_fish_trout_density_plateau",dict), name.attrib = ecoval.translate("A_fish_trout_density_perha",dict), range = c(0,3750), x = c(0,1000,2500,3750), u = c(pnt2val(4), pnt2val(3), pnt2val(1), pnt2val(0)), required = FALSE, utility = FALSE, col = col) denskeysp_densbt_ju <- utility.endnode.intpol1d.create( name.node = ecoval.translate("N_fish_trout_density_jura",dict), name.attrib = ecoval.translate("A_fish_trout_density_perha",dict), range = c(0,5250), x = c(0,1000,3500,5250), u = c(pnt2val(4), pnt2val(3), pnt2val(1), pnt2val(0)), required = FALSE, utility = FALSE, col = col) denskeysp_densbt_preal <- utility.endnode.intpol1d.create( name.node = ecoval.translate("N_fish_trout_density_prealps",dict), name.attrib = ecoval.translate("A_fish_trout_density_perha",dict), range = c(0,3000), x = c(0,500,2000,3000), u = c(pnt2val(4), pnt2val(3), pnt2val(1), pnt2val(0)), required = FALSE, utility = FALSE, col = col) denskeysp_densbt_al <- utility.endnode.intpol1d.create( name.node = ecoval.translate("N_fish_trout_density_alps",dict), name.attrib = ecoval.translate("A_fish_trout_density_perha",dict), range = c(0,750), x = c(0,200,500,750), u = c(pnt2val(4), pnt2val(3), pnt2val(1), pnt2val(0)), required = FALSE, utility = FALSE, col = col) comb <- data.frame(c(ecoval.translate("L_region_class_swissplateau",dict), ecoval.translate("L_region_class_swissjura",dict), ecoval.translate("L_region_class_swissprealps",dict), ecoval.translate("L_region_class_swissalps",dict))) colnames(comb) <- ecoval.translate("A_region_class",dict) denskeysp_densbt <- utility.endnode.cond.create( name.node = ecoval.translate("N_fish_trout_density",dict), attrib.levels = comb, nodes = list(denskeysp_densbt_pla, denskeysp_densbt_ju, denskeysp_densbt_preal, denskeysp_densbt_al), required = FALSE, utility = FALSE, col = col) comb <- data.frame(c(ecoval.translate("L_fish_density_keyspecies2_class_high",dict), ecoval.translate("L_fish_density_keyspecies2_class_moderate",dict), ecoval.translate("L_fish_density_keyspecies2_class_low",dict))) colnames(comb) <- ecoval.translate("A_fish_density_keyspecies2_class",dict) denskeysp_denskeysp2 <- utility.endnode.discrete.create( name.node = ecoval.translate("N_fish_density_keyspecies2",dict), attrib.levels = comb, u = c(pnt2val(0), pnt2val(2), pnt2val(4)), required = FALSE, utility = FALSE, col = col) comb <- data.frame(c(ecoval.translate("L_fish_density_keyspecies3_class_high",dict), ecoval.translate("L_fish_density_keyspecies3_class_moderate",dict), ecoval.translate("L_fish_density_keyspecies3_class_low",dict))) colnames(comb) <- ecoval.translate("A_fish_density_keyspecies3_class",dict) denskeysp_denskeysp3 <- utility.endnode.discrete.create( name.node = ecoval.translate("N_fish_density_keyspecies3",dict), attrib.levels = comb, u = c(pnt2val(0), pnt2val(2), pnt2val(4)), required = FALSE, utility = FALSE, col = col) comb <- data.frame(c(ecoval.translate("L_fish_density_keyspecies4_class_high",dict), ecoval.translate("L_fish_density_keyspecies4_class_moderate",dict), ecoval.translate("L_fish_density_keyspecies4_class_low",dict))) colnames(comb) <- ecoval.translate("A_fish_density_keyspecies4_class",dict) denskeysp_denskeysp4 <- utility.endnode.discrete.create( name.node = ecoval.translate("N_fish_density_keyspecies4",dict), attrib.levels = comb, u = c(pnt2val(0), pnt2val(2), pnt2val(4)), required = FALSE, utility = FALSE, col = col) comb <- data.frame(c(ecoval.translate("L_fish_density_keyspecies5_class_high",dict), ecoval.translate("L_fish_density_keyspecies5_class_moderate",dict), ecoval.translate("L_fish_density_keyspecies5_class_low",dict))) colnames(comb) <- ecoval.translate("A_fish_density_keyspecies5_class",dict) denskeysp_denskeysp5 <- utility.endnode.discrete.create( name.node = ecoval.translate("N_fish_density_keyspecies5",dict), attrib.levels = comb, u = c(pnt2val(0), pnt2val(2), pnt2val(4)), required = FALSE, utility = FALSE, col = col) deform_anom <- utility.endnode.intpol1d.create( name.node = ecoval.translate("N_fish_anomalies",dict), name.attrib = ecoval.translate("A_fish_anomalies_fraction",dict), range = c(0,50), x = c(0,1,5,50), u = c(pnt2val(0), pnt2val(1), pnt2val(3), pnt2val(4)), required = FALSE, utility = FALSE, col = col) specdom <- utility.aggregation.create( name.node = ecoval.translate("N_fish_communitystructure",dict), nodes = list(species, dominance), name.fun = "utility.aggregate.add", par = c(1,1), required = FALSE, col = col) popstrucind_popstrucbt <- utility.aggregation.create( name.node = ecoval.translate("N_fish_popstruct_trout",dict), nodes = list(popstrucind_popstrucbt_agecoh, popstrucind_popstrucbt_0plusdens), name.fun = "utility.aggregate.min", par = c(1,1), required = FALSE, col = col) populationstructure <- utility.aggregation.create( name.node = ecoval.translate("N_fish_popstruct",dict), nodes = list(popstrucind_popstrucbt, popstrucind_popstrucind2, popstrucind_popstrucind3, popstrucind_popstrucind4, popstrucind_popstrucind5), name.fun = "utility.aggregate.add", par = c(1,1,1,1,1), required = FALSE, col = col) denskeysp <- utility.aggregation.create( name.node = ecoval.translate("N_fish_density",dict), nodes = list(denskeysp_densbt, denskeysp_denskeysp2, denskeysp_denskeysp3, denskeysp_denskeysp4, denskeysp_denskeysp5), name.fun = "utility.aggregate.add", par = c(1,1,1,1,1), required = FALSE, col = col) fish <- utility.aggregation.create( name.node = ecoval.translate("N_fish",dict), nodes = list(specdom,populationstructure,denskeysp,deform_anom), name.fun = "utility.aggregate.add", par = c(1,1,1,1), required = FALSE, col = col) return(fish) }
tritomat <- function(dmat,n) { out <- matrix(0,n,n) out[lower.tri(out)] <- dmat out <- t(out) out[lower.tri(out)] <- dmat t(out) }
calc.loglik.a <- function(a, y, mu, sf) { n <- length(y) if (length(mu) == 1) { mu <- rep(mu, n) } if (length(sf) == 1) { sf <- rep(sf, n) } func1 <- n/a*log(1/a) func2 <- -sum(1/a*log(mu)) func3 <- -n*lgamma(1/a) func4 <- sum(lgamma(y+1/a)) func5 <- -sum((y+1/a)*log(sf+1/(a*mu))) return(-sum(func1, func2, func3, func4, func5)) } calc.loglik.b <- function(b, y, mu, sf) { n <- length(y) if (length(mu) == 1) { mu <- rep(mu, n) } if (length(sf) == 1) { sf <- rep(sf, n) } func1 <- sum(mu/b*log(1/b)) func2 <- -sum(lgamma(mu/b)) func3 <- sum(lgamma(y+mu/b)) func4 <- -sum((y+mu/b)*log(sf+1/b)) return(-sum(func1, func2, func3, func4)) } calc.loglik.k <- function(k, y, mu, sf) { n <- length(y) if (length(mu) == 1) { mu <- rep(mu, n) } if (length(sf) == 1) { sf <- rep(sf, n) } func3 <- sum(mu^2*log(mu)/k) func4 <- -sum(mu^2*log(k)/k) func5 <- -sum(lgamma(mu^2/k)) func6 <- sum(lgamma(y+mu^2/k)) func7 <- -sum((y+mu^2/k)*log(sf+mu/k)) return(-sum(func3, func4, func5, func6, func7)) }
useShinydashboard <- function() { if (!requireNamespace(package = "shinydashboard")) message("Package 'shinydashboard' is required to run this function") deps <- findDependencies(shinydashboard::dashboardPage( header = shinydashboard::dashboardHeader(), sidebar = shinydashboard::dashboardSidebar(), body = shinydashboard::dashboardBody() )) attachDependencies(tags$div(class = "main-sidebar", style = "display: none;"), value = deps) }
imputeIPT <- function(data, pool=TRUE) { time <- data[,1] status <- data[,2] g1 <- data[,3] == 0 g2 <- !g1 tmax <- max(time) data1 <- data[g1,] data2 <- data[g2,] time1 <- data1[,1] status1 <- data1[,2] time2 <- data2[,1] status2 <- data2[,2] if(pool) { fitS1 <- survfit(Surv(time, status) ~ 1) fitS2 <- fitS1 } else { fitS1 <- survfit(Surv(time1, status1) ~ 1) fitS2 <- survfit(Surv(time2, status2) ~ 1) } fit1 <- survfit(Surv(time1, 1-status1) ~ 1) fit2 <- survfit(Surv(time2, 1-status2) ~ 1) T <- time C <- time delta <- as.logical(status) Tdelta <- delta vS1 <- !delta & g1 vS2 <- !delta & g2 if(any(vS1)) { tmp <- sampleFromCondKM(T[vS1], fitS1, tmax, 1) T[vS1] <- tmp[1,] Tdelta[vS1] <- tmp[2,] } if(any(vS2)) { tmp <- sampleFromCondKM(T[vS2], fitS2, tmax, 1) T[vS2] <- tmp[1,] Tdelta[vS2] <- tmp[2,] } v1 <- delta & g1 v2 <- delta & g2 if(any(v1)) C[v1] <- sampleFromCondKM(C[v1], fit1, tmax, 0)[1,] if(any(v2)) C[v2] <- sampleFromCondKM(C[v2], fit2, tmax, 0)[1,] matrix(c(T, C, data[,3], Tdelta), nrow=nrow(data), ncol=4) } permuteIPT <- function(data, pp, index=TRUE) { pT <- data[pp, 1] tmp <- matrix(c(pmin(pT, data[,2]), (pT <= data[,2]), data[,3]), nrow=nrow(data), ncol=3) tmp[,2] <- (pT <= data[,2]) * data[pp, 4] tmp }
Xt_siginv_X = function(tx, siginv, y = NULL){ D = dim(siginv)[1] I = dim(tx)[2] / D if(is.null(y)){ ret.mat = matrix(0, nrow = dim(tx)[1], ncol = dim(tx)[1]) for(i in 1:I){ ind.cur = (D * (i - 1) + 1) : (D*i) prod.cur = tx[,ind.cur] %*% siginv %*% t(tx[,ind.cur]) ret.mat = ret.mat + prod.cur } } else if(!is.null(y)){ ret.mat = matrix(0, nrow = dim(tx)[1], ncol = 1) for(i in 1:I){ ind.cur = (D * (i - 1) + 1) : (D*i) prod.cur = tx[,ind.cur] %*% siginv %*% y[ind.cur] ret.mat = ret.mat + prod.cur } } return(ret.mat) }
robspca <- function(X, k=NULL, alpha=1e-4, beta=1e-4, gamma=100, center=TRUE, scale=FALSE, max_iter=1000, tol=1e-5, verbose=TRUE) UseMethod("robspca") robspca.default <- function(X, k=NULL, alpha=1e-4, beta=1e-4, gamma=100, center=TRUE, scale=FALSE, max_iter=1000, tol=1e-5, verbose=TRUE) { X <- as.matrix(X) if (any(is.na(X))) { warning("Missing values are omitted: na.omit(X).") X <- stats::na.omit(X) } robspcaObj = list(loadings = NULL, transform = NULL, scores = NULL, eigenvalues = NULL, center = center, scale = scale) n <- nrow(X) p <- ncol(X) if(is.null(k)) k <- min(n,p) if(k > min(n,p)) k <- min(n,p) if(k<1) stop("Target rank is not valid!") if(center == TRUE) { robspcaObj$center <- colMeans(X) X <- sweep(X, MARGIN = 2, STATS = robspcaObj$center, FUN = "-", check.margin = TRUE) } else { robspcaObj$center <- FALSE } if(scale == TRUE) { robspcaObj$scale <- sqrt(colSums(X**2) / (n-1)) if(is.complex(robspcaObj$scale)) { robspcaObj$scale[Re(robspcaObj$scale) < 1e-8 ] <- 1+0i } else {robspcaObj$scale[robspcaObj$scale < 1e-8] <- 1} X <- sweep(X, MARGIN = 2, STATS = robspcaObj$scale, FUN = "/", check.margin = TRUE) } else { robspcaObj$scale <- FALSE } svd_init <- svd(X, nu = k, nv = k) Dmax <- svd_init$d[1] A <- svd_init$v[,1:k] B <- svd_init$v[,1:k] S = matrix(0, nrow = nrow(X), ncol = ncol(X)) alpha <- alpha * Dmax**2 beta <- beta * Dmax**2 nu <- 1.0 / (Dmax**2 + beta) kappa <- nu * alpha obj <- c() improvement <- Inf noi <- 1 while (noi <= max_iter && improvement > tol) { XS <- X - S XB <- X %*% B Z <- t(X - S) %*% (X %*% B) svd_update <- svd(Z) A <- svd_update$u %*% t(svd_update$v) R = XS - XB %*% t(A) grad <- t(X) %*% (R %*% A ) - beta * B B_temp <- B + nu * grad idxH <- which(B_temp > kappa) idxL <- which(B_temp <= -kappa) B = matrix(0, nrow = nrow(B_temp), ncol = ncol(B_temp)) B[idxH] <- B_temp[idxH] - kappa B[idxL] <- B_temp[idxL] + kappa R <- X - (X %*% B) %*% t(A) idxH <- which(R > gamma) idxL <- which(R <= -gamma) S = matrix(0, nrow = nrow(X), ncol = ncol(X)) S[idxH] <- R[idxH] - gamma S[idxL] <- R[idxL] + gamma obj <- c(obj, 0.5 * sum(R**2) + alpha * sum(abs(B)) + 0.5 * beta * sum(B**2) + gamma * sum(abs(S)) ) if(noi > 1){ improvement <- (obj[noi-1] - obj[noi]) / obj[noi] } if(verbose > 0 && noi > 1) { print(sprintf("Iteration: %4d, Objective: %1.5e, Relative improvement %1.5e", noi, obj[noi], improvement)) } noi <- noi + 1 } robspcaObj$loadings <- B robspcaObj$transform <- A robspcaObj$scores <- X %*% B robspcaObj$eigenvalues <- svd_update$d / (n - 1) robspcaObj$sparse <- S robspcaObj$objective <- obj robspcaObj$sdev <- sqrt( robspcaObj$eigenvalues ) robspcaObj$var <- sum( apply( Re(X) , 2, stats::var ) ) if(is.complex(X)) robspcaObj$var <- Re(robspcaObj$var + sum( apply( Im(X) , 2, stats::var ) )) class(robspcaObj) <- "robspca" return( robspcaObj ) } print.robspca <- function(x , ...) { cat("Standard deviations:\n") print(round(x$sdev, 3)) cat("\nEigenvalues:\n") print(round(x$eigenvalues, 3)) cat("\nSparse loadings:\n") print(round(x$loadings, 3)) } summary.robspca <- function( object , ... ) { variance = object$sdev**2 explained_variance_ratio = variance / object$var cum_explained_variance_ratio = cumsum( explained_variance_ratio ) x <- t(data.frame( var = round(variance, 3), sdev = round(object$sdev, 3), prob = round(explained_variance_ratio, 3), cum = round(cum_explained_variance_ratio, 3))) rownames( x ) <- c( 'Explained variance', 'Standard deviations', 'Proportion of variance', 'Cumulative proportion') colnames( x ) <- paste(rep('PC', length(object$sdev)), 1:length(object$sdev), sep = "") x <- as.matrix(x) return( x ) }
rm(list=ls()) sources <- c("costFunction.R","sigmoid.R","plotData.R", "plotDecisionBoundary.R","mapFeature.R", "predict.R") for (i in 1:length(sources)) { cat(paste("Loading ",sources[i],"\n")) source(sources[i]) } data <- read.table('ex2data1.txt',sep = ',') X <- data[,c(1,2)]; y <- data[,3] X <- as.matrix(X) cat(sprintf('Plotting data with + indicating (y = 1) examples and o indicating (y = 0) examples.\n')) plotData(X, y) cat(sprintf('\nProgram paused. Press enter to continue.\n')) m <- dim(X)[1] n <- dim(X)[2] X <- cbind(rep(1,m),X) initial_theta <- rep(0,n+1) cF <- costFunction(X, y)(initial_theta) cost <- costFunction(X, y)(initial_theta) grd <- grad(X,y)(initial_theta) cat(sprintf('Cost at initial theta (zeros): %f\n', cost)) cat(sprintf('Gradient at initial theta (zeros): \n')) cat(sprintf(' %f \n', grd)) cat(sprintf('\nProgram paused. Press enter to continue.\n')) line <- readLines(con = stdin(),1) optimRes <- optim(par = initial_theta, fn = costFunction(X,y), gr = grad(X,y), method="BFGS", control = list(maxit = 400)) theta <- optimRes$par cost <- optimRes$value cat(sprintf('Cost at theta found by optim: %f\n', cost)) cat(sprintf('theta: \n')) cat(sprintf(' %f \n', theta)) plotDecisionBoundary(theta, X, y) cat(sprintf('\nProgram paused. Press enter to continue.\n')) line <- readLines(con = stdin(),1) prob <- sigmoid(t(c(1,45,85)) %*% theta) cat(sprintf('For a student with scores 45 and 85, we predict an admission probability of\n %f\n', prob)) p <- predict(theta, X) cat(sprintf('Train Accuracy: %f\n', mean(p == y) * 100))
GRL <- function(level){ x <- NULL if(level==1){ x1 <- github.cssegisanddata.covid19(state = "Greenland", level = 2) x2 <- ourworldindata.org(id = "GRL") x <- full_join(x1, x2, by = "date") } return(x) }
setMethodS3("toFileListTree", "character", function(x, depth=-1, dirsFirst=TRUE, ...) { if (length(x) == 0 || depth == 0) return() pattern <- "^([^/\\]*[/\\])(.*)" heads <- gsub(pattern, "\\1", x) tails <- gsub(pattern, "\\2", x) isLeave <- (tails == x) if (sum(isLeave) > 0) { leaves <- heads[isLeave] class(leaves) <- "FileListTree" leaves <- list(leaves) names(leaves) <- "." heads <- heads[!isLeave] tails <- tails[!isLeave] } else { leaves <- NULL } uheads <- sort(unique(heads)) tailOutput <- vector("list", length(uheads)) names(tailOutput) <- uheads for (head in uheads) { idxs <- which(heads == head) tree <- toFileListTree(tails[idxs], depth=depth-1, dirsFirst=dirsFirst, ...) tailOutput[[head]] <- tree } if (dirsFirst) { output <- c(tailOutput, leaves) } else { output <- c(leaves, tailOutput) } class(output) <- "FileListTree" output }, private=TRUE) setMethodS3("pasteTree", "FileListTree", function(x, indent=" ", nodeStr=" ", childStr="+-", collapse=NULL, .totalIndent="", ...) { if (length(x) == 0) return() s <- c() if (!is.list(x)) { x <- paste(.totalIndent, childStr, x, sep="") s <- c(s, x) if (!is.null(collapse)) s <- paste(s, collapse=collapse) return(s) } .nextTotalIndent <- paste(indent, .totalIndent, sep="") names <- names(x) for (kk in seq_along(x)) { values <- x[[kk]] name <- names[kk] if (name != ".") s <- c(s, paste(.totalIndent, nodeStr, name, sep="")) s <- c(s, pasteTree(values, indent=indent, .totalIndent=.nextTotalIndent, ...)) } if (!is.null(collapse)) s <- paste(s, collapse=collapse) s }, private=TRUE) setMethodS3("cat", "FileListTree", function(x, collapse="\n", ...) { s <- pasteTree(x, ..., collapse=collapse) cat(s, collapse=collapse) invisible(s) }, private=TRUE)
context("Handling phases with a single observation.") set.seed(20210323) A1 <- rbinom(1, 15, 0.3) * 100 / 15 B1 <- rbinom(1, 15, 0.2) * 100 / 15 while (A1 == B1) B1 <- rbinom(1, 15, 0.2) * 100 / 15 A3 <- rbinom(3, 14:16, 0.3) * 100 / (14:16) while (B1 %in% A3) A3 <- rbinom(3, 14:16, 0.3) * 100 / (14:16) B3 <- rbinom(3, 14:16, 0.2) * 100 / (14:16) while (A1 %in% B3) B3 <- rbinom(3, 14:16, 0.2) * 100 / (14:16) test_that("calc_ES() works with single observation in baseline.", { expect_warning(calc_ES(A_data = A1, B_data = B3, improvement = "decrease", scale = "percentage", ES = c("LOR","LRRd","LRRi"))) expect_error(calc_ES(A_data = A1, B_data = B3, improvement = "decrease", scale = "percentage", ES = "SMD", warn = FALSE)) expect_warning(calc_ES(A_data = A1, B_data = B3, improvement = "decrease", scale = "percentage", ES = "SMD", std_dev = "pool")) NAP_Tau <- calc_ES(A_data = A1, B_data = B3, improvement = "decrease", ES = c("NAP","Tau"), confidence = NULL) expect_true(all(is.infinite(NAP_Tau$SE))) NOMs <- calc_ES(A_data = A1, B_data = B3, improvement = "decrease", ES = c("NAP","Tau","PND","PAND","PEM","IRD","Tau-U"), confidence = NULL, format = "wide") expect_equal(NOMs$NAP_Est, NOMs$PEM_Est) expect_equal(NOMs$NAP_Est, NOMs$PND_Est) expect_equal(NOMs$Tau_Est, NOMs$`Tau-U_Est`) }) test_that("calc_ES() works with single observation in treatment", { expect_warning(calc_ES(A_data = A3, B_data = B1, improvement = "decrease", scale = "percentage", ES = c("LOR","LRRd","LRRi"))) expect_warning(calc_ES(A_data = A3, B_data = B1, improvement = "decrease", scale = "percentage", ES = "SMD")) expect_warning(calc_ES(A_data = A3, B_data = B1, improvement = "decrease", scale = "percentage", ES = "SMD", std_dev = "pool")) NAP_Tau <- calc_ES(A_data = A3, B_data = B1, improvement = "decrease", ES = c("NAP","Tau"), confidence = NULL) expect_true(all(is.infinite(NAP_Tau$SE))) NOMs <- calc_ES(A_data = A1, B_data = B3, improvement = "decrease", ES = c("NAP","Tau","PND","PAND","PEM","IRD","Tau-U"), confidence = NULL, format = "wide") expect_equal(NOMs$NAP_Est, NOMs$PEM_Est) expect_equal(NOMs$NAP_Est, NOMs$PND_Est) expect_equal(NOMs$Tau_Est, NOMs$`Tau-U_Est`) }) test_that("calc_ES() works with single observation in each phase", { expect_warning(calc_ES(A_data = A1, B_data = B1, improvement = "decrease", scale = "percentage", ES = c("LOR","LRRd","LRRi"))) ratio_measures <- calc_ES(A_data = A1, B_data = B1, improvement = "decrease", scale = "percentage", ES = c("LOR","LRRd","LRRi"), warn = FALSE) expect_true(all(is.na(ratio_measures$Est))) expect_true(all(is.na(ratio_measures$SE))) expect_error(calc_ES(A_data = A1, B_data = B1, improvement = "decrease", scale = "percentage", ES = "SMD", warn = FALSE)) expect_error(calc_ES(A_data = A1, B_data = B1, improvement = "decrease", scale = "percentage", ES = "SMD", std_dev = "pool", warn = FALSE)) NAP_Tau <- calc_ES(A_data = A1, B_data = B1, improvement = "decrease", ES = c("NAP","Tau"), confidence = NULL) expect_true(all(is.infinite(NAP_Tau$SE))) NOMs <- calc_ES(A_data = A1, B_data = B1, improvement = "decrease", ES = c("NAP","Tau","PND","PAND","PEM","IRD","Tau-U"), confidence = NULL, format = "wide") expect_identical(NOMs$NAP_Est, NOMs$PEM_Est) expect_identical(NOMs$NAP_Est, NOMs$PND_Est) expect_equal(NOMs$Tau_Est, NOMs$`Tau-U_Est`) }) test_that("calc_ES() works with three observations in each phase.", { ES_SE <- calc_ES(A_data = A3, B_data = B3, improvement = "decrease", scale = "percentage", ES = c("LOR","LRRd","LRRi","SMD","NAP","Tau")) expect_identical(names(ES_SE), c("ES","Est","SE","CI_lower","CI_upper")) NOMs <- calc_ES(A_data = A3, B_data = B3, improvement = "decrease", ES = c("PND","PAND","PEM","IRD","Tau-U")) expect_identical(names(NOMs), c("ES","Est")) })
betadisperF <- function (d, group, type = c("median", "centroid"), bias.adjust = FALSE) { ordimedian<-function (ord, groups, display = "sites", label = FALSE, ...) { medfun <- function(x, ord) sum(sqrt(rowSums(sweep(ord, 2, x)^2)), na.rm = TRUE) dmedfun <- function(x, ord) { up <- -sweep(ord, 2, x) dn <- sqrt(rowSums(sweep(ord, 2, x)^2)) colSums(sweep(up, 1, dn, "/")) } pts <- scores(ord, display = display, ...) inds <- names(table(groups)) medians <- matrix(NA, nrow = length(inds), ncol = ncol(pts)) rownames(medians) <- inds colnames(medians) <- colnames(pts) for (i in inds) { X <- pts[groups == i, , drop = FALSE] if (NROW(X) > 0) medians[i, ] <- optim(apply(X, 2, median, na.rm = TRUE), fn = medfun, gr = dmedfun, ord = X, method = "BFGS")$par if (label) ordiArgAbsorber(medians[i, 1], medians[i, 2], label = i, FUN = text, ...) } invisible(medians) } ordiArgAbsorber<-function(..., shrink, origin, scaling, triangular, display, choices, const, FUN) match.fun(FUN)(...) "scores" <-function(x, ...) UseMethod("scores") "scores.default" <- function (x, choices, display = c("sites", "species"), ...) { display <- match.arg(display) att <- names(x) if (is.data.frame(x) && all(sapply(x, is.numeric))) x <- as.matrix(x) if (is.list(x) && display == "sites") { if ("points" %in% att) X <- x$points else if ("rproj" %in% att) X <- x$rproj else if ("x" %in% att) X <- x$x else if ("scores" %in% att) X <- x$scores else if ("sites" %in% att) X <- x$sites else if("li" %in% att) X <- x$li else if("l1" %in% att) X <- x$l1 else stop("Can't find scores") } else if (is.list(x) && display == "species") { if ("species" %in% att) X <- x$species else if ("cproj" %in% att) X <- x$cproj else if ("rotation" %in% att) X <- x$rotation else if ("loadings" %in% att) X <- x$loadings else if ("co" %in% att) X <- x$co else if ("c1" %in% att) X <- x$c1 else stop("Can't find scores") } else if (is.numeric(x)) { X <- as.matrix(x) } if (is.null(rownames(X))) { root <- substr(display, 1, 4) rownames(X) <- paste(root, 1:nrow(X), sep = "") } if (is.null(colnames(X))) colnames(X) <- paste("Dim", 1:ncol(X), sep = "") if (!missing(choices)) { choices <- choices[choices <= ncol(X)] X <- X[, choices, drop = FALSE] } X <- as.matrix(X) X } dblcen <- function(x, na.rm = TRUE) { cnt <- colMeans(x, na.rm = na.rm) x <- sweep(x, 2L, cnt, check.margin = FALSE) cnt <- rowMeans(x, na.rm = na.rm) sweep(x, 1L, cnt, check.margin = FALSE) } spatialMed <- function(vectors, group, pos) { axes <- seq_len(NCOL(vectors)) spMedPos <- ordimedian(vectors, group, choices = axes[pos]) spMedNeg <- ordimedian(vectors, group, choices = axes[!pos]) cbind(spMedPos, spMedNeg) } Resids <- function(x, c) { if (is.matrix(c)) d <- x - c else d <- sweep(x, 2, c) rowSums(d^2) } TOL <- 1e-07 if (!inherits(d, "dist")) stop("distances 'd' must be a 'dist' object") if (any(d < -TOL, na.rm = TRUE)) stop("dissimilarities 'd' must be non-negative") if (missing(type)) type <- "median" type <- match.arg(type) if (!is.factor(group)) { group <- as.factor(group) } else { group <- droplevels(group) } n <- attr(d, "Size") x <- matrix(0, ncol = n, nrow = n) x[row(x) > col(x)] <- d^2 labs <- attr(d, "Labels") if (any(gr.na <- is.na(group))) { group <- group[!gr.na] x <- x[!gr.na, !gr.na] n <- n - sum(gr.na) labs <- labs[!gr.na] warning("Missing observations due to 'group' removed.") } if (any(x.na <- apply(x, 1, function(x) any(is.na(x))))) { x <- x[!x.na, !x.na] group <- group[!x.na] n <- n - sum(x.na) labs <- labs[!x.na] warning("Missing observations due to 'd' removed.") } x <- x + t(x) x<- dblcen(x) e <- eigen(-x/2, symmetric = TRUE) vectors <- e$vectors eig <- e$values eig <- eig[(want <- abs(eig/eig[1]) > TOL)] vectors <- vectors[, want, drop = FALSE] %*% diag(sqrt(abs(eig)), nrow = length(eig)) pos <- eig > 0 centroids <- switch(type, centroid = apply(vectors, 2, function(x) tapply(x,group, mean)), median = spatialMed(vectors, group, pos)) if(is.matrix(centroids)==FALSE){ centroids<-t(as.matrix(centroids)) rownames(centroids)<-"YES"} dist.pos <- Resids(vectors[, pos, drop = FALSE], centroids[group, pos, drop = FALSE]) dist.neg <- 0 if (any(!pos)) dist.neg <- Resids(vectors[, !pos, drop = FALSE], centroids[group, !pos, drop = FALSE]) zij <- sqrt(abs(dist.pos - dist.neg)) if (bias.adjust) { n.group <- table(group) zij <- zij * sqrt(n.group[group]/(n.group[group] - 1)) } colnames(vectors) <- names(eig) <- paste("PCoA", seq_along(eig), sep = "") if (is.matrix(centroids)) colnames(centroids) <- names(eig) else names(centroids) <- names(eig) rownames(vectors) <- names(zij) <- labs retval <- list(eig = eig, vectors = vectors, distances = zij, group = group, centroids = centroids, call = match.call()) class(retval) <- "betadisper" attr(retval, "method") <- attr(d, "method") attr(retval, "type") <- type attr(retval, "bias.adjust") <- bias.adjust retval }
biascorrection <- function(experimental, calibration, samplelocusname, minmax = FALSE, correct_method = "best", selection_method = "SSE", type = 1, csvdir = paste0(tempdir(), "/csvdir/"), plotdir = paste0(tempdir(), "/plotdir/"), logfilename = paste0(tempdir(), "/log.txt"), plot_height = 5, plot_width = 7.5, plot_textsize = 16, seed = 1234, parallel = TRUE) { stopifnot( is.character(experimental), is.character(calibration), is.character(samplelocusname), is.logical(minmax), is.numeric(type), type == 1 || type == 2, is.character(correct_method), correct_method %in% c("best", "hyperbolic", "cubic", "b", "h", "c"), is.character(selection_method), selection_method %in% c("SSE", "RelError"), is.character(csvdir), is.character(plotdir), is.character(logfilename), is.numeric(plot_height), is.numeric(plot_width), is.numeric(plot_textsize), is.numeric(seed), is.logical(parallel) ) plotdir <- gsub("([[:alnum:]])$", "\\1/", plotdir) csvdir <- gsub("([[:alnum:]])$", "\\1/", csvdir) on_start(plotdir, csvdir, logfilename, parallel) rv <- list() rv$minmax <- minmax rv$selection_method <- selection_method rv$sample_locus_name <- handle_text_input(samplelocusname) if (type == 1) { rv$fileimport_experimental <- clean_dt( data.table::fread(experimental, header = T), "experimental", type = 1, logfilename = logfilename )[["dat"]] write_csv(table = rv$fileimport_experimental, filename = paste0(csvdir, "raw_experimental_data.csv")) cal_type_1 <- clean_dt(data.table::fread(calibration, header = T), "calibration", type = 1, logfilename = logfilename) rv$fileimport_calibration <- cal_type_1[["dat"]] write_csv(table = rv$fileimport_calibration, filename = paste0(csvdir, "raw_calibration_data.csv")) rv$vec_cal <- cal_type_1[["vec_cal"]] rv$aggregated_experimental <- aggregated_input( datatable = rv$fileimport_experimental, description = "experimental", vec_cal = rv$vec_cal, type = 1 ) write_csv(table = rv$aggregated_experimental, filename = paste0(csvdir, "aggregated_experimental_data.csv")) rv$aggregated_calibration <- aggregated_input( datatable = rv$fileimport_calibration, description = "calibration", vec_cal = rv$vec_cal ) write_csv(table = rv$aggregated_calibration, filename = paste0(csvdir, "aggregated_calibration_data.csv")) } else if (type == 2) { return(paste0("The correction of PCR measurement ", "biases of this type of data is not implemented yet.")) } else { return("ERROR. Please specify a valid type of data to correct (1 or 2).") } if (type == 1) { regression_results <- regression_utility( data = rv$fileimport_calibration, samplelocusname = rv$sample_locus_name, locus_id = NULL, rv = rv, mode = NULL, logfilename = logfilename, minmax = rv$minmax, seed = seed ) plotlist_reg <- regression_results[["plot_list"]] rv$result_list <- regression_results[["result_list"]] plotting_utility( data = rv$fileimport_calibration, plotlist_reg = plotlist_reg, type = 1, samplelocusname = rv$sample_locus_name, locus_id = NULL, rv = rv, mode = NULL, plotdir = plotdir, logfilename = logfilename, minmax = rv$minmax, plot_height = plot_height, plot_width = plot_width, plot_textsize = plot_textsize ) rv$reg_stats <- statistics_list(rv$result_list, minmax = rv$minmax) write_csv(table = rv$reg_stats, filename = paste0(csvdir, rv$sample_locus_name, "_regression_stats_", gsub("\\-", "", substr(Sys.time(), 1, 10)), "_", gsub("\\:", "", substr(Sys.time(), 12, 16)), ".csv") ) rv$choices_list <- rv$reg_stats[, c("Name"), with = F ][ , ("better_model") := 0 ] solved_eq_h <- solving_equations(datatable = rv$fileimport_calibration, regmethod = rv$choices_list, type = 1, rv = rv, mode = "corrected", logfilename = logfilename, minmax = rv$minmax) rv$fileimport_cal_corrected_h <- solved_eq_h[["results"]] colnames(rv$fileimport_cal_corrected_h) <- colnames( rv$fileimport_calibration ) write_csv(table = rv$fileimport_cal_corrected_h, filename = paste0(csvdir, rv$sample_locus_name, "_corrected_calibrations_h_", get_timestamp(), ".csv")) rv$substitutions_corrected_h <- solved_eq_h[["substitutions"]] if (nrow(rv$substitutions_corrected_h) > 0) { write_csv(table = rv$substitutions_corrected_h, filename = paste0(csvdir, rv$sample_locus_name, "_substituted_corrected_h_", get_timestamp(), ".csv")) } regression_results <- regression_utility( data = rv$fileimport_cal_corrected_h, samplelocusname = rv$sample_locus_name, rv = rv, mode = "corrected", logfilename = logfilename, minmax = rv$minmax, seed = seed ) plotlist_reg <- regression_results[["plot_list"]] rv$result_list_hyperbolic <- regression_results[["result_list"]] plotting_utility( data = rv$fileimport_cal_corrected_h, plotlist_reg = plotlist_reg, type = 1, samplelocusname = rv$sample_locus_name, locus_id = NULL, rv = rv, mode = "corrected_h", plotdir = plotdir, logfilename = logfilename, minmax = rv$minmax, plot_height = plot_height, plot_width = plot_width, plot_textsize = plot_textsize ) rv$reg_stats_corrected_h <- statistics_list( resultlist = rv$result_list_hyperbolic, minmax = rv$minmax ) write_csv(table = rv$reg_stats_corrected_h, filename = paste0(csvdir, rv$sample_locus_name, "_corrected_regression_stats_h_", gsub("\\-", "", substr(Sys.time(), 1, 10)), "_", gsub("\\:", "", substr(Sys.time(), 12, 16)), ".csv") ) createbarerrorplots( statstable_pre = rv$reg_stats, statstable_post = rv$reg_stats_corrected_h, rv = rv, type = 1, locus_id = NULL, plotdir = plotdir, logfilename = logfilename, mode = "corrected_h", plot_height = plot_height, plot_width = plot_width, plot_textsize = plot_textsize ) rv$choices_list <- rv$reg_stats[, c("Name"), with = F ][ , ("better_model") := 1 ] solved_eq_c <- solving_equations(datatable = rv$fileimport_calibration, regmethod = rv$choices_list, type = 1, rv = rv, mode = "corrected", logfilename = logfilename, minmax = rv$minmax) rv$fileimport_cal_corrected_c <- solved_eq_c[["results"]] colnames(rv$fileimport_cal_corrected_c) <- colnames( rv$fileimport_calibration ) write_csv(table = rv$fileimport_cal_corrected_c, filename = paste0(csvdir, rv$sample_locus_name, "_corrected_calibrations_c_", get_timestamp(), ".csv")) rv$substitutions_corrected_c <- solved_eq_c[["substitutions"]] if (nrow(rv$substitutions_corrected_c) > 0) { write_csv(table = rv$substitutions_corrected_c, filename = paste0(csvdir, rv$sample_locus_name, "_substituted_corrected_c_", get_timestamp(), ".csv") ) } regression_results <- regression_utility( data = rv$fileimport_cal_corrected_c, samplelocusname = rv$sample_locus_name, rv = rv, mode = "corrected", logfilename = logfilename, minmax = rv$minmax, seed = seed ) plotlist_reg <- regression_results[["plot_list"]] rv$result_list_cubic <- regression_results[["result_list"]] plotting_utility( data = rv$fileimport_experimental_corrected_c, plotlist_reg = plotlist_reg, type = 1, samplelocusname = rv$sample_locus_name, locus_id = NULL, rv = rv, mode = "corrected_c", plotdir = plotdir, logfilename = logfilename, minmax = rv$minmax, plot_height = plot_height, plot_width = plot_width, plot_textsize = plot_textsize ) rv$reg_stats_corrected_c <- statistics_list( resultlist = rv$result_list_cubic, minmax = rv$minmax ) write_csv(table = rv$reg_stats_corrected_c, filename = paste0(csvdir, rv$sample_locus_name, "_corrected_regression_stats_c_", gsub("\\-", "", substr(Sys.time(), 1, 10)), "_", gsub("\\:", "", substr(Sys.time(), 12, 16)), ".csv") ) createbarerrorplots( statstable_pre = rv$reg_stats, statstable_post = rv$reg_stats_corrected_c, rv = rv, locus_id = NULL, type = 1, plotdir = plotdir, logfilename = logfilename, mode = "corrected_c", plot_height = plot_height, plot_width = plot_width, plot_textsize = plot_textsize ) if (correct_method %in% c("best", "b")) { rv$choices_list <- better_model( statstable_pre = rv$reg_stats, statstable_post_hyperbolic = rv$reg_stats_corrected_h, statstable_post_cubic = rv$reg_stats_corrected_c, selection_method = rv$selection_method ) } else if (correct_method %in% c("hyperbolic", "h")) { rv$choices_list <- rv$reg_stats[, c("Name"), with = F ][ , ("better_model") := 0 ] } else if (correct_method %in% c("cubic", "c")) { rv$choices_list <- rv$reg_stats[, c("Name"), with = F ][ , ("better_model") := 1 ] } solved_eq <- solving_equations( datatable = rv$fileimport_experimental, regmethod = rv$choices_list, mode = NULL, type = 1, rv = rv, logfilename = logfilename, minmax = rv$minmax ) rv$final_results <- solved_eq[["results"]] write_csv(table = rv$final_results, filename = paste0(csvdir, rv$sample_locus_name, "_corrected_values_", get_timestamp(), ".csv")) rv$substitutions <- solved_eq[["substitutions"]] if (nrow(rv$substitutions) > 0) { write_csv(table = rv$substitutions, filename = paste0(csvdir, rv$sample_locus_name, "_substituted_values_", get_timestamp(), ".csv")) } } return(rv) } NULL NULL NULL NULL NULL
"safety"
plot.growth_day<-function(x, type="PlantTranspiration", bySpecies = FALSE, xlim = NULL, ylim=NULL, xlab = NULL, ylab = NULL, ...) { GROWTH_TYPES = .getSubdailyGROWTHPlotTypes() PWB_TYPES = .getSubdailySPWBPlotTypes() type = match.arg(type,GROWTH_TYPES) if(type %in% PWB_TYPES) { plot.pwb_day(x, type, bySpecies, xlim, ylim, xlab, ylab,...) } CBInst = x$PlantCBInst if(type=="SugarLeaf") { OM = CBInst$SugarLeaf if(is.null(ylab)) ylab = .getYLab(type) return(.multiple_subday_dynamics(t(OM), ylab = ylab, ylim = ylim)) } } plot.spwb_day<-function(x, type="PlantTranspiration", bySpecies = FALSE, xlim = NULL, ylim=NULL, xlab = NULL, ylab = NULL, ...) { plot.pwb_day(x, type, bySpecies, xlim, ylim, xlab, ylab,...) } plot.pwb_day<-function(x, type="PlantTranspiration", bySpecies = FALSE, xlim = NULL, ylim=NULL, xlab = NULL, ylab = NULL, ...) { if(!("EnergyBalance" %in% names(x))) stop("Plotting function available for transpirationMode = 'Sperry' only.") EB = x$EnergyBalance Plants = x$Plants PlantsInst = x$PlantsInst SunlitLeavesInst = x$SunlitLeavesInst ShadeLeavesInst = x$ShadeLeavesInst type = match.arg(type,.getSubdailySPWBPlotTypes()) cohortnames = row.names(x$cohorts) timesteps = as.numeric(colnames(x$PlantsInst$LeafPsi)) if(is.null(xlab)) xlab = "Time step" if(type=="LeafPsiAverage") { OM = PlantsInst$LeafPsi if(bySpecies) { lai1 = tapply(Plants$LAI, x$cohorts$Name, sum, na.rm=T) OMlai = sweep(OM, 1, Plants$LAI, "*") m1 = apply(OMlai,2, tapply, x$cohorts$Name, sum, na.rm=T) OM = sweep(m1,1,lai1,"/") } if(is.null(ylab)) ylab = "Leaf water potential (MPa)" return(.multiple_subday_dynamics(t(OM), ylab = ylab, ylim = ylim)) } else if(type=="StemPsi") { OM = PlantsInst$StemPsi if(bySpecies) { lai1 = tapply(Plants$LAI, x$cohorts$Name, sum, na.rm=T) OMlai = sweep(OM, 1, Plants$LAI, "*") m1 = apply(OMlai,2, tapply, x$cohorts$Name, sum, na.rm=T) OM = sweep(m1,1,lai1,"/") } if(is.null(ylab)) ylab = "Stem water potential (MPa)" return(.multiple_subday_dynamics(t(OM), ylab = ylab, ylim = ylim)) } else if(type=="LeafSympPsi") { OM = PlantsInst$LeafSympPsi if(bySpecies) { lai1 = tapply(Plants$LAI, x$cohorts$Name, sum, na.rm=T) OMlai = sweep(OM, 1, Plants$LAI, "*") m1 = apply(OMlai,2, tapply, x$cohorts$Name, sum, na.rm=T) OM = sweep(m1,1,lai1,"/") } if(is.null(ylab)) ylab = "Leaf symplastic water potential (MPa)" return(.multiple_subday_dynamics(t(OM), ylab = ylab, ylim = ylim)) } else if(type=="StemSympPsi") { OM = PlantsInst$StemSympPsi if(bySpecies) { lai1 = tapply(Plants$LAI, x$cohorts$Name, sum, na.rm=T) OMlai = sweep(OM, 1, Plants$LAI, "*") m1 = apply(OMlai,2, tapply, x$cohorts$Name, sum, na.rm=T) OM = sweep(m1,1,lai1,"/") } if(is.null(ylab)) ylab = "Stem symplastic water potential (MPa)" return(.multiple_subday_dynamics(t(OM), ylab = ylab, ylim = ylim)) } else if(type=="RootPsi") { OM = PlantsInst$RootPsi if(bySpecies) { lai1 = tapply(Plants$LAI, x$cohorts$Name, sum, na.rm=T) OMlai = sweep(OM, 1, Plants$LAI, "*") m1 = apply(OMlai,2, tapply, x$cohorts$Name, sum, na.rm=T) OM = sweep(m1,1,lai1,"/") } if(is.null(ylab)) ylab = "Root crown water potential (MPa)" return(.multiple_subday_dynamics(t(OM), ylab = ylab, ylim = ylim)) } else if(type=="StemPLC") { OM = PlantsInst$StemPLC*100 if(bySpecies) { lai1 = tapply(Plants$LAI, x$cohorts$Name, sum, na.rm=T) OMlai = sweep(OM, 1, Plants$LAI, "*") m1 = apply(OMlai,2, tapply, x$cohorts$Name, sum, na.rm=T) OM = sweep(m1,1,lai1,"/") } if(is.null(ylab)) ylab = "Stem percent of conductance loss (%)" return(.multiple_subday_dynamics(t(OM), ylab = ylab, ylim = ylim)) } else if(type=="StemRWC") { OM = PlantsInst$StemRWC*100 if(bySpecies) { lai1 = tapply(Plants$LAI, x$cohorts$Name, sum, na.rm=T) OMlai = sweep(OM, 1, Plants$LAI, "*") m1 = apply(OMlai,2, tapply, x$cohorts$Name, sum, na.rm=T) OM = sweep(m1,1,lai1,"/") } if(is.null(ylab)) ylab = "Stem relative water content (%)" return(.multiple_subday_dynamics(t(OM), ylab = ylab, ylim = ylim)) } else if(type=="StemSympRWC") { OM = PlantsInst$StemSympRWC*100 if(bySpecies) { lai1 = tapply(Plants$LAI, x$cohorts$Name, sum, na.rm=T) OMlai = sweep(OM, 1, Plants$LAI, "*") m1 = apply(OMlai,2, tapply, x$cohorts$Name, sum, na.rm=T) OM = sweep(m1,1,lai1,"/") } if(is.null(ylab)) ylab = "Stem symplasm relative water content (%)" return(.multiple_subday_dynamics(t(OM), ylab = ylab, ylim = ylim)) } else if(type=="LeafRWC") { OM = PlantsInst$LeafRWC*100 if(bySpecies) { lai1 = tapply(Plants$LAI, x$cohorts$Name, sum, na.rm=T) OMlai = sweep(OM, 1, Plants$LAI, "*") m1 = apply(OMlai,2, tapply, x$cohorts$Name, sum, na.rm=T) OM = sweep(m1,1,lai1,"/") } if(is.null(ylab)) ylab = "Leaf relative water content (%)" return(.multiple_subday_dynamics(t(OM), ylab = ylab, ylim = ylim)) } else if(type=="LeafSympRWC") { OM = PlantsInst$LeafSympRWC*100 if(bySpecies) { lai1 = tapply(Plants$LAI, x$cohorts$Name, sum, na.rm=T) OMlai = sweep(OM, 1, Plants$LAI, "*") m1 = apply(OMlai,2, tapply, x$cohorts$Name, sum, na.rm=T) OM = sweep(m1,1,lai1,"/") } if(is.null(ylab)) ylab = "Leaf symplasm relative water content (%)" return(.multiple_subday_dynamics(t(OM), ylab = ylab, ylim = ylim)) } else if(type=="SoilPlantConductance") { OM = PlantsInst$dEdP if(bySpecies) { OM = apply(OM,2, tapply, x$cohorts$Name, sum, na.rm=T) } if(is.null(ylab)) ylab = expression(paste("Soil-plant conductance ",(mmol%.%m^{-2}%.%MPa^{-1}%.%s^{-1}))) return(.multiple_subday_dynamics(t(OM), ylab = ylab, ylim = ylim)) } else if(type=="PlantWaterBalance") { OM = PlantsInst$PWB if(bySpecies) { lai1 = tapply(Plants$LAI, x$cohorts$Name, sum, na.rm=T) OMlai = sweep(OM, 1, Plants$LAI, "*") m1 = apply(OMlai,2, tapply, x$cohorts$Name, sum, na.rm=T) OM = sweep(m1,1,lai1,"/") } if(is.null(ylab)) ylab = expression(paste("Extraction - transpiration (",L%.%m^{-2},")")) return(.multiple_subday_dynamics(t(OM), ylab = ylab, ylim = ylim)) } else if(type=="WaterBalancePerLeaf") { OM = PlantsInst$PWB if(bySpecies) { m1 = apply(OM,2, tapply, x$cohorts$Name, sum, na.rm=T) lai1 = tapply(Plants$LAI, x$cohorts$Name, sum, na.rm=T) OM = sweep(m1,1,lai1,"/") } else { OM = sweep(OM,1,Plants$LAI,"/") } if(is.null(ylab)) ylab = expression(paste("Extraction - transpiration per leaf area (",L%.%m^{-2},")")) return(.multiple_subday_dynamics(t(OM), ylab = ylab, ylim = ylim)) } else if(type=="PlantExtraction") { OM = x$ExtractionInst nlayers = nrow(OM) if(is.null(ylab)) ylab = expression(paste("Extraction from soil layers ",(L%.%m^{-2}))) return(.multiple_subday_dynamics(t(OM), ylab = ylab, ylim = ylim)) } else if(type=="PlantTranspiration") { OM = PlantsInst$E if(bySpecies) { OM = apply(OM,2, tapply, x$cohorts$Name, sum, na.rm=T) } if(is.null(ylab)) ylab = expression(paste("Plant transpiration ",(L%.%m^{-2}))) return(.multiple_subday_dynamics(t(OM), ylab = ylab, ylim = ylim)) } else if(type=="TranspirationPerLeaf") { OM = PlantsInst$E if(bySpecies) { m1 = apply(OM,2, tapply, x$cohorts$Name, sum, na.rm=T) lai1 = tapply(Plants$LAI, x$cohorts$Name, sum, na.rm=T) OM = sweep(m1,1,lai1,"/") } else { OM = sweep(OM,1,Plants$LAI,"/") } if(is.null(ylab)) ylab = expression(paste("Transpiration per leaf area ",(L%.%m^{-2}))) return(.multiple_subday_dynamics(t(OM), ylab = ylab, ylim = ylim)) } else if(type=="PlantGrossPhotosynthesis") { OM = PlantsInst$Ag if(bySpecies) { OM = apply(OM,2, tapply, x$cohorts$Name, sum, na.rm=T) } if(is.null(ylab)) ylab = expression(paste("Plant gross photosynthesis ",(gC%.%m^{-2}))) return(.multiple_subday_dynamics(t(OM), ylab = ylab, ylim = ylim)) } else if(type=="PlantNetPhotosynthesis") { OM = PlantsInst$An if(bySpecies) { OM = apply(OM,2, tapply, x$cohorts$Name, sum, na.rm=T) } if(is.null(ylab)) ylab = expression(paste("Plant net photosynthesis ",(gC%.%m^{-2}))) return(.multiple_subday_dynamics(t(OM), ylab = ylab, ylim = ylim)) } else if(type=="GrossPhotosynthesisPerLeaf") { OM = PlantsInst$Ag if(bySpecies) { m1 = apply(OM,2, tapply, x$cohorts$Name, sum, na.rm=T) lai1 = tapply(Plants$LAI, x$cohorts$Name, sum, na.rm=T) OM = sweep(m1,1,lai1,"/") } else { OM = sweep(OM,1,Plants$LAI,"/") } if(is.null(ylab)) ylab = expression(paste("Gross photosynthesis per leaf area ",(gC%.%m^{-2}))) return(.multiple_subday_dynamics(t(OM), ylab = ylab, ylim = ylim)) } else if(type=="NetPhotosynthesisPerLeaf") { OM = PlantsInst$An if(bySpecies) { m1 = apply(OM,2, tapply, x$cohorts$Name, sum, na.rm=T) lai1 = tapply(Plants$LAI, x$cohorts$Name, sum, na.rm=T) OM = sweep(m1,1,lai1,"/") } else { OM = sweep(OM,1,Plants$LAI,"/") } if(is.null(ylab)) ylab = expression(paste("Net photosynthesis per leaf area ",(gC%.%m^{-2}))) return(.multiple_subday_dynamics(t(OM), ylab = ylab, ylim = ylim)) } else if(type=="LeafTranspiration") { OM_SL = SunlitLeavesInst$E OM_SH = ShadeLeavesInst$E if(bySpecies) { lai1 = tapply(Plants$LAI, x$cohorts$Name, sum, na.rm=T) OMlai = sweep(OM_SL, 1, Plants$LAI, "*") m1 = apply(OMlai,2, tapply, x$cohorts$Name, sum, na.rm=T) OM_SL = sweep(m1,1,lai1,"/") OMlai = sweep(OM_SH, 1, Plants$LAI, "*") m1 = apply(OMlai,2, tapply, x$cohorts$Name, sum, na.rm=T) OM_SH = sweep(m1,1,lai1,"/") } if(is.null(ylab)) ylab=expression(paste("Leaf transpiration ",(mmol%.%m^{-2}%.%s^{-1}))) return(.multiple_subday_dynamics_sunlit_shade(t(OM_SL), t(OM_SH), ylab = ylab, ylim = ylim)) } else if(type=="LeafNetPhotosynthesis") { OM_SL = SunlitLeavesInst$An OM_SH = ShadeLeavesInst$An if(bySpecies) { lai1 = tapply(Plants$LAI, x$cohorts$Name, sum, na.rm=T) OMlai = sweep(OM_SL, 1, Plants$LAI, "*") m1 = apply(OMlai,2, tapply, x$cohorts$Name, sum, na.rm=T) OM_SL = sweep(m1,1,lai1,"/") OMlai = sweep(OM_SH, 1, Plants$LAI, "*") m1 = apply(OMlai,2, tapply, x$cohorts$Name, sum, na.rm=T) OM_SH = sweep(m1,1,lai1,"/") } if(is.null(ylab)) ylab=expression(paste("Leaf net photosynthesis ",(mu%.%mol%.%m^{-2}%.%s^{-1}))) return(.multiple_subday_dynamics_sunlit_shade(t(OM_SL), t(OM_SH), ylab = ylab, ylim = ylim)) } else if(type=="LeafGrossPhotosynthesis") { OM_SL = SunlitLeavesInst$Ag OM_SH = ShadeLeavesInst$Ag if(bySpecies) { lai1 = tapply(Plants$LAI, x$cohorts$Name, sum, na.rm=T) OMlai = sweep(OM_SL, 1, Plants$LAI, "*") m1 = apply(OMlai,2, tapply, x$cohorts$Name, sum, na.rm=T) OM_SL = sweep(m1,1,lai1,"/") OMlai = sweep(OM_SH, 1, Plants$LAI, "*") m1 = apply(OMlai,2, tapply, x$cohorts$Name, sum, na.rm=T) OM_SH = sweep(m1,1,lai1,"/") } if(is.null(ylab)) ylab=expression(paste("Leaf gross photosynthesis ",(mu%.%mol%.%m^{-2}%.%s^{-1}))) return(.multiple_subday_dynamics_sunlit_shade(t(OM_SL), t(OM_SH), ylab = ylab, ylim = ylim)) } else if(type=="PlantAbsorbedSWR") { OM_SL = SunlitLeavesInst$Abs_SWR OM_SH = ShadeLeavesInst$Abs_SWR if(bySpecies) { lai1 = tapply(Plants$LAI, x$cohorts$Name, sum, na.rm=T) OMlai = sweep(OM_SL, 1, Plants$LAI, "*") m1 = apply(OMlai,2, tapply, x$cohorts$Name, sum, na.rm=T) OM_SL = sweep(m1,1,lai1,"/") OMlai = sweep(OM_SH, 1, Plants$LAI, "*") m1 = apply(OMlai,2, tapply, x$cohorts$Name, sum, na.rm=T) OM_SH = sweep(m1,1,lai1,"/") } if(is.null(ylab)) ylab=expression(paste("Plant absorbed SWR ",(W%.%m^{-2}))) return(.multiple_subday_dynamics_sunlit_shade(t(OM_SL), t(OM_SH), ylab = ylab, ylim = ylim)) } else if(type=="LeafAbsorbedSWR") { OM_SL = SunlitLeavesInst$Abs_SWR OM_SH = ShadeLeavesInst$Abs_SWR if(bySpecies) { m1 = apply(OM_SL,2, tapply, x$cohorts$Name, sum, na.rm=T) lai1 = apply(x$SunlitLeaves$LAI,2, tapply, x$cohorts$Name, sum, na.rm=T) OM_SL = m1/lai1 m1 = apply(OM_SH,2, tapply, x$cohorts$Name, sum, na.rm=T) lai1 = apply(x$ShadeLeaves$LAI,2, tapply, x$cohorts$Name, sum, na.rm=T) OM_SH = m1/lai1 } else { OM_SL = OM_SL/x$SunlitLeaves$LAI OM_SH = OM_SH/x$ShadeLeaves$LAI } if(is.null(ylab)) ylab=expression(paste("Absorbed SWR per leaf area ",(W%.%m^{-2}))) return(.multiple_subday_dynamics_sunlit_shade(t(OM_SL), t(OM_SH), ylab = ylab, ylim = ylim)) } else if(type=="LeafNetLWR") { OM_SL = SunlitLeavesInst$Net_LWR OM_SH = ShadeLeavesInst$Net_LWR if(bySpecies) { m1 = apply(OM_SL,2, tapply, x$cohorts$Name, sum, na.rm=T) lai1 = apply(x$SunlitLeaves$LAI,2, tapply, x$cohorts$Name, sum, na.rm=T) OM_SL = m1/lai1 m1 = apply(OM_SH,2, tapply, x$cohorts$Name, sum, na.rm=T) lai1 = apply(x$ShadeLeaves$LAI,2, tapply, x$cohorts$Name, sum, na.rm=T) OM_SH = m1/lai1 } else { OM_SL = OM_SL/x$SunlitLeaves$LAI OM_SH = OM_SH/x$ShadeLeaves$LAI } if(is.null(ylab)) ylab=expression(paste("Net LWR per leaf area ",(W%.%m^{-2}))) return(.multiple_subday_dynamics_sunlit_shade(t(OM_SL), t(OM_SH), ylab = ylab, ylim = ylim)) } else if(type=="LeafPsi") { OM_SL = SunlitLeavesInst$Psi OM_SH = ShadeLeavesInst$Psi if(bySpecies) { lai1 = tapply(Plants$LAI, x$cohorts$Name, sum, na.rm=T) OMlai = sweep(OM_SL, 1, Plants$LAI, "*") m1 = apply(OMlai,2, tapply, x$cohorts$Name, sum, na.rm=T) OM_SL = sweep(m1,1,lai1,"/") OMlai = sweep(OM_SH, 1, Plants$LAI, "*") m1 = apply(OMlai,2, tapply, x$cohorts$Name, sum, na.rm=T) OM_SH = sweep(m1,1,lai1,"/") } if(is.null(ylab)) ylab="Leaf water potential (-MPa)" return(.multiple_subday_dynamics_sunlit_shade(t(OM_SL), t(OM_SH), ylab = ylab, ylim = ylim)) } else if(type=="LeafTemperature") { OM_SL = SunlitLeavesInst$Temp OM_SH = ShadeLeavesInst$Temp if(bySpecies) { lai1 = tapply(Plants$LAI, x$cohorts$Name, sum, na.rm=T) OMlai = sweep(OM_SL, 1, Plants$LAI, "*") m1 = apply(OMlai,2, tapply, x$cohorts$Name, sum, na.rm=T) OM_SL = sweep(m1,1,lai1,"/") OMlai = sweep(OM_SH, 1, Plants$LAI, "*") m1 = apply(OMlai,2, tapply, x$cohorts$Name, sum, na.rm=T) OM_SH = sweep(m1,1,lai1,"/") } if(is.null(ylab)) ylab="Leaf temperature (degrees C)" return(.multiple_subday_dynamics_sunlit_shade(t(OM_SL), t(OM_SH), ylab = ylab, ylim = ylim)) } else if(type=="LeafVPD") { OM_SL = SunlitLeavesInst$VPD OM_SH = ShadeLeavesInst$VPD if(bySpecies) { lai1 = tapply(Plants$LAI, x$cohorts$Name, sum, na.rm=T) OMlai = sweep(OM_SL, 1, Plants$LAI, "*") m1 = apply(OMlai,2, tapply, x$cohorts$Name, sum, na.rm=T) OM_SL = sweep(m1,1,lai1,"/") OMlai = sweep(OM_SH, 1, Plants$LAI, "*") m1 = apply(OMlai,2, tapply, x$cohorts$Name, sum, na.rm=T) OM_SH = sweep(m1,1,lai1,"/") } if(is.null(ylab)) ylab="Leaf vapour pressure deficit (kPa)" return(.multiple_subday_dynamics_sunlit_shade(t(OM_SL), t(OM_SH), ylab = ylab, ylim = ylim)) } else if(type=="LeafStomatalConductance") { OM_SL = SunlitLeavesInst$Gsw OM_SH = ShadeLeavesInst$Gsw if(bySpecies) { lai1 = tapply(Plants$LAI, x$cohorts$Name, sum, na.rm=T) OMlai = sweep(OM_SL, 1, Plants$LAI, "*") m1 = apply(OMlai,2, tapply, x$cohorts$Name, sum, na.rm=T) OM_SL = sweep(m1,1,lai1,"/") OMlai = sweep(OM_SH, 1, Plants$LAI, "*") m1 = apply(OMlai,2, tapply, x$cohorts$Name, sum, na.rm=T) OM_SH = sweep(m1,1,lai1,"/") } if(is.null(ylab)) ylab=expression(paste("Stomatal conductance ", (mol%.%m^{-2}%.%s^{-1}))) return(.multiple_subday_dynamics_sunlit_shade(t(OM_SL), t(OM_SH), ylab = ylab, ylim = ylim)) } else if(type=="LeafIntrinsicWUE") { OM_SL = SunlitLeavesInst$An/SunlitLeavesInst$Gsw OM_SH = ShadeLeavesInst$An/ShadeLeavesInst$Gsw if(bySpecies) { lai1 = tapply(Plants$LAI, x$cohorts$Name, sum, na.rm=T) OMlai = sweep(OM_SL, 1, Plants$LAI, "*") m1 = apply(OMlai,2, tapply, x$cohorts$Name, sum, na.rm=T) OM_SL = sweep(m1,1,lai1,"/") OMlai = sweep(OM_SH, 1, Plants$LAI, "*") m1 = apply(OMlai,2, tapply, x$cohorts$Name, sum, na.rm=T) OM_SH = sweep(m1,1,lai1,"/") } if(is.null(ylab)) ylab=expression(paste("iWUE ", (mu%.%mol%.%mol^{-1}))) return(.multiple_subday_dynamics_sunlit_shade(t(OM_SL), t(OM_SH), ylab = ylab, ylim = ylim)) } else if(type=="LeafCi") { OM_SL = SunlitLeavesInst$Ci OM_SH = ShadeLeavesInst$Ci if(bySpecies) { lai1 = tapply(Plants$LAI, x$cohorts$Name, sum, na.rm=T) OMlai = sweep(OM_SL, 1, Plants$LAI, "*") m1 = apply(OMlai,2, tapply, x$cohorts$Name, sum, na.rm=T) OM_SL = sweep(m1,1,lai1,"/") OMlai = sweep(OM_SH, 1, Plants$LAI, "*") m1 = apply(OMlai,2, tapply, x$cohorts$Name, sum, na.rm=T) OM_SH = sweep(m1,1,lai1,"/") } if(is.null(ylab)) ylab=expression(paste("Intercellular CO2 concentration ", (ppm))) return(.multiple_subday_dynamics_sunlit_shade(t(OM_SL), t(OM_SH), ylab = ylab, ylim = ylim)) } else if(type=="Temperature") { if(is.null(ylab)) ylab = "Temperature (degrees C)" df = data.frame(row.names=timesteps) df[["Above-canopy"]] = EB$Temperature$Tatm df[["Inside-canopy"]] = EB$Temperature$Tcan df[["Soil"]] = EB$Temperature$Tsoil.1 g<-.multiple_subday_dynamics(as.matrix(df), ylab=ylab, ylim = ylim) return(g) } else if(type=="CanopyEnergyBalance") { if(is.null(ylab)) ylab = expression(W%.%m^{-2}) df = data.frame(row.names=timesteps) df[["Balance"]] = EB$CanopyEnergyBalance$Ebalcan df[["SWR abs."]] = EB$CanopyEnergyBalance$SWRcan df[["LWR net"]] = EB$CanopyEnergyBalance$LWRcan df[["Latent heat"]] = -EB$CanopyEnergyBalance$LEcan df[["Convection can./atm."]] = -EB$CanopyEnergyBalance$Hcan df[["Convection soil/can."]] = -EB$SoilEnergyBalance$Hcansoil g<-.multiple_subday_dynamics(as.matrix(df), ylab=ylab, ylim = ylim) return(g) } else if(type=="SoilEnergyBalance") { if(is.null(ylab)) ylab = expression(W%.%m^{-2}) df = data.frame(row.names=timesteps) df[["Balance"]] = EB$SoilEnergyBalance$Ebalsoil df[["SWR abs."]] = EB$SoilEnergyBalance$SWRsoil df[["LWR net"]] = EB$SoilEnergyBalance$LWRsoil df[["Convection soil/can."]] = EB$SoilEnergyBalance$Hcansoil df[["Latent heat"]] = -EB$SoilEnergyBalance$LEsoil g<-.multiple_subday_dynamics(as.matrix(df), ylab=ylab, ylim = ylim) return(g) } }
sens.analysis.aberrant.rank <- function(cases.exposed,referents.exposed,case.rank,no.referents,Gamma){ mi=cases.exposed+referents.exposed; Ji=no.referents+1; pi.bar=mi/(mi+Gamma*(Ji-mi)); pi.double.bar=Gamma*mi/(Gamma*mi+(Ji-mi)); di=case.rank; teststat=sum(di*cases.exposed); lower.bound.pval=1-pnorm((teststat-sum(di*pi.bar))/sqrt(sum(di^2*pi.bar*(1-pi.bar)))); upper.bound.pval=1-pnorm((teststat-sum(di*pi.double.bar))/(sqrt(sum(di^2*pi.double.bar*(1-pi.double.bar))))); list(lower.bound.pval=lower.bound.pval,upper.bound.pval=upper.bound.pval); }
StubRegistry <- R6::R6Class( "StubRegistry", public = list( request_stubs = list(), global_stubs = list(), print = function(x, ...) { cat("<webmockr stub registry> ", sep = "\n") cat(" Registered Stubs", sep = "\n") for (i in seq_along(self$request_stubs)) { cat(" ", self$request_stubs[[i]]$to_s(), "\n") } invisible(self$request_stubs) }, register_stub = function(stub) { self$request_stubs <- Filter(length, c(self$request_stubs, stub)) }, find_stubbed_request = function(req) { stubs <- c(self$global_stubs, self$request_stubs) stubs[self$request_stub_for(req)] }, request_stub_for = function(request_signature) { stubs <- c(self$global_stubs, self$request_stubs) vapply(stubs, function(z) { tmp <- RequestPattern$new(method = z$method, uri = z$uri, uri_regex = z$uri_regex, query = z$query, body = z$body, headers = z$request_headers) tmp$matches(request_signature) }, logical(1)) }, remove_request_stub = function(stub) { xx <- vapply(self$request_stubs, function(x) x$to_s(), "") if (stub$to_s() %in% xx) { self$request_stubs <- self$request_stubs[-which(stub$to_s() %in% xx)] } else { stop( "Request stub \n\n ", stub$to_s(), "\n\n is not registered.", call. = FALSE ) } }, remove_all_request_stubs = function() { self$request_stubs <- list() }, is_registered = function(x) any(self$request_stub_for(x)) ) ) json_validate <- function(x) { res <- tryCatch(jsonlite::validate(x), error = function(e) e) if (inherits(res, "error")) return(FALSE) res } make_body <- function(x) { if (is.null(x)) return("") if (inherits(x, "mock_file")) x <- x$payload if (inherits(x, "form_file")) x <- unclass(x) clzzes <- vapply(x, function(z) inherits(z, "form_file"), logical(1)) if (any(clzzes)) for(i in seq_along(x)) x[[i]] <- unclass(x[[i]]) if (json_validate(x)) body <- x else body <- jsonlite::toJSON(x, auto_unbox = TRUE) paste0(" with body ", body) } make_headers <- function(x) { if (is.null(x)) return("") paste0(" with headers ", jsonlite::toJSON(x, auto_unbox = TRUE)) } make_status <- function(x) { if (is.null(x)) return("") paste0(" with status ", as.character(x)) }
`clustering_w` <- function (net, measure = "am") { if (is.null(attributes(net)$tnet)) net <- as.tnet(net, type = "weighted one-mode tnet") if (attributes(net)$tnet != "weighted one-mode tnet") stop("Network not loaded properly") if (length(measure) < 1) stop("You must specify a measure") for (i in 1:length(measure)) if(!(measure[i] %in% c("bi", "am", "gm", "ma", "mi"))) stop("You must specify a correct measure") net <- net[order(net[, "i"], net[, "j"]), ] dimnames(net)[[2]] <- c("i", "j", "wij") tmp <- net dimnames(tmp)[[2]] <- c("j", "k", "wjk") tmp <- merge(net, tmp) index <- tmp[, "i"] != tmp[, "k"] tmp <- tmp[index, ] tmp <- tmp[, c("i", "k", "wij", "wjk")] dimnames(net)[[2]] <- c("i", "k", "wik") net[, "wik"] <- TRUE tmp <- merge(tmp, net, all.x = TRUE) tmp[is.na(tmp[, "wik"]), "wik"] <- FALSE index <- as.logical(tmp[, "wik"]) tmp <- tmp[, c("wij", "wjk")] output <- rep(0, length(measure)) for (i in 1:length(measure)) { if (measure[i] == "am") { tvalues <- rowSums(tmp) } else if (measure[i] == "gm") { tvalues <- sqrt(tmp[, "wij"] * tmp[, "wjk"]) } else if (measure[i] == "ma") { tvalues <- pmax.int(tmp[, "wij"], tmp[, "wjk"]) } else if (measure[i] == "mi") { tvalues <- pmin.int(tmp[, "wij"], tmp[, "wjk"]) } else if (measure[i] == "bi") { tvalues <- rep(1, nrow(tmp)) } else { stop("measure incorrectly specified") } output[i] <- sum(tvalues[index]) output[i] <- output[i]/sum(tvalues) } names(output) <- measure return(output) }
context("compare results with outputs from StatXact") dat <- read.csv("TESTDATA.csv") n_test <- nrow(dat) sas <- matrix(NA, n_test,2) v1 <- matrix(NA, n_test,2) sas_lst <- readLines("bscCI_test.lst") offset_bscline <- 20 counter <- 1 ii <- 1 while (counter < length(sas_lst)) { txt <- sas_lst[counter] if (grepl("I=",txt)) { txt_bsc <- sas_lst[counter+offset_bscline] txt_bsc <- sub("\\(Blyth-Still-Casella\\) = \\(", "", txt_bsc) txt_bsc <- sub("\\)", "", txt_bsc) txt_bsc <- strsplit(txt_bsc, ",")[[1]] txt_bsc <- trimws(txt_bsc) sas[ii,] <- as.numeric(txt_bsc) ii <- ii+1 counter <- counter+offset_bscline } else { counter <- counter+1 } } system.time( for (ii in 1:n_test) { v1[ii,] <- bscCI(dat$n[ii], dat$x[ii], 0.95, digits = ) } ) expect_equal(sas[,1], v1[,1], tolerance = 1e-4) expect_equal(sas[,2], v1[,2], tolerance = 1e-4)
ggplot2loon.ggmatrix <- function(ggObj, ..., activeGeomLayers = integer(0), layerId = NULL, scaleToFun = NULL, ggGuides = FALSE, parent = NULL, pack = TRUE, exteriorLabelProportion = 1/5, canvasHeight = 700, canvasWidth = 850) { args <- c( list(activeGeomLayers = activeGeomLayers, parent = parent, ggGuides = ggGuides, pack = pack, exteriorLabelProportion = exteriorLabelProportion, canvasHeight = canvasHeight, canvasWidth = canvasWidth), ... ) if(is.null(parent)) { parent <- l_toplevel() subwin <- loon::l_subwin(parent, 'ggplot') tktitle(parent) <- paste("loon.ggplot", "--path:", subwin) parent <- as.character(tcltk::tcl('frame', subwin)) } nrow <- ggObj$nrow ncol <- ggObj$ncol byrow <- ggObj$byrow ggplots <- ggObj$plots nplots <- length(ggplots) ggplots <- lapply(ggplots, function(plot){ if(ggplot2::is.ggplot(plot)) { plot } else if(is.ggmatrix_plot_obj(plot)) { plot$fn(ggObj$data, plot$mapping) } else { stop("not implemented so far", call. = FALSE) } } ) title <- ggObj$title xlab <- ggObj$xlab ylab <- ggObj$ylab xAxisLabels <- ggObj$xAxisLabels yAxisLabels <- ggObj$yAxisLabels showXAxisPlotLabels <- ggObj$showXAxisPlotLabels & !is.null(xAxisLabels) showYAxisPlotLabels <- ggObj$showYAxisPlotLabels & !is.null(yAxisLabels) start.xpos <- if(!is.null(ylab)) 1 else 0 start.ypos <- if(!is.null(title)){ ifelse(showXAxisPlotLabels, 2, 1) } else { ifelse(showXAxisPlotLabels, 1, 0) } ggLayout <- lapply(ggplots, function(plot){ build <- ggplot_build(plot) build$layout }) span <- round(1/exteriorLabelProportion) rowspan <- span columnspan <- span lapply(seq(nplots), function(i){ plot <- ggplots[[i]] layout <- ggLayout[[i]]$layout rowspan <<- max(rowspan, span*layout$ROW) columnspan <<- max(columnspan, span*layout$COL) } ) if(byrow) { outside <- nrow inside <- ncol } else { outside <- ncol inside <- nrow } loonplots <- list() names <- c() for(i in 1:outside) { for(j in 1:inside){ plotId <- (i - 1) * inside + j if(plotId > nplots) { break } else { args$parent <- parent args$showLabels <- FALSE args$pack <- FALSE args$layerId <- layerId args$scaleToFun <- scaleToFun lp <- do.call( ggplot2loon.ggplot, c(list(ggObj = ggplots[[plotId]]), args) ) loonplots[[plotId]] <- lp names[plotId] <- if(byrow) paste0("x", i, "y", j) else paste0("x", j, "y", i) if(dim(ggLayout[[plotId]]$layout)[1] == 1) { tcltk::tkconfigure(paste(lp,'.canvas',sep=''), width = canvasWidth/ncol, height = canvasHeight/nrow) row.start <- if(byrow) (i - 1) * rowspan + start.ypos else (j - 1) * rowspan + start.ypos col.start <- if(byrow) (j - 1) * columnspan + start.xpos else (i - 1) * columnspan + start.xpos tcltk::tkgrid(lp, row = row.start, column= col.start, rowspan = rowspan, columnspan = columnspan, sticky = "nesw") for (ii in col.start:(col.start + columnspan - 1)) { tcltk::tkgrid.columnconfigure(parent, ii, weight=1) } for (ii in row.start:(row.start + rowspan - 1)) { tcltk::tkgrid.rowconfigure(parent, ii, weight=1) } } else { lplots <- lp$plots layout <- ggLayout[[plotId]]$layout numofROW <- max(layout$ROW) numofCOL <- max(layout$COL) lapply(lplots, function(lplot){ tcltk::tkconfigure(paste(lplot,'.canvas',sep=''), width = canvasWidth/ncol/numofCOL, height = canvasHeight/nrow/numofROW) } ) showStrips <- ggObj$showStrips layout <- ggLayout[[plotId]]$layout FacetWrap <- is.FacetWrap(ggObj$facet) FacetGrid <- is.FacetGrid(ggObj$facet) fun <- if(FacetGrid) { facet_grid_tkpack } else if(FacetWrap) { facet_wrap_tkpack } else stop("Not implemented yet. So far, only `facet_wrap()` and `facet_grid()` are allowed to split panels", call. = FALSE) do.call( fun, list( plotId = plotId, ggLayout = ggLayout, showStrips = showStrips, lplots = lplots, numofROW = numofROW, numofCOL = numofCOL, byrow = byrow, start.ypos = start.ypos, start.xpos = start.xpos, rowspan = rowspan, columnspan = columnspan, span = span, rownames = rownames, colnames = colnames, i = i, j = j, ncol = ncol, nrow = nrow, parent = parent, layout = layout ) ) } } } } modify_loon_tk_labes(parent = parent, title = title, xlab = xlab, ylab = ylab, xAxisLabels = xAxisLabels, yAxisLabels = yAxisLabels, start.xpos = start.xpos, start.ypos = start.ypos, columnspan = columnspan, rowspan = rowspan, ncol = ncol, nrow = nrow, showXAxisPlotLabels = showXAxisPlotLabels, showYAxisPlotLabels = showYAxisPlotLabels) names(loonplots) <- names structure( loonplots, class = c("l_ggmatrix", "l_compound", "loon") ) } modify_loon_tk_labes <- function(parent = tcltk::tktoplevel(), title = NULL, xlab = NULL, ylab = NULL, xAxisLabels = NULL, yAxisLabels = NULL, start.xpos = 1, start.ypos = 1, columnspan = 1, rowspan = 1, ncol = 1, nrow = 1, showXAxisPlotLabels = FALSE, showYAxisPlotLabels = FALSE) { if(!is.null(title)) { tit <- as.character( tcltk::tcl('label', as.character(loon::l_subwin(parent,'title')), text= title, bg = set_tkLabel()$titleBackground, fg = set_tkLabel()$titleForeground, borderwidth = set_tkLabel()$titleBorderwidth, relief = set_tkLabel()$titleRelief) ) tcltk::tkconfigure(tit, font = tcltk::tkfont.create(size = 16, weight="bold")) tcltk::tkgrid(tit, row = 0, column = start.xpos, rowspan = 1, columnspan = columnspan * ncol, sticky="w") } if(showXAxisPlotLabels) { for(i in 1:length(xAxisLabels)){ xAxisLabel <- as.character( tcltk::tcl('label', as.character(loon::l_subwin(parent, paste0('xAxisLabel-', i))), text= xAxisLabels[i], bg = set_tkLabel()$xlabelBackground, fg = set_tkLabel()$xlabelForeground, borderwidth = set_tkLabel()$xlabelBorderwidth, relief = set_tkLabel()$xlabelRelief) ) tcltk::tkgrid(xAxisLabel, row = start.ypos - 1, column = start.xpos + (i - 1) * columnspan, rowspan = 1, columnspan = columnspan, sticky="nesw") } } if(showYAxisPlotLabels) { for(i in 1:length(yAxisLabels)){ yAxisLabel <- as.character( tcltk::tcl('label', as.character(loon::l_subwin(parent, paste0('yAxisLabel-', i))), text= paste(paste0(" ", strsplit(yAxisLabels[i], "")[[1L]], " "), collapse = "\n"), bg = set_tkLabel()$ylabelBackground, fg = set_tkLabel()$ylabelForeground, borderwidth = set_tkLabel()$ylabelBorderwidth, relief = set_tkLabel()$ylabelRelief) ) tcltk::tkgrid(yAxisLabel, row = start.ypos + (i - 1)* rowspan, column = start.xpos + columnspan * ncol, rowspan = rowspan, columnspan = 1, sticky="nesw") } } if(!is.null(xlab)){ xlabel <- as.character( tcltk::tcl('label', as.character(loon::l_subwin(parent,'xlabel')), text= xlab, bg = set_tkLabel()$xlabelBackground, fg = set_tkLabel()$xlabelForeground, borderwidth = set_tkLabel()$xlabelBorderwidth, relief = set_tkLabel()$xlabelRelief) ) tcltk::tkgrid(xlabel, row = rowspan * nrow + start.ypos, column = start.xpos, rowspan = 1, columnspan = columnspan * ncol, sticky="nesw") } if(!is.null(ylab)){ ylabel <- as.character( tcltk::tcl('label', as.character(loon::l_subwin(parent,'ylabel')), text= paste(paste0(" ", strsplit(ylab, "")[[1]], " "), collapse = "\n"), bg = set_tkLabel()$ylabelBackground, fg = set_tkLabel()$ylabelForeground, borderwidth = set_tkLabel()$ylabelBorderwidth, relief = set_tkLabel()$ylabelRelief) ) tcltk::tkgrid(ylabel, row = start.ypos, column = 0, rowspan = rowspan * nrow, columnspan = 1, sticky="nesw") } tkpack(parent, fill="both", expand=TRUE) }
prunemodes<-function(lst,modenum=1,num=NULL,exmalim=NULL,maxnum=NULL) { if (is.null(num)){ curmodenum<-moodilkm(lst$parent)$lkm num<-curmodenum-modenum } go.on<-TRUE nn<-1 while (go.on){ len<-length(lst$parent) child.frekve<-matrix(0,len,1) for (i in 1:len){ if (lst$parent[i]>0) child.frekve[lst$parent[i]]<-child.frekve[lst$parent[i]]+1 } ml<-moodilkm(lst$parent) mode.list<-ml$modloc roots.of.modes<-matrix(0,length(mode.list),1) for (aa in 1:length(mode.list)){ node<-mode.list[aa] while ((lst$parent[node]>0) && (child.frekve[lst$parent[node]]==1)){ node<-lst$parent[node] } roots.of.modes[aa]<-node } em<-excmas(lst) or<-order(em[roots.of.modes]) smallest<-ml$modloc[or[1]] if (nn==1) exma.of.modes<-em[roots.of.modes] node<-smallest emsmallest<-em[node] if ((is.null(exmalim)) || ((!is.null(exmalim)) && (emsmallest<=exmalim))){ rem.list<-c(node) while ((lst$parent[node]>0) && (child.frekve[lst$parent[node]]==1)){ node<-lst$parent[node] rem.list<-c(rem.list,node) } for (kk in 1:length(rem.list)){ remo<-rem.list[kk] for (ll in 1:length(lst$parent)){ if (lst$parent[ll]>remo) lst$parent[ll]<-lst$parent[ll]-1 } lst$parent<-lst$parent[-remo] } lst$level<-lst$level[-rem.list] lst$volume<-lst$volume[-rem.list] lst$center<-lst$center[,-rem.list] lst$distcenter<-lst$distcenter[,-rem.list] lst$proba<-lst$proba[-rem.list] lst$infopointer<-lst$infopointer[-rem.list] } else if ((!is.null(exmalim)) && (emsmallest>exmalim)) go.on<-FALSE nn<-nn+1 if ((nn>num) && (is.null(exmalim))) go.on<-FALSE if ((!is.null(maxnum)) && (nn>maxnum)) go.on<-FALSE } lst$exma.of.modes<-exma.of.modes return(lst=lst) }
summary_starts_uni_print_model_fit <- function(object, digits_fit=3) { if ( ! object$some_missings ){ cat("-----------------------------------------------------------------\n") cat("Model Fit \n\n") cat( paste0("Chi square test of model fit: \nChi2(df=", object$model_fit$df_sem, ")", " ", "=", " ", round( object$model_fit$chisq, digits_fit ), ", p", " ", "=", " ", round( object$model_fit$p_chisq, digits_fit ), "\n\n") ) cat( "SRMR", "=", round( object$model_fit$SRMR, digits_fit ), "\n" ) cat( "RMSEA", "=", round( object$model_fit$RMSEA, digits_fit ), "\n" ) } }
library(rethinking) library(animation) library(ellipse) curve( inv_logit(x) , from=-6 , to=6 , lwd=4 , col=2 , xlab="logit(p)" , ylab="p" , yaxt="n" ) axis(2,at=c(0,0.5,1),labels=c(0,0.5,1)) abline(h=0.5,lty=3) dens( rnorm(1e4,0,1) , lwd=4 , col=4 , xlab="alpha" , xlim=c(-30,30) ) dens( inv_logit( rnorm(1e4,0,10) ) , lwd=4 , col=2 , xlab="probability of event" ) a <- rnorm(1e4,0,1.5) b <- rnorm(1e4,0,0.5) xseq <- seq(from=-3,to=3,len=100) p <- sapply( xseq , function(x) inv_logit(a+b*x) ) plot( NULL , xlim=c(-2.5,2.5) , ylim=c(0,1) , xlab="x value" , ylab="probability" ) for ( i in 1:10 ) lines( xseq , p[i,] , lwd=3 , col=2 ) n_points <- 20 a_true <- (-1) b_true <- 1 x <- runif(n_points,-2,2) y <- rbern(n_points, inv_logit(a_true + b_true*x) ) xlims <- c(-2,2) ylims <- c(0,1) ellipse_hist <- list() ani.record(reset=TRUE) NSTEPS <- 10 for ( i in 0:n_points ) { xmean <- mean( x[1:i] ) al <- alist( y ~ dbern(p), logit(p) <- a + b*x , a ~ dnorm(0,1), b ~ dnorm(0,1) ) if ( i > 0 ) { dati <- list( x=x[1:i] , y=y[1:i] ) q <- quap( al , data=dati , dofit=TRUE ) pp <- extract.samples(q) } else { q <- quap( al , data=list(y=1,x=1) , dofit=FALSE ) pp <- as.data.frame(extract.prior(q)) } a_link <- function(x) inv_logit( a + b*x ) the_text <- concat("n = ",i) xseq <- seq(from=-2.2,to=2.2,length=50) ahat <- mean(pp$a) bhat <- mean(pp$b) if ( i > 0 ) { mu <- link( q , data=list(x=xseq) ) ci <- apply(mu,2,PI) } use_cols <- c(2, 4, 5, 6, 3) the_pf <- function(samp,step) { par(mfrow=c(1,2)) plot(NULL,xlim=c(-2.5,2.5),ylim=c(-2.5,2.5),bty="n",xlab="alpha",ylab="beta") points( a_true , b_true , pch=3 , col=2 , lwd=3 ) pm <- colMeans(pp) the_contour <- list() for ( l in c(0.5,0.8,0.95) ) the_contour[[ concat(l) ]] <- ellipse(cov(pp),centre=pm,level=l) if ( length(ellipse_hist) > 0 & samp==1 ) { mixf <- (NSTEPS-step)/NSTEPS for ( l in c(0.5,0.8,0.95) ) { the_contour[[ concat(l) ]] <- (1-mixf)*the_contour[[concat(l)]] + mixf*ellipse_hist[[concat(l)]] } } thelwd <- 2 if ( samp==1 ) thelwd <- thelwd + 4*(NSTEPS-step)/NSTEPS for ( l in c(0.5,0.8,0.95) ) lines(the_contour[[concat(l)]],col=1,lwd=thelwd ) pb <- get("prior_blend",envir=parent.frame(n = 1)) points( pb[[1]][,step] , pb[[2]][,step] , lwd=2 , col=use_cols[1:3] , pch=16 , cex=1.6 ) plot(NULL,xlim=xlims,ylim=ylims,xlab="x value",ylab="probability of event",bty="n" ,yaxt="n") axis(2,at=c(0,0.5,1),labels=c(0,0.5,1)) abline(h=0.5,lty=3) if ( i > 0 ) { points( x[1:i] , y[1:i] , pch=1 , lwd=3 , cex=1.2 ) } mtext(the_text) } if ( i==0 ) r <- NULL n_prior_samples <- 5 if ( i==0 | i==n_points ) n_prior_samples <- 20 r <- anim_prior_predictive( prior=pp , linkf=a_link , n=n_prior_samples , n_to_show=3 , n_steps=NSTEPS , ylim=ylims , ylab="probability of event" , xlim=xlims , pf=the_pf , do_reset=FALSE , start_from=r , accel=-0.5 , vel0=1 ) for ( l in c(0.5,0.8,0.95) ) ellipse_hist[[ concat(l) ]] <- ellipse(cov(pp),centre=colMeans(pp),level=l) } oopts = ani.options(interval = 0.02) ani.replay() a <- rnorm(1e4,0,1.5) delta <- rnorm(1e4,0,1.5) xseq <- seq(from=-3,to=3,len=100) p <- sapply( xseq , function(x) inv_logit(a) ) plot( NULL , xlim=c(-2.5,2.5) , ylim=c(0,1) , xlab="x value" , ylab="probability" ) for ( i in 1:10 ) lines( xseq , p[i,] , lwd=3 , col=2 ) N <- 1000 G <- sample( 1:2 , size=N , replace=TRUE ) D <- rbern( N , ifelse( G==1 , 0.3 , 0.8 ) ) + 1 accept_rate <- matrix( c(0.1,0.3,0.1,0.3) , nrow=2 ) accept_rate <- matrix( c(0.05,0.2,0.1,0.3) , nrow=2 ) p <- sapply( 1:N , function(i) accept_rate[D[i],G[i]] ) A <- rbern( N , p ) table(G,D) table(G,A) table( G , A , D ) dat_sim <- list( A=A , D=D , G=G ) m1 <- ulam( alist( A ~ bernoulli(p), logit(p) <- a[G], a[G] ~ normal(0,1) ), data=dat_sim , chains=4 , cores=4 ) precis(m1,depth=2) m2 <- ulam( alist( A ~ bernoulli(p), logit(p) <- a[G,D], matrix[G,D]:a ~ normal(0,1) ), data=dat_sim , chains=4 , cores=4 ) precis(m2,depth=3) post1 <- extract.samples(m1) G_contrast <- post1$a[,1] - post1$a[,2] dens(G_contrast,lwd=4,col=2,xlab="Gender contrast") post2 <- extract.samples(m2) G_contrast_D1 <- post2$a[,1,1] - post2$a[,2,1] G_contrast_D2 <- post2$a[,1,2] - post2$a[,2,2] dens(G_contrast_D1,lwd=4,col=2,xlab="Gender contrast",ylim=c(0,2)) dens(G_contrast_D2,lwd=4,col=4,add=TRUE) diff_prob <- inv_logit( post1$a[,1] ) - inv_logit( post1$a[,2] ) dens(diff_prob,lwd=4,col=2,xlab="Gender contrast (probability)") diff_prob_D1 <- inv_logit(post2$a[,1,1]) - inv_logit(post2$a[,2,1]) diff_prob_D2 <- inv_logit(post2$a[,1,2]) - inv_logit(post2$a[,2,2]) dens(diff_prob_D1,lwd=4,col=2,xlab="Gender contrast (probability)",xlim=c(-0.15,0.15)) dens(diff_prob_D2,lwd=4,col=4,add=TRUE) x <- as.data.frame(cbind( A=dat_sim$A , G=dat_sim$G , D=dat_sim$D )) head(x,20) dat_sim2 <- aggregate( A ~ G + D , dat_sim , sum ) dat_sim2$N <- aggregate( A ~ G + D , dat_sim , length )$A m2_bin <- ulam( alist( A ~ binomial(N,p), logit(p) <- a[G,D], matrix[G,D]:a ~ normal(0,1) ), data=dat_sim2 , chains=4 , cores=4 ) precis(m2_bin,3) data(UCBadmit) d <- UCBadmit dat <- list( A = d$admit, N = d$applications, G = ifelse(d$applicant.gender=="female",1,2), D = as.integer(d$dept) ) mG <- ulam( alist( A ~ binomial(N,p), logit(p) <- a[G], a[G] ~ normal(0,1) ), data=dat , chains=4 , cores=4 ) precis(mG,2) mGD <- ulam( alist( A ~ binomial(N,p), logit(p) <- a[G,D], matrix[G,D]:a ~ normal(0,1) ), data=dat , chains=4 , cores=4 ) precis(mGD,3) traceplot(mGD) trankplot(mGD) post1 <- extract.samples(mG) PrA_G1 <- inv_logit( post1$a[,1] ) PrA_G2 <- inv_logit( post1$a[,2] ) diff_prob <- PrA_G1 - PrA_G2 dens(diff_prob,lwd=4,col=2,xlab="Gender contrast (probability)") post2 <- extract.samples(mGD) PrA <- inv_logit( post2$a ) diff_prob_D_ <- sapply( 1:6 , function(i) PrA[,1,i] - PrA[,2,i] ) plot(NULL,xlim=c(-0.2,0.3),ylim=c(0,25),xlab="Gender contrast (probability)",ylab="Density") for ( i in 1:6 ) dens( diff_prob_D_[,i] , lwd=4 , col=1+i , add=TRUE ) abline(v=0,lty=3) total_apps <- sum(dat$N) apps_per_dept <- sapply( 1:6 , function(i) sum(dat$N[dat$D==i]) ) p_G1 <- link(mGD,data=list( D=rep(1:6,times=apps_per_dept), N=rep(1,total_apps), G=rep(1,total_apps))) p_G2 <- link(mGD,data=list( D=rep(1:6,times=apps_per_dept), N=rep(1,total_apps), G=rep(2,total_apps))) dens( p_G1 - p_G2 , lwd=4 , col=2 , xlab="effect of gender perception" ) abline(v=0,lty=3) w <- xtabs( dat$N ~ dat$D ) / sum(dat$N) w <- w/max(w) plot(NULL,xlim=c(-0.2,0.3),ylim=c(0,25),xlab="Gender contrast (probability)",ylab="Density") for ( i in 1:6 ) dens( diff_prob_D_[,i] , lwd=2+8*w[i]^3 , col=1+i , add=TRUE ) abline(v=0,lty=3)
summary.incaix <- function(object, ...){ cat("\n INCA index :", format(object$Total, digits=4), "\n") }
learnIQ1var.formula <- function (formula, data=list(), treatName, intNames, method="homo", cmObject, ...){ if (method=="homo"){ stop ("method must be hetero to use formula specification"); } mf <- model.frame (formula=formula, data=data); x <- model.matrix (attr (mf, "terms"), data=mf); xNames = colnames (x); findTxt = xNames %in% treatName; txtCol = which (findTxt*1==1); findFirst = xNames %in% paste (treatName, xNames, sep=":"); findLast = xNames %in% paste (xNames, treatName, sep=":"); if (length (findFirst) > 0){ txtFirst = which (findFirst*1==1); } else{ txtFirst = NULL; } if (length (findLast) > 0){ txtLast = which (findLast*1==1); } else{ txtLast = NULL; } intOrder = c (txtCol, txtFirst, txtLast); numInt = length (intOrder); H1CVar = cbind (x[,-c (1,intOrder)]); A1 = x[,txtCol]; mainNames = colnames (H1CVar); if (length (intNames) > 0){ ints = which (mainNames %in% intNames); } else{ ints = NULL; } est <- learnIQ1var.default (cmObject, H1CVar, ints, method, ...); est$call <- match.call (); est$formula <- formula; est }
find_formula <- function(x, verbose = TRUE, ...) { UseMethod("find_formula") } formula_ok <- function(x, verbose = TRUE, ...) { f <- find_formula(x, verbose = FALSE) check_1 <- .check_formula_for_dollar(f, verbose = verbose) check_2 <- .check_formula_for_T(f, verbose = verbose) all(check_1 && check_2) } find_formula.default <- function(x, verbose = TRUE, ...) { f <- tryCatch(list(conditional = stats::formula(x)), error = function(x) NULL) .find_formula_return(f, verbose = verbose) } find_formula.list <- function(x, verbose = TRUE, ...) { if (.obj_has_name(x, "gam")) { if ("mer" %in% names(x)) { f.random <- .fix_gamm4_random_effect(find_formula(x$mer)$random) if (length(f.random) == 1) { f.random <- f.random[[1]] } else if (length(f.random) == 0) { f.random <- NULL } } x <- x$gam class(x) <- c(class(x), c("glm", "lm")) f <- .compact_list(list(conditional = stats::formula(x), random = f.random)) } else { f <- find_formula.default(x, ...) } .find_formula_return(f, verbose = verbose) } find_formula.data.frame <- function(x, verbose = TRUE, ...) { stop("A data frame is not a valid object for this function.") } find_formula.aovlist <- function(x, verbose = TRUE, ...) { f <- attr(x, "terms", exact = TRUE) attributes(f) <- NULL .find_formula_return(list(conditional = f)) } find_formula.anova <- function(x, verbose = TRUE, ...) { stop("Formulas cannot be retrieved from anova() objects.") } find_formula.SemiParBIV <- function(x, verbose = TRUE, ...) { f <- stats::formula(x, ...) names(f) <- c("Equation 1", "Equation 2", "Equation 3")[1:length(f)] f <- list(conditional = f) .find_formula_return(f, verbose = verbose) } find_formula.gam <- function(x, verbose = TRUE, ...) { f <- tryCatch(stats::formula(x), error = function(x) NULL) if (!is.null(f)) { if (is.list(f)) { mi <- .gam_family(x) if (!is.null(mi) && mi$family == "ziplss") { f <- list(conditional = f[[1]], zero_inflated = f[[2]]) } else if (mi$family == "Multivariate normal") { r <- lapply(f, function(.i) deparse(.i[[2]])) f <- lapply(f, function(.i) list(conditional = .i)) names(f) <- r attr(f, "is_mv") <- "1" } } else { f <- list(conditional = f) } } .find_formula_return(f, verbose = verbose) } find_formula.gamlss <- function(x, verbose = TRUE, ...) { f <- tryCatch( { f.cond <- stats::as.formula(.get_fixed_effects(x$mu.formula)) f.random <- lapply(.findbars(x$mu.formula), function(.x) { f <- .safe_deparse(.x) stats::as.formula(paste0("~", f)) }) if (length(f.random) == 1) { f.random <- f.random[[1]] } else if (grepl("random\\((.*)\\)", .safe_deparse(f.cond))) { re <- gsub("(.*)random\\((.*)\\)", "\\2", .safe_deparse(f.cond)) f.random <- stats::as.formula(paste0("~1|", re)) f.cond <- stats::update.formula(f.cond, stats::as.formula(paste0(". ~ . - random(", re, ")"))) } .compact_list(list( conditional = f.cond, random = f.random, sigma = x$sigma.formula, nu = x$nu.formula, tau = x$tau.formula )) }, error = function(x) { NULL } ) .find_formula_return(f, verbose = verbose) } find_formula.bamlss <- function(x, verbose = TRUE, ...) { f <- stats::formula(x) if (!is.null(f$mu)) { f.cond <- f$mu$formula } else if (!is.null(f$pi)) { f.cond <- f$pi$formula } if (!is.null(f$sigma)) { f.sigma <- stats::as.formula(paste0("~", as.character(f$sigma$formula)[3])) } else if (!is.null(f$pi)) { f.sigma <- NULL } f <- .compact_list(list( conditional = stats::as.formula(.safe_deparse(f.cond)), sigma = f.sigma )) .find_formula_return(f, verbose = verbose) } find_formula.gamm <- function(x, verbose = TRUE, ...) { f <- .compact_list(find_formula(x$gam)) random <- .fix_gamm_random_effect(names(x$lme$groups)) if (length(random) == 0) { f.random <- NULL } else if (length(random) > 1) { f.random <- lapply(random, function(r) stats::as.formula(paste0("~1|", r))) } else { f.random <- stats::as.formula(paste0("~1|", random)) } .find_formula_return(.compact_list(c(f, list(random = f.random)))) } find_formula.rma <- function(x, verbose = TRUE, ...) { NULL } find_formula.metaplus <- find_formula.rma find_formula.meta_random <- find_formula.rma find_formula.meta_fixed <- find_formula.rma find_formula.meta_bma <- find_formula.rma find_formula.censReg <- find_formula.default find_formula.maxLik <- find_formula.default find_formula.maxim <- find_formula.default find_formula.systemfit <- function(x, verbose = TRUE, ...) { f <- stats::formula(x) l <- lapply(f, function(i) { list(conditional = i) }) f <- .compact_list(l) if (length(f) > 1) { attr(f, "is_mv") <- "1" } .find_formula_return(f) } find_formula.selection <- function(x, verbose = TRUE, ...) { model_call <- parse(text = deparse(get_call(x)))[[1]] f <- list(conditional = list( selection = stats::as.formula(model_call$selection), outcome = stats::as.formula(model_call$outcome) )) attr(f, "two_stage") <- TRUE .find_formula_return(f, verbose = verbose) } find_formula.svy_vglm <- function(x, verbose = TRUE, ...) { find_formula(x$fit) } find_formula.mjoint <- function(x, verbose = TRUE, ...) { s <- summary(x) f.cond <- s$formLongFixed if (length(s$formLongFixed) == 1) { names(f.cond) <- "conditional" } else { names(f.cond) <- paste0("conditional", 1:length(f.cond)) } f.rand <- s$formLongRandom if (length(s$formLongRandom) == 1) { names(f.rand) <- "random" } else { names(f.rand) <- paste0("random", 1:length(f.rand)) } f <- c(f.cond, f.rand, list(survival = s$formSurv)) .find_formula_return(f, verbose = verbose) } find_formula.mvord <- function(x, verbose = TRUE, ...) { f <- list(conditional = x$rho$formula) .find_formula_return(f, verbose = verbose) } find_formula.btergm <- function(x, verbose = TRUE, ...) { f <- list(conditional = x@formula) .find_formula_return(f, verbose = verbose) } find_formula.mediate <- function(x, verbose = TRUE, ...) { f <- list( mediator = find_formula(x$model.m), outcome = find_formula(x$model.y) ) .find_formula_return(f, verbose = verbose) } find_formula.averaging <- function(x, verbose = TRUE, ...) { f_random <- tryCatch( { models <- attributes(x)$modelList find_formula(models[[1]]) }, error = function(e) { NULL } ) f <- find_formula.default(x) if (!.obj_has_name(f, "random") && .obj_has_name(f_random, "random")) { f$random <- f_random$random } .find_formula_return(f, verbose = verbose) } find_formula.glht <- function(x, verbose = TRUE, ...) { .find_formula_return(list(conditional = stats::formula(x$model))) } find_formula.joint <- function(x, verbose = TRUE, ...) { f <- stats::formula(x) .find_formula_return(list(conditional = f$lformula, survival = f$sformula)) } find_formula.betareg <- function(x, verbose = TRUE, ...) { f <- stats::formula(x) fs <- .safe_deparse(f) if (grepl("|", fs, fixed = TRUE)) { fs <- trimws(unlist(strsplit(fs, "|", fixed = TRUE))) f <- list( conditional = stats::as.formula(fs[1]), precision = stats::as.formula(paste0("~", fs[2])) ) } else { f <- list(conditional = f) } .find_formula_return(f, verbose = verbose) } find_formula.afex_aov <- function(x, verbose = TRUE, ...) { if (length(attr(x, "within")) == 0L) { fff <- find_formula(x$lm, verbose = verbose, ...) fff$conditional[2] <- call(attr(x, "dv")) fff } else { d <- get_data(x, shape = "long") dv <- attr(x, "dv") id <- attr(x, "id") within <- names(attr(x, "within")) within <- paste0(within, collapse = "*") within <- paste0("(", within, ")") e <- paste0("Error(", id, "/", within, ")") between <- names(attr(x, "between")) if (length(between) > 0L) { tempf <- find_formula(x$lm)[[1]] between <- as.character(tempf)[3] between <- paste0("(", between, ")") within <- paste0(c(within, between), collapse = "*") } out <- list(conditional = stats::formula(paste0(dv, "~", within, "+", e))) class(out) <- c("insight_formula", "list") out } } find_formula.mira <- function(x, verbose = TRUE, ...) { .find_formula_return(find_formula(x$analyses[[1]])) } find_formula.gee <- function(x, verbose = TRUE, ...) { f <- tryCatch( { id <- parse(text = .safe_deparse(x$call))[[1]]$id list( conditional = stats::formula(x), random = stats::as.formula(paste0("~", id)) ) }, error = function(x) { NULL } ) .find_formula_return(f, verbose = verbose) } find_formula.MANOVA <- function(x, verbose = TRUE, ...) { f <- .compact_list(list( conditional = x$input$formula, random = stats::as.formula(paste0("~", x$input$subject)) )) .find_formula_return(f, verbose = verbose) } find_formula.RM <- find_formula.MANOVA find_formula.gls <- function(x, verbose = TRUE, ...) { fcorr <- x$call$correlation if (!is.null(fcorr)) { f_corr <- parse(text = .safe_deparse(x$call$correlation))[[1]] } else { f_corr <- NULL } if (is.symbol(f_corr)) { f_corr <- paste("~", .safe_deparse(f_corr)) } else { f_corr <- f_corr$form } l <- tryCatch( { list( conditional = stats::formula(x), correlation = stats::as.formula(f_corr) ) }, error = function(x) { NULL } ) .find_formula_return(.compact_list(l)) } find_formula.LORgee <- function(x, verbose = TRUE, ...) { f <- tryCatch( { id <- parse(text = .safe_deparse(x$call))[[1]]$id list( conditional = stats::formula(x), random = stats::as.formula(paste0("~", id)) ) }, error = function(x) { NULL } ) .find_formula_return(f, verbose = verbose) } find_formula.cglm <- function(x, verbose = TRUE, ...) { f <- tryCatch( { id <- parse(text = .safe_deparse(x$call))[[1]]$id list( conditional = stats::formula(x), random = stats::as.formula(paste0("~", id)) ) }, error = function(x) { NULL } ) .find_formula_return(f, verbose = verbose) } find_formula.betamfx <- find_formula.betareg find_formula.betaor <- find_formula.betareg find_formula.logitmfx <- function(x, verbose = TRUE, ...) { find_formula.default(x$fit, ...) } find_formula.poissonmfx <- find_formula.logitmfx find_formula.negbinmfx <- find_formula.logitmfx find_formula.logitor <- find_formula.logitmfx find_formula.negbinirr <- find_formula.logitmfx find_formula.poissonirr <- find_formula.logitmfx find_formula.probitmfx <- find_formula.logitmfx find_formula.ivreg <- function(x, verbose = TRUE, ...) { f <- tryCatch( { f <- .safe_deparse(stats::formula(x)) cond <- .trim(substr(f, start = 0, stop = regexpr(pattern = "\\|", f) - 1)) instr <- .trim(substr(f, regexpr(pattern = "\\|", f) + 1, stop = 10000L)) list( conditional = stats::as.formula(cond), instruments = stats::as.formula(paste0("~", instr)) ) }, error = function(x) { NULL } ) .find_formula_return(f, verbose = verbose) } find_formula.iv_robust <- find_formula.ivreg find_formula.ivFixed <- find_formula.ivreg find_formula.plm <- function(x, verbose = TRUE, ...) { f <- tryCatch( { f <- .safe_deparse(stats::formula(x)) bar_pos <- regexpr(pattern = "\\|", f) if (bar_pos == -1) { stop_pos <- nchar(f) + 1 } else { stop_pos <- bar_pos } cond <- .trim(substr(f, start = 0, stop = stop_pos - 1)) instr <- .trim(substr(f, stop_pos + 1, stop = 10000L)) if (.is_empty_string(instr)) { list(conditional = stats::as.formula(cond)) } else { instr <- gsub("(^\\.\\s*)(.*)", "\\2", instr) list( conditional = stats::as.formula(cond), instruments = stats::as.formula(paste0("~", instr)) ) } }, error = function(x) { NULL } ) .find_formula_return(f, verbose = verbose) } find_formula.pgmm <- find_formula.plm find_formula.felm <- function(x, verbose = TRUE, ...) { f <- .safe_deparse(stats::formula(x)) f_parts <- .trim(unlist(strsplit(f, "(?<!\\()\\|(?![\\w\\s\\+\\(~]*[\\)])", perl = TRUE))) f.cond <- f_parts[1] if (length(f_parts) > 1) { f.rand <- paste0("~", f_parts[2]) } else { f.rand <- NULL } if (length(f_parts) > 2) { f.instr <- paste0("~", f_parts[3]) } else { f.instr <- NULL } if (length(f_parts) > 3) { f.clus <- paste0("~", f_parts[4]) } else { f.clus <- NULL } f <- .compact_list(list( conditional = stats::as.formula(f.cond), random = stats::as.formula(f.rand), instruments = stats::as.formula(f.instr), cluster = stats::as.formula(f.clus) )) .find_formula_return(f, verbose = verbose) } find_formula.mhurdle <- function(x, verbose = TRUE, ...) { f <- .safe_deparse(stats::formula(x)[[3]]) f_parts <- .trim(unlist(strsplit(f, "(?<!\\()\\|(?![\\w\\s\\+\\(~]*[\\)])", perl = TRUE))) f.zi <- paste0("~", f_parts[1]) if (length(f_parts) > 1) { f.cond <- paste0(.safe_deparse(stats::formula(x)[[2]]), "~", f_parts[2]) } else { f.cond <- NULL } if (length(f_parts) > 2) { f.ip <- paste0("~", f_parts[3]) } else { f.ip <- NULL } if (f.zi == "~0") { f.zi <- NULL } if (f.ip == "~0") { f.ip <- NULL } f <- .compact_list(list( conditional = stats::as.formula(f.cond), zero_inflated = stats::as.formula(f.zi), infrequent_purchase = stats::as.formula(f.ip) )) .find_formula_return(f, verbose = verbose) } find_formula.feglm <- function(x, verbose = TRUE, ...) { f <- .safe_deparse(stats::formula(x)) f_parts <- unlist(strsplit(f, "(?<!\\()\\|(?![\\w\\s\\+\\(~]*[\\)])", perl = TRUE)) f.cond <- .trim(f_parts[1]) if (length(f_parts) > 1) { f.instr <- paste0("~", .trim(f_parts[2])) } else { f.instr <- NULL } if (length(f_parts) > 2) { f.clus <- paste0("~", .trim(f_parts[3])) } else { f.clus <- NULL } f <- .compact_list(list( conditional = stats::as.formula(f.cond), instruments = stats::as.formula(f.instr), cluster = stats::as.formula(f.clus) )) .find_formula_return(f, verbose = verbose) } find_formula.fixest <- function(x, verbose = TRUE, ...) { f <- .safe_deparse(stats::formula(x)) f_parts <- unlist(strsplit(f, "(?<!\\()\\|(?![\\w\\s\\+\\(~]*[\\)])", perl = TRUE)) f.cond <- .trim(f_parts[1]) if (length(f_parts) > 1) { f.clus <- paste0("~", .trim(f_parts[2])) } else { f.clus <- parse(text = deparse(x$call))[[1]]$fixef if (!is.null(f.clus)) { f.clus <- paste("~", paste(eval(f.clus), collapse = " + ")) } } f <- .compact_list(list( conditional = stats::as.formula(f.cond), cluster = stats::as.formula(f.clus) )) .find_formula_return(f, verbose = verbose) } find_formula.feis <- function(x, verbose = TRUE, ...) { f <- .safe_deparse(stats::formula(x)) f_parts <- unlist(strsplit(f, "(?<!\\()\\|(?![\\w\\s\\+\\(~]*[\\)])", perl = TRUE)) f.cond <- .trim(f_parts[1]) id <- parse(text = .safe_deparse(x$call))[[1]]$id if (length(f_parts) > 1) { f.slopes <- paste0("~", .trim(f_parts[2])) } else { f.slopes <- NULL } f <- .compact_list(list( conditional = stats::as.formula(f.cond), slopes = stats::as.formula(f.slopes), random = stats::as.formula(paste0("~", id)) )) .find_formula_return(f, verbose = verbose) } find_formula.bife <- function(x, verbose = TRUE, ...) { f <- .safe_deparse(stats::formula(x)) f_parts <- unlist(strsplit(f, "|", fixed = TRUE)) f.cond <- .trim(f_parts[1]) if (length(f_parts) > 1) { f.rand <- paste0("~", .trim(f_parts[2])) } else { f.rand <- NULL } f <- .compact_list(list( conditional = stats::as.formula(f.cond), random = stats::as.formula(f.rand) )) .find_formula_return(f, verbose = verbose) } find_formula.ivprobit <- function(x, verbose = TRUE, ...) { NULL } find_formula.wbm <- function(x, verbose = TRUE, ...) { f <- .safe_deparse(stats::formula(x)) f_parts <- unlist(strsplit(f, "(?<!\\()\\|(?![\\w\\s\\+\\(~]*[\\)])", perl = TRUE)) f.cond <- .trim(f_parts[1]) if (length(f_parts) > 1) { f.instr <- paste0("~", .trim(f_parts[2])) } else { f.instr <- NULL } if (length(f_parts) > 2) { f_parts[3] <- .trim(f_parts[3]) if (grepl("\\((.+)\\|(.+)\\)", f_parts[3])) { if (length(gregexpr("\\|", f_parts[3])[[1]]) > 1) { f.rand <- .findbars(stats::as.formula(paste("~", f_parts[3]))) } else { f.rand <- gsub("(\\(|\\))", "", f_parts[3]) f.rand <- stats::as.formula(paste0("~", .trim(f.rand))) } f.clint <- NULL } else { f.clint <- f_parts[3] f.clint <- paste0("~", .trim(f.clint)) f.rand <- NULL } } else { f.rand <- NULL f.clint <- NULL } f <- .compact_list(list( conditional = stats::as.formula(f.cond), instruments = stats::as.formula(f.instr), interactions = stats::as.formula(f.clint), random = f.rand )) .find_formula_return(f, verbose = verbose) } find_formula.wbgee <- find_formula.wbm find_formula.glimML <- function(x, verbose = TRUE, ...) { f <- .compact_list(list( conditional = x@formula, random = x@random )) .find_formula_return(f, verbose = verbose) } find_formula.tobit <- function(x, verbose = TRUE, ...) { f <- tryCatch( list(conditional = parse(text = .safe_deparse(x$call))[[1]]$formula), error = function(x) NULL ) .find_formula_return(f, verbose = verbose) } find_formula.hurdle <- function(x, verbose = TRUE, ...) { .zeroinf_formula(x, verbose = verbose) } find_formula.zeroinfl <- find_formula.hurdle find_formula.zerotrunc <- find_formula.hurdle find_formula.zcpglm <- function(x, verbose = TRUE, ...) { .zeroinf_formula(x, separator = "\\|\\|", verbose = verbose) } find_formula.clmm2 <- function(x, verbose = TRUE, ...) { f <- .compact_list(list( conditional = stats::as.formula(.safe_deparse(attr(x$location, "terms", exact = TRUE))), scale = stats::as.formula(.safe_deparse(attr(x$scale, "terms", exact = TRUE))), random = stats::as.formula(paste0("~", parse(text = .safe_deparse(x$call))[[1]]$random)) )) .find_formula_return(f, verbose = verbose) } find_formula.clm2 <- function(x, verbose = TRUE, ...) { f <- .compact_list(list( conditional = stats::formula(attr(x$location, "terms", exact = TRUE)), scale = stats::formula(attr(x$scale, "terms", exact = TRUE)) )) .find_formula_return(f, verbose = verbose) } find_formula.DirichletRegModel <- function(x, verbose = TRUE, ...) { f <- .safe_deparse(stats::formula(x)) f_parts <- unlist(strsplit(f, "(?<!\\()\\|(?![\\w\\s\\+\\(~]*[\\)])", perl = TRUE)) f.cond <- .trim(f_parts[1]) if (length(f_parts) > 1) { f.cond2 <- paste0("~", .trim(f_parts[2])) } else { f.cond2 <- NULL } if (length(f_parts) > 2) { f.cond3 <- paste0("~", .trim(f_parts[3])) } else { f.cond3 <- NULL } out <- .compact_list(list( conditional = stats::as.formula(f.cond), conditional2 = stats::as.formula(f.cond2), conditional3 = stats::as.formula(f.cond3) )) if (x$parametrization == "alternative") { if (length(out) == 2) names(out)[2] <- "precision" } .find_formula_return(out) } find_formula.glmmTMB <- function(x, verbose = TRUE, ...) { f.cond <- stats::formula(x) f.zi <- stats::formula(x, component = "zi") f.disp <- stats::formula(x, component = "disp") if (identical(.safe_deparse(f.zi), "~0") || identical(.safe_deparse(f.zi), "~1")) { f.zi <- NULL } if (identical(.safe_deparse(f.disp), "~0") || identical(.safe_deparse(f.disp), "~1")) { f.disp <- NULL } f.random <- lapply(.findbars(f.cond), function(.x) { f <- .safe_deparse(.x) stats::as.formula(paste0("~", f)) }) if (length(f.random) == 1) { f.random <- f.random[[1]] } f.zirandom <- lapply(.findbars(f.zi), function(.x) { f <- .safe_deparse(.x) if (f == "NULL") { return(NULL) } stats::as.formula(paste0("~", f)) }) if (length(f.zirandom) == 1) { f.zirandom <- f.zirandom[[1]] } f.cond <- stats::as.formula(.get_fixed_effects(f.cond)) if (!is.null(f.zi)) f.zi <- stats::as.formula(.get_fixed_effects(f.zi)) f <- .compact_list(list( conditional = f.cond, random = f.random, zero_inflated = f.zi, zero_inflated_random = f.zirandom, dispersion = f.disp )) .find_formula_return(f, verbose = verbose) } find_formula.nlmerMod <- function(x, verbose = TRUE, ...) { f.random <- lapply(.findbars(stats::formula(x)), function(.x) { f <- .safe_deparse(.x) stats::as.formula(paste0("~", f)) }) if (length(f.random) == 1) { f.random <- f.random[[1]] } f.cond <- .nobars(stats::as.formula(gsub("(.*)(~)(.*)~(.*)", "\\1\\2\\4", .safe_deparse(stats::formula(x))))) f.nonlin <- stats::as.formula(paste0("~", .trim(gsub("(.*)~(.*)~(.*)", "\\2", .safe_deparse(stats::formula(x)))))) f <- .compact_list(list( conditional = f.cond, nonlinear = f.nonlin, random = f.random )) .find_formula_return(f, verbose = verbose) } find_formula.merMod <- function(x, verbose = TRUE, ...) { f.cond <- stats::formula(x) f.random <- lapply(.findbars(f.cond), function(.x) { f <- .safe_deparse(.x) stats::as.formula(paste0("~", f)) }) if (length(f.random) == 1) { f.random <- f.random[[1]] } f.cond <- stats::as.formula(.get_fixed_effects(f.cond)) f <- .compact_list(list(conditional = f.cond, random = f.random)) .find_formula_return(f, verbose = verbose) } find_formula.rlmerMod <- find_formula.merMod find_formula.cpglmm <- find_formula.merMod find_formula.glmmadmb <- find_formula.merMod find_formula.mixed <- find_formula.merMod find_formula.clmm <- find_formula.merMod find_formula.cgamm <- find_formula.merMod find_formula.coxme <- find_formula.merMod find_formula.HLfit <- find_formula.merMod find_formula.merModList <- function(x, verbose = TRUE, ...) { find_formula(x[[1]], ...) } find_formula.sem <- function(x, verbose = TRUE, ...) { if (!.is_semLme(x)) { return(NULL) } f.cond <- x$formula f.random <- lapply(.findbars(f.cond), function(.x) { f <- .safe_deparse(.x) stats::as.formula(paste0("~", f)) }) if (length(f.random) == 1) { f.random <- f.random[[1]] } f.cond <- stats::as.formula(.get_fixed_effects(f.cond)) f <- .compact_list(list(conditional = f.cond, random = f.random)) .find_formula_return(f, verbose = verbose) } find_formula.lme <- function(x, verbose = TRUE, ...) { fm <- eval(x$call$fixed) fmr <- eval(x$call$random) fcorr <- x$call$correlation if (!is.null(fcorr)) { fc <- parse(text = .safe_deparse(x$call$correlation))[[1]]$form } else { fc <- NULL } f <- .compact_list(list( conditional = fm, random = fmr, correlation = stats::as.formula(fc) )) .find_formula_return(f, verbose = verbose) } find_formula.lqmm <- function(x, verbose = TRUE, ...) { fm <- eval(x$call$fixed) fmr <- .safe_deparse(x$call$random) fmg <- .safe_deparse(x$call$group) f <- .compact_list(list( conditional = fm, random = stats::as.formula(paste0(fmr, "|", fmg)) )) .find_formula_return(f, verbose = verbose) } find_formula.mixor <- function(x, verbose = TRUE, ...) { fm <- x$call$formula f_id <- deparse(x$call$id) f_rs <- x$call$which.random.slope if (!is.null(f_rs)) { f_rs <- trimws(unlist(strsplit(.safe_deparse(x$call$formula[[3]]), "\\+")))[f_rs] fmr <- paste(f_rs, "|", f_id) } else { fmr <- f_id } fmr <- stats::as.formula(paste("~", fmr)) f <- .compact_list(list( conditional = fm, random = fmr )) .find_formula_return(f, verbose = verbose) } find_formula.MixMod <- function(x, verbose = TRUE, ...) { f.cond <- stats::formula(x) f.zi <- stats::formula(x, type = "zi_fixed") f.random <- stats::formula(x, type = "random") f.zirandom <- stats::formula(x, type = "zi_random") f <- .compact_list(list( conditional = f.cond, random = f.random, zero_inflated = f.zi, zero_inflated_random = f.zirandom )) .find_formula_return(f, verbose = verbose) } find_formula.BBmm <- function(x, verbose = TRUE, ...) { f.cond <- parse(text = .safe_deparse(x$call))[[1]]$fixed.formula f.rand <- parse(text = .safe_deparse(x$call))[[1]]$random.formula f <- .compact_list(list( conditional = stats::as.formula(f.cond), random = stats::as.formula(f.rand) )) .find_formula_return(f, verbose = verbose) } find_formula.mmclogit <- function(x, verbose = TRUE, ...) { f <- tryCatch( { list( conditional = stats::formula(x), random = stats::as.formula(parse(text = .safe_deparse(x$call))[[1]]$random) ) }, error = function(x) { NULL } ) .find_formula_return(f, verbose = verbose) } find_formula.glmm <- function(x, verbose = TRUE, ...) { f.cond <- stats::as.formula(x$fixedcall) f.random <- lapply(x$randcall, function(.x) { av <- all.vars(.x) stats::as.formula(paste0("~1|", av[length(av)])) }) if (length(f.random) == 1) { f.random <- f.random[[1]] } f <- .compact_list(list(conditional = f.cond, random = f.random)) .find_formula_return(f, verbose = verbose) } find_formula.BGGM <- function(x, verbose = TRUE, ...) { list(conditional = x$formula) } find_formula.mcmc.list <- function(x, verbose = TRUE, ...) { NULL } find_formula.stanreg <- function(x, verbose = TRUE, ...) { if (inherits(x, "nlmerMod")) { find_formula.nlmerMod(x, ...) } else { f.cond <- stats::formula(x) if (inherits(x, "gamm4")) { f.random <- tryCatch( { lapply(.findbars(stats::formula(x$glmod)), function(.x) { f <- .safe_deparse(.x) stats::as.formula(paste0("~", f)) }) }, error = function(e) { NULL } ) } else { f.random <- lapply(.findbars(f.cond), function(.x) { f <- .safe_deparse(.x) stats::as.formula(paste0("~", f)) }) } if (length(f.random) == 1) { f.random <- f.random[[1]] } f.cond <- stats::as.formula(.get_fixed_effects(f.cond)) f <- .compact_list(list(conditional = f.cond, random = f.random)) .find_formula_return(f, verbose = verbose) } } find_formula.brmsfit <- function(x, verbose = TRUE, ...) { f <- stats::formula(x) if (.obj_has_name(f, "forms")) { mv_formula <- lapply(f$forms, .get_brms_formula) attr(mv_formula, "is_mv") <- "1" f <- mv_formula } else { f <- .get_brms_formula(f) } .find_formula_return(f, verbose = verbose) } find_formula.stanmvreg <- function(x, verbose = TRUE, ...) { f <- stats::formula(x) mv_formula <- lapply(f, .get_stanmv_formula) attr(mv_formula, "is_mv") <- "1" .find_formula_return(mv_formula) } find_formula.MCMCglmm <- function(x, verbose = TRUE, ...) { fm <- x$Fixed$formula fmr <- x$Random$formula f <- .compact_list(list(conditional = fm, random = fmr)) .find_formula_return(f, verbose = verbose) } find_formula.BFBayesFactor <- function(x, verbose = TRUE, ...) { if (.classify_BFBayesFactor(x) == "linear") { fcond <- utils::tail(x@numerator, 1)[[1]]@identifier$formula dt <- utils::tail(x@numerator, 1)[[1]]@dataTypes frand <- names(dt)[which(dt == "random")] if (!.is_empty_object(frand)) { f.random <- stats::as.formula(paste0("~", paste(frand, collapse = " + "))) for (i in frand) { fcond <- sub(i, "", fcond, fixed = TRUE) } while (grepl("\\+$", .trim(fcond))) { fcond <- gsub("(.*)\\+$", "\\1", .trim(fcond)) } if (grepl("~$", .trim(fcond))) { fcond <- paste(fcond, "1") } f.cond <- stats::as.formula(.trim(fcond)) } else { f.random <- NULL f.cond <- stats::as.formula(fcond) } } else if (.classify_BFBayesFactor(x) %in% c("ttest1", "ttest2")) { f.cond <- tryCatch(stats::as.formula(x@numerator[[1]]@identifier$formula), error = function(e) NULL) f.random <- NULL } else { return(NULL) } f <- .compact_list(list( conditional = f.cond, random = f.random )) .find_formula_return(f, verbose = verbose) } find_formula.model_fit <- function(x, verbose = TRUE, ...) { find_formula(x$fit, ...) } .get_brms_formula <- function(f) { f_cond <- f$formula f_random <- lapply(.findbars(f_cond), function(.x) { fm <- .safe_deparse(.x) stats::as.formula(paste0("~", fm)) }) if (length(f_random) == 1) { f_random <- f_random[[1]] } f_cond <- stats::as.formula(.get_fixed_effects(f_cond)) f_zi <- f$pforms$zi f_zirandom <- NULL f_sigma <- f$pforms$sigma f_mu <- f$pforms$mu f_nu <- f$pforms$nu f_shape <- f$pforms$shape f_beta <- f$pforms$beta f_phi <- f$pforms$phi f_hu <- f$pforms$hu f_ndt <- f$pforms$ndt f_zoi <- f$pforms$zoi f_coi <- f$pforms$coi f_kappa <- f$pforms$kappa f_bias <- f$pforms$bias f_bs <- f$pforms$bs f_sigmarandom <- NULL f_betarandom <- NULL if (!.is_empty_object(f_zi)) { f_zirandom <- lapply(.findbars(f_zi), function(.x) { f <- .safe_deparse(.x) stats::as.formula(paste0("~", f)) }) if (length(f_zirandom) == 1) { f_zirandom <- f_zirandom[[1]] } f_zi <- stats::as.formula(paste0("~", .safe_deparse(f_zi[[3L]]))) f_zi <- stats::as.formula(.get_fixed_effects(f_zi)) } if (!.is_empty_object(f_sigma)) { f_sigmarandom <- lapply(.findbars(f_sigma), function(.x) { f <- .safe_deparse(.x) stats::as.formula(paste0("~", f)) }) if (length(f_sigmarandom) == 1) { f_sigmarandom <- f_sigmarandom[[1]] } f_sigma <- stats::as.formula(paste0("~", .safe_deparse(f_sigma[[3L]]))) f_sigma <- stats::as.formula(.get_fixed_effects(f_sigma)) } if (!.is_empty_object(f_beta)) { f_betarandom <- lapply(.findbars(f_beta), function(.x) { f <- .safe_deparse(.x) stats::as.formula(paste0("~", f)) }) if (length(f_betarandom) == 1) { f_betarandom <- f_betarandom[[1]] } f_beta <- stats::as.formula(paste0("~", .safe_deparse(f_beta[[3L]]))) f_beta <- stats::as.formula(.get_fixed_effects(f_beta)) } .compact_list(list( conditional = f_cond, random = f_random, zero_inflated = f_zi, zero_inflated_random = f_zirandom, sigma = f_sigma, sigma_random = f_sigmarandom, beta = f_beta, beta_random = f_betarandom, shape = f_shape, phi = f_phi, hurdle = f_hu, mu = f_mu, nu = f_nu, ndt = f_ndt, bs = f_bs, bias = f_bias, zero_one_inflated = f_zoi, conditional_one_inflated = f_coi, kappa = f_kappa )) } .get_stanmv_formula <- function(f) { f_cond <- f f_random <- lapply(.findbars(f_cond), function(.x) { fm <- .safe_deparse(.x) stats::as.formula(paste0("~", fm)) }) if (length(f_random) == 1) { f_random <- f_random[[1]] } f_cond <- stats::as.formula(.get_fixed_effects(f_cond)) .compact_list(list( conditional = f_cond, random = f_random )) } .zeroinf_formula <- function(x, separator = "\\|", verbose = TRUE) { f <- tryCatch(stats::formula(x), error = function(x) NULL) if (is.null(f)) { return(NULL) } f <- .trim(unlist(strsplit(.safe_deparse(f), separator))) c.form <- stats::as.formula(f[1]) if (length(f) == 2) { zi.form <- stats::as.formula(paste0("~", f[2])) } else { zi.form <- NULL } c.form <- .dot_formula(f = c.form, model = x) zi.form <- tryCatch( { if (as.character(zi.form[2]) == ".") { resp <- .safe_deparse(c.form[2]) pred <- setdiff(colnames(.recover_data_from_environment(x)), resp) zi.form <- stats::as.formula(paste(resp, "~", paste0(pred, collapse = " + "))) } zi.form }, error = function(e) { zi.form } ) f <- .compact_list(list(conditional = c.form, zero_inflated = zi.form)) .find_formula_return(f, verbose = verbose) } .dot_formula <- function(f, model) { tryCatch( { if (as.character(f[[3]])[1] == ".") { resp <- .safe_deparse(f[[2]]) pred <- setdiff(colnames(.recover_data_from_environment(model)), resp) f <- stats::as.formula(paste(resp, "~", paste0(pred, collapse = " + "))) } f }, error = function(e) { f } ) } .fix_gamm_random_effect <- function(x) { g_in_terms <- length(x) > 1 && x[length(x)] == "g" xr_in_terms <- length(x) > 1 && x[length(x)] == "Xr" x <- x[!(grepl("(Xr\\.\\d|g\\.\\d)", x) | x %in% c("Xr", "g"))] if (!length(x) && isTRUE(g_in_terms)) { x <- "g" } if (!length(x) && isTRUE(xr_in_terms)) { x <- "Xr" } x } .fix_gamm4_random_effect <- function(f) { if (inherits(f, "formula")) { f <- list(f) } len <- length(f) keep <- sapply(f, function(i) { i <- gsub("(~1| | \\|)", "", deparse(i)) !any(grepl("(Xr\\.\\d|g\\.\\d)", i) | i %in% c("Xr", "g")) }) f <- .compact_list(f[keep]) if (!length(f) && len > 1) { f <- list(stats::as.formula("~1 | Xr")) } f } .find_formula_return <- function(f, verbose = TRUE) { if (is.null(f)) { return(NULL) } .check_formula_for_dollar(f, verbose = verbose) .check_formula_for_T(f, verbose = verbose) class(f) <- c("insight_formula", class(f)) f } .check_formula_for_T <- function(f, verbose = TRUE) { f <- .safe_deparse(f[[1]]) if (.is_empty_object(f)) { return(TRUE) } if (grepl("(.*)poly\\((.*),\\s*raw\\s*=\\s*T\\)", f)) { if (verbose) { warning(format_message( "Looks like you are using 'poly()' with 'raw = T'. This results in unexpected behaviour, because 'all.vars()' considers 'T' as variable.", "Please use 'raw = TRUE'." ), call. = FALSE ) } return(FALSE) } return(TRUE) } .check_formula_for_dollar <- function(f, verbose = TRUE) { if (.is_empty_object(f)) { return(TRUE) } if (any(grepl("\\$", .safe_deparse(f[[1]])))) { fc <- try(.formula_clean(f[[1]]), silent = TRUE) if (inherits(fc, "try-error")) { stop(attributes(fc)$condition$message, call. = FALSE) } else { if (verbose) { warning( format_message(paste0( "Using `$` in model formulas can produce unexpected results. Specify your model using the `data` argument instead.", "\n Try: ", fc$formula, ", data = ", fc$data )), call. = FALSE ) } return(FALSE) } } return(TRUE) } .formula_clean <- function(f) { fc <- as.character(f) LHS <- fc[2] RHS <- fc[3] pattern <- "[\\s*+:()|^,\\-\\/]" parts <- trimws(unlist(strsplit(split = pattern, x = LHS, perl = TRUE))) d_LHS <- unique(gsub("(.*)\\$(.*)", "\\1", parts[grepl("(.*)\\$(.*)", parts)])) parts <- trimws(unlist(strsplit(split = pattern, x = RHS, perl = TRUE))) d_RHS <- unique(gsub("(.*)\\$(.*)", "\\1", parts[grepl("(.*)\\$(.*)", parts)])) if (.n_unique(c(d_LHS, d_RHS)) > 1) { stop("Multiple data objects present in formula. Specify your model using the `data` argument instead.", call. = FALSE) } else { d <- unique(d_RHS) } LHS_clean <- gsub(paste0(d_LHS, "\\$"), "", LHS) RHS_clean <- gsub(paste0(d_RHS, "\\$"), "", RHS) list(data = d, formula = paste(LHS_clean, fc[1], RHS_clean)) } format.insight_formula <- function(x, what = c("conditional", "random"), ...) { ft <- format(x[[1]]) if ("random" %in% names(x)) { x[["random"]] <- paste0("(", format(x[["random"]]), ")") } for (part in what[-1]) { if (part %in% names(x)) { ft <- paste0(ft, " + ", format(x[[part]])) } } ft }
xgboard.init <- function(what, watchnames, maximizer, log) { envir <- new.env() envir[["persist"]] <- matrix(rep(c(0, 0, 0, rep(0, 2 * length(what))), length(watchnames)), nrow = length(watchnames), byrow = TRUE) envir[["params"]] <- list(length(watchnames), maximizer) envir[["timer"]] <- unname(Laurae::timer()) envir[["log"]] <- log envir[["watch"]] <- watchnames envir[["what"]] <- what envir[["loop"]] <- 1 cat(paste(c("Iteration", "Watchlist", "CurrentTime", "Time", what, paste0(what, "Improve")), collapse = ","), "\n", sep = "", file = log, append = FALSE) return(envir) }
expected <- eval(parse(text="c(1.5, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60)")); test(id=0, code={ argv <- eval(parse(text="list(c(1.5, 1.5, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60), FALSE, FALSE, NA)")); .Internal(`unique`(argv[[1]], argv[[2]], argv[[3]], argv[[4]])); }, o=expected);
test_that("namespace operators always evaluated locally", { expect_equal(partial_eval(quote(base::sum(1, 2))), 3) expect_equal(partial_eval(quote(base:::sum(1, 2))), 3) }) test_that("namespaced calls to dplyr functions are stripped", { expect_equal(partial_eval(quote(dplyr::n())), expr(n())) }) test_that("use quosure environment for unevaluted formulas", { x <- 1 expect_equal(partial_eval(expr(~x)), quote(~1)) }) test_that("can look up inlined function", { expect_equal( partial_eval(expr((!!mean)(x)), vars = "x"), expr(mean(x)) ) }) test_that("respects tidy evaluation pronouns", { x <- "X" X <- "XX" expect_equal(partial_eval(expr(.data$x)), expr(x)) expect_equal(partial_eval(expr(.data[["x"]])), expr(x)) expect_equal(partial_eval(expr(.data[[x]])), expr(X)) expect_equal(partial_eval(expr(.env$x)), "X") expect_equal(partial_eval(expr(.env[["x"]])), "X") expect_equal(partial_eval(expr(.env[[x]])), "XX") }) test_that("fails with multi-classes", { x <- structure(list(), class = c('a', 'b')) expect_error(partial_eval(x), "Unknown input type", fixed = TRUE) }) test_that("across() translates character vectors", { lf <- lazy_frame(a = 1, b = 2) expect_snapshot(lf %>% summarise(across(a:b, "log"))) expect_snapshot(lf %>% summarise(across(a:b, "log", base = 2))) expect_snapshot(lf %>% summarise(across(a, c("log", "exp")))) out <- lf %>% summarise(across(a:b, c(x = "log", y = "exp"))) expect_equal(colnames(out), c("a_x", "a_y", "b_x", "b_y")) }) test_that("across() translates functions", { lf <- lazy_frame(a = 1, b = 2) expect_snapshot(lf %>% summarise(across(a:b, log))) expect_snapshot(lf %>% summarise(across(a:b, log, base = 2))) expect_snapshot(lf %>% summarise(across(a:b, list(log, exp)))) out <- lf %>% summarise(across(a:b, list(x = log, y = exp))) expect_equal(colnames(out), c("a_x", "a_y", "b_x", "b_y")) }) test_that("untranslatable functions are preserved", { lf <- lazy_frame(a = 1, b = 2) expect_snapshot(lf %>% summarise(across(a:b, SQL_LOG))) }) test_that("across() translates formulas", { lf <- lazy_frame(a = 1, b = 2) expect_snapshot(lf %>% summarise(across(a:b, ~ log(.x, 2)))) expect_snapshot(lf %>% summarise(across(a:b, list(~ log(.x, 2))))) }) test_that("across() translates NULL", { lf <- lazy_frame(a = 1, b = 2) expect_snapshot(lf %>% mutate(across(a:b))) }) test_that("can control names", { lf <- lazy_frame(a = 1, b = 2) out <- lf %>% summarise(across(a:b, c("log", "exp"), .names = "{.fn}_{.col}")) expect_equal(colnames(out), c("log_a", "exp_a", "log_b", "exp_b")) }) test_that("old _at functions continue to work", { withr::local_options(lifecycle_verbosity = "quiet") lf <- lazy_frame(a = 1, b = 2) expect_snapshot(lf %>% dplyr::summarise_at(dplyr::vars(a:b), "sum")) expect_snapshot(lf %>% dplyr::summarise_at(dplyr::vars(a:b), sum)) expect_snapshot(lf %>% dplyr::summarise_at(dplyr::vars(a:b), ~ sum(.))) }) test_that("if_all translations names, strings, and formulas", { lf <- lazy_frame(a = 1, b = 2) expect_equal(capture_if_all(lf, if_all(a, is.na)), expr(is.na(a))) expect_equal(capture_if_all(lf, if_all(a, "is.na")), expr(is.na(a))) expect_equal(capture_if_all(lf, if_all(a, ~ is.na(.))), expr(is.na(a))) }) test_that("if_all collapses multiple expresions", { lf <- lazy_frame(data.frame(a = 1, b = 2)) expect_equal( capture_if_all(lf, if_all(everything(), is.na)), expr(is.na(a) & is.na(b)) ) }) test_that("if_all/any works in filter()", { lf <- lazy_frame(a = 1, b = 2) expect_snapshot(lf %>% filter(if_all(a:b, ~ . > 0))) expect_snapshot(lf %>% filter(if_any(a:b, ~ . > 0))) }) test_that("if_all/any works in mutate()", { lf <- lazy_frame(a = 1, b = 2) expect_snapshot(lf %>% mutate(c = if_all(a:b, ~ . > 0))) expect_snapshot(lf %>% mutate(c = if_any(a:b, ~ . > 0))) })
cat("\014") rm(list = ls()) setwd("~/git/of_dollars_and_data") source(file.path(paste0(getwd(),"/header.R"))) library(scales) library(readxl) library(lubridate) library(zoo) library(ggrepel) library(tidyverse) folder_name <- "0210_max_401k" out_path <- paste0(exportdir, folder_name) dir.create(file.path(paste0(out_path)), showWarnings = FALSE) annual_savings <- 10000 cap_gains <- 0.15 annual_dividend <- 0.02 annual_growth <- 0.05 inc_tax <- 0.24 plan_fee <- 0.00 final_results <- data.frame() tax_rates <- seq(0, 0.34, 0.01) counter <- 1 for(tax_rate_retire in tax_rates){ n_years <- 30 df <- data.frame() for(i in 1:n_years){ df[i, "year"] <- i if(i == 1){ df[i, "value_roth401k"] <- annual_savings df[i, "value_trad401k"] <- annual_savings/(1-inc_tax) df[i, "post_tax_dividend"] <- 0 df[i, "unrealized_gains"] <- 0 df[i, "cum_unrealized_gains"] <- 0 df[i, "value_taxable"] <- annual_savings df[i, "liquid_taxable"] <- annual_savings } else{ df[i, "post_tax_dividend"] <- (df[(i-1), "value_taxable"] * annual_dividend) * (1 - cap_gains) df[i, "unrealized_gains"] <- df[(i-1), "value_taxable"] * annual_growth df[i, "cum_unrealized_gains"] <- df[(i-1), "cum_unrealized_gains"] + df[i, "unrealized_gains"] df[i, "value_taxable"] <- df[(i-1), "value_taxable"] + df[i, "unrealized_gains"] + df[i, "post_tax_dividend"] + annual_savings df[i, "liquid_taxable"] <- df[i, "value_taxable"] - (cap_gains*df[i, "cum_unrealized_gains"]) df[i, "value_roth401k"] <- (df[(i-1), "value_roth401k"] * (1+annual_growth+annual_dividend-plan_fee)) + annual_savings df[i, "value_trad401k"] <- (df[(i-1), "value_trad401k"] * (1+annual_growth+annual_dividend)) + (annual_savings/(1-inc_tax)) } df[i, "liquid_trad401k"] <- df[i, "value_trad401k"] * (1-tax_rate_retire) df[i, "roth401k_tot_premium"] <- df[i, "value_roth401k"]/df[i, "liquid_taxable"] df[i, "trad401k_tot_premium"] <- df[i, "liquid_trad401k"]/df[i, "liquid_taxable"] df[i, "roth401k_ann_premium"] <- df[i, "roth401k_tot_premium"]^(1/i) - 1 df[i, "trad401k_ann_premium"] <- df[i, "trad401k_tot_premium"]^(1/i) - 1 } final_results[counter, "tax_rate"] <- tax_rate_retire final_results[counter, "trad401k_ann_premium"] <- df[nrow(df), "trad401k_ann_premium"] final_results[counter, "trad401k_tot_premium"] <- df[nrow(df), "trad401k_tot_premium"] final_results[counter, "trad401k_value_premium"] <- df[nrow(df), "liquid_trad401k"] - df[nrow(df), "liquid_taxable"] counter <- counter + 1 } file_path <- paste0(out_path, "/roth_vs_taxable_balance_40yr_redux.jpeg") source_string <- paste0("Source: Simulated data (OfDollarsAndData.com)") note_string <- str_wrap(paste0("Note: Assumes a ", 100*(annual_growth+annual_dividend), "% annual growth rate, a ", 100*cap_gains, "% tax rate on capital gains, ", format_as_dollar(annual_savings, 0), " in annual savings, and a ", n_years, "-year investment period."), width = 85) to_plot <- df %>% select(year, value_roth401k, liquid_taxable) %>% rename(`Roth 401k` = value_roth401k, `Taxable Account` = liquid_taxable) %>% gather(-year, key=key, value=value) text_labels <- to_plot %>% filter(year == max(to_plot$year)) %>% mutate(label = paste0(format_as_dollar(value/1000000, 1), "M")) plot <- ggplot(to_plot, aes(x = year, y = value, col = key)) + geom_line() + geom_text(data=text_labels, aes(x=year, y=value, col = key, label = label), hjust=-0.1, show.legend = FALSE) + scale_color_manual(values = c("blue", "black")) + scale_y_continuous(label = dollar) + scale_x_continuous(limits = c(0, 35)) + of_dollars_and_data_theme + theme(legend.title = element_blank(), legend.position = "bottom") + ggtitle(paste0("Roth 401(k) vs. Taxable Account Value")) + labs(x = "Year" , y = paste0("Value After Taxes"), caption = paste0("\n", source_string, "\n", note_string)) ggsave(file_path, plot, width = 15, height = 12, units = "cm")
context("convertDiscrete") test_that("discrete param NameToValue", { f = function(x) 2 * x p = makeDiscreteParam(id = "x", values = list(a = "char", b = 2L, c = 2.2, d = f, "e")) expect_equal(discreteNameToValue(p, "b"), 2L) expect_equal(discreteNameToValue(p, "c"), 2.2) expect_equal(discreteNameToValue(p, "e"), "e") expect_error(discreteNameToValue(p, ""), "Names not used") p = makeIntegerParam(id = "y") expect_error(discreteNameToValue(p, "a")) p = makeDiscreteParam("x", values = c(a = 1e-8, b = 1e-9)) expect_equal(discreteNameToValue(p, "a"), 1e-8) expect_equal(discreteNameToValue(p, "b"), 1e-9) }) test_that("discrete param ValueToName", { f = function(x) 2 * x p = makeDiscreteParam(id = "x", values = list(a = "char", b = 2L, c = 2.2, d = f, "e")) expect_equal(discreteValueToName(p, 2L), "b") expect_equal(discreteValueToName(p, 2.2), "c") expect_equal(discreteValueToName(p, "e"), "e") expect_equal(discreteValueToName(p, f), "d") expect_error(discreteValueToName(p, 3), "Value not found") expect_error(discreteNameToValue(p, 2)) p = makeIntegerParam(id = "y") expect_error(discreteNameToValue(p, "a")) p = makeDiscreteParam("x", values = c(a = 1e-8, b = 1e-9)) expect_equal(discreteValueToName(p, 1e-8), "a") expect_equal(discreteValueToName(p, 1e-9), "b") }) test_that("discrete vec param NameToValue", { f = function(x) 2 * x p = makeDiscreteVectorParam(id = "x", len = 2, values = list(a = "char", b = 2L, c = c(2.2, 3.3), d = f, "e")) expect_equal(discreteNameToValue(p, c("a", "b")), list(a = "char", b = 2L)) expect_equal(discreteNameToValue(p, c("e", "b")), list(e = "e", b = 2L)) expect_equal(discreteNameToValue(p, c("c", "d")), list(c = c(2.2, 3.3), d = f)) }) test_that("discrete vec param ValueToName", { f = function(x) 2 * x p = makeDiscreteVectorParam(id = "x", len = 2, values = list(a = "char", b = 2L, c = 2.2, d = f, "e")) expect_equal(discreteValueToName(p, list(2L, "char")), c("b", "a")) expect_equal(discreteValueToName(p, list(2.2, f)), c("c", "d")) })
`dominant.WGassociation` <- function(o) { attr(o,"pvalues")[,"dominant"] }
checkVec <- function(val){ if (length(val) == 0){ return("no inputted value") }else if (length(val)>1){ return("Multiple values inputted (see table below)") }else { return(val) } }
kmeans_clustersRProg<-function(codebook,k=5,times=5,seed=NULL) { if (is.null(seed)) {times<-times } else {times<-1} codebook<-as.matrix(codebook) n_max<-k c_max<-times Machprest<-.Machine CENTROIDS<-vector(mode = "list", length = n_max) CLUSNum<-rep(0,nrow(codebook)) ERR<-NULL IND<-NULL SEED<-NULL withProgress(message = paste0('Total training times = ',times), value = 0, { for (j in c(2:n_max)) { best<-Machprest$double.xmax for (i in c(1:c_max)) {KM<-som_kmeansRProg(codebook,j,100,seed=seed); if (KM$err<best) {k_best<-KM$clusters; c_best<-KM$centroids; best<-KM$err; Seed<-KM$seed} incProgress(1/times, detail = paste("Time:", i)) } CENTROIDS[[j]]<-c_best CLUSNum<-cbind(CLUSNum,k_best) ERR<-c(ERR,best) ind<-db_indexR(codebook,k_best,c_best) IND<-c(IND,ind) SEED<-c(SEED,Seed) } }) result<-list("centroids" = CENTROIDS, "clusNum" = CLUSNum, "err" = ERR, "ind"=IND, "seed"=SEED) return(result) }
esr_pars <- function(x, ...) { UseMethod("esr_pars") }
h2o.extendedIsolationForest <- function(training_frame, x, model_id = NULL, ignore_const_cols = TRUE, categorical_encoding = c("AUTO", "Enum", "OneHotInternal", "OneHotExplicit", "Binary", "Eigen", "LabelEncoder", "SortByResponse", "EnumLimited"), ntrees = 100, sample_size = 256, extension_level = 0, seed = -1) { training_frame <- .validate.H2OFrame(training_frame, required=TRUE) parms <- list() parms$training_frame <- training_frame if(!missing(x)) parms$ignored_columns <- .verify_datacols(training_frame, x)$cols_ignore if (!missing(model_id)) parms$model_id <- model_id if (!missing(ignore_const_cols)) parms$ignore_const_cols <- ignore_const_cols if (!missing(categorical_encoding)) parms$categorical_encoding <- categorical_encoding if (!missing(ntrees)) parms$ntrees <- ntrees if (!missing(sample_size)) parms$sample_size <- sample_size if (!missing(extension_level)) parms$extension_level <- extension_level if (!missing(seed)) parms$seed <- seed model <- .h2o.modelJob('extendedisolationforest', parms, h2oRestApiVersion=3, verbose=FALSE) return(model) } .h2o.train_segments_extendedIsolationForest <- function(training_frame, x, ignore_const_cols = TRUE, categorical_encoding = c("AUTO", "Enum", "OneHotInternal", "OneHotExplicit", "Binary", "Eigen", "LabelEncoder", "SortByResponse", "EnumLimited"), ntrees = 100, sample_size = 256, extension_level = 0, seed = -1, segment_columns = NULL, segment_models_id = NULL, parallelism = 1) { model_id <- NULL verbose <- NULL destination_key <- NULL training_frame <- .validate.H2OFrame(training_frame, required=TRUE) parms <- list() parms$training_frame <- training_frame if(!missing(x)) parms$ignored_columns <- .verify_datacols(training_frame, x)$cols_ignore if (!missing(ignore_const_cols)) parms$ignore_const_cols <- ignore_const_cols if (!missing(categorical_encoding)) parms$categorical_encoding <- categorical_encoding if (!missing(ntrees)) parms$ntrees <- ntrees if (!missing(sample_size)) parms$sample_size <- sample_size if (!missing(extension_level)) parms$extension_level <- extension_level if (!missing(seed)) parms$seed <- seed segment_parms <- list() if (!missing(segment_columns)) segment_parms$segment_columns <- segment_columns if (!missing(segment_models_id)) segment_parms$segment_models_id <- segment_models_id segment_parms$parallelism <- parallelism segment_models <- .h2o.segmentModelsJob('extendedisolationforest', segment_parms, parms, h2oRestApiVersion=3) return(segment_models) }
columns <- function(z){ x <- as.matrix(z) n <- ncol(x) xlist <- vector("list", n) for(i in 1:n) xlist[[i]] <- x[,i] if(length(cn <- colnames(x)) == n) names(xlist) <- cn xlist } rows <- function(z){ x <- as.matrix(z) n <- nrow(x) xlist <- vector("list", n) for(i in 1:n) xlist[[i]] <- x[i,] if(length(rn <- rownames(x)) == n) names(xlist) <- rn xlist }
interpolate_spline <- function(observations, targets, value, lon_obs = lon, lat_obs = lat, lon_targets = lon, lat_targets = lat, k = 50) { if (!requireNamespace("mgcv", quietly = TRUE)) { stop("mgcv is needed for this function to work. Install it via install.packages(\"mgcv\")", call. = FALSE) } lon_targets <- deparse(substitute(lon_targets)) lat_targets <- deparse(substitute(lat_targets)) lon_obs <- deparse(substitute(lon_obs)) lat_obs <- deparse(substitute(lat_obs)) value <- deparse(substitute(value)) sos <- deparse(substitute("sos")) names(observations)[names(observations) == lon_obs] <- "lon" names(observations)[names(observations) == lat_obs] <- "lat" names(targets)[names(targets) == lon_targets] <- "lon" names(targets)[names(targets) == lon_targets] <- "lon" f <- as.formula(paste0(value, "~ s(lat, lon,", "bs = ", sos, ", m = -1, k = ", k, ")")) pred_gam <- tryCatch( { mgcv::gam(f, data = observations) }, error = function(e) { stop("Error: dimension k is chosen too large (default k = 50). Reduce dimension k manually as argument in function call.", call. = FALSE) }) response <- as.numeric(mgcv::predict.gam(pred_gam, targets, type = "response")) targets[,paste0(value, "_pred")] <- response return(targets) }
require(FrF2) colpick(6, 2) colpick(6, 3, estimable=compromise(6, 4)$requirement) colpick(6, 3, estimable=rbind(4, c(1:3,5:6))) colpick("6-1.1", 3, estimable=compromise(6, 4)$requirement) colpick(catlg["6-1.1"], 3, estimable=compromise(6, 4)$requirement) colpick(catlg["8-2.1"], 1) colpick("9-3.2", 2) tail(colpick(55, 2)$clear2fis) phimax(8, 2) phimax(8, 2, c(4,3,1)) phimax(9, 4) X <- rbind(c(1,1,1,0,0,0,1), c(1,1,0,1,1,1,0)) blockgencreate(X, 2) Xcalc(rbind(c(1,1,0,0),c(0,1,1,1)), gen=c("AB","BCD")) Xcalc(rbind(c(1,1,0,0),c(0,1,1,1)), gen=list(c(1,2),2:4)) Xcalc(rbind(c(1,1,0,0),c(0,1,1,1)), gen=c(3,14)) Xcalc(rbind(c(1,1,0,0),c(0,1,1,1)), gen=catlg[nruns(catlg)==16 & res(catlg)==4]) plangodolphin <- FF_from_X(colpick(4, 2)$X, randomize=FALSE) cbind(run.order(plangodolphin), plangodolphin)
context("miceFast-impute_N") test_that("impute_N", { set.seed(1234) data <- cbind(as.matrix(airquality[, -5]), intercept = 1, index = 1:nrow(airquality)) weights <- rgamma(nrow(data), 3, 3) groups <- as.numeric(airquality[, 5]) model <- new(miceFast) model$set_data(data) model$set_w(weights) model$set_g(groups) imp_miceFast <- model$impute_N("lm_bayes", 1, c(3, 4, 5, 6), 10000)$imputations imp_miceFast_noise <- model$impute_N("lm_noise", 1, c(3, 4, 5, 6), 10000)$imputations imp_miceFast_pred <- model$impute("lm_pred", 1, c(3, 4, 5, 6))$imputations imp_miceFast_pmm <- model$impute_N("pmm", 1, c(3, 4, 5, 6), 1)$imputations expect_true(mean((imp_miceFast - imp_miceFast_pred)**2) < 1) expect_true(mean((imp_miceFast_noise - imp_miceFast_pred)**2) < 1) expect_true(mean((imp_miceFast_pmm - imp_miceFast_pred)**2) < 1000) mse_pmm_kbig <- mean(replicate(100, mean((model$impute_N("pmm", 1, c(3, 4, 5, 6), 100)$imputations - imp_miceFast_pred)**2))) mse_pmm_ksmall <- mean(replicate(100, mean((model$impute_N("pmm", 1, c(3, 4, 5, 6), 1)$imputations - imp_miceFast_pred)**2))) expect_true(mse_pmm_ksmall < mse_pmm_kbig) rm(model) })
makeRLearner.regr.bcart = function() { makeRLearnerRegr( cl = "regr.bcart", package = "tgp", par.set = makeParamSet( makeDiscreteLearnerParam(id = "bprior", default = "bflat", values = c("b0", "b0not", "bflat", "bmle", "bmznot", "bmzt")), makeNumericVectorLearnerParam(id = "tree", len = 2, default = c(0.5, 2), lower = c(0, 0), upper = c(1, Inf)), makeIntegerVectorLearnerParam(id = "BTE", len = 3, default = c(2000, 7000, 2), lower = 0), makeIntegerLearnerParam(id = "R", default = 1, lower = 1), makeLogicalLearnerParam(id = "m0r1", default = TRUE), makeUntypedLearnerParam(id = "itemps", default = NULL), makeLogicalLearnerParam(id = "krige", default = TRUE), makeLogicalLearnerParam(id = "zcov", default = FALSE), makeLogicalLearnerParam(id = "Ds2x", default = FALSE), makeLogicalLearnerParam(id = "improv", default = FALSE), makeLogicalLearnerParam(id = "trace", default = FALSE, tunable = FALSE), makeIntegerLearnerParam(id = "verb", default = 1L, lower = 0L, upper = 4L, tunable = FALSE) ), properties = c("numerics", "se", "factors"), name = "Bayesian CART", short.name = "bcart", callees = "bcart" ) } trainLearner.regr.bcart = function(.learner, .task, .subset, .weights = NULL, ...) { d = getTaskData(.task, .subset, target.extra = TRUE) col.types = vcapply(d$data, function(x) class(x)) factor.ind = (col.types == "factor") if (any(factor.ind)) { d.num = d$data[, !factor.ind, drop = FALSE] n.num = ncol(d.num) d.factor = d$data[, factor.ind, drop = FALSE] d.factor = createDummyFeatures(d.factor, method = "reference") d$data = cbind(d.num, d.factor) return(tgp::bcart(X = d$data, Z = d$target, basemax = n.num, pred.n = FALSE, ...)) } else { return(tgp::bcart(X = d$data, Z = d$target, pred.n = FALSE, ...)) } } predictLearner.regr.bcart = function(.learner, .model, .newdata, ...) { col.types = vcapply(.newdata, function(x) class(x)) factor.ind = (col.types == "factor") if (any(factor.ind)) { newdata.num = .newdata[, !factor.ind, drop = FALSE] newdata.factor = .newdata[, factor.ind, drop = FALSE] newdata.factor = createDummyFeatures(newdata.factor, method = "reference") newdata = cbind(newdata.num, newdata.factor) p = predict(.model$learner.model, XX = newdata, pred.n = FALSE, ...) } else { p = predict(.model$learner.model, XX = .newdata, pred.n = FALSE, ...) } if (.learner$predict.type == "response") { return(p$ZZ.km) } else { return(cbind(p$ZZ.km, sqrt(p$ZZ.ks2))) } }
context("Test colouring of dendrograms") test_that("Can find leaf colours", { hc <- hclust(dist(USArrests), "ave") dend <- as.dendrogram(hc) colours5=c("red",'green','blue','cyan','magenta') cdendk5 <- colour_clusters(dend,k=5,col=colours5) leafcolours <- unlist(dendrapply(cdendk5,function(n) if(is.leaf(n)) structure(attr(n,'edgePar')$col, .Names=attr(n,'label')) else NULL)) expect_that(leaf_colours(cdendk5), equals(leafcolours)) no_colours <- structure(rep(NA_character_,length(leafcolours)), .Names=names(leafcolours)) expect_that(leaf_colours(dend),equals(no_colours), 'no edge colours in dendrogram') expect_that(leaf_colours(cdendk5,'label'),equals(no_colours), 'no label colours in dendrogram') expect_that(leaf_colours(cdendk5,'node'),equals(no_colours), 'no node colours ') }) test_that("Colour a dendrogram by cluster identity", { hc <- hclust(dist(USArrests), "ave") dend <- as.dendrogram(hc) cdend2 <- colour_clusters(dend,k=2,col=c("red",'green')) leafcolours <- leaf_colours(cdend2) expect_that(labels(hc), equals(names(leafcolours))) expect_equivalent(rep(c("red",'green'),c(16,34)),leafcolours) colours5=c("red",'green','blue','cyan','magenta') cdend5 <- colour_clusters(dend,k=5,col=colours5) leafcolours <- leaf_colours(cdend5) expect_that(labels(hc), equals(names(leafcolours))) expect_equivalent(rep(colours5,c(2L,14L,14L,10L,10L)),leafcolours) }) test_that("Colouring a dendrogram by cutting on height or number of groups", { hc <- hclust(dist(USArrests), "ave") dend <- as.dendrogram(hc) colours5=c("red",'green','blue','cyan','magenta') cdendk5 <- colour_clusters(dend,k=5,col=colours5) cdendh50 <- colour_clusters(dend,h=50,col=colours5) expect_that(cdendk5, equals(cdendh50)) }) test_that("Can cut/colour an hclust object returning a dendrogram", { hc <- hclust(dist(USArrests), "ave") dend <- as.dendrogram(hc) colours5=c("red",'green','blue','cyan','magenta') cdendk5 <- colour_clusters(dend,k=5,col=colours5) chck5 <- colour_clusters(hc,k=5,col=colours5) expect_that(cdendk5, equals(chck5)) }) test_that("Can colour a dendrogram and add group labels", { hc <- hclust(dist(USArrests), "ave") dend <- as.dendrogram(hc) colours5=c("red",'green','blue','cyan','magenta') cdendk51 <- colour_clusters(dend,k=5,col=colours5,groupLabels=TRUE) cdendk52 <- colour_clusters(dend,k=5,col=colours5,groupLabels=1:5) cdendk53 <- colour_clusters(dend,k=5,col=colours5,groupLabels=LETTERS[1:5]) cdendk54 <- colour_clusters(dend,k=5,col=colours5,groupLabels=as.roman) }) test_that("Can colour a dendrogram with non-unique labels",{ dmat=structure(c(4.66, 2.72, 2.75, 2.71, 4.21, 2.83, 3.45, 2.26, 3.4, 2.68, 0.74, 3, 2.32, 5.09, 2.96), Labels = c("A", "B", "C", "D", "E", "F"), Size = 6L, class = "dist", Diag = FALSE, Upper = FALSE) dmat2=structure(c(4.66, 2.72, 2.75, 2.71, 4.21, 2.83, 3.45, 2.26, 3.4, 2.68, 0.74, 3, 2.32, 5.09, 2.96), Labels = c("A", "A", "B", "A", "B", "A"), Size = 6L, class = "dist", Diag = FALSE, Upper = FALSE) hc=hclust(dmat) hc2=hclust(dmat2) pdf(file = tf <- tempfile(fileext = '.pdf')) plot(hc) unlink(tf) expect_is(hcd<-colour_clusters(hc, k=2), 'dendrogram') expect_is(hcd2<-colour_clusters(hc2, k=2), 'dendrogram') expect_equal(unname(leaf_colors(hcd)),unname(leaf_colors(hcd2))) })
setMethod("dim", "timeSeries", function(x) attr(x, "dim")) setReplaceMethod("dim", "timeSeries", function(x, value) { if (is.null(value)) return(as.vector(x)) else x } ) setMethod("colnames", "timeSeries", function(x, do.NULL = TRUE, prefix = "col") x@units ) setMethod("rownames", "timeSeries", function (x, do.NULL = TRUE, prefix = "row") { if (length(x@positions) > 0) as.character(time(x)) else NULL } ) setMethod("dimnames", "timeSeries", function(x) { list(rownames(x),colnames(x)) } ) setMethod("colnames<-", "timeSeries", function(x, value) { units <- as.character(value) if(!length(units)) if (x@format == "counts") units <- paste("SS", seq(NCOL(x)), sep = ".") else units <- paste("TS", seq(NCOL(x)), sep = ".") if (length(units) != NCOL(x)) stop("length of 'colnames' not equal to array extent",call.=FALSE) x@units <- units colnames([email protected]) <- units x } ) setMethod("rownames<-", c("timeSeries", "timeDate"), function (x, value) { .timeSeries( data = getDataPart(x), charvec = as.numeric(value, "sec"), units = colnames(x), format = value@format, FinCenter = value@FinCenter, recordIDs = x@recordIDs, title = x@title, documentation = x@documentation) } ) setMethod("rownames<-", "timeSeries", function (x, value) { if (is.null(value)) return(.signalSeries(data = getDataPart(x), units = colnames(x), recordIDs = x@recordIDs, title = x@title, documentation = x@documentation)) charvec <- timeDate(charvec = value) if (any(is.na(charvec))) .signalSeries(data = getDataPart(x), units = colnames(x), recordIDs = x@recordIDs, title = x@title, documentation = x@documentation) else .timeSeries(data = getDataPart(x), charvec = as.numeric(charvec, "sec"), units = colnames(x), format = charvec@format, FinCenter = charvec@FinCenter, recordIDs = x@recordIDs, title = x@title, documentation = x@documentation) } ) setMethod("dimnames<-", c("timeSeries", "list"), function(x, value) { rownames(x) <- value[[1]] colnames(x) <- value[[2]] x } ) setMethod("names", "timeSeries", function(x) c(colnames(x), names(x@recordIDs))) setReplaceMethod("names", "timeSeries", function(x, value) { nc <- ncol(x) nv <- length(value) nr <- length(x@recordIDs) colnames(x) <- value[seq.int(nv)][seq.int(nc)] if (nv > nc) names(x@recordIDs) <- value[-seq.int(nc)][seq.int(nr)] x })