code
stringlengths
1
13.8M
do.dspp <- function(X, label, ndim=2, preprocess=c("center","scale","cscale","decorrelate","whiten"), lambda=1.0, rho=1.0){ aux.typecheck(X) n = nrow(X) p = ncol(X) label = check_label(label, n) ulabel = unique(label) for (i in 1:length(ulabel)){ if (sum(label==ulabel[i])==1){ stop("* do.dspp : no degerate class of size 1 is allowed.") } } if (any(is.na(label))||(any(is.infinite(label)))){stop("* Supervised Learning : any element of 'label' as NA or Inf will simply be considered as a class, not missing entries.") } ndim = as.integer(ndim) if (!check_ndim(ndim,p)){stop("* do.dspp : 'ndim' is a positive integer in [1, if (missing(preprocess)){ algpreprocess = "center" } else { algpreprocess = match.arg(preprocess) } lambda = as.double(lambda) if (!check_NumMM(lambda, 0, 1e+10, compact=FALSE)){stop("* do.dspp : 'lambda' is a positive real number.")} rho = as.double(rho) if (!check_NumMM(rho, 0, 1e+10, compact=TRUE)){stop(" do.dspp : 'rho' is a nonnegative real number.")} tmplist = aux.preprocess.hidden(X,type=algpreprocess,algtype="linear") trfinfo = tmplist$info pX = tmplist$pX W = array(0,c(n,n)) for (i in 1:n){ xi = matrix(pX[i,],ncol=1) tgtidx = setdiff(which(label==label[i]),i) Xi = t(pX[tgtidx,]) W[tgtidx,i] = dspp_compute_wi(xi,Xi,lambda) } radius = rep(0,n) for (i in 1:n){ tgtrow = as.vector(W[i,]) idxmax = which(tgtrow==max(tgtrow)) if (length(idxmax)>1){ idxmax = as.integer(idxmax[1]) } maxdist = as.vector(pX[i,])-as.vector(pX[idxmax,]) radius[i] = sqrt(sum(maxdist*maxdist)) } B = array(0,c(n,n)) for (i in 1:n){ veci = as.vector(pX[i,]) for (j in 1:n){ vecj = as.vector(pX[j,]) if (i!=j){ if (dspp_distnorm(veci,vecj)<=radius[i]){ if (label[i]!=label[j]){ B[i,j] = 1 } } } } } classmean = array(0,c(length(ulabel), p)) for (i in 1:length(ulabel)){ partidx = which(label==ulabel[i]) classmean[i,] = colMeans(pX[partidx,]) } Sw = array(0,c(p,p)) for (i in 1:n){ cvec = pX[i,] clabel = label[i] tgtmat = pX[-i,] tgtlabel = label[-i] Smat = dspp_compute_Sw(cvec,clabel,tgtmat,tgtlabel,ulabel,classmean,as.double(radius[i])) Sw = Sw+Smat } W = (W+t(W))/2 B = (B+t(B))/2 Sw= (Sw+t(Sw))/2 Lw = diag(rowSums(W))-W Lb = diag(rowSums(B))-B LHS = ((t(pX)%*%Lw%*%pX) + (rho*Sw)) RHS = (t(pX)%*%Lb%*%pX) projection = aux.geigen(LHS,RHS,ndim,maximal=FALSE) result = list() result$Y = pX%*%projection result$trfinfo = trfinfo result$projection = projection return(result) } dspp_compute_wi <- function(xi, Xi, lambda){ n = ncol(Xi) si = CVXR::Variable(n) obj = (CVXR::p_norm(xi-(Xi%*%si),p=2) + lambda*CVXR::p_norm(si,p=1)) constr = list(si>=0) prob = CVXR::Problem(Minimize(obj), constr) result = solve(prob) return(as.vector(result$getValue(si))) } dspp_distnorm <- function(vec1, vec2){ vecdiff = as.vector(vec1)-as.vector(vec2) output = as.double(sqrt(sum(vecdiff*vecdiff))) return(output) } dspp_compute_Sw <- function(cvec, clabel, tgtmat, tgtlabel, ulabel, classmean, radius){ p = length(cvec) Smat = array(0,c(p,p)) ntgt = nrow(tgtmat) for (i in 1:ntgt){ vecdiff = as.vector(cvec)-as.vector(tgtmat[i,]) if (sqrt(sum(vecdiff*vecdiff))<radius){ if (tgtlabel[i]!=clabel){ tgtvec = (tgtmat[i,]) tgtidx = which(ulabel==clabel) meanvec = (classmean[tgtidx,]) mvdiff = as.vector(tgtvec)-as.vector(meanvec) Smat = Smat + outer(mvdiff,mvdiff) } } } return(Smat) }
options(width = 75, digits = 2, scipen = 5) set.seed(0) library(portfolio) load("tradelist.RData") p.current <- portfolios[["p.current.abs"]] p.target <- portfolios[["p.target.abs"]] data <- data.list[["data.abs"]] sorts <- list(alpha = 1.5, ret.1.d = 1) tl <- new("tradelist", orig = p.current, target = p.target, sorts = sorts, turnover = 2000, chunk.usd = 2000, data = data, to.equity = FALSE) p.current@shares[, c("shares", "price")] p.target@shares[, c("shares", "price")] tl@candidates[, c("side", "shares", "mv")] tmp <- data.frame(side = tl@candidates[, "side"], alpha = tl@ranks[, "alpha"]) row.names(tmp) <- tl@candidates$id tmp <- tmp[order(tmp$alpha, decreasing = TRUE),] tmp tl@ranks$rank <- rank(-tl@ranks$alpha, na.last = TRUE, ties.method = "random") alpha <- tl@ranks[,!names(tl@ranks) %in% "ret.1.d"] alpha$sort <- "alpha" alpha[order(alpha$rank), c("rank", "side", "alpha", "shares", "mv")] tmp <- tl@ranks[order(tl@ranks$ret.1.d), c("side","ret.1.d")] tmp <- cbind(rank = 1:nrow(tmp), tmp) tmp$ret.1.d <- tmp$ret.1.d[order(tmp$ret.1.d, decreasing = TRUE)] row.names(tmp) <- tl@candidates$id tmp.1 <- tl@ranks[order(tl@ranks$alpha, decreasing = TRUE), c("alpha", "ret.1.d")] tmp.1 <- tmp.1 <- cbind(rank = 1:nrow(tmp.1), tmp.1) tmp.1 tmp.2 <- tl@ranks[order(tl@ranks$ret.1.d, decreasing = TRUE), c("alpha", "ret.1.d")] tmp.2 <- cbind(rank = 1:nrow(tmp.2), tmp.2) tmp.2 tl@ranks$rank <- rank(-tl@ranks$ret.1.d, na.last = TRUE, ties.method = "random") ret.1.d <- tl@ranks[,!names(tl@ranks) %in% "alpha"] ret.1.d$sort <- "ret.1.d" alpha.rank.orig <- alpha$rank alpha$rank <- alpha$rank alpha[order(alpha$rank), c("rank", "side", "alpha", "shares", "mv")] ret.1.d[order(ret.1.d$rank), c("rank", "side", "ret.1.d", "shares", "mv")] alpha$rank <- alpha.rank.orig alpha <- alpha[,!names(alpha) %in% "alpha"] ret.1.d <- ret.1.d[,!names(ret.1.d) %in% "ret.1.d"] overall.ranks <- rbind(alpha, ret.1.d) overall.ranks <- overall.ranks[order(overall.ranks$rank), c("id", "sort", "rank", "side", "shares", "mv")] row.names(overall.ranks) <- paste(overall.ranks$id, overall.ranks$sort, sep = ".") overall.ranks[, c("rank", "sort", "side", "shares", "mv")] ranks <- alpha top.ranks <- aggregate(overall.ranks[c("rank")], by = list(id = overall.ranks$id), min) ranks$rank <- top.ranks$rank[match(ranks$id, top.ranks$id)] ranks[order(ranks$rank), c("rank", "shares", "mv")] alpha$rank <- alpha.rank.orig alpha$rank <- alpha$rank / 10 overall.ranks <- data.frame() overall.ranks <- rbind(alpha, ret.1.d) overall.ranks <- overall.ranks[order(overall.ranks$rank), c("id", "sort", "rank", "side", "shares", "mv")] row.names(overall.ranks) <- paste(overall.ranks$id, overall.ranks$sort, sep = ".") overall.ranks[c("rank", "side", "shares", "mv")] top.ranks <- do.call(rbind, lapply(split(overall.ranks, overall.ranks$id), function(x) { x[which.min(x$rank),] })) top.ranks <- top.ranks[order(top.ranks$rank),] top.ranks[c("rank","sort","shares","mv")] ranks <- alpha top.ranks <- aggregate(overall.ranks[c("rank")], by = list(id = overall.ranks$id), min) ranks$rank <- top.ranks$rank[match(ranks$id, top.ranks$id)] alpha$rank <- alpha.rank.orig alpha$rank <- alpha$rank / 1.5 overall.ranks <- data.frame() overall.ranks <- rbind(alpha, ret.1.d) overall.ranks <- overall.ranks[order(overall.ranks$rank), c("id", "sort", "rank", "side", "shares", "mv")] row.names(overall.ranks) <- paste(overall.ranks$id, overall.ranks$sort, sep = ".") overall.ranks[c("rank", "side", "shares", "mv")] top.ranks <- do.call(rbind, lapply(split(overall.ranks, overall.ranks$id), function(x) { x[which.min(x$rank),] })) top.ranks <- top.ranks[order(top.ranks$rank),] top.ranks[c("rank","sort","shares","mv")] ranks <- alpha top.ranks <- aggregate(overall.ranks[c("rank")], by = list(id = overall.ranks$id), min) ranks$rank <- top.ranks$rank[match(ranks$id, top.ranks$id)] tmp <- ranks[order(ranks$rank), c("rank", "sort", "shares", "mv")] tmp$rank <- rank(tmp$rank, ties.method = "first") tmp[order(tmp$rank),c("rank","shares","mv")] r.max <- max(tmp$rank) + 1 r.mult <- 0.15 r.add <- 0.85 tmp$rank.s <- (r.mult * tmp$rank[nrow(tmp):1] / r.max) + r.add rank.s <- tmp tmp[c("rank","shares","mv","rank.s")] tmp$rank.t <- qnorm(tmp$rank.s) tmp[c("rank", "shares", "mv","rank.s", "rank.t")] tl@chunks[order(-tl@chunks$rank.t), c("side", "shares", "mv", "alpha", "ret.1.d", "rank.t", "chunk.shares", "chunk.mv")] trading.volume <- data.frame(rank.t = tl@ranks$rank.t, volume = tl@data$volume[match(tl@ranks$id, tl@data$id)], shares = tl@ranks$shares) row.names(trading.volume) <- tl@ranks$id trading.volume[order(-trading.volume$rank.t),] tl@chunks[order(-tl@chunks$rank.t), c("side", "mv", "alpha", "ret.1.d", "rank.t", "chunk.shares", "chunk.mv", "tca.rank")] tl@chunks[order(tl@chunks$tca.rank, decreasing = TRUE), c("side", "mv", "alpha", "ret.1.d", "rank.t", "chunk.shares", "chunk.mv", "tca.rank")] rank.s[c("rank","shares","mv","rank.s")] rank.t <- rank.s rank.t$rank.t <- qnorm(rank.t$rank.s) rank.t[c("rank","shares","mv","rank.s","rank.t")] misc$rank.s head(tl@swaps[, c("tca.rank.enter", "tca.rank.exit", "rank.gain")]) [email protected][, c("tca.rank.enter", "tca.rank.exit", "rank.gain")] [email protected][, c("side", "mv", "alpha", "ret.1.d", "rank.t", "chunk.shares", "chunk.mv", "tca.rank")] tl@actual[, !names(tl@actual) %in% c("id")] rm(list = ls()) load("tradelist.RData") p.current <- portfolios[["p.current.lo"]] p.target <- portfolios[["p.target.lo"]] data <- data.list[["data.lo"]] oe <- portfolio:::mvShort(p.current) + portfolio:::mvLong(p.current) te <- portfolio:::mvShort(p.target) + portfolio:::mvLong(p.target) sorts <- list(alpha = 1, ret.1.d = 1.1) tl <- new("tradelist", orig = p.current, target = p.target, chunk.usd = 2000, sorts = sorts, turnover = 30250, target.equity = te, data = data) nt <- mvCandidates(tl) p.current.shares <- p.current@shares[, c("shares", "price")] p.current.shares p.target.shares <- p.target@shares[, c("shares", "price")] p.target.shares sub.candidates <- tl@candidates[,!names(tl@candidates) %in% "id"] sub.candidates sorts <- list(alpha = 1, ret.1.d = 1.1) row.names(data) <- data$id sub.data <- data[, c("id", "volume", "price.usd", "alpha", "ret.1.d")] sub.data tl <- new("tradelist", orig = p.current, target = p.target, chunk.usd = 2000, sorts = sorts, turnover = 30250, data = data) tl <- new("tradelist", orig = p.current, target = p.target, chunk.usd = 2000, sorts = sorts, turnover = 30250, target.equity = 47500, data = data) tl@candidates ranks <- [email protected]$ret.1.d ranks <- split(ranks, ranks$side) ranks$B$rank <- 1:nrow(ranks$B) ranks$S$rank <- 1:nrow(ranks$S) ranks tmp <- rbind(ranks$B, ranks$S)[order(rbind(ranks$B, ranks$S)[["rank"]]),] tmp[,!names(tmp) %in% "id"] [email protected][["alpha"]][,!names([email protected][["alpha"]]) %in% "id"] ranks <- [email protected][["ret.1.d"]] ranks[["rank"]] <- ranks[["rank"]]/sorts[["ret.1.d"]] ranks [email protected][["alpha"]] alpha <- [email protected][["alpha"]] ret.1.d <- [email protected][["ret.1.d"]] alpha <- alpha[,!names(alpha) %in% "alpha"] ret.1.d <- ret.1.d[,!names(ret.1.d) %in% "ret.1.d"] duplicates <- rbind(alpha, ret.1.d) duplicates <- duplicates[order(duplicates$id),] row.names(duplicates) <- 1:nrow(duplicates) duplicates tl.ranks <- tl@ranks top.ranks <- aggregate(duplicates[c("rank")], by = list(id = duplicates$id), min) tl.ranks$rank <- top.ranks$rank[match(tl.ranks$id, top.ranks$id)] tl.ranks[order(tl.ranks$rank), !names(tl@ranks) %in% c("id", "alpha", "ret.1.d", "rank.t")] tl.ranks$rank <- rank(tl.ranks$rank) tl.ranks <- tl.ranks[, !names(tl.ranks) %in% c("id", "alpha", "ret.1.d")] tl.ranks[order(tl.ranks$rank), !names(tl@ranks) %in% c("id", "alpha", "ret.1.d", "rank.t")] misc$scaled.ranks.lo tl.ranks <- tl@ranks[order(tl@ranks$rank.t),!names(tl.ranks) %in% "id"] tl.ranks sub.chunks <- tl@chunks[, c("side", "rank.t", "chunk.shares", "chunk.mv", "tca.rank")] sub.chunks head(sub.chunks[order(sub.chunks[["tca.rank"]]),]) swaps.sub <- tl@swaps[, c("side.enter", "tca.rank.enter", "side.exit", "tca.rank.exit", "rank.gain")] swaps.sub sub.swaps.actual <- [email protected][, c("side.enter", "tca.rank.enter", "side.exit", "tca.rank.exit", "rank.gain")] sub.swaps.actual tl.bak <- tl tl@turnover <- 30250 - [email protected] tl <- portfolio:::calcSwapsActual(tl) sub.swaps.actual <- [email protected][, c("side.enter", "tca.rank.enter", "side.exit", "tca.rank.exit", "rank.gain")] sub.swaps.actual tl <- tl.bak sub.chunks.actual <- [email protected][,!names([email protected]) %in% c("id", "orig", "target", "shares", "mv")] sub.chunks.actual tl.actual <- tl@actual[, !names(tl@actual) %in% c("id")] tl.actual rm(list = ls()) load("tradelist.RData") p.current <- portfolios[["p.current.ls"]] p.target <- portfolios[["p.target.ls"]] data <- data.list$data.ls sorts <- list(alpha = 1, ret.1.d = 1/2) oe <- portfolio:::mvShort(p.current) + portfolio:::mvLong(p.current) te <- portfolio:::mvShort(p.target) + portfolio:::mvLong(p.target) tl <- new("tradelist", orig = p.current, target = p.target, chunk.usd = 2500, sorts = sorts, turnover = 36825, target.equity = te, data = data) nt <- mvCandidates(tl) p.current.shares <- p.current@shares[, !names(p.current@shares) %in% "id"] p.current.shares p.target.shares <- p.target@shares[, !names(p.target@shares) %in% "id"] p.target.shares sub.candidates <- tl@candidates[,!names(tl@candidates) %in% "id"] sub.candidates row.names(tl@restricted) <- 1:nrow(tl@restricted) tl@restricted sorts <- list(alpha = 1, ret.1.d = 1/2) row.names(data) <- data$id sub.data <- data[, c("id", "volume", "price.usd", "alpha", "ret.1.d")] sub.data tl <- new("tradelist", orig = p.current, target = p.target, chunk.usd = 2000, sorts = sorts, turnover = 36825, data = data) tl <- new("tradelist", orig = p.current, target = p.target, chunk.usd = 2000, sorts = sorts, turnover = 36825, target.equity = te, data = data) ranks <- [email protected]$alpha ranks <- split(ranks, ranks$side) ranks$B$rank <- 1:nrow(ranks$B) ranks$S$rank <- 1:nrow(ranks$S) ranks$X$rank <- 1:nrow(ranks$X) ranks tmp <- do.call(rbind, lapply(ranks, function(x) {x})) tmp <- tmp[order(tmp$rank),] tmp[,!names(tmp) %in% "id"] [email protected][["alpha"]][,!names([email protected][["alpha"]]) %in% "id"] ranks <- [email protected][["alpha"]] ranks[["rank"]] <- ranks[["rank"]]/sorts[["alpha"]] ranks [email protected][["ret.1.d"]] alpha <- [email protected][["alpha"]] ret.1.d <- [email protected][["ret.1.d"]] alpha <- alpha[,!names(alpha) %in% "alpha"] ret.1.d <- ret.1.d[,!names(ret.1.d) %in% "ret.1.d"] duplicates <- rbind(alpha, ret.1.d) duplicates <- duplicates[order(duplicates$id),] row.names(duplicates) <- 1:nrow(duplicates) duplicates tl.ranks <- tl@ranks top.ranks <- aggregate(duplicates[c("rank")], by = list(id = duplicates$id), min) tl.ranks$rank <- top.ranks$rank[match(tl.ranks$id, top.ranks$id)] tl.ranks[order(tl.ranks$rank), !names(tl@ranks) %in% c("id", "alpha", "ret.1.d", "rank.t")] tl.ranks$rank <- rank(tl.ranks$rank) tl.ranks <- tl.ranks[, !names(tl.ranks) %in% c("id", "alpha", "ret.1.d")] tl.ranks[order(tl.ranks$rank), !names(tl.ranks) %in% c("id", "alpha", "ret.1.d", "rank.t")] misc$scaled.ranks.ls tl.ranks <- tl@ranks[order(tl@ranks$rank.t),!names(tl.ranks) %in% "id"] tl.ranks sub.chunks <- tl@chunks[, c("side", "rank.t", "chunk.shares", "chunk.mv", "tca.rank")] sub.chunks swaps.sub <- tl@swaps[, c("side.enter", "tca.rank.enter", "side.exit", "tca.rank.exit", "rank.gain")] swaps.sub sub.swaps.actual <- [email protected][, c("side.enter", "tca.rank.enter", "side.exit", "tca.rank.exit", "rank.gain")] sub.swaps.actual tl.bak <- tl tl@turnover <- nt - [email protected] tl <- portfolio:::calcSwapsActual(tl) sub.swaps.actual <- [email protected][, c("side.enter", "tca.rank.enter", "side.exit", "tca.rank.exit", "rank.gain")] sub.swaps.actual tl <- tl.bak sub.chunks.actual <- [email protected][,!names([email protected]) %in% c("id", "orig", "target", "shares", "mv")] sub.chunks.actual tl@actual
Search3 <- function(MaxPhage,MaxBacteria,new_matrix,phage_names){ PhageSet3=0 BestBacteria3=0 for (i in 1:(MaxPhage-2)){ for(j in (i+1):(MaxPhage-1)){ for(k in (j+1):MaxPhage){ BacteriaSet3=0 for (b in 1:MaxBacteria){ if (new_matrix[b,i] | new_matrix[b,j]| new_matrix[b,k]){ BacteriaSet3=BacteriaSet3+1 } } if (BacteriaSet3 > BestBacteria3){ PhageSet3=c(i,j,k) BestBacteria3=BacteriaSet3 if (BestBacteria3 == MaxBacteria){ return(c(phage_names[PhageSet3],BestBacteria3)) } } } } } return(c(phage_names[PhageSet3],BestBacteria3)) }
Weibull <- function(alpha,beta=1){ if(length(beta)!=1){stop("beta parameter must be a single value")} if(length(alpha)!=1){stop("alpha parameter must be a single value")} new("Curve",type="Weibull",PDF="dweibull",CDF="pweibull",RF="rweibull",inverse="qweibull",paramno=2,pnames=c("scale","shape"),pvalue=list(alpha,beta)) } Lognormal <- function(mu,sigma=1){ if(length(mu)!=1){stop("mu parameter must be a single value")} if(length(sigma)!=1){stop("sigma parameter must be a single value")} new("Curve",type="Lognormal",PDF="dlnorm",CDF="plnorm",RF="rlnorm",inverse="qlnorm",paramno=2,pnames=c("meanlog","sdlog"),pvalue=list(mu,sigma)) } Exponential <- function(lambda){ if(length(lambda)!=1){stop("lambda parameter must be a single value")} new("Curve",type="Exponential",PDF="dexp",CDF="pexp",RF="rexp",inverse="qexp",paramno=1,pnames="rate",pvalue=list(lambda)) } Blank <- function(){ new("Curve",type="Blank",PDF="pmin",CDF="pmin",RF="INF",inverse="INF",paramno=1,pnames="Zero",pvalue=list(0)) } PieceExponential <- function(start,lambda){ if(length(start)!=length(lambda)){stop("Piecewise exponential curve has mismatched length 'start' and 'lambda' vectors")} if(start[1]!=0){stop("First element of piecewise exponential curve must start at 0")} if(is.unsorted(start,strictly=TRUE)){stop("Start times must be in ascending order with no duplicates")} new("Curve",type="PieceExponential",PDF="dpieceexp",CDF="ppieceexp",RF="rpieceexp",inverse="qpieceexp",paramno=2,pnames=c("start","rate"),pvalue=list(start,lambda)) } MixExp <- function(props,lambdas){ if(length(props)!=length(lambdas)){stop("Mixture exponential curve has mismatched length 'props' and 'lambdas' vectors")} if(sum(props)!=1){stop("Proportions must sum to 1!")} new("Curve",type="MixExp",PDF="dmixexp",CDF="pmixexp",RF="rmixexp",inverse="qmixexp",paramno=2,pnames=c("props","lambdas"),pvalue=list(props,lambdas)) } MixWei <- function(props,alphas,betas=rep(1,length(props))){ if(length(props)!=length(alphas)){stop("Mixture weibull curve has mismatched length 'props' and 'alphas' vectors")} if(length(props)!=length(betas)){stop("Mixture weibull curve has mismatched length 'props' and 'betas' vectors")} if(sum(props)!=1){stop("Proportions must sum to 1!")} new("Curve",type="MixWei",PDF="dmixwei",CDF="pmixwei",RF="rmixwei",inverse="qmixwei",paramno=3,pnames=c("props","betas","alphas"),pvalue=list(props,betas,alphas)) } LogLogistic <- function(theta, eta){ new('Curve', type='LogLogistic', PDF='dloglog', CDF='ploglog', RF='rloglog',inverse='qloglog', paramno=2, pnames=c('scale', 'shape'), pvalue=list(theta, eta)) } Gompertz <- function(theta, eta){ new('Curve', type='Gompertz', PDF='dgompertz', CDF='pgompertz', RF='rgompertz',inverse='qgompertz', paramno=2, pnames=c('scale', 'shape'), pvalue=list(theta, eta)) } GGamma <- function(theta, eta, rho){ new('Curve', type='GGamma', PDF='dggamma', CDF='pggamma', RF='rggamma',inverse="qggamma", paramno=3, pnames=c('scale', 'shape', 'family'), pvalue=list(theta, eta, rho)) } LinearR <- function(rlength,Nactive,Ncontrol){ new("RCurve",type="LinearR",PDF="linear_recruitPDF",CDF="linear_recruit",RF="linear_sim",inverse="NULL",paramno=1,pnames="rlength",pvalue=list(rlength),N=Nactive+Ncontrol,Nactive=Nactive,Ncontrol=Ncontrol,Ratio=Nactive/Ncontrol,Length=rlength,maxF=Inf) } InstantR <- function(Nactive,Ncontrol){ new("RCurve",type="InstantR",PDF="NULL",CDF="instant_recruit",RF="instant_sim",inverse="NULL",paramno=1,pnames="Dummy",pvalue=list(0),N=Nactive+Ncontrol,Nactive=Nactive,Ncontrol=Ncontrol,Ratio=Nactive/Ncontrol,Length=0,maxF=Inf) } PieceR <- function(recruitment,ratio){ lengths <- recruitment[,1] rates <- recruitment[,2] N <- sum(rates*lengths) Nactive <- N*(ratio/(ratio+1)) Ncontrol <- N-Nactive new("RCurve",type="PieceR",PDF="piece_recruitPDF",CDF="piece_recruit",RF="piece_sim",inverse="NULL",paramno=2,pnames=c("lengths","rates"),pvalue=list(lengths,rates),N=N,Ratio=ratio,Nactive=Nactive,Ncontrol=Ncontrol,Length=sum(lengths),maxF=Inf) } PieceRMaxF <- function(recruitment,ratio,maxF){ lengths <- recruitment[,1] rates <- recruitment[,2] N <- sum(rates*lengths) Nactive <- N*(ratio/(ratio+1)) Ncontrol <- N-Nactive new("RCurve",type="PieceR",PDF="piece_recruitPDFMaxF",CDF="piece_recruitMaxF",RF="piece_simMaxF",inverse="NULL",paramno=3,pnames=c("lengths","rates","maxF"),pvalue=list(lengths,rates,maxF),N=N,Ratio=ratio,Nactive=Nactive,Ncontrol=Ncontrol,Length=sum(lengths),maxF=maxF) }
library(sf) library(sp) mtq <- st_read(system.file("gpkg/mtq.gpkg", package="cartography"), quiet = TRUE) mob <- read.csv(system.file("csv/mob.csv", package="cartography")) mob_97209 <- mob[mob$i == 97209, ] mob.sf <- getLinkLayer(x = mtq, df = mob_97209, dfid = c("i", "j")) expect_equal(nrow(mob.sf), 10 ) expect_silent(getLinkLayer(x = as(mtq, "Spatial"),df = mob_97209, dfid = c("i", "j"))) expect_error(getLinkLayer(spdf = as(mtq, "Spatial"))) expect_error(getLinkLayer(mtq[1:5,], df = mob_97209)) expect_warning(getLinkLayer(mtq[1:20,], df = mob_97209))
get_match_list = function(str, pattern, ignore_case=TRUE, global=TRUE, perl=TRUE, fixed=FALSE) { match_ind = NULL starts = NULL ends = NULL capture_text = NULL if (global) { matches_raw = gregexpr(pattern, str, fixed = fixed, perl = perl & !fixed, ignore.case = ignore_case & !fixed)[[1]] if (all(matches_raw == -1)) return(NULL) matches = regmatches(rep(str, length(matches_raw)), matches_raw) } else { matches_raw = regexpr(pattern, str, fixed = fixed, perl = perl & !fixed, ignore.case = ignore_case & !fixed) matches = regmatches(str, matches_raw)[[1]] } if (perl & !is.null(attr(matches_raw, "capture.start"))) { capture_start = attr(matches_raw, "capture.start") capture_length = attr(matches_raw, "capture.length") - 1 capture_end = capture_start + capture_length match_df = data.table::data.table(match_ind = c(seq_len(length(matches))), match = matches, starts = as.numeric(capture_start), ends = as.numeric(capture_end)) match_df = match_df[order(match_ind, starts), ] match_df[, capture_text := stringr::str_sub(str, starts, ends)] match_list = split( match_df$capture_text, paste0(match_df$match_ind, "_", match_df$match) ) names(match_list) = gsub("^\\d+_", "", names(match_list)) } else { match_list = lapply(seq_len(length(matches)), function(x) character(0)) names(match_list) = matches } return(match_list) }
BootstrapVaR <- function(Ra, number.resamples, cl){ if (nargs() < 3){ stop("Too few arguments") } if (nargs() > 3){ stop("Too many arguments") } profit.loss.data <- as.vector(Ra) unsorted.loss.data <- -profit.loss.data losses.data <- sort(unsorted.loss.data) n <- length(losses.data) if (length(cl) != 1) { stop("Confidence level must be a scalar") } if (length(number.resamples) != 1){ stop("Number of resamples must be a scalar"); } if (cl >= 1){ stop("Confidence level must be less that 1") } if (cl <= 0){ stop("Confidence level must be at least 0") } if (number.resamples <= 0){ stop("Number of resamples must be at least 0") } VaR <- bootstrap(losses.data, number.resamples, HSVaR, cl)$thetastar y <- mean(VaR) return (y) }
stream_progress <- function(stream) { lastProgress <- invoke(stream, "lastProgress") if (is.null(lastProgress)) { NULL } else { lastProgress %>% invoke("toString") %>% fromJSON() } } stream_view <- function( stream, ...) { if (!"shiny" %in% installed.packages()) stop("The 'shiny' package is required for this operation.") validate <- stream_progress(stream) interval <- 1000 shinyUI <- get("shinyUI", envir = asNamespace("shiny")) tags <- get("tags", envir = asNamespace("shiny")) div <- get("div", envir = asNamespace("shiny")) HTML <- get("HTML", envir = asNamespace("shiny")) ui <- shinyUI( div( tags$head( tags$style(HTML(" html, body, body > div { width: 100%; height: 100%; margin: 0px; } ")) ), d3Output("plot", width = "100%", height = "100%") ) ) options <- list(...) observe <- get("observe", envir = asNamespace("shiny")) invalidateLater <- get("invalidateLater", envir = asNamespace("shiny")) server <- function(input, output, session) { first <- stream_progress(stream) output$plot <- renderD3( r2d3( data = list( sources = as.list(first$sources$description), sinks = as.list(first$sink$description) ), script = system.file("streams/stream.js", package = "sparklyr"), container = "div", options = options ) ) observe({ invalidateLater(interval, session) data <- stream_progress(stream) session$sendCustomMessage(type = "sparklyr_stream_view", list( timestamp = data$timestamp, rps = list( "in" = if (is.numeric(data$inputRowsPerSecond)) floor(data$inputRowsPerSecond) else 0, "out" = if (is.numeric(data$processedRowsPerSecond)) floor(data$processedRowsPerSecond) else 0 ) )) }) } runGadget <- get("runGadget", envir = asNamespace("shiny")) runGadget(ui, server) stream } stream_stats <- function(stream, stats = list()) { data <- stream_progress(stream) if (is.null(stats$stats)) { stats$sources <- data$sources$description stats$sink <- data$sink$description stats$stats <- list() } stats$stats[[length(stats$stats) + 1]] <- list( timestamp = data$timestamp, rps = list( "in" = if (is.numeric(data$inputRowsPerSecond)) floor(data$inputRowsPerSecond) else 0, "out" = if (is.numeric(data$processedRowsPerSecond)) floor(data$processedRowsPerSecond) else 0 ) ) stats } stream_render <- function( stream = NULL, collect = 10, stats = NULL, ...) { if (is.null(stats)) { stats <- stream_stats(stream) for (i in seq_len(collect)) { Sys.sleep(1) stats <- stream_stats(stream, stats) } } r2d3( data = list( sources = as.list(stats$sources), sinks = as.list(stats$sink), stats = stats$stats ), script = system.file("streams/stream.js", package = "sparklyr"), container = "div", options = options ) }
confounders.emm <- function(case, exposed, type = c("RR", "OR", "RD"), bias_parms = NULL, alpha = 0.05){ if(length(type) > 1) stop('Choose between RR, OR, or RD implementation.') if(is.null(bias_parms)) bias_parms <- c(1, 1, 0, 0) else bias_parms <- bias_parms if(length(bias_parms) != 4) stop('The argument bias_parms should be made of the following components: (1) Association between the confounder and the outcome among those who were exposed, (2) Association between the confounder and the outcome among those who were not exposed, (3) Prevalence of the confounder among the exposed, and (4) Prevalence of the confounder among the unexposed.') if(!all(bias_parms[3:4] >= 0 & bias_parms[3:4] <=1)) stop('Prevalences should be between 0 and 1.') if(!all(bias_parms[1:2] > 0) & type != "RD") stop('Association between the confounder and the outcome should be greater than 0.') if(inherits(case, c("table", "matrix"))) tab <- case else { tab.df <- table(case, exposed) tab <- tab.df[2:1, 2:1] } a <- as.numeric(tab[1, 1]) b <- as.numeric(tab[1, 2]) c <- as.numeric(tab[2, 1]) d <- as.numeric(tab[2, 2]) type <- match.arg(type) if (type == "RR") { crude.rr <- (a/(a + c)) / (b/(b + d)) se.log.crude.rr <- sqrt((c/a) / (a+c) + (d/b) / (b+d)) lci.crude.rr <- exp(log(crude.rr) - qnorm(1 - alpha/2) * se.log.crude.rr) uci.crude.rr <- exp(log(crude.rr) + qnorm(1 - alpha/2) * se.log.crude.rr) M1 <- (a + c) * bias_parms[3] N1 <- (b + d) * bias_parms[4] A1 <- (bias_parms[1] * M1 * a) / (bias_parms[1] * M1 + (a + c) - M1) B1 <- (bias_parms[2] * N1 * b) / (bias_parms[2] * N1 + (b + d) - N1) C1 <- M1 - A1 D1 <- N1 - B1 M0 <- a + c - M1 N0 <- b + d - N1 A0 <- a - A1 B0 <- b - B1 C0 <- c - C1 D0 <- d - D1 if(A1 < 0 | B1 < 0 | C1 < 0 | D1 < 0 | A0 < 0 | B0 < 0 | C0 < 0 | D0 < 0) stop('Parameters chosen lead to negative cell(s) in adjusted 2x2 table(s).') tab.cfder <- matrix(c(A1, B1, C1, D1), nrow = 2, byrow = TRUE) tab.nocfder <- matrix(c(A0, B0, C0, D0), nrow = 2, byrow = TRUE) SMRrr <- a / ((M1 * B1/N1) + (M0 * B0/N0)) MHrr <- (A1 * N1/(M1 + N1) + A0 * N0/(M0 + N0)) / (B1 * M1/(M1 + N1) + B0 * M0/(M0 + N0)) cfder.rr <- (A1/(A1 + C1)) / (B1/(B1 + D1)) nocfder.rr <- (A0/(A0 + C0)) / (B0/(B0 + D0)) RRadj.smr <- crude.rr / SMRrr RRadj.mh <- crude.rr / MHrr if (is.null(rownames(tab))) rownames(tab) <- paste("Row", 1:2) if (is.null(colnames(tab))) colnames(tab) <- paste("Col", 1:2) if (is.null(rownames(tab))){ rownames(tab.cfder) <- paste("Row", 1:2) } else { rownames(tab.cfder) <- row.names(tab) } if (is.null(colnames(tab))){ colnames(tab.cfder) <- paste("Col", 1:2) } else { colnames(tab.cfder) <- colnames(tab) } if (is.null(rownames(tab))){ rownames(tab.nocfder) <- paste("Row", 1:2) } else { rownames(tab.nocfder) <- row.names(tab) } if (is.null(colnames(tab))){ colnames(tab.nocfder) <- paste("Col", 1:2) } else { colnames(tab.nocfder) <- colnames(tab) } rmat <- rbind(c(crude.rr, lci.crude.rr, uci.crude.rr)) colnames(rmat) <- c(" ", paste(100 * (alpha/2), "%", sep = ""), paste(100 * (1 - alpha/2), "%", sep = "")) rmatc <- rbind(c(SMRrr, RRadj.smr), c(MHrr, RRadj.mh)) rownames(rmatc) <- c("Standardized Morbidity Ratio:", " Mantel-Haenszel:") colnames(rmatc) <- c(" ", "Adjusted RR") rmat <- rbind(rmat, c(cfder.rr, NA, NA), c(nocfder.rr, NA, NA)) rownames(rmat) <- c(" Crude Relative Risk:", "Relative Risk, Confounder +:", "Relative Risk, Confounder -:") } if (type == "OR"){ crude.or <- (a/b) / (c/d) se.log.crude.or <- sqrt(1/a + 1/b + 1/c + 1/d) lci.crude.or <- exp(log(crude.or) - qnorm(1 - alpha/2) * se.log.crude.or) uci.crude.or <- exp(log(crude.or) + qnorm(1 - alpha/2) * se.log.crude.or) C1 <- c * bias_parms[3] D1 <- d * bias_parms[4] A1 <- (bias_parms[1] * C1 * a) / (bias_parms[1] * C1 + c - C1) B1 <- (bias_parms[2] * D1 * b) / (bias_parms[2] * D1 + d - D1) M1 <- A1 + C1 N1 <- B1 + D1 A0 <- a - A1 B0 <- b - B1 C0 <- c - C1 D0 <- d - D1 M0 <- A0 + C0 N0 <- B0 + C0 if(A1 < 0 | B1 < 0 | C1 < 0 | D1 < 0 | A0 < 0 | B0 < 0 | C0 < 0 | D0 < 0) stop('Parameters chosen lead to negative cell(s) in adjusted 2x2 table(s).') tab.cfder <- matrix(c(A1, B1, C1, D1), nrow = 2, byrow = TRUE) tab.nocfder <- matrix(c(A0, B0, C0, D0), nrow = 2, byrow = TRUE) SMRor <- a / ((C1 * B1/D1) + (C0 * B0/D0)) MHor <- (A1 * D1/(M1 + N1) + A0 * D0/(M0 + N0)) / (B1 * C1/(M1 + N1) + B0 * C0/(M0 + N0)) cfder.or <- (A1 / C1) / (B1 / D1) nocfder.or <- (A0 / C0) / (B0 / D0) ORadj.smr <- crude.or / SMRor ORadj.mh <- crude.or / MHor if (is.null(rownames(tab))) rownames(tab) <- paste("Row", 1:2) if (is.null(colnames(tab))) colnames(tab) <- paste("Col", 1:2) if (is.null(rownames(tab))){ rownames(tab.cfder) <- paste("Row", 1:2) } else { rownames(tab.cfder) <- row.names(tab) } if (is.null(colnames(tab))){ colnames(tab.cfder) <- paste("Col", 1:2) } else { colnames(tab.cfder) <- colnames(tab) } if (is.null(rownames(tab))){ rownames(tab.nocfder) <- paste("Row", 1:2) } else { rownames(tab.nocfder) <- row.names(tab) } if (is.null(colnames(tab))){ colnames(tab.nocfder) <- paste("Col", 1:2) } else { colnames(tab.nocfder) <- colnames(tab) } rmat <- rbind(c(crude.or, lci.crude.or, uci.crude.or)) colnames(rmat) <- c(" ", paste(100 * (alpha/2), "%", sep = ""), paste(100 * (1 - alpha/2), "%", sep = "")) rmatc <- rbind(c(SMRor, ORadj.smr), c(MHor, ORadj.mh)) rownames(rmatc) <- c("Standardized Morbidity Ratio:", " Mantel-Haenszel:") colnames(rmatc) <- c(" ", "Adjusted OR") rmat <- rbind(rmat, c(cfder.or, NA, NA), c(nocfder.or, NA, NA)) rownames(rmat) <- c(" Crude Odds Ratio:", "Odds Ratio, Confounder +:", "Odds Ratio, Confounder -:") } if (type == "RD"){ crude.rd <- (a / (a + c)) - (b / (b + d)) se.log.crude.rd <- sqrt((a * c) / (a + c)^3 + (b * d) / (b + d)^3) lci.crude.rd <- crude.rd - qnorm(1 - alpha/2) * se.log.crude.rd uci.crude.rd <- crude.rd + qnorm(1 - alpha/2) * se.log.crude.rd M1 <- (a + c) * bias_parms[3] N1 <- (b + d) * bias_parms[4] M0 <- (a + c) - M1 N0 <- (b + d) - N1 A1 <- (bias_parms[1] * M1 * M0 + M1 * a) / (a + c) B1 <- (bias_parms[2] * N1 * N0 + N1 * b) / (b + d) C1 <- M1 - A1 D1 <- N1 - B1 A0 <- a - A1 B0 <- b - B1 C0 <- c - C1 D0 <- d - D1 if(A1 < 0 | B1 < 0 | C1 < 0 | D1 < 0 | A0 < 0 | B0 < 0 | C0 < 0 | D0 < 0) stop('Parameters chosen lead to negative cell(s) in adjusted 2x2 table(s).') tab.cfder <- matrix(c(A1, B1, C1, D1), nrow = 2, byrow = TRUE) tab.nocfder <- matrix(c(A0, B0, C0, D0), nrow = 2, byrow = TRUE) MHrd <- (((A1 * N1 - B1 * M1) / (M1 + N1)) + ((A0 * N0 - B0 * M0) / (M0 + N0))) / ((M1 * N1 / (M1 + N1)) + (M0 * N0 / (M0 + N0))) cfder.rd <- (A1 / M1) - (B1 / N1) nocfder.rd <- (A0 / M0) - (B0 / N0) RDadj.mh <- crude.rd - MHrd if (is.null(rownames(tab))) rownames(tab) <- paste("Row", 1:2) if (is.null(colnames(tab))) colnames(tab) <- paste("Col", 1:2) if (is.null(rownames(tab))){ rownames(tab.cfder) <- paste("Row", 1:2) } else { rownames(tab.cfder) <- row.names(tab) } if (is.null(colnames(tab))){ colnames(tab.cfder) <- paste("Col", 1:2) } else { colnames(tab.cfder) <- colnames(tab) } if (is.null(rownames(tab))){ rownames(tab.nocfder) <- paste("Row", 1:2) } else { rownames(tab.nocfder) <- row.names(tab) } if (is.null(colnames(tab))){ colnames(tab.nocfder) <- paste("Col", 1:2) } else { colnames(tab.nocfder) <- colnames(tab) } rmat <- rbind(c(crude.rd, lci.crude.rd, uci.crude.rd)) colnames(rmat) <- c(" ", paste(100 * (alpha/2), "%", sep = ""), paste(100 * (1 - alpha/2), "%", sep = "")) rmatc <- rbind(c(MHrd, RDadj.mh)) rownames(rmatc) <- "Mantel-Haenszel:" colnames(rmatc) <- c(" ", "Adjusted RD") rmat <- rbind(rmat, c(cfder.rd, NA, NA), c(nocfder.rd, NA, NA)) rownames(rmat) <- c(" Crude Risk Difference:", "Risk Difference, Confounder +:", "Risk Difference, Confounder -:") } res <- list(obs.data = tab, cfder.data = tab.cfder, nocfder.data = tab.nocfder, obs.measures = rmat, adj.measures = rmatc, bias.parms = bias_parms) class(res) <- c("episensr", "list") res }
context("getAlgorithmNames") test_that("getAlgorithmNames", { s = getAlgorithmNames(testscenario1) })
.prepare_get_data <- function(x, mf, effects = "fixed", verbose = TRUE) { if (.is_empty_object(mf)) { if (isTRUE(verbose)) { warning("Could not get model data.", call. = FALSE) } return(NULL) } mw <- NULL offcol <- grep("^(\\(offset\\)|offset\\((.*)\\))", colnames(mf)) if (length(offcol) && .obj_has_name(x, "call") && .obj_has_name(x$call, "offset")) { colnames(mf)[offcol] <- clean_names(.safe_deparse(x$call$offset)) } mf <- .backtransform(mf) mf[] <- lapply(mf, function(.x) { if (is.matrix(.x) && dim(.x)[2] == 1 && !inherits(.x, c("ns", "bs", "poly", "mSpline"))) { as.vector(.x) } else { .x } }) mc <- sapply(mf, is.matrix) rn <- find_response(x, combine = TRUE) rn_not_combined <- find_response(x, combine = FALSE) if (is.null(rn)) rn <- "" if (is.null(rn_not_combined)) rn_not_combined <- "" trials.data <- NULL if (mc[1] && rn == colnames(mf)[1]) { mc[1] <- FALSE if (inherits(x, c("coxph", "flexsurvreg", "coxme", "survreg", "survfit", "crq", "psm", "coxr"))) { n_of_responses <- ncol(mf[[1]]) mf <- cbind(as.data.frame(as.matrix(mf[[1]])), mf) colnames(mf)[1:n_of_responses] <- rn_not_combined } else { tryCatch( { trials.data <- as.data.frame(mf[[1]]) colnames(trials.data) <- rn_not_combined pattern <- sprintf("%s(\\s*)-(\\s*)%s", rn_not_combined[2], rn_not_combined[1]) if (any(grepl(pattern = pattern, x = rn))) { trials.data[[2]] <- trials.data[[1]] + trials.data[[2]] } }, error = function(x) { NULL } ) } } if (any(mc)) { md <- tryCatch( { eval(stats::getCall(x)$data, environment(stats::formula(x))) }, error = function(x) { NULL } ) if (is.null(md)) { mf_matrix <- mf[, which(mc), drop = FALSE] mf_nonmatrix <- mf[, -which(mc), drop = FALSE] if (any(class(mf_matrix[[1]]) == "rms")) { class(mf_matrix[[1]]) <- "matrix" } mf_list <- lapply(mf_matrix, as.data.frame, stringsAsFactors = FALSE) mf_matrix <- do.call(cbind, mf_list) mf <- cbind(mf_nonmatrix, mf_matrix) } else { if (any(is.na(colnames(md)))) { colnames(md) <- make.names(colnames(md)) } mf_matrix <- mf[, -which(mc), drop = FALSE] spline.term <- clean_names(names(which(mc))) other.terms <- clean_names(colnames(mf_matrix))[-1] needed.vars <- c(other.terms, spline.term) if (is.matrix(mf[[1]])) { needed.vars <- c(dimnames(mf[[1]])[[2]], needed.vars) } else { needed.vars <- c(colnames(mf)[1], needed.vars) } if ("(weights)" %in% needed.vars && !.obj_has_name(md, "(weights)")) { needed.vars <- needed.vars[-which(needed.vars == "(weights)")] mw <- mf[["(weights)"]] fw <- find_weights(x) if (!is.null(fw) && fw %in% colnames(md)) { needed.vars <- c(needed.vars, fw) } } if (inherits(x, c("coxph", "coxme", "coxr")) || any(grepl("^Surv\\(", spline.term))) { mf <- md } else { needed.vars <- .compact_character(unique(clean_names(needed.vars))) mf <- md[, needed.vars, drop = FALSE] value_labels <- lapply(mf, function(.l) attr(.l, "labels", exact = TRUE)) variable_labels <- lapply(mf, function(.l) attr(.l, "label", exact = TRUE)) mf <- stats::na.omit(mf) mf <- as.data.frame(mapply(function(.d, .l) { attr(.d, "labels") <- .l .d }, mf, value_labels, SIMPLIFY = FALSE), stringsAsFactors = FALSE) mf <- as.data.frame(mapply(function(.d, .l) { attr(.d, "label") <- .l .d }, mf, variable_labels, SIMPLIFY = FALSE), stringsAsFactors = FALSE) } if (!is.null(mw)) mf$`(weights)` <- mw } pv <- tryCatch( { find_predictors(x, effects = effects, flatten = TRUE, verbose = verbose) }, error = function(x) { NULL } ) if (!is.null(pv) && !all(pv %in% colnames(mf)) && isTRUE(verbose)) { warning(format_message("Some model terms could not be found in model data. You probably need to load the data into the environment."), call. = FALSE) } } mos_eisly <- grepl(pattern = "^mo\\(([^,)]*).*", x = colnames(mf)) if (any(mos_eisly)) { mf <- mf[!mos_eisly] } strata_columns <- grepl("^strata\\((.*)\\)", colnames(mf)) if (any(strata_columns)) { for (sc in colnames(mf)[strata_columns]) { strata_variable <- gsub("strata\\((.*)\\)", "\\1", sc) levels(mf[[sc]]) <- gsub(paste0("\\Q", strata_variable, "=", "\\E"), "", levels(mf[[sc]])) } } factors <- colnames(mf)[grepl("^(as\\.factor|factor)\\((.*)\\)", colnames(mf))] cvn <- .remove_pattern_from_names(colnames(mf), ignore_lag = TRUE) if (colnames(mf)[1] == rn[1] && grepl("^I\\(", rn[1])) { md <- tryCatch( { tmp <- .recover_data_from_environment(x)[, unique(c(rn_not_combined, cvn)), drop = FALSE] tmp[, rn_not_combined, drop = FALSE] }, error = function(x) { NULL } ) if (!is.null(md)) { mf <- cbind(mf, md) cvn <- .remove_pattern_from_names(colnames(mf), ignore_lag = TRUE) cvn[1] <- rn[1] } } dupes <- which(duplicated(cvn)) if (!.is_empty_string(dupes)) cvn[dupes] <- sprintf("%s.%s", cvn[dupes], 1:length(dupes)) colnames(mf) <- cvn weighting_var <- find_weights(x) if (!is.null(weighting_var) && !weighting_var %in% colnames(mf) && length(weighting_var) == 1) { mf <- tryCatch( { tmp <- suppressWarnings(cbind(mf, get_weights(x))) colnames(tmp)[ncol(tmp)] <- weighting_var tmp }, error = function(e) { mf } ) } if (!is.null(trials.data)) { new.cols <- setdiff(colnames(trials.data), colnames(mf)) if (!.is_empty_string(new.cols)) mf <- cbind(mf, trials.data[, new.cols, drop = FALSE]) } .add_remaining_missing_variables(x, mf, effects, component = "all", factors = factors) } .add_remaining_missing_variables <- function(model, mf, effects, component, factors = NULL) { model_call <- get_call(model) if (!is.null(model_call)) { data_arg <- tryCatch(parse(text = .safe_deparse(model_call))[[1]]$data, error = function(e) NULL) } else { data_arg <- NULL } if (is.null(data_arg) && all(grepl("(.*)\\$(.*)", colnames(mf)))) { colnames(mf) <- gsub("(.*)\\$(.*)", "\\2", colnames(mf)) } predictors <- find_predictors( model, effects = effects, component = component, flatten = TRUE, verbose = FALSE ) missing_vars <- setdiff(predictors, colnames(mf)) if (!is.null(missing_vars) && length(missing_vars) > 0) { env_data <- .recover_data_from_environment(model) if (!is.null(env_data) && all(missing_vars %in% colnames(env_data))) { shared_columns <- intersect(colnames(env_data), c(missing_vars, colnames(mf))) env_data <- stats::na.omit(env_data[shared_columns]) if (nrow(env_data) == nrow(mf) && !any(missing_vars %in% colnames(mf))) { mf <- cbind(mf, env_data[missing_vars]) } } } if (length(factors)) { factors <- gsub("^(as\\.factor|factor)\\((.*)\\)", "\\2", factors) for (i in factors) { if (.is_numeric_character(mf[[i]])) { mf[[i]] <- .to_numeric(mf[[i]]) attr(mf[[i]], "factor") <- TRUE } } attr(mf, "factors") <- factors } mf } .return_combined_data <- function(x, mf, effects, component, model.terms, is_mv = FALSE, verbose = TRUE) { response <- unlist(model.terms$response) factors <- attr(mf, "factors", exact = TRUE) if (is_mv) { fixed.component.data <- switch(component, all = c( sapply(model.terms[-1], function(i) i$conditional), sapply(model.terms[-1], function(i) i$zero_inflated), sapply(model.terms[-1], function(i) i$dispersion) ), conditional = sapply(model.terms[-1], function(i) i$conditional), zi = , zero_inflated = sapply(model.terms[-1], function(i) i$zero_inflated), dispersion = sapply(model.terms[-1], function(i) i$dispersion) ) random.component.data <- switch(component, all = c( sapply(model.terms[-1], function(i) i$random), sapply(model.terms[-1], function(i) i$zero_inflated_random) ), conditional = sapply(model.terms[-1], function(i) i$random), zi = , zero_inflated = sapply(model.terms[-1], function(i) i$zero_inflated_random) ) fixed.component.data <- unlist(fixed.component.data) random.component.data <- unlist(random.component.data) } else { all_elements <- intersect(names(model.terms), .get_elements("fixed", "all")) fixed.component.data <- switch(component, all = unlist(model.terms[all_elements]), conditional = model.terms$conditional, zi = , zero_inflated = model.terms$zero_inflated, dispersion = model.terms$dispersion ) random.component.data <- switch(component, all = c(model.terms$random, model.terms$zero_inflated_random), conditional = model.terms$random, zi = , zero_inflated = model.terms$zero_inflated_random ) } if (!.is_empty_object(fixed.component.data)) { fixed.component.data <- .remove_values(fixed.component.data, c("1", "0")) fixed.component.data <- .remove_values(fixed.component.data, c(1, 0)) } if (!.is_empty_object(random.component.data)) { random.component.data <- .remove_values(random.component.data, c("1", "0")) random.component.data <- .remove_values(random.component.data, c(1, 0)) } weights <- find_weights(x) vars <- switch(effects, all = unique(c(response, fixed.component.data, random.component.data, weights)), fixed = unique(c(response, fixed.component.data, weights)), random = unique(random.component.data) ) vars <- c(vars, find_offset(x)) still_missing <- setdiff(vars, colnames(mf)) vars <- intersect(vars, colnames(mf)) dat <- mf[, vars, drop = FALSE] if (.is_empty_object(dat)) { if (isTRUE(verbose)) { warning(format_message(sprintf("Data frame is empty, probably component '%s' does not exist in the %s-part of the model?", component, effects)), call. = FALSE) } return(NULL) } if (length(still_missing) && isTRUE(verbose)) { warning(format_message(sprintf("Following potential variables could not be found in the data: %s", paste0(still_missing, collapse = " ,"))), call. = FALSE) } if ("(offset)" %in% colnames(mf) && !("(offset)" %in% colnames(dat))) { dat <- cbind(dat, mf[["(offset"]]) } attr(dat, "factors") <- factors dat } .add_zeroinf_data <- function(x, mf, tn) { tryCatch( { env_data <- eval(x$call$data, envir = parent.frame())[, tn, drop = FALSE] if (.obj_has_name(x$call, "subset")) { env_data <- subset(env_data, subset = eval(x$call$subset)) } .merge_dataframes(env_data, mf, replace = TRUE) }, error = function(x) { mf } ) } .get_zelig_relogit_frame <- function(x) { vars <- find_variables(x, flatten = TRUE, verbose = FALSE) x$data[, vars, drop = FALSE] } .return_zeroinf_data <- function(x, component, verbose = TRUE) { model.terms <- find_variables(x, effects = "all", component = "all", flatten = FALSE, verbose = FALSE) model.terms$offset <- find_offset(x) mf <- tryCatch( { stats::model.frame(x) }, error = function(x) { NULL } ) mf <- .prepare_get_data(x, mf, verbose = verbose) mf <- .add_zeroinf_data(x, mf, model.terms$zero_inflated) fixed.data <- switch(component, all = c(model.terms$conditional, model.terms$zero_inflated, model.terms$offset), conditional = c(model.terms$conditional, model.terms$offset), zi = , zero_inflated = model.terms$zero_inflated ) mf[, unique(c(model.terms$response, fixed.data, find_weights(x))), drop = FALSE] } .get_data_from_modelframe <- function(x, dat, effects, verbose = TRUE) { if (.is_empty_object(dat)) { warning("Could not get model data.", call. = FALSE) return(NULL) } cn <- clean_names(colnames(dat)) ft <- switch(effects, fixed = find_variables(x, effects = "fixed", flatten = TRUE), all = find_variables(x, flatten = TRUE), random = find_random(x, split_nested = TRUE, flatten = TRUE) ) remain <- intersect(c(ft, find_weights(x)), cn) mf <- tryCatch( { dat[, remain, drop = FALSE] }, error = function(x) { dat } ) .prepare_get_data(x, mf, effects, verbose = verbose) } .recover_data_from_environment <- function(x) { model_call <- get_call(x) dat <- tryCatch( { eval(model_call$data, envir = parent.frame()) }, error = function(e) { NULL } ) if (is.null(dat)) { dat <- tryCatch( { eval(model_call$data, envir = globalenv()) }, error = function(e) { NULL } ) } if (!is.null(dat) && .obj_has_name(model_call, "subset")) { dat <- subset(dat, subset = eval(model_call$subset)) } dat } .get_S4_data_from_env <- function(x) { dat <- tryCatch( { eval(x@call$data, envir = parent.frame()) }, error = function(e) { NULL } ) if (is.null(dat)) { dat <- tryCatch( { eval(x@call$data, envir = globalenv()) }, error = function(e) { NULL } ) } if (!is.null(dat) && .obj_has_name(x@call, "subset")) { dat <- subset(dat, subset = eval(x@call$subset)) } dat } .get_startvector_from_env <- function(x) { tryCatch( { sv <- eval(parse(text = .safe_deparse(x@call))[[1]]$start) if (is.list(sv)) sv <- sv[["nlpars"]] names(sv) }, error = function(e) { NULL } ) } .backtransform <- function(mf) { tryCatch( { patterns <- c( "scale\\(log", "exp\\(scale", "log\\(log", "log", "log1p", "log10", "log2", "sqrt", "exp", "expm1", "scale" ) for (i in patterns) { mf <- .backtransform_helper(mf, i) } mf }, error = function(e) { mf } ) } .backtransform_helper <- function(mf, type) { cn <- .get_transformed_names(colnames(mf), type) if (!.is_empty_string(cn)) { for (i in cn) { if (type == "scale\\(log") { mf[[i]] <- exp(.unscale(mf[[i]])) } else if (type == "exp\\(scale") { mf[[i]] <- .unscale(log(mf[[i]])) } else if (type == "log\\(log") { mf[[i]] <- exp(exp(mf[[i]])) } else if (type == "log") { mf[[i]] <- exp(mf[[i]]) } else if (type == "log1p") { mf[[i]] <- expm1(mf[[i]]) } else if (type == "log10") { mf[[i]] <- 10^(mf[[i]]) } else if (type == "log2") { mf[[i]] <- 2^(mf[[i]]) } else if (type == "sqrt") { mf[[i]] <- (mf[[i]])^2 } else if (type == "exp") { mf[[i]] <- log(mf[[i]]) } else if (type == "expm1") { mf[[i]] <- log1p(mf[[i]]) } else if (type == "scale") { mf[[i]] <- .unscale(mf[[i]]) } colnames(mf)[colnames(mf) == i] <- .get_transformed_terms(i, type) } } mf } .unscale <- function(x) { m <- attr(x, "scaled:center") s <- attr(x, "scaled:scale") if (is.null(m)) m <- 0 if (is.null(s)) s <- 1 s * x + m } .get_transformed_terms <- function(model, type = "all") { if (is.character(model)) { x <- model } else { x <- find_terms(model, flatten = TRUE) } pattern <- sprintf("%s\\(([^,\\+)]*).*", type) .trim(gsub(pattern, "\\1", x[grepl(pattern, x)])) } .get_transformed_names <- function(x, type = "all") { pattern <- sprintf("%s\\(([^,)]*).*", type) x[grepl(pattern, x)] } .retrieve_htest_data <- function(x) { out <- tryCatch( { if (grepl("^svy", x$data.name)) { if (grepl("pearson's x^2", tolower(x$method), fixed = TRUE)) { d <- x$observed } else { d <- NULL } } else { data_name <- trimws(unlist(strsplit(x$data.name, "(and|by)"))) data_comma <- unlist(strsplit(data_name, "(\\([^)]*\\))")) if (any(grepl(",", data_comma, fixed = TRUE))) { data_name <- trimws(unlist(strsplit(data_comma, ", ", fixed = TRUE))) } if (grepl("Kruskal-Wallis", x$method, fixed = TRUE) && grepl("^list\\(", data_name)) { l <- eval(.str2lang(x$data.name)) names(l) <- paste0("x", 1:length(l)) return(l) } data_call <- lapply(data_name, .str2lang) columns <- lapply(data_call, eval) if (!grepl(" (and|by) ", x$data.name) && (grepl("^McNemar", x$method) || (length(columns) == 1 && is.matrix(columns[[1]])))) { return(as.table(columns[[1]])) } else if (grepl("^Kruskal-Wallis", x$method) && length(columns) == 1 && is.list(columns[[1]])) { l <- columns[[1]] names(l) <- paste0("x", 1:length(l)) return(l) } else { max_len <- max(sapply(columns, length)) for (i in 1:length(columns)) { if (length(columns[[i]]) < max_len) { columns[[i]] <- c(columns[[i]], rep(NA, max_len - length(columns[[i]]))) } } d <- as.data.frame(columns) } if (all(grepl("(.*)\\$(.*)", data_name)) && length(data_name) == length(colnames(d))) { colnames(d) <- gsub("(.*)\\$(.*)", "\\2", data_name) } else if (ncol(d) > 2) { colnames(d) <- paste0("x", 1:ncol(d)) } else if (ncol(d) == 2) { colnames(d) <- c("x", "y") } else { colnames(d) <- "x" } } d }, error = function(e) { NULL } ) if (is.null(out)) { for (parent_level in 1:5) { out <- tryCatch( { data_name <- trimws(unlist(strsplit(x$data.name, "(and|,|by)"))) as.table(get(data_name, envir = parent.frame(n = parent_level))) }, error = function(e) { NULL } ) if (!is.null(out)) break } } out }
m2tk<-function(m0) { mo=sort(m0,decreasing=TRUE) M=sum(mo)/3 Md=mo-M if(Md[2]>=0) {k=M/(abs(M)-Md[3])} if(Md[2]<0) {k=M/(abs(M)+Md[1])} if(Md[2]>0) {T=-2*Md[2]/Md[3]} if(Md[2]==0) {T=0} if(Md[2]<0) {T=2*Md[2]/Md[1]} return(list(k=k,T=T)) }
model_parameters.clm2 <- function(model, ci = .95, bootstrap = FALSE, iterations = 1000, component = c("all", "conditional", "scale"), standardize = NULL, exponentiate = FALSE, p_adjust = NULL, verbose = TRUE, ...) { component <- match.arg(component) if (component == "all") { merge_by <- c("Parameter", "Component") } else { merge_by <- "Parameter" } out <- .model_parameters_generic( model = model, ci = ci, component = component, bootstrap = bootstrap, iterations = iterations, merge_by = c("Parameter", "Component"), standardize = standardize, exponentiate = exponentiate, p_adjust = p_adjust, ... ) attr(out, "object_name") <- deparse(substitute(model), width.cutoff = 500) out } model_parameters.clmm2 <- model_parameters.clm2 model_parameters.clmm <- model_parameters.cpglmm ci.clm2 <- function(x, ci = .95, component = c("all", "conditional", "scale"), ...) { component <- match.arg(component) .ci_generic(model = x, ci = ci, dof = Inf, component = component) } ci.clmm2 <- ci.clm2 standard_error.clm2 <- function(model, component = c("all", "conditional", "scale"), ...) { component <- match.arg(component) stats <- .get_se_from_summary(model) parms <- insight::get_parameters(model, component = component) .data_frame( Parameter = parms$Parameter, SE = stats[parms$Parameter], Component = parms$Component ) } standard_error.clmm2 <- standard_error.clm2 p_value.clm2 <- function(model, component = c("all", "conditional", "scale"), ...) { component <- match.arg(component) params <- insight::get_parameters(model) cs <- stats::coef(summary(model)) p <- cs[, 4] out <- .data_frame( Parameter = params$Parameter, Component = params$Component, p = as.vector(p) ) if (component != "all") { out <- out[out$Component == component, ] } out } p_value.clmm2 <- p_value.clm2 simulate_model.clm2 <- function(model, iterations = 1000, component = c("all", "conditional", "scale"), ...) { component <- match.arg(component) out <- .simulate_model(model, iterations, component = component) class(out) <- c("parameters_simulate_model", class(out)) attr(out, "object_name") <- .safe_deparse(substitute(model)) out } simulate_model.clmm2 <- simulate_model.clm2
lineups_stats_per_possesion <- function(df1,df2,df3,p,m){ minutes <- (df2[1,2]/df2[1,1])/5 minutes <- trunc(minutes) tm_poss <- df2[1,4] - df2[1,15] / (df2[1,15] + df3[1,16]) * (df2[1,4] - df2[1,3]) * 1.07 + df2[1,21] + 0.4 * df2[1,13] opp_poss <- df3[1,4] - df3[1,15] / (df3[1,15] + df2[1,16]) * (df3[1,4] - df3[1,3]) * 1.07 + df3[1,21] + 0.4 * df3[1,13] pace <- m * ((tm_poss + opp_poss) / (2 * (df2[1,2] / 5))) if(ncol(df1)==29){ lyneup_poss <- (pace/m) * df1[6] for(i in 7:ncol(df1)){ if(i==9||i==12||i==15||i==18){ df1[i]<- round(df1[i],3) } else{ df1[i] <- round((df1[i]/lyneup_poss) * p,2) } } names(df1) = c("PG","SG","SF","PF","C","MP","FG","FGA","FG%","3P","3PA","3P%","2P","2PA","2P%","FT","FTA","FT%", "ORB","DRB","TRB","AST","STL","BLK","TOV","PF","+","-","+/-") }else if(ncol(df1)==27){ lyneup_poss <- (pace/m) * df1[4] for(i in 7:ncol(df1)){ if(i==7||i==10||i==13||i==16){ df1[i]<- round(df1[i],3) } else{ df1[i] <- round((df1[i]/lyneup_poss) * p,2) } } names(df1) = c("PG","SG","SF","MP","FG","FGA","FG%","3P","3PA","3P%","2P","2PA","2P%","FT","FTA","FT%", "ORB","DRB","TRB","AST","STL","BLK","TOV","PF","+","-","+/-") }else if(ncol(df1)==26){ lyneup_poss <- (pace/m) * df1[3] for(i in 7:ncol(df1)){ if(i==6||i==9||i==12||i==15){ df1[i]<- round(df1[i],3) } else{ df1[i] <- round((df1[i]/lyneup_poss) * p,2) } } names(df1) = c("PF","C","MP","FG","FGA","FG%","3P","3PA","3P%","2P","2PA","2P%","FT","FTA","FT%", "ORB","DRB","TRB","AST","STL","BLK","TOV","PF","+","-","+/-") } else if (ncol(df1)==25){ lyneup_poss <- (pace/m) * df1[2] for(i in 7:ncol(df1)){ if(i==5||i==8||i==11||i==14){ df1[i]<- round(df1[i],3) } else{ df1[i] <- round((df1[i]/lyneup_poss) * p,2) } } } df1[is.na(df1)] <- 0 return(df1) }
summary.bma <- function (object, ...) { info.bma(object) }
gi_write_gitignore <- function(fetched_template, gitignore_file = here::here(".gitignore")) { stopifnot(basename(gitignore_file) == ".gitignore") if (!file.exists(gitignore_file)) { message( crayon::red(clisymbols::symbol$bullet), " The .gitignore file could not be found in the project directory", here::here(), "Would you like to create it?", "\n" ) response <- utils::menu(c("Yes", "No")) if (response == 1) { file.create(gitignore_file) } else { stop( "Could not find the file: ", crayon::red$bold(gitignore_file) ) } } existing_lines <- readLines(gitignore_file, warn = FALSE, encoding = "UTF-8") fetched_template_splitted <- unlist(strsplit(fetched_template, "\n")) new <- setdiff(fetched_template_splitted, existing_lines) if (length(new) == 0) { message( crayon::yellow(clisymbols::symbol$bullet), " Nothing to be modified in the .gitignore file.\n" ) return(FALSE) } all <- c(existing_lines, new) xfun::write_utf8(all, gitignore_file) message( crayon::green(clisymbols::symbol$bullet), " .gitignore file successfully modified.\n" ) invisible(TRUE) }
panel.ci <- function( x, y, lower, upper, groups = NULL, subscripts, col, fill = if (is.null(groups)) plot.line$col else superpose.line$col, alpha = 0.15, lty = 0, lwd = if (is.null(groups)) plot.line$lwd else superpose.line$lwd, grid = FALSE, ..., col.line = if (is.null(groups)) plot.line$col else superpose.line$col ) { plot.line <- trellis.par.get("plot.line") superpose.line <- trellis.par.get("superpose.line") dots <- list(...) if (!missing(col)) { if (missing(col.line)) col.line <- col } if (!identical(grid, FALSE)) { if (!is.list(grid)) grid <- switch(as.character(grid), "TRUE" = list(h = -1, v = -1, x = x, y = y), h = list(h = -1, v = 0, y = y), v = list(h = 0, v = -1, x = x), list(h = 0, v = 0)) do.call(lattice::panel.grid, grid) } nobs <- sum(!is.na(y)) if (!is.null(groups)) do.call(panel.superpose, updateList(list( x = x, y = y, lower = lower, upper = upper, groups = groups, subscripts = subscripts, panel.groups = panel.ci, alpha = alpha, col.line = col.line, fill = fill, lty = lty, lwd = lwd ), dots)) else if (nobs > 0) { lower <- lower[subscripts] upper <- upper[subscripts] ord <- order(x) x <- sort(x) do.call(panel.polygon, updateList(list( x = c(x, rev(x)), y = c(upper[ord], rev(lower[ord])), alpha = alpha, col = fill, border = "transparent", lty = 0, lwd = 0, identifier = "ci" ), dots)) panel.lines( x = x, y = lower[ord], alpha = alpha, col = col.line, lty = lty, lwd = lwd, identifier = "ci" ) panel.lines( x = x, y = upper[ord], alpha = alpha, col = col.line, lty = lty, lwd = lwd, identifier = "ci" ) } else { return() } } prepanel.ci <- function( x, y, lower, upper, subscripts, groups = NULL, ... ) { if (any(!is.na(x)) && any(!is.na(y))) { ord <- order(as.numeric(x)) if (!is.null(groups)) { gg <- groups[subscripts] dx <- unlist(lapply(split(as.numeric(x)[ord], gg[ord]), diff)) dy <- unlist(lapply(split(as.numeric(y)[ord], gg[ord]), diff)) } else { dx <- diff(as.numeric(x[ord])) dy <- diff(as.numeric(y[ord])) } list(xlim = scale.limits(x), ylim = scale.limits(c(lower, upper)), dx = dx, dy = dy, xat = if (is.factor(x)) sort(unique(as.numeric(x))) else NULL, yat = if (is.factor(y)) sort(unique(as.numeric(y))) else NULL) } else prepanel.null() }
"cortest.normal" <- function(R1,R2=NULL, n1=NULL,n2=NULL,fisher=TRUE) { cl <- match.call() if (dim(R1)[1] != dim(R1)[2]) {n1 <- dim(R1)[1] message("R1 was not square, finding R from data") R1 <- cor(R1,use="pairwise")} if(!is.matrix(R1) ) R1 <- as.matrix(R1) p <- dim(R1)[2] if(is.null(n1)) {n1 <- 100 warning("n not specified, 100 used") } if(is.null(R2)) { if(fisher) {R <- 0.5*log((1+R1)/(1-R1)) R <- R*R} else {R <- R1*R1} diag(R) <- 0 E <- (sum(R*lower.tri(R))) chisq <- E *(n1-3) df <- p*(p-1)/2 p.val <- pchisq(chisq,df,lower.tail=FALSE) } else { if (dim(R2)[1] != dim(R2)[2]) {n2 <- dim(R2)[1] message("R2 was not square, finding R from data") R2 <- cor(R2,use="pairwise")} if(!is.matrix(R2) ) R2 <- as.matrix(R2) if(fisher) { R1 <- 0.5*log((1+R1)/(1-R1)) R2 <- 0.5*log((1+R2)/(1-R2)) diag(R1) <- 0 diag(R2) <- 0 } R <- R1 -R2 R <- R*R if(is.null(n2)) n2 <- n1 n <- (n1*n2)/(n1+n2) E <- (sum(R*lower.tri(R))) chisq <- E *(n-3) df <- p*(p-1)/2 p.val <- pchisq(chisq,df,lower.tail=FALSE) } result <- list(chi2=chisq,prob=p.val,df=df,Call=cl) class(result) <- c("psych", "cortest") return(result) } "cortest.normal1" <- function(R1,R2=NULL, n1=NULL,n2=NULL,fisher=TRUE) { cl <- match.call() if(!is.matrix(R1) ) R1 <- as.matrix(R1) if(!is.matrix(R2) ) R2 <- as.matrix(R2) r <- dim(R1)[1] c <- dim(R1)[2] R1 <- 0.5*log((1+R1)/(1-R1)) R2 <- 0.5*log((1+R2)/(1-R2)) R <- R1 -R2 R <- R*R if(is.null(n2)) n2 <- n1 n <- (n1*n2)/(n1+n2) E <- sum(R) chisq <- E *(n-3) df <- r*c p.val <- pchisq(chisq,df,lower.tail=FALSE) result <- list(chi2=chisq,prob=p.val,df=df,Call=cl) class(result) <- c("psych", "cortest") return(result) } test.cortest.normal <- function(n.var=10,n1=100,n2=1000,n.iter=100) { R <- diag(1,n.var) summary <- list() for(i in 1:n.iter) { x <- sim.correlation(R,n1) if(n2 >3 ) { y <- sim.correlation(R,n2) summary[[i]] <- cortest(x,y,n1=n1,n2=n2)$prob } else {summary[[i]] <- cortest(x,n1=n1)$prob } } result <- unlist(summary) return(result) }
setMethod("SI", signature(object = "Nri", i = "missing", j = "missing"), function(object, i, j) return(.SI(object@SI)) ) setMethod("SI", signature(object = "Nri", i = "ANY", j = "missing"), function(object, i, j) return(object@SI[i,]) ) setMethod("SI", signature(object = "Nri", i = "missing", j = "ANY"), function(object, i, j) return(object@SI[,j]) ) setMethod("SI", signature(object = "Nri", i = "ANY", j = "ANY"), function(object, i, j) return(object@SI[i,j]) ) setReplaceMethod("SI", signature(object = "Nri", value = "matrix"), function(object, value) { object@SI <- new(".SI", value) return(object) } ) setReplaceMethod("SI", signature(object = "Nri", value = "data.frame"), function(object, value) { object@SI <- new(".SI", value) return(object) } ) setReplaceMethod("SI", signature(object = "Nri", value = "ANY"), function(object, value) { object@SI <- new(".SI", value) return(object) } )
function.MaxSe <- function(data, marker, status, tag.healthy = 0, direction = c("<", ">"), control = control.cutpoints(), pop.prev, ci.fit = FALSE, conf.level = 0.95, measures.acc){ direction <- match.arg(direction) cutpointsSe <- measures.acc$cutoffs[which(round(measures.acc$Se[,1],10) == round(max(measures.acc$Se[,1],na.rm=TRUE),10))] if (length(cutpointsSe)> 1) { Spnew <- obtain.optimal.measures(cutpointsSe, measures.acc)$Sp cMaxSe <- cutpointsSe[which(round(Spnew[,1],10) == round(max(Spnew[,1],na.rm=TRUE),10))] } if (length(cutpointsSe)== 1) { cMaxSe <- cutpointsSe } optimal.cutoff <- obtain.optimal.measures(cMaxSe, measures.acc) res <- list(measures.acc = measures.acc, optimal.cutoff = optimal.cutoff) res }
vcgCreateKDtree <- function(mesh, nofPointsPerCell=16,maxDepth=64) { if (is.matrix(mesh)) { if (ncol(mesh) == 2) mesh <- cbind(mesh,0) if (ncol(mesh) == 3) { mesh <- list(vb=t(mesh)) class(mesh) <- "mesh3d" } else stop("if query is a matrix, only 2 or 3 columns are allowed") } out <- .Call("createKDtree",mesh,nofPointsPerCell,maxDepth) class(out) <- "vcgKDtree" return(out) } vcgSearchKDtree <- function(kdtree, query,k ,threads=0) { if (!inherits(kdtree,"vcgKDtree")) stop("no valid kdtree") if (is.matrix(query)) { if (ncol(query) == 2) query <- cbind(query,0) if (ncol(query) == 3) { query <- list(vb=t(query)) class(query) <- "mesh3d" } else stop("if query is a matrix, only 2 or 3 columns are allowed") } else { if(!inherits(query,"mesh3d")) stop("only meshes or matrices allowed") } out <- .Call("RsearchKDtree",kdtree$kdtree,kdtree$target,query,k,threads) out$index <- out$index+1 return(out) } vcgCreateKDtreeFromBarycenters <- function(mesh, nofPointsPerCell=16,maxDepth=64) { mesh <- meshintegrity(mesh,facecheck=TRUE) barycenters <- vcgBary(mesh) out <- vcgCreateKDtree(barycenters,nofPointsPerCell,maxDepth) out$targetptr <- .Call("RmeshXPtr",mesh) class(out) <- "vcgKDtreeWithBarycenters" return(out) } vcgClostOnKDtreeFromBarycenters <- function(x,query,k=50,sign=TRUE,barycentric=FALSE, borderchk = FALSE, angdev=NULL, weightnorm=FALSE, facenormals=FALSE,threads=1) { if (! inherits(x,"vcgKDtreeWithBarycenters")) stop("provide valid object") if (is.matrix(query) && is.numeric(query)) { query <- list(vb=t(query)) class(query) <- "mesh3d" } else if (!inherits(query,"mesh3d")) { stop("argument 'mesh' needs to be object of class 'mesh3d'") } if (is.null(angdev) || is.null(query$it)) angdev <- 0 out <- .Call("RsearchKDtreeForClosestPoints",x$kdtree,x$target,x$targetptr,query,k,sign,borderchk,barycentric,angdev,weightnorm,facenormals,threads) out$it <- query$it return(out) }
edg <- function(y, a, b, m=2) { r3 <- (a + b*m^3)/(a + b*m*m)^(3/2) r4 <- (a + b*m^4)/(a + b*m*m)^2 x <- (1 + 1/(24*(a + b*m*m)))*(y + .5 - a - b*m)/sqrt(a + b*m*m) He2 <- x*x - 1 He3 <- x^3 - 3*x He5 <- x^5 - 10*x^3 + 15*x return(pnorm(x) - dnorm(x)*(r3*He2/6 + He3*r4/24 + r3*r3*He5/72)) }
ss.calc<- function(power=0.8, Case.Rate=NULL, k=NULL, MAF=NULL, OR=NULL, Alpha=0.05, True.Model='All', Test.Model='All') { if(is.null(k)==T & is.null(Case.Rate)==T){ stop("k, the number of controls per case, or Case.Rate, the proportion of cases in the study sample, must be specified.") } if(is.null(k)==F & is.null(Case.Rate)==F){ stop("Specify one of k, the number of controls per case, or Case.Rate, the proportion of cases in the study sample, not both.") } if(is.null(MAF)==T){ stop("MAF (minor allele frequency) must be specified.") } if(is.null(OR)==T){ stop("OR (detectable odds ratio) must be specified.") } if(sum(Case.Rate>=1)>0 | sum(Case.Rate<=0)>0){ stop("R2 must be greater than 0 and less than 1.") } if(sum(MAF>=1)>0 | sum(MAF<=0)>0){ stop("MAF must be greater than 0 and less than 1.") } if(sum(power>=1)>0 | sum(power<=0)>0){ stop("Power must be greater than 0 and less than 1.") } if(sum(k<=0)>0){ stop("k must be greater than 0.") } if(sum(OR<=0)>0){ stop("OR must be greater than 0.") } if(sum(Alpha>=1)>0 | sum(Alpha<=0)>0){ stop("Alpha must be greater than 0 and less than 1.") } if(sum(!(Test.Model %in% c("Dominant", "Recessive", "Additive", "2df", "All")))>0){ stop(paste("Invalid Test.Model:", paste(Test.Model[!(Test.Model %in% c("Dominant", "Recessive", "Additive", "2df", "All"))], collapse=', '))) } if(sum(!(True.Model %in% c("Dominant", "Recessive", "Additive", "All")))>0){ stop(paste("Invalid True.Model:", paste(True.Model[!(True.Model %in% c("Dominant", "Recessive", "Additive", "All"))], collapse=', '))) } if('All' %in% Test.Model){Test.Model<-c("Dominant", "Recessive", "Additive", "2df")} if('All' %in% True.Model){True.Model<-c("Dominant", "Recessive", "Additive")} if(is.null(Case.Rate)==T){Case.Rate = 1/(1+k)} power.tab <- expand.grid(power, Case.Rate) colnames(power.tab) <- c('power', 'Case.Rate') iter <- nrow(power.tab) final.ss.tab <- NULL for (zz in 1:iter){ power <- power.tab[zz,"power"] Case.Rate <- power.tab[zz,'Case.Rate'] o.save.tab <-NULL for (o in OR){ m.save.tab<-NULL for (m in MAF){ save.tab <- NULL P_AA <- (1-m)^2 P_AB <- 2*m*(1-m) P_BB <- m^2 if('Dominant' %in% True.Model){ a <- (1-o) b <- (P_AA-Case.Rate+o*(Case.Rate+P_AB+P_BB)) c <- -o*(P_AB+P_BB)*Case.Rate soln <- quad_roots(a,b,c)[2] P_AA_case_d <- (Case.Rate-soln)/P_AA P_AB_case_d <- P_BB_case_d <- soln/(P_AB+P_BB) prob_AA_case_d <- P_AA_case_d*P_AA prob_AB_case_d <- P_AB_case_d*P_AB prob_BB_case_d <- P_BB_case_d*P_BB prob_AA_control_d <- (1-P_AA_case_d)*P_AA prob_AB_control_d <- (1-P_AB_case_d)*P_AB prob_BB_control_d <- (1-P_BB_case_d)*P_BB dom.tab <- data.frame(model=rep('Dominant',2),table=rbind(c(prob_AA_case_d, prob_AB_case_d, prob_BB_case_d), c(prob_AA_control_d, prob_AB_control_d,prob_BB_control_d))) save.tab<-rbind(save.tab, dom.tab) } if('Additive' %in% True.Model){ a <- (o-1) b <- (P_AB+o*P_BB+Case.Rate-Case.Rate*o) c <- -P_AB*Case.Rate soln <- quad_roots(a,b,c)[2] upper.lim<-min(soln, P_AB) fa.1<-function(x){o-x*(P_AA-Case.Rate+x+((o*x*P_BB)/(P_AB-x+o*x)))/((Case.Rate-x-((o*x*P_BB)/(P_AB-x+o*x)))*(P_AB-x))} trial<-fa.1(upper.lim) counter<-0 while(trial>0 & counter<1000){upper.lim<-upper.lim-0.00000000001 trial<-fa.1(upper.lim) counter<-counter+1 } add1.root<-uniroot(fa.1,lower = 0, upper = upper.lim)$root P_AB_case_a1 <- add1.root/P_AB prob_AB_case_a1 <- P_AB_case_a1*P_AB prob_AB_control_a1 <- (1-P_AB_case_a1)*P_AB prob_AA_case_a1 <-P_AA*prob_AB_case_a1/(o*prob_AB_control_a1+prob_AB_case_a1) prob_AA_control_a1 <- P_AA-prob_AA_case_a1 prob_BB_case_a1 <- (prob_AA_case_a1*P_BB*o^2)/(prob_AA_case_a1*o^2 + prob_AA_control_a1) prob_BB_control_a1 <- P_BB-prob_BB_case_a1 add.tab1<-data.frame(model=rep('Additive',2),table=rbind(c(prob_AA_case_a1, prob_AB_case_a1, prob_BB_case_a1), c(prob_AA_control_a1, P_AB-prob_AB_case_a1,prob_BB_control_a1))) save.tab<-rbind(save.tab, add.tab1) } if('Recessive' %in% True.Model){ a <- (1-o) b <- o*P_BB+(o-1)*Case.Rate+P_AA + P_AB c <- -o*(P_BB)*Case.Rate soln <- quad_roots(a,b,c)[2] P_AB_case_r <- P_AA_case_r <- (Case.Rate-soln)/(P_AB+P_AA) P_BB_case_r <- soln/P_BB prob_AA_case_r <- P_AA_case_r*P_AA prob_AB_case_r <- P_AB_case_r*P_AB prob_BB_case_r <- P_BB_case_r*P_BB prob_AA_control_r <- (1-P_AA_case_r)*P_AA prob_AB_control_r <- (1-P_AB_case_r)*P_AB prob_BB_control_r <- (1-P_BB_case_r)*P_BB rec.tab<-data.frame(model=rep('Recessive',2),table=rbind(c(prob_AA_case_r, prob_AB_case_r, prob_BB_case_r), c(prob_AA_control_r, P_AB-prob_AB_case_r,prob_BB_control_r))) save.tab<-rbind(save.tab, rec.tab) } m.save.tab<-rbind(m.save.tab, data.frame(True.Model = save.tab[,1], MAF=m, OR = o, Disease.Status = rep(c('case', "control"),nrow(save.tab)/2), Geno.AA = save.tab[,2],Geno.AB = save.tab[,3], Geno.BB = save.tab[,4])) } o.save.tab<-rbind(o.save.tab, m.save.tab) } ss.tab<-NULL for (mod in Test.Model){ temp<-NULL for (j in seq(1, nrow(o.save.tab),2)){ t<-o.save.tab[j:(j+1),c("Geno.AA", "Geno.AB", "Geno.BB")] ll.alt<-calc.like(logistic.mles(t, model = mod), t, model=mod) ll.null<-null.ll(t) stat<-2*(as.numeric(ll.alt-ll.null)) ss<-NULL for (q in 1:length(Alpha)){ if(mod=='2df'){ ss = c(ss, uniroot(function(x) ncp.search(x=x, power=power, Alpha=Alpha[q], df=2), lower=0, upper=1000, extendInt = 'upX', tol=0.00001)$root/stat) }else{ss = c(ss, uniroot(function(x) ncp.search(x=x, power=power, Alpha=Alpha[q], df=1), lower=0, upper=1000, extendInt = 'upX', tol=0.00001)$root/stat) } } temp<-rbind(temp, ss) } ss.tab<-rbind(ss.tab,data.frame(Test.Model=mod, o.save.tab[seq(1, nrow(o.save.tab),2),1:3], Power=power, Case.Rate,temp)) } colnames(ss.tab)<-c('Test.Model', 'True.Model', 'MAF', 'OR', 'Power','Case.Rate', paste("N_total_at_Alpha_", Alpha, sep='')) final.ss.tab<-rbind(final.ss.tab, ss.tab) } return(final.ss.tab) }
LaplaceMetropolis_gaussian <- function(theta, data = NULL, data_y, prior_p, prior_st, method = c("likelihood", "L1center", "median")) { method = match.arg(method) theta = as.matrix(theta) niter = length(theta[,1]) p = length(theta[1,]) if(method == "likelihood") { h = NULL for(t in (1:niter)) { h = c(h, margin_like_gaussian(theta[t,], data, data_y) + margin_prior_gaussian(theta[t,], data, prior_p = prior_p, prior_st = prior_st)) hmax = max(h) } } if(method == "L1center") { L1sum = NULL oneniter = as.matrix(rep(1,niter)) onep = as.matrix(rep(1,p)) for(t in (1:niter)) { thetat = theta[t,] thetatmat = oneniter %*% thetat L1sum = c(L1sum, sum(abs((theta - oneniter %*% thetat) %*% onep))) } argL1center = min((1:niter)[L1sum == min(L1sum)]) thetaL1center = theta[argL1center,] hmax = margin_like_gaussian(thetaL1center, data, data_y) + margin_prior_gaussian(thetaL1center, data, prior_p = prior_p, prior_st = prior_st) } if(method == "median") { thetamed = apply(theta, 2, median) hmax = margin_like_gaussian(thetamed, data, data_y) + margin_prior_gaussian(thetamed, data, prior_p = prior_p, prior_st = prior_st) } if(p == 1) { logdetV = 2 * log(mad(theta[,1])) } else { eigenval = eigen(cov.mve(theta)$cov)$values logdetV = sum(log(eigenval[which(eigenval > 0)])) } return(hmax + 0.5 * p * log(2 * pi) + 0.5 * logdetV) }
plot.cROC <- function(x, ask = TRUE, ...) { change.ROC.format <- function(p, ROC) { temp <- reshape(ROC, varying = paste("p", round(p, 3), sep = ""), sep = "", v.names = "ROC", timevar = "p", times = p, idvar = "comb", direction = "long") temp[order(temp$comb),] } plot.accuracy <- function(ROC, names.cat, n.cat, n.levels, names.cont, exp.cat, dim.exp.cat, range.marker, accuracy, accuracy.main, dots, ask, ci.fit) { if(ask) readline("Press return for next page....") if(ci.fit) { accuracy.ci <- paste(accuracy,c("ql","qh"),sep="") } if (n.cat == 0) { plot(ROC[ , names.cont], ROC[ , accuracy], xlab = names.cont, ylab = accuracy, xlim = range(ROC[ , names.cont]), ylim = if(accuracy == "TH") range.marker else c(0,1), type = "l", main = accuracy.main) if(ci.fit) { lines(ROC[ , names.cont], ROC[ , accuracy.ci[1]], lty=2) lines(ROC[ , names.cont], ROC[ , accuracy.ci[2]], lty=2) } if (accuracy == "AUC") abline(h = 0.5, col = "grey") } else { if (n.cat == 1) { for(i in 1:dim.exp.cat) { if(ci.fit) { plot(ROC[ROC[, names.cat] == exp.cat[i, ], names.cont], ROC[ROC[, names.cat] == exp.cat[i, ], accuracy], xlab = names.cont, ylab = accuracy, xlim = range(ROC[ , names.cont]), ylim = if(accuracy == "TH") range.marker else c(0,1), type="l", main = paste0(accuracy.main, " \n ", paste(names.cat, "=", exp.cat[i,,drop = TRUE]))) lines(ROC[ROC[, names.cat] == exp.cat[i, ], names.cont], ROC[ROC[, names.cat] == exp.cat[i, ], accuracy.ci[1]], lty=2) lines(ROC[ROC[, names.cat] == exp.cat[i, ], names.cont], ROC[ROC[, names.cat] == exp.cat[i, ], accuracy.ci[2]], lty=2) if (accuracy == "AUC") abline(h = 0.5, col = "grey") if(ask & i < dim.exp.cat) readline("Press return for next page....") } else { if(i==1) plot(ROC[ROC[, names.cat] == exp.cat[i, ], names.cont], ROC[ROC[, names.cat] == exp.cat[i, ], accuracy], xlab = names.cont, ylab = accuracy, xlim = range(ROC[ , names.cont]), ylim = if(accuracy == "TH") range.marker else c(0,1), type="l", main = accuracy.main) else lines(ROC[ROC[, names.cat] == exp.cat[i, ], names.cont], ROC[ROC[, names.cat] == exp.cat[i, ], accuracy], lty=i) if (accuracy == "AUC") abline(h = 0.5, col = "grey") } } if(!ci.fit) legend(if(!is.null(dots$pos.legend)) dots$pos.legend else "bottomright", legend = paste(names.cat, "=", exp.cat[, , drop = TRUE]), lty=1:dim.exp.cat, cex = if(!is.null(dots$cex.legend)) dots$cex.legend else 1, y.intersp = if(!is.null(dots$y.intersp.legend)) dots$y.intersp.legend else 1) } else { for (i in 1:dim.exp.cat) { ind <- apply(t(apply(ROC[, names.cat], 1, function(x) x == exp.cat[i, ])), 1, all) if(ci.fit) { print(paste0(accuracy.main, " \n ", paste(paste(names.cat,"=",as.matrix(exp.cat)[i,]), collapse = ", "))) plot(ROC[ind, names.cont], ROC[ind, accuracy], xlab = names.cont, ylab = accuracy, xlim = range(ROC[ , names.cont]), ylim = if(accuracy == "TH") range.marker else c(0,1), type="l", main = paste0(accuracy.main, " \n ", paste(paste(names.cat,"=",as.matrix(exp.cat)[i,]), collapse = ", "))) lines(ROC[ind, names.cont], ROC[ind, accuracy.ci[1]], lty = i) lines(ROC[ind, names.cont], ROC[ind, accuracy.ci[2]], lty = i) if (accuracy == "AUC") abline(h = 0.5, col = "grey") if(ask & i < dim.exp.cat) readline("Press return for next page....") } else { if(i==1) plot(ROC[ind, names.cont], ROC[ind, accuracy], xlab = names.cont, ylab = accuracy, xlim = range(ROC[ , names.cont]), ylim = if(accuracy == "TH") range.marker else c(0,1), type="l", main = accuracy.main) else lines(ROC[ind, names.cont], ROC[ind, accuracy], lty = i) if (accuracy == "AUC") abline(h = 0.5, col = "grey") } } if(!ci.fit) legend(if(!is.null(dots$pos.legend)) dots$pos.legend else "bottomright", legend = sapply(1:dim.exp.cat, function(s) paste(paste(names.cat,"=",as.matrix(exp.cat)[s,]), collapse = ", ")), lty = 1:dim.exp.cat, cex = if(!is.null(dots$cex.legend)) dots$cex.legend else 1, y.intersp = if(!is.null(dots$y.intersp.legend)) dots$y.intersp.legend else 1) } } } dots <- list(...) ci.fit <- ifelse(is.null(x$ci.fit),FALSE,x$ci.fit) p <- x$p n.p <- length(p) colnames(x$ROC$est) <- paste("p", round(x$p, 3), sep = "") ROC <- cbind(x$newdata, x$ROC$est) set.accuracy <- c("AUC", "pAUC") if(is.null(x$pAUC)) { pAUC.legend <- "" pAUC.main <- "" } else { pAUC.legend <- ifelse(attr(x$pAUC, "focus") == "FPF", paste0(" (FPF = ", attr(x$pAUC, "value"), ")"), paste0(" (Se = ", attr(x$pAUC, "value"), ")")) pAUC.main <- ifelse(attr(x$pAUC, "focus") == "FPF", paste0("Partial area under the conditional ROC curve", pAUC.legend), paste0("Partial area under the specificity conditional ROC curve", pAUC.legend)) } set.accuracy.legend <- c("AUC", paste0("pAUC", pAUC.legend)) set.accuracy.main <- c("Area under the conditional ROC curve", pAUC.main) ind.accuracy <- is.element(set.accuracy, set.accuracy[is.element(set.accuracy, names(x))]) if(any(ind.accuracy)) { accuracy <- set.accuracy[ind.accuracy] accuracy.main <- set.accuracy.main[ind.accuracy] accuracy.legend <- set.accuracy.legend[ind.accuracy] } else { accuracy <- NULL } if(!is.null(accuracy)) { for (i in 1:length(accuracy)){ aux <- names(ROC) ROC <- cbind(ROC, x[[accuracy[i]]]) names(ROC) <- c(aux, colnames(x[[accuracy[i]]])) } } range.marker <- range(x$data[, x$marker], na.rm = TRUE) names.cov <- names(ROC[, 1:(ncol(ROC) - n.p - (2*ci.fit+1)*sum(ind.accuracy)), drop = FALSE]) ind.cat <- unlist(lapply(ROC[ ,names.cov, drop = FALSE], is.factor)) names(ind.cat) <- names.cov names.cont <- names.cov[!ind.cat] n.cont <- length(names.cont) n.cat <- sum(ind.cat) names.cat <- if(n.cat > 0) names.cov[ind.cat] delete.obs <- duplicated(x$newdata) ROC <- ROC[!delete.obs,,drop = FALSE] if (n.cont > 1) { ROC[, names.cont] <- apply(round(ROC[ , names.cont, drop = FALSE], 3), 2, factor) } if (n.cat > 0) { exp.cat <- unique(ROC[, names.cat, drop = FALSE]) exp.cat.matrix <- as.matrix(exp.cat) dim.exp.cat <- nrow(exp.cat) levels.cat <- if(n.cat > 0) lapply(ROC[, names.cat, drop = FALSE], levels) n.levels <- as.numeric(unlist(lapply(levels.cat, length))) if(n.cont == 0) { ROC.long <- change.ROC.format(p, ROC) print(xyplot(as.formula(paste("ROC ~ p |", paste(names.cat, collapse = "+"))), data = ROC.long, ylim = c(-0.1,1.05), xlab = "FPF", ylab = "TPF", strip = strip.custom(strip.names = TRUE, strip.levels = TRUE, sep = " = ", par.strip.text = list(cex = if(!is.null(dots$cex.par.strip.text)) dots$cex.par.strip.text else 0.75)), panel = function(x, y, subscripts) { panel.xyplot(x, y, type = "l") for (i in 1:length(set.accuracy)) if(ind.accuracy[i]) { acc.val <- round(unique(ROC.long[subscripts, set.accuracy[i]]),2) if(ci.fit) { acc.val <- paste(acc.val, "(", round(unique(ROC.long[subscripts, paste(set.accuracy[i],"ll",sep="")]),2),", ",round(unique(ROC.long[subscripts, paste(set.accuracy[i],"ul",sep="")]),2),")", sep="") } ltext(0.99, 0.01 + (if(!is.null(dots$y.intersp.legend)) dots$y.intersp.legend else 0.14) * (i-1), labels = paste(accuracy.legend[i],"=",acc.val), adj = c(1,0.5), cex = if(!is.null(dots$cex.legend)) dots$cex.legend else 0.5) } })) } else { if(n.cont == 1) { if (length(names.cat) == 1) { for(i in 1:dim.exp.cat) { if(i > 1) { if(ask) readline("Press return for next page....") } persp(p, ROC[ROC[ , names.cat] == exp.cat[i, ], names.cont], t(as.matrix(ROC[ROC[ , names.cat] == exp.cat[i, ], -(c(1:(1 + n.cat), if(!is.null(accuracy)) ncol(ROC):(ncol(ROC) + 1 - (2*ci.fit+1)*length(accuracy))))])), xlab = "FPF", ylab = names.cont, zlab = "TPF", main = paste0("Conditional ROC surface \n ", exp.cat.matrix[i, ]), theta = if (!is.null(dots$theta))dots$theta else 20, phi = if (!is.null(dots$phi))dots$phi else 30, col = if(!is.null(dots$col))dots$col else "white", shade = if(!is.null(dots$shade))dots$shade else 0.5, ticktype = "detailed", cex.axis = dots$cex.axis, cex.lab = dots$cex.lab, cex.main = dots$cex.main, cex = dots$cex) } if(any(ind.accuracy)) for(i in (1:length(set.accuracy))[ind.accuracy]) plot.accuracy(ROC, names.cat, n.cat, n.levels, names.cont, exp.cat, dim.exp.cat, range.marker, set.accuracy[i], set.accuracy.main[i], dots, ask, ci.fit) } else { oldpar <- par(no.readonly = TRUE) on.exit(par(oldpar)) par(mfrow = n.levels[1:2]) for (i in 1:(dim.exp.cat/prod(n.levels[1:2]))) { if(i > 1) { if(ask) readline("Press return for next page....") } k <- 0 for (j in 1:(n.levels[1]*n.levels[2])) { ind <- apply(t(apply(ROC[,names.cat], 1, function(x) x == exp.cat[(i-1)*prod(n.levels[1:2]) + j,])), 1, all) persp(p, ROC[ind, names.cont], t(as.matrix(ROC[ind, -(c(1:(n.cont + n.cat),if(!is.null(accuracy)) ncol(ROC):(ncol(ROC) + 1 - (2*ci.fit+1)*length(accuracy))))])), xlab = "FPF", ylab = names.cont, zlab="TPF", main = paste(paste(names.cat, "=", c(exp.cat.matrix[j,1:2], exp.cat.matrix[1+(i-1)*prod(n.levels[1:2]),-(1:2)])), collapse = ", "), theta = if (!is.null(dots$theta))dots$theta else 20, phi = if (!is.null(dots$phi))dots$phi else 30, col = if(!is.null(dots$col))dots$col else "white", shade = if(!is.null(dots$shade))dots$shade else 0.5, ticktype = "detailed", cex.axis = dots$cex.axis, cex.lab = dots$cex.lab, cex.main = dots$cex.main,cex = dots$cex) } } if(any(ind.accuracy)) for(i in (1:length(set.accuracy))[ind.accuracy]) plot.accuracy(ROC, names.cat, n.cat, n.levels, names.cont, exp.cat, dim.exp.cat, range.marker, set.accuracy[i], set.accuracy[i], dots, ask, ci.fit) } } else { cat.cont <- vector("list", dim.exp.cat) for(i in 1:dim.exp.cat) { cat.cont[[i]] <- vector("list", n.cont) for(j in 1:n.cont) { ind <- t(apply(ROC[ , names.cat, drop = F], 1, function(x) x == exp.cat[i, ])) if(dim(ind)[1] == 1) ind <- t(ind) cat.cont[[i]][[j]] <- unique(ROC[apply(ind, 1, all), names.cont[j]]) } } n.comb <- c(0, as.numeric(cumsum(unlist(lapply(cat.cont, function(x)cumprod(lapply(x, length))[n.cont]))))*n.p) ROC.long <- change.ROC.format(p, ROC) for (i in 1:dim.exp.cat) { if(i > 1 && ask) { readline("Press return for next page....") } print(xyplot(as.formula(paste("ROC ~ p |", paste(names.cont, collapse = "+"))), data = ROC.long, ylim = c(-0.1,1.05), subset = (1 + n.comb[i]):n.comb[i + 1], strip = strip.custom(style = 3, strip.names = TRUE, strip.levels = TRUE, sep = " = ", par.strip.text = list(cex = if(!is.null(dots$par.strip.text)) dots$par.strip.text else 0.75)), panel = function(x, y, subscripts) { panel.xyplot(x, y, type = "l") for (j in 1:length(set.accuracy)) if(ind.accuracy[j]) { acc.val <- round(unique(ROC.long[subscripts, set.accuracy[j]]),2) if(ci.fit) { acc.val <- paste(acc.val, "(", round(unique(ROC.long[subscripts, paste(set.accuracy[j],"ql",sep="")]),2),", ",round(unique(ROC.long[subscripts, paste(set.accuracy[j],"qh",sep="")]),2),")", sep="") } ltext(0.99, 0.01 + (if(!is.null(dots$y.intersp.legend)) dots$y.intersp.legend else 0.14) * (j-1), labels = paste(accuracy.legend[j],"=",acc.val), adj = c(1,0.5), cex = if(!is.null(dots$cex.legend)) dots$cex.legend else 1) } }, main = paste(names.cat, "=", exp.cat.matrix[i, ]))) } } } } else { if(n.cont == 1) { persp(p, ROC[ , names.cont], t(as.matrix(ROC[ ,-(c(1:(1 + n.cat), if(!is.null(accuracy)) ncol(ROC):(ncol(ROC) + 1 - (2*ci.fit+1)*length(accuracy))))])), xlab = "FPF", ylab = names.cont, zlab = "TPF", main = "Conditional ROC surface", theta = if (!is.null(dots$theta))dots$theta else 20, phi = if (!is.null(dots$phi))dots$phi else 30, col = if(!is.null(dots$col))dots$col else "white", shade = if(!is.null(dots$shade))dots$shade else 0.5, ticktype = "detailed", cex.axis = dots$cex.axis, cex.lab = dots$cex.lab, cex.main = dots$cex.main,cex = dots$cex) if(any(ind.accuracy)) for(i in (1:length(set.accuracy))[ind.accuracy]) plot.accuracy(ROC, names.cat, n.cat, n.levels, names.cont, exp.cat, dim.exp.cat, range.marker, set.accuracy[i], set.accuracy.main[i], dots, ask, ci.fit) } else { ROC.long <- change.ROC.format(p, ROC) print(xyplot(as.formula(paste("ROC ~ p |", paste(names.cont, collapse = "+"))), data = ROC.long, ylim = c(-0.1,1.05), strip = strip.custom(style = 3, strip.names = TRUE, strip.levels = TRUE, sep = " = ", par.strip.text = list(cex = if(!is.null(dots$par.strip.text)) dots$par.strip.text else 0.75)), panel = function(x, y, subscripts) { panel.xyplot(x, y, type = "l") for (i in 1:length(set.accuracy)) if(ind.accuracy[i]) { acc.val <- round(unique(ROC.long[subscripts, set.accuracy[i]]),2) if(ci.fit) { acc.val <- paste(acc.val, "(", round(unique(ROC.long[subscripts, paste(set.accuracy[i],"ll",sep="")]),2),", ",round(unique(ROC.long[subscripts, paste(set.accuracy[i],"ul",sep="")]),2),")", sep="") } ltext(0.99, 0.01 + (if(!is.null(dots$y.intersp.legend)) dots$y.intersp.legend else 0.14) * (i-1), labels = paste(accuracy.legend[i],"=",acc.val), adj = c(1,0.5), cex = if(!is.null(dots$cex.legend)) dots$cex.legend else 0.5) } } )) } } }
NULL NULL NULL NULL NULL utils::globalVariables(names=c('beanplot','Change','env','gamlss','hPlot', 'initDate','initEq','melt','mktdata','param.combo', 'Period','plotSimpleGamlss','price','redisClose', 'redisConnect','redisGetContext','timespan'))
GetDashboards<- function(dashboard.limit='', dashboard.offset='') { request.body <- c() request.body$locale <- unbox(AdobeAnalytics$SC.Credentials$locale) request.body$elementDataEncoding <- unbox("utf8") if(dashboard.limit != ''){ request.body$dashboard_limit <- dashboard.limit } if(dashboard.offset != ''){ request.body$dashboard_offset <- dashboard.offset } response <- ApiRequest(body=toJSON(request.body),func.name="Bookmark.GetDashboards") if(length(response$dashboards[[1]]) == 0) { return(print("No Dashboards Defined For This Report Suite")) } response_df<- response[[1]] pages <- response_df$pages response_df$pages <- NULL response_df <- cbind(response_df, ldply(pages, quickdf)) bookmarks <- response_df$bookmarks response_df$bookmarks <- NULL accumulator<- data.frame() for(i in 1:nrow(response_df)){ bkmk_parsed <- ldply(bookmarks[[i]],quickdf) temp <- cbind(response_df[i,], bkmk_parsed, row.names = NULL) accumulator <- rbind.fill(accumulator, temp) } return(accumulator) }
UncInd <- function (Flow = NULL, Tij = t(Flow), Import =NULL, Export =NULL) { N <- InternalNetwork (Tij,Import,Export) ncTij <- ncol(Tij) nrTij <- nrow(Tij) ncomp <- ncol(N$Tint) compNames <- rownames(N$Tint) Throughput <- sum(Tij) Ascend <- Ascendfun(Tij,1:nrow(Tij),1:ncol(Tij)) AMI <- Ascend[[1]] / Throughput Q <- N$FlowFrom/Throughput Q <- Q[Q>0] HR <- -sum(Q*log2(Q)) DR <- HR - AMI RU <- AMI/HR Hmax <- ncomp*log2(nrTij) blsum <- 0 for (i in 1:nrTij) { for (j in N$jN) { if (Tij[i,j]>0) blsum <- blsum + (Tij[i,j]/N$FlowFrom[j])*log2(Tij[i,j]/N$FlowFrom[j]) } } Hc <- Hmax + blsum names(Hc)<-NULL CE <- Hc/Hmax Hsys <- Hmax - Hc list(AMI=AMI, HR=HR, DR=DR, RU=RU,Hmax=Hmax,Hc=Hc, Hsys=Hsys,CE=CE) }
library(checkargs) context("isNonZeroIntegerOrNaOrNanOrInfVector") test_that("isNonZeroIntegerOrNaOrNanOrInfVector works for all arguments", { expect_identical(isNonZeroIntegerOrNaOrNanOrInfVector(NULL, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNonZeroIntegerOrNaOrNanOrInfVector(TRUE, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNonZeroIntegerOrNaOrNanOrInfVector(FALSE, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNonZeroIntegerOrNaOrNanOrInfVector(NA, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroIntegerOrNaOrNanOrInfVector(0, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNonZeroIntegerOrNaOrNanOrInfVector(-1, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroIntegerOrNaOrNanOrInfVector(-0.1, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNonZeroIntegerOrNaOrNanOrInfVector(0.1, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNonZeroIntegerOrNaOrNanOrInfVector(1, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroIntegerOrNaOrNanOrInfVector(NaN, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroIntegerOrNaOrNanOrInfVector(-Inf, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroIntegerOrNaOrNanOrInfVector(Inf, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroIntegerOrNaOrNanOrInfVector("", stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNonZeroIntegerOrNaOrNanOrInfVector("X", stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNonZeroIntegerOrNaOrNanOrInfVector(c(TRUE, FALSE), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNonZeroIntegerOrNaOrNanOrInfVector(c(FALSE, TRUE), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNonZeroIntegerOrNaOrNanOrInfVector(c(NA, NA), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroIntegerOrNaOrNanOrInfVector(c(0, 0), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNonZeroIntegerOrNaOrNanOrInfVector(c(-1, -2), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroIntegerOrNaOrNanOrInfVector(c(-0.1, -0.2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNonZeroIntegerOrNaOrNanOrInfVector(c(0.1, 0.2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNonZeroIntegerOrNaOrNanOrInfVector(c(1, 2), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroIntegerOrNaOrNanOrInfVector(c(NaN, NaN), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroIntegerOrNaOrNanOrInfVector(c(-Inf, -Inf), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroIntegerOrNaOrNanOrInfVector(c(Inf, Inf), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroIntegerOrNaOrNanOrInfVector(c("", "X"), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNonZeroIntegerOrNaOrNanOrInfVector(c("X", "Y"), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_error(isNonZeroIntegerOrNaOrNanOrInfVector(NULL, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNonZeroIntegerOrNaOrNanOrInfVector(TRUE, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNonZeroIntegerOrNaOrNanOrInfVector(FALSE, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_identical(isNonZeroIntegerOrNaOrNanOrInfVector(NA, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_error(isNonZeroIntegerOrNaOrNanOrInfVector(0, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_identical(isNonZeroIntegerOrNaOrNanOrInfVector(-1, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_error(isNonZeroIntegerOrNaOrNanOrInfVector(-0.1, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNonZeroIntegerOrNaOrNanOrInfVector(0.1, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_identical(isNonZeroIntegerOrNaOrNanOrInfVector(1, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroIntegerOrNaOrNanOrInfVector(NaN, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroIntegerOrNaOrNanOrInfVector(-Inf, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroIntegerOrNaOrNanOrInfVector(Inf, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_error(isNonZeroIntegerOrNaOrNanOrInfVector("", stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNonZeroIntegerOrNaOrNanOrInfVector("X", stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNonZeroIntegerOrNaOrNanOrInfVector(c(TRUE, FALSE), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNonZeroIntegerOrNaOrNanOrInfVector(c(FALSE, TRUE), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_identical(isNonZeroIntegerOrNaOrNanOrInfVector(c(NA, NA), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_error(isNonZeroIntegerOrNaOrNanOrInfVector(c(0, 0), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_identical(isNonZeroIntegerOrNaOrNanOrInfVector(c(-1, -2), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_error(isNonZeroIntegerOrNaOrNanOrInfVector(c(-0.1, -0.2), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNonZeroIntegerOrNaOrNanOrInfVector(c(0.1, 0.2), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_identical(isNonZeroIntegerOrNaOrNanOrInfVector(c(1, 2), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroIntegerOrNaOrNanOrInfVector(c(NaN, NaN), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroIntegerOrNaOrNanOrInfVector(c(-Inf, -Inf), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroIntegerOrNaOrNanOrInfVector(c(Inf, Inf), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_error(isNonZeroIntegerOrNaOrNanOrInfVector(c("", "X"), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNonZeroIntegerOrNaOrNanOrInfVector(c("X", "Y"), stopIfNot = TRUE, message = NULL, argumentName = NULL)) })
kaplanMeier_at_t0 <- function(time, event, t0){ obj <- survfit(Surv(time, event) ~ 1) Surv_t <- summary(obj)$surv t <- summary(obj)$time n <- summary(obj)$n.risk res <- rep(NA, length(t0)) for (i in 1:length(t0)){ ti <- t0[i] if (min(t) > ti){res[i] <- 1} if (min(t) <= ti){ if (ti %in% t){res[i] <- Surv_t[t == ti]} else { Surv_ti <- min(Surv_t[t < ti]) res[i] <- Surv_ti } } } res <- cbind(t0, res) dimnames(res)[[2]] <- c("t0", "S at t0") return(res) }
strmeasure=function(P,sorted=FALSE,depths=NULL,alpha=0,method="Mean"){ if(is.data.frame(P)) P=as.matrix(P) if(is.list(P)){ m=length(P) n=length(P[[1]]) y=matrix(0,n,m) for(i in 1:m){ y[,i]=P[[i]] if(length(P[[i]])!=n){ stop("When using a list, each element must be a vector of the same length.") } } P=y } match.arg(method,c("Tukey","Mean")) if(is.vector(P)) p=1 if(is.matrix(P)) p=ncol(P) if(p<1|p>2) stop("Data must be on the circle or on the sphere.") if(p==1){ if(max(P)>2*pi | min(P)<0) stop("In 2D, the dataset must be a vector of angles") if(method=="Mean") return(dirmoytronq(P,sort=sorted,profondeurs=depths,alpha=alpha)) if(method=="Tukey") return(tukmedtronq(P,sort=sorted,profondeurs=depths,alpha=alpha)) } if(p==2){ if(method=="Mean") return(sdirmoytronq(P,sort=FALSE,profondeurs=depths,alpha=alpha)) if(method=="Tukey") stop("Truncation based on Tukey is available for the circle only.") } } dirmoytronq=function(P,sort=FALSE,profondeurs=NULL,alpha=0) { n=length(P) if(length(profondeurs)==0) { for(i in 1:n) { profondeurs[i]=tukdepthc3(P,P[i])[[2]] } } if(sort==FALSE) { perm=order(P) P=P[perm] profondeurs=profondeurs[perm] } bonpoints=NULL bonpoints=P[which(profondeurs>=alpha)] if(length(bonpoints)!=0) { dm=mean.circular(circular(bonpoints))[[1]] if(dm<=0) { dm=dm+2*pi } } else { dm=NA } return(dm) } sdirmoytronq=function(P,sort=FALSE,profondeurs=NULL,alpha=0) { n=length(P[,1]) if(length(profondeurs)==0) { for(i in 1:n) { profondeurs[i]=tukdepths2(P,P[i,]) } } bonpoints=NULL bonpoints=P[which(profondeurs>=alpha),] if(length(bonpoints[,1])!=0) { dm=c(mean(bonpoints[,1]),mean(bonpoints[,2]),mean(bonpoints[,3])) if(sum(dm^2)==0) { dm=NA } else { dm=dm/sqrt(sum(dm^2)) } } else { dm=NA } return(dm) } tukmedtronq=function(P,sort=FALSE,profondeurs=NULL,alpha=0) { n=length(P) if(length(profondeurs)==0) { for(i in 1:n) { profondeurs[i]=tukdepthc3(P,P[i])[[2]] } } if(sort==FALSE) { perm=order(P) P=P[perm] profondeurs=profondeurs[perm] } bonpoints=NULL v=which(profondeurs>=alpha) bonpoints=P[v] if(length(bonpoints)!=0) { tmt=tukmedc(bonpoints) } else { tmt=NA } return(tmt) }
summary.findFn <- function(object, minPackages = 12, minCount=NA, ...) { Sum <- attr(object, 'PackageSummary') nrows <- nrow(Sum) minPackages <- min(nrows, minPackages, na.rm=TRUE) minCount <- { if(minPackages<1) 0 else min(minCount, Sum$Count[minPackages], na.rm=TRUE) } sel <- (Sum[, 'Count'] >= minCount) sumTh <- Sum[sel,, drop=FALSE] structure(list(PackageSummary = sumTh, minPackages = minPackages, minCount = minCount, matches = attr(object, "matches"), nrow = nrow(object), nPackages = length(sel), string = attr(object, 'string'), call = attr(object, "call")), class = c("summary.findFn", "list")) } print.summary.findFn <- function(x, ...) { cat("\nCall:\n") cat(paste(deparse(x$call), sep = "\n", collapse = "\n"), "\n\n", sep = "") cat("Total number of matches: ", sum( x$matches) , "\n", sep = "") cat('Downloaded ', x$nrow, ' links in ', x$nPackages, " package", c('.', 's.')[1 + (x$nPackages > 1)], "\n\n", sep='') string <- x$string cat("Packages with at least ", x$minCount, " match", if(x$minCount == 1) "" else "es", " using pattern\n '", string, "'\n", sep = "") packSum <- x$PackageSummary packSum$Date <- substr(packSum$Date, 1, regexpr(" ", packSum$Date) - 1) row.names(packSum) <- NULL print(packSum, ...) invisible() }
str_sub <- function(string, start = 1L, end = -1L) { if (is.matrix(start)) { stri_sub(string, from = start) } else { stri_sub(string, from = start, to = end) } } "str_sub<-" <- function(string, start = 1L, end = -1L, omit_na = FALSE, value) { if (is.matrix(start)) { stri_sub(string, from = start, omit_na = omit_na) <- value } else { stri_sub(string, from = start, to = end, omit_na = omit_na) <- value } string }
micSim <- function(initPop, immigrPop=NULL, transitionMatrix, absStates=NULL, initStates=c(), initStatesProb=c(), maxAge=99, simHorizon, fertTr=c(), dateSchoolEnrol='09/01', reportMothers = FALSE) { if(is.null(initPop)) stop('No starting population has been defined.') if(!is.null(initPop)){ if(paste(colnames(initPop),collapse='/')!='ID/birthDate/initState') stop('Matrix specifying the starting population has not been defined properly.') } if(!is.null(immigrPop)){ if(paste(colnames(immigrPop),collapse='/')!='ID/immigrDate/birthDate/immigrInitState') stop('Matrix specifying immigrants has not been defined properly.') } if(is.null(transitionMatrix)) stop('Matrix defining transition pattern und functions has not been defined properly.') if(maxAge<=0) stop('The maximal age until which individual life courses are simulated should exceed zero.') if(length(simHorizon)!=2) stop('The simulation horizon has not been defined properly.') if(class(simHorizon)[1]!='dates' & class(simHorizon)[2]!='dates') stop('The simulation horizon has not been defined properly.') if(is.null(absStates)) absStates <- setdiff(colnames(transitionMatrix),rownames(transitionMatrix)) if(length(fertTr)>0){ if(is.null(initStates) | is.null(initStatesProb)) stop('For children potentially born during simulation no inital state(s) and/or corresponding occurrence probabilities have been defined.') } if(length(fertTr)==0 & reportMothers){ warning('No fertility events are specified. Therefore, no offspring are produced during the simulation and linking of maternal IDs to newborn IDs is not possible. Check reportMothers argument or the definition of the fertility matrix fertTr.') } if(length(dateSchoolEnrol)==0){ dateSchoolEnrol <- '09/01' } queue <- matrix(NA,ncol=6,nrow=0) colnames(queue) <- c('ID','currTime','currState','currAge','nextState','timeToNextState') t.clock <- as.numeric(simHorizon[1]) transitions <- matrix(NA,ncol=5,nrow=0) colnames(transitions) <- c('ID', 'From', 'To', 'transitionTime', 'transitionAge') if(reportMothers){ mothers <- matrix(NA,ncol=2,nrow=0) } isLeapYear <- function(year) { return(((year %% 4 == 0) & (year %% 100 != 0)) | (year %% 400 == 0)) } getAgeInYears <- function(days) { date <- chron(days) c.y <- as.numeric(as.character(years(date))) completeYears <- c.y - 1970 daysInCY <- ifelse(isLeapYear(c.y), 366, 365) fracCY <- as.numeric(date - chron(paste(1,'/',1,'/',c.y), format=c(dates='d/m/y')) + 1)/daysInCY return(completeYears + fracCY) } isBirthEvent <- function(currState, destState){ if(length(fertTr)==0) return(FALSE) fert <- matrix(unlist(strsplit(fertTr,split='->')), ncol=2, byrow=TRUE) cS <- unlist(strsplit(currState,'/')) if(!("f" %in% cS)) return(FALSE) dS <- unlist(strsplit(destState,'/')) for(i in 1:nrow(fert)){ ff <- fert[i,] oS <- unlist(strsplit(ff[1],'/')) bS <- unlist(strsplit(ff[2],'/')) cond1 <- !(F %in% (oS %in% cS)) & !(F %in% (bS %in% dS)) cond2 <- paste((cS[!(cS %in% oS)]),collapse="/") == paste((dS[!(dS %in% bS)]),collapse="/") if(cond1 & cond2){ return(TRUE) } } return(FALSE) } addNewNewborn <- function(birthTime=birthTime, motherID=NULL){ birthState <- sample(apply(initStates,1,paste,collapse='/'),size=1,replace=T,prob=initStatesProb) if(is.null(immigrPop)){ id <- as.numeric(max(as.numeric(initPop[,'ID'])))+1 } else { id <- as.numeric(max(c(as.numeric(immigrPop[,'ID']),as.numeric(initPop[,'ID']))))+1 } birthDate <- dates(chron(birthTime, format=c(dates='d/m/Y', times='h:m:s'),out.format=c(dates='d/m/year', times='h:m:s'))) newInd <- c(id,as.character(birthDate),birthState) initPop <<- rbind(initPop,newInd) if(reportMothers) mothers <<- rbind(mothers, c(motherID, id)) nE <- getNextStep(c(id,birthState,0,birthTime)) } isSchoolEnrolment <- function(currState,destState){ enrol <- F if(T %in% ('no' %in% unlist(strsplit(currState,'/'))) & T %in% ('low' %in% unlist(strsplit(destState,'/')))) enrol <- T return(enrol) } getNextStep <- function(inp, isIMInitEvent=F){ id <- as.numeric(unlist(inp[1])) currState <- as.character(unlist(inp[2])) currAge <- as.numeric(unlist(inp[3])) calTime <- as.numeric(unlist(inp[4])) lagToWaitingTime <- ifelse(isIMInitEvent, (as.numeric(calTime) - as.numeric(simHorizon[1]))/365.25,0) ageInYears <- getAgeInYears(currAge) possTr <- transitionMatrix[which(rownames(transitionMatrix) %in% currState),] possTr <- possTr[which(possTr !=0)] nextEventMatrix <- matrix(0, ncol=2, nrow=length(possTr)) ranMaxAge <- maxAge-ageInYears ranMaxYear <- (as.numeric(simHorizon[2]) - calTime)/365.25 ran <- min(ranMaxYear,ranMaxAge) ranAge <- c(ageInYears,ageInYears+ranMaxAge) ranYear <- chron(c(calTime, as.numeric(calTime)+ran*365.25)) historiesInd <- transitions[as.numeric(transitions[,'ID']) %in% id & as.numeric(transitions[,'transitionTime']) <= calTime,,drop=F] initPopInd <- initPop[as.numeric(initPop[,'ID']) %in% id,] birthTime <- initPopInd['birthDate'] initState <- as.character(unlist(initPopInd['initState'])) if(as.numeric(birthTime) < as.numeric(simHorizon[1]) | id %in% as.numeric(immigrPop[,'ID'])) { dur <- rbind(c(initState,NA),cbind(historiesInd[,'To'], historiesInd[,'transitionTime'])) dur <- cbind(dur,c(diff(as.numeric(dur[,2])),0)) colnames(dur) <- c('TransitionTo','AtTime','durUntil') dur[which(is.na(dur[,'AtTime'])),'durUntil'] <- NA } else { birthTime <- initPop[as.numeric(initPop[,'ID']) %in% id, 'birthDate'] dur <- rbind(c(initState,birthTime),cbind(historiesInd[,'To'], historiesInd[,'transitionTime'])) dur <- cbind(dur,c(diff(as.numeric(dur[,2])),0)) colnames(dur) <- c('TransitionTo','AtTime','durUntil') } for(i in 1:length(possTr)){ tr <- possTr[i] destState <- names(tr) cS <- unlist(strsplit(currState,'/')) dS <- unlist(strsplit(destState, '/')) covToCh <- which((cS==dS)==F) durSinceLastCovCh <- Inf if(length(covToCh)==1){ covHist <- do.call(rbind,sapply(dur[,'TransitionTo'],strsplit,split='/'))[,covToCh] idd <- which(covHist==cS[covToCh]) if(length(idd)>1){ if(F %in% (diff(idd)==1)){ y <- rev(idd)[c(-1,diff(rev(idd)))==-1] idd <- rev(y)[c(diff(rev(y)),1)==1] } } durSinceLastCovCh <- sum(as.numeric(dur[idd,'durUntil'])) if(is.na(durSinceLastCovCh)) durSinceLastCovCh <- 0 } if(length(covToCh)>1 & (!destState %in% absStates)){ cat('Recognized a possible transition implying a change of two or more covariates.', 'Concerning the derivation of the time being elapsed since the last transition this feature is not yet implemented.', 'Current State: ',currState,' -> Possible transition to ',destState,'\n') } indRateFctDET <- function(x){ res <- eval(do.call(tr, args=list(age=trunc(ageInYears)+x,calTime=trunc(1970.001+calTime/365.25)+x,duration=trunc(durSinceLastCovCh/365.25)+x))) return(res) } ranAccuracyInDays <- (0:(trunc(ran*365.25)+1))/365.25 detE <- indRateFctDET(ranAccuracyInDays) daysToTrInYears <- (which(detE == Inf)[1] - 1)/365.25 if (Inf %in% detE) { timeToNext <- daysToTrInYears } else { u <- -log(1-runif(1)) indRateFct <- function(x){ ageIn <- ageInYears+x calIn <- 1970.001+calTime/365.25+x durIn <- durSinceLastCovCh/365.25+x res <- eval(do.call(tr, args=list(age=ageIn,calTime= calIn,duration=durIn))) if(TRUE %in% (res<0)) stop('I have found negative rate value/s for transition: ',tr,'\n This is implausible. Please check this. Simulation has been stopped.\n') return(res) } if(sum(indRateFct(0:ran))==0){ intHaz <- 0 } else { intHaz <- try(integrate(indRateFct, lower=0, upper=ran)$value, silent=TRUE) if(inherits(intHaz, 'try-error')){ intHaz <- integrate(indRateFct, lower=0, upper=ran, stop.on.error = FALSE, rel.tol = 0.01)$value } } if(u<=intHaz){ invHazFct <- function(x){ try.res <- try(integrate(indRateFct, lower=0, upper=x)$value-u, silent=TRUE) if(inherits(try.res, 'try-error')){ try.res <- integrate(indRateFct, lower=0, upper=x, stop.on.error = FALSE, rel.tol = 0.01)$value-u } return(try.res) } timeToNext <- uniroot(invHazFct,interval=c(0,ran))$root } else { timeToNext <- Inf } } nextEventMatrix[i,1] <- destState nextEventMatrix[i,2] <- (timeToNext+lagToWaitingTime)*365.25 } nE <- nextEventMatrix[which(nextEventMatrix[,2]==min(as.numeric(nextEventMatrix[,2]))),,drop=F] if(dim(nE)[1]>1) nE <- nE[1,,drop=F] if(nE[1,2]!=Inf){ tt <- chron(as.numeric(calTime) + as.numeric(nE[1,2]) - ageInYears%%1, out.format=c(dates='d/m/year', times='h/m/s')) if(isSchoolEnrolment(currState,nE[1,1])){ enYear <- years(tt) if(as.numeric(months(tt)) <= 9) { enDate <- chron(paste(enYear,dateSchoolEnrol,sep='/'), format=c(dates='y/m/d'), out.format=c(dates='d/m/year')) } else { enYear <- as.numeric(as.character(enYear)) enDate <- chron(paste(enYear,dateSchoolEnrol,sep='/'), format=c(dates='y/m/d'), out.format=c(dates='d/m/year')) } diffToEn <- as.numeric(enDate-tt) nE[1,2] <- as.numeric(nE[1,2]) + diffToEn } queue <<- rbind(queue, c(id, t.clock, currState, currAge - lagToWaitingTime*365.25, nE[1,1], nE[1,2])) } return(nE) } cat('Initialization ... \n') IN <- data.frame(ID=initPop[,'ID'],currState=initPop[,'initState'],age=(simHorizon[1]-initPop[,'birthDate']), calTime=rep(as.numeric(simHorizon[1]),dim(initPop)[1]),stringsAsFactors=FALSE) init <- apply(IN, 1, getNextStep) if(!is.null(immigrPop)){ IM <- data.frame(ID=immigrPop[,'ID'], currState=immigrPop[,'immigrInitState'], age=immigrPop[,'immigrDate']-immigrPop[,'birthDate'], calTime=as.numeric(immigrPop[,'immigrDate']),stringsAsFactors=FALSE) immigrInitPop <- immigrPop[,c('ID','birthDate','immigrInitState')] colnames(immigrInitPop)[3] <- 'initState' initPop <- rbind(initPop, immigrInitPop) imit <- apply(IM, 1, getNextStep, isIMInitEvent=T) } cat('Simulation is running ... \n') currYear <- as.numeric(as.character(years(simHorizon[1]))) while(dim(queue)[1]>0 & t.clock <= as.numeric(simHorizon[2])){ queue <- queue[order(as.numeric(queue[,'currTime'])+as.numeric(queue[,'timeToNextState'])),,drop=F] indS <- queue[1,] queue <- queue[-1,,drop=F] t.clock <- as.numeric(indS['currTime']) + as.numeric(indS['timeToNextState']) cY <- as.numeric(as.character(years(t.clock))) if(t.clock > as.numeric(simHorizon[2])) break if(cY>currYear){ cat('Year: ',cY,'\n') currYear <- cY } age <- as.numeric(indS['currAge']) + as.numeric(indS['timeToNextState']) transitions <- rbind(transitions, c(indS[c('ID','currState','nextState')], t.clock, age)) if(!indS['nextState'] %in% absStates){ if(isBirthEvent(indS['currState'],indS['nextState'])){ if(reportMothers){ addNewNewborn(birthTime=t.clock, motherID=indS['ID']) } else { addNewNewborn(birthTime=t.clock) } } res <- getNextStep(c(indS[c('ID','nextState')], age, t.clock)) } } transitions <- transitions[order(as.numeric(transitions[,1])),,drop=F] if (nrow(transitions) == 0){ transitionsOut <- data.frame(ID=initPop[,'ID'], From= rep(NA,nrow(initPop)), To=rep(NA,nrow(initPop)), transitionTime = rep(NA,nrow(initPop)), transitionAge = rep(NA,nrow(initPop)), stringsAsFactors = FALSE) cat('Simulation has finished.\n') cat('Beware that along the simulation horizon the individual/s considered do/es not experience any transition/s.\n') cat('------------------\n') } else { cat('Simulation has finished.\n------------------\n') transitionsOut <- data.frame(ID=transitions[,'ID'], From=transitions[,'From'], To=transitions[,'To'], transitionTime = dates(chron(as.numeric(transitions[,'transitionTime']), out.format=c(dates='d/m/year', times='h:m:s'))), transitionAge = round(getAgeInYears(as.numeric(transitions[,'transitionAge'])),2), stringsAsFactors = FALSE) } pop <- merge(initPop, transitionsOut, all=T, by='ID') pop <- pop[order(as.numeric(pop[,1])),] if(reportMothers) { colnames(mothers) <- c("motherID", "ID") pop <- merge(pop, mothers, by="ID", all.x=TRUE) pop <- pop[order(as.numeric(pop[,1])),] } return(pop) } micSimParallel <- function(initPop, immigrPop=NULL, transitionMatrix, absStates=NULL, initStates=c(), initStatesProb=c(), maxAge=99, simHorizon, fertTr=c(), dateSchoolEnrol='09/01', reportMothers = FALSE, cores=1, seeds=1254){ cat('Starting at ');print(Sys.time()) N <- dim(initPop)[1] M <- ifelse(is.null(immigrPop),0,dim(immigrPop)[1]) if(is.null(cores) | cores==1 | N+M<=20) { pop <- micSim(initPop, immigrPop, transitionMatrix, absStates, initStates, initStatesProb, maxAge, simHorizon, fertTr, dateSchoolEnrol, reportMothers = FALSE) } else { widthV <- max(trunc(N/cores), 10) widthW <- max(trunc(M/cores), 10) intV <- matrix(NA,ncol=2,nrow=cores) intW <- matrix(NA,ncol=2,nrow=cores) nI <- trunc(N/widthV) nIM <- trunc(M/widthW) ni <- 1 for(i in 1:(nI-1)){ intV[i,1] <- ni intV[i,2] <- ni+widthV-1 ni <- ni+widthV } intV[nI,1] <- ni intV[nI,2] <- N ni <- 1 if(nIM>1){ for(i in 1:(nIM-1)){ intW[i,1] <- ni intW[i,2] <- ni+widthW-1 ni <- ni+widthW } } intW[nIM,1] <- ni intW[nIM,2] <- M initPopList <- list() immigrPopList <- list() for(core in 1:cores){ if(!is.na(intV[core,1])){ initPopList[[core]] <- initPop[intV[core,1]:intV[core,2],] } else { initPopList[[core]] <- NA } if(!is.na(intW[core,1])){ immigrPopList[[core]] <- immigrPop[intW[core,1]:intW[core,2],] } else { immigrPopList[[core]] <- NA } } nL <- cores - sum(unlist((lapply(initPopList, is.na)))) mL <- cores - sum(unlist((lapply(immigrPopList, is.na)))) sfInit(parallel=T,cpus=cores,slaveOutfile=NULL) sfLibrary(chron) sfExportAll() sfClusterSetupRNGstream(seed=(rep(seeds,35)[1:length(cores)])) myPar <- function(itt){ if(itt<=mL){ immigrPopL <- immigrPopList[[itt]] } else { immigrPopL <- NULL } if (itt<=nL) { initPopL <- initPopList[[itt]] } else { initPopL <- NULL stop("\nCompared to the number of migrants, the starting population is too small to justify running a distributed simulation on several cores.") } popIt <- micSim(initPop=initPopL, immigrPop=immigrPopL, transitionMatrix=transitionMatrix, absStates=absStates, initStates=initStates, initStatesProb=initStatesProb, maxAge=maxAge, simHorizon=simHorizon, fertTr=fertTr, dateSchoolEnrol=dateSchoolEnrol, reportMothers = FALSE) return(popIt) } pop <- sfLapply(1:max(nL,mL), myPar) refID <- 0 replaceID <- function(rr){ pop[[i]][which(as.numeric(pop[[i]][,1])==rr[1]),1] <<- rr[2] return(NULL) } for(i in 1:length(pop)){ if(!is.na(immigrPopList[[i]])[1]){ allIDs <- c(initPopList[[i]]$ID, immigrPopList[[i]]$ID) } else { allIDs <- initPopList[[i]]$ID } exIDs <- unique(as.numeric(pop[[i]][,1])) repl <- setdiff(exIDs, allIDs) if(length(repl)>0) { newIDs <- cbind(repl,-(refID+(1:length(repl)))) idch <- apply(newIDs,1,replaceID) refID <- max(abs(newIDs[,2])) } } pop <- do.call(rbind,pop) pop[as.numeric(pop[,1])<0,1] <- abs(as.numeric(pop[as.numeric(pop[,1])<0,1]))+N+M pop <- pop[order(as.numeric(pop[,1])),] sfStop() } cat('Stopped at ');print(Sys.time()) return(pop) }
context("ashr with weighted samples") test_that("optimization with weights matches expectations", { set.seed(1) z=rnorm(100,0,2) z.ash= ash(z[1:50],1,optmethod="mixEM") z.ash.w = ash(z,1,optmethod="w_mixEM",weights = c(rep(1,50),rep(0,50)), g=get_fitted_g(z.ash)) expect_equal(get_fitted_g(z.ash.w)$pi, get_fitted_g(z.ash)$pi, tol=0.001) skip_if_not_installed("mixsqp") z.ash.w2 = ash(z,1,optmethod="mixSQP",weights = c(rep(1,50),rep(0,50)), g = get_fitted_g(z.ash)) expect_equal(get_fitted_g(z.ash.w2)$pi, get_fitted_g(z.ash.w)$pi,tol = 1e-4) skip_if_mixkwdual_doesnt_work() z.ash.w3 = ash(z,1,optmethod="mixIP",weights = c(rep(1,50),rep(0,50)), g = get_fitted_g(z.ash)) expect_equal(get_fitted_g(z.ash.w3)$pi, get_fitted_g(z.ash.w)$pi,tol = 1e-4) })
expected <- eval(parse(text="TRUE")); test(id=0, code={ argv <- eval(parse(text="list(structure(list(a_string = c(\"foo\", \"bar\"), a_bool = FALSE, a_struct = structure(list(a = 1, b = structure(c(1, 3, 2, 4), .Dim = c(2L, 2L)), c = \"foo\"), .Names = c(\"a\", \"b\", \"c\")), a_cell = structure(list(1, \"foo\", structure(c(1, 3, 2, 4), .Dim = c(2L, 2L)), \"bar\"), .Dim = c(2L, 2L)), a_complex_scalar = 0+1i, a_list = list(1, structure(c(1, 3, 2, 4), .Dim = c(2L, 2L)), \"foo\"), a_complex_matrix = structure(c(1+2i, 5+0i, 3-4i, -6+0i), .Dim = c(2L, 2L)), a_range = c(1, 2, 3, 4, 5), a_scalar = 1, a_complex_3_d_array = structure(c(1+1i, 3+1i, 2+1i, 4+1i, 5-1i, 7-1i, 6-1i, 8-1i), .Dim = c(2L, 2L, 2L)), a_3_d_array = structure(c(1, 3, 2, 4, 5, 7, 6, 8), .Dim = c(2L, 2L, 2L)), a_matrix = structure(c(1, 3, 2, 4), .Dim = c(2L, 2L)), a_bool_matrix = structure(c(TRUE, FALSE, FALSE, TRUE), .Dim = c(2L, 2L))), .Names = c(\"a_string\", \"a_bool\", \"a_struct\", \"a_cell\", \"a_complex_scalar\", \"a_list\", \"a_complex_matrix\", \"a_range\", \"a_scalar\", \"a_complex_3_d_array\", \"a_3_d_array\", \"a_matrix\", \"a_bool_matrix\")))")); do.call(`is.list`, argv); }, o=expected);
averaged.network = function(strength, threshold) { check.bn.strength(strength, valid = c("bootstrap", "bayes-factor")) threshold = check.threshold(threshold, strength) avg = averaged.network.backend(strength = strength, threshold = threshold) avg$learning$algo = "averaged" avg$learning$args = list(threshold = threshold) return(avg) } inclusion.threshold = function(strength) { check.bn.strength(strength, valid = c("bootstrap", "bayes-factor")) threshold(strength = strength, method = "l1") }
expected <- eval(parse(text="FALSE")); test(id=0, code={ argv <- eval(parse(text="list(c(0, 0, 0, 0, 0, 1.75368801162502e-134, 0, 0, 0, 2.60477585273833e-251, 1.16485035372295e-260, 0, 1.53160350210786e-322, 0.333331382328728, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3.44161262707711e-123, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.968811545398e-173, 0, 8.2359965384697e-150, 0, 0, 0, 0, 6.51733217171341e-10, 0, 2.36840184577368e-67, 0, 9.4348408357524e-307, 0, 1.59959906013771e-89, 0, 8.73836857865034e-286, 7.09716190970992e-54, 0, 0, 0, 1.530425353017e-274, 8.57590058044551e-14, 0.333333106397154, 0, 0, 1.36895217898448e-199, 2.0226102635783e-177, 5.50445388209462e-42, 0, 0, 0, 0, 1.07846402051283e-44, 1.88605464411243e-186, 1.09156111051203e-26, 0, 3.0702877273237e-124, 0.333333209689785, 0, 0, 0, 0, 0, 0, 3.09816093866831e-94, 0, 0, 4.7522727332095e-272, 0, 0, 2.30093251441394e-06, 0, 0, 1.27082826644707e-274, 0, 0, 0, 0, 0, 0, 0, 4.5662025456054e-65, 0, 2.77995853978268e-149, 0, 0, 0))")); do.call(`is.function`, argv); }, o=expected);
library(ggplot2) library(data.table) a <- 1 b <- c(-1.5, -1, -0.5, 0) theta <- seq(-4, 4, 0.01) ccirt <- function(theta, a, b) { return(1 / (1 + exp(-a * (theta - b)))) } df1 <- data.frame(sapply(1:length(b), function(i) ccirt(theta, a, b[i])), theta) df1 <- melt(df1, id.vars = "theta") ggplot(data = df1, aes(x = theta, y = value, col = variable)) + geom_line() + xlab("Ability") + ylab("Cumulative probability") + xlim(-4, 4) + ylim(0, 1) + theme_bw() + theme( text = element_text(size = 14), panel.grid.major = element_blank(), panel.grid.minor = element_blank() ) + ggtitle("Cumulative probabilities") + scale_color_manual("", values = c("red", "yellow", "green", "blue"), labels = paste0("P(Y >= ", 1:4, ")") ) df2 <- data.frame(1, sapply( 1:length(b), function(i) ccirt(theta, a, b[i]) )) df2 <- data.frame(sapply( 1:length(b), function(i) df2[, i] - df2[, i + 1] ), df2[, ncol(df2)], theta) df2 <- melt(df2, id.vars = "theta") ggplot(data = df2, aes(x = theta, y = value, col = variable)) + geom_line() + xlab("Ability") + ylab("Category probability") + xlim(-4, 4) + ylim(0, 1) + theme_bw() + theme( text = element_text(size = 14), panel.grid.major = element_blank(), panel.grid.minor = element_blank() ) + ggtitle("Category probabilities") + scale_color_manual("", values = c("black", "red", "yellow", "green", "blue"), labels = paste0("P(Y >= ", 0:4, ")") ) df3 <- data.frame(1, sapply( 1:length(b), function(i) ccirt(theta, a, b[i]) )) df3 <- data.frame(sapply( 1:length(b), function(i) df3[, i] - df3[, i + 1] ), df3[, ncol(df3)]) df3 <- data.frame(exp = as.matrix(df3) %*% 0:4, theta) ggplot(data = df3, aes(x = theta, y = exp)) + geom_line() + xlab("Ability") + ylab("Expected item score") + xlim(-4, 4) + ylim(0, 4) + theme_bw() + theme( text = element_text(size = 14), panel.grid.major = element_blank(), panel.grid.minor = element_blank() ) + ggtitle("Expected item score")
plotContours<-function(eList, yearStart, yearEnd, qBottom=NA, qTop=NA, whatSurface = 3, qUnit = 2, contourLevels = NA, span = 60, pval = 0.05, printTitle = TRUE, vert1 = NA, vert2 = NA, horiz = NA, tcl=0.03, flowDuration = TRUE, customPar=FALSE, yTicks=NA,tick.lwd=1,usgsStyle = FALSE, lwd=2,cex.main=1,cex.axis=1,color.palette=colorRampPalette(c("white","gray","blue","red")),...) { localINFO <- getInfo(eList) localDaily <- getDaily(eList) localsurfaces <- getSurfaces(eList) nVectorYear <- localINFO$nVectorYear bottomLogQ <- localINFO$bottomLogQ stepLogQ <- localINFO$stepLogQ nVectorLogQ <- localINFO$nVectorLogQ if (is.numeric(qUnit)){ qUnit <- qConst[shortCode=qUnit][[1]] } else if (is.character(qUnit)){ qUnit <- qConst[qUnit][[1]] } if(!customPar){ par(mgp=c(2.5,0.5,0)) } surfaceName<-c("log of Concentration","Standard Error of log(C)","Concentration") j<-3 j<-if(whatSurface==1) 1 else j j<-if(whatSurface==2) 2 else j surf<-localsurfaces surfaceMin<-min(surf[,,j]) surfaceMax<-max(surf[,,j]) surfaceSpan<-c(surfaceMin,surfaceMax) contourLevels<-if(is.na(contourLevels[1])) pretty(surfaceSpan,n=5) else contourLevels if(all(c("Year","LogQ") %in% names(attributes(localsurfaces)))){ x <- attr(localsurfaces, "Year") y <- attr(localsurfaces, "LogQ") } else { x <- seq(localINFO$bottomYear, by=localINFO$stepYear, length.out=localINFO$nVectorYear) y <- ((1:nVectorLogQ)*stepLogQ) + (bottomLogQ - stepLogQ) } yLQ<-y qFactor<-qUnit@qUnitFactor y<-exp(y)*qFactor numX<-length(x) numY<-length(y) qBottomT <- ifelse(is.na(qBottom), quantile(localDaily$Q, probs = 0.05)*qFactor, qBottom) qTopT <- ifelse(is.na(qTop), quantile(localDaily$Q, probs = 0.95)*qFactor, qTop) if(any(is.na(yTicks))){ if(is.na(qBottom)){ qBottom <- max(0.9*y[1],qBottomT) } if(is.na(qTop)){ qTop <- min(1.1*y[numY],qTopT) } yTicks <- logPretty3(qBottom,qTop) } if(yearEnd-yearStart >= 4){ xSpan<-c(yearStart,yearEnd) xTicks<-pretty(xSpan,n=5) xlabels <- xTicks } else { xlabels <- c(as.Date(paste(yearStart,"-01-01",sep="")), as.Date(paste(yearEnd,"-01-01",sep=""))) xlabels <- pretty(xlabels,n=5) xTicksDates <- as.POSIXlt(xlabels) years <- xTicksDates$year + 1900 day <- xTicksDates$yday xTicks <- years + day/365 xlabels <- format(xlabels, "%Y-%b") } nYTicks<-length(yTicks) surfj<-surf[,,j] surft<-t(surfj) plotTitle<-if(printTitle) paste(localINFO$shortName," ",localINFO$paramShortName,"\nEstimated",surfaceName[j],"Surface in Color") else NULL if(flowDuration) { numDays<-length(localDaily$Day) freq<-rep(0,nVectorLogQ) durSurf<-rep(0,length(x)*length(y)) dim(durSurf)<-c(length(x),length(y)) centerDays<-seq(1,365,22.9) centerDays<-floor(centerDays) for (ix in 1:16) { startDay<-centerDays[ix]-span endDay<-centerDays[ix]+span goodDays<-seq(startDay,endDay,1) goodDays<-ifelse(goodDays>0,goodDays,goodDays+365) goodDays<-ifelse(goodDays<366,goodDays,goodDays-365) numDays<-length(localDaily$Day) isGood <- localDaily$Day %in% goodDays spanDaily<-data.frame(localDaily,isGood) spanDaily<-subset(spanDaily,isGood) n<-length(spanDaily$Day) LogQ<-spanDaily$LogQ for(jQ in 1:length(y)) { ind<-ifelse(LogQ < yLQ[jQ],1,0) freq[jQ]<-sum(ind)/n } xInd<-seq(ix,numX,16) numXind<-length(xInd) for(ii in 1:numXind) { iX<-xInd[ii] durSurf[iX,]<-freq } } plevels<-c(pval,1-pval) pct1<-format(plevels[1]*100,digits=2) pct2<-format(plevels[2]*100,digits=2) plotTitle<- plotTitle<-if(printTitle)paste(localINFO$shortName," ",localINFO$paramShortName,"\nEstimated",surfaceName[j],"Surface in Color\nBlack lines are",pct1,"and",pct2,"flow percentiles") } vectorNone<-c(yearStart,log(yTicks[1],10)-1,yearEnd,log(yTicks[1],10)-1) v1<-if(is.na(vert1)) vectorNone else c(vert1,log(yTicks[1],10),vert1,log(yTicks[nYTicks],10)) v2<-if(is.na(vert2)) vectorNone else c(vert2,log(yTicks[1],10),vert2,log(yTicks[nYTicks],10)) h1<-if(is.na(horiz)) vectorNone else c(yearStart,log(horiz,10),yearEnd,log(horiz,10)) deltaY <- (log(yTicks[length(yTicks)],10)-log(yTicks[1],10))/25 deltaX <- (yearEnd-yearStart)/25 yLab<-ifelse(usgsStyle,qUnit@unitUSGS,qUnit@qUnitExpress) logY <- log(y,10) filled.contour(x,log(y,10),surft,levels=contourLevels,xlim=c(yearStart,yearEnd), ylim=c(log(yTicks[1],10),log(yTicks[nYTicks],10)), xaxs="i",yaxs="i", color.palette=color.palette, plot.axes={ width <- grconvertX(par("usr")[2],from="user",to="inches") - grconvertX(par("usr")[1],from="user",to="inches") height <- grconvertY(par("usr")[4],from="user",to="inches") - grconvertY(par("usr")[3],from="user",to="inches") axis(1,tcl=0,at=xTicks,labels=xlabels,cex.axis=cex.axis) axis(2,tcl=0,las=1,at=log(yTicks,10),labels=yTicks,cex.axis=cex.axis) axis(3, tcl = 0, at = xTicks, labels =FALSE,cex.axis=cex.axis) axis(4, tcl = 0, at = log(yTicks, 10), labels=FALSE,cex.axis=cex.axis) if(flowDuration) contour(x,log(y,10),durSurf,add=TRUE,drawlabels=FALSE,levels=plevels,lwd=lwd) segments(v1[1],v1[2],v1[3],v1[4]) segments(v2[1],v2[2],v2[3],v2[4]) segments(h1[1],h1[2],h1[3],h1[4]) segments(xTicks, rep(log(yTicks[1],10),length(xTicks)), xTicks, rep(grconvertY(grconvertY(par("usr")[3],from="user",to="inches")+tcl,from="inches",to="user"),length(xTicks)), lwd = tick.lwd) segments(xTicks, rep(log(yTicks[nYTicks],10),length(xTicks)), xTicks, rep(grconvertY(grconvertY(par("usr")[4],from="user",to="inches")-tcl,from="inches",to="user"),length(xTicks)), lwd = tick.lwd) segments(rep(yearStart,length(yTicks)), log(yTicks,10), rep(grconvertX(grconvertX(par("usr")[1],from="user",to="inches")+tcl,from="inches",to="user"),length(yTicks)),log(yTicks,10), lwd = tick.lwd) segments(rep(grconvertX(grconvertX(par("usr")[2],from="user",to="inches")-tcl,from="inches",to="user"),length(yTicks)), log(yTicks,10), rep(yearEnd,length(yTicks)),log(yTicks,10), lwd = tick.lwd) }, plot.title = { if(printTitle) { title(main = plotTitle, ylab = yLab,cex.main = cex.main) } else { title(main = NULL, ylab = yLab) } } ) }
context("ticket/attachments") test_that("we can get a list of attachments", { testthat::skip_on_cran() skip_unless_integration() ticket_id <- rt_ticket_create("General", "root@localhost", "Attachment test") attachments <- rt_ticket_attachments(ticket_id) testthat::expect_is(attachments, "data.frame") testthat::expect_length(attachments, 4) }) test_that("we can get an attachment", { testthat::skip_on_cran() skip_unless_integration() ticket_id <- rt_ticket_create("General", "root@localhost", "Attachment test") attachments <- rt_ticket_attachments(ticket_id) attachment <- rt_ticket_attachment(ticket_id, attachments[1,"id"][[1]]) testthat::expect_is(attachment, "rt_api") testthat::expect_gt(nchar(attachment$body), 0) }) test_that("we can get an attachment's content", { testthat::skip_on_cran() skip_unless_integration() ticket_id <- rt_ticket_create("General", "root@localhost", "Attachment test") attachments <- rt_ticket_attachments(ticket_id) content <- rt_ticket_attachment_content(ticket_id, attachments$id[1]) testthat::expect_is(content, "response") content <- rt_ticket_attachment_content(ticket_id, attachments$id[3]) testthat::expect_is(content, "response") })
h2Estimate <- function(data, nreps = 1000) { colnames(data) <- c("trait1", "trait2", "dad") hm0.real = glm(cbind(trait1, trait2) ~ 1, data = data, family = binomial) hm1.real = glmer(cbind(trait1, trait2) ~ (1 | dad), data = data, family = binomial) Dobs = as.numeric(deviance(hm0.real) - deviance(hm1.real)) if(Dobs < 1e-5){ pval = 1 Dobs = 0 sim = NA trueTau2 <- 0 h2 <- 0 perm1 = NA }else{ ncases <- nrow(data) perm1 = replicate(nreps, { neworder = sample(1:ncases, ncases) ptable = data.frame(dad = data$dad, t1 = data$trait1[neworder], t2 = data$trait2[neworder]) hm0 = glm(cbind(t1, t2) ~ 1, data = ptable, family = binomial) hm1 = glmer(cbind(t1, t2) ~ (1 | dad), data = ptable, family = binomial) D = as.numeric(deviance(hm0) - deviance(hm1)) D }) pval <- length(which(perm1 > Dobs))/length(perm1) trueTau2 <- (VarCorr(hm1.real)$dad[1])^2 h2 <- 4 * (trueTau2/(trueTau2 + (pi/sqrt(3))^2)) } out <- list(h2 = h2, pval = pval, deviance = Dobs, sim = perm1, trueTau2 = trueTau2, obsMod_glmer = hm1.real, obsMod_glm = hm0.real) return(out) }
cat("\n\n Basics: vector, matrix, attribute, attr, dim, structure \n\n, t, %*%, outer, crossprod") x <- c(13, 11, 18, 2, 134, 154, 2, 3, 4, 12) is.vector(x) is.matrix(x) attributes(x) ?attributes matrix(x, nrow=2) ?matrix X1m1 <- matrix(x, nrow=2) class(X1m1) X1m2 <- matrix(x, ncol=5) X1m1 == X1m2 identical(X1m1, X1m2) ?identical attributes(X1m1) attributes(X1m2) X1m3 <- x attr(X1m3, "dim") <- c(2,5) ?attr X1m3 is.vector(X1m3) is.matrix(X1m3) is.data.frame(X1m3) attributes(X1m3) identical(X1m1, X1m3) X1m4 <- x dim(X1m4) <- c(2,5) ?dim X1m4 attributes(X1m4) identical(X1m1, X1m4) X1m5 <- structure(x, dim=c(2,5)) ?structure X1m5 identical(X1m1, X1m5) X1m6 <- rbind(x[c(1,3,5,7,9)], x[c(2,4,6,8,10)]) class(x[1:5]) class(X1m6) identical(X1m1, X1m6) X1m7 <- cbind(x[1:2], x[3:4], x[5:6], x[7:8],x[9:10]) identical(X1m1, X1m7) x1m7 <- X1m7 identical(x, x1m7) dim(x1m7) <- c(1,10) x1m7 identical(x, x1m7) x1m7new1 <- drop(x1m7) ?drop x1m7new1 identical(x, x1m7new1) x1m7new2 <- as.vector(x1m7) identical(x, x1m7new2) ?t tX1m1 <- t(X1m1) tX1m1 X2m1 <- matrix(x, nrow=5, byrow=TRUE) X2m1 dim(X2m1) identical(X2m1, t(X1m1)) X2m2 <- X1m1 X2m2 dim(X2m2) dim(X2m2) <- c(5,2) dim(X2m2) X2m2 identical(X1m1, X2m2) X2m1 == X2m2 y <- c(12, 12, 41, 22) x %*% y y <- rep(c(1,2,3,4,5), 2) x %*% y t(x) %*% y y %*% x outer(x,y) outer(x,y, FUN="*") outer(x,y, FUN="+") outer(x,y, FUN="/") outer(x,y, FUN=function(a, b) {b - 2*a}) X3 <- matrix(rnorm(10), nrow=2) crossprod(X1m1, X3) t(X1m1) %*% X3 ?crossprod x <- 1:6 X <- data.frame(x1 = x, x2 = x, x3 = x) Y <- data.frame(z1 = rnorm(6), z2 = rnorm(6), x3 = rnorm(6)) Z <- cbind(X, Y) colnames(Z) Z2 <- data.frame(X,Y) colnames(Z2)
epictmcmcsir <- function(object, distancekernel, datatype, blockupdate, nsim, nchains, sus, suspower, trans, transpower, kernel, spark, delta, periodproposal, parallel, n, ni, net, dis, num, nsuspar, ntranspar) { initial <- list(NULL) infperiodproposal <- vector(mode="double", length = 2) delta2prior <- vector(mode="double", length = 2) delta1 <- vector(mode="double", length = 2) if (datatype == "known removal") { anum11 <- 1 if (is.null(delta)) { stop("Specify the arguments of the parameters of the infectious period distribution: delta", call. =FALSE) } else { if (!is.list(delta)) { stop("The argument \"delta\" must be a list of three:\n1) a fixed shape parameter of the infectious period density.\n2) a vector of initial values of the rate parameter of the infectious period density with size equal to \"nchains\". \n3) a vector of the parameter values of the gamma prior distribution for the rate parameter.", call.= FALSE) } if (length(delta) != 3) { stop("Error in entering the arguments of the delta parameters of the infectious period distribution: delta", call.=FALSE) } if ( length(delta[[1]])>1) { stop("Error in entering the arguments of the fixed shape parameter of the infectious period density: delta", call.=FALSE) } initial[[1]] <- matrix(0, ncol = nchains, nrow = 2) initial[[1]][1,] <- rep(delta[[1]], nchains) if (is.vector(delta[[2]])) { if (length(delta[[2]]) == nchains) { initial[[1]][2,] <- delta[[2]] } else if (length(delta[[2]]) == 1) { initial[[1]] <- rep(delta[[2]],nchains) } else { stop("Error in entering the initial values of the delta parameter: delta[[2]]", call.= FALSE) } } else { stop("Error in entering the initial values of the delta parameter: delta[[2]]", call.= FALSE) } if (length(delta[[3]]) == 2) { delta2prior <- delta[[3]] } else { stop("Error in entering the parameter values of the gamma prior distribution of the delta parameter: delta[[3]]", call.= FALSE) } } if (is.null(periodproposal) ) { infperiodproposal <- c(0,0) } else { if (!is.matrix(periodproposal)) { periodproposal <- matrix(periodproposal, ncol = 2, nrow = 1) infperiodproposal <- periodproposal[1, ] } else if (all(dim(periodproposal)[1]!=1 & dim(periodproposal)[2]!=2) == TRUE) { stop("Error: the parameters of the gamma proposal distribution for updating the infectious periods and infection times should be entered as a 1 by 2 matrix or as a vector: periodproposal", call.=FALSE) } else { infperiodproposal <- periodproposal[1, ] } } if (is.null(blockupdate) ) { blockupdate <- c(1, 1) } } else if (datatype == "known epidemic") { blockupdate <- vector(mode="integer", length = 2) if (!is.null(delta)) { warning("The infectious period rate is not updated as the option of datatype = \"known epidemic\".", call. = TRUE) } anum11 <- 2 infperiodproposal <- c(0,0) delta2prior <- c(0, 0) initial[[1]] <- matrix(rep(0.0,nchains), ncol = nchains, nrow = 2) blockupdate <- c(1, 1) } else { stop("Specify datatype as \"known removal\" or \"known epidemic\" ", call. = FALSE) } anum55 <- kernel[[4]] kernelparproposalvar <- kernel[[1]] kernelparprior <- kernel[[3]] priordistkernelparpar <- kernel[[2]] initial[[5]] <- kernel[[5]] initial[[4]] <- spark[[5]] anum44 <- spark[[4]] sparkproposalvar <- spark[[1]] priordistsparkpar <- spark[[2]] sparkprior <- spark[[3]] anum22 <- sus[[4]] initial[[2]] <- sus[[5]] suscov <- sus[[6]] susproposalvar <- sus[[1]] priordistsuspar <- sus[[2]] priorpar1sus <- sus[[3]][[1]] priorpar2sus <- sus[[3]][[2]] anum66 <- suspower[[4]] initial[[6]] <- suspower[[5]] powersusproposalvar <- suspower[[1]] priordistpowersus <- suspower[[2]] priorpar1powersus <- suspower[[3]][[1]] priorpar2powersus <- suspower[[3]][[2]] anum33 <- trans[[4]] initial[[3]] <- trans[[5]] transcov <- trans[[6]] transproposalvar <- trans[[1]] priordisttranspar <- trans[[2]] priorpar1trans <- trans[[3]][[1]] priorpar2trans <- trans[[3]][[2]] anum77 <- transpower[[4]] initial[[7]] <- transpower[[5]] powertransproposalvar <- transpower[[1]] priordistpowertrans <- transpower[[2]] priorpar1powertrans <- transpower[[3]][[1]] priorpar2powertrans <- transpower[[3]][[2]] anum2 <- c(anum11, anum22, anum33, anum44, anum55, anum66, anum77) cat("************************************************","\n") cat("Start performing MCMC for the ", datatype," SIR ILM for","\n") cat(nsim, "iterations", "\n") cat("************************************************","\n") if (nchains > 1L) { n=as.integer(n); nsim=as.integer(nsim); ni=as.integer(ni); num=as.integer(num); anum2=as.vector(anum2, mode="integer"); temp = as.integer(0); nsuspar=as.integer(nsuspar); ntranspar=as.integer(ntranspar); net=matrix(as.double(net), ncol=n, nrow=n); dis=matrix(as.double(dis), ncol=n, nrow=n); epidat=matrix(as.double(object$epidat), ncol=4, nrow=n); blockupdate=as.vector(blockupdate, mode="integer"); priordistsuspar=as.vector(priordistsuspar, mode="integer"); priordisttranspar=as.vector(priordisttranspar, mode="integer"); priordistkernelparpar=as.vector(priordistkernelparpar, mode="integer"); priordistsparkpar=as.integer(priordistsparkpar); priordistpowersus=as.vector(priordistpowersus, mode="integer"); priordistpowertrans=as.vector(priordistpowertrans, mode="integer"); suspar=as.vector(initial[[2]][,1], mode="double"); suscov=matrix(as.double(suscov), ncol=nsuspar, nrow=n); powersus=as.vector(initial[[6]][,1], mode="double"); transpar=as.vector(initial[[3]][,1], mode="double"); transcov=matrix(as.double(transcov), ncol=ntranspar, nrow=n); powertrans=as.vector(initial[[7]][,1], mode="double"); kernelpar=as.vector(initial[[5]][,1], mode="double"); spark=initial[[4]][1]; delta1=as.vector(initial[[1]][,1], mode = "double"); kernelparproposalvar=as.vector(kernelparproposalvar, mode="double"); sparkproposalvar=as.double(sparkproposalvar); susproposalvar=as.vector(susproposalvar, mode="double"); powersusproposalvar=as.vector(powersusproposalvar, mode="double"); transproposalvar=as.vector(transproposalvar, mode="double"); powertransproposalvar=as.vector(powertransproposalvar, mode="double"); infperiodproposal=as.vector(infperiodproposal, mode="double"); priorpar1sus=as.vector(priorpar1sus, mode="double"); priorpar2sus=as.vector(priorpar2sus, mode="double"); priorpar1powersus=as.vector(priorpar1powersus, mode="double"); priorpar2powersus=as.vector(priorpar2powersus, mode="double"); priorpar1trans=as.vector(priorpar1trans, mode="double"); priorpar2trans=as.vector(priorpar2trans, mode="double"); priorpar1powertrans=as.vector(priorpar1powertrans, mode="double"); priorpar2powertrans=as.vector(priorpar2powertrans, mode="double"); kernelparprior=matrix(as.double(kernelparprior), ncol=2, nrow=2); sparkprior=as.vector(sparkprior, mode="double"); delta2prior=as.vector(delta2prior, mode="double"); susparop= matrix(as.double(0), ncol=nsuspar, nrow=nsim); powersusparop=matrix(as.double(0), ncol=nsuspar, nrow=nsim); transparop= matrix(as.double(0), ncol=ntranspar, nrow=nsim); powertransparop=matrix(as.double(0), ncol=ntranspar, nrow=nsim); kernelparop=matrix(as.double(0), ncol=2, nrow=nsim); sparkop=matrix(as.double(0), ncol=1, nrow=nsim); delta2op=matrix(as.double(0), ncol=1, nrow=nsim); epidatmctim=matrix(as.double(0), ncol=n, nrow=nsim); epidatmcrem=matrix(as.double(0), ncol=n, nrow=nsim); loglik=matrix(as.double(0), ncol=1, nrow=nsim) sirmcmc <- list(n,nsim,ni,num,anum2,temp,nsuspar,ntranspar,net,dis,epidat,blockupdate,priordistsuspar, priordisttranspar, priordistkernelparpar, priordistsparkpar, priordistpowersus, priordistpowertrans,suspar,suscov,powersus,transpar,transcov,powertrans,kernelpar,spark,delta1, kernelparproposalvar, sparkproposalvar, susproposalvar, powersusproposalvar, transproposalvar, powertransproposalvar, infperiodproposal, priorpar1sus, priorpar2sus, priorpar1powersus, priorpar2powersus, priorpar1trans, priorpar2trans, priorpar1powertrans, priorpar2powertrans, kernelparprior, sparkprior, delta2prior, susparop, powersusparop, transparop, powertransparop, kernelparop, sparkop, delta2op, epidatmctim, epidatmcrem, loglik) parallel.function <- function(i) { .Fortran("mcmcsir_f", n= sirmcmc[[1]], nsim = sirmcmc[[2]], ni= sirmcmc[[3]], num= sirmcmc[[4]], anum2= sirmcmc[[5]], nsuspar= sirmcmc[[7]], ntranspar= sirmcmc[[8]], net= sirmcmc[[9]], dis= sirmcmc[[10]], epidat= sirmcmc[[11]], blockupdate= sirmcmc[[12]], priordistsuspar= sirmcmc[[13]], priordisttranspar= sirmcmc[[14]], priordistkernelparpar= sirmcmc[[15]], priordistsparkpar= sirmcmc[[16]], priordistpowersus= sirmcmc[[17]], priordistpowertrans= sirmcmc[[18]], suspar= as.vector(initial[[2]][,i], mode="double"), suscov= sirmcmc[[20]], powersus= as.vector(initial[[6]][,i], mode="double"), transpar= as.vector(initial[[3]][,i], mode="double"), transcov= sirmcmc[[23]], powertrans= as.vector(initial[[7]][,i], mode="double"), kernelpar= as.vector(initial[[5]][,i], mode="double"), spark= initial[[4]][i], delta1=as.vector(initial[[1]][,i], mode = "double"), kernelparproposalvar= sirmcmc[[28]], sparkproposalvar= sirmcmc[[29]], susproposalvar= sirmcmc[[30]], powersusproposalvar= sirmcmc[[31]], transproposalvar= sirmcmc[[32]], powertransproposalvar= sirmcmc[[33]], infperiodproposal= sirmcmc[[34]], priorpar1sus= sirmcmc[[35]], priorpar2sus= sirmcmc[[36]], priorpar1powersus= sirmcmc[[37]], priorpar2powersus= sirmcmc[[38]], priorpar1trans= sirmcmc[[39]], priorpar2trans= sirmcmc[[40]], priorpar1powertrans= sirmcmc[[41]], priorpar2powertrans= sirmcmc[[42]], kernelparprior= sirmcmc[[43]], sparkprior= sirmcmc[[44]], delta2prior= sirmcmc[[45]], susparop= sirmcmc[[46]], powersusparop= sirmcmc[[47]], transparop= sirmcmc[[48]], powertransparop= sirmcmc[[49]], kernelparop= sirmcmc[[50]], sparkop= sirmcmc[[51]], delta2op= sirmcmc[[52]], epidatmctim= sirmcmc[[53]], epidatmcrem= sirmcmc[[54]], loglik= sirmcmc[[55]], NAOK = TRUE) } if (parallel) { no_cores <- min(nchains,getOption("cl.cores", detectCores())) cl <- makeCluster(no_cores) varlist <- unique(c(ls(), ls(envir=.GlobalEnv), ls(envir=parent.env(environment())))) clusterExport(cl, varlist=varlist, envir=environment()) wd <- getwd() clusterExport(cl, varlist="wd", envir=environment()) clusterSetRNGStream(cl = cl) datmcmc22 <- parLapply(cl=cl, X=1:no_cores, fun=parallel.function) stopCluster(cl) } else { datmcmc22 <- list(NULL) for (i in seq_len(nchains)) { datmcmc22[[i]] <- parallel.function(i) } } } else if (nchains == 1L) { datmcmc22 <- .Fortran("mcmcsir_f", n=as.integer(n), nsim=as.integer(nsim), ni=as.integer(ni), num=as.integer(num), anum2=as.vector(anum2, mode="integer"), nsuspar=as.integer(nsuspar), ntranspar=as.integer(ntranspar), net=matrix(as.double(net), ncol=n, nrow=n), dis=matrix(as.double(dis), ncol=n, nrow=n), epidat=matrix(as.double(object$epidat), ncol=4, nrow=n), blockupdate=as.vector(blockupdate, mode="integer"), priordistsuspar=as.vector(priordistsuspar, mode="integer"), priordisttranspar=as.vector(priordisttranspar, mode="integer"), priordistkernelparpar=as.vector(priordistkernelparpar, mode="integer"), priordistsparkpar=as.integer(priordistsparkpar), priordistpowersus=as.vector(priordistpowersus, mode="integer"), priordistpowertrans=as.vector(priordistpowertrans, mode="integer"), suspar=as.vector(initial[[2]][,1], mode="double"), suscov=matrix(as.double(suscov), ncol=nsuspar, nrow=n), powersus=as.vector(initial[[6]][,1], mode="double"), transpar=as.vector(initial[[3]][,1], mode="double"), transcov=matrix(as.double(transcov), ncol=ntranspar, nrow=n), powertrans=as.vector(initial[[7]][,1], mode="double"), kernelpar=as.vector(initial[[5]][,1], mode="double"), spark=initial[[4]][1], delta1=as.vector(initial[[1]][,1], mode = "double"), kernelparproposalvar=as.vector(kernelparproposalvar, mode="double"), sparkproposalvar=as.double(sparkproposalvar), susproposalvar=as.vector(susproposalvar, mode="double"), powersusproposalvar=as.vector(powersusproposalvar, mode="double"), transproposalvar=as.vector(transproposalvar, mode="double"), powertransproposalvar=as.vector(powertransproposalvar, mode="double"), infperiodproposal=as.vector(infperiodproposal, mode="double"), priorpar1sus=as.vector(priorpar1sus, mode="double"), priorpar2sus=as.vector(priorpar2sus, mode="double"), priorpar1powersus=as.vector(priorpar1powersus, mode="double"), priorpar2powersus=as.vector(priorpar2powersus, mode="double"), priorpar1trans=as.vector(priorpar1trans, mode="double"), priorpar2trans=as.vector(priorpar2trans, mode="double"), priorpar1powertrans=as.vector(priorpar1powertrans, mode="double"), priorpar2powertrans=as.vector(priorpar2powertrans, mode="double"), kernelparprior=matrix(as.double(kernelparprior), ncol=2, nrow=2), sparkprior=as.vector(sparkprior, mode="double"), delta2prior=as.vector(delta2prior, mode="double"), susparop= matrix(as.double(0), ncol=nsuspar, nrow=nsim), powersusparop=matrix(as.double(0), ncol=nsuspar, nrow=nsim), transparop= matrix(as.double(0), ncol=ntranspar, nrow=nsim), powertransparop=matrix(as.double(0), ncol=ntranspar, nrow=nsim), kernelparop=matrix(as.double(0), ncol=2, nrow=nsim), sparkop=matrix(as.double(0), ncol=1, nrow=nsim), delta2op=matrix(as.double(0), ncol=1, nrow=nsim), epidatmctim=matrix(as.double(0), ncol=n, nrow=nsim), epidatmcrem=matrix(as.double(0), ncol=n, nrow=nsim), loglik=matrix(as.double(0), ncol=1, nrow=nsim), NAOK = TRUE) } names <- c(paste("Alpha_s[",seq_len(nsuspar),"]", sep = "")) namet <- c(paste("Alpha_t[",seq_len(ntranspar),"]", sep = "")) namepowers <- c(paste("Psi_s[",seq_len(nsuspar),"]", sep = "")) namepowert <- c(paste("Psi_t[",seq_len(ntranspar),"]", sep = "")) if (nchains > 1L) { result77 <- list(NULL) for (i in seq_len(nchains)){ result777 <- NULL namecols <- NULL if (anum2[2]==1) { result777 <- cbind(result777, datmcmc22[[i]]$susparop ) namecols <- c(namecols, names[1:nsuspar]) } if (anum2[6]==1) { result777 <- cbind(result777, datmcmc22[[i]]$powersusparop) namecols <- c(namecols, namepowers[1:nsuspar]) } if (anum2[3]==1) { result777 <- cbind(result777, datmcmc22[[i]]$transparop) namecols <- c(namecols, namet[1:ntranspar]) } if (anum2[7]==1) { result777 <- cbind(result777, datmcmc22[[i]]$powertransparop) namecols <- c(namecols, namepowert[1:ntranspar]) } if (anum2[4]==1) { result777 <- cbind(result777, datmcmc22[[i]]$sparkop[, 1]) namecols <- c(namecols, "Spark") } if (anum2[5]==1) { result777 <- cbind(result777, datmcmc22[[i]]$kernelparop[, 1]) namecols <- c(namecols, "Spatial parameter") } else if (anum2[5]==2) { result777 <- cbind(result777, datmcmc22[[i]]$kernelparop) namecols <- c(namecols, c("Spatial parameter", "Network parameter")) } if (anum2[1]==1) { result777 <- cbind(result777, datmcmc22[[i]]$delta2op[, 1]) namecols <- c(namecols, "Infectious period rate") } result777 <- cbind(result777, datmcmc22[[i]]$loglik) namecols <- c(namecols, "Log-likelihood") result777 <- data.frame(result777) colnames(result777) <- namecols if (anum2[1]==2) { result777 <- list(result777) } else if (anum2[1]==1) { result777 <- list(result777, datmcmc22[[i]]$epidatmctim) } result77[[i]] <- result777 } } else { result77 <- NULL namecols <- NULL if (anum2[2]==1) { result77 <- cbind(result77, datmcmc22$susparop) namecols <- c(namecols, names[1:nsuspar]) } if (anum2[6]==1) { result77 <- cbind(result77, datmcmc22$powersusparop) namecols <- c(namecols, namepowers[1:nsuspar]) } if (anum2[3]==1) { result77 <- cbind(result77, datmcmc22$transparop) namecols <- c(namecols, namet[1:ntranspar]) } if (anum2[7]==1) { result77 <- cbind(result77, datmcmc22$powertransparop) namecols <- c(namecols, namepowert[1:ntranspar]) } if (anum2[4]==1) { result77 <- cbind(result77, datmcmc22$sparkop[, 1]) namecols <- c(namecols, "Spark") } if (anum2[5]==1) { result77 <- cbind(result77, datmcmc22$kernelparop[, 1]) namecols <- c(namecols, "Spatial parameter") } else if (anum2[5]==2) { result77 <- cbind(result77, datmcmc22$kernelparop) namecols <- c(namecols, c("Spatial parameter", "Network parameter")) } if (anum2[1]==1) { result77 <- cbind(result77, datmcmc22$delta2op[, 1]) namecols <- c(namecols, "Infectious period rate") } result77 <- cbind(result77, datmcmc22$loglik) namecols <- c(namecols, "Log-likelihood") result77 <- data.frame(result77) colnames(result77) <- namecols if (anum2[1]==2) { result77 <- list(result77) } else if (anum2[1]==1) { result77 <- list(result77, datmcmc22$epidatmctim) } } if (nchains == 1){ if (length(result77) == 1) { dim.results <- dim(result77[[1]]) mcmcsamp <- as.mcmc(result77[[1]][,-dim.results[2]]) accpt <- 1-rejectionRate(as.mcmc(mcmcsamp)) num.iter <- niter(as.mcmc(mcmcsamp)) num.par <- nvar(as.mcmc(mcmcsamp)) log.likelihood <- as.mcmc(result77[[1]][,dim.results[2]]) out <- list(compart.framework = object$type, kernel.type = object$kerneltype, data.assumption = datatype, parameter.samples = mcmcsamp, log.likelihood = log.likelihood, acceptance.rate = accpt, number.iteration = num.iter, number.parameter = num.par, number.chains = nchains) } else { dim.results <- dim(result77[[1]]) mcmcsamp <- as.mcmc(result77[[1]][,-dim.results[2]]) accpt <- 1-rejectionRate(as.mcmc(mcmcsamp)) num.iter <- niter(as.mcmc(mcmcsamp)) num.par <- nvar(as.mcmc(mcmcsamp)) log.likelihood <- as.mcmc(result77[[1]][,dim.results[2]]) num.inf <- sum(object$epidat[,2]!=Inf) infection.times.samples <- as.mcmc(result77[[2]][,1:num.inf]) Average.infectious.periods <- as.mcmc(apply(object$epidat[1:num.inf,2]-infection.times.samples,1,mean)) out <- list(compart.framework = object$type, kernel.type = object$kerneltype, data.assumption = datatype, parameter.samples = mcmcsamp, log.likelihood = log.likelihood, acceptance.rate = accpt, number.iteration = num.iter, number.parameter = num.par, number.chains = nchains, infection.times.samples = infection.times.samples, Average.infectious.periods = Average.infectious.periods) } } else { if (length(result77[[1]]) == 1) { dim.results <- dim(result77[[1]][[1]]) mcmcsamp <- list(NULL) log.likelihood <- list(NULL) accpt <- list(NULL) for(i in seq_len(nchains)){ mcmcsamp[[i]] <- as.mcmc(result77[[i]][[1]][,-dim.results[2]]) accpt[[i]] <- 1-rejectionRate(as.mcmc(mcmcsamp[[i]])) log.likelihood[[i]] <- as.mcmc(result77[[i]][[1]][,dim.results[2]]) } num.iter <- niter(as.mcmc(mcmcsamp[[1]])) num.par <- nvar(as.mcmc(mcmcsamp[[1]])) out <- list(compart.framework = object$type, kernel.type = object$kerneltype, data.assumption = datatype, parameter.samples = mcmcsamp, log.likelihood = log.likelihood, acceptance.rate = accpt, number.iteration = num.iter, number.parameter = num.par, number.chains = nchains) } else { dim.results <- dim(result77[[1]][[1]]) mcmcsamp <- list(NULL) log.likelihood <- list(NULL) accpt <- list(NULL) num.inf <- sum(object$epidat[,2]!=Inf) infection.times.samples <- list(NULL) Average.infectious.periods <- list(NULL) for(i in seq_len(nchains)){ mcmcsamp[[i]] <- as.mcmc(result77[[i]][[1]][,-dim.results[2]]) accpt[[i]] <- 1-rejectionRate(as.mcmc(mcmcsamp[[i]])) log.likelihood[[i]] <- as.mcmc(result77[[i]][[1]][,dim.results[2]]) infection.times.samples[[i]] <- as.mcmc(result77[[i]][[2]][,seq_len(num.inf)]) Average.infectious.periods[[i]] <- as.mcmc(apply(object$epidat[seq_len(num.inf),2]-infection.times.samples[[i]],1,mean)) } num.iter <- niter(as.mcmc(mcmcsamp[[1]])) num.par <- nvar(as.mcmc(mcmcsamp[[1]])) out <- list(compart.framework = object$type, kernel.type = object$kerneltype, data.assumption = datatype, parameter.samples = mcmcsamp, log.likelihood = log.likelihood, acceptance.rate = accpt, number.iteration = num.iter, number.parameter = num.par, number.chains = nchains, infection.times.samples = infection.times.samples, Average.infectious.periods = Average.infectious.periods) } } }
add_linpred_rvars = function( newdata, object, ..., value = ".linpred", ndraws = NULL, seed = NULL, re_formula = NULL, dpar = NULL, columns_to = NULL ) { linpred_rvars( object = object, newdata = newdata, ..., value = value, ndraws = ndraws, seed = seed, re_formula = re_formula, dpar = dpar, columns_to = columns_to ) } linpred_rvars = function( object, newdata, ..., value = ".linpred", ndraws = NULL, seed = NULL, re_formula = NULL, dpar = NULL, columns_to = NULL ) { UseMethod("linpred_rvars") } linpred_rvars.default = function( object, newdata, ..., value = ".linpred", seed = NULL, dpar = NULL, columns_to = NULL ) { pred_rvars_default_( .name = "linpred_rvars", .f = rstantools::posterior_linpred, ..., object = object, newdata = newdata, output_name = value, seed = seed, dpar = dpar, columns_to = columns_to ) } linpred_rvars.stanreg = function( object, newdata, ..., value = ".linpred", ndraws = NULL, seed = NULL, re_formula = NULL, dpar = NULL, columns_to = NULL ) { stop_on_non_generic_arg_( names(enquos(...)), "[add_]linpred_rvars", re_formula = "re.form", ndraws = "draws" ) pred_rvars_( .f = rstantools::posterior_linpred, ..., object = object, newdata = newdata, output_name = value, draws = ndraws, seed = seed, re.form = re_formula, dpar = NULL, columns_to = columns_to ) } linpred_rvars.brmsfit = function( object, newdata, ..., value = ".linpred", ndraws = NULL, seed = NULL, re_formula = NULL, dpar = NULL, columns_to = NULL ) { pred_rvars_( .f = rstantools::posterior_linpred, ..., object = object, newdata = newdata, output_name = value, ndraws = ndraws, seed = seed, re_formula = re_formula, dpar = dpar, columns_to = columns_to ) }
require("RWeka") m1 <- J48(Species ~ ., data = iris) writeLines(rJava::.jstrVal(m1$classifier)) save(m1, file = "m1.rda") load("m1.rda") rJava::.jstrVal(m1$classifier) m1 <- J48(Species ~ ., data = iris) rJava::.jcache(m1$classifier) save(m1, file = "m1.rda") load("m1.rda") writeLines(rJava::.jstrVal(m1$classifier)) unlink("m1.rda") graphVisualizer <- function(file, width = 400, height = 400, title = substitute(file), ...) { visualizer <- .jnew("weka/gui/graphvisualizer/GraphVisualizer") reader <- .jnew("java/io/FileReader", file) .jcall(visualizer, "V", "readDOT", .jcast(reader, "java/io/Reader")) .jcall(visualizer, "V", "layoutGraph") frame <- .jnew("javax/swing/JFrame", paste("graphVisualizer:", title)) container <- .jcall(frame, "Ljava/awt/Container;", "getContentPane") .jcall(container, "Ljava/awt/Component;", "add", .jcast(visualizer, "java/awt/Component")) .jcall(frame, "V", "setSize", as.integer(width), as.integer(height)) .jcall(frame, "V", "setVisible", TRUE) } c("-W", "weka.classifiers.trees.J48", "--", "-M", 30) Weka_control(W = J48, "--", M = 30) myAB <- make_Weka_classifier("weka/classifiers/meta/AdaBoostM1") myAB(Species ~ ., data = iris, control = c("-W", "weka.classifiers.trees.J48", "--", "-M", 30)) myAB(Species ~ ., data = iris, control = Weka_control(W = J48, "--", M = 30)) AdaBoostM1(Species ~ ., data = iris, control = Weka_control(W = list(J48, "--", M = 30))) AdaBoostM1(Species ~ ., data = iris, control = Weka_control(W = list(J48, M = 30)))
mergePosterior <- function(...){ chains <- list(...) if( inherits(chains[[1]], what = c("ratematrix_multi_chain", "ratematrix_single_chain") ) ){ if( length( chains[[1]] ) == 1 ) stop( "Need two or more posterior distributions to merge." ) } else if( inherits(chains[[1]], what = "list") ){ if( inherits(chains[[1]][[1]], what = c("ratematrix_multi_chain", "ratematrix_single_chain") ) ){ if( length( chains[[1]] ) == 1 ) stop( "Need two or more posterior distributions to merge." ) class.post <- sapply(chains[[1]], function(x) inherits(x, what = c("ratematrix_multi_chain", "ratematrix_single_chain") )) if( !all( class.post ) ) stop( "All input objects need to be posterior distributions." ) chains <- chains[[1]] } else{ stop( "All input objects need to be posterior distributions." ) } } else{ stop( "All input objects need to be posterior distributions." ) } if( sum( sapply(chains, function(x) inherits(x, what=c("ratematrix_single_chain", "ratematrix_multi_chain")) ) ) == length(chains) ){ if( length( unique( sapply(chains, function(x) class(x)[1] ) ) ) > 1 ) stop("Posterior chains need to belong to the same model. \n") if( length(chains) == 1 ){ if( inherits(chains[[1]], what=c("ratematrix_single_chain")) ){ p <- 1 } else{ p <- length( chains[[1]]$matrix ) regimes <- names( chains[[1]]$matrix ) } } if( length(chains) > 1 ){ if( inherits(chains[[1]], what=c("ratematrix_single_chain")) ){ p <- 1 } else{ p <- length( chains[[1]]$matrix ) regimes <- names( chains[[1]]$matrix ) } } } else{ stop("Arguments need to be output of 'readMCMC' function. Of class 'ratematrix_single_chain' or 'ratematrix_multi_chain'. \n") } mcmc.join <- list() mcmc.join$root <- do.call(rbind, lapply(chains, function(x) x$root) ) if( p == 1 ){ mcmc.join$matrix <- do.call(c, lapply(chains, function(x) x$matrix) ) class( mcmc.join ) <- "ratematrix_single_chain" } else{ mcmc.join$matrix <- lapply(1:p, function(y) do.call(c, lapply(chains, function(x) x$matrix[[y]]) ) ) names( mcmc.join$matrix ) <- regimes class( mcmc.join ) <- "ratematrix_multi_chain" } return( mcmc.join ) }
amova.rda <- function( x, x.data ) { message("Calculation of AMOVA for a balanced design") rda.terms <- attributes(x$terms)$term.labels if (length(rda.terms) > 2) {stop("Calculations only shown for maximum 2 levels")} if (length(rda.terms) == 1) { message("No higher hierarchical level") anova.result <- vegan::anova.cca(x, by="terms", permutations=0) print(anova.result) Df.all <- c(anova.result$Df, sum(anova.result$Df)) Variance.all <- c(anova.result$Variance, sum(anova.result$Variance)) table1 <- data.frame(cbind(Df.all, Variance.all)) names(table1) <- c("Df", "Variance") rownames(table1) <- c(rda.terms, "within.Samples", "Total") table1$SumSq <- table1$Variance * (table1[3, "Df"]) table1$MeanSq <- table1$SumSq / table1$Df message(paste("\n", "Sums-of-Squares are calculated by multiplying variance with (number of individuals - 1)")) print(table1) message("Mean population size:") n1 <- mean(table(x.data[, rda.terms[1]])) print(n1) table2 <- table1[, c(1:2)] names(table2) <- c("Covariance", "Percent") table2[2, 1] <- table1[2, "MeanSq"] table2[1, 1] <- (table1[1, "MeanSq"] - table2[2, 1]) / n1 table2[3, 1] <- sum(table2[1:2, 1]) table2[1, 2] <- 100* table2[1, 1] / table2[3, 1] table2[2, 2] <- 100 * table2[2, 1] / table2[3, 1] table2[3, 2] <- 100 print(table2) } if (length(rda.terms) == 2) { message("Population level of '", rda.terms[2], "' nested within higher level of '", rda.terms[1], "'") anova.result <- vegan::anova.cca(x, by="terms", permutations=0) print(anova.result) Df.all <- c(anova.result$Df, sum(anova.result$Df)) Variance.all <- c(anova.result$Variance, sum(anova.result$Variance)) table1 <- data.frame(cbind(Df.all, Variance.all)) names(table1) <- c("Df", "Variance") rownames(table1) <- c(rda.terms, "within.Samples", "Total") table1$SumSq <- table1$Variance * (table1[4, "Df"]) table1$MeanSq <- table1$SumSq / table1$Df message(paste("\n", "Sums-of-Squares are calculated by multiplying variance with (number of individuals - 1)")) message(paste("The (number of individuals - 1) is also the Df for the total Sum-of-Squares.")) print(table1) message("Mean population size:") n1 <- mean(table(x.data[, rda.terms[2]])) print(n1) message("Mean sizes of higher level:") n2 <- mean(table(x.data[, rda.terms[1]])) print(n2) table2 <- table1[, c(1:2)] names(table2) <- c("Covariance", "Percent") table2[3, 1] <- table1[3, "MeanSq"] table2[2, 1] <- (table1[2, "MeanSq"] - table2[3, 1]) / n1 table2[1, 1] <- (table1[1, "MeanSq"] - table2[3, 1] - n1*table2[2, 1]) / n2 table2[4, 1] <- sum(table2[1:3, 1]) table2[1, 2] <- 100* table2[1, 1] / table2[4, 1] table2[2, 2] <- 100 * table2[2, 1] / table2[4, 1] table2[3, 2] <- 100 * table2[3, 1] / table2[4, 1] table2[4, 2] <- 100 message(paste("\n", "Calculation of covariance")) print(table2) PHI <- numeric(length=3) names(PHI) <- c("Samples-Total", "Samples-Pop", "Pop-Total") PHI[1] <- (table2[1, 1] + table2[2, 1]) / table2[4, 1] PHI[2] <- table2[2, 1] / (table2[2, 1] + table2[3, 1]) PHI[3] <- table2[1, 1] / (table2[4, 1]) message(paste("\n", "Phi statistics")) print(PHI) } }
putPlot <- function(pm, value, i, j){ pos <- get_pos(pm, i, j) if (is.null(value)) { pm$plots[[pos]] <- make_ggmatrix_plot_obj(wrap("blank", funcArgName = "ggally_blank")) } else if (mode(value) == "character") { if (value == "blank") { pm$plots[[pos]] <- make_ggmatrix_plot_obj(wrap("blank", funcArgName = "ggally_blank")) } else { stop("character values (besides 'blank') are not allowed to be stored as plot values.") } } else { pm$plots[[pos]] <- value } pm } getPlot <- function(pm, i, j){ if (FALSE) { cat("i: ", i, " j: ", j, "\n") } pos <- get_pos(pm, i, j) if (pos > length(pm$plots)) { plotObj <- NULL } else { plotObj <- pm$plots[[pos]] } if (is.null(plotObj)) { p <- ggally_blank() } else { if (ggplot2::is.ggplot(plotObj)) { p <- plotObj } else if (inherits(plotObj, "ggmatrix_plot_obj")) { fn <- plotObj$fn p <- fn(pm$data, plotObj$mapping) } else if (inherits(plotObj, "legend_guide_box")) { p <- plotObj } else { firstNote <- str_c("Position: i = ", i, ", j = ", j, "\nstr(plotObj):\n", sep = "") strObj <- capture.output({ str(plotObj) }) stop(str_c("unknown plot object type.\n", firstNote, strObj)) } p <- add_gg_info(p, pm$gg) } p } get_pos <- function(pm, i, j) { if (isTRUE(pm$byrow)) { pos <- j + (pm$ncol * (i - 1)) } else { pos <- i + (pm$nrow * (j - 1)) } pos } get_pos_rev <- function(pm, pos) { if (isTRUE(pm$byrow)) { i <- ceiling(pos / pm$ncol) j <- (pos - 1) %% pm$ncol + 1 } else { i <- (pos - 1) %% pm$nrow + 1 j <- ceiling(pos / pm$nrow) } c(i, j) } check_i_j <- function(pm, i, j) { if ( (length(i) > 1) || (mode(i) != "numeric")) { stop("'i' may only be a single numeric value") } if ( (length(j) > 1) || (mode(j) != "numeric")) { stop("'j' may only be a single numeric value") } if (i > pm$nrow || i < 1) { stop("'i' may only be in the range from 1:", pm$nrow) } if (j > pm$ncol || j < 1) { stop("'j' may only be in the range from 1:", pm$ncol) } invisible() } `[.ggmatrix` <- function(pm, i, j, ...) { check_i_j(pm, i, j) getPlot(pm, i, j) } `[<-.ggmatrix` <- function(pm, i, j, ..., value) { check_i_j(pm, i, j) putPlot(pm, value, i, j) }
remlri <- function(yty,Xty,Zty,XtX,ZtZ,XtZ,ndf,tau=1,imx=100,tol=10^-5,alg=c("FS","NR","EM")){ XtXi <- pinvsm(XtX) XtXiZ <- XtXi%*%XtZ ZtZX <- (-1)*crossprod(XtZ,XtXiZ) diag(ZtZX) <- diag(ZtZX) + ZtZ ZtyX <- Zty-crossprod(XtZ,XtXi)%*%Xty nz <- length(Zty) Deig <- eigen(ZtZX,symmetric=TRUE) nze <- sum(Deig$val>Deig$val[1]*.Machine$double.eps) Deig$values <- Deig$values[1:nze] Deig$vectors <- Deig$vectors[,1:nze] newval <- 1 /(Deig$val+1/tau) Dmat <- Deig$vec%*%tcrossprod(diag(newval),Deig$vec) Bmat <- XtXiZ%*%Dmat alpha <- (XtXi+Bmat%*%t(XtXiZ))%*%Xty - Bmat%*%Zty beta <- Dmat%*%ZtyX sig <- (yty-t(c(Xty,Zty))%*%c(alpha,beta))/ndf if(sig<=0) sig <- 10^-3 n2LLold <- sum(-log(newval)) + sum(log(tau)*nz) + ndf*log(sig) alg <- alg[1] vtol <- 1 iter <- 0 ival <- TRUE if(alg=="FS"){ trval <- sum(newval) gg <- (crossprod(beta)/((tau^2)*sig)) - ((nz/tau)-(trval/(tau^2))) hh <- (nz/(tau^2)) - 2*(trval/(tau^3)) + sum(newval^2)/(tau^4) while(ival) { tau <- tau + as.numeric(gg/hh) if(tau<=0) tau <- 10^-3 newval <- 1/(Deig$val+1/tau) Dmat <- Deig$vec%*%tcrossprod(diag(newval),Deig$vec) Bmat <- XtXiZ%*%Dmat alpha <- (XtXi+Bmat%*%t(XtXiZ))%*%Xty - Bmat%*%Zty beta <- Dmat%*%ZtyX sig <- (yty-t(c(Xty,Zty))%*%c(alpha,beta))/ndf if(sig<=0) sig <- 10^-3 n2LLnew <- sum(-log(newval)) + sum(log(tau)*nz) + ndf*log(sig) vtol <- abs((n2LLold-n2LLnew)/n2LLold) iter <- iter + 1L if(vtol>tol && iter<imx){ n2LLold <- n2LLnew trval <- sum(newval) gg <- (crossprod(beta)/((tau^2)*sig)) - ((nz/tau)-(trval/(tau^2))) hh <- (nz/(tau^2)) - 2*(trval/(tau^3)) + sum(newval^2)/(tau^4) } else { ival <- FALSE } } } else if(alg=="NR"){ trval <- sum(newval) gg <- (crossprod(beta)/((tau^2)*sig)) - ((nz/tau)-(trval/(tau^2))) hh <- 2*(trval/(tau^3)) - (nz/(tau^2)) + sum(newval^2)/(tau^4) hh <- hh + 2*crossprod(beta)/((tau^3)*sig) - 2*crossprod(beta,Dmat%*%beta)/((tau^4)*sig) while(ival) { tau <- tau + as.numeric(gg/hh) if(tau<=0) tau <- 10^-3 newval <- 1/(Deig$val+1/tau) Dmat <- Deig$vec%*%tcrossprod(diag(newval),Deig$vec) Bmat <- XtXiZ%*%Dmat alpha <- (XtXi+Bmat%*%t(XtXiZ))%*%Xty - Bmat%*%Zty beta <- Dmat%*%ZtyX sig <- (yty-t(c(Xty,Zty))%*%c(alpha,beta))/ndf if(sig<=0) sig <- 10^-3 n2LLnew <- sum(-log(newval)) + sum(log(tau)*nz) + ndf*log(sig) vtol <- abs((n2LLold-n2LLnew)/n2LLold) iter <- iter + 1L if(vtol>tol && iter<imx){ n2LLold <- n2LLnew trval <- sum(newval) gg <- (crossprod(beta)/((tau^2)*sig)) - ((nz/tau)-(trval/(tau^2))) hh <- 2*(trval/(tau^3)) - (nz/(tau^2)) + sum(newval^2)/(tau^4) hh <- hh + 2*crossprod(beta)/((tau^3)*sig) - 2*crossprod(beta,Dmat%*%beta)/((tau^4)*sig) } else { ival <- FALSE } } } else { while(ival) { tau <- (mean(beta^2)/sig) + sum(newval)/nz if(tau<=0) tau <- 10^-3 newval <- 1/(Deig$val+1/tau) Dmat <- Deig$vec%*%tcrossprod(diag(newval),Deig$vec) Bmat <- XtXiZ%*%Dmat alpha <- (XtXi+Bmat%*%t(XtXiZ))%*%Xty - Bmat%*%Zty beta <- Dmat%*%ZtyX sig <- (yty-t(c(Xty,Zty))%*%c(alpha,beta))/ndf if(sig<=0) sig <- 10^-3 n2LLnew <- sum(-log(newval)) + sum(log(tau)*nz) + ndf*log(sig) vtol <- abs((n2LLold-n2LLnew)/n2LLold) iter <- iter + 1L if(vtol>tol && iter<imx){ n2LLold <- n2LLnew } else { ival <- FALSE } } } list(tau=as.numeric(tau),sig=as.numeric(sig),iter=iter, cnvg=as.logical(ifelse(vtol>tol,FALSE,TRUE)),vtol=as.numeric(vtol), alpha=alpha,beta=beta,logLik=(-0.5)*n2LLnew) }
context("bulk_postcode_lookup") test_that("bulk_postcode_lookup works as expected", { skip_on_cran() single_postcode <- c("PR3 0SG") pc_list <- list(postcodes = c("PR3 0SG", "M45 6GN", "EX165BL")) lookup_results <- bulk_postcode_lookup(pc_list) expect_error(bulk_postcode_lookup(single_postcode)) expect_error(bulk_postcode_lookup(list())) pc_list <- list(postcodes = 1:101) expect_error(bulk_postcode_lookup(pc_list)) pc_list <- list(postcodes = 1:50, o = 1:51) expect_error(bulk_postcode_lookup(pc_list)) expect_that(lookup_results, is_a("list")) })
dmnorm <- function(x, mean=rep(0,d), varcov, log=FALSE) { d <- if(is.matrix(varcov)) ncol(varcov) else 1 if(d==1) return(dnorm(x, mean, sqrt(varcov), log=log)) x <- if (is.vector(x)) t(matrix(x)) else data.matrix(x) if(ncol(x) != d) stop("mismatch of dimensions of 'x' and 'varcov'") if(is.matrix(mean)) { if ((nrow(x) != nrow(mean)) || (ncol(mean) != d)) stop("mismatch of dimensions of 'x' and 'mean'") } if(is.vector(mean)) mean <- outer(rep(1, nrow(x)), as.vector(matrix(mean,d))) X <- t(x - mean) conc <- pd.solve(varcov, log.det=TRUE) Q <- colSums((conc %*% X)* X) log.det <- attr(conc, "log.det") logPDF <- as.vector(Q + d*logb(2*pi) + log.det)/(-2) if(log) logPDF else exp(logPDF) } rmnorm <- function(n=1, mean=rep(0,d), varcov, sqrt=NULL) { sqrt.varcov <- if(is.null(sqrt)) chol(varcov) else sqrt d <- if(is.matrix(sqrt.varcov)) ncol(sqrt.varcov) else 1 mean <- outer(rep(1,n), as.vector(matrix(mean,d))) drop(mean + t(matrix(rnorm(n*d), d, n)) %*% sqrt.varcov) } pmnorm <- function(x, mean=rep(0, d), varcov, ...) { d <- NCOL(varcov) x <- if (is.vector(x)) matrix(x, 1, d) else data.matrix(x) n <- nrow(x) if(is.vector(mean)) mean <- outer(rep(1, n), as.vector(matrix(mean,d))) if(d == 1) p <- as.vector(pnorm(x, mean, sqrt(varcov))) else { pv <- numeric(n) for (j in 1:n) p <- pv[j] <- if(d == 2) biv.nt.prob(Inf, lower=rep(-Inf, 2), upper=x[j,], mean[j,], varcov) else if(d == 3) ptriv.nt(Inf, x=x[j,], mean[j,], varcov) else sadmvn(lower=rep(-Inf, d), upper=x[j,], mean[j,], varcov, ...) if(n > 1) p <- pv } return(p) } sadmvn <- function(lower, upper, mean, varcov, maxpts=2000*d, abseps=1e-6, releps=0) { if(any(lower > upper)) stop("lower>upper integration limits") if(any(lower == upper)) return(0) d <- as.integer(if(is.matrix(varcov)) ncol(varcov) else 1) varcov <- matrix(varcov, d, d) sd <- sqrt(diag(varcov)) rho <- cov2cor(varcov) lower <- as.double((lower-mean)/sd) upper <- as.double((upper-mean)/sd) if(d == 1) return(pnorm(upper) - pnorm(lower)) if(d == 2) return(biv.nt.prob(Inf, lower, upper, rep(0,2), rho)) infin <- rep(2,d) infin <- replace(infin, (upper == Inf) & (lower > -Inf), 1) infin <- replace(infin, (upper < Inf) & (lower == -Inf), 0) infin <- replace(infin, (upper == Inf) & (lower == -Inf), -1) infin <- as.integer(infin) if(any(infin == -1)) { if(all(infin == -1)) return(1) k <- which(infin != -1) d <- length(k) lower <- lower[k] upper <- upper[k] if(d == 1) return(pnorm(upper) - pnorm(lower)) rho <- rho[k, k] infin <- infin[k] if(d == 2) return(biv.nt.prob(Inf, lower, upper, rep(0,2), rho)) } lower <- replace(lower, lower == -Inf, 0) upper <- replace(upper, upper == Inf, 0) correl <- as.double(rho[upper.tri(rho, diag=FALSE)]) maxpts <- as.integer(maxpts) abseps <- as.double(abseps) releps <- as.double(releps) error <- as.double(0) value <- as.double(0) inform <- as.integer(0) result <- .Fortran("sadmvn", d, lower, upper, infin, correl, maxpts, abseps, releps, error, value, inform, PACKAGE="mnormt") prob <- result[[10]] attr(prob,"error") <- result[[9]] attr(prob,"status") <- switch(1 + result[[11]], "normal completion", "accuracy non achieved", "oversize") return(prob) } dmt <- function (x, mean=rep(0,d), S, df = Inf, log = FALSE) { if (df == Inf) return(dmnorm(x, mean, S, log = log)) d <- if(is.matrix(S)) ncol(S) else 1 if (d==1) { y <- dt((x-mean)/sqrt(S), df=df, log=log) if(log) y <- (y - 0.5*logb(S)) else y <- y/sqrt(S) return(y) } x <- if (is.vector(x)) t(matrix(x)) else data.matrix(x) if (ncol(x) != d) stop("mismatch of dimensions of 'x' and 'varcov'") if (is.matrix(mean)) {if ((nrow(x) != nrow(mean)) || (ncol(mean) != d)) stop("mismatch of dimensions of 'x' and 'mean'") } if(is.vector(mean)) mean <- outer(rep(1, nrow(x)), as.vector(matrix(mean,d))) X <- t(x - mean) S.inv <- pd.solve(S, log.det=TRUE) Q <- colSums((S.inv %*% X) * X) logDet <- attr(S.inv, "log.det") logPDF <- (lgamma((df + d)/2) - 0.5 * (d * logb(pi * df) + logDet) - lgamma(df/2) - 0.5 * (df + d) * logb(1 + Q/df)) if(log) logPDF else exp(logPDF) } rmt <- function(n=1, mean=rep(0,d), S, df=Inf, sqrt=NULL) { sqrt.S <- if(is.null(sqrt)) chol(S) else sqrt d <- if(is.matrix(sqrt.S)) ncol(sqrt.S) else 1 v <- if(df==Inf) 1 else rchisq(n, df)/df z <- rmnorm(n, rep(0, d), sqrt=sqrt.S) mean <- outer(rep(1, n), as.vector(matrix(mean, d))) drop(mean + z/sqrt(v)) } pmt <- function(x, mean=rep(0, d), S, df=Inf, ...){ d <- NCOL(S) x <- if(is.vector(x)) matrix(x, 1, d) else data.matrix(x) n <- nrow(x) if(is.vector(mean)) mean <- outer(rep(1, n), as.vector(matrix(mean,d))) if(d == 1) p <- as.vector(pt((x-mean)/sqrt(S), df=df)) else { pv <- numeric(n) for (j in 1:n) p <- pv[j] <- if(d == 2) biv.nt.prob(df, lower=rep(-Inf, 2), upper=x[j,], mean[j,], S) else if(d == 3) ptriv.nt(df, x=x[j,], mean=mean[j,], S) else sadmvt(df, lower=rep(-Inf, d), upper=x[j,], mean[j,], S, ...) if(n > 1) p <- pv } return(p) } sadmvt <- function(df, lower, upper, mean, S, maxpts=2000*d, abseps=1e-6, releps=0) { if(df == Inf) return(sadmvn(lower, upper, mean, S, maxpts, abseps, releps)) if(any(lower > upper)) stop("lower>upper integration limits") if(any(lower == upper)) return(0) if(round(df) != df) warning("non integer df is rounded to integer") df <- as.integer(round(df)) d <- as.integer(if(is.matrix(S)) ncol(S) else 1) S <- matrix(S, d, d) sd <- sqrt(diag(S)) rho <- cov2cor(S) lower <- as.double((lower-mean)/sd) upper <- as.double((upper-mean)/sd) if(d == 1) return(pt(upper, df) - pt(lower, df)) if(d == 2) return(biv.nt.prob(df, lower, upper, rep(0,2), rho)) infin <- rep(2,d) infin <- replace(infin, (upper == Inf) & (lower > -Inf), 1) infin <- replace(infin, (upper < Inf) & (lower == -Inf), 0) infin <- replace(infin, (upper == Inf) & (lower == -Inf), -1) infin <- as.integer(infin) if(any(infin == -1)) { if(all(infin == -1)) return(1) k <- which(infin != -1) d <- length(k) lower <- lower[k] upper <- upper[k] if(d == 1) return(pt(upper, df=df) - pt(lower, df=df)) rho <- rho[k, k] infin <- infin[k] if(d == 2) return(biv.nt.prob(df, lower, upper, rep(0,2), rho)) } lower <- replace(lower, lower == -Inf, 0) upper <- replace(upper, upper == Inf, 0) correl <- rho[upper.tri(rho, diag=FALSE)] maxpts <- as.integer(maxpts) abseps <- as.double(abseps) releps <- as.double(releps) error <- as.double(0) value <- as.double(0) inform <- as.integer(0) result <- .Fortran("sadmvt", d, df, lower, upper, infin, correl, maxpts, abseps, releps, error, value, inform, PACKAGE="mnormt") prob <- result[[11]] attr(prob,"error") <- result[[10]] attr(prob,"status") <- switch(1+result[[12]], "normal completion", "accuracy non achieved", "oversize") return(prob) } biv.nt.prob <- function(df, lower, upper, mean, S){ if(any(dim(S) != c(2,2))) stop("dimensions mismatch") if(length(mean) != 2) stop("dimensions mismatch") if(round(df) != df) warning("non integer df is rounded to integer") nu <- if(df < Inf) as.integer(round(df)) else 0 sd <- sqrt(diag(S)) rho <- cov2cor(S)[1,2] lower <- as.double((lower-mean)/sd) upper <- as.double((upper-mean)/sd) if(any(lower > upper)) stop("lower>upper integration limits") if(any(lower == upper)) return(0) infin <- c(2,2) infin <- replace(infin, (upper == Inf) & (lower > -Inf), 1) infin <- replace(infin, (upper < Inf) & (lower == -Inf), 0) infin <- replace(infin, (upper == Inf) & (lower == -Inf), -1) infin <- as.integer(infin) if(any(infin == -1)) { if(all(infin == -1)) return(1) k <- which(infin != -1) return(pt(upper[k], df=df) - pt(lower[k], df=df)) } lower <- replace(lower, lower == -Inf, 0) upper <- replace(upper, upper == Inf, 0) rho <- as.double(rho) prob <- as.double(0) a <- .Fortran("smvbvt", prob, nu, lower, upper, infin, rho, PACKAGE="mnormt") return(a[[1]]) } ptriv.nt <- function(df, x, mean, S){ if(any(dim(S) != c(3,3))) stop("dimensions mismatch") if(length(mean) != 3) stop("dimensions mismatch") if(round(df) != df) warning("non integer df is rounded to integer") nu <- if(df < Inf) as.integer(round(df)) else 0 if(any(x == -Inf)) return(0) ok <- !is.infinite(x) p <- if(sum(ok) == 1) pt(df, (x[ok]-mean[ok])/sqrt(S[ok,ok])) else if(sum(ok) == 2) biv.nt.prob(nu, rep(2 -Inf), x[ok], mean[ok], S[ok,ok]) else { sd <- sqrt(diag(S)) h <- as.double((x-mean)/sd) cor <- cov2cor(S) rho <- as.double(c(cor[2,1], cor[3,1], cor[2,3])) prob <- as.double(0) epsi <- as.double(1e-14) a <- .Fortran("stvtl", prob, nu, h, rho, epsi, PACKAGE="mnormt") p <- a[[1]] } return(p) } pd.solve <- function(x, silent=FALSE, log.det=FALSE) { if(is.null(x)) return(NULL) if(any(is.na(x))) {if(silent) return (NULL) else stop("NA's in x") } if(length(x) == 1) x <- as.matrix(x) if(!(inherits(x, "matrix"))) {if(silent) return(NULL) else stop("x is not a matrix")} if(max(abs(x - t(x))) > .Machine$double.eps) {if(silent) return (NULL) else stop("x appears to be not symmetric") } x <- (x + t(x))/2 u <- try(chol(x, pivot = FALSE), silent = silent) if(inherits(u, "try-error")) { if(silent) return(NULL) else stop("x appears to be not positive definite") } inv <- chol2inv(u) if(log.det) attr(inv, "log.det") <- 2 * sum(log(diag(u))) dimnames(inv) <- rev(dimnames(x)) return(inv) } .onLoad <- function(library, pkg) { library.dynam("mnormt", pkg, library) invisible() }
rain <- function(n) rainbow(n, v=0.8) excl <- function(n) c(" predict.LPS <- function( object, newdata, type = c("class", "probability", "score"), method = c("Wright", "Radmacher", "exact"), threshold = 0.9, na.rm = TRUE, subset = NULL, col.lines = " col.classes = c(" plot = FALSE, side = NULL, cex.col = NA, cex.row = NA, mai.left = NA, mai.bottom = NA, mai.right = 1, mai.top = 0.1, side.height = 1, side.col = NULL, col.heatmap = heat(), zlim = "0 centered", norm = c("rows", "columns", "none"), norm.robust = FALSE, customLayout = FALSE, getLayout = FALSE, ... ) { type <- match.arg(type) method <- match.arg(method) norm <- match.arg(norm) if(isTRUE(plot) && !isTRUE(customLayout)) { heights <- 3 if(!is.null(side)) heights <- c(lcm(ncol(side)*side.height), heights) if(type == "class") { heights <- c(lcm(2*side.height), heights) } else { heights <- c(1, heights) } widths <- 1L if(is.null(side)) { mat <- matrix(c(2,1), ncol=1) } else { mat <- matrix(c(3,1,2), ncol=1) } } else { mat <- as.integer(NA) heights <- as.integer(NA) widths <- as.integer(NA) } if(isTRUE(getLayout)) { return(list(mat=mat, heights=heights, widths=widths)) } if(is.vector(newdata)) { score <- newdata if(!is.null(subset)) score <- score[ subset ] } else { expr <- as.matrix(newdata[, names(object$coeff) ]) if(!is.null(subset)) expr <- expr[ subset , , drop=FALSE ] score <- apply(t(expr) * object$coeff, 2, sum, na.rm=na.rm) } if(type == "score") { out <- score } else { if(method == "Radmacher") { P1 <- as.double(abs(score - object$means[1]) < abs(score - object$means[2])) P2 <- 1 - P1 } else if(method == "Wright") { D1 <- dnorm(score, mean=object$means[1], sd=object$sd[1]) D2 <- dnorm(score, mean=object$means[2], sd=object$sd[2]) P1 <- D1 / (D1 + D2) P2 <- 1 - P1 } else if(method == "exact") { if(object$means[1] < object$means[2]) { gLow <- 1L; gHigh <- 2L } else { gLow <- 2L; gHigh <- 1L } D <- list(double(length(score)), double(length(score))) for(i in 1:length(score)) { D[[ gLow ]][i] <- sum(object$scores[[ gLow ]] >= score[i]) / length(object$scores[[ gLow ]]) D[[ gHigh ]][i] <- sum(object$scores[[ gHigh ]] <= score[i]) / length(object$scores[[ gHigh ]]) } P1 <- D[[1]] / (D[[1]] + D[[2]]) P2 <- 1 - P1 } } if(type == "probability") { out <- cbind(P1, P2) colnames(out) <- object$classes rownames(out) <- names(score) } else if(type == "class") { out <- rep(as.character(NA), length(P1)) names(out) <- names(score) out[ P1 > threshold ] <- object$classes[1] out[ P2 > threshold ] <- object$classes[2] out[ P1 > threshold & P2 > threshold ] <- paste(object$classes, collapse=" & ") } if(isTRUE(plot)) { if(!isTRUE(customLayout)) { layout(mat=mat, heights=heights) on.exit(layout(1)) } expr <- expr[ order(score) , order(object$t) ] out <- c( list(out), heat.map( expr = expr, customLayout = TRUE, cex.col = cex.col, cex.row = cex.row, mai.left = mai.left, mai.bottom = mai.bottom, mai.right = mai.right, mai.top = 0.1, side = side, side.height = side.height, side.col = side.col, col.heatmap = col.heatmap, zlim = zlim, norm = norm, norm.robust = norm.robust ) ) axis(side=4, at=(1:ncol(expr) - 1L) / (ncol(expr) - 1L), labels=sprintf("%+0.3f", object$t[ colnames(expr) ]), las=2, cex.axis=out$cex.row, tick=FALSE) if(type != "score") { Y1 <- which(head(P1[ order(score) ] > threshold, -1) != tail(P1[ order(score) ] > threshold, -1)) Y2 <- which(head(P2[ order(score) ] > threshold, -1) != tail(P2[ order(score) ] > threshold, -1)) abline(v=c(Y1-0.5, Y2-0.5)/(nrow(expr) - 1L), lwd=2, col=col.lines) box() } x <- tail(which(sort(object$coeff) <= 0), 1)-0.5 abline(h=x/(ncol(expr) - 1L), lwd=2, col=col.lines) par(mai=c(0, out$mai.left, mai.top, mai.right)) if(type == "score") { plot(x=1:nrow(expr), xlim=c(0.5, nrow(expr)+0.5), y=score[ order(score) ], type="o", pch=16, cex=0.5, xaxs="i", yaxs="i", xpd=NA, xaxt="n", yaxt="n", xlab="", ylab="Score") } else if(type == "probability") { plot(x=1:nrow(expr), xlim=c(0.5, nrow(expr)+0.5), ylim=0:1, y=P1[ order(score) ], type="o", pch=16, cex=0.5, xaxs="i", yaxs="i", xpd=NA, xaxt="n", xlab="", ylab="Probability", col=col.classes[1]) par(new=TRUE) plot(x=1:nrow(expr), xlim=c(0.5, nrow(expr)+0.5), ylim=0:1, y=P2[ order(score) ], type="o", pch=16, cex=0.5, xaxs="i", yaxs="i", xpd=NA, xaxt="n", yaxt="n", xlab="", ylab="", bty="n", col=col.classes[2]) abline(h=threshold, lty="dotted") legend(x="right", inset=0.01, bg=" } else if(type == "class") { plot(x=NA, y=NA, xlim=c(0.5, nrow(expr)+0.5), ylim=0:1, xaxs="i", yaxs="i", xaxt="n", yaxt="n", xlab="", ylab="Class") k <- factor(out[[1]][ order(score) ]) levels(k) <- col.classes rect(xleft=(1:nrow(expr))-0.5, xright=(1:nrow(expr))+0.5, ybottom=0, ytop=1, col=as.character(k)) text(y=0.5, labels=object$classes[ which.min(object$means) ], adj=0, col="white", font=2, x=1) text(y=0.5, labels=object$classes[ which.max(object$means) ], adj=1, col="white", font=2, x=nrow(expr)) } } return(out) }
CMAR_C <- function(train, test, min_confidence=0.5, min_support=0.01, databaseCoverage=4){ alg <- RKEEL::R6_CMAR_C$new() alg$setParameters(train, test, min_confidence, min_support, databaseCoverage) return (alg) } R6_CMAR_C <- R6::R6Class("R6_CMAR_C", inherit = AssociativeClassificationAlgorithm, public = list( min_confidence = 0.5, min_support = 0.01, databaseCoverage = 4, setParameters = function(train, test, min_confidence=0.5, min_support=0.01, databaseCoverage=4){ super$setParameters(train, test) stopText <- "" if((hasMissingValues(train)) || (hasMissingValues(test))){ stopText <- paste0(stopText, "Dataset has missing values and the algorithm does not accept it.\n") } if((hasContinuousData(train)) || (hasContinuousData(test))){ stopText <- paste0(stopText, "Dataset has continuous data and the algorithm does not accept it.\n") } if(stopText != ""){ stop(stopText) } self$min_confidence <- min_confidence self$min_support <- min_support self$databaseCoverage <- databaseCoverage } ), private = list( jarName = "Clas-CMAR.jar", algorithmName = "CMAR-C", algorithmString = "Accurate and Efficient Classification Based on Multiple Class Association Rules (CMAR)", getParametersText = function(){ text <- "" text <- paste0(text, "Minimum Confidence = ", self$min_confidence, "\n") text <- paste0(text, "Minimum Support = ", self$min_support, "\n") text <- paste0(text, "Database Coverage Threshold (delta) = ", self$databaseCoverage, "\n") return(text) } ) )
library(icd) library(crayon) if (!exists("e", mode = "environment") || length(ls(envir = e)) == 0) { d2_dir <- "/tmp/d3" e <- new.env() nms <- lapply(list.files(d2_dir, full.names = TRUE), load, envir = e) nms <- unlist(nms) } for (n in nms) { message(blue("Working on "), yellow(n)) xo <- get(x = n, envir = as.environment("package:icd")) xe <- get(x = n, envir = e) if (identical(xo, xe)) { message(green("Identical")) next } print(testthat::compare(xo, xe)) }
tam_mml_calc_prob_R <- function(iIndex, A, AXsi, B, xsi, theta, nnodes, maxK, recalc=TRUE, avoid_outer=FALSE ) { D <- ncol(theta) if(recalc){ LI <- length(iIndex) LXsi <- dim(A)[3] AXsi.tmp <- array( 0, dim=c( LI, maxK, nnodes ) ) for (kk in 1:maxK){ A_kk <- matrix( A[ iIndex, kk, ], nrow=LI, ncol=LXsi ) AXsi.tmp[, kk, 1:nnodes ] <- A_kk %*% xsi } AXsi[iIndex,] <- AXsi.tmp[,,1] } else { AXsi.tmp <- array( AXsi[ iIndex, ], dim=c( length(iIndex), maxK, nnodes ) ) } dim_Btheta <- c(length(iIndex), maxK, nnodes) Btheta <- array(0, dim=dim_Btheta ) for( dd in 1:D ){ B_dd <- B[iIndex,,dd,drop=FALSE] theta_dd <- theta[,dd] if (! avoid_outer){ Btheta_add <- array(B_dd %o% theta_dd, dim=dim(Btheta)) } else { Btheta_add <- tam_rcpp_tam_mml_calc_prob_R_outer_Btheta( Btheta=Btheta, B_dd=B_dd, theta_dd=theta_dd, dim_Btheta=dim_Btheta ) Btheta_add <- array(Btheta_add, dim=dim_Btheta) } Btheta <- Btheta + Btheta_add } rr0 <- Btheta + AXsi.tmp dim_rr <- dim(rr0) rr <- tam_rcpp_calc_prob_subtract_max_exp( rr0=rr0, dim_rr=dim_rr ) rprobs <- tam_rcpp_tam_mml_calc_prob_R_normalize_rprobs( rr=rr, dim_rr=dim_rr) rprobs <- array(rprobs, dim=dim_rr) res <- list("rprobs"=rprobs, "AXsi"=AXsi) return(res) }
context("Replicate") test_that("length of results are correct", { a <- rlply(4, NULL) b <- rlply(4, 1) expect_equal(length(a), 4) expect_equal(length(b), 4) }) test_that("name of id column is set", { df <- rdply(4, function() c(a=1), .id='index') expect_equal(names(df), c('index', 'a')) })
labels <- function(object, ...) UseMethod("labels") labels.default <- function(object, ...) { if(length(d <- dim(object))) { nt <- dimnames(object) if(is.null(nt)) nt <- vector("list", length(d)) for(i in seq_along(d)) if(!length(nt[[i]])) nt[[i]] <- as.character(seq_len(d[i])) } else { nt <- names(object) if(!length(nt)) nt <- as.character(seq_along(object)) } nt }
test_that("checkData", { expect_error( makeClassifTask(data = binaryclass.df, target = "foo"), "doesn't contain target var: foo" ) df = multiclass.df df[1, multiclass.target] = NA expect_error(makeClassifTask(data = df, target = multiclass.target), "missing values") df = regr.df df[1, regr.target] = NaN expect_error(makeRegrTask(data = df, target = regr.target), "missing values") df = regr.df df[1, regr.target] = Inf expect_error(makeRegrTask(data = df, target = regr.target), "be finite") df = regr.df df[1, getTaskFeatureNames(regr.task)[1]] = Inf expect_error(makeRegrTask(data = df, target = regr.target), "infinite") df = regr.df df[1, getTaskFeatureNames(regr.task)[1]] = NaN expect_error(makeRegrTask(data = df, target = regr.target), "contains NaN") df = binaryclass.df df[, binaryclass.target] = as.character(df[, binaryclass.target]) task = makeClassifTask(data = df, target = binaryclass.target) expect_true(is.factor(getTaskTargets(task))) df = binaryclass.df df[, binaryclass.target] = as.logical(as.integer(binaryclass.df[, binaryclass.target]) - 1) task = makeClassifTask(data = df, target = binaryclass.target) expect_true(is.factor(getTaskTargets(task))) df = regr.df df[, regr.target] = as.integer(regr.df[, regr.target]) task = makeRegrTask(data = df, target = regr.target) expect_true(is.numeric(getTaskTargets(task))) df = multiclass.df df[, 1] = as.logical(df[, 1]) colnames(df)[1] = "aaa" expect_error(makeClassifTask(data = df, target = multiclass.target), "Unsupported feature type") expect_equal(nrow(getTaskData(costiris.task)), nrow(getTaskCosts(costiris.task))) }) test_that("changeData . getTaskData is a noop on builtin tasks", { pkgdata = data(package = "mlr")$results[, "Item"] tasknames = grep("\\.task$", pkgdata, value = TRUE) for (task in tasknames) { taskdata = get(task) changeddata = changeData(taskdata, getTaskData(taskdata, functionals.as = "matrix")) taskdata$env = NULL changeddata$env = NULL expect_equal(taskdata, changeddata) } })
plot.MFAmix <- function(x, axes = c(1, 2), choice = "ind", label=TRUE, coloring.var = "not", coloring.ind=NULL, nb.partial.axes=3, col.ind=NULL, col.groups=NULL, partial = NULL, lim.cos2.plot = 0, lim.contrib.plot=0, xlim = NULL, ylim = NULL, cex = 1, main = NULL, leg=TRUE,posleg="topleft",cex.leg=0.8, col.groups.sup=NULL,posleg.sup="topright",nb.paxes.sup=3,...) { cl<-match.call() if (!inherits(x, "MFAmix")) stop("use only with \"MFAmix\" objects") n <- nrow(x$ind$coord) if (is.null(x$sqload.sup)) sup <- FALSE else sup <- TRUE if (!(choice %in% c("ind", "sqload", "levels", "cor", "axes", "groups"))) stop("\"choice\" must be either \"ind\",\"sqload\",\"cor\", \"levels\",\"axes\" or \"groups\"",call.=FALSE) if ((choice=="levels") & is.null(x$levels) & is.null(x$levels.sup)) stop("\"choice=levels\" is not possible with pure quantitative data",call. = FALSE) if ((choice=="cor") & is.null(x$quanti) & is.null(x$quanti.sup)) stop("\"choice=cor\" is not possible with pure qualitative data",call. = FALSE) if (!is.logical(leg)) stop("argument \"leg\" must be TRUE or FALSE",call. = FALSE) if (lim.cos2.plot != 0 & lim.contrib.plot!=0) stop("use either \"lim.cos2.plot\" OR \"lim.contrib.plot\"",call. = FALSE) if (!is.null(partial)) if (!is.character(partial) | length(which(rownames(x$ind$coord) %in% partial))==0) stop("invalid values in \"partial\"",call. = FALSE) if (!is.null(coloring.ind)) { if (choice!="ind") warning("use \"coloring.ind\" only if choice=\"ind\"") if (!is.null(partial)) warning("use \"coloring.ind\" only if partial=NULL") } if (!is.null(coloring.ind)) { if (!is.factor(coloring.ind) | length(coloring.ind)!=n) { warning("\"coloring.ind\" must be either NULL or a qualitative variable of class factor. Its length must be equal to the number of individuals") coloring.ind=NULL } } if (coloring.var!="groups" & coloring.var!="type" & coloring.var!="not") stop("'coloring.var' must be one of the following: 'not', 'type', 'groups'",call. = FALSE) if (coloring.var=="type") if (choice=="ind" | choice=="cor" | choice=="levels"| choice=="axes") { warning("coloring.var=\"type\" is not used if choice=\"ind\", \"cor\",\"levels\" or \"axes\"",call. = FALSE) coloring.var <- "not" } if (coloring.var=="groups") if (choice=="ind") { warning("\"coloring.var\" is not used if choice=\"ind\"") coloring.var <- "not" } eig.axes <- x$eig[axes,1] dim1 <- axes[1] dim2 <- axes[2] lab.x <- paste("Dim ", dim1, " (", signif(x$eig[axes[1],2], 4), " %)", sep = "") lab.y <- paste("Dim ",dim2, " (", signif(x$eig[axes[2],2], 4), " %)", sep = "") ngroup <- nrow(x$groups$contrib) name.groups <- names(x$partial.axes) name.groups.sup <- names(x$partial.axes.sup) if (sup) ngroupsup <- nrow(x$group.sup) if (is.null(col.groups)) col.groups <- 2:(ngroup+1) else if (length(col.groups)!=ngroup) { warning("invalid length of \"col.groups\"") col.groups <- 2:(ngroup+1) } if (sup) if (is.null(col.groups.sup)) col.groups.sup <- (ngroup+2):(ngroup+ngroupsup+1) else if (length(col.groups.sup)!=ngroupsup) { warning("invalid length of \"col.groups.sup\"") col.groups.sup <- (ngroup+2):(ngroup+ngroupsup+1) } p1 <- x$global.pca$rec$p1 p <- x$global.pca$rec$p p2<-x$global.pca$rec$p2 m <- ncol(x$global.pca$rec$W)-p1 if (sup) { p.sup <- x$rec.sup$p p1.sup <- x$rec.sup$p1 p2.sup <- x$rec.sup$p2 } if (choice == "axes") { if (is.null(main)) main <- "Partial axes" if (is.null(xlim)) xlim <- c(-1.1, 1.1) if (is.null(ylim)) ylim <- c(-1.1, 1.1) graphics::plot(0, 0, xlab = lab.x, ylab = lab.y, xlim = xlim, ylim = ylim, col = "white", asp = 1, cex = cex, main = main,...) x.cercle <- seq(-1, 1, by = 0.01) y.cercle <- sqrt(1 - x.cercle^2) graphics::lines(x.cercle, y = y.cercle) graphics::lines(x.cercle, y = -y.cercle) graphics::abline(v = 0, lty = 2, cex = cex) graphics::abline(h = 0, lty = 2, cex = cex) coord.paxes <- NULL col.paxes <- NULL for (i in 1:ngroup) { nmax <- min(nrow(x$partial.axes[[i]]),nb.partial.axes) coord.paxes <- rbind(coord.paxes, x$partial.axes[[i]][1:nmax,c(dim1,dim2)]) col.paxes <- c(col.paxes,rep(col.groups[i],nmax)) } if (coloring.var != "groups") col.paxes <- rep("black",nrow(coord.paxes)) for (v in 1:nrow(coord.paxes)) { graphics::arrows(0, 0, coord.paxes[v, 1], coord.paxes[v, 2], length = 0.1, angle = 15, code = 2, col = col.paxes[v], cex = cex) if (abs(coord.paxes[v, 1]) > abs(coord.paxes[v, 2])) { if (coord.paxes[v, 1] >= 0) pos <- 4 else pos <- 2 } else { if (coord.paxes[v, 2] >= 0) pos <- 3 else pos <- 1 } graphics::text(coord.paxes[v, 1], y = coord.paxes[v, 2], labels = rownames(coord.paxes)[v], pos = pos, col = col.paxes[v], cex = cex,...) } if ((coloring.var == "groups") & (leg==TRUE)) graphics::legend((posleg), legend = name.groups, text.col = col.groups, cex = cex.leg) if (sup) { coord.paxes <- NULL col.paxes <- NULL for (i in 1:ngroupsup) { nmax <- min(nrow(x$partial.axes.sup[[i]]),nb.paxes.sup) coord.paxes <- rbind(coord.paxes, x$partial.axes.sup[[i]][1:nmax,c(dim1,dim2)]) col.paxes <- c(col.paxes,rep(col.groups.sup[i],nmax)) } if (coloring.var != "groups") col.paxes <- rep("black",nrow(coord.paxes)) for (v in 1:nrow(coord.paxes)) { graphics::arrows(0, 0, coord.paxes[v, 1], coord.paxes[v, 2], length = 0.1, angle = 15, lty=5, code = 2, col = col.paxes[v], cex = cex) if (abs(coord.paxes[v, 1]) > abs(coord.paxes[v, 2])) { if (coord.paxes[v, 1] >= 0) pos <- 4 else pos <- 2 } else { if (coord.paxes[v, 2] >= 0) pos <- 3 else pos <- 1 } graphics::text(coord.paxes[v, 1], y = coord.paxes[v, 2], labels = rownames(coord.paxes)[v], pos = pos, col = col.paxes[v], cex = cex,...) } if ((coloring.var == "groups") & (leg==TRUE)) graphics::legend((posleg.sup), legend = name.groups.sup, text.col = col.groups.sup, cex = cex.leg) } } if (choice == "groups") { if (is.null(main)) main <- "Groups contributions" coord.groups <- x$groups$contrib[, axes, drop = FALSE] xmax <- max(coord.groups[,1],x$groups.sup[,dim1], xlim) xlim <- c(0, xmax * 1.2) ymax <- max(coord.groups[,2],x$groups.sup[,dim1],ylim) ylim <- c(0, ymax * 1.2) if (coloring.var != "groups") { col.groups = rep("darkred", nrow(coord.groups)) if (sup) col.groups.sup <- rep("blue", ngroupsup) } graphics::plot(coord.groups, xlab = lab.x, ylab = lab.y, xlim = xlim, ylim = ylim, pch = 17, col = col.groups, cex = cex, main = main, cex.main = cex * 1.2, asp = 1,...) graphics::abline(v = 0, lty = 2,cex=cex) graphics::abline(h = 0, lty = 2,cex=cex) if (label) graphics::text(coord.groups[, 1], y = coord.groups[, 2], labels = rownames(coord.groups), pos = 3, col = col.groups, cex = cex) if (sup) { graphics::points(x$group.sup[,axes,drop=FALSE], xlab = lab.x, ylab = lab.y, xlim = xlim, ylim = ylim, pch = 2, col = col.groups.sup, cex = cex, main= main, cex.main = cex * 1.2, asp = 1,...) if (label) graphics::text(x=x$group.sup[,dim1], y=x$group.sup[,dim2], labels = rownames(x$group.sup), pos = 3, col = col.groups.sup, cex = cex,...) } } if (choice=="sqload") { if (is.null(main)) main <- "Squared loadings" xmax <- max(x$sqload[, dim1],x$sqload.sup[, dim1],xlim) xlim <- c(-0.1, xmax * 1.2) ymax <- max(x$sqload[, dim2],x$sqload.sup[, dim2],ylim) ylim <- c(-0.1, ymax * 1.2) graphics::plot(0, 0, type="n",xlab = lab.x, ylab = lab.y, xlim = xlim, ylim = ylim,cex=cex,main=main,...) graphics::abline(v = 0, lty = 2,cex=cex) graphics::abline(h = 0, lty = 2,cex=cex) col.var <- rep(1,p) if (coloring.var == "groups") { for (i in 1:ngroup) col.var[which(x$index.group==i)] <- col.groups[i] } if (coloring.var=="type") { if (p1 >0) col.var[1:p1] <- "blue" if (p2 >0) col.var[(p1+1):p] <- "red" } for (j in 1:p) { graphics::arrows(0,0,x$sqload[j,dim1],x$sqload[j,dim2], length = 0.1, angle = 15, code = 2,cex=cex,col=col.var[j]) if (label) { if (x$sqload[j,dim1] > x$sqload[j,dim1]) { pos <- 4 } else pos <- 3 graphics::text(x$sqload[j,dim1],x$sqload[j,dim2], labels = rownames(x$sqload)[j], pos = pos,cex=cex,col=col.var[j],...) } } if ((coloring.var == "groups") & (leg==TRUE)) graphics::legend((posleg), legend = name.groups, text.col = col.groups, cex = cex.leg) if (coloring.var=="type" & (leg==TRUE)) graphics::legend(posleg, legend = c("numerical","categorical"), text.col = c("blue","red"), cex=cex.leg) if (sup) { col.var.sup <- rep(4,) if (coloring.var == "groups") for (i in 1:ngroupsup) col.var.sup[which(x$index.groupsup==i)] <- col.groups.sup[i] if (coloring.var=="type") { if (p1.sup >0) col.var.sup[1:p1.sup] <- "blue" if (p2.sup >0) col.var.sup[(p1.sup+1):p.sup] <- "red" } for (j in 1:nrow(x$sqload.sup)) { graphics::arrows(0, 0, x$sqload.sup[j, dim1], x$sqload.sup[j, dim2], length = 0.1, angle = 15, code = 2, lty=5, col=col.var.sup[j],cex = cex,...) if (label) { if (x$sqload.sup[j, dim1] > x$sqload.sup[j, dim2]) { pos <- 4 } else pos <- 3 graphics::text(x$sqload.sup[j, dim1], x$sqload.sup[j, dim2], labels = rownames(x$sqload.sup)[j], pos = pos, cex = cex,col=col.var.sup[j],...) } } if ((coloring.var == "groups") & (leg==TRUE)) graphics::legend((posleg.sup), legend = name.groups.sup, text.col = col.groups.sup, cex = cex.leg) } } if (choice == "cor") { if (is.null(main)) main <- "Correlation circle" if (is.null(xlim)) xlim = c(-1.1, 1.1) if (is.null(ylim)) ylim = c(-1.1, 1.1) graphics::plot(0, 0, main = main, xlab = lab.x, ylab = lab.y, xlim = xlim, ylim = ylim, col = "white", asp = 1, cex = cex,...) x.cercle <- seq(-1, 1, by = 0.01) y.cercle <- sqrt(1 - x.cercle^2) graphics::lines(x.cercle, y = y.cercle) graphics::lines(x.cercle, y = -y.cercle) graphics::abline(v = 0, lty = 2, cex = cex) graphics::abline(h = 0, lty = 2, cex = cex) if (!is.null(x$quanti)) { if (lim.cos2.plot == 0 & lim.contrib.plot==0) { lim.plot<-0 base.lim<-x$quanti$cos2[,axes] } if (lim.cos2.plot != 0) { lim.plot<-lim.cos2.plot base.lim<-x$quanti$cos2[,axes] } if(lim.contrib.plot!=0) { lim.plot<-lim.contrib.plot base.lim<-x$quanti$contrib[,axes] base.lim<-100*(base.lim/sum(eig.axes)) } } coord.var <- x$quanti$coord[, axes, drop = FALSE] col.var <- rep(1,p) if (coloring.var == "groups") { for (i in 1:ngroup) col.var[which(x$index.group==i)] <- col.groups[i] } col.var <- col.var[1:p1] test.empty.plot<-c() for (v in 1:nrow(coord.var)) { if (sum(base.lim[v, ] , na.rm = TRUE) >= lim.plot && !is.na(sum(base.lim[v, ], na.rm = TRUE))) { test.empty.plot<-c(test.empty.plot,1) graphics::arrows(0, 0, coord.var[v, 1], coord.var[v,2], length = 0.1, angle = 15, code = 2,cex = cex,col=col.var[v]) if (label) { if (abs(coord.var[v, 1]) > abs(coord.var[v, 2])) { if (coord.var[v, 1] >= 0) pos <- 4 else pos <- 2 } else { if (coord.var[v, 2] >= 0) pos <- 3 else pos <- 1 } graphics::text(coord.var[v, 1], y = coord.var[v, 2], labels = rownames(coord.var)[v], pos = pos, cex = cex,col=col.var[v]) } } } if(is.null(test.empty.plot)) warning("\"lim.cos.plot\" (or \"lim.contrib.plot\") is too large. No variable can be plotted") if ((coloring.var == "groups") & (leg==TRUE)) graphics::legend(posleg, legend = name.groups[unique(x$index.group[1:p1])], text.col = unique(col.var), cex = cex.leg) if (!is.null(x$quanti.sup)) { coord.var.sup <- x$quanti.sup$coord[, axes, drop = FALSE] col.var.sup <- rep(1,p1.sup) if (coloring.var == "groups") { for (i in 1:ngroupsup) col.var.sup[which(x$index.groupsup==i)] <- col.groups.sup[i] } col.var.sup <- col.var.sup[1:p1.sup] for (v in 1:nrow(coord.var.sup)) { graphics::arrows(0, 0, coord.var.sup[v, 1], coord.var.sup[v,2], length = 0.1, angle = 15, code = 2,cex = cex,col= col.var.sup[v],lty=5) if (label) { if (abs(coord.var.sup[v, 1]) > abs(coord.var.sup[v,2])) { if (coord.var.sup[v, 1] >= 0) pos <- 4 else pos <- 2 } else { if (coord.var.sup[v, 2] >= 0) pos <- 3 else pos <- 1 } graphics::text(coord.var.sup[v, 1], y = coord.var.sup[v, 2], labels = rownames(coord.var.sup)[v], pos = pos, cex = cex,col=col.var.sup[v]) } } if ((coloring.var == "groups") & (leg==TRUE)) graphics::legend(posleg.sup, legend = name.groups.sup[unique(x$index.groupsup[1:p1.sup])], text.col = unique(col.var.sup), cex = cex.leg) } } if (choice == "ind") { if (is.null(main)) main <- "Individuals component map" coord.ind <- x$ind$coord if (lim.cos2.plot == 0 & lim.contrib.plot==0) { lim.plot<-0 select.ind <- 1:nrow(coord.ind) } if (lim.cos2.plot != 0 & lim.contrib.plot==0) { lim.plot <- lim.cos2.plot base.lim <- x$ind$cos2[,axes] select.ind <- which(apply(base.lim[,],1,sum)>=lim.plot) } if (lim.cos2.plot == 0 & lim.contrib.plot!=0) { lim.plot <- lim.contrib.plot base.lim <- x$ind$contrib[,axes] base.lim <- 100*(base.lim/sum(eig.axes)) select.ind <- which(apply(base.lim[,],1,sum)>=lim.plot) } if (is.null(partial)) { if (length(select.ind)==0) stop("\"lim.cos.plot\" (or \"lim.contrib.plot\") is too large. No individuals can be plotted",call. = FALSE) coord.ind <- coord.ind[select.ind, , drop=FALSE] xmin <- min(xlim,coord.ind[, dim1]) xmax <- max(xlim,coord.ind[, dim1]) xlim <- c(xmin, xmax) * 1.2 ymin <- min(ylim,coord.ind[, dim2]) ymax <- max(ylim,coord.ind[, dim2]) ylim <- c(ymin, ymax) * 1.2 if (is.null(col.ind) | is.null(coloring.ind)) { col.plot.ind <- rep("black",nrow(coord.ind)) } if (is.factor(coloring.ind)) { quali<-coloring.ind if (!is.null(col.ind)) { levels(quali) <- col.ind col.plot.ind <- quali } if (is.null(col.ind)) col.plot.ind <- as.numeric(quali) } col.plot.ind.total<-col.plot.ind col.plot.ind <- col.plot.ind[select.ind] graphics::plot(coord.ind[, axes,drop=FALSE], xlim = xlim, ylim = ylim, xlab = lab.x, ylab = lab.y, pch = 20, col = as.character(col.plot.ind), cex = cex, main=main,...) graphics::abline(h = 0, lty = 2, cex = cex) graphics::abline(v = 0, lty = 2, cex = cex) if (leg==TRUE & is.factor(coloring.ind)) graphics::legend(posleg, legend =paste(cl["coloring.ind"],levels(coloring.ind),sep="="), text.col = levels(as.factor(col.plot.ind.total)), cex =cex.leg) if (label) graphics::text(coord.ind[, axes], labels = rownames(coord.ind), pos = 3, col = as.character(col.plot.ind), cex = cex,...) } if (!is.null(partial)) { select.partial <- which(rownames(coord.ind[select.ind,,drop=FALSE]) %in% partial) if (length(select.partial)==0) stop("\"lim.cos.plot\" (or \"lim.contrib.plot\") is too large. No partial individuals can be plotted",call. = FALSE) coord.ind.part <- coord.ind[select.partial, , drop=FALSE] xmin <- min(xlim,coord.ind[, dim1]) xmax <- max(xlim,coord.ind[, dim1]) ymin <- min(ylim,coord.ind[, dim2]) ymax <- max(ylim,coord.ind[, dim2]) for (i in 1:ngroup) { t <- x$ind.partial[[i]][select.partial,axes,drop=FALSE] xmin <- min(xmin, t[,1]) xmax <- max(xmax, t[,1]) ymin <- min(ymin,t[,2]) ymax <- max(ymax, t[,2]) } xlim <- c(xmin, xmax) * 1.2 ylim <- c(ymin, ymax) * 1.2 col.plot.ind <- rep("black",nrow(coord.ind)) graphics::plot(as.matrix(coord.ind[,axes]), xlim = xlim, ylim = ylim, xlab = lab.x, ylab = lab.y, pch = 20, cex = cex,main=main,...) graphics::abline(h = 0, lty = 2, cex = cex) graphics::abline(v = 0, lty = 2, cex = cex) if (label) graphics::text(coord.ind.part[, axes,drop=FALSE], labels = rownames(coord.ind.part), pos = 3, col = as.character(col.plot.ind), cex = cex) for (i in 1:ngroup) { t <- x$ind.partial[[i]][select.partial,axes,drop=FALSE] graphics::points(t,col=col.groups[i],pch=20,...) for (j in 1:length(select.partial)) { m <- list(x=c(coord.ind.part[j,dim1],t[j,1]), y=c(coord.ind.part[j,dim2],t[j,2])) graphics::lines(m,col=col.groups[i]) } } if(leg==TRUE) graphics::legend(posleg, legend = name.groups, text.col = col.groups, cex = cex.leg) } } if (choice == "levels") { if (is.null(main)) main <- "Levels component map" xmin <- min(xlim,x$levels$coord[, dim1],x$levels.sup$coord[, dim1]) xmax <- max(xlim,x$levels$coord[, dim1],x$levels.sup$coord[, dim1]) xlim <- c(xmin, xmax) * 1.2 ymin <- min(ylim,x$levels$coord[, dim2],x$levels.sup$coord[, dim2]) ymax <- max(ylim,x$levels$coord[, dim2],x$levels.sup$coord[, dim2]) ylim <- c(ymin, ymax) * 1.2 graphics::plot(0,0, xlim = xlim, ylim = ylim, xlab = lab.x, ylab = lab.y, type="n", cex = cex,main=main, ...) graphics::abline(h = 0, lty = 2, cex = cex) graphics::abline(v = 0, lty = 2, cex = cex) if (!is.null(x$levels)) { if (lim.cos2.plot == 0 & lim.contrib.plot==0) { lim.plot<-0 base.lim<-x$levels$cos2[,axes] } if (lim.cos2.plot != 0) { lim.plot<-lim.cos2.plot base.lim<-x$levels$cos2[,axes] } if (lim.contrib.plot!=0) { lim.plot<-lim.contrib.plot base.lim<-x$levels$contrib[,axes] base.lim<-100*(base.lim/sum(eig.axes)) } coord.lev <- x$levels$coord[, axes, drop = FALSE] col.lev <- rep(1,p1+m) if (coloring.var == "groups") { for (i in 1:ngroup) col.lev[which(x$index.group2==i)] <- col.groups[i] } col.lev <- col.lev[(p1+1):(p1+m)] test.empty.plot<-c() for (v in 1:nrow(coord.lev)) { if (sum(base.lim[v, ], na.rm = TRUE) >= lim.plot && !is.na(sum(base.lim[v, ], na.rm = TRUE))) { test.empty.plot<-c(test.empty.plot,1) graphics::points(coord.lev[v, 1], coord.lev[v,2], col=col.lev[v], pch=20,cex = cex,...) if (label) { if (abs(coord.lev[v, 1]) > abs(coord.lev[v,2])) { if (coord.lev[v, 1] >= 0) pos <- 4 else pos <- 2 } else { if (coord.lev[v, 2] >= 0) pos <- 3 else pos <- 1 } graphics::text(coord.lev[v, 1], y = coord.lev[v, 2], col=col.lev[v], labels = rownames(coord.lev)[v], pos = pos, cex = cex) } } } if (is.null(test.empty.plot)) warning("\"lim.cos.plot\" (or \"lim.contrib.plot\") is too large. No level can be plotted") if ((coloring.var == "groups") & (leg==TRUE)) graphics::legend(posleg, legend = name.groups[unique(x$index.group2[(p1+1):(p1+m)])], text.col = unique(col.lev), cex = cex.leg) } if (!is.null(x$levels.sup)) { coord.lev.sup <- x$levels.sup$coord[, axes, drop = FALSE] m.sup <- nrow(coord.lev.sup) col.lev.sup <- rep(4,p1.sup+m.sup) if (coloring.var == "groups") { for (i in 1:ngroupsup) col.lev.sup[which(x$index.groupsup2==i)] <- col.groups.sup[i] } col.lev.sup <- col.lev.sup[(p1.sup+1):(p1.sup+m.sup)] for (v in 1:nrow(coord.lev.sup)) { graphics::points(coord.lev.sup[v, 1], coord.lev.sup[v,2], pch=1,cex = cex, col=col.lev.sup[v],...) if (label) { if (abs(coord.lev.sup[v, 1]) > abs(coord.lev.sup[v,2])) { if (coord.lev.sup[v, 1] >= 0) pos <- 4 else pos <- 2 } else { if (coord.lev.sup[v, 2] >= 0) pos <- 3 else pos <- 1 } graphics::text(coord.lev.sup[v, 1], y = coord.lev.sup[v, 2], labels = rownames(coord.lev.sup)[v], pos = pos, col=col.lev.sup[v], cex = cex) } } if ((coloring.var == "groups") & (leg==TRUE)) graphics::legend(posleg.sup, legend = name.groups[unique(x$index.groupsup2[(p1+1):(p1+m)])], text.col = unique(col.lev.sup), cex = cex.leg) } } }
gd_url = function() { return("http://api.glassdoor.com/api/api.htm") }
context("knitr") test_that("include_graphics() can create HTML tag for file it can't find", { expect_silent( result <- knitr::include_graphics("docs/assets/external.png", error = FALSE) ) expect_identical(as.character(result), "docs/assets/external.png") })
heckit5fit <- function(selection, outcome1, outcome2, data=sys.frame(sys.parent()), ys=FALSE, yo=FALSE, xs=FALSE, xo=FALSE, mfs=FALSE, mfo=FALSE, printLevel=print.level, print.level=0, maxMethod="Newton-Raphson", ... ) { checkIMRcollinearity <- function(X, tol=1e6) { X <- X[!apply(X, 1, function(row) any(is.na(row))),] if(kappa(X) < tol) return(FALSE) if(kappa(X[,-ncol(X)]) > tol) return(FALSE) return(TRUE) } if( class( selection ) != "formula" ) { stop( "argument 'selection' must be a formula" ) } if( length( selection ) != 3 ) { stop( "argument 'selection' must be a 2-sided formula" ) } thisCall <- match.call() mf <- match.call(expand.dots = FALSE) m <- match(c("selection", "data", "subset"), names(mf), 0) mfS <- mf[c(1, m)] mfS$drop.unused.levels <- TRUE mfS$na.action <- na.pass mfS[[1]] <- as.name("model.frame") names(mfS)[2] <- "formula" mfS <- eval(mfS, parent.frame()) mtS <- attr(mfS, "terms") XS <- model.matrix(mtS, mfS) YS <- model.response( mfS ) YSLevels <- levels( as.factor( YS ) ) if( length( YSLevels ) != 2 ) { stop( "the dependent variable of 'selection' has to contain", " exactly two levels (e.g. FALSE and TRUE)" ) } ysNames <- names( YS ) YS <- as.integer(YS == YSLevels[ 2 ]) names( YS ) <- ysNames badRow <- is.na(YS) badRow <- badRow | apply(XS, 1, function(v) any(is.na(v))) if("formula" %in% class( outcome1 )) { if( length( outcome1 ) != 3 ) { stop( "argument 'outcome1' must be a 2-sided formula" ) } m <- match(c("outcome1", "data", "subset"), names(mf), 0) mf1 <- mf[c(1, m)] mf1$drop.unused.levels <- TRUE mf1$na.action <- na.pass mf1[[1]] <- as.name("model.frame") names(mf1)[2] <- "formula" mf1 <- eval(mf1, parent.frame()) mt1 <- attr(mf1, "terms") XO1 <- model.matrix(mt1, mf1) YO1 <- model.response(mf1, "numeric") badRow <- badRow | (is.na(YO1) & (!is.na(YS) & YS == 0)) badRow <- badRow | (apply(XO1, 1, function(v) any(is.na(v))) & (!is.na(YS) & YS == 0)) if("formula" %in% class( outcome2 )) { if( length( outcome2 ) != 3 ) { stop( "argument 'outcome2' must be a 2-sided formula" ) } m <- match(c("outcome2", "data", "subset"), names(mf), 0) mf2 <- mf[c(1, m)] mf2$drop.unused.levels <- TRUE mf2$na.action <- na.pass mf2[[1]] <- as.name("model.frame") names(mf2)[2] <- "formula" mf2 <- eval(mf2, parent.frame()) mt2 <- attr(mf2, "terms") XO2 <- model.matrix(mt2, mf2) YO2 <- model.response(mf2, "numeric") badRow <- badRow | (is.na(YO2) & (!is.na(YS) & YS == 1)) badRow <- badRow | (apply(XO2, 1, function(v) any(is.na(v))) & (!is.na(YS) & YS == 1)) } else stop("argument 'outcome2' must be a formula") } else if("list" %in% class(outcome1)) { if(length(outcome1) != 2) { stop("argument 'outcome1' must be either a formula or a list of two formulas") } if("formula" %in% class(outcome1[[1]])) { if( length( outcome1[[1]] ) != 3 ) { stop( "argument 'outcome1[[1]]' must be a 2-sided formula" ) } } else stop( "argument 'outcome1[[1]]' must be a formula" ) if("formula" %in% class(outcome1[[2]])) { if( length( outcome1[[2]] ) != 3 ) { stop( "argument 'outcome[[2]]' must be a 2-sided formula" ) } formula1 <- outcome1[[1]] formula2 <- outcome1[[2]] m <- match(c("outcome1", "data", "subset", "offset"), names(mf), 0) oArg <- match("outcome1", names(mf), 0) mf[[oArg]] <- formula1 mf1 <- mf[c(1, m)] mf1$drop.unused.levels <- TRUE mf1$na.action = na.pass mf1[[1]] <- as.name("model.frame") names(mf1)[2] <- "formula" mf1 <- eval(mf1, parent.frame()) mt1 <- attr(mf1, "terms") XO1 <- model.matrix(mt1, mf1) YO1 <- model.response(mf1, "numeric") badRow <- badRow | (is.na(YO1) & (!is.na(YS) & YS == 0)) badRow <- badRow | (apply(XO1, 1, function(v) any(is.na(v))) & (!is.na(YS) & YS == 0)) mf[[oArg]] <- formula2 mf2 <- mf[c(1, m)] mf2$drop.unused.levels <- TRUE mf2$na.action <- na.pass mf2[[1]] <- as.name("model.frame") names(mf2)[2] <- "formula" mf2 <- eval(mf2, parent.frame()) mt2 <- attr(mf2, "terms") XO2 <- model.matrix(mt2, mf2) YO2 <- model.response(mf2, "numeric") badRow <- badRow | (is.na(YO2) & (!is.na(YS) & YS == 1)) badRow <- badRow | (apply(XO2, 1, function(v) any(is.na(v))) & (!is.na(YS) & YS == 1)) } else stop( "argument 'outcome[[2]]' must be a formula" ) } else stop("argument 'outcome1' must be a formula or a list of two formulas") NXS <- ncol(XS) NXO1 <- ncol(XO1) NXO2 <- ncol(XO2) XS <- XS[!badRow,,drop=FALSE] YS <- YS[!badRow] XO1 <- XO1[!badRow,,drop=FALSE] YO1 <- YO1[!badRow] XO2 <- XO2[!badRow,,drop=FALSE] YO2 <- YO2[!badRow] nObs <- length(YS) i1 <- YS == 0 i2 <- YS == 1 XS1 <- XS[i1,,drop=FALSE] XS2 <- XS[i2,,drop=FALSE] XO1 <- XO1[i1,,drop=FALSE] XO2 <- XO2[i2,,drop=FALSE] YO1 <- YO1[i1] YO2 <- YO2[i2] N1 <- length(YO1) N2 <- length(YO2) probitResult <- probit(YS ~ XS - 1, maxMethod = maxMethod ) if( print.level > 0) { cat("The probit part of the model:\n") print(summary(probitResult)) } gamma <- coef(probitResult) invMillsRatio1 <- dnorm( -XS1%*%gamma)/pnorm( -XS1%*%gamma) invMillsRatio2 <- dnorm( XS2%*%gamma)/pnorm( XS2%*%gamma) colnames(invMillsRatio1) <- colnames(invMillsRatio2) <- "invMillsRatio" XO1 <- cbind(XO1, invMillsRatio1) XO2 <- cbind(XO2, invMillsRatio2) if(checkIMRcollinearity(XO1)) { warning("Inverse Mills Ratio is virtually multicollinear to the rest of explanatory variables in the outcome equation 1") } if(checkIMRcollinearity(XO2)) { warning("Inverse Mills Ratio is virtually multicollinear to the rest of explanatory variables in the outcome equation 2") } lm1 <- lm(YO1 ~ -1 + XO1) lm2 <- lm(YO2 ~ -1 + XO2) intercept1 <- any(apply(model.matrix(lm1), 2, function(v) (v[1] > 0) & (all(v == v[1])))) intercept2 <- any(apply(model.matrix(lm2), 2, function(v) (v[1] > 0) & (all(v == v[1])))) se1 <- summary(lm1)$sigma se2 <- summary(lm2)$sigma delta1 <- mean( invMillsRatio1^2 - XS1%*%gamma *invMillsRatio1) delta2 <- mean( invMillsRatio2^2 + XS2%*%gamma *invMillsRatio2) betaL1 <- coef(lm1)["XO1invMillsRatio"] betaL2 <- coef(lm2)["XO2invMillsRatio"] sigma1 <- sqrt( se1^2 + ( betaL1*delta1)^2) sigma2 <- sqrt( se2^2 + ( betaL2*delta2)^2) rho1 <- -betaL1/sigma1 rho2 <- betaL2/sigma2 if( rho1 <= -1) rho1 <- -0.99 if( rho2 <= -1) rho2 <- -0.99 if( rho1 >= 1) rho1 <- 0.99 if( rho2 >= 1) rho2 <- 0.99 iBetaS <- 1:NXS iBetaO1 <- seq(tail(iBetaS, 1)+1, length=NXO1) iMills1 <- tail(iBetaO1, 1) + 1 iSigma1 <- iMills1 + 1 iRho1 <- tail(iSigma1, 1) + 1 iBetaO2 <- seq(tail(iRho1, 1) + 1, length=NXO2) iMills2 <- tail(iBetaO2, 1) + 1 iSigma2 <- iMills2 + 1 iRho2 <- tail(iSigma2, 1) + 1 nParam <- iRho2 coefficients <- numeric(nParam) coefficients[iBetaS] <- coef(probitResult) names(coefficients)[iBetaS] <- gsub("^XS", "", names(coef(probitResult))) coefficients[iBetaO1] <- coef(lm1)[names(coef(lm1)) != "XO1invMillsRatio"] names(coefficients)[iBetaO1] <- gsub("^XO1", "", names(coef(lm1))[names(coef(lm1)) != "XO1invMillsRatio"]) coefficients[iBetaO2] <- coef(lm2)[names(coef(lm2)) != "XO2invMillsRatio"] names(coefficients)[iBetaO2] <- gsub("^XO2", "", names(coef(lm2))[names(coef(lm2)) != "XO2invMillsRatio"]) coefficients[c(iMills1, iSigma1, iRho1, iMills2, iSigma2, iRho2)] <- c(coef(lm1)["XO1invMillsRatio"], sigma1, rho1, coef(lm2)["XO2invMillsRatio"], sigma2, rho2) names(coefficients)[c(iMills1, iSigma1, iRho1, iMills2, iSigma2, iRho2)] <- c("invMillsRatio1", "sigma1", "rho1", "invMillsRatio2", "sigma2", "rho2") vc <- matrix(0, nParam, nParam) colnames(vc) <- row.names(vc) <- names(coefficients) vc[] <- NA if(!is.null(vcov(probitResult))) vc[iBetaS,iBetaS] <- vcov(probitResult) param <- list(index=list(betaS=iBetaS, betaO1=iBetaO1, betaO2=iBetaO2, Mills1=iMills1, sigma1=iSigma1, rho1=iRho1, Mills2=iMills2, sigma2=iSigma2, rho2=iRho2, errTerms = c( iMills1, iMills2, iSigma1, iSigma2, iRho1, iRho2 ), outcome = c( iBetaO1, iMills1, iBetaO2, iMills2 ) ), oIntercept1=intercept1, oIntercept2=intercept2, nObs=nObs, nParam=nParam, df=nObs-nParam + 2, NXS=NXS, NXO1=NXO1, NXO2=NXO2, N1=N1, N2=N2, levels=YSLevels ) result <- list(probit=probitResult, lm1=lm1, rho1=rho1, sigma1=sigma1, lm2=lm2, rho2=rho2, sigma2=sigma2, call = thisCall, termsS=mtS, termsO=list(mt1, mt2), ys=switch(as.character(ys), "TRUE"=YS, "FALSE"=NULL), xs=switch(as.character(xs), "TRUE"=XS, "FALSE"=NULL), yo=switch(as.character(yo), "TRUE"=list(YO1, YO2), "FALSE"=NULL), xo=switch(as.character(xo), "TRUE"=list(XO1, XO2), "FALSE"=NULL), mfs=switch(as.character(mfs), "TRUE"=list(mfS), "FALSE"=NULL), mfo=switch(as.character(mfs), "TRUE"=list(mf1, mf2), "FALSE"=NULL), param=param, coefficients=coefficients, vcov=vc ) result$tobitType <- 5 result$method <- "2step" class( result ) <- c( "selection", class(result)) return( result ) }
setGeneric("plot")
plotresprm <- function (prmdcvobj, optcomp, y, X, ...) { prm.cv <- prm_cv(X,y, a = optcomp, plot.opt=FALSE, ...) par(mfrow = c(1, 2)) predcv <- prm.cv$predicted[, optcomp] preddcvall <- prmdcvobj$pred[,optcomp, ] preddcv <- apply(preddcvall, 1, mean) ylimits <- max(abs(preddcvall - drop(y))) ylimits <- sort(c(-ylimits, ylimits)) plot(predcv, predcv - y, xlab = "Predicted y", ylab = "Residuals", cex.lab = 1.2, cex = 0.7, pch = 3, col = 1, ylim = ylimits, ...) title("Results from CV") abline(h = 0, lty = 1) plot(preddcv, preddcv - y, xlab = "Predicted y", ylab = "Residuals", cex.lab = 1.2, cex = 0.7, pch = 3, col = gray(0.6), type = "n", ylim = ylimits, ...) for (i in 1:ncol(preddcvall)) { points(preddcv, preddcvall[, i] - y, cex = 0.7, pch = 3, col = gray(0.6)) } points(preddcv, preddcv - y, cex = 0.7, pch = 3, col = 1) title("Results from Repeated Double-CV") abline(h = 0, lty = 1) invisible() }
library(tourr) library(plotly) mat <- rescale(as.matrix(flea[1:6])) tour <- new_tour(mat, grand_tour(), NULL) tour_dat <- function(step_size) { step <- tour(step_size) proj <- center(mat %*% step$proj) data.frame(x = proj[,1], y = proj[,2], species = flea$species) } proj_dat <- function(step_size) { step <- tour(step_size) data.frame( x = step$proj[,1], y = step$proj[,2], measure = colnames(mat) ) } steps <- c(0, rep(1/15, 50)) stepz <- cumsum(steps) tour_dats <- lapply(steps, tour_dat) tour_datz <- Map(function(x, y) cbind(x, step = y), tour_dats, stepz) tour_dat <- dplyr::bind_rows(tour_datz) proj_dats <- lapply(steps, proj_dat) proj_datz <- Map(function(x, y) cbind(x, step = y), proj_dats, stepz) proj_dat <- dplyr::bind_rows(proj_datz) ax <- list( title = "", range = c(-1, 1), zeroline = FALSE ) options(digits = 2) proj_dat %>% plot_ly(x = ~x, y = ~y, frame = ~step, color = I("gray80")) %>% add_segments(xend = 0, yend = 0) %>% add_text(text = ~measure) %>% add_markers(color = ~species, data = tour_dat) %>% hide_legend() %>% layout(xaxis = ax, yaxis = ax) %>% animation_opts(33, redraw = FALSE)
logLik.srm <- function (object, ...) { out <- object$loglike attr(out, "df") <- length(object$coef) attr(out, "nobs") <- NA class(out) <- "logLik" return(out) }
if(exists("mission_time")) rm(mission_time) rv_test<-c(3,3,3,2,1,2,1) pi_test<-c(3,1,1/12,1/12,1/12,1/52,1/52) walkby<-c(3,1/12,1/52,1/52,1/52,1/52,1/52) cases<-cbind(rv_test,pi_test,walkby) mttf<-NULL CFRat14<-NULL for(case in 1:dim(cases)[1]) { rv_test<-cases[case,1] pi_test<-cases[case,2] walkby<-cases[case,3] hf<-ftree.make(type="or", name="HF Vaporizer", name2="Rupture") hf<-addLogic(hf, at=1, type="inhibit", name="Overpressure", name2="Unrelieved") hf<-addDemand(hf, at=1, mttf=1e6, name= "Vaporizer Rupture", name2="Due to Stress/Fatigue") hf<-addLogic(hf, at=2, type="or", name="Pressure Relief System", name2="in Failed State") hf<-addLogic(hf, at=2, type="or", name="Overpressure", name2="Occurs") hf<-addLogic(hf, at=4, type="or", name="Pressure Relief", name2="Isolated") hf<-addLatent(hf, at=6, mttf=10, inspect=walkby, name="Valve 20", name2="Left Closed") hf<-addLatent(hf, at=6, mttf=10, inspect=walkby, display_under=7, name="Valve 21", name2="Left Closed") hf<-addLogic(hf, at=4, type="or", name="Rupture Disk Fails", name2="to Open at Design Pt.") hf<-addLogic(hf, at=9, type="or", name="Installation/Mfr", name2="Errors") hf<-addProbability(hf, at=10, prob=.001, name="Rupture Disk", name2="Installed Upside Down") hf<-addProbability(hf, at=10, prob=.001, display_under=11, name="Wrong Rupture Disk", name2="Installed") hf<-addProbability(hf, at=10, prob=.001, display_under=12, name="Rupture Disk", name2="Manuf. Error") hf<-addLogic(hf, at=9, type="or", name="Pressure Between Disk", name2="and Relief Valve") hf<-addLogic(hf, at=14, type="inhibit", name="Pressure NOT" , name2="Detectable by PI") hf<-addLatent(hf, at=15, mttf=10, inspect=pi_test, name="Pressure Gage", name2="Failed Low Position") hf<-addLatent(hf, at=15, mttf=10, inspect=pi_test, name="Rupture Disk Leak", name2="Undetected") hf<-addLogic(hf, at=14, type="inhibit", name="Pressure" , name2="Detectable by PI") hf<-addProbability(hf, at=18, prob=(1-hf$PBF[16]), name="Pressure Gage", name2="Detects Pressure") hf<-addLatent(hf, at=18, mttf=10, inspect=walkby, name="Rupture Disk Leak", name2="Detectable") hf<-addLogic(hf, at=4, type="or", name="Pressure Relief Fails", name2=" to Open at Design Pt") hf<-addLatent(hf, at=21, mttf=300, inspect=rv_test, name="Pressure Relief", name2="set too high") hf<-addLatent(hf, at=21, mttf=300, inspect=rv_test, name="Pressure Relief Unable", name2="to Open at Design Pt") hf<-addDemand(hf, at=5, mttf=10, name= "High Pressure", name2="Feed to Vaporizer") hf<-addDemand(hf, at=5, mttf=10, name= "Vaporizer Heating", name2="Runaway") hf<-ftree.calc(hf) mttf<-c(mttf,1/ hf$CFR[1]) CFRat14<-c(CFRat14, hf$CFR[14]) } cases<-cbind(cases, mttf, CFRat14) print(cases)
add_CPUE <- function(ctl.in, ctl.out = NULL, overwrite = FALSE, q = data.frame( "fleet" = 3, "link" = 1, "link_info" = 0, "extra_se" = 0, "biasadj" = 0, "float" = 0, "LO" = -20, "HI" = 20, "INIT" = 0, "PRIOR" = 0, "PR_SD" = 99, "PR_type" = 0, "PHASE" = 1, "env_var" = 0, "use_dev" = 0, "dev_mnyr" = 0, "dev_mxyr" = 0, "dev_PH" = 0, "Block" = 0, "Blk_Fxn" = 0, "name" = NULL)) { ctl <- readLines(ctl.in) startline <- findspot("Q_setup", ctl, gopast = " if (is.null(q[, "name"])) q[, "name"] <- paste0(" if (substr(trimws(q[, "name"]), 1, 1) != " Q_setup <- apply(q[, c("fleet", "link", "link_info", "extra_se", "biasadj", "float", "name")], 1, paste, collapse = " ") ctl <- append(x = ctl, values = Q_setup, after = startline) endline <- findspot("Q_parms", ctl, goto = " Q_parms <- apply(q[, c("LO", "HI", "INIT", "PRIOR", "PR_SD", "PR_type", "PHASE", "env_var", "use_dev", "dev_mnyr", "dev_mxyr", "dev_PH", "Block", "Blk_Fxn", "name")], 1, paste, collapse = " ") ctl <- append(x = ctl, values = Q_parms, after = endline - 1) if (!is.null(ctl.out)) { write <- TRUE if (file.exists(ctl.out) & !overwrite) write <- FALSE if (write) writeLines(text = ctl, con = ctl.out) } invisible(ctl) } findspot <- function(string, lines, gopast = NULL, goto = NULL) { searchfor <- NULL if (!is.null(gopast)) searchfor <- gopast if (!is.null(goto)) { searchfor <- paste(sapply(strsplit(goto, "")[[1]], function(x) paste0("[^", x, "]")), collapse = "") } if (is.null(searchfor)) stop("gopast or goto must be specified.") loc <- grep(string, lines) while(grepl(searchfor, substring(trimws(lines[loc]), 1, nchar(searchfor)))) { loc <- loc + 1 } if (!is.null(goto)) loc <- loc - 1 return(loc) } remove_CPUE <- function(string, ctl.in, ctl.out, dat.in, dat.out, overwrite = FALSE) { ctl <- readLines(ctl.in) line <- findspot("Q_setup", ctl, gopast = " while(!grepl(string, ctl[line])) line <- line + 1 ctl <- ctl[-line] line <- findspot("Q_parms", ctl, gopast = " while(!grepl(string, ctl[line])) line <- line + 1 ctl <- ctl[-line] if (!is.null(ctl.out)) { write <- TRUE if (file.exists(ctl.out) & !overwrite) write <- FALSE if (write) writeLines(text = ctl, con = ctl.out) } dat <- r4ss::SS_readdat(dat.in, verbose = FALSE) fleetnum <- grep(string, dat$fleetnames) dat$CPUE <- dat$CPUE[dat$CPUE$index != fleetnum, ] SS_writedat(dat, dat.out, verbose = FALSE, overwrite = overwrite) } remove_q_ctl <- function(string, ctl.in, filename = TRUE, ctl.out, overwrite = FALSE) { if(filename == TRUE) { ctl <- readLines(ctl.in) } else { ctl <- ctl.in } line <- findspot("Q_setup", ctl, gopast = " while(!grepl(string, ctl[line])) line <- line + 1 ctl <- ctl[-line] line <- findspot("Q_parms", ctl, gopast = " while(!grepl(string, ctl[line])) line <- line + 1 ctl <- ctl[-line] if (!is.null(ctl.out)) { write <- TRUE if (file.exists(ctl.out) & !overwrite) write <- FALSE if (write) writeLines(text = ctl, con = ctl.out) } invisible(ctl) }
label <- function(x, default=NULL, ...) UseMethod("label") label.default <- function(x, default=NULL, units=plot, plot=FALSE, grid=FALSE, html=FALSE, ...) { if(length(default) > 1) stop("the default string cannot be of length greater then one") at <- attributes(x) lab <- at[['label']] if(length(default) && (!length(lab) || lab=='')) lab <- default un <- at$units labelPlotmath(lab, if(units) un else NULL, plotmath=plot, grid=grid, html=html) } label.Surv <- function(x, default=NULL, units=plot, plot=FALSE, grid=FALSE, html=FALSE, type=c('any', 'time', 'event'), ...) { type <- match.arg(type) if(length(default) > 1) stop("the default string cannot be of length greater then one") at <- attributes(x) lab <- at[['label']] ia <- at$inputAttributes if((! length(lab) || lab == '') && length(ia)) { poss <- switch(type, any = c(ia$event$label, ia$time2$label, ia$time$label), time = c( ia$time2$label, ia$time$label), event = ia$event$label ) for(lb in poss) if(! length(lab) && lb != '') lab <- lb } if(length(default) && (!length(lab) || lab=='')) lab <- default un <- NULL if(units) { un <- at$units if(! length(un) && length(ia)) { un <- ia$time2$units if(! length(un)) un <- ia$time$units } } labelPlotmath(lab, un, plotmath=plot, grid=grid, html=html) } label.data.frame <- function(x, default=NULL, self=FALSE, ...) { if(self) { label.default(x) } else { if(length(default) > 0 && length(default) != length(x)) { stop('length of default must same as x') } else if(length(default) == 0) { default <- list(default) } labels <- mapply(FUN=label, x=x, default=default, MoreArgs=list(self=TRUE), USE.NAMES=FALSE) names(labels) <- names(x) return(labels) } } labelPlotmath <- function(label, units=NULL, plotmath=TRUE, html=FALSE, grid=FALSE, chexpr=FALSE) { if(! length(label)) label <- '' if(! length(units) || (length(units) == 1 && is.na(units))) units <- '' if(html) return(markupSpecs$html$varlabel (label, units)) if(! plotmath) return(markupSpecs$plain$varlabel(label, units)) g <- function(x, y=NULL, xstyle=NULL, ystyle=NULL) { h <- function(w, style=NULL) if(length(style)) sprintf('%s(%s)', style, w) else w tryparse <- function(z, original, chexpr) { p <- try(parse(text=z), silent=TRUE) if(is.character(p)) original else if(chexpr) sprintf('expression(%s)', z) else p } if(! length(y)) return(tryparse(h(plotmathTranslate(x), xstyle), x, chexpr)) w <- paste('list(',h(plotmathTranslate(x), xstyle), ',', h(plotmathTranslate(y), ystyle), ')', sep='') tryparse(w, paste(x, y), chexpr) } if(units=='') g(label) else if(label=='') g(units) else g(label, units, ystyle='scriptstyle') } plotmathTranslate <- function(x) { if(length(grep('paste', x))) return(x) specials <- c(' ','%','_') spec <- FALSE for(s in specials) if(length(grep(s,x))) spec <- TRUE if(! spec && is.character(try(parse(text=x), silent=TRUE))) spec <- TRUE if(spec) x <- paste('paste("',x,'")',sep='') else if(substring(x,1,1)=='/') x <- paste('phantom()', x, sep='') x } labelLatex <- function(x=NULL, label='', units='', size='smaller[2]', hfill=FALSE, bold=FALSE, default='', double=FALSE) { if(length(x)) { if(label == '') label <- label(x) if(units == '') units <- units(x) } if(default == '' && length(x)) default <- deparse(substitute(x)) if(label == '') return(default) label <- latexTranslate(label) bs <- if(double) '\\\\' else '\\' if(bold) label <- paste('{', bs, 'textbf ', label, '}', sep='') if(units != '') { units <- latexTranslate(units) if(length(size) && size != '') units <- paste('{', bs, size, ' ', units, '}', sep='') if(hfill) units <- paste(bs, 'hfill ', units, sep='') else units <- paste(' ', units, sep='') label <- paste(label, units, sep='') } label } "label<-" <- function(x, ..., value) UseMethod("label<-") "label<-.default" <- function(x, ..., value) { if(is.list(value)) { stop("cannot assign a list to be a object label") } if(length(value) != 1L) { stop("value must be character vector of length 1") } attr(x, 'label') <- value if('labelled' %nin% class(x)) { class(x) <- c('labelled', class(x)) } return(x) } "label<-.data.frame" <- function(x, self=TRUE, ..., value) { if(!is.data.frame(x)) { stop("x must be a data.frame") } if(missing(self) && is.list(value)) { self <- FALSE } if(self) { xc <- class(x) xx <- unclass(x) label(xx) <- value class(xx) <- xc return(xx) } else { if(length(value) != length(x)) { stop("value must have the same length as x") } for (i in seq(along.with=x)) { label(x[[i]]) <- value[[i]] } } return(x) } "[.labelled"<- function(x, ...) { tags <- valueTags(x) x <- NextMethod("[") valueTags(x) <- tags x } "print.labelled"<- function(x, ...) { x.orig <- x u <- attr(x, 'units', exact=TRUE) if(length(u)) attr(x,'units') <- NULL cat(attr(x, "label", exact=TRUE), if(length(u)) paste('[', u, ']', sep=''), "\n") attr(x, "label") <- NULL class(x) <- if(length(class(x))==1 && class(x)=='labelled') NULL else class(x)[class(x) != 'labelled'] if(!length(attr(x,'class'))) attr(x,'class') <- NULL NextMethod("print") invisible(x.orig) } as.data.frame.labelled <- as.data.frame.vector Label <- function(object, ...) UseMethod("Label") Label.data.frame <- function(object, file='', append=FALSE, ...) { nn <- names(object) for(i in 1:length(nn)) { lab <- attr(object[[nn[i]]], 'label', exact=TRUE) lab <- if(length(lab)==0) '' else lab cat("label(",nn[i],")\t<- '",lab,"'\n", append=if(i==1) append else TRUE, file=file, sep='') } invisible() } relevel.labelled <- function(x, ...) { lab <- label(x) x <- NextMethod(x) label(x) <- lab x } reLabelled <- function(object) { for(i in 1:length(object)) { x <- object[[i]] lab <- attr(x, 'label', exact=TRUE) cl <- class(x) if(length(lab) && !any(cl=='labelled')) { class(x) <- c('labelled',cl) object[[i]] <- x } } object } llist <- function(..., labels=TRUE) { dotlist <- list(...) lname <- names(dotlist) name <- vname <- as.character(sys.call())[-1] for(i in 1:length(dotlist)) { vname[i] <- if(length(lname) && lname[i]!='') lname[i] else name[i] lab <- vname[i] if(labels) { lab <- attr(dotlist[[i]],'label', exact=TRUE) if(length(lab) == 0) lab <- vname[i] } label(dotlist[[i]]) <- lab } names(dotlist) <- vname[1:length(dotlist)] dotlist } prList <- function(x, lcap=NULL, htmlfig=0, after=FALSE) { if(! length(names(x))) stop('x must have names') if(length(lcap) && (length(lcap) != length(x))) stop('if given, lcap must have same length as x') mu <- markupSpecs$html g <- if(htmlfig == 0) function(x, X=NULL) paste(x, X) else if(htmlfig == 1) function(x, X=NULL) paste(mu$cap(x), mu$lcap(X)) else function(x, X=NULL) paste0('\n if(length(X) && X != '') paste0('\n', mu$lcap(X))) i <- 0 for(n in names(x)) { i <- i + 1 y <- x[[n]] if(length(names(y)) && length(class(y)) == 1 && class(y) == 'list' && length(y) > 1) { for(m in names(y)) { if(! after) cat('\n', g(paste0(n, ': ', m)), '\n', sep='') suppressWarnings(print(y[[m]])) if(after) cat('\n', g(paste0(n, ': ', m)), '\n', sep='') } if(length(lcap) && lcap[i] != '') cat(mu$lcap(lcap[i])) } else { if(! after) cat('\n', g(n, if(length(lcap)) lcap[i]), '\n', sep='') suppressWarnings(print(x[[n]])) if(after) cat('\n', g(n, if(length(lcap)) lcap[i]), '\n', sep='') } } invisible() } putHfig <- function(x, ..., scap=NULL, extra=NULL, subsub=TRUE, hr=TRUE, table=FALSE, file='', append=FALSE, expcoll=NULL) { ec <- length(expcoll) > 0 if(ec && ! table) stop('expcoll can only be specified for tables, not figures') mu <- markupSpecs$html lcap <- unlist(list(...)) if(length(lcap)) lcap <- paste(lcap, collapse=' ') if(ec && length(lcap)) stop('does not work when lcap is specified because of interaction with markdown sub-subheadings') if(! length(lcap) && ! length(scap)) { if(ec) { if(hr) x <- c(mu$hrule, x) x <- mu$expcoll(paste(expcoll, collapse=' '), paste(x, collapse='\n')) cat(x, file=file, append=append, sep='\n') return(invisible()) } if(hr) cat(mu$hrule, '\n', sep='', file=file, append=append) if(table) cat(x, file=file, append=append || hr, sep='\n') else suppressWarnings(print(x)) return(invisible()) } if(! length(scap)) { scap <- lcap lcap <- NULL } scap <- if(table) mu$tcap(scap) else mu$cap(scap) if(subsub) scap <- paste0('\n if(hr && ! ec) cat(mu$hrule, '\n', sep='', file=file, append=append) if(! ec) cat(scap, '\n', sep='', file=file, append=append | hr) if(length(lcap)) { lcap <- if(table) mu$ltcap(lcap) else mu$lcap(lcap) if(length(extra)) lcap <- paste0( '<TABLE width="100%" BORDER="0" CELLPADDING="3" CELLSPACING="3">', '<TR><TD>', lcap, '</TD>', paste(paste0('<TD style="text-align:right;padding: 0 1ex 0 1ex;">', extra, '</TD>'), collapse=''), '</TR></TABLE>') if(ec) x <- c(lcap, x) else cat(lcap, '\n', sep='', file=file, append=TRUE) } if(ec) x <- mu$expcoll(paste(expcoll, collapse=' '), paste(c(if(hr) mu$hrule, scap, x), collapse='\n')) if(table) cat(x, sep='\n', file=file, append=TRUE) else suppressWarnings(print(x)) invisible() } putHcap <- function(..., scap=NULL, extra=NULL, subsub=TRUE, hr=TRUE, table=FALSE, file='', append=FALSE) { mu <- markupSpecs$html fcap <- if(table) mu$tcap else mu$cap flcap <- if(table) mu$ltcap else mu$lcap output <- function(r) if(is.logical(file)) return(r) else { cat(r, sep='\n', file=file, append=append) return(invisible()) } lcap <- unlist(list(...)) if(length(lcap)) lcap <- paste(lcap, collapse=' ') r <- NULL if(! length(lcap) && ! length(scap)) return('') if(! length(scap)) { scap <- lcap lcap <- NULL } scap <- fcap(scap) if(subsub) scap <- paste0('\n if(hr) r <- c(r, mu$hrule) r <- c(r, scap) if(length(lcap)) { lcap <- flcap(lcap) if(length(extra)) lcap <- paste0( '<TABLE width="100%" BORDER="0" CELLPADDING="3" CELLSPACING="3">', '<TR><TD>', lcap, '</TD>', paste(paste0('<TD style="text-align:right;padding: 0 1ex 0 1ex;">', extra, '</TD>'), collapse=''), '</TR></TABLE>') r <- c(r, lcap) } output(r) } combineLabels <- function(...) { w <- list(...) labs <- sapply(w[[1]], label) lw <- length(w) if(lw > 1) for(j in 2:lw) { lab <- sapply(w[[j]], label) lab <- lab[lab != ''] if(length(lab)) labs[names(lab)] <- lab } labs[labs != ''] }
require(geometa, quietly = TRUE) require(testthat) require(XML) context("GMLTimePeriod") test_that("encoding - with dates",{ testthat::skip_on_cran() start <- ISOdate(2000, 1, 12, 12, 59, 45) end <- ISOdate(2010, 8, 22, 13, 12, 43) expect_error(ISOTimePeriod$new(beginPosition = start, endPosition = end)) expect_error(GMLTimePeriod$new(beginPosition = end, endPosition = start)) md <- GMLTimePeriod$new(beginPosition = start, endPosition = end) xml <- md$encode() expect_is(xml, "XMLInternalNode") md2 <- GMLTimePeriod$new(xml = xml) xml2 <- md2$encode() expect_true(ISOAbstractObject$compare(md, md2)) }) test_that("encoding - with year+month",{ testthat::skip_on_cran() md <- GMLTimePeriod$new(beginPosition = "2000-01", endPosition = "2015-02") xml <- md$encode() expect_is(xml, "XMLInternalNode") md2 <- GMLTimePeriod$new(xml = xml) xml2 <- md2$encode() expect_true(ISOAbstractObject$compare(md, md2)) }) test_that("encoding - with years",{ testthat::skip_on_cran() md <- GMLTimePeriod$new(beginPosition = 2000, endPosition = 2010) xml <- md$encode() expect_is(xml, "XMLInternalNode") md2 <- GMLTimePeriod$new(xml = xml) xml2 <- md2$encode() expect_true(ISOAbstractObject$compare(md, md2)) })
context("map_data") test_that("lon & lat columns are found", { df <- mapdeck::capitals expect_true( mapdeck:::find_lon_column(names(df)) == "lon" ) expect_true( mapdeck:::find_lat_column(names(df)) == "lat" ) l <- mapdeck:::resolve_data( df, list(), "POINT" ) expect_true( l[["lon"]] == "lon" ) expect_true( l[["lat"]] == "lat" ) })
rm(list = ls()) if(FALSE){ library(testthat) library(lavaSearch2) } library(nlme) lava.options(symbols = c("~","~~")) context("Utils-nlme") n <- 5e1 mSim <- lvm(c(Y1~1*eta,Y2~1*eta,Y3~1*eta,Y4~1*eta,eta~G+Gender)) latent(mSim) <- ~eta categorical(mSim, labels = c("M","F")) <- ~Gender transform(mSim,Id~Y1) <- function(x){1:NROW(x)} set.seed(10) dW <- lava::sim(mSim,n,latent = FALSE) dW <- dW[order(dW$Id),,drop=FALSE] dL <- reshape2::melt(dW,id.vars = c("G","Id","Gender"), variable.name = "time") dL <- dL[order(dL$Id),,drop=FALSE] dL$time.num <- as.numeric(dL$time) test_that("invariant to the order in the dataset", { e1.gls <- gls(Y1 ~ Gender, data = dW[order(dW$Id),], weights = varIdent(form = ~1|Gender), method = "ML") out1 <- getVarCov2(e1.gls, cluster = dW$Id) index.cluster <- as.numeric(names(out1$index.Omega)) expect_true(all(diff(index.cluster)>0)) e2.gls <- gls(Y1 ~ Gender, data = dW[order(dW$Gender),], weights = varIdent(form = ~1|Gender), method = "ML") out2 <- getVarCov2(e2.gls, cluster = dW$Id) index.cluster <- as.numeric(names(out2$index.Omega)) expect_true(all(diff(index.cluster)>0)) }) e.gls <- nlme::gls(value ~ time + G + Gender, weights = varIdent(form =~ 1|time), data = dL, method = "ML") test_that("Heteroschedasticity", { vec.sigma <- c(1,coef(e.gls$modelStruct$varStruct, unconstrained = FALSE)) expect_equal(diag(vec.sigma^2 * sigma(e.gls)^2), unname(getVarCov2(e.gls, cluster = "Id")$Omega)) }) e.lme <- nlme::lme(value ~ time + G + Gender, random = ~ 1|Id, data = dL, method = "ML") e.lme.bis <- nlme::lme(value ~ time + G + Gender, random = ~ 1|Id, correlation = corCompSymm(), data = dL, method = "ML") e.gls <- nlme::gls(value ~ time + G + Gender, correlation = corCompSymm(form=~ 1|Id), data = dL, method = "ML") test_that("Compound symmetry", { expect_equal(unclass(getVarCov(e.gls)), unname(getVarCov2(e.gls)$Omega)) expect_equal(unname(getVarCov(e.lme, type = "marginal", individuals = 1)[[1]]), unname(getVarCov2(e.lme)$Omega)) expect_equal(unname(getVarCov(e.lme.bis, type = "marginal", individuals = 1)[[1]]), unname(getVarCov2(e.lme.bis)$Omega)) }) e.lme <- nlme::lme(value ~ time + G + Gender, random = ~ 1|Id, correlation = corSymm(form =~ time.num|Id), data = dL, method = "ML") e.gls <- nlme::gls(value ~ time + G + Gender, correlation = corSymm(form=~ time.num|Id), data = dL, method = "ML") test_that("Unstructured ", { expect_equal(unclass(getVarCov(e.gls)), unname(getVarCov2(e.gls)$Omega)) expect_equal(unname(getVarCov(e.lme, type = "marginal", individuals = 1)[[1]]), unname(getVarCov2(e.lme)$Omega)) }) e.lme <- nlme::lme(value ~ time + G + Gender, random = ~ 1|Id, correlation = corSymm(form =~ time.num|Id), weight = varIdent(form = ~ 1|time), data = dL, method = "ML") e.gls <- nlme::gls(value ~ time + G + Gender, correlation = corSymm(form =~ time.num|Id), weight = varIdent(form = ~ 1|time), data = dL, method = "ML") test_that("Unstructured with weights", { expect_equal(unclass(getVarCov(e.gls)), unname(getVarCov2(e.gls)$Omega)) expect_equal(unname(getVarCov(e.lme, type = "marginal", individuals = 1)[[1]]), unname(getVarCov2(e.lme)$Omega)) }) dfW <- data.frame("id" = c("1", "2", "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"), "group" = c("AC", "AB", "AB", "BC", "BC", "AC", "AB", "AC", "BC", "AC", "BC", "AB", "AB", "BC", "AB", "AC", "BC", "AC", "AC", "AC", "BC", "AB", "AB", "BC", "AB", "AB", "BC", "AC", "BC", "AC"), "vasaucA" = c( 51.0, 42.0, 54.0, NA, NA, 16.5, 58.5, 129.0, NA, 52.5, NA, 23.5, 98.0, NA, 177.0, 67.0, NA, 55.0, 79.5, 3.5, NA, 33.0, 9.5, NA, 47.5, 66.5, NA, 85.5, NA, 143.5), "vasaucB" = c(NA, 35.0, 62.0, 64.0, 80.5, NA, 33.5, NA, 59.0, NA, 32.5, 13.0, 120.0, 102.0, 166.5, NA, 138.0, NA, NA, NA, 161.5, 53.5, 13.5, 116.5, 68.0, 104.5, 103.0, NA, 36.0, NA), "vasaucC" = c( 48.5, NA, NA, 65.0, 94.5, 19.5, NA, 102.0, 56.5, 78.5, 18.0, NA, NA, 14.0, NA, 51.0, 168.5, 10.0, 28.0, 3.5, 127.0, NA, NA, 36.5, NA, NA, 33.5, 45.0, 7.5, 132.0)) level.Id <- sort(as.numeric(as.character(dfW$id))) dfW$id <- factor(dfW$id, levels = level.Id) dfW$group <- as.factor(dfW$group) dfL <- reshape2::melt(dfW, id.vars = c("id","group"), measure.vars = c("vasaucA","vasaucB","vasaucC"), value.name = "vasauc", variable.name = "treatment") dfL <- dfL[order(dfL$id, dfL$treatment),] dfL$treatment <- gsub("vasauc","",dfL$treatment) dfL$treatment <- as.factor(dfL$treatment) dfL$treatment.num <- as.numeric(dfL$treatment) dfL2 <- dfL dfL2$id <- as.character(dfL2$id) dfL2[dfL2$id == "2","id"] <- "0" dfL2[dfL2$id == "1","id"] <- "2" dfL2[dfL2$id == "0","id"] <- "1" dfL2$id <- factor(dfL2$id, levels = level.Id) dfL2 <- dfL2[order(dfL2$id,dfL2$treatment),] e.gls <- gls(vasauc ~ treatment, correlation = corSymm(form =~ treatment.num | id), weights = varIdent(form =~ 1|treatment), na.action = na.omit, data = dfL) logLik(e.gls) e.gls2 <- gls(vasauc ~ treatment, correlation = corSymm(form =~ treatment.num | id), weights = varIdent(form =~ 1|treatment), na.action = na.omit, data = dfL2) logLik(e.gls2) Sigma <- unname(getVarCov2(e.gls)$Omega) Sigma2 <- unname(getVarCov2(e.gls2)$Omega) expect_equal(Sigma, Sigma2, tol = 1e-5) expect_equal(Sigma[c(1,2),c(1,2)], unclass(nlme::getVarCov(e.gls2, individual = 1)), tol = 1e-5) expect_equal(Sigma[c(1,2),c(1,2)], unclass(nlme::getVarCov(e.gls, individual = 2)), tol = 1e-5) expect_equal(Sigma[c(1,3),c(1,3)], unclass(nlme::getVarCov(e.gls2, individual = 2)), tol = 1e-5) expect_equal(Sigma[c(1,3),c(1,3)], unclass(nlme::getVarCov(e.gls, individual = 1)), tol = 1e-5) expect_equal(Sigma[c(2,3),c(2,3)], unclass(nlme::getVarCov(e.gls2, individual = 4)), tol = 1e-5) expect_equal(Sigma[c(2,3),c(2,3)], unclass(nlme::getVarCov(e.gls, individual = 4)), tol = 1e-5) e.lme <- nlme::lme(value ~ time + G + Gender, random=~1|Id/Gender, data = dL, method = "ML") expect_error(getVarCov2(e.lme)) df.PET <- data.frame("ID" = c( 925, 2020, 2059, 2051, 2072, 2156, 2159, 2072, 2020, 2051, 2231, 2738, 2231, 2777, 939, 539, 2738, 2777, 925, 2156, 2159, 2059), "session" = c("V", "V", "V", "V", "V", "V", "V", "C", "C", "C", "C", "C", "V", "C", "C", "V", "V", "V", "C", "C", "C", "C"), "PET" = c(-2.53, -6.74, -8.17, -2.44, -3.54, -1.27, -0.55, -0.73, -1.42, 3.35, -2.11, 2.60, -4.52, 0.99, -1.02, -1.78, -5.86, 1.20, NA, NA, NA, NA) ) df.PET$session.index <- as.numeric(as.factor(df.PET$session)) e.lme <- lme(PET ~ session, random = ~ 1 | ID, weights = varIdent(form=~session.index|session), na.action = "na.omit", data = df.PET) test_that("getVarCov2 - NA", { expect_equal(matrix(c( 7.893839, 1.583932, 1.583932, 4.436933), 2, 2), unname(getVarCov2(e.lme)$Omega), tol = 1e-6, scale = 1) })
context("dnf") test_that("dnf", { expr <- quote(if (x > 1) y > 3) clause <- as_dnf(expr) expect_equal(length(clause), 2) }) test_that("rewritten if", { expr <- quote(!(gender %in% "male" & y > 3) | x > 6) clause <- as_dnf(expr) expect_equal(as.character(clause), '!(gender %in% "male") | y <= 3 | x > 6') }) test_that("clause as.character", { expr <- quote(if (x > 1) y > 3) clause <- as_dnf(expr) expect_equal(as.character(clause), "x <= 1 | y > 3") }) test_that("clause as if", { expr <- quote(if (x > 1) y > 3) clause <- as_dnf(expr) expect_equal(as.character(clause, as_if = TRUE), "if (x > 1) y > 3") expr <- quote(if (x > 1) (y > 3)) clause <- as_dnf(expr) expect_equal(as.character(clause, as_if = TRUE), "if (x > 1) y > 3") expr <- quote(!(x > 1)|(y > 3)) clause <- as_dnf(expr) expect_equal(as.character(clause, as_if = TRUE), "if (x > 1) y > 3") expr <- quote(!(x > 1) | y > 3) clause <- as_dnf(expr) expect_equal(as.character(clause, as_if = TRUE), "if (x > 1) y > 3") expr <- quote(!(x > 1 & z > 2) | y > 3) clause <- as_dnf(expr) expect_equal(as.character(clause), "x <= 1 | z <= 2 | y > 3") expect_equal(as.character(clause, as_if=TRUE), "if (x > 1 & z > 2) y > 3") }) test_that("simple clause works",{ expr <- quote(x > 1) clause <- as_dnf(expr) expect_equal(as.character(clause), "x > 1") expr <- quote((x > 1)) clause <- as_dnf(expr) expect_equal(as.character(clause), "x > 1") expr <- quote(!(x > 1)) clause <- as_dnf(expr) expect_equal(as.character(clause), "x <= 1") }) test_that("low level stuff works", { expect_equal(op(quote(1)), 1) expr <- quote( x > 1 || y > 2) dnf <- as_dnf(expr) expect_equal(as.character(dnf), "x > 1 | y > 2") expect_output(print(dnf), as.character(dnf)) expr <- quote(while(true){}) expect_error(as_dnf(expr), "Invalid expression") }) test_that("long statement works", { long_sum <- paste0("x", 1:100, collapse = " + ") text <- paste0(long_sum, " == 0") expr <- parse(text = text)[[1]] dnf <- as_dnf(expr) s <- as.character(dnf) expect_equal(s, text) }) describe("as_dnf", { it("works with simple expressions", { dnf <- as_dnf(quote(x > 1)) expect_equal(dnf[[1]], quote(x > 1)) expect_equal(length(dnf), 1) dnf <- as_dnf(quote(x == 1)) expect_equal(dnf[[1]], quote(x == 1)) expect_equal(length(dnf), 1) dnf <- as_dnf(quote(A == "a")) expect_equal(dnf[[1]], quote(A == "a")) expect_equal(length(dnf), 1) }) it("works with if statements", { dnf <- as_dnf(quote(if (x > 1) y < 0)) expect_equivalent(dnf, expression(x <=1, y < 0)) dnf <- as_dnf(quote(if (A == "a") y < 0)) expect_equivalent(dnf, expression(A != "a", y < 0)) dnf <- as_dnf(quote(if (A != "a") y < 0)) expect_equivalent(dnf, expression(A == "a", y < 0)) dnf <- as_dnf(quote(if (A %in% "a") y < 0)) expect_equivalent(dnf, expression(!(A %in% "a"), y < 0)) }) it("works with complex if statements", { dnf <- as_dnf(quote(if (x > 1 & z > 1) y < 0)) expect_equal(dnf[[1]], quote(x <= 1)) expect_equal(dnf[[2]], quote(z <= 1)) expect_equal(dnf[[3]], quote(y < 0)) expect_equal(length(dnf), 3) dnf <- as_dnf(quote(if (x > 1 & z > 1 & w > 1) y < 0)) expect_equivalent(dnf, expression(x <= 1, z <= 1, w <= 1, y < 0)) }) })
data("dataMultilevelIV") all.L3.models <- c("REF", "FE_L2", "FE_L3", "GMM_L2", "GMM_L3") all.L2.models <- c("REF", "FE_L2", "GMM_L2") context("Correctness - multilevelIV - Formula transformations") test_that("Transformations are correct for L2", { skip_on_cran() expect_silent(correct.res <- multilevelIV(formula = y ~ X11 + X12 + X13 + X14 + X15 + X21 + X22 + X23 + X24 + X31 + X32 + X33 + (1+X11 | SID) | endo(X15, X21), data = dataMultilevelIV, verbose = FALSE)) data.altered <- dataMultilevelIV data.altered$y <- exp(data.altered$y) expect_silent(res.trans.lhs <- multilevelIV(formula = log(y) ~ X11 + X12 + X13 + X14 + X15 + X21 + X22 + X23 + X24 + X31 + X32 + X33 + (1+X11 | SID) | endo(X15, X21), data = data.altered, verbose = FALSE)) expect_equal(coef(res.trans.lhs), coef(correct.res)) for(m in all.L2.models) expect_equal(coef(summary(res.trans.lhs, model = m)), coef(summary(correct.res, model = m))) data.altered <- dataMultilevelIV data.altered$X23 <- exp(data.altered$X23) expect_silent(res.trans.exo <- multilevelIV(formula = y ~ X11 + X12 + X13 + X14 + X15 + X21 + X22 + log(X23) + X24 + X31 + X32 + X33 + (1+X11 | SID) | endo(X15, X21), data = data.altered, verbose = FALSE)) expect_equal(coef(res.trans.exo), coef(correct.res), check.attributes = FALSE) for(m in all.L2.models) expect_equal(coef(summary(res.trans.exo, model = m)), coef(summary(correct.res, model = m)), check.attributes = FALSE) data.altered <- dataMultilevelIV data.altered$X15 <- exp(data.altered$X15) expect_silent(res.trans.endo <- multilevelIV(formula = y ~ X11 + X12 + X13 + X14 + log(X15) + X21 + X22 + X23 + X24 + X31 + X32 + X33 + (1+X11 | SID) | endo(log(X15), X21), data = data.altered, verbose = FALSE)) expect_equal(coef(res.trans.endo), coef(correct.res), check.attributes = FALSE) for(m in all.L2.models) expect_equal(coef(summary(res.trans.endo, model = m)), coef(summary(correct.res, model = m)), check.attributes = FALSE) data.altered <- dataMultilevelIV data.altered$X11 <- exp(data.altered$X11) expect_silent(res.trans.slope <- multilevelIV(formula = y ~ log(X11) + X12 + X13 + X14 + X15 + X21 + X22 + X23 + X24 + X31 + X32 + X33 + (1+log(X11) | SID) | endo(X15, X21), data = data.altered, verbose = FALSE)) expect_equal(coef(res.trans.slope), coef(correct.res), check.attributes = FALSE) for(m in all.L2.models) expect_equal(coef(summary(res.trans.slope, model = m)), coef(summary(correct.res, model = m)), check.attributes = FALSE) }) test_that("Transformations are correct for L3", { skip_on_cran() expect_message(correct.res <- multilevelIV(formula = y ~ X11 + X12 + X13 + X14 + X15 + X21 + X22 + X23 + X24 + X31 + X32 + X33 + (1+X11 | CID) + (1 | SID) | endo(X15, X21), data = dataMultilevelIV, verbose = FALSE), regexp = "singular") data.altered <- dataMultilevelIV data.altered$y <- exp(data.altered$y) expect_message(res.trans.lhs <- multilevelIV(formula = log(y) ~ X11 + X12 + X13 + X14 + X15 + X21 + X22 + X23 + X24 + X31 + X32 + X33 + (1+X11 | CID) + (1 | SID) | endo(X15, X21), data = data.altered, verbose = FALSE), regexp = "singular") expect_equal(coef(res.trans.lhs), coef(correct.res), check.attributes = FALSE) for(m in all.L3.models) expect_equal(coef(summary(res.trans.lhs, model = m)), coef(summary(correct.res, model = m)), check.attributes = FALSE) data.altered <- dataMultilevelIV data.altered$X23 <- exp(data.altered$X23) expect_message(res.trans.exo <- multilevelIV(formula = y ~ X11 + X12 + X13 + X14 + X15 + X21 + X22 + log(X23) + X24 + X31 + X32 + X33 + (1+X11 | CID) + (1 | SID) | endo(X15, X21), data = data.altered, verbose = FALSE), regexp = "singular") expect_equal(coef(res.trans.exo), coef(correct.res), check.attributes = FALSE) for(m in all.L3.models) expect_equal(coef(summary(res.trans.exo, model = m)), coef(summary(correct.res, model = m)), check.attributes = FALSE) data.altered <- dataMultilevelIV data.altered$X15 <- exp(data.altered$X15) expect_message(res.trans.endo <- multilevelIV(formula = y ~ X11 + X12 + X13 + X14 + log(X15) + X21 + X22 + X23 + X24 + X31 + X32 + X33 + (1+X11 | CID) + (1 | SID) | endo(log(X15), X21), data = data.altered, verbose = FALSE), regexp = "singular") expect_equal(coef(res.trans.endo), coef(correct.res), check.attributes = FALSE) for(m in all.L3.models) expect_equal(coef(summary(res.trans.endo, model = m)), coef(summary(correct.res, model = m)), check.attributes = FALSE) data.altered <- dataMultilevelIV data.altered$X11 <- exp(data.altered$X11) expect_message(res.trans.slope <- multilevelIV(formula = y ~ log(X11) + X12 + X13 + X14 + X15 + X21 + X22 + X23 + X24 + X31 + X32 + X33 + (1+log(X11) | CID) + (1 | SID) | endo(X15, X21), data = data.altered, verbose = FALSE), regexp = "singular") expect_equal(coef(res.trans.slope), coef(correct.res), check.attributes = FALSE) for(m in all.L3.models) expect_equal(coef(summary(res.trans.slope, model = m)), coef(summary(correct.res, model = m)), check.attributes = FALSE) }) context("Correctness - multilevelIV - Data sorting") test_that("Unsorted data is correct L2", { skip_on_cran() rownames(dataMultilevelIV) <- as.character(seq(from=nrow(dataMultilevelIV)+100000, to=1+100000)) expect_silent(res.sorted <- multilevelIV(formula = y ~ X11 + X12 + X13 + X14 + X15 + X21 + X22 + X23 + X24 + X31 + X32 + X33 + (1+X11 | SID) | endo(X15, X21), data = dataMultilevelIV, verbose = FALSE)) data.altered <- dataMultilevelIV data.altered <- data.altered[sample(x=nrow(dataMultilevelIV), size = nrow(dataMultilevelIV), replace = FALSE), ] expect_silent(res.unsorted <- multilevelIV(formula = y ~ X11 + X12 + X13 + X14 + X15 + X21 + X22 + X23 + X24 + X31 + X32 + X33 + (1+X11 | SID) | endo(X15, X21), data = data.altered, verbose = FALSE)) expect_equal(coef(res.unsorted), coef(res.sorted)) for(m in all.L2.models){ expect_equal(coef(summary(res.unsorted, model = m)), coef(summary(res.sorted, model = m))) expect_equal(names(fitted(res.sorted, model = m)), rownames(dataMultilevelIV)) expect_equal(names(resid(res.sorted, model = m)), rownames(dataMultilevelIV)) expect_equal(names(fitted(res.unsorted, model = m)), rownames(data.altered)) expect_equal(names(resid(res.unsorted, model = m)), rownames(data.altered)) } }) test_that("Unsorted data is correct L3", { skip_on_cran() rownames(dataMultilevelIV) <- as.character(seq(from=nrow(dataMultilevelIV)+100000, to=1+100000)) expect_silent(res.sorted <- multilevelIV(formula = y ~ X11 + X12 + X13 + X14 + X15 + X21 + X22 + X23 + X24 + X31 + X32 + X33 + (1+X12|CID)+(1+X11 | SID) | endo(X15, X21), data = dataMultilevelIV, verbose = FALSE)) data.altered <- dataMultilevelIV data.altered <- data.altered[sample.int(n=nrow(dataMultilevelIV), replace = FALSE), ] expect_silent(res.unsorted <- multilevelIV(formula = y ~ X11 + X12 + X13 + X14 + X15 + X21 + X22 + X23 + X24 + X31 + X32 + X33 + (1+X12|CID)+(1+X11 | SID) | endo(X15, X21), data = data.altered, verbose = FALSE)) expect_equal(coef(res.unsorted), coef(res.sorted)) for(m in all.L3.models){ expect_equal(coef(summary(res.unsorted, model = m)), coef(summary(res.sorted, model = m))) expect_equal(names(fitted(res.sorted, model = m)), rownames(dataMultilevelIV)) expect_equal(names(resid(res.sorted, model = m)), rownames(dataMultilevelIV)) expect_equal(names(fitted(res.unsorted, model = m)), rownames(data.altered)) expect_equal(names(resid(res.unsorted, model = m)), rownames(data.altered)) } }) context("Correctness - multilevelIV - Reproduce results") test_that("REF is same as lmer()", { skip_on_cran() expect_silent(res.ml2 <- multilevelIV(formula = y ~ X11 + X12 + X13 + X14 + X15 + X21 + X22 + X23 + X24 + X31 + X32 + X33 + (1+X11 | SID) | endo(X15, X21), data = dataMultilevelIV, verbose = FALSE)) expect_silent(res.lmer2 <- lmer(formula = y ~ X11 + X12 + X13 + X14 + X15 + X21 + X22 + X23 + X24 + X31 + X32 + X33 + (1+X11 | SID), data = dataMultilevelIV, control = lmerControl(optimizer = "Nelder_Mead", optCtrl = list(maxfun=100000)))) expect_equal(coef(res.ml2)[, "REF"], coef(summary(res.lmer2))[, "Estimate"]) expect_silent(res.ml3 <- multilevelIV(formula = y ~ X11 + X12 + X13 + X14 + X15 + X21 + X22 + X23 + X24 + X31 + X32 + X33 + (1|CID)+(1+X11 | SID) | endo(X15, X21), data = dataMultilevelIV, verbose = FALSE)) expect_silent(res.lmer3 <- lmer(formula = y ~ X11 + X12 + X13 + X14 + X15 + X21 + X22 + X23 + X24 + X31 + X32 + X33 +(1|CID)+ (1+X11 | SID), data = dataMultilevelIV, control = lmerControl(optimizer = "Nelder_Mead", optCtrl = list(maxfun=100000)))) expect_equal(coef(res.ml3)[, "REF"], coef(summary(res.lmer3))[, "Estimate"]) }) test_that("Retrieve generated data params", { skip_on_cran() expect_silent(res.ml3 <- multilevelIV(formula = y ~ X11 + X12 + X13 + X14 + X15 + X21 + X22 + X23 + X24 + X31 + X32 + X33 + (1|CID)+(1| SID) | endo(X15), data = dataMultilevelIV, verbose = FALSE)) correct.coefs <- c("(Intercept)"=64, X11 = 3, X12=9, X13=-2, X14 = 2, X15 = -1, X21 = -1.5, X22 = -4, X23 = -3, X24 = 6, X31 = 0.5, X32 = 0.1, X33 = -0.5) expect_equal(coef(res.ml3)[, "REF"], correct.coefs, tolerance = 0.1) }) test_that("Reproduce results by Kim and Frees 2007", { skip_on_cran() kf.formula <- TLI ~ GRADE_3 + RETAINED + SWITCHSC + S_FREELU + FEMALE + BLACK + HISPANIC + OTHER+ C_COHORT+ T_EXPERI + CLASS_SI+ P_MINORI + (1 + GRADE_3|NEWCHILD) | endo(CLASS_SI) df.data.kf <- read.csv("dallas2485.csv", header=TRUE) expect_silent(res.kf <- multilevelIV(formula = kf.formula, data = df.data.kf, verbose = FALSE)) correct.coefs <- cbind(REF = c("(Intercept)"=69.78, GRADE_3=3.375, RETAINED=9.205, SWITCHSC=-0.365, S_FREELU=-0.227, FEMALE=-1.234, BLACK=-4.745, HISPANIC=-3.608, OTHER=6.526, C_COHORT=1.497, T_EXPERI=-0.116, CLASS_SI=0.157, P_MINORI=0.069)) expect_equal(coef(res.kf)[, "REF"], correct.coefs[, "REF"], tolerance=0.1) }) context("Correctness - multilevelIV - Predict") expect_silent(res.m2 <- multilevelIV(y ~ X11 + X12 + X13 + X14 + X15 + X21 + X22 + X23 + X24 + X31 + X32 + X33 + (1|SID) | endo(X15), data = dataMultilevelIV, verbose = FALSE)) expect_silent(res.m3 <- multilevelIV(y ~ X11 + X12 + X13 + X14 + X15 + X21 + X22 + X23 + X24 + X31 + X32 + X33 + (1| CID) + (1|SID) | endo(X15), data = dataMultilevelIV, verbose = FALSE)) test_that("No newdata results in fitted values", { for(m in all.L2.models) expect_equal(predict(res.m2, model=m), fitted(res.m2, model=m)) for(m in all.L3.models) expect_equal(predict(res.m3, model=m), fitted(res.m3, model=m)) }) test_that("Same prediction data as for fitting results in fitted values", { for(m in all.L2.models) expect_equal(predict(res.m2, newdata=dataMultilevelIV,model=m), fitted(res.m2, model=m)) for(m in all.L3.models) expect_equal(predict(res.m3, newdata=dataMultilevelIV, model=m), fitted(res.m3, model=m)) }) test_that("Correct structure of predictions", { for(m in all.L2.models){ expect_silent(pred.2 <- predict(res.m2, newdata=dataMultilevelIV, model=m)) expect_true(is.numeric(pred.2)) expect_true(length(pred.2) == nrow(dataMultilevelIV)) expect_true(all(names(pred.2) == names(fitted(res.m2, model=m)))) expect_true(all(names(pred.2) == rownames(dataMultilevelIV))) } for(m in all.L3.models){ expect_silent(pred.3 <- predict(res.m3, newdata=dataMultilevelIV, model=m)) expect_true(is.numeric(pred.3)) expect_true(length(pred.3) == nrow(dataMultilevelIV)) expect_true(all(names(pred.3) == names(fitted(res.m3, model=m)))) expect_true(all(names(pred.3) == rownames(dataMultilevelIV))) } }) test_that("Correct when using transformations in the formula", { skip_on_cran() expect_silent(res.m2 <- multilevelIV(y ~ X11 + X12 + X13 + X14 + I((X15+14)/4) + X21 + X22 + X23 + X24 + log(X31) + X32 + X33 + (1|SID) | endo(I((X15+14)/4)), data = dataMultilevelIV, verbose = FALSE)) for(m in all.L2.models) expect_equal(predict(res.m2, newdata=dataMultilevelIV,model=m), fitted(res.m2, model=m)) expect_silent(res.m3 <- multilevelIV(y ~ X11 + X12 + X13 + X14 + I((X15+14)/4) + X21 + X22 + X23 + X24 + log(X31) + X32 + X33 + (1| CID) + (1|SID) | endo(I((X15+14)/4)), data = dataMultilevelIV, verbose = FALSE)) for(m in all.L3.models) expect_equal(predict(res.m3, newdata=dataMultilevelIV, model=m), fitted(res.m3, model=m)) })
wald.ci <- function (x, n = 100, conf.level = 0.95) { alpha = 1 - conf.level p = x/n zstar <- -qnorm(alpha/2) interval <- p + c(-1, 1) * zstar * sqrt(p * (1 - p)/n) attr(interval, "conf.level") <- conf.level return(interval) }
library(keras) input1 <- layer_input(name = "input1", dtype = "float32", shape = c(1)) input2 <- layer_input(name = "input2", dtype = "float32", shape = c(1)) output1 <- layer_add(name = "output1", inputs = c(input1, input2)) output2 <- layer_add(name = "output2", inputs = c(input2, input1)) model <- keras_model( inputs = c(input1, input2), outputs = c(output1, output2) ) export_savedmodel(model, "keras-multiple", as_text = TRUE)
holdout <- function(data, prop = .5, grouping = NULL, seed = NULL) { if (!is.null(seed)) { old.seed <- .Random.seed old.kind <- RNGkind()[1] set.seed(seed) } if (!is.null(grouping)) { if (length(prop) > 1 & length(prop) != nrow(unique(data[grouping]))) { prop <- prop[1] warning('The length of prop and the number of groups do not match. Only the first proportion is used.') } if (any(is.na(data[grouping]))) { data <- data[!is.na(data[grouping]), ] warning('Data contains observations with missing values on the grouping variables. These were excluded.') } n_cali <- ceiling(table(data[grouping]) * prop) filter <- NULL for (i in as.character(unlist(unique(data[grouping])))) { tmp <- which(data[grouping] == i) tmp_filter <- sample(tmp, n_cali[i]) filter <- c(filter, tmp_filter) } } else { n_cali <- ceiling(nrow(data)*prop) filter <- sort(sample(nrow(data), n_cali)) } output <- list(calibrate = data[filter, ], validate = data[-filter, ]) class(output) <- 'stuartHoldout' if (!is.null(seed)) { RNGkind(old.kind) .Random.seed <<- old.seed } return(output) }
rm(list = ls()) library(data.table) library(foreign) library(pdynmc) setwd(dir = "D:/Work/20_Projekte/50_Linear-Dynamic-Panel-Models/50_Drafts/20_Paper/50_Revisiting-habits-and-heterogeneity-in-demands") dat <- read.dta(file = "bc2.dta", convert.dates = TRUE, convert.factors = TRUE, missing.type = FALSE, convert.underscore = FALSE, warn.missing.labels = TRUE) dat$yearquarter <- as.character(dat$yearquarter) dat$yearquarterA <- as.character(dat$yearquarterA) sink(file="HNRandAS_log.txt") m1 <- pdynmc(dat = dat, varname.i = "i", varname.t = "t", use.mc.diff = TRUE, use.mc.lev = FALSE, use.mc.nonlin = TRUE, include.y = FALSE, varname.y = "foodin", lagTerms.y = 1, include.x = TRUE, varname.reg.end = "lrxtot", lagTerms.reg.end = 0, maxLags.reg.end = 5, varname.reg.ex = "lrhearn", lagTerms.reg.ex = 0, maxLags.reg.ex = 5, include.x.instr = TRUE, varname.reg.instr = "lrhearn", include.x.toInstr = FALSE, fur.con = FALSE, fur.con.diff = NULL, fur.con.lev = NULL, varname.reg.fur = NULL, lagTerms.reg.fur = NULL, include.dum = TRUE, dum.diff = TRUE, dum.lev = TRUE, varname.dum = c("week", "yearquarter"), w.mat = "iid.err", std.err = "corrected", estimation = "onestep", opt.meth = "BFGS") summary(m1) m2 <- pdynmc(dat = dat, varname.i = "i", varname.t = "t", use.mc.diff = TRUE, use.mc.lev = FALSE, use.mc.nonlin = TRUE, include.y = FALSE, varname.y = "foodin", lagTerms.y = 1, include.x = TRUE, varname.reg.end = "lrxtot", lagTerms.reg.end = 0, maxLags.reg.end = 5, varname.reg.ex = "lrhearn", lagTerms.reg.ex = 0, maxLags.reg.ex = 5, include.x.instr = TRUE, varname.reg.instr = "lrhearn", include.x.toInstr = FALSE, fur.con = FALSE, fur.con.diff = NULL, fur.con.lev = NULL, varname.reg.fur = NULL, lagTerms.reg.fur = NULL, include.dum = TRUE, dum.diff = TRUE, dum.lev = FALSE, varname.dum = c("week", "yearquarter"), w.mat = "iid.err", std.err = "corrected", estimation = "onestep", opt.meth = "BFGS") summary(m2) m3 <- pdynmc(dat = dat, varname.i = "i", varname.t = "t", use.mc.diff = TRUE, use.mc.lev = FALSE, use.mc.nonlin = TRUE, include.y = FALSE, varname.y = "foodin", lagTerms.y = 1, include.x = TRUE, varname.reg.end = "lrxtot", lagTerms.reg.end = 0, maxLags.reg.end = 5, varname.reg.ex = "lrhearn", lagTerms.reg.ex = 0, maxLags.reg.ex = 5, include.x.instr = TRUE, varname.reg.instr = "lrhearn", include.x.toInstr = FALSE, fur.con = FALSE, fur.con.diff = NULL, fur.con.lev = NULL, varname.reg.fur = NULL, lagTerms.reg.fur = NULL, include.dum = TRUE, dum.diff = FALSE, dum.lev = TRUE, varname.dum = c("week", "yearquarter"), w.mat = "iid.err", std.err = "corrected", estimation = "onestep", opt.meth = "BFGS") summary(m3) m4 <- pdynmc(dat = dat, varname.i = "i", varname.t = "t", use.mc.diff = TRUE, use.mc.lev = FALSE, use.mc.nonlin = TRUE, include.y = FALSE, varname.y = "foodin", lagTerms.y = 1, include.x = TRUE, varname.reg.end = "lrxtot", lagTerms.reg.end = 0, maxLags.reg.end = 5, varname.reg.ex = "lrhearn", lagTerms.reg.ex = 0, maxLags.reg.ex = 5, include.x.instr = TRUE, varname.reg.instr = "lrhearn", include.x.toInstr = FALSE, fur.con = FALSE, fur.con.diff = NULL, fur.con.lev = NULL, varname.reg.fur = NULL, lagTerms.reg.fur = NULL, include.dum = FALSE, dum.diff = NULL, dum.lev = NULL, varname.dum = NULL, w.mat = "iid.err", std.err = "corrected", estimation = "onestep", opt.meth = "BFGS") summary(m4) m5 <- pdynmc(dat = dat, varname.i = "i", varname.t = "t", use.mc.diff = TRUE, use.mc.lev = FALSE, use.mc.nonlin = TRUE, include.y = FALSE, varname.y = "foodin", lagTerms.y = 1, include.x = TRUE, varname.reg.end = "lrxtot", lagTerms.reg.end = 0, maxLags.reg.end = 5, varname.reg.ex = "lrhearn", lagTerms.reg.ex = 0, maxLags.reg.ex = 5, include.x.instr = TRUE, varname.reg.instr = "lrhearn", include.x.toInstr = FALSE, fur.con = TRUE, fur.con.diff = TRUE, fur.con.lev = TRUE, varname.reg.fur = c("nch","nad","hage","hage2"), lagTerms.reg.fur = c(0,0,0,0), include.dum = TRUE, dum.diff = TRUE, dum.lev = TRUE, varname.dum = c("week", "yearquarter"), w.mat = "iid.err", std.err = "corrected", estimation = "onestep", opt.meth = "BFGS") summary(m5) m6 <- pdynmc(dat = dat, varname.i = "i", varname.t = "t", use.mc.diff = TRUE, use.mc.lev = FALSE, use.mc.nonlin = TRUE, include.y = FALSE, varname.y = "foodin", lagTerms.y = 1, include.x = TRUE, varname.reg.end = "lrxtot", lagTerms.reg.end = 0, maxLags.reg.end = 5, varname.reg.ex = "lrhearn", lagTerms.reg.ex = 0, maxLags.reg.ex = 5, include.x.instr = TRUE, varname.reg.instr = "lrhearn", include.x.toInstr = FALSE, fur.con = TRUE, fur.con.diff = TRUE, fur.con.lev = TRUE, varname.reg.fur = c("nch","nad","hage","hage2"), lagTerms.reg.fur = c(0,0,0,0), include.dum = TRUE, dum.diff = TRUE, dum.lev = FALSE, varname.dum = c("week", "yearquarter"), w.mat = "iid.err", std.err = "corrected", estimation = "onestep", opt.meth = "BFGS") summary(m6) m7 <- pdynmc(dat = dat, varname.i = "i", varname.t = "t", use.mc.diff = TRUE, use.mc.lev = FALSE, use.mc.nonlin = TRUE, include.y = FALSE, varname.y = "foodin", lagTerms.y = 1, include.x = TRUE, varname.reg.end = "lrxtot", lagTerms.reg.end = 0, maxLags.reg.end = 5, varname.reg.ex = "lrhearn", lagTerms.reg.ex = 0, maxLags.reg.ex = 5, include.x.instr = TRUE, varname.reg.instr = "lrhearn", include.x.toInstr = FALSE, fur.con = TRUE, fur.con.diff = TRUE, fur.con.lev = TRUE, varname.reg.fur = c("nch","nad","hage","hage2"), lagTerms.reg.fur = c(0,0,0,0), include.dum = TRUE, dum.diff = FALSE, dum.lev = TRUE, varname.dum = c("week", "yearquarter"), w.mat = "iid.err", std.err = "corrected", estimation = "onestep", opt.meth = "BFGS") summary(m7) m8 <- pdynmc(dat = dat, varname.i = "i", varname.t = "t", use.mc.diff = TRUE, use.mc.lev = FALSE, use.mc.nonlin = TRUE, include.y = FALSE, varname.y = "foodin", lagTerms.y = 1, include.x = TRUE, varname.reg.end = "lrxtot", lagTerms.reg.end = 0, maxLags.reg.end = 5, varname.reg.ex = "lrhearn", lagTerms.reg.ex = 0, maxLags.reg.ex = 5, include.x.instr = TRUE, varname.reg.instr = "lrhearn", include.x.toInstr = FALSE, fur.con = TRUE, fur.con.diff = TRUE, fur.con.lev = TRUE, varname.reg.fur = c("nch","nad","hage","hage2"), lagTerms.reg.fur = c(0,0,0,0), include.dum = FALSE, dum.diff = NULL, dum.lev = NULL, varname.dum = NULL, w.mat = "iid.err", std.err = "corrected", estimation = "onestep", opt.meth = "BFGS") summary(m8) m9 <- pdynmc(dat = dat, varname.i = "i", varname.t = "t", use.mc.diff = TRUE, use.mc.lev = FALSE, use.mc.nonlin = TRUE, include.y = FALSE, varname.y = "foodin", lagTerms.y = 1, include.x = TRUE, varname.reg.end = "lrxtot", lagTerms.reg.end = 0, maxLags.reg.end = 5, varname.reg.ex = "lrhearn", lagTerms.reg.ex = 0, maxLags.reg.ex = 5, include.x.instr = TRUE, varname.reg.instr = "lrhearn", include.x.toInstr = FALSE, fur.con = TRUE, fur.con.diff = TRUE, fur.con.lev = FALSE, varname.reg.fur = c("nch","nad","hage","hage2"), lagTerms.reg.fur = c(0,0,0,0), include.dum = TRUE, dum.diff = TRUE, dum.lev = TRUE, varname.dum = c("week", "yearquarter"), w.mat = "iid.err", std.err = "corrected", estimation = "onestep", opt.meth = "BFGS") summary(m9) m10 <- pdynmc(dat = dat, varname.i = "i", varname.t = "t", use.mc.diff = TRUE, use.mc.lev = FALSE, use.mc.nonlin = TRUE, include.y = FALSE, varname.y = "foodin", lagTerms.y = 1, include.x = TRUE, varname.reg.end = "lrxtot", lagTerms.reg.end = 0, maxLags.reg.end = 5, varname.reg.ex = "lrhearn", lagTerms.reg.ex = 0, maxLags.reg.ex = 5, include.x.instr = TRUE, varname.reg.instr = "lrhearn", include.x.toInstr = FALSE, fur.con = TRUE, fur.con.diff = TRUE, fur.con.lev = FALSE, varname.reg.fur = c("nch","nad","hage","hage2"), lagTerms.reg.fur = c(0,0,0,0), include.dum = TRUE, dum.diff = TRUE, dum.lev = FALSE, varname.dum = c("week", "yearquarter"), w.mat = "iid.err", std.err = "corrected", estimation = "onestep", opt.meth = "BFGS") summary(m10) m11 <- pdynmc(dat = dat, varname.i = "i", varname.t = "t", use.mc.diff = TRUE, use.mc.lev = FALSE, use.mc.nonlin = TRUE, include.y = FALSE, varname.y = "foodin", lagTerms.y = 1, include.x = TRUE, varname.reg.end = "lrxtot", lagTerms.reg.end = 0, maxLags.reg.end = 5, varname.reg.ex = "lrhearn", lagTerms.reg.ex = 0, maxLags.reg.ex = 5, include.x.instr = TRUE, varname.reg.instr = "lrhearn", include.x.toInstr = FALSE, fur.con = TRUE, fur.con.diff = TRUE, fur.con.lev = FALSE, varname.reg.fur = c("nch","nad","hage","hage2"), lagTerms.reg.fur = c(0,0,0,0), include.dum = TRUE, dum.diff = FALSE, dum.lev = TRUE, varname.dum = c("week", "yearquarter"), w.mat = "iid.err", std.err = "corrected", estimation = "onestep", opt.meth = "BFGS") summary(m11) m12 <- pdynmc(dat = dat, varname.i = "i", varname.t = "t", use.mc.diff = TRUE, use.mc.lev = FALSE, use.mc.nonlin = TRUE, include.y = FALSE, varname.y = "foodin", lagTerms.y = 1, include.x = TRUE, varname.reg.end = "lrxtot", lagTerms.reg.end = 0, maxLags.reg.end = 5, varname.reg.ex = "lrhearn", lagTerms.reg.ex = 0, maxLags.reg.ex = 5, include.x.instr = TRUE, varname.reg.instr = "lrhearn", include.x.toInstr = FALSE, fur.con = TRUE, fur.con.diff = TRUE, fur.con.lev = FALSE, varname.reg.fur = c("nch","nad","hage","hage2"), lagTerms.reg.fur = c(0,0,0,0), include.dum = FALSE, dum.diff = NULL, dum.lev = NULL, varname.dum = NULL, w.mat = "iid.err", std.err = "corrected", estimation = "onestep", opt.meth = "BFGS") summary(m12) m13 <- pdynmc(dat = dat, varname.i = "i", varname.t = "t", use.mc.diff = TRUE, use.mc.lev = FALSE, use.mc.nonlin = TRUE, include.y = FALSE, varname.y = "foodin", lagTerms.y = 1, include.x = TRUE, varname.reg.end = "lrxtot", lagTerms.reg.end = 0, maxLags.reg.end = 5, varname.reg.ex = "lrhearn", lagTerms.reg.ex = 0, maxLags.reg.ex = 5, include.x.instr = TRUE, varname.reg.instr = "lrhearn", include.x.toInstr = FALSE, fur.con = TRUE, fur.con.diff = FALSE, fur.con.lev = TRUE, varname.reg.fur = c("nch","nad","hage","hage2"), lagTerms.reg.fur = c(0,0,0,0), include.dum = TRUE, dum.diff = TRUE, dum.lev = TRUE, varname.dum = c("week", "yearquarter"), w.mat = "iid.err", std.err = "corrected", estimation = "onestep", opt.meth = "BFGS") summary(m13) m14 <- pdynmc(dat = dat, varname.i = "i", varname.t = "t", use.mc.diff = TRUE, use.mc.lev = FALSE, use.mc.nonlin = TRUE, include.y = FALSE, varname.y = "foodin", lagTerms.y = 1, include.x = TRUE, varname.reg.end = "lrxtot", lagTerms.reg.end = 0, maxLags.reg.end = 5, varname.reg.ex = "lrhearn", lagTerms.reg.ex = 0, maxLags.reg.ex = 5, include.x.instr = TRUE, varname.reg.instr = "lrhearn", include.x.toInstr = FALSE, fur.con = TRUE, fur.con.diff = FALSE, fur.con.lev = TRUE, varname.reg.fur = c("nch","nad","hage","hage2"), lagTerms.reg.fur = c(0,0,0,0), include.dum = TRUE, dum.diff = TRUE, dum.lev = FALSE, varname.dum = c("week", "yearquarter"), w.mat = "iid.err", std.err = "corrected", estimation = "onestep", opt.meth = "BFGS") summary(m14) m15 <- pdynmc(dat = dat, varname.i = "i", varname.t = "t", use.mc.diff = TRUE, use.mc.lev = FALSE, use.mc.nonlin = TRUE, include.y = FALSE, varname.y = "foodin", lagTerms.y = 1, include.x = TRUE, varname.reg.end = "lrxtot", lagTerms.reg.end = 0, maxLags.reg.end = 5, varname.reg.ex = "lrhearn", lagTerms.reg.ex = 0, maxLags.reg.ex = 5, include.x.instr = TRUE, varname.reg.instr = "lrhearn", include.x.toInstr = FALSE, fur.con = TRUE, fur.con.diff = FALSE, fur.con.lev = TRUE, varname.reg.fur = c("nch","nad","hage","hage2"), lagTerms.reg.fur = c(0,0,0,0), include.dum = TRUE, dum.diff = FALSE, dum.lev = TRUE, varname.dum = c("week", "yearquarter"), w.mat = "iid.err", std.err = "corrected", estimation = "onestep", opt.meth = "BFGS") summary(m15) m16 <- pdynmc(dat = dat, varname.i = "i", varname.t = "t", use.mc.diff = TRUE, use.mc.lev = FALSE, use.mc.nonlin = TRUE, include.y = FALSE, varname.y = "foodin", lagTerms.y = 1, include.x = TRUE, varname.reg.end = "lrxtot", lagTerms.reg.end = 0, maxLags.reg.end = 5, varname.reg.ex = "lrhearn", lagTerms.reg.ex = 0, maxLags.reg.ex = 5, include.x.instr = TRUE, varname.reg.instr = "lrhearn", include.x.toInstr = FALSE, fur.con = TRUE, fur.con.diff = FALSE, fur.con.lev = TRUE, varname.reg.fur = c("nch","nad","hage","hage2"), lagTerms.reg.fur = c(0,0,0,0), include.dum = FALSE, dum.diff = NULL, dum.lev = NULL, varname.dum = NULL, w.mat = "iid.err", std.err = "corrected", estimation = "onestep", opt.meth = "BFGS") summary(m16) ls()[grepl(ls(), pattern = "m")] length(ls()[grepl(ls(), pattern = "m")])
multilevelIV <- function(formula, data, lmer.control=lmerControl(optimizer = "Nelder_Mead", optCtrl=list(maxfun=100000)), verbose=TRUE){ .SD <- NULL cl <- match.call() check_err_msg(checkinput_multilevel_formula(formula=formula)) check_err_msg(checkinput_multilevel_data(data=data)) check_err_msg(checkinput_multilevel_dataVSformula(formula=formula, data=data)) check_err_msg(checkinput_multilevel_lmercontrol(lmer.control=lmer.control)) check_err_msg(checkinput_multilevel_verbose(verbose = verbose)) F.formula <- Formula::as.Formula(formula) f.lmer <- formula(F.formula, lhs = 1, rhs = 1) names.endo <- formula_readout_special(F.formula = F.formula, name.special = "endo", from.rhs = 2, params.as.chars.only = TRUE) l4.form <- lme4::lFormula(formula = f.lmer, data=data) num.levels <- lme4formula_get_numberoflevels(l4.form) dt.response <- as.data.table(l4.form$fr[, 1, drop = FALSE], keep.rownames = "rownames") name.y <- colnames(l4.form$fr)[1] dt.FE <- as.data.table(l4.form$X) names.X <- colnames(dt.FE) names.X1 <- setdiff(names.X, names.endo) dt.slp <- as.data.table(l4.form$X[, unique(unlist(l4.form$reTrms$cnms)), drop=FALSE]) dt.groudids <- as.data.table(l4.form$fr[, unique(unlist(names(l4.form$reTrms$cnms))), drop=FALSE]) names.min.req.cols <- unique(c(colnames(dt.response), colnames(dt.FE), colnames(dt.slp), colnames(dt.groudids))) dt.model.data <- cbind(dt.response, dt.FE, dt.slp, dt.groudids)[, .SD, .SDcols = names.min.req.cols] rm(dt.response, dt.FE, dt.slp, dt.groudids) if(verbose) message("Fitting linear mixed-effects model ",format(f.lmer),".") res.lmer <- tryCatch(lme4::lmer(formula = f.lmer, data=data, REML = TRUE, control = lmer.control), error = function(e)return(e)) if(is(res.lmer, "error")) stop("lme4::lmer() could not be fitted with error: ", sQuote(res.lmer$message), "\nPlease revise your data and formula.", call. = FALSE) res.VC <- tryCatch(lme4::VarCorr(res.lmer), error = function(e)return(e)) if(is(res.VC, "error")) stop("lme4::VarCorr() could not be fitted with error: ", sQuote(res.VC$message), "\nPlease revise your data and formula.", call. = FALSE) if(num.levels == 2){ name.groupid.L2 <- names(l4.form$reTrms$cnms)[[1]] names.Z2 <- l4.form$reTrms$cnms[[name.groupid.L2]] res <- multilevel_2levels(cl = cl, f.orig = formula, dt.model.data = dt.model.data, res.VC = res.VC, name.group.L2 = name.groupid.L2, name.y = name.y, names.X = names.X, names.X1 = names.X1, names.Z2 = names.Z2, verbose = verbose) } else{ name.groupid.L2 <- names(l4.form$reTrms$cnms)[[1]] name.groupid.L3 <- names(l4.form$reTrms$cnms)[[2]] names.Z2 <- l4.form$reTrms$cnms[[name.groupid.L2]] names.Z3 <- l4.form$reTrms$cnms[[name.groupid.L3]] res <- multilevel_3levels(cl = cl, f.orig = formula, dt.model.data = dt.model.data, res.VC = res.VC, name.group.L2 = name.groupid.L2, name.group.L3 = name.groupid.L3, name.y = name.y, names.X = names.X, names.X1 = names.X1, names.Z2 = names.Z2, names.Z3 = names.Z3, verbose = verbose) } res$l.fitted <- lapply(res$l.fitted, function(fit){fit[rownames(data)]}) res$l.residuals <- lapply(res$l.residuals, function(resid){resid[rownames(data)]}) return(res) }
.dt_footnotes_key <- "_footnotes" dt_footnotes_get <- function(data) { dt__get(data, .dt_footnotes_key) } dt_footnotes_set <- function(data, footnotes) { dt__set(data, .dt_footnotes_key, footnotes) } dt_footnotes_init <- function(data) { dplyr::tibble( locname = character(0), grpname = character(0), colname = character(0), locnum = numeric(0), rownum = integer(0), colnum = integer(0), footnotes = list(character(0)) ) %>% dt_footnotes_set(footnotes = ., data = data) } dt_footnotes_add <- function(data, locname, grpname, colname, locnum, rownum, footnotes) { data %>% dt_footnotes_get() %>% dplyr::bind_rows( dplyr::tibble( locname = locname, grpname = grpname, colname = colname, locnum = locnum, rownum = rownum, colnum = NA_integer_, footnotes = list(footnotes) ) ) %>% dt_footnotes_set(footnotes = ., data = data) }
colours <- colors <- function(distinct = FALSE) { c <- .Call(C_colors) if(distinct) c[!duplicated(t(col2rgb(c)))] else c } col2rgb <- function(col, alpha = FALSE) { if(any(as.character(col) %in% "0")) stop("numerical color values must be positive", domain = NA) if (is.factor(col)) col <- as.character(col) .Call(C_col2rgb, col, alpha) } gray <- function(level, alpha = NULL) .Call(C_gray, level, alpha) grey <- gray rgb <- function(red, green, blue, alpha, names = NULL, maxColorValue = 1) { if(missing(green) && missing(blue)) { if(is.matrix(red) || is.data.frame(red)) { red <- data.matrix(red) if(ncol(red) < 3L) stop("at least 3 columns needed") green <- red[,2L]; blue <- red[,3L]; red <- red[,1L] } } .Call(C_rgb, red, green, blue, if (missing(alpha)) NULL else alpha, maxColorValue, names) } hsv <- function(h = 1, s = 1, v = 1, alpha = 1) .Call(C_hsv, h, s, v, if(missing(alpha)) NULL else alpha) hcl <- function (h = 0, c = 35, l = 85, alpha = 1, fixup = TRUE) .Call(C_hcl, h, c, l, if(missing(alpha)) NULL else alpha, fixup) rgb2hsv <- function(r, g = NULL, b = NULL, maxColorValue = 255) { rgb <- if(is.null(g) && is.null(b)) as.matrix(r) else rbind(r, g, b) if(!is.numeric(rgb)) stop("rgb matrix must be numeric") d <- dim(rgb) if(d[1L] != 3L) stop("rgb matrix must have 3 rows") n <- d[2L] if(n == 0L) return(cbind(c(h = 1, s = 1, v = 1))[, 0L]) rgb <- rgb/maxColorValue if(any(0 > rgb) || any(rgb > 1)) stop("rgb values must be in [0, maxColorValue]") .Call(C_RGB2hsv, rgb) } palette <- function(value) { if(missing(value)) .Call(C_palette, character()) else invisible(.Call.graphics(C_palette, value)) } recordPalette <- function() .Call.graphics(C_palette2, .Call(C_palette2, NULL)) rainbow <- function (n, s = 1, v = 1, start = 0, end = max(1,n - 1)/n, alpha = 1) { if ((n <- as.integer(n[1L])) > 0) { if(start == end || any(c(start,end) < 0)|| any(c(start,end) > 1)) stop("'start' and 'end' must be distinct and in [0, 1].") hsv(h = seq.int(start, ifelse(start > end, 1, 0) + end, length.out = n) %% 1, s, v, alpha) } else character() } topo.colors <- function (n, alpha = 1) { if ((n <- as.integer(n[1L])) > 0) { j <- n %/% 3 k <- n %/% 3 i <- n - j - k c(if(i > 0) hsv(h = seq.int(from = 43/60, to = 31/60, length.out = i), alpha = alpha), if(j > 0) hsv(h = seq.int(from = 23/60, to = 11/60, length.out = j), alpha = alpha), if(k > 0) hsv(h = seq.int(from = 10/60, to = 6/60, length.out = k), alpha = alpha, s = seq.int(from = 1, to = 0.3, length.out = k), v = 1)) } else character() } terrain.colors <- function (n, alpha = 1) { if ((n <- as.integer(n[1L])) > 0) { k <- n%/%2 h <- c(4/12, 2/12, 0/12) s <- c(1, 1, 0) v <- c(0.65, 0.9, 0.95) c(hsv(h = seq.int(h[1L], h[2L], length.out = k), s = seq.int(s[1L], s[2L], length.out = k), v = seq.int(v[1L], v[2L], length.out = k), alpha = alpha), hsv(h = seq.int(h[2L], h[3L], length.out = n - k + 1)[-1L], s = seq.int(s[2L], s[3L], length.out = n - k + 1)[-1L], v = seq.int(v[2L], v[3L], length.out = n - k + 1)[-1L], alpha = alpha)) } else character() } heat.colors <- function (n, alpha = 1) { if ((n <- as.integer(n[1L])) > 0) { j <- n %/% 4 i <- n - j c(rainbow(i, start = 0, end = 1/6, alpha = alpha), if (j > 0) hsv(h = 1/6, s = seq.int(from = 1-1/(2*j), to = 1/(2*j), length.out = j), v = 1, alpha = alpha)) } else character() } cm.colors <- function (n, alpha = 1) { if ((n <- as.integer(n[1L])) > 0L) { even.n <- n %% 2L == 0L k <- n %/% 2L l1 <- k + 1L - even.n l2 <- n - k + even.n c(if(l1 > 0L) hsv(h = 6/12, s = seq.int(.5, ifelse(even.n,.5/k,0), length.out = l1), v = 1, alpha = alpha), if(l2 > 1) hsv(h = 10/12, s = seq.int(0, 0.5, length.out = l2)[-1L], v = 1, alpha = alpha)) } else character() } gray.colors <- function(n, start = 0.3, end = 0.9, gamma = 2.2, alpha = NULL) gray(seq.int(from = start^gamma, to = end^gamma, length.out = n)^(1/gamma), alpha) grey.colors <- gray.colors
context("test-simtrait-BEDMatrix") if (suppressMessages(suppressWarnings(require(BEDMatrix)))) { X <- suppressMessages(suppressWarnings(BEDMatrix('dummy-33-101-0.1'))) X_R <- t( X[] ) n <- nrow(X) m <- ncol(X) test_that("allele_freqs works with BEDMatrix", { p_anc_hat <- allele_freqs(X_R) expect_equal( p_anc_hat, allele_freqs(X) ) expect_equal( p_anc_hat, allele_freqs( X, m_chunk_max = 11 ) ) p_anc_hat <- allele_freqs( X_R, fold = TRUE ) expect_equal( p_anc_hat, allele_freqs( X, fold = TRUE ) ) expect_equal( p_anc_hat, allele_freqs( X, fold = TRUE, m_chunk_max = 11 ) ) }) test_that("sim_trait works with BEDMatrix", { m_causal <- 5 herit <- 0.8 kinship <- diag(n) / 2 p_anc <- allele_freqs(X) obj <- sim_trait(X = X, m_causal = m_causal, herit = herit, p_anc = p_anc) trait <- obj$trait causal_indexes <- obj$causal_indexes causal_coeffs <- obj$causal_coeffs expect_equal( length(trait), n) expect_equal( length(causal_indexes), m_causal ) expect_true( all(causal_indexes <= m) ) expect_true( all(causal_indexes >= 1) ) expect_equal( length(causal_coeffs), m_causal) obj <- sim_trait(X = X, m_causal = m_causal, herit = herit, kinship = kinship) trait <- obj$trait causal_indexes <- obj$causal_indexes causal_coeffs <- obj$causal_coeffs expect_equal( length(trait), n) expect_equal( length(causal_indexes), m_causal ) expect_true( all(causal_indexes <= m) ) expect_true( all(causal_indexes >= 1) ) expect_equal( length(causal_coeffs), m_causal) }) }
"GreHSize" "segdata"
library(sf) library(terra) library(bcmaps) library(rasterbc) datadir_bc('C:/rasterbc_data', quiet=TRUE) example.name = 'Regional District of Central Okanagan' bc.bound.sf = bc_bound() districts.sf = regional_districts() example.sf = districts.sf[districts.sf$ADMIN_AREA_NAME==example.name, ] example.pestcode = 'IBM' df.fids.all = listdata_bc('fids') df.mpb = df.fids.all[grepl(example.pestcode, rownames(df.fids.all)), ] print(df.mpb) yr.example = 2008 dmg.levels = c('trace', 'light', 'moderate', 'severe', 'verysevere') hybrid.level = 'mid' vnames = paste(example.pestcode, dmg.levels, sep='_') eg.rasterlist = sapply(vnames, \(v) opendata_bc(geo=example.sf, 'fids', v, yr.example, quiet=TRUE)) cpoint = st_geometry(example.sf) |> st_centroid() |> st_transform(crs(eg.rasterlist[[1]])) |> st_coordinates() par(mfrow=c(1,5)) mapply(\(r, label) { plot(r, mar=c(0,0,0,0), legend=FALSE, axes=FALSE, reset=FALSE) graphics::text(x=cpoint[[1]], y=cpoint[[2]], label) }, r=eg.rasterlist, label=dmg.levels) dev.off() hybrid.vname = paste(example.pestcode, hybrid.level, sep='_') hybrid.raster = opendata_bc(geo=example.sf, 'fids', hybrid.vname, yr.example, quiet=TRUE) plot(hybrid.raster, main='estimated damage levels (% susceptible killed) - surveyed in 2008') yrs.all = 2004:2013 mpb.rasterlist = sapply(yrs.all, \(yr) opendata_bc(geo=example.sf, 'fids', hybrid.vname, yr, quiet=TRUE)) par(mfrow=c(2,5)) mapply(\(r, label) { plot(r, mar=c(0,0,0,0), legend=FALSE, axes=FALSE, reset=FALSE) graphics::text(x=cpoint[[1]], y=cpoint[[2]], label) }, r=mpb.rasterlist, label=yrs.all) sum() vname.example = c('') yr = 2008 eg.raster = opendata_bc(geo=example.sf, collection='fids', varname='IBM_mid', year=yr) plot(eg.raster) plot(bgcz.raster, col=rainbow(5), main='Biogeoclimatic zones') plot(st_geometry(example.sf), add=TRUE)
context("Testing reproducibility of results with examples") suppressWarnings(RNGversion("3.5.0")) set.seed(1) simUVgauss<-simGaussMiss<- c(rnorm(n=20, mean=30), rnorm(n=20, mean=25), rnorm(n=300, mean=40), rnorm(n=300, mean=43), rnorm(n=300, mean=43, sd = 10)) set.seed(1) simUVpoiss<- c(rpois(n=20, lambda = 30), rpois(n=20, lambda = 300), rpois(n=300, lambda = 200), rpois(n=300, lambda = 250), rpois(n=300, lambda = 230)) sim3Vgauss<- cbind(simUVgauss+10, simUVgauss, simUVgauss+90) sim3Vpoiss<- cbind(simUVpoiss+10, simUVpoiss, simUVpoiss+90) sim3Vmix <- cbind(sim3Vpoiss, sim3Vgauss) numremoved<- 0.1*length(simUVgauss) set.seed(1) removeIndices<- sample.int(length(simUVgauss), round(numremoved)) simGaussMiss[removeIndices]<-NA trueCPs<- c(1, 21, 41, 341, 641) ocpd1<- onlineCPD(simUVgauss, hazard_func=function(x, lambda){const_hazard(x, lambda=100)}, probModel=list("g"), init_params=list(list(m=0, k=0.01, a=0.01, b=0.0001)), multivariate=FALSE, cpthreshold = 0.5, truncRlim =10^(-4), minRlength= 1, maxRlength= 10^4, minsep=1, maxsep=10^4) test_that("Univariate gaussian example, maxCPs: ", { expect_identical(ocpd1$changepoint_lists$maxCPs[[1]], trueCPs) }) test_that("Univariate gaussian example, colmaxes: ", { expect_identical(ocpd1$changepoint_lists$colmaxes[[1]], trueCPs) }) test_that("Univariate gaussian example, threscps: ", { expect_identical(ocpd1$changepoint_lists$threshcps[[1]], trueCPs) }) ocpd2<- onlineCPD(simUVpoiss, hazard_func=function(x, lambda){const_hazard(x, lambda=100)}, probModel=list("p"), init_params=list(list(a=1, b=1)), multivariate=FALSE, cpthreshold = 0.5, truncRlim =10^(-4), minRlength= 1, maxRlength= 10^4, minsep=1, maxsep=10^4) test_that("Univariate poisson example, maxCPs: ", { expect_identical(ocpd2$changepoint_lists$maxCPs[[1]], c(1,21,41,341)) }) test_that("Univariate poisson example, colmaxes: ", { expect_identical(ocpd2$changepoint_lists$colmaxes[[1]], c(1,21,41,341)) }) test_that("Univariate poisson example, threscps: ", { expect_identical(ocpd2$changepoint_lists$threshcps[[1]], c(1,21,41,341)) }) ocpd3<- onlineCPD(sim3Vgauss, hazard_func=function(x, lambda){const_hazard(x, lambda=100)}, probModel=list("g"), init_params=list(list(m=0, k=0.01, a=0.01, b=0.0001)), multivariate=TRUE, cpthreshold = 0.5, truncRlim =10^(-4), minRlength= 1, maxRlength= 10^4, minsep=1, maxsep=10^4) test_that("Multivariate gaussian example, maxCPs: ", { expect_identical(ocpd3$changepoint_lists$maxCPs[[1]], trueCPs) }) test_that("Multivariate gaussian example, colmaxes: ", { expect_identical(ocpd3$changepoint_lists$colmaxes[[1]], trueCPs) }) test_that("Multivariate gaussian example, threscps: ", { expect_identical(ocpd3$changepoint_lists$threshcps[[1]], trueCPs) }) ocpd4<- onlineCPD(sim3Vpoiss, hazard_func=function(x, lambda){const_hazard(x, lambda=100)}, probModel=list("p"), init_params=list(list(a=1, b=1)), multivariate=TRUE, cpthreshold = 0.5, truncRlim =10^(-4), minRlength= 1, maxRlength= 10^4, minsep=1, maxsep=10^4) test_that("Multivariate poisson example, maxCPs: ", { expect_identical(ocpd4$changepoint_lists$maxCPs[[1]], c(1,21,41,340)) }) test_that("Multivariate poisson example, colmaxes: ", { expect_identical(ocpd4$changepoint_lists$colmaxes[[1]], c(1,21,38,41,340)) }) test_that("Multivariate poisson example, threscps: ", { expect_identical(ocpd4$changepoint_lists$threshcps[[1]], c(1,21,38, 41,340)) }) ocpd5<- onlineCPD(sim3Vmix, hazard_func=function(x, lambda){const_hazard(x, lambda=100)}, probModel=list("p"), init_params=c(rep(list(list(a=1, b=1)),3), rep(list(list(m=0, k=0.01, a=0.01, b=0.0001)), 3)), multivariate=TRUE, cpthreshold = 0.5, truncRlim =10^(-4), minRlength= 1, maxRlength= 10^4, minsep=1, maxsep=10^4) test_that("mixed gauss and poiss example, maxCPs: ", { expect_identical(ocpd5$changepoint_lists$maxCPs[[1]], c(1,21,39,340)) }) test_that("mixed gauss and poisson example, colmaxes: ", { expect_identical(ocpd5$changepoint_lists$colmaxes[[1]], c(1,21,38,39,340)) }) test_that("mixed gauss and poisson example, threscps: ", { expect_identical(ocpd5$changepoint_lists$threshcps[[1]], c(1,21,38,39,340)) }) ocpd6<- onlineCPD(simGaussMiss, hazard_func=function(x, lambda){const_hazard(x, lambda=100)}, probModel=list("g"), init_params=list(list(m=0, k=0.01, a=0.01, b=0.0001)), multivariate=FALSE, cpthreshold = 0.5, missPts = "mean", truncRlim =10^(-4), minRlength= 1, maxRlength= 10^4, minsep=1, maxsep=10^4) test_that("Univariate gaussian with missing points example, maxCPs: ", { expect_identical(ocpd6$changepoint_lists$maxCPs[[1]], c( 1, 22, 41, 341, 641)) }) test_that("Univariate gaussian with missing points example, colmaxes: ", { expect_identical(ocpd6$changepoint_lists$colmaxes[[1]], c( 1, 22, 41, 341, 641)) }) test_that("Univariate gaussian with missing points example, threscps: ", { expect_identical(ocpd6$changepoint_lists$threshcps[[1]], c( 1, 22, 41, 341, 641)) })
NULL setGeneric('settings', function(x, ...) standardGeneric('settings')) setMethod('settings', 'AcousticEvent', function(x, ...) x@settings) setGeneric('settings<-', function(x, value) standardGeneric('settings<-')) setMethod('settings<-', 'AcousticEvent', function(x, value) { x@settings <- value validObject(x) x }) setGeneric('localizations', function(x, ...) standardGeneric('localizations')) setMethod('localizations', 'AcousticEvent', function(x, ...) x@localizations) setGeneric('localizations<-', function(x, value) standardGeneric('localizations<-')) setMethod('localizations<-', 'AcousticEvent', function(x, value) { x@localizations <- value validObject(x) x }) setGeneric('id', function(x, ...) standardGeneric('id')) setMethod('id', 'AcousticEvent', function(x, ...) x@id) setGeneric('id<-', function(x, value) standardGeneric('id<-')) setMethod('id<-', 'AcousticEvent', function(x, value) { x@id <- value validObject(x) x }) setGeneric('detectors', function(x, ...) standardGeneric('detectors')) setMethod('detectors', 'AcousticEvent', function(x, ...) x@detectors) setGeneric('detectors<-', function(x, value) standardGeneric('detectors<-')) setMethod('detectors<-', 'AcousticEvent', function(x, value) { x@detectors <- value validObject(x) x }) setGeneric('species', function(x, ...) standardGeneric('species')) setMethod('species', 'AcousticEvent', function(x, ...) x@species) setMethod('species', 'AcousticStudy', function(x, type='id',...) { sapply(events(x), function(e) species(e)[[type]]) }) setGeneric('species<-', function(x, value) standardGeneric('species<-')) setMethod('species<-', 'AcousticEvent', function(x, value) { x@species <- value validObject(x) x }) setGeneric('files', function(x, ...) standardGeneric('files')) setMethod('files', 'AcousticEvent', function(x, ...) x@files) setGeneric('files<-', function(x, value) standardGeneric('files<-')) setMethod('files<-', 'AcousticEvent', function(x, value) { x@files <- value validObject(x) x }) setGeneric('ancillary', function(x, ...) standardGeneric('ancillary')) setMethod('ancillary', 'AcousticEvent', function(x, ...) x@ancillary) setGeneric('ancillary<-', function(x, value) standardGeneric('ancillary<-')) setMethod('ancillary<-', 'AcousticEvent', function(x, value) { x@ancillary <- safeListAdd(x@ancillary, value) validObject(x) x }) setMethod('[', 'AcousticEvent', function(x, i) { x@detectors[i] }) setMethod('[<-', 'AcousticEvent', function(x, i, value) { x@detectors[i] <- value validObject(x) x }) setMethod('$', 'AcousticEvent', function(x, name) { '[['(x@detectors, name) }) setMethod('$<-', 'AcousticEvent', function(x, name, value) { x@detectors[[name]] <- value validObject(x) x }) setMethod('[[', 'AcousticEvent', function(x, i) { '[['(x@detectors, i) }) setMethod('[[<-', 'AcousticEvent', function(x, i, value) { x@detectors[[i]] <- value validObject(x) x }) .DollarNames.AcousticEvent <- function(x, pattern='') { grep(pattern, names(detectors(x)), value=TRUE) } setMethod('id', 'AcousticStudy', function(x, ...) x@id) setMethod('id<-', 'AcousticStudy', function(x, value) { x@id <- value validObject(x) x }) setMethod('files', 'AcousticStudy', function(x, ...) x@files) setMethod('files<-', 'AcousticStudy', function(x, value) { x@files <- value validObject(x) x }) setGeneric('gps', function(x, ...) standardGeneric('gps')) setMethod('gps', 'AcousticStudy', function(x, ...) x@gps) setGeneric('gps<-', function(x, value) standardGeneric('gps<-')) setMethod('gps<-', 'AcousticStudy', function(x, value) { x@gps <- value validObject(x) x }) setMethod('detectors', 'AcousticStudy', function(x, ...) { getDetectorData(x) }) setGeneric('events', function(x, ...) standardGeneric('events')) setMethod('events', 'AcousticStudy', function(x, ...) x@events) setGeneric('events<-', function(x, value) standardGeneric('events<-')) setMethod('events<-', 'AcousticStudy', function(x, value) { x@events <- value validObject(x) x }) setMethod('settings', 'AcousticStudy', function(x, ...) x@settings) setMethod('settings<-', 'AcousticStudy', function(x, value) { x@settings <- value validObject(x) x }) setGeneric('effort', function(x, ...) standardGeneric('effort')) setMethod('effort', 'AcousticStudy', function(x, ...) x@effort) setGeneric('effort<-', function(x, value) standardGeneric('effort<-')) setMethod('effort<-', 'AcousticStudy', function(x, value) { x@effort <- value validObject(x) x }) setGeneric('pps', function(x, ...) standardGeneric('pps')) setMethod('pps', 'AcousticStudy', function(x, ...) x@pps) setGeneric('pps<-', function(x, value) standardGeneric('pps<-')) setMethod('pps<-', 'AcousticStudy', function(x, value) { x@pps <- value validObject(x) x }) setMethod('ancillary', 'AcousticStudy', function(x, ...) x@ancillary) setMethod('ancillary<-', 'AcousticStudy', function(x, value) { x@ancillary <- safeListAdd(x@ancillary, value) validObject(x) x }) setGeneric('models', function(x, ...) standardGeneric('models')) setMethod('models', 'AcousticStudy', function(x, ...) x@models) setGeneric('models<-', function(x, value) standardGeneric('models<-')) setMethod('models<-', 'AcousticStudy', function(x, value) { x@models <- value validObject(x) x }) setMethod('[', 'AcousticStudy', function(x, i) { x@events <- x@events[i] x@events <- x@events[sapply(x@events, function(e) { !is.null(e) })] x }) setMethod('[<-', 'AcousticStudy', function(x, i, value) { x@events[i] <- value validObject(x) x }) setMethod('$', 'AcousticStudy', function(x, name) { '[['(x@events, name) }) setMethod('$<-', 'AcousticStudy', function(x, name, value) { x@events[[name]] <- value validObject(x) x }) setMethod('[[', 'AcousticStudy', function(x, i) { '[['(x@events, i) }) setMethod('[[<-', 'AcousticStudy', function(x, i, value) { x@events[[i]] <- value validObject(x) x }) .DollarNames.AcousticStudy <- function(x, pattern='') { grep(pattern, names(events(x)), value=TRUE) }
test_that("incorrect source and target are rejected", { n1 <- Node$new() expect_error(e <- Arrow$new(42, n1), class="non-Node_endpoint") expect_error(e <- Arrow$new(n1, 42), class="non-Node_endpoint") }) test_that("incorrect labels are rejected", { n1 <- Node$new() n2 <- Node$new() expect_error(a <- Arrow$new(n1, n2, TRUE), class="non-string_label") }) test_that("arrow is defined correctly", { n1 <- Node$new() n2 <- Node$new() expect_silent(a <- Arrow$new(n1, n2, "a1")) expect_identical(n1, a$source()) expect_identical(n2, a$target()) expect_equal(a$label(), "a1") }) test_that("base edge object is defined correctly", { n1 <- Node$new() n2 <- Node$new() expect_silent(a <- Arrow$new(n1, n2, "a1")) V <- a$endpoints() expect_identical(n1, V[[1]]) expect_identical(n2, V[[2]]) })
setConstructorS3("GenericReporter", function(tags="*", ...) { if (!is.null(tags)) { tags <- Arguments$getTags(tags, collapse=NULL) } extend(Object(), "GenericReporter", .alias = NULL, .tags = tags ) }) setMethodS3("as.character", "GenericReporter", function(x, ...) { this <- x s <- sprintf("%s:", class(this)[1]) s <- c(s, paste("Name:", getName(this))) s <- c(s, paste("Tags:", paste(getTags(this), collapse=","))) s <- c(s, sprintf("Path: %s", getPath(this))) GenericSummary(s) }, protected=TRUE) setMethodS3("getAlias", "GenericReporter", function(this, ...) { this$.alias }, protected=TRUE) setMethodS3("setAlias", "GenericReporter", function(this, alias=NULL, ...) { if (!is.null(alias)) { alias <- Arguments$getFilename(alias); if (regexpr("[,]", alias) != -1) { throw("Aliases (names) must not contain commas: ", alias) } } this$.alias <- alias }, protected=TRUE) setMethodS3("getName", "GenericReporter", function(this, ...) { name <- getAlias(this) if (is.null(name)) { name <- getInputName(this) } name }) setMethodS3("getTags", "GenericReporter", function(this, collapse=NULL, ...) { tags <- getInputTags(this) tags <- c(tags, this$.tags) tags <- Arguments$getTags(tags, collapse=NULL) tags <- locallyUnique(tags) tags[tags == "*"] <- getAsteriskTags(this, collapse=",") tags <- tags[nzchar(tags)] tags <- locallyUnique(tags) if (!is.null(collapse)) { tags <- paste(tags, collapse=collapse) } else { if (length(tags) > 0) tags <- unlist(strsplit(tags, split=",")) } if (length(tags) == 0) tags <- NULL tags }) setMethodS3("getInputName", "GenericReporter", abstract=TRUE, protected=TRUE) setMethodS3("getInputTags", "GenericReporter", abstract=TRUE, protected=TRUE) setMethodS3("getAsteriskTags", "GenericReporter", function(this, ...) { "" }, protected=TRUE) setMethodS3("getFullName", "GenericReporter", function(this, ...) { name <- getName(this) tags <- getTags(this) fullname <- paste(c(name, tags), collapse=",") fullname <- gsub("[,]$", "", fullname) fullname }) setMethodS3("getReportSet", "GenericReporter", abstract=TRUE, protected=TRUE) setMethodS3("getRootPath", "GenericReporter", function(this, ...) { "reports" }, protected=TRUE) setMethodS3("getMainPath", "GenericReporter", function(this, ...) { rootPath <- getRootPath(this) name <- getName(this) tags <- getTags(this, collapse=",") if (length(tags) == 0 || !nzchar(tags)) { tags <- "raw"; } path <- filePath(rootPath, name, tags) path <- Arguments$getWritablePath(path) path }, protected=TRUE) setMethodS3("getPath", "GenericReporter", abstract=TRUE) setMethodS3("setup", "GenericReporter", abstract=TRUE) setMethodS3("process", "GenericReporter", abstract=TRUE)
miniusloglik.lev.wts <- function(dat, pars) { n=nrow(dat) index=match("time", colnames(dat), 0) if(index==1){ dat=as.data.frame(cbind(start=rep(0, n), stop=dat[,1], status=dat[,2], dat[,-c(1,2)])) } tt=dat[,"stop"] delta=dat[,"status"] wts=dat[,"wts"] cov=as.matrix(dat[,-c(1:4)]) m=length(pars) sigma=exp(pars[m]) beta=as.matrix(pars[-m]) zz=(log(tt)-cov%*%beta)/sigma ff=dlev(zz)/(sigma*tt) FF=plev(zz) tt0=dat[,"start"] FF0=rep(0, n) idx=(tt0==0) if(sum(idx)>0){ tt0.trun=tt0[!idx] zz0=(log(tt0.trun)-cov[!idx,]%*%beta)/sigma FF0[!idx]=plev(zz0) } ll=delta*log(ff/(1-FF0))+(1-delta)*log((1-FF)/(1-FF0)) res=(-1)*sum(wts*ll) return(res) }
yuenContrast <- function(IV, ...) UseMethod("yuenContrast")
testData = createData(sampleSize = 200, overdispersion = 0.0, randomEffectVariance = 0) fittedModel <- glm(observedResponse ~ Environment1, family = "poisson", data = testData) simulationOutput <- simulateResiduals(fittedModel = fittedModel) x = testQuantiles(simulationOutput) x \dontrun{ x$pvals x$qgamFits summary(x$qgamFits[[1]]) testQuantiles(simulationOutput, quantiles = c(0.7)) fittedModel <- glm(observedResponse ~ 1 , family = "poisson", data = testData) simulationOutput <- simulateResiduals(fittedModel = fittedModel) testQuantiles(simulationOutput, predictor = testData$Environment1) plot(simulationOutput) plotResiduals(simulationOutput) }
find_thread_urls <- function(keywords=NA, sort_by="top", subreddit=NA, period="month") ifelse( is.na(keywords), build_homepage_url(sort_by, subreddit, period), build_keywords_url(keywords, sort_by, subreddit, period) ) |> parse_request_url(data_builder = build_thread_df) |> rbind_list() |> dedup_df() build_thread_df <- function(json) { data.frame( date_utc = extract_json_attribute(json, "created_utc") |> timestamp_to_date(), title = extract_json_attribute(json, "title"), text = extract_json_attribute(json, "selftext"), subreddit = extract_json_attribute(json, "subreddit"), comments = extract_json_attribute(json, "num_comments"), url = REDDIT_URL %+% extract_json_attribute(json, "permalink"), stringsAsFactors = FALSE ) } build_keywords_url <- function(keywords, sort_by, subreddit, period) { validate_one_of(sort_by, SORT_KEYWORD_OPTIONS) build_base_request_url(subreddit) %+% "search.json?" %+% ifelse(is.na(subreddit), "", "restrict_sr=on&") %+% "q=" %+% space2plus(keywords) %+% "&sort=" %+% sort_by %+% "&" %+% create_url_limits(period) } build_homepage_url <- function(sort_by, subreddit, period) { validate_one_of(sort_by, SORT_HOMEPAGE_OPTIONS) build_base_request_url(subreddit) %+% sort_by %+% ".json?" %+% create_url_limits(period) } build_base_request_url <- function(subreddit) REDDIT_URL %+% ifelse(is.na(subreddit), "/", "/r/" %+% space2plus(subreddit) %+% "/") create_url_limits <- function(period) { validate_one_of(period, PERIOD_OPTIONS) "t=" %+% period %+% "&limit=100" }
library("vcr") invisible(vcr::vcr_configure(dir = "../fixtures", write_disk_path = "../files")) vcr::check_cassette_names() ogpath <- rdryad_cache$cache_path_get() testthat::setup({ rdryad_cache$cache_path_set(full_path="tests/files") }) testthat::teardown({ rdryad_cache$cache_path_set(full_path=ogpath) })
shQuote <- function(string, type = c("sh", "csh", "cmd", "cmd2")) { if(missing(type) && .Platform$OS.type == "windows") type <- "cmd" type <- match.arg(type) if(type == "cmd") { string <- gsub("(\\\\*)\"", "\\1\\1\\\\\"", string) string <- sub("(\\\\+)$", "\\1\\1", string) paste0("\"", string, "\"", recycle0 = TRUE) } else if (type == "cmd2") gsub('([()%!^"<>&|])', "^\\1", string) else if(!any(grepl("'", string))) paste0("'", string, "'", recycle0 = TRUE) else if(type == "sh") paste0('"', gsub('(["$`\\])', "\\\\\\1", string), '"') else if(!any(grepl("([$`])", string))) paste0('"', gsub('(["!\\])' , "\\\\\\1", string), '"') else paste0("'", gsub("'", "'\"'\"'", string, fixed = TRUE), "'") } .standard_regexps <- function() { list(valid_package_name = "[[:alpha:]][[:alnum:].]*[[:alnum:]]", valid_package_version = "([[:digit:]]+[.-]){1,}[[:digit:]]+", valid_R_system_version = "[[:digit:]]+\\.[[:digit:]]+\\.[[:digit:]]+", valid_numeric_version = "([[:digit:]]+[.-])*[[:digit:]]+") }
library(shiny) server <- function(input, output, session) { shinyjs::onclick("nowcast_img", updateTabsetPanel(session, inputId="navbar", selected= "Nowcasts")) shinyjs::onclick("forecast_img", updateTabsetPanel(session, inputId="navbar", selected= "Forecasts")) shinyjs::onclick("epimodel_img", updateTabsetPanel(session, inputId="navbar", selected= "Scenarios")) rt.ts <- reactive({ icl_rt_f <- icl %>% select(date, constant_mobility_mean_time_varying_reproduction_number_R.t.) %>% rename(mean_rt = constant_mobility_mean_time_varying_reproduction_number_R.t.) icl_rt <- icl_model %>% select(date, mean_time_varying_reproduction_number_R.t.) %>% rename(mean_rt = mean_time_varying_reproduction_number_R.t.) icl_rt <- rbind(icl_rt, icl_rt_f) fu <- filter(gu, !is.na(r_values_mean)) rt.rt.xts <- xts(rt_live[,4], rt_live$date) can.rt.xts <- xts(can.state.observed[,8],can.state.observed$date) epifc.rt.xts <- xts(epi_forecast[which(epi_forecast$type == "nowcast"),4], epi_forecast[which(epi_forecast$type == "nowcast"),]$date) gu.xts <- xts(fu[,19],fu$date) ucla.rt.xts <- xts(ucla_state[,2],ucla_state$date) ucla.rt.xts <- ucla.rt.xts[paste0("/",Sys.Date()-1)] if ( exists("icl") & exists('icl_model') ) { icl_rt <- icl_model %>% select(date, mean_time_varying_reproduction_number_R.t.) %>% rename(mean_rt = mean_time_varying_reproduction_number_R.t.) icl.rt.xts <- xts(icl_rt[,2], icl_rt$date) } df <- merge(rt.rt.xts, can.rt.xts,epifc.rt.xts, gu.xts, ucla.rt.xts, icl.rt.xts) df$mean.rt <- rowMeans(df[,c(1:4,6)], na.rm = TRUE) df[is.nan(as.numeric(df))] <- NA_character_ df <- as.data.table(df) %>% as.data.frame() df[,2:8] <- sapply(df[,2:8], function(x) as.numeric(as.character(x)) ) return(df) }) output$mean.rt.box <- renderValueBox({ cdt <- Sys.Date()-1 current.rt <- round(rt.ts()[which(rt.ts()$index == cdt),8], digits = 2) valueBox(current.rt, subtitle = paste0(ifelse(current.rt >= 1.4, "Spread of COVID-19 is very likely increasing", ifelse(current.rt < 1.4 & current.rt >= 1.1, "Spread of COVID-19 may be increasing", ifelse(current.rt < 1.1 & current.rt >= 0.9, "Spread of COVID-19 is likely stable", "Spread of COVID-19 is likely decreasing" ) ) ) ), color = "blue" ) }) observeEvent(input$Rt_explain, { sendSweetAlert( session = session, title = "What does a Reff of this size mean?", text = HTML("<p>If the R effective is greater than 1, COVID-19 will spread <b>exponentially</b>. If R effective is less than 1, COVID-19 will spread more slowly and cases will decline. The higher the value of R effective, the faster an epidemic will progress. The following graph illustrates the change in growth as R effective increases.</p> <img src='reff_cuml_infection.png' alt='Infections increase faster with larger values of R effective' width='400' height='400'/> <p><a href='https://www.cebm.net/covid-19/when-will-it-be-over-an-introduction-to-viral-reproduction-numbers-r0-and-re/' target='_blank'>Source: CEBM</a></p>" ), html = TRUE, type = NULL ) }) output$hilo_rt.box <- renderUI({ df <- rt.ts() df <- df %>% filter(index < Sys.Date()) %>% slice(n()) rt.min <- as.numeric( apply(df[,c(2:5,7)], 1, function(i) min(i, na.rm = TRUE)) ) rt.max <- as.numeric( apply(df[,c(2:5,7)], 1, function(i) max(i, na.rm = TRUE)) ) name.min <- switch(as.character(colnames(df)[match(apply(df[,c(2:5,7)], 1, function(i) min(i, na.rm = TRUE)),df)]), "rt.rt.xts" = "rt.live", "can.rt.xts" = "COVIDActNow", "epifc.rt.xts" = "EpiForecasts", "gu.xts" = "covid19-projections.com", "ucla.rt.xts" = "UCLA", "icl.rt.xts" = "ICL") name.max<- switch(as.character(colnames(df)[match(apply(df[,c(2:5,7)], 1, function(i) max(i, na.rm = TRUE)),df)]), "rt.rt.xts" = "rt.live", "can.rt.xts" = "COVIDActNow", "epifc.rt.xts" = "EpiForecasts", "gu.xts" = "covid19-projections.com", "ucla.rt.xts" = "UCLA", "icl.rt.xts" = "ICL") tagList(valueBox( paste0( round(rt.min,digits = 2)," - ", round(rt.max,digits = 2)) , paste0(name.min," - ",name.max), color = "navy", width = 12) ) }) output$rt.plot <- renderPlotly({ df <- rt.ts() %>% filter(index < Sys.Date() & index > Sys.Date() -80) p <- plot_ly(df, hoverinfo = 'text') %>% add_trace(x = df[[1]], y = df[[2]], name = "rt.live", type = 'scatter', mode = "lines", line = list(color="orange", dash = 'dot', opacity = 0.5), text = paste0(df[[1]], "<br>", "rt.live estimated Reff: ", round(df[[2]], digits=2) ) ) %>% add_trace(x = df[[1]], y = df[[3]], name = "COVIDActNow", type = 'scatter', mode = "lines", line = list(color="blue", dash = 'dot', opacity = 0.5), hoverinfo = 'text', text = paste0(df[[1]], "<br>", "COVIDActNow estimated Reff: ", round(df[[3]], digits=2) ) ) %>% add_trace(x = df[[1]], y = df[[4]], name = "EpiForecasts", type = 'scatter', mode = "lines", line = list(color="purple", dash = 'dot', opacity = 0.5), hoverinfo = 'text', text = paste0(df[[1]], "<br>", "EpiForecasts estimated Reff: ", round(df[[4]], digits=2) ) ) %>% add_trace(x = df[[1]], y = df[[5]], name = "covid19-projections.com", type = 'scatter', mode = "lines", line = list(color="red", dash = 'dot', opacity = 0.5), hoverinfo = 'text', text = paste0(df[[1]], "<br>", "covid19-projections.com estimated Reff: ", round(df[[5]], digits=2) ) ) %>% add_trace(x = df[[1]], y = df[[7]], name = "ICL", type = 'scatter', mode = "lines", line = list(color="grey", dash = 'dot', opacity = 0.5), hoverinfo = 'text', text = paste0(df[[1]], "<br>", "Imperial College London estimated Reff: ", round(df[[7]], digits=2) ) ) %>% add_trace(x = df[[1]], y = df[[8]], name = "Mean Reff", type = 'scatter', mode = "lines", hoverinfo = 'text', line = list(color = ' text = paste0(df[[1]], "<br>", "Mean estimated Reff: ", round(df[[8]], digits=2), "<br>", ifelse(round(df[[8]], digits=2) >= 1.4, "Spread of COVID-19 is very likely increasing", ifelse(round(df[[8]], digits=2) < 1.4 & round(df[[8]], digits=2) >= 1.1, "Spread of COVID-19 may be increasing", ifelse(round(df[[8]], digits=2) < 1.1 & round(df[[8]], digits=2) >= 0.9, "Spread of COVID-19 is likely stable", "Spread of COVID-19 is likely decreasing" ) ) ) ) ) %>% layout( title = NULL, xaxis = list(title = NULL, showgrid = FALSE, zeroline = FALSE ), yaxis = list(title = "R-Eff", showline = TRUE, showgrid = FALSE, zeroline = FALSE ), margin = list(l = 100), showlegend = TRUE, shapes = list( type = "line", x0 = 0, x1 = 1, xref = "paper", y0 = 1, y1 = 1, yref = "y", line = list(color = "gray50", dash= "dash", opacity = 0.3)) ) return(p) }) output$dlRt <- downloadHandler( filename = function() { paste("R_eff_Nowcasts_",Sys.Date(),'.csv', sep='') }, content = function(file) { t <- c(paste("R-Effective Model and Ensemble Time Series", sep = ""),"","","","","","") tt <- c(paste("COVID Assessment Tool - Downloaded on",Sys.Date(), sep = " "),"","","","","","") l <- c("Date","rt.live","COVIDActNow","EpiForecasts","covid19-projections.com","ICL","Mean Reff") df <- rt.ts()[,c(1:5,7,8)] %>% filter(index < Sys.Date() & index > Sys.Date() -80) df[,2:7] <- lapply(df[,2:7],function(x) round(x,2)) df[] <- lapply(df, as.character) s <- c("Please see the Technical Notes tab of the application for data sources.","","","","","","") p <- c(paste0("Prepared by: ",state_name," Department of Public Health"),"","","","","","") dlm <- rbind(t, tt, l, df, s, p) write.table(dlm, file, row.names = F, col.names = F, quote = F, na= "NA", sep = ",") }) county.rt <- reactive({ progress <- Progress$new() on.exit(progress$close()) progress$set(message = "Gathering R Effective Nowcasts", value = 0) c <- names(canfipslist[match(input$select.county.rt,canfipslist)]) cnty <- input$select.county.rt progress$inc(3/4) out <- filter(can.county.observed, fips == cnty) cnty.rt <- out %>% select(date,RtIndicator) %>% as.data.frame() cnty.rt$date <- as.Date(cnty.rt$date) progress$inc(1/4) df <- xts(cnty.rt[,-1],cnty.rt$date) if( c %in% unique(gu.cnty$subregion)) { cnty.gu <- gu.cnty %>% filter(subregion == c) %>% select(date, r_values_mean) gu.xts <- xts(cnty.gu[,-1],cnty.gu$date) df <- merge(df,gu.xts) } if (ncol(df) > 1) {df$mean.proj <- rowMeans(df[,1:ncol(df)], na.rm = TRUE)} df <- as.data.table(df) %>% as.data.frame() %>% filter(index < Sys.Date()) return(df) }) output$county.rt.plot <- renderPlotly({ df <- county.rt() c <- names(canfipslist[match(input$select.county.rt,canfipslist)]) p <- plot_ly(df, x = df[[1]], y = df[[2]], name = "COVIDActNow", type = 'scatter', mode = "lines", line = list(color="blue", dash = 'dot', opacity = 0.5), hoverinfo = 'text', text = paste0(df[[1]], "<br>", "COVIDActNow estimated Reff: ", round(df[[2]], digits=2) ) ) if (c %in% unique(gu.cnty$subregion) ) {p <- p %>% add_trace(x = df[[1]], y = df[["gu.xts"]], name = "covid19-projections.com", type = 'scatter', mode = "lines", line = list(color="red", dash = 'dot', opacity = 0.5), hoverinfo = 'text', text = paste0(df[[1]], "<br>", "covid19-projections.com estimated Reff: ", round(df[["gu.xts"]], digits=2) ) ) } if (ncol(df) > 2) {p <- p %>% add_trace(x = df[[1]], y = df[["mean.proj"]], name = "Mean Reff", type = 'scatter', mode = "lines", hoverinfo = 'text', text = paste0(df[[1]], "<br>", "Mean estimated Reff: ", round(df[["mean.proj"]], digits=2), "<br>", ifelse(round(df[["mean.proj"]], digits=2) >= 1.4, "Spread of COVID-19 is very likely increasing", ifelse(round(df[["mean.proj"]], digits=2) < 1.4 & round(df[["mean.proj"]], digits=2) >= 1.1, "Spread of COVID-19 may be increasing", ifelse(round(df[["mean.proj"]], digits=2) < 1.1 & round(df[["mean.proj"]], digits=2) >= 0.9, "Spread of COVID-19 is likely stable", "Spread of COVID-19 is likely decreasing" ) ) ) ), inherit = FALSE, line = list(color = ' linetype = "solid" ) } p <- p %>% layout( legend = list(orientation = 'h'), title = as.character(counties[match(input$select.county.rt, counties$fips),"county"]), xaxis = list(title = NULL, showgrid = FALSE, zeroline = FALSE ), yaxis = list(title = "R-Eff", showline = TRUE, showgrid = FALSE, zeroline = FALSE ), margin = list(l = 100), showlegend = TRUE, shapes = list( type = "line", x0 = 0, x1 = 1, xref = "paper", y0 = 1, y1 = 1, yref = "y", line = list(color = "gray50", dash= "dash", opacity = 0.3) ) ) return(p) }) output$dlRt.indv.cnty <- downloadHandler( filename = function() { paste("Rt_Nowcasts_",names(canfipslist[match(input$select.county.rt,canfipslist)]),"_",Sys.Date(),'.csv', sep='') }, content = function(file) { c <- names(canfipslist[match(input$select.county.rt,canfipslist)]) t <- c(paste("R-Effective County Model Time Series for ",c, sep = ""),"","","","") tt <- c(paste("COVID Assessment Tool - Downloaded on",Sys.Date(), sep = " "),"","","","") df <- county.rt() %>% as.data.frame() if ( ncol(df) > 2 ) { df[,2:ncol(df)] <- lapply(df[,2:ncol(df)],function(x) round(x,2)) } else { df[,2] <- round(df[,2],2) } df[is.na(df)] <- 0 df[] <- lapply(df, as.character) l <- c("Date","COVIDActNow") if ( c %in% unique(gu.cnty$subregion) ) { l <- c(l, c("covid19-projections.com")) } if ( c %in% unique(ucla_cnty_rt$county) ) { l <- c(l, c("UCLA")) } if ( length(l) > 2 ) { l <- c(l, c("Mean Reff") ) } s <- c("Please see the Technical Notes tab of the application for data sources.","","","","") p <- c(paste0("Prepared by: ",state_name," Department of Public Health"),"","","","") dlm <- rbind(t, tt, l, df, s, p) write.table(dlm, file, row.names = F, col.names = F, quote = F, na= "NA", sep = ",") }) cnty.7.day.rt <- data.table(can.county.observed) %>% .[, max_date := max(date, na.rm = T), by = .(county)] %>% .[date > Sys.Date()-7, .(Rt.m = mean(RtIndicator, na.rm = T), ll = mean(RtIndicator - RtIndicatorCI90, na.rm=T), ul = mean(RtIndicator + RtIndicatorCI90, na.rm=T)), by = .(county)] %>% na.omit() output$rt.dot.plot <- renderPlotly({ df <- cnty.7.day.rt p <- plot_ly(df, x = ~ reorder(df$county, desc(df$Rt.m)), y = ~ df$Rt.m, name = "R effective", type = 'scatter', mode = "markers", marker = list(color = ' hoverinfo = 'text', text = ~paste0(df$county, " County<br>","7-day Average Reff: ", round(df$Rt.m, digits=2), "<br>", ifelse(df$Rt.m >= 1.4, "Spread of COVID-19 is very likely increasing", ifelse(df$Rt.m < 1.4 & df$Rt.m >= 1.1, "Spread of COVID-19 may be increasing", ifelse(df$Rt.m < 1.1 & df$Rt.m >= 0.9, "Spread of COVID-19 is likely stable", "Spread of COVID-19 is likely decreasing" ) ) ) ) ) %>% add_segments(x =~ reorder(df$county, df$Rt.m), xend = ~ reorder(df$county, df$Rt.m), y = df$ll, yend = df$ul, type = "scatter", mode = "lines", opacity = .5, line = list(color=' showlegend = FALSE ) %>% layout( xaxis = list(title = "", tickangle = -30, showgrid = FALSE, zeroline = FALSE ), yaxis = list(title = "R-Eff", showline = TRUE, showgrid = FALSE, zeroline = FALSE ), margin = list(l = 100), showlegend = FALSE, shapes = list( type = "line", x0 = 0, x1 = 1, xref = "paper", y0 = 1, y1 = 1, yref = "y", line = list(color = "gray50", dash= "dash", opacity = 0.3) ) ) return(p) }) output$dlRt.cnty <- downloadHandler( filename = function() { paste("Rt_Nowcasts_7DayAvg_Counties",Sys.Date(),'.csv', sep='') }, content = function(file) { t <- c(paste("R-Effective 7 Day Averages for Counties", sep = ""),"","","","") tt <- c(paste("COVID Assessment Tool - Downloaded on",Sys.Date(), sep = " "),"","","","") df <- cnty.7.day.rt %>% as.data.frame() if ( ncol(df) > 2 ) { df[,2:ncol(df)] <- lapply(df[,2:ncol(df)],function(x) round(x,2)) } else { df[,2] <- round(df[,2],2) } df[is.na(df)] <- 0 df[] <- lapply(df, as.character) l <- c("County","COVIDActNow - 7 Day Avg", "LL", "UL") s <- c("Please see the Technical Notes tab of the application.","","","","") p <- c(paste0("Prepared by: ",state_name," Department of Public Health"),"","","","") u <- c("Source: COVIDActNow - https://blog.covidactnow.org/modeling-metrics-critical-to-reopen-safely/","","","","") dlm <- rbind(t, tt, l, df, s, p, u) write.table(dlm, file, row.names = F, col.names = F, quote = F, na= "NA", sep = ",") }) hosp.proj.ts <- reactive({ min_hosp <- min(covid$Most.Recent.Date) hosp <- covid %>% select(Most.Recent.Date,COVID.19.Positive.Patients) %>% filter(covid$County.Name == state_name) %>% as.data.frame() can.hosp.proj <- can.state.observed %>% select(date, hospitalBedsRequired) %>% filter(min_hosp <= date & date <= Sys.Date() + 30) IHME.hosp.proj <- IHME %>% select(date, allbed_mean) %>% filter(min_hosp <= date & date <= Sys.Date() + 30) mobs.hosp.proj <- mobs %>% select(2,8) %>% filter(min_hosp <= date & date <= Sys.Date() + 30) mit.hosp.proj <- mit %>% select(11,7) %>% filter(min_hosp <= date & date <= Sys.Date() + 30) covid.xts <- xts(hosp[,-1],hosp$Most.Recent.Date) can.proj.xts <- xts(can.hosp.proj[,-1],can.hosp.proj$date) ihme.proj.xts <- xts(IHME.hosp.proj[,-1],IHME.hosp.proj$date) mobs.proj.xts <- xts(mobs.hosp.proj[,-1],mobs.hosp.proj$date) mit.proj.xts <- xts(mit.hosp.proj[,-1],mit.hosp.proj$date) df <- merge(covid.xts,can.proj.xts,ihme.proj.xts,mobs.proj.xts,mit.proj.xts) df$mean.proj <- rowMeans(df[,2:5], na.rm = TRUE) df$mean.proj <- ifelse(!is.na(df$covid.xts), NA, df$mean.proj) df <- as.data.table(df) %>% as.data.frame() df$period <- ifelse(!is.na(df$covid.xts), "solid", "dot") df$type <- ifelse(!is.na(df$covid.xts), "Est.", "Proj.") return(df) }) output$actual.hosp.box <- renderValueBox({ cdt <- max(covid$Most.Recent.Date) current.hosp <- as.character(covid[which(covid$Most.Recent.Date == cdt & covid$County.Name == state_name),"COVID.19.Positive.Patients"]) valueBox( "Actuals Go Here", paste0("Actuals: ",cdt), color = "black") }) output$mean.proj.hosp.box <- renderUI({ cdt.ihme <- max( IHME[which(IHME$date <= Sys.Date() + 30),]$date ) mean.proj <- hosp.proj.ts() %>% slice(n()) %>% select(7) valueBox( format(round(mean.proj, digits = 0), big.mark = ","), paste0("Mean 30-Day Forecast through ", cdt.ihme), color = "blue", width = 12) }) output$hosp.proj.plot <- renderPlotly({ df <- hosp.proj.ts() cdt <- max(df[which(!is.na(df$covid.xts)),1]) p <- plot_ly(df, hoverinfo = 'text') %>% add_trace(x = df[[1]], y = df[[2]], name = "Actuals", type = 'scatter', mode = "lines+markers", hoverinfo = 'text', text = paste0(df[[1]], "<br>", "Actual Hospitalization (PLACEHOLDER DATA - PLEASE REPLACE!!): ", format(round(df[[2]],0), big.mark = ",") ), line = list(color = "black"), marker = list(color = "black", symbol= "circle") ) %>% add_trace(x = df[[1]], y = df[[3]], name = ~I(paste0("COVIDActNow - ",df$type)), type = 'scatter', mode = "lines", inherit = TRUE, line = list(color="orange"), linetype = ~I(period), hoverinfo = 'text', text = paste0(df[[1]], "<br>", "COVIDActNow Estimate: ", format(round(df[[3]],0), big.mark = ",") ) ) %>% add_trace(x = df[[1]], y = df[[4]], name = ~I(paste0("IHME - ",df$type)), type = 'scatter', mode = "lines", inherit = TRUE, line = list(color="navy"), linetype = ~I(period), hoverinfo = 'text', text = paste0(df[[1]], "<br>", "IHME Estimate: ", format(round(df[[4]],0), big.mark = ",") ) ) %>% add_trace(x = df[[1]], y = df[[5]], name = ~I(paste0("MOBS - ",df$type)), type = 'scatter', mode = "lines", inherit = TRUE, line = list(color="red"), linetype = ~I(period), hoverinfo = 'text', text = paste0(df[[1]], "<br>", "MOBS Estimate: ", format(round(df[[5]],0), big.mark = ",") ) ) %>% add_trace(x = df[[1]], y = df[[6]], name = ~I(paste0("MIT - ",df$type)), type = 'scatter', mode = "lines", inherit = TRUE, line = list(color="green"), linetype = ~I(period), hoverinfo = 'text', text = paste0(df[[1]], "<br>", "MIT Estimate: ", format(round(df[[6]],0), big.mark = ",") ) ) %>% add_trace(x = df[[1]], y = df[[7]], name = "Mean Proj.", type = 'scatter', mode = "lines", hoverinfo = 'text', text = paste0(df[[1]], "<br>", "Mean Projection: ", format(round(df[[7]],0), big.mark = ",") ), line = list(color = ' ) %>% layout( title = NULL, xaxis = list(title = NULL, showline = TRUE, showgrid = FALSE, zeroline = FALSE ), yaxis = list(title = "Hospitalizations", showline = TRUE, showgrid = FALSE, zeroline = FALSE ), margin = list(l = 100), showlegend = TRUE, shapes = list(type = "line", y0 = 0, y1 = 1, yref = "paper", x0 = cdt, x1 = cdt, line = list(color = "black", dash = 'dash') ) ) return(p) }) output$dlhosp <- downloadHandler( filename = function() { paste("Hospital_Forecasts_",Sys.Date(),'.csv', sep='') }, content = function(file) { t <- c(paste("Statewide Hospitalization Forecasts", sep = ""),"","","","","","") tt <- c(paste("COVID Assessment Tool - Downloaded on",Sys.Date(), sep = " "),"","","","","","") l <- c("Date","Actuals", "COVIDActNow","IHME","MOBS","MIT","Mean") df <- hosp.proj.ts()[,1:7] %>% as.data.frame() df[,2:7] <- lapply(df[,2:7],function(x) round(x,2)) df[is.na(df)] <- 0 df[] <- lapply(df, as.character) s <- c("Please see the Technical Notes tab of the application for data sources.","","","","","","") p <- c("Prepared by: California Department of Public Health - COVID Modeling Team","","","","","","") dlm <- rbind(t, tt, l, df, s, p) write.table(dlm, file, row.names = F, col.names = F, quote = F, na= "NA", sep = ",") }) county.hosp <- reactive({ progress <- Progress$new() on.exit(progress$close()) progress$set(message = "Gathering Hospitalization Forecasts", value = 0) cnty <- input$select.county.hosp progress$inc(3/4) out <- filter(can.county.observed, fips == cnty) cnty.hosp <- out %>% select(date,hospitalBedsRequired) %>% as.data.frame() progress$inc(1/4) return(cnty.hosp) }) hosp.proj.cnty.ts <- reactive({ c <- names(canfipslist[match(input$select.county.hosp,canfipslist)]) min_hosp <- min(covid$Most.Recent.Date) hosp <- covid %>% select(Most.Recent.Date,COVID.19.Positive.Patients) %>% filter(covid$County.Name == c) %>% as.data.frame() can.hosp.proj <- county.hosp() %>% select(date, hospitalBedsRequired) %>% filter(min_hosp <= date & date <= Sys.Date() + 30) covid.xts <- xts(hosp[,-1],hosp$Most.Recent.Date) can.proj.xts <- xts(can.hosp.proj[,-1],can.hosp.proj$date) df <- merge(covid.xts,can.proj.xts) df <- as.data.table(df) %>% as.data.frame() df$period <- ifelse(!is.na(df$covid.xts), "solid", "dot") return(df) }) output$actual.cnty.hosp.box <- renderValueBox({ c <- names(canfipslist[match(input$select.county.hosp,canfipslist)]) cdt <- max(covid$Most.Recent.Date) current.hosp <- as.character(covid[which(covid$Most.Recent.Date == cdt & covid$County.Name == c),"COVID.19.Positive.Patients"]) valueBox( "Counts/Beds Here", paste0("Actuals / Total Beds: ",cdt), color = "black") }) output$mean.cnty.proj.hosp.box <- renderValueBox({ cdt.ihme <- max( IHME[which(IHME$date <= Sys.Date() + 30),]$date ) mean.proj <- hosp.proj.cnty.ts() %>% slice(n()) %>% select(3) valueBox( format(round(mean.proj, digits = 0), big.mark = ","), paste0("30-Day Forecast through ", cdt.ihme), color = "blue") }) output$county.hosp.plot <- renderPlotly({ df <- hosp.proj.cnty.ts() cdt <- max(df[which(!is.na(df$covid.xts)),1]) today <- list(type = "line", y0 = 0, y1 = 1, yref = "paper", x0 = cdt, x1 = cdt, line = list(color = "black", dash = 'dash') ) p <- plot_ly(df, hoverinfo = 'text') %>% add_trace(x = df[[1]], y = df[[2]], name = "Actuals", type = 'scatter', mode = "lines+markers", hoverinfo = 'text', text = paste0(df[[1]], "<br>", "Actual Hospitalization (PLACEHOLDER DATA - PLEASE REPLACE!!): ", format(df[[2]], big.mark = ",") ), line = list(color = "black"), marker = list(color = "black", symbol= "circle") ) %>% add_trace(x = df[[1]], y = df[[3]], name = "COVIDActNow - Proj.", type = 'scatter', mode = "lines", inherit = TRUE, line = list(color="orange"), linetype = ~I(period), hoverinfo = 'text', text = paste0(df[[1]], "<br>", "COVIDActNow Estimate: ", format(df[[3]], big.mark = ",") ) ) %>% layout( title = as.character(counties[match(input$select.county.hosp, counties$fips),"county"]), xaxis = list(title = NULL, showline = TRUE, showgrid = FALSE, zeroline = FALSE ), yaxis = list(title = "Hospitalziations", showline = TRUE, showgrid = FALSE, zeroline = FALSE), margin = list(l = 100), showlegend = TRUE, shapes = list(today) ) return(p) }) output$dlhosp.cnty <- downloadHandler( filename = function() { paste("Hospital_Forecasts_for_",names(canfipslist[match(input$select.county.hosp,canfipslist)]),Sys.Date(),'.csv', sep='') }, content = function(file) { c <- names(canfipslist[match(input$select.county.hosp,canfipslist)]) t <- c(paste("Hospitalization Forecasts for ",c, sep = ""),"","","","","","") tt <- c(paste("COVID Assessment Tool - Downloaded on",Sys.Date(), sep = " "),"","","","","","") l <- c("Date","Actuals", "COVIDActNow") df <- hosp.proj.cnty.ts()[,1:3] %>% as.data.frame() df[,2:3] <- lapply(df[,2:3],function(x) round(x,2)) df[is.na(df)] <- 0 df[] <- lapply(df, as.character) s <- c("Please see the Technical Notes tab of the application for data sources.","","","","","","") p <- c(paste0("Prepared by: ",state_name," Department of Public Health"),"","","","","","") dlm <- rbind(t, tt, l, df, s, p) write.table(dlm, file, row.names = F, col.names = F, quote = F, na= "NA", sep = ",") }) cdeath.ca <- reactive({ reich_test <- reich_lab %>% unique() %>% as.data.frame() cdeaths_test <- covid %>% select(Most.Recent.Date,Total.Count.Deaths) %>% filter(covid$County.Name == state_name) %>% mutate(model_team = 'Actuals') %>% rename(model_team = model_team, target_end_date = Most.Recent.Date, pointNA = Total.Count.Deaths ) %>% select(model_team, pointNA, target_end_date) %>% as.data.frame() reich_test <- rbind(reich_test,cdeaths_test) reich_test <- reich_test %>% distinct(model_team, target_end_date, .keep_all = TRUE) %>% spread(model_team, pointNA) }) output$actual.cdeath.box <- renderValueBox({ cdt <- max(covid$Most.Recent.Date) current.deaths <- as.character(covid[which(covid$Most.Recent.Date == cdt & covid$County.Name == state_name),4]) valueBox( format(as.numeric(current.deaths), big.mark = ","), paste0("Actuals (NYTIMES DATA): ",cdt), color = "black") }) output$mean.proj.cdeaths.box <- renderUI({ ensemble <- cdeath.ca() %>% select(target_end_date,COVIDhub.ensemble) %>% filter(!is.na(COVIDhub.ensemble)) cdt.ens <- max(ensemble$target_end_date) mean.proj <- ensemble %>% slice(n()) %>% select(2) valueBox( format(round(mean.proj, digits = 0), big.mark = ","), paste0("COVIDhub Ensemble Forecast through ", cdt.ens), color = "blue", width = 12) }) output$cdeath.proj.plot <- renderPlotly({ df <- cdeath.ca() models <- names(df) models <- setdiff(models, c("target_end_date", "CU.nointerv", "CU.60contact","CU.70contact", "CU.80contact","CU.80contact1x10p","CU.80contact1x5p","CU.80contactw10p", "CU.80contactw5p","COVIDhub.ensemble", "Actuals" ) ) models <- models %>% c("Actuals","COVIDhub.ensemble") p <- plot_ly(data=df, type = "scatter", mode = "lines") for(trace in models){ if (trace == "Actuals") { p <- p %>% plotly::add_trace(x = ~target_end_date, y = as.formula(paste0("~`", trace, "`")), name = trace, type = 'scatter', mode = "lines+markers", line = list(color ="black"), marker = list(color = "black", symbol= "circle"), hoverinfo = 'text', text = paste0(df[[1]], "<br>", "Actual Total Deaths (NYTIMES DATA): ", format(df$Actuals, big.mark = ",")) ) } else { if (trace == "COVIDhub.ensemble") { p <- p %>% add_trace(x = ~target_end_date, y = as.formula(paste0("~`", trace, "`")), inherit = FALSE, name = trace, line = list(shape = "spline", color = ' marker = list(color = ' hoverinfo = 'text', text = paste0(df[[1]], "<br>", "COVIDhub Ensemble Forecast: ", format(df$COVIDhub.ensemble, big.mark = ",")) ) } else { p <- p %>% plotly::add_trace(x = ~target_end_date, y = as.formula(paste0("~`", trace, "`")), name = trace, type = 'scatter', mode = "lines", line = list(color ="lightgray"), hoverinfo = 'text+y', text = paste0(df[[1]], "<br>", trace," Forecast") ) } } } p %>% layout(title = NULL, xaxis = list(title = " ", showline = TRUE, showgrid = FALSE, zeroline = FALSE ), yaxis = list(title = "Total Deaths", showline = TRUE, showgrid = FALSE, zeroline = FALSE, hoverformat = ',.2r' ), margin = list(l = 100), legend = list(traceorder = "reversed"), showlegend = TRUE) }) output$dlDeath <- downloadHandler( filename = function() { paste("Cumulative_Deaths_Forecasts_",Sys.Date(),'.csv', sep='') }, content = function(file) { t <- c(paste("Statewide Cumulative Deaths Forecasts", sep = ""),rep("",ncol(cdeath.ca())-1) ) tt <- c(paste("COVID Assessment Tool - Downloaded on",Sys.Date(), sep = " "),rep("",ncol(cdeath.ca())-1)) l <- names(cdeath.ca()) df <- cdeath.ca() %>% as.data.frame() df[is.na(df)] <- 0 df[] <- lapply(df, as.character) s <- c("Please see the Technical Notes tab of the application for data sources.",rep("",ncol(cdeath.ca())-1)) p <- c(paste0("Prepared by: ",state_name," Department of Public Health"),rep("",ncol(cdeath.ca())-1)) dlm <- rbind(t, tt, l, df, s, p) write.table(dlm, file, row.names = F, col.names = F, quote = F, na= "NA", sep = ",") }) county.deaths <- reactive({ progress <- Progress$new() on.exit(progress$close()) progress$set(message = "Gathering Death Forecast Data", value = 0) fips <- input$select.county.death cnty <- names(canfipslist[match(fips,canfipslist)]) death <- covid %>% select(Most.Recent.Date,Total.Count.Deaths) %>% filter(covid$County.Name == cnty) %>% as.data.frame() min_death <- min(death$Most.Recent.Date) progress$inc(3/4) out <- filter(can.county.observed, county == cnty) can.death <- out %>% select(date,cumulativeDeaths) %>% filter(min_death <= date & date <= Sys.Date() + 30) %>% rename(CovidActNow = cumulativeDeaths) %>% as.data.frame() yu.death <- filter( yu, CountyName==cnty) %>% select(date,predicted_deaths) %>% filter(min_death <= date & date <= Sys.Date() + 30) %>% rename(YuGroup = predicted_deaths) %>% as.data.frame() progress$inc(1/4) covid.xts <- xts(death[,-1],death$Most.Recent.Date) can.proj.xts <- xts(can.death[,-1],can.death$date) yu.proj.xts <- xts(yu.death[,-1],yu.death$date) df <- merge(covid.xts,can.proj.xts,yu.proj.xts) df$mean.proj <- rowMeans(df[,2:3], na.rm = TRUE) df$mean.proj <- ifelse(!is.na(df$covid.xts), NA, df$mean.proj) df <- as.data.table(df) %>% as.data.frame() df$period <- ifelse(!is.na(df$covid.xts), "solid", "dot") df$type <- ifelse(!is.na(df$covid.xts), "Est.", "Proj.") return(df) }) output$actual.cnty.death.box <- renderValueBox({ c <- names(canfipslist[match(input$select.county.death,canfipslist)]) cdt <- max(covid$Most.Recent.Date) current.deaths <- as.character(covid[which(covid$Most.Recent.Date == cdt & covid$County.Name == c),"Total.Count.Deaths"]) valueBox( paste0(format(as.numeric(current.deaths), big.mark = ",") ), paste0("Actual Deaths (NYTIMES DATA): ",cdt), color = "black") }) output$mean.cnty.proj.death.box <- renderValueBox({ df <- county.deaths() cdt <- max( df$index ) mean.proj <- df %>% slice(n()) %>% select(mean.proj) valueBox( format(round(mean.proj, digits = 0), big.mark = ","), paste0("30-Day Forecast through ", cdt), color = "blue") }) output$county.death.plot <- renderPlotly({ df <- county.deaths() cdt <- max(df[which(!is.na(df$covid.xts)),1]) today <- list(type = "line", y0 = 0, y1 = 1, yref = "paper", x0 = cdt, x1 = cdt, line = list(color = "black", dash = 'dash') ) p <- plot_ly(df, hoverinfo = 'text') %>% add_trace(x = df[[1]], y = df[[2]], name = "Actuals", type = 'scatter', mode = "lines+markers", hoverinfo = 'text', text = paste0(df[[1]], "<br>", "Actual Deaths (NYTIMES DATA): ", format(df[[2]], big.mark = ",") ), line = list(color = "black"), marker = list(color = "black", symbol= "circle") ) %>% add_trace(x = df[[1]], y = df[[3]], name = ~I(paste0("COVIDActNow - ",df$type)), type = 'scatter', mode = "lines", inherit = TRUE, line = list(color="orange"), linetype = ~I(period), hoverinfo = 'text', text = paste0(df[[1]], "<br>", "COVIDActNow Estimate: ", format(df[[3]], big.mark = ",") ) ) %>% add_trace(x = df[[1]], y = df[[4]], name = ~I(paste0("Berkeley Yu - ",df$type)), type = 'scatter', mode = "lines", inherit = TRUE, line = list(color="blue"), linetype = ~I(period), hoverinfo = 'text', text = paste0(df[[1]], "<br>", "Berkeley Estimate: ", format(df[[4]], big.mark = ",") ) ) %>% add_trace(x = df[[1]], y = df[[5]], name = "Mean Proj.", type = 'scatter', mode = "lines", hoverinfo = 'text', text = paste0(df[[1]], "<br>", "Mean Projection: ", format(round(df[[4]],0), big.mark = ",") ), line = list(color = ' ) %>% layout( title = as.character(counties[match(input$select.county.death, counties$fips),"county"]), xaxis = list(title = NULL, showline = TRUE, showgrid = FALSE, zeroline = FALSE ), yaxis = list(title = "Total Deaths", showline = TRUE, showgrid = FALSE, zeroline = FALSE), margin = list(l = 100), showlegend = TRUE, shapes = list(today) ) return(p) }) output$dlDeath.cnty <- downloadHandler( filename = function() { paste("Cumulative_Death_Forecasts_for_",names(canfipslist[match(input$select.county.death,canfipslist)]),Sys.Date(),'.csv', sep='') }, content = function(file) { c <- names(canfipslist[match(input$select.county.death,canfipslist)]) t <- c(paste("Cumulative Death Forecasts for ",c, sep = ""),rep("",ncol(county.deaths())-1)) tt <- c(paste("COVID Assessment Tool - Downloaded on",Sys.Date(), sep = " "),rep("",ncol(county.deaths())-1)) df <- county.deaths() %>% select(-c(period, type)) %>% rename(date = index) %>% as.data.frame() df[is.na(df)] <- 0 df[] <- lapply(df, as.character) l <- c("Date","Total Deaths") if ( "can.proj.xts" %in% names(county.deaths()) ) { l <- c(l, c("COVIDActNow")) } if ( "yu.proj.xts" %in% names(county.deaths()) ) { l <- c(l, c("Berkeley")) } if ( length(l) > 2 ) { l <- c(l, c("Mean") ) } s <- c("Please see the Technical Notes tab of the application for data sources.",rep("",ncol(county.deaths())-1)) p <- c(paste0("Prepared by: ",state_name," Department of Public Health"),rep("",ncol(county.deaths())-1)) dlm <- rbind(t, tt, l, df, s, p) write.table(dlm, file, row.names = F, col.names = F, quote = F, na= "NA", sep = ",") }) output$model.descrip.ts <- renderUI({ UKKC <- as.character(input$include_JHU_UKKC) model_descrip_list <- lapply(UKKC, function(i) { HTML(paste("<p>",as.character(scenarios[match(i, scenarios$colvar),2]),": ", as.character(scenarios[match(i, scenarios$colvar),4]),"</p>")) }) do.call(tagList, model_descrip_list) }) output$physical.select <- renderUI({ s <- as.character(state_name == input$county_ts) choice.list <- switch(s, "TRUE" = list ( "4/11/2020" = otherlist[1:2], "4/07/2020" = otherlist[3] ), list ( "4/11/2020" = otherlist[1:2] ) ) pickerInput( inputId = "include_JHU_UKKC", "Select Scenario", choices = choice.list, selected = c("strictDistancingNow", "weakDistancingNow"), options = list(`actions-box` = TRUE, noneSelectedText = "Select Scenario"), multiple = TRUE, choicesOpt = list( style = rep(("color: black; background: white; font-weight: bold;"),13)) ) }) output$epi_covid_select <- renderUI({ selectInput("select_COVID", "Select Actuals (THIS IS PLACEHOLDER DATA):", COVIDvar, selected = switch(input$selected_crosswalk, "1" = "COVID.19.Positive.Patients", "2" = "ICU.COVID.19.Positive.Patients", "3" = "Total.Count.Deaths") ) }) state.model.xts <- reactive({ c <- input$county_ts IHME_sts <- to_xts_IHME(IHME,state_name, switch(input$selected_crosswalk, "1" = "allbed_mean", "2" = "ICUbed_mean", "3" = "totdea_mean" )) IHME_sts.L <- to_xts_IHME(IHME,state_name, switch(input$selected_crosswalk, "1" = "allbed_lower", "2" = "ICUbed_lower", "3" = "totdea_lower" )) IHME_sts.H <- to_xts_IHME(IHME,state_name, switch(input$selected_crosswalk, "1" = "allbed_upper", "2" = "ICUbed_upper", "3" = "totdea_upper" )) CAN_sts <- to_xts_CAN(CAN_aws, c, switch(input$selected_crosswalk, "1" = "hospitalizations", "2" = "beds", "3" = "deaths" )) COVID_sts <- to_xts_COVID(covid, c) if (c != state_name) { all_ts <- suppressWarnings( merge.xts( CAN_sts, COVID_sts, fill = NA) ) } else { all_ts <- suppressWarnings( merge.xts( IHME_sts, IHME_sts.L, IHME_sts.H, CAN_sts, COVID_sts, fill = NA ) ) } all_ts <- all_ts["20200301/20201231"] return(all_ts) }) total.cnty.beds <- reactive({ c <- input$county_ts beds <- 100 }) jhu.no <- "UK.\\w+.\\d+_\\d+|.\\w+_\\w{4,}" jhu.M <- "UK.\\w+.\\d+_\\d+.M|.\\w+_\\w{4,}.M" jhu.lh <- "UK.\\w+.\\d[w].\\w+.[LH]|.\\w+_\\w{4,}.[LH]" jhu.lh.b <- "UK.\\w+.\\d+_\\d+.[LH]|.\\w+_\\w{4,}.[LH]" output$physical.graph <- renderDygraph({ df <- state.model.xts() dtrange <- paste(as.character(input$dateRange_ts), collapse = "/") chbx <- c() if ( input$actuals == TRUE) {chbx <- c(chbx,c(input$select_COVID)) } UKKC <- as.character(input$include_JHU_UKKC) if ( TRUE %in% grepl(jhu.no, UKKC) & input$physical.mmd == "M" ) { JHU_list <- UKKC[grep(jhu.no,UKKC)] chbx <- c(chbx, c(JHU_list) ) } else { JHU_list <- UKKC[grep(jhu.no,UKKC)] chbx <- c(chbx, c( as.character(lapply(seq_along(JHU_list), function(i) { paste0(as.character( JHU_list[[i]] ),".M" ) } ) ) ) ) } if (TRUE %in% grepl(jhu.no, UKKC) & input$physical.iqr == TRUE) { JHU_list <- UKKC[grep(jhu.no,UKKC)] chbx <- c(chbx, c( as.character(lapply(seq_along(JHU_list), function(i) {paste0(as.character( JHU_list[[i]] ),".L" ) } )) ), c( as.character(lapply(seq_along(JHU_list), function(i) {paste0(as.character( JHU_list[[i]] ),".H" ) } )) ) ) } if ( TRUE %in% grepl("IHME_sts", UKKC ) & input$county_ts == state_name ) { chbx <- chbx %>% c("IHME_sts") } if ( TRUE %in% grepl("IHME_sts", UKKC ) & input$IHME.iqr == TRUE & input$county_ts == state_name) { IHME <- "IHME_sts" chbx <- c(chbx, c( as.character(lapply(seq_along(IHME), function(i) {paste0(as.character( IHME[[i]] ),".L") } )) ), c( as.character(lapply(seq_along(IHME), function(i) {paste0(as.character( IHME[[i]] ),".H") } )) ) ) } if ( TRUE %in% grepl("weakDistancingNow|strictDistancingNow",UKKC) & input$county_ts %in% can_counties == TRUE ) { can <- UKKC[grep("weakDistancingNow|strictDistancingNow",UKKC)] chbx <- chbx %>% c(can) } df <- df[,c(chbx)] FUNC_JSFormatNumber <- "function(x) {return x.toString().replace(/(\\d)(?=(\\d{3})+(?!\\d))/g, '$1,')}" d <- dygraph(df, main = switch(input$selected_crosswalk, "1" = paste0(input$county_ts," COVID Hospitalizations"), "2" = paste0(input$county_ts," COVID ICU Patients"), "3" = paste0(input$county_ts," COVID Cumulative Deaths") )) if ( TRUE %in% grepl(jhu.lh, chbx) | TRUE %in% grepl(jhu.lh.b, chbx) ) { if ( input$physical.mmd == "M") { chbx.M <- chbx[grep(jhu.no,chbx)] chbx.M <- unique(str_remove(chbx.M, "\\.[LH]")) for (scenario in chbx.M) { d <- d %>% dySeries(c( paste0(scenario,".L"),paste0(scenario),paste0(scenario,".H")), label = names(modellist[match(scenario,modellist)]), fillGraph = FALSE) } } else { chbx.M <- chbx[grep(jhu.M,chbx)] chbx.M <- str_remove(chbx.M, ".M") for (scenario in chbx.M) { d <- d %>% dySeries(c( paste0(scenario,".L"),paste0(scenario,".M"),paste0(scenario,".H")), label = names(modellist[match(scenario,modellist)]), fillGraph = FALSE) } } } else { if ( input$physical.mmd == "M") { chbx.M <- chbx[grep(jhu.no,chbx)] for (scenario in chbx.M) { d <- d %>% dySeries(paste0(scenario), label = names(modellist[match(scenario,modellist)]), fillGraph = FALSE) } } else { chbx.M <- chbx[grep(jhu.M,chbx)] chbx.M <- str_remove(chbx.M, ".M") for (scenario in chbx.M) { d <- d %>% dySeries(paste0(scenario,".M"), label = names(modellist[match(scenario,modellist)]), fillGraph = FALSE) } } } if ( TRUE %in% grepl("IHME_sts.[LH]", chbx) ){ if ( "IHME_sts.L" %in% c(chbx) ) {d <- d %>% dySeries(c("IHME_sts.L","IHME_sts","IHME_sts.H"), label = 'IHME Model', fillGraph = FALSE) } } else { if ( "IHME_sts" %in% c(chbx) ) {d <- d %>% dySeries("IHME_sts", label = 'IHME Model', fillGraph = FALSE) } } if ( "weakDistancingNow" %in% c(chbx) ) {d <- d %>% dySeries("weakDistancingNow", label = 'CAN: Delay/Distancing', fillGraph = FALSE) } if ( "strictDistancingNow" %in% c(chbx) ) {d <- d %>% dySeries("strictDistancingNow", label = 'CAN: Shelter in Place', fillGraph = FALSE) } if ( "Total.Count.Deaths" %in% c(chbx) ) {d <- d %>% dySeries("Total.Count.Deaths", label = "Total Deaths", fillGraph= FALSE, drawPoints = TRUE, pointSize = 5, pointShape = "square", color = "black") } if ( "COVID.19.Positive.Patients" %in% c(chbx) ) {d <- d %>% dySeries("COVID.19.Positive.Patients", label = "Patients Positive for COVID-19", fillGraph= FALSE, drawPoints = TRUE, pointSize = 5, pointShape = "diamond", color = "black") } if ( "ICU.COVID.19.Positive.Patients" %in% c(chbx) ) {d <- d %>% dySeries("ICU.COVID.19.Positive.Patients", label = "ICU Patients Positive for COVID-19", fillGraph= FALSE, drawPoints = TRUE, pointSize = 5, pointShape = "hexagon", color = "black") } if ( input$selected_crosswalk == "1" & input$county_ts == state_name) { d <- d %>% dyLimit(50000, label = "Phase 1 Surge Capacity", labelLoc = c("left"), color = "black", strokePattern = "dashed") } else { if ( input$selected_crosswalk == "1" & !is.na(total.cnty.beds()) == TRUE ) { d <- d %>% dyLimit(total.cnty.beds(), label = "Total Licensed Beds", labelLoc = c("left"), color = "black", strokePattern = "dashed") } } d <- d %>% dyOptions(digitsAfterDecimal=0, strokeWidth = 3, connectSeparatedPoints = TRUE, drawGrid = FALSE) %>% dyAxis("y", axisLabelFormatter=htmlwidgets::JS(FUNC_JSFormatNumber), valueFormatter=htmlwidgets::JS(FUNC_JSFormatNumber)) %>% dyHighlight(highlightSeriesOpts = list(strokeWidth = 4)) %>% dyEvent(Sys.Date(), "Today", labelLoc = "top") %>% dyLegend(show = "always", labelsDiv = "legendDivID2", hideOnMouseOut = TRUE) %>% dyRangeSelector(height = 30, dateWindow = c((Sys.Date() - 30), as.Date("2020-12-31")) ) }) output$physical.graph.static <- renderPlot({ df <- state.model.xts()[ paste0( as.Date(input$physical.graph_date_window[[1]]),"/",as.Date(input$physical.graph_date_window[[2]]) ) ] chbx <- c() if ( input$actuals == TRUE) {chbx <- c(chbx,c(input$select_COVID)) } UKKC <- as.character(input$include_JHU_UKKC) if ( TRUE %in% grepl(jhu.no, UKKC) & input$physical.mmd == "M" ) { JHU_list <- UKKC[grep(jhu.no,UKKC)] chbx <- c(chbx, c(JHU_list) ) } else { JHU_list <- UKKC[grep(jhu.no,UKKC)] chbx <- c(chbx, c( as.character(lapply(seq_along(JHU_list), function(i) { paste0(as.character( JHU_list[[i]] ),".M" ) } ) ) ) ) } if (TRUE %in% grepl(jhu.no, UKKC) & input$physical.iqr == TRUE) { JHU_list <- UKKC[grep(jhu.no,UKKC)] chbx <- c(chbx, c( as.character(lapply(seq_along(JHU_list), function(i) {paste0(as.character( JHU_list[[i]] ),".L" ) } )) ), c( as.character(lapply(seq_along(JHU_list), function(i) {paste0(as.character( JHU_list[[i]] ),".H" ) } )) ) ) } if ( TRUE %in% grepl("IHME_sts", UKKC ) & input$county_ts == state_name ) { chbx <- chbx %>% c("IHME_sts") } if ( TRUE %in% grepl("IHME_sts", UKKC ) & input$IHME.iqr == TRUE & input$county_ts == state_name) { IHME <- "IHME_sts" chbx <- c(chbx, c( as.character(lapply(seq_along(IHME), function(i) {paste0(as.character( IHME[[i]] ),".L") } )) ), c( as.character(lapply(seq_along(IHME), function(i) {paste0(as.character( IHME[[i]] ),".H") } )) ) ) } if ( TRUE %in% grepl("weakDistancingNow|strictDistancingNow",UKKC) & input$county_ts %in% can_counties == TRUE ) { can <- UKKC[grep("weakDistancingNow|strictDistancingNow",UKKC)] chbx <- chbx %>% c(can) } df <- df[,c(chbx)] colors <- c("No Intervention"= "black", "IHME Model" = " "CAN: Shelter in Place" = " "CAN: Delay/Distancing" = " 'JHU: NPIs 30-40% Effective' = " 'JHU: NPIs 40-50% Effective' = " 'JHU: NPIs 50-60% Effective' = " 'JHU: NPIs 60-70% Effective' = " "JHU: Continuing Lockdown" = " 'JHU: Slow-paced Reopening' = " 'JHU: Moderate-paced Reopening' = " 'JHU: Fast-paced Reopening' = " "Total Deaths" = "black", "Patients Positive for COVID-19" = "black", "ICU Patients Positive for COVID-19" = "black" ) p <- ggplot() if (input$selected_crosswalk == "1" & input$drop_hline == TRUE & input$county_ts == state_name) { p <- p + geom_line(df, mapping = aes(x= Index, y = 50000), color = "black", linetype = "dashed") + geom_text(aes(x = as.Date(input$physical.graph_date_window[[1]]), y= 50000, label = "Phase 1 Surge Capacity"), hjust = -0.1, vjust = -0.3) } else { if ( input$selected_crosswalk == "1" & !is.na(total.cnty.beds()) == TRUE ) { p <- p + geom_line(df, mapping = aes(x= Index, y = total.cnty.beds()), color = "black", linetype = "dashed") + geom_text(aes(x = as.Date(input$physical.graph_date_window[[1]]), y= total.cnty.beds(), label = "Total Licensed Beds"), hjust = -0.1, vjust = -0.3) } } if ( TRUE %in% grepl(jhu.no, chbx)) { chbx.M <- chbx[grep(jhu.no,chbx)] chbx.M <- unique(str_remove(chbx.M, "\\.[MLH]")) for (scenario in chbx.M) { c <- as.character(colors[match(names(modellist[match(scenario,modellist)]),names(colors))]) if ( scenario %in% c(chbx) ) { p <- p + geom_line(df, mapping = aes_string(x="Index", y=scenario, color = shQuote(names(modellist[match(scenario,modellist)])) ), size = 1.5, linetype = "solid") } if ( paste0(scenario,".M") %in% c(chbx) ) { p <- p + geom_line(df, mapping = aes_string(x="Index", y=paste0(scenario,".M"), color = shQuote(names(modellist[match(scenario,modellist)])) ), size = 1.5, linetype = "solid") } if ( paste0(scenario,".L") %in% c(chbx) ) { p <- p + geom_ribbon(df, mapping = aes_string(x ="Index", ymin = paste0(scenario,".L"), ymax = paste0(scenario,".H") ), fill=c, color = c, alpha = 0.2) } } } if ( "IHME_sts" %in% c(chbx) ) { p <- p + geom_line(df, mapping = aes(x=Index, y=IHME_sts, color = "IHME Model"), size = 1.5, linetype = "solid") } if ( "IHME_sts.L" %in% c(chbx) ) { p <- p + geom_ribbon(df, mapping = aes(x = Index, ymin = IHME_sts.L, ymax = IHME_sts.H), fill=" if ( "strictDistancingNow" %in% c(chbx) ) { p <- p + geom_point(df, mapping = aes(x=Index, y=strictDistancingNow, color = "CAN: Shelter in Place") ) } if ( "weakDistancingNow" %in% c(chbx) ) { p <- p + geom_point(df, mapping = aes(x=Index, y=weakDistancingNow, color = "CAN: Delay/Distancing") ) } if ( "Total.Count.Deaths" %in% c(chbx) ) {p <- p + geom_point(df, mapping = aes(x = Index, y = Total.Count.Deaths, color = "Total Deaths"), shape = 15, fill = "black", size = 3 ) } if ( "COVID.19.Positive.Patients" %in% c(chbx) ) {p <- p + geom_point(df, mapping = aes(x = Index, y = COVID.19.Positive.Patients, color = "Patients Positive for COVID-19"), shape = 23, fill = "black", size = 3 ) } if ( "ICU.COVID.19.Positive.Patients" %in% c(chbx) ) {p <- p + geom_point(df, mapping = aes(x = Index, y = ICU.COVID.19.Positive.Patients, color = "ICU Patients Positive for COVID-19"), shape = 19, fill = "black", size = 3 ) } p <- p + scale_y_continuous(labels = scales::comma) p <- p + labs(x = "Date", y = switch(input$selected_crosswalk, "1" = "Hospital Bed Occupancy", "2" = "ICU Bed Occupancy", "3" = "Cumulative Deaths"), color = "Legend") + scale_color_manual(values = colors) + ggtitle(switch(input$selected_crosswalk, "1" = paste0(input$county_ts," COVID Hospitalizations"), "2" = paste0(input$county_ts," COVID ICU Patients"), "3" = paste0(input$county_ts," COVID Cumulative Deaths") )) + theme(plot.title = element_text(size = 18, face = "bold"), axis.title = element_text(face = "bold", size = 18, colour = "black"), axis.text.x = element_text(face = "bold", color = "black", size = 18), axis.text.y = element_text(face = "bold", color = "black", size = 18), axis.line = element_line(color = "black", size = 1, linetype = "solid"), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.border = element_blank(), panel.background = element_blank(), legend.text=element_text(size=14), legend.position = "bottom" ) return(p) }) static.plot.data <- reactive({ df <- state.model.xts()[ paste0( as.Date(input$physical.graph_date_window[[1]]),"/",as.Date(input$physical.graph_date_window[[2]]) ) ] chbx <- c() if ( input$actuals == TRUE) {chbx <- c(chbx,c(input$select_COVID)) } UKKC <- as.character(input$include_JHU_UKKC) if ( TRUE %in% grepl("UK.\\w+.\\d+_\\d+|.\\w+_\\w{4,}", UKKC) & input$physical.mmd == "M" ) { JHU_list <- UKKC[grep("UK.\\w+.\\d+_\\d+|.\\w+_\\w{4,}",UKKC)] chbx <- c(chbx, c(JHU_list) ) } else { JHU_list <- UKKC[grep("UK.\\w+.\\d+_\\d+|.\\w+_\\w{4,}",UKKC)] chbx <- c(chbx, c( as.character(lapply(seq_along(JHU_list), function(i) { paste0(as.character( JHU_list[[i]] ),".M" ) } ) ) ) ) } if (TRUE %in% grepl("UK.\\w+.\\d+_\\d+|.\\w+_\\w{4,}", UKKC) & input$physical.iqr == TRUE) { JHU_list <- UKKC[grep("UK.\\w+.\\d+_\\d+|.\\w+_\\w{4,}",UKKC)] chbx <- c(chbx, c( as.character(lapply(seq_along(JHU_list), function(i) {paste0(as.character( JHU_list[[i]] ),".L" ) } )) ), c( as.character(lapply(seq_along(JHU_list), function(i) {paste0(as.character( JHU_list[[i]] ),".H" ) } )) ) ) } if ( TRUE %in% grepl("IHME_sts", UKKC ) & input$county_ts == state_name ) { chbx <- chbx %>% c("IHME_sts") } if ( TRUE %in% grepl("IHME_sts", UKKC ) & input$IHME.iqr == TRUE & input$county_ts == state_name) { IHME <- "IHME_sts" chbx <- c(chbx, c( as.character(lapply(seq_along(IHME), function(i) {paste0(as.character( IHME[[i]] ),".L") } )) ), c( as.character(lapply(seq_along(IHME), function(i) {paste0(as.character( IHME[[i]] ),".H") } )) ) ) } if ( TRUE %in% grepl("weakDistancingNow|strictDistancingNow",UKKC) & input$selected_crosswalk != "2") { can <- UKKC[grep("weakDistancingNow|strictDistancingNow",UKKC)] chbx <- chbx %>% c(can) } df <- df[,c(chbx)] %>% data.frame() %>% mutate(Date = seq(as.Date(input$physical.graph_date_window[[1]]),as.Date(input$physical.graph_date_window[[2]]), by = "day")) df }) output$dlScenario <- downloadHandler( filename = function () { paste0("COVID_Scenarios_",input$county_ts,".csv") }, content = function(file) { t <- c(paste("Long-term COVID Scenarios for ",input$county_ts, sep = ""),rep("",ncol(static.plot.data())-1)) tt <- c(paste("COVID Assessment Tool - Downloaded on",Sys.Date(), sep = " "),rep("",ncol(static.plot.data())-1)) l <- names(static.plot.data()) df <- static.plot.data() df[is.na(df)] <- 0 df[] <- lapply(df, as.character) s <- c("Please see the Technical Notes tab of the application for data sources.",rep("",ncol(static.plot.data())-1)) p <- c(paste0("Prepared by: ",state_name," Department of Public Health"), rep("",ncol(static.plot.data())-1)) dlm <- rbind(t, tt, l, df, s, p) write.table(dlm, file, row.names = F, col.names = F, quote = F, na= "NA", sep = ",") } ) }
loadDataADaMSDTM <- function(files, convertToDate = FALSE, dateVars = "DTC$", verbose = TRUE, encoding = "UTF-8", ...){ names(files) <- toupper(file_path_sans_ext(basename(files))) idxDuplFiles <- duplicated(names(files)) if(any(idxDuplFiles)) warning(sum(idxDuplFiles), " duplicated file name. These files will have the same name in the 'dataset' column.") readFct <- function(file, ...) switch(file_ext(file), 'sas7bdat' = read_sas(file, encoding = encoding, ...), 'xpt' = read_xpt(file, ...), stop(paste("File with extension:", file_ext(file), "currently not supported.")) ) dataList <- sapply(names(files), function(name){ if(verbose) message("Import ", name, " dataset.") data <- as.data.frame(readFct(files[name], ...)) if(nrow(data) > 0){ data <- cbind(data, DATASET = name) if(convertToDate){ colsDate <- grep(dateVars, colnames(data), value = TRUE) data[, colsDate] <- lapply(colsDate, function(col){ convertToDateTime(data[, col], colName = col) }) } colnames(data) <- toupper(colnames(data)) }else if(verbose) warning("Dataset ", name, " is empty.") data }, simplify = FALSE) dataList <- dataList[!sapply(dataList, is.null)] labelVars <- c(getLabelVars(dataList), 'DATASET' = "Dataset Name") attr(dataList, "labelVars") <- labelVars return(dataList) } convertToDateTime <- function(x, format = c("%Y-%m-%dT%H:%M", "%Y-%m-%d"), colName = NULL, verbose = TRUE){ if(is.character(x)){ isEmpty <- function(x) is.na(x) | x == "" }else{ isEmpty <- function(x) is.na(x) } newTime <- .POSIXct(rep(NA_real_, length(x))) for(formatI in format){ idxMissingRecords <- which(is.na(newTime) & !isEmpty(x)) newTime[idxMissingRecords] <- as.POSIXct(x[idxMissingRecords], format = formatI) if(all(!is.na(newTime[!isEmpty(x)]))) break } if(any(is.na(newTime[!isEmpty(x)]))){ warning( "Vector", if(!is.null(colName)) paste0(": ", colName), " not of specified calendar date format, so is not converted to date/time format.", immediate. = TRUE, call. = FALSE ) newTime <- x }else if(verbose) message("Convert vector", if(!is.null(colName)) paste0(": ", colName), " to calendar date/time format.") return(newTime) } getLabelVar <- function(var, data = NULL, labelVars = NULL, label = NULL){ res <- if(!is.null(var)){ if(is.null(data) & is.null(labelVars) & is.null(label)){ res <- var names(res) <- var res }else{ var <- unname(var) res <- sapply(var, function(x){ attrX <- if(!is.null(label)){ if(!is.null(names(label)) && x %in% names(label)){ label[x] }else if(is.null(names(label)) && length(label) == 1 && length(var) == 1){ label } } if((is.null(attrX) || is.na(attrX)) && !is.null(labelVars)){ attrX <- labelVars[x] } if(is.null(attrX) || is.na(attrX)) attrX <- attributes(data[[x]])$label attrX <- unname(attrX) ifelse(is.null(attrX) || is.na(attrX), x, attrX) }) } } return(res) } getLabelVars <- function(data, labelVars = NULL) { if(!missing(data)){ if(!is.data.frame(data)){ labelVarsFromDataList <- lapply(data, getLabelVars) labelVarsFromData <- unlist(labelVarsFromDataList) names(labelVarsFromData) <- unlist(lapply(labelVarsFromDataList, names)) labelVars <- c(labelVars, labelVarsFromData) labelVars <- labelVars[!duplicated(names(labelVars))] return(labelVars) } labelVarsFromData <- unlist( sapply(colnames(data), function(col) attributes(data[[col]])$label, simplify = FALSE ) ) labelVars <- c(labelVars, labelVarsFromData) labelVars <- labelVars[!duplicated(names(labelVars))] } return(labelVars) } getLabelParamcd <- function(paramcd, data, paramcdVar = "PARAMCD", paramVar = "PARAM"){ vars <- c(paramcdVar, paramVar) varsNotInData <- vars[which(!vars %in% colnames(data))] if(length(varsNotInData) > 0) stop(paste("Parameters:", toString(sQuote(varsNotInData)), "not available in 'data', you may need to adapt the", "parameters: 'paramVar'/'paramcdVar'.")) label <- data[match(paramcd, data[, paramcdVar]), paramVar] names(label) <- paramcd res <- sapply(names(label), function(xName){ x <- as.character(label[xName]) ifelse(is.null(x) || is.na(x), xName, x) }) return(res) }
prop.cint <- function(k, n, method=c("binomial", "z.score"), correct=TRUE, conf.level=0.95, alternative=c("two.sided", "less", "greater")) { method <- match.arg(method) alternative <- match.arg(alternative) if (any(k < 0) || any(k > n) || any(n < 1)) stop("arguments must be integer vectors with 0 <= k <= n") if (any(conf.level <= 0) || any(conf.level > 1)) stop("conf.level must be in range [0,1]") l <- max(length(k), length(n), length(conf.level)) if (length(k) < l) k <- rep(k, length.out=l) if (length(n) < l) n <- rep(n, length.out=l) if (length(conf.level) < l) conf.level <- rep(conf.level, length.out=l) if (method == "binomial") { alpha <- if (alternative == "two.sided") (1 - conf.level) / 2 else (1 - conf.level) lower <- safe.qbeta(alpha, k, n - k + 1) upper <- safe.qbeta(alpha, k + 1, n - k, lower.tail=FALSE) cint <- switch(alternative, two.sided = data.frame(lower = lower, upper = upper), less = data.frame(lower = 0, upper = upper), greater = data.frame(lower = lower, upper = 1)) } else { alpha <- if (alternative == "two.sided") (1 - conf.level) / 2 else (1 - conf.level) z <- qnorm(alpha, lower.tail=FALSE) yates <- if (correct) 0.5 else 0.0 k.star <- k - yates k.star <- pmax(0, k.star) A <- n + z^2 B <- -2 * k.star - z^2 C <- k.star^2 / n lower <- solve.quadratic(A, B, C, nan.lower=0)$lower k.star <- k + yates k.star <- pmin(n, k.star) A <- n + z^2 B <- -2 * k.star - z^2 C <- k.star^2 / n upper <- solve.quadratic(A, B, C, nan.upper=1)$upper cint <- switch(alternative, two.sided = data.frame(lower = lower, upper = upper), less = data.frame(lower = rep(0,l), upper = upper), greater = data.frame(lower = lower, upper = rep(1,l))) } cint } safe.qbeta <- function (p, shape1, shape2, lower.tail=TRUE) { stopifnot(length(p) == length(shape1) && length(p) == length(shape2)) is.0 <- shape1 <= 0 is.1 <- shape2 <= 0 ok <- !(is.0 | is.1) x <- rep_len(NA, length(p)) x[ok] <- qbeta(p[ok], shape1[ok], shape2[ok], lower.tail=lower.tail) x[is.0 & !is.1] <- 0 x[is.1 & !is.0] <- 1 x }
`ordivector` <- function(ordiplot,spec,lty=2,...) { speciescoord <- scores(ordiplot, display="species") speciesselect <- speciescoord[rownames(speciescoord)==spec] sitescoord <- scores(ordiplot, display="sites") b1 <- speciesselect[2]/speciesselect[1] b2 <- -1/b1 calc <- array(dim=c(nrow(sitescoord),3)) calc[,3] <- sitescoord[,2]-b2*sitescoord[,1] calc[,1] <- calc[,3]/(b1-b2) calc[,2] <- b1*calc[,1] for (i in 1:nrow(sitescoord)) { graphics::segments(sitescoord[,1], sitescoord[,2], calc[,1], calc[,2], lty=lty) } graphics::abline(0, b1, lty=lty) graphics::arrows(0, 0, speciesselect[1], speciesselect[2],lty=1,...) }
na.omit.ltraj <- function(object, ...) { if (!inherits(object, "ltraj")) stop("ltraj should be of class ltraj") p4s <- .checkp4(object) info <- infolocs(object) for (i in 1:length(object)) { x <- object[[i]] if (!is.null(info)) info[[i]] <- info[[i]][(!is.na(x[,1]))&(!is.na(x[,2])),,drop=FALSE] object[[i]] <- x[(!is.na(x[,1]))&(!is.na(x[,2])),] } if (!is.null(info)) infolocs(object) <- info res <- rec(object) attr(res, "proj4string") <- p4s return(res) }