code
stringlengths
1
13.8M
ci.RateD <- function(x1, x2, e1, e2, cov.prob=0.95, BB.grdnum=2000, midp=T) {if(x1*x2==0) {lambda1=(x1+0.5)/(e1+1) lambda2=(x2+0.5)/(e2+1) delta=lambda2-lambda1 sigma=sqrt(lambda1/(e1+1)+lambda2/(e2+1)) } if(x1*x2>0) {lambda1=x1/e1 lambda2=x2/e2 delta=lambda2-lambda1 sigma=sqrt(lambda1/e1+lambda2/e2) } lower=min(delta-5*sigma, -1/e1-1/e2) upper=max(delta+5*sigma, 1/e1+1/e2) delta.grd=sort(unique(c(0, seq(lower, upper, length=BB.grdnum)))) BB.grdnum=length(delta.grd) fit=prateD.exact(x1, x2, e1, e2, delta.grd, midp=midp) pv1=fit$pv1 pv2=fit$pv2 for(j in 1:BB.grdnum) pv1[BB.grdnum-j+1]=max(pv1[1:(BB.grdnum-j+1)]); pv2[j]=max(pv2[j:BB.grdnum]) lower=range(delta.grd[pv1>(1-cov.prob)/2 & pv2>(1-cov.prob)/2])[1] upper=range(delta.grd[pv1>(1-cov.prob)/2 & pv2>(1-cov.prob)/2])[2] est=delta.grd[abs(pv2-pv1)==min(abs(pv2-pv1))][1] id0=(1:BB.grdnum)[delta.grd==0] p=min(1, 2*min(pv1[id0], pv2[id0])) status=1 if(min(delta.grd)==lower || max(delta.grd)==upper) status=0 return(list(est=est, lower=lower, upper=upper, status=status, p=p)) }
library(knitr) library(qsimulatR) knitr::opts_chunk$set(fig.align='center', comment='') x <- qstate(nbits=2) x CatInBox <- qstate(nbits=1, basis=c("|dead>", "|alive>")) CatInBox CatInBox <- qstate(nbits=1, basis=c("|dead>", "|alive>"), coefs=as.complex(c(1/sqrt(2), 1/sqrt(2)))) CatInBox plot(x, qubitnames=c("bit1", "bit2")) x <- qstate(nbits=2) y <- H(1) * x y plot(y) myGate <- function(bit) { methods::new("sqgate", bit=as.integer(bit), M=array(as.complex(c(1,0,0,-1)), dim=c(2,2)), type="myGate") } z <- myGate(1) * y z truth.table(X, 1) truth.table(CNOT, 2) z <- CNOT(c(1,2)) * y z plot(z) CX12 <- cqgate(bits=c(1L, 2L), gate=X(2L)) z <- CX12 * y z z <- SWAP(c(1,2)) * y z plot(z) z <- SWAP(c(2,1)) * y z x <- H(1) *(H(2) * qstate(3)) x y <- CCNOT(c(1,2,3)) * x y plot(y) y <- CSWAP(c(1,2,3)) * x y plot(y) myswap <- function(bits){ function(x){ CNOT(bits) * (CNOT(rev(bits)) * (CNOT(bits) * x)) } } truth.table(myswap, 2) circuit <- myswap(1:2) plot(circuit(qstate(2))) res <- measure(y, 1) summary(res) plot(res$psi) rv <- measure(y, 3, rep=1000)$value hist(rv, freq=FALSE, main="Probability for Qubit 3") filename <- paste0(tempdir(), "/circuit.py") export2qiskit(y, filename=filename) cat(readLines(filename), sep = '\n') file.remove(filename)
get_dispatch <- function(obj) UseMethod("get_dispatch") get_dispatch.dispatcher <- function(obj) obj[['dispatch']]
normalVaR <- function(periodPercentReturns, probability = 0.95) { stopifnot(isUnivariate(periodPercentReturns)) R = periodPercentReturns ans = mean(R) - qnorm(probability) * nVariance(R) names(ans) = paste(probability, "normal VaR") ans } normalVaRRatio <- function(periodPercentReturns, probability = 0.95, nAssets = 1) { stopifnot(isUnivariate(periodPercentReturns)) R = periodPercentReturns normalVaR = normalVaR(R, probability) ans = normalVaR / nAssets names(ans) = paste(probability, "normal VaR Ratio") ans } normalRewardToVaR <- function(periodPercentReturns, targetReturn = 0, probability = 0.95, method = c("geometric", "arithmetic"), scale = c("quarterly", "monthly", "weekly", "daily"), nAssets = 1) { stopifnot(isUnivariate(periodPercentReturns)) method = match.arg(method) Scale = .scale(match.arg(scale)) R = periodPercentReturns targetReturn = targetReturn * Scale Return = annualisedReturn(R, method, scale) - targetReturn Risk = normalVaRRatio(R, probability) ans = Return / Risk names(ans) = paste(probability, "Normal Reward to VaR") ans } conditionalVaRRatio <- function(periodPercentReturns, targetReturn = 0, probability = 0.95, method = c("geometric", "arithmetic"), scale = c("quarterly", "monthly", "weekly", "daily")) { stopifnot(isUnivariate(periodPercentReturns)) method = match.arg(method) Scale = .scale(match.arg(scale)) R = periodPercentReturns Return = annualisedReturn(R, method, scale) - targetReturn * Scale Risk = ans = Return / Risk names(ans) = "Conditional VaR Ratio" ans } conditionalSharpeRatio <- function(periodPercentReturns, targetReturn = 0, probability = 0.95, method = c("geometric", "arithmetic"), scale = c("quarterly", "monthly", "weekly", "daily")) { stopifnot(isUnivariate(periodPercentReturns)) method = match.arg(method) Scale = .scale(match.arg(scale)) R = periodPercentReturns targetReturn = targetReturn * Scale Return = annualisedReturn(R, method, scale) - targetReturn Risk = ans = Return / Risk names(ans) = "Conditional Sharpe Ratio" ans } modifiedVaR <- function(periodPercentReturns, targetReturn = 0, probability = 0.95, method = c("geometric", "arithmetic"), scale = c("quarterly", "monthly", "weekly", "daily")) { stopifnot(isUnivariate(periodPercentReturns)) method = match.arg(method) Scale = .scale(match.arg(scale)) R = periodPercentReturns M = mean(R) S = nSkewness(R) KE = excessKurtosis(R) V = nVariance(R) zc = -qnorm(probability) Return = annualisedReturn(R, method, scale) - targetReturn Risk = M + V * ( zc + ((zc^2-1)/6)*S + ((zc^3-3*zc)/24)*KE - ((2*zc^3-5*zc)/36) * S^2 ) ans = Return / Risk names(ans) = "Cornish Fischer VaR" ans } modSharpeRatio <- function(periodPercentReturns, targetReturn = 0, probability = 0.95, method = c("geometric", "arithmetic"), scale = c("quarterly", "monthly", "weekly", "daily")) { stopifnot(isUnivariate(periodPercentReturns)) method = match.arg(method) Scale = .scale(match.arg(scale)) R = periodPercentReturns Return = annualisedReturn(R, method, scale) - targetReturn * Scale Risk = modifiedVaR(R, targetReturn, probability, method, scale) ans = Return / Risk names(ans) = "Modified Sharpe Ratio" ans }
extract_EAP_by_array <-function(StanS4class, name.of.parameter ){ if (class("name.of.parameter")=="character"){ name.of.parameter <-substitute(name.of.parameter) } fit <- methods::as(StanS4class, "stanfit") extract.expression.dim <- paste( "length(dim(extract(fit,par=c(name.of.parameter ))[[1]]))-1" ,sep = "") foo.dim <- parse(text = extract.expression.dim) dim<- eval(foo.dim) if (dim==0) { extract.expression <- paste( "mean (extract(fit)$",name.of.parameter, ",)" ,sep = "") } if (dim==1) { extract.expression <- paste( "apply(extract(fit)$",name.of.parameter, ", MARGIN = 2, mean)" ,sep = "") } if (dim==2){ extract.expression <- paste( "apply(extract(fit)$",name.of.parameter, ", MARGIN = c(2,3), mean)" ,sep = "") } if (dim==3){ extract.expression <- paste( "apply(extract(fit)$",name.of.parameter, ", MARGIN = c(2,3,4), mean)" ,sep = "") } if (dim==4){ extract.expression <- paste( "apply(extract(fit)$",name.of.parameter, ", MARGIN = c(2,3,4,5), mean)" ,sep = "") } foo <- parse(text = extract.expression ) e<- eval(foo) return(e) } extract_EAP_CI <-function(StanS4class, parameter.name, dimension.of.parameter, dig=5, summary=TRUE ){ fit <- methods::as(StanS4class, "stanfit") C <-dimension.of.parameter if (C==1){ EAP <- signif( as.data.frame(summary(fit)[[1]])[parameter.name,"mean"], digits = dig) CI.lower <- signif( as.data.frame(summary(fit)[[1]])[parameter.name,"2.5%"], digits = dig) CI.upper <- signif( as.data.frame(summary(fit)[[1]])[parameter.name,"97.5%"], digits = dig) l<-list( name=parameter.name, EAP=EAP, CI.lower=CI.lower, CI.upper=CI.upper) names(l) <- c( "parameter.name", paste(parameter.name,".EAP",sep = ""), paste(parameter.name,".CI.lower",sep = ""), paste(parameter.name,".CI.upper",sep = "") ) d <- as.data.frame(l) if (summary==TRUE) print(knitr::kable(d, format = "pandoc")) return(l) }else name <- paste(parameter.name,".name",sep = "") EAP <- paste(parameter.name,".EAP",sep = "") CI.lower <- paste(parameter.name,".CI.lower",sep = "") CI.upper <- paste(parameter.name,".CI.upper",sep = "") assign(name, vector()) assign(EAP, vector()) assign(CI.lower, vector()) assign(CI.upper, vector()) for (cd in 1:C) { name[cd] <- paste(parameter.name,"[",cd,"]", sep = "") EAP[cd] <- signif( as.data.frame(summary(fit)[[1]])[name[cd],"mean"], digits = dig) CI.lower[cd]<- signif( as.data.frame(summary(fit)[[1]])[name[cd],"2.5%"], digits = dig) CI.upper[cd]<- signif( as.data.frame(summary(fit)[[1]])[name[cd],"97.5%"], digits = dig) } l<-list( name = name, EAP = as.numeric(EAP), CI.lower=as.numeric(CI.lower), CI.upper=as.numeric(CI.upper) ) names(l) <- c( paste(parameter.name,".name",sep = ""), paste(parameter.name,".EAP",sep = ""), paste(parameter.name,".CI.lower",sep = ""), paste(parameter.name,".CI.upper",sep = "") ) d <- as.data.frame(l) if (summary==TRUE) print(knitr::kable(d, format = "pandoc")) return(l) } extract_estimates_MRMC <- function(StanS4class,dig=3){ C <-StanS4class@dataList$C M <-StanS4class@dataList$M Q <-StanS4class@dataList$Q fit <- methods::as(StanS4class, "stanfit") name.z <- vector() z.EAP <- vector() z.CI.lower<- vector() z.CI.upper<- vector() for (cd in 1:C) { name.z[cd] <- paste("z[",cd,"]", sep = "") z.EAP[cd] <- signif( as.data.frame(summary(fit)[[1]])[name.z[cd],"mean"], digits = dig) z.CI.lower[cd]<- signif( as.data.frame(summary(fit)[[1]])[name.z[cd],"2.5%"], digits = dig) z.CI.upper[cd]<- signif( as.data.frame(summary(fit)[[1]])[name.z[cd],"97.5%"], digits = dig) } dz.list <- extract_EAP_CI(StanS4class = fit, parameter.name = "dz", dimension.of.parameter = C-1, dig = dig, summary = FALSE) name.dz <- dz.list$dz.name dz.EAP <- dz.list$dz.EAP dz.CI.lower <- dz.list$dz.CI.lower dz.CI.upper <- dz.list$dz.CI.upper name.mu <- array(0,dim = c(M,Q)) mu.EAP <- array(0,dim = c(M,Q)) mu.CI.lower <- array(0,dim = c(M,Q)) mu.CI.upper <- array(0,dim = c(M,Q)) for (md in 1:M) { for (qd in 1:Q) { name.mu[md,qd] <- paste("mu[",md,",",qd,"]", sep = "") mu.EAP[md,qd] <- signif( as.data.frame(summary(fit)[[1]])[name.mu[md,qd],"mean"], digits = dig) mu.CI.lower[md,qd]<- signif( as.data.frame(summary(fit)[[1]])[name.mu[md,qd],"2.5%"], digits = dig) mu.CI.upper[md,qd]<- signif( as.data.frame(summary(fit)[[1]])[name.mu[md,qd],"97.5%"], digits = dig) } } name.v <- array(0,dim = c(M,Q)) v.EAP <- array(0,dim = c(M,Q)) v.CI.lower<- array(0,dim = c(M,Q)) v.CI.upper<- array(0,dim = c(M,Q)) for (md in 1:M) { for (qd in 1:Q) { name.v[md,qd] <- paste("v[",md,",",qd,"]", sep = "") v.EAP[md,qd] <- signif( as.data.frame(summary(fit)[[1]])[name.v[md,qd],"mean"], digits = dig) v.CI.lower[md,qd]<- signif( as.data.frame(summary(fit)[[1]])[name.v[md,qd],"2.5%"], digits = dig) v.CI.upper[md,qd]<- signif( as.data.frame(summary(fit)[[1]])[name.v[md,qd],"2.5%"], digits = dig) } } name.ppp <- array(0,dim = c(C,M,Q)) ppp.EAP <- array(0,dim = c(C,M,Q)) ppp.CI.lower <- array(0,dim = c(C,M,Q)) ppp.CI.upper <- array(0,dim = c(C,M,Q)) for (cd in 1:C) { for (md in 1:M) { for (qd in 1:Q) { name.ppp[cd,md,qd] <- paste("ppp[",cd,",",md,",",qd,"]", sep = "") ppp.EAP[cd,md,qd] <- signif( as.data.frame(summary(fit)[[1]])[name.ppp[cd,md,qd],"mean"], digits = dig) ppp.CI.lower[cd,md,qd]<- signif( as.data.frame(summary(fit)[[1]])[name.ppp[cd,md,qd],"2.5%"], digits = dig) ppp.CI.upper[cd,md,qd]<- signif( as.data.frame(summary(fit)[[1]])[name.ppp[cd,md,qd],"2.5%"], digits = dig) } } } w.list <- extract_EAP_CI(StanS4class = fit, parameter.name = "w",dimension.of.parameter = 1,dig = dig, summary = FALSE) name.w <- w.list$w.name w.EAP <- w.list$w.EAP w.CI.lower <- w.list$w.CI.lower w.CI.upper <- w.list$w.CI.upper dl.list <- extract_EAP_CI(StanS4class = fit, parameter.name = "dl",dimension.of.parameter = C,dig = dig, summary = FALSE) name.dl <- dl.list$dl.name dl.EAP <- dl.list$dl.EAP dl.CI.lower <- dl.list$dl.CI.lower dl.CI.upper <- dl.list$dl.CI.upper l.list <- extract_EAP_CI(StanS4class = fit, parameter.name = "l",dimension.of.parameter = C,dig = dig, summary = FALSE) name.l <- l.list$l.name l.EAP <- l.list$l.EAP l.CI.lower <- l.list$l.CI.lower l.CI.upper <- l.list$l.CI.upper A.list <- extract_EAP_CI(StanS4class = fit, parameter.name = "A",dimension.of.parameter = M,dig = dig, summary = FALSE) name.A <- A.list$A.name A.EAP <- A.list$A.EAP A.CI.lower <- A.list$A.CI.lower A.CI.upper <- A.list$A.CI.upper name.AA <- array(0,dim = c(M,Q)) AA.EAP <- array(0,dim = c(M,Q)) AA.CI.lower<- array(0,dim = c(M,Q)) AA.CI.upper<- array(0,dim = c(M,Q)) for (md in 1:M) { for (qd in 1:Q) { name.AA[md,qd] <- paste("AA[",md,",",qd,"]", sep = "") AA.EAP[md,qd] <- signif( as.data.frame(summary(fit)[[1]])[name.AA[md,qd],"mean"], digits = dig) AA.CI.lower[md,qd]<- signif( as.data.frame(summary(fit)[[1]])[name.AA[md,qd],"2.5%"], digits = dig) AA.CI.upper[md,qd]<- signif( as.data.frame(summary(fit)[[1]])[name.AA[md,qd],"2.5%"], digits = dig) } } name.aa <- array(0,dim = c(M,Q)) aa.EAP <- array(0,dim = c(M,Q)) aa.CI.lower<- array(0,dim = c(M,Q)) aa.CI.upper<- array(0,dim = c(M,Q)) for (md in 1:M) { for (qd in 1:Q) { name.aa[md,qd] <- paste("aa[",md,",",qd,"]", sep = "") aa.EAP[md,qd] <- signif( as.data.frame(summary(fit)[[1]])[name.aa[md,qd],"mean"], digits = dig) aa.CI.lower[md,qd]<- signif( as.data.frame(summary(fit)[[1]])[name.aa[md,qd],"2.5%"], digits = dig) aa.CI.upper[md,qd]<- signif( as.data.frame(summary(fit)[[1]])[name.aa[md,qd],"2.5%"], digits = dig) } } name.bb <- array(0,dim = c(M,Q)) bb.EAP <- array(0,dim = c(M,Q)) bb.CI.lower<- array(0,dim = c(M,Q)) bb.CI.upper<- array(0,dim = c(M,Q)) for (md in 1:M) { for (qd in 1:Q) { name.bb[md,qd] <- paste("bb[",md,",",qd,"]", sep = "") bb.EAP[md,qd] <- signif( as.data.frame(summary(fit)[[1]])[name.bb[md,qd],"mean"], digits = dig) bb.CI.lower[md,qd]<- signif( as.data.frame(summary(fit)[[1]])[name.bb[md,qd],"2.5%"], digits = dig) bb.CI.upper[md,qd]<- signif( as.data.frame(summary(fit)[[1]])[name.bb[md,qd],"2.5%"], digits = dig) } } return( list( w.EAP = w.EAP, dz.EAP = dz.EAP, z.EAP = z.EAP, mu.EAP = mu.EAP, v.EAP = v.EAP, ppp.EAP = ppp.EAP, l.EAP = l.EAP, dl.EAP = dl.EAP, A.EAP = A.EAP, AA.EAP = AA.EAP, aa.EAP = aa.EAP, bb.EAP = bb.EAP, w.CI.upper = w.CI.upper, dz.CI.upper = dz.CI.upper, z.CI.upper = z.CI.upper, mu.CI.upper = mu.CI.upper, v.CI.upper = v.CI.upper, ppp.CI.upper = ppp.CI.upper, l.CI.upper = l.CI.upper, dl.CI.upper = dl.CI.upper, A.CI.upper = A.CI.upper, AA.CI.upper = AA.CI.upper, aa.CI.upper = aa.CI.upper, bb.CI.upper = bb.CI.upper, w.CI.lower = w.CI.lower, dz.CI.lower = dz.CI.lower, z.CI.lower = z.CI.lower, mu.CI.lower = mu.CI.lower, v.CI.lower = v.CI.lower, ppp.CI.lower = ppp.CI.lower, l.CI.lower = l.CI.lower, dl.CI.lower = dl.CI.lower, A.CI.lower = A.CI.lower, AA.CI.lower = AA.CI.lower, aa.CI.lower = aa.CI.lower, bb.CI.lower = bb.CI.lower )) } extractAUC <-function(StanS4class, dig=3, summary=TRUE, new.imaging.device=TRUE, print_CI_of_AUC = TRUE ){ if(summary==TRUE){ fit <- methods::as(StanS4class, "stanfit") if(StanS4class@studyDesign =="MRMC") { M <-as.integer(StanS4class@dataList$M) AUC <- vector() A.CI.lower<- vector() A.CI.upper<- vector() name <- vector() nnname <- vector() for (md in 1:M) { AUC[md] <- signif( mean(rstan::extract(fit)$A[,md]), digits = dig) name[md] <-md nnname[md] <-paste("A[",md,"]",sep = "") A.CI.lower[md] <- signif( as.data.frame(summary(fit)[[1]])[nnname[md],"2.5%"], digits = dig) A.CI.upper[md] <- signif( as.data.frame(summary(fit)[[1]])[nnname[md],"97.5%"], digits = dig) } message(crayon::silver( "\n------------------------------")) message(crayon::silver( "\n* The following table shows the AUCs for each modality, that is, the area under the AFROC curves.")) message(crayon::silver( "\n* The following table shows, from the left, modality ID, expected a posterior estimates and upper and lower credible interbals for AUCs.")) print(knitr::kable(data.frame(Modality=name, AUC.EAP=AUC, AUC.CI.lower=A.CI.lower, AUC.CI.upper=A.CI.upper ) , align ="cccc", format="pandoc") ) if(print_CI_of_AUC)message("\n------------------------------\n") if(print_CI_of_AUC)message("In the Figure of AUCs, the two intervals are shown for each modality, i.e., ") if(new.imaging.device&&print_CI_of_AUC) grDevices::dev.new() if(print_CI_of_AUC) print( rstan::plot(methods::as(StanS4class, "stanfit"),par=nnname)) AUCs <- data.frame(Modality=name, AUC.EAP=AUC, AUC.CI.lower=A.CI.lower, AUC.CI.upper=A.CI.upper ) return( list(AUCs=AUCs ,nnname=nnname ) ) } if(!StanS4class@studyDesign =="MRMC"){ AUC <- signif( as.data.frame(summary(fit)[[1]])["A","mean"], digits = dig ) A.CI.lower <- signif( as.data.frame(summary(fit)[[1]])["A","2.5%"], digits = dig) A.CI.upper <- signif( as.data.frame(summary(fit)[[1]])["A","97.5%"], digits = dig) print(knitr::kable(data.frame( AUC=AUC, lowerCI=A.CI.lower, upperCI=A.CI.upper ) , align ="cccc", format="pandoc") ) invisible(data.frame( AUC=AUC, A.CI.lower=A.CI.lower, A.CI.upper=A.CI.upper ) ) } }}
optimLBFGSB<-function(x=NULL,fun,lower,upper,control=list(),...){ if(is.null(x)) x <- lower + runif(length(lower)) * (upper-lower) else x <- x[1,] con<-list(funEvals=100) con[names(control)] <- control control<-con control$maxit <- control$funEvals control$types <- NULL fn <- function(x,...)fun(matrix(x,1),...) control$funEvals <- NULL res <- optim(par=x,fn=fn,lower=lower,upper=upper,control=control,method="L-BFGS-B",...) list(x=NA,y=NA,xbest=matrix(res$par,1),ybest=res$value,count= res$counts[[1]] +res$counts[[2]] * 2 * length(res$par),msg=res$message) }
context("testMGD") source("test-main.R") test_that(paste("Supported mgd approaches are:", args_default(.choices = TRUE)$.approach_mgd, collapse = ", "), { expect_error(testMGD(res_multi_linear, .approach_mgd = "Hello World")) }) test_that("Not providing a cSEMResults_multi object causes an error", { expect_error(testMGD(res_single_linear)) expect_error(testMGD(res_single_linear_boot)) }) test_that(".approach_mgd = 'Klesel' does not work for nonlinear models", { expect_error(testMGD(res_multi_nonlinear, .approach_mgd = "Klesel")) expect_error(testMGD(res_multi_nonlinear_boot, .approach_mgd = "all")) expect_error(testMGD(res_multi_nonlinear_2ndorder, .approach_mgd = "all")) }) test_that(".approach_mgd = 'Sarstedt' can not be combined with .handle_inadmissibles = 'drop'", { expect_error( testMGD(res_multi_linear, .approach_mgd = "Sarstedt", .handle_inadmissibles = "drop") ) expect_error( testMGD(res_multi_nonlinear, .approach_mgd = "all", .handle_inadmissibles = "drop") ) }) for(i in args_default(.choices = TRUE)$.approach_mgd) { test_that(paste("testMGD works for .approach_mgd = ", i), { expect_output( testMGD( .object = res_multi_linear_boot, .approach_mgd = i, .R_permutation = 5, .handle_inadmissibles = "replace" ) ) }) if(i %in% c("Chin", "Keil", "Nitzl", "Sarstedt", "Henseler")) test_that("Chin, Keil, Nitzl and Sarstedt work for nonlinear models", { expect_output( testMGD( .object = res_multi_nonlinear, .approach_mgd = i, .R_permutation = 5, .R_bootstrap = 5, .handle_inadmissibles = "replace" ) ) expect_output( testMGD( .object = res_multi_nonlinear_2ndorder, .approach_mgd = i, .R_permutation = 5, .R_bootstrap = 5, .handle_inadmissibles = "replace" ) ) }) } test_that("testMGD() works for second order models (.approach_mgd = 'all')", { expect_output( testMGD( .object = res_multi_2ndorder_boot, .approach_mgd = "all", .R_permutation = 5, .handle_inadmissibles = "replace" ) ) })
DIx <- function(l1, l2, details=FALSE, version = 1) { l1 <- c(l1, rep(0, max(0, length(l2)-length(l1)))) l2 <- c(l2, rep(0, max(0, length(l1)-length(l2)))) l1 <- l1/sum(l1) l2 <- l2/sum(l2) pp <- getFromNamespace(".permutations", ns="HelpersMG")(v=l1, r=length(l1), n=length(l1), set=FALSE) p <- (mean(apply(pp, 1, function(x) {sqrt(1-(sum(x*l2)))}))) vn1 <- sum(l1 != 0) vn2 <- sum(l2 != 0) if (version == 2) { vmax1 <- -sum(rep(1/vn1, vn1) * log(rep(1/vn1, vn1))) vmax2 <- -sum(rep(1/vn2, vn2) * log(rep(1/vn2, vn2))) p1 <- 2*vmax1+sum(l1[l1 != 0] * log(l1[l1 != 0])) p2 <- 2*vmax2+sum(l2[l2 != 0] * log(l2[l2 != 0])) } else { p1 <- sum(l1[l1 != 0] * log(l1[l1 != 0])) p2 <- sum(l2[l2 != 0] * log(l2[l2 != 0])) } if (details) { return(c(Average.Edwards=p, Geometric.mean.Shannon=sqrt(p1*p2), DIx=p*sqrt(p1*p2))) } else { return(p*sqrt(p1*p2)) } }
extract_manual <- function (x, i, j, ..., drop = TRUE, basis = 0) { x_size <- torch_size(x) if (is.list(x_size)) { x_size <- lapply(x_size, function (x) ifelse(is.null(x), NA, x)) x_size <- unlist(x_size) } n_indices <- length(x_size) cl <- match.call() args <- as.list(cl)[-1] known_args <- c("x", "i", "j", "drop", "basis") extra_indices <- args[!names(args) %in% known_args] if (missing(i)) i <- list(NA) else i <- list(validate_index(i)) if (missing(j)) { if (n_indices > 1) j <- list(NA) else j <- list() } else { j <- list(validate_index(j)) } extra_indices <- lapply(extra_indices, evaluate_index) indices <- c(i, j, extra_indices) names(indices) <- NULL if (length(indices) != n_indices) { stop ('incorrect number of dimensions') } begin <- vapply(indices, function (x) { if (length(x) == 1 && is.na(x)) 0 else x[1] - basis }, FUN.VALUE = 0) end <- vapply(indices, function (x) { if (length(x) == 1 && is.na(x)) Inf else x[length(x)] - basis }, FUN.VALUE = 0) end <- pmin(end, x_size) + 1 print(begin) begin_shape <- do.call('shape', as.list(begin)) end_shape <- do.call('shape', as.list(end)) stride_shape <- as.list(rep(1L, n_indices)) if (drop) { shrink <- vapply(indices, function (x) { length(x) == 1 && !is.na(x) }, FALSE) shrink_integer <- integer_mask(shrink) } else { shrink_integer <- 0 } begin_mask <- end_mask <- integer_mask(is.na(x_size)) list(begin = begin, end = end, begin_shape = begin_shape, end_shape = end_shape, begin_mask = begin_mask, end_mask = end_mask, stride_shape = stride_shape) } is.blank <- function (x) is.name(x) && as.character(x) == '' integer_mask <- function (mask) sum(2 ^ (seq_along(mask) - 1)[mask]) evaluate_index <- function (x, validate = TRUE, n = 3) { if (is.blank(x)) { x <- NA } else { if (is.call(x) | is.name(x)) x <- eval(x, envir = parent.frame(n = n)) if (validate) x <- validate_index(x) } x } validate_index <- function (x, base = 0) { append <- switch (as.character(base), `0` = " with 0-based indexing", `1` = " with unknown dimensions") if (!(is.numeric(x) && is.finite(x))) { stop ("invalid index - must be numeric and finite", append) } if (!(is.vector(x))) { stop ("only vector indexing of Tensors is currently supported", append) } if (any(x < 0)) { stop ("negative indexing of Tensors is not currently supported", append) } if (x[length(x)] < x[1]) { stop ("decreasing indexing of Tensors is not currently supported", append) } x } check_zero_based <- function (call) { args <- as.list(call)[-1] other_args <- c("x", "drop", "basis") names <- names(args) indices <- args[!names %in% other_args] indices <- lapply(indices, evaluate_index, validate = FALSE, n = 4) contain_zero <- vapply(indices, function (x) { (is.atomic(x) | is.list(x)) && any(is_a_zero(x)) }, FUN.VALUE = FALSE) default_one_based <- is.null(getOption("tensorflow.one_based_extract")) if (any(contain_zero) & default_one_based) { warning(paste( "It looks like you might be using 0-based indexing to extract using `[`.", "The rTorch package now uses 1-based (R-like) extraction by default.\n", "You can switch to the old behavior (1-based extraction) with:", " options(torch.one_based_extract = FALSE)\n", "If your indexing is as you intend, you can disable this warning with:", " options(torch.one_based_extract = TRUE)", sep = "\n" ), call. = FALSE) } } is_a_zero <- function (x) { vapply(x, function (x) { identical(x, 0) | identical(x, 0L) }, FUN.VALUE = FALSE) }
ebirdfreq <- function(loctype, loc, startyear = 1900, endyear = format(Sys.Date(), "%Y"), startmonth = 1, endmonth = 12, long = TRUE, ...) { if (!all(c(startmonth, endmonth) %in% 1:12)) { stop("Invalid month(s) provided (must be integer between 1 and 12)") } currentyear <- format(Sys.Date(), "%Y") if (!all(c(startyear, endyear) %in% 1900:currentyear)) { stop(paste0("Invalid year(s) provided (must be integer between 1900 and ", currentyear, ")")) } if (loctype == "hotspots") { if (!grepl("^L\\d{1,8}$", loc)) stop("Invalid hotspot code") } else if (loctype %in% c("counties", "states")) { } else { stop("Not a valid location type") } args <- list(r = loc, bmo = startmonth, emo = endmonth, byr = startyear, eyr = endyear, personal = "false", fmt = "tsv") url <- "http://ebird.org/ebird/barchartData" url_full <- modify_url(url, query = args) message(url_full) stop( "This function has been made temporarily defunct as you now need to be logged into the eBird website to download frequency data, but we cannot authenticate via the API to do so. This function will be reinstated when the frequency data become available through the API. In the meantime, you can paste the url above in your browser to obtain the web download of the frequency data for the desired location and date. See https://github.com/ropensci/rebird/issues/82 for more information." ) ret <- GET(url, query = args, ...) stop_for_status(ret) asChar <- readBin(ret$content, "character") freq <- tbl_df(read.delim(text = asChar, skip = 12, stringsAsFactors = FALSE)[,-50]) if (loctype == "hotspots" && all(is.na(freq[, -1]))) { warning("No observations returned, check hotspot code") } names(freq) <- c("comName", vapply(month.name, paste, FUN.VALUE = character(4), 1:4, sep = "-")) if (!long) { return(freq) } else { freq_long <- reshape(data.frame(freq[-1, ]), varying = 2:49, direction = "long", v.names = "frequency", idvar = "comName", timevar = "monthQt", times = names(freq)[2:49]) ss <- data.frame(sampleSize = unlist(freq[1, -1])) ss$monthQt <- rownames(ss) freq_long <- left_join(freq_long, ss, by = "monthQt") tbl_df(freq_long) } }
run_ggquickeda <- function(data = NULL) { if (!is.null(data) && !is.data.frame(data)) { stop("data must be a data.frame", call. = FALSE) } appDir <- system.file("shinyapp", package = "ggquickeda") if (appDir == "") { stop("Could not find shiny app directory. Try re-installing `ggquickeda`.", call. = FALSE) } if (!is.null(data)) { .GlobalEnv$ggquickeda_initdata <- data on.exit(rm(ggquickeda_initdata, envir = .GlobalEnv)) } shiny::runApp(appDir, display.mode = "normal") } if (getRversion() >= "2.15.1") utils::globalVariables(c("ggquickeda_initdata"))
library(rethinking) library(animation) library(ellipse) blank(bty="n",w=1.4,h=0.8) al <- alist( y ~ dnorm(mu,1), mu <- a + b*x , a ~ dnorm(0,1), b ~ dnorm(0,1) ) q <- quap( al , data=list(y=1) , dofit=FALSE ) pp <- extract.prior(q) a_link <- function(x) a + b*x anim_prior_predictive( prior=pp , linkf=a_link , n=20 , n_to_show=3 , n_steps=20 , ylim=c(-2,2) , ylab="outcome" ) oopts = ani.options(interval = 0.03) ani.replay() n_points <- 10 n_points <- 0 x <- rnorm(n_points) x <- ifelse( x > 2 , 2 , x ) x <- ifelse( x < -2 , -2 , x ) y <- rnorm(n_points, 0 + 0.7*x,0.5) xlims <- c(-2,2) ylims <- c(-2,2) ellipse_hist <- list() ani.record(reset=TRUE) NSTEPS <- 20 for ( i in 0:n_points ) { xmean <- mean( x[1:i] ) al <- alist( y ~ dnorm(mu,1), mu <- a + b*x , a ~ dnorm(0,1), b ~ dnorm(0,1) ) if ( i > 0 ) { dati <- list( x=x[1:i] , y=y[1:i] ) q <- quap( al , data=dati , dofit=TRUE ) pp <- extract.samples(q) } else { q <- quap( al , data=list(y=1,x=1) , dofit=FALSE ) pp <- as.data.frame(extract.prior(q)) } a_link <- function(x) a + b*x the_text <- concat("n = ",i) xseq <- seq(from=-2.2,to=2.2,length=50) ahat <- mean(pp$a) bhat <- mean(pp$b) if ( i > 0 ) { mu <- link( q , data=list(x=xseq) ) ci <- apply(mu,2,PI) } use_cols <- c(2, 4, 5, 6, 3) the_pf <- function(samp,step) { par(mfrow=c(1,2)) plot(NULL,xlim=c(-2.5,2.5),ylim=c(-2.5,2.5),bty="n",xlab="intercept",ylab="slope") pm <- colMeans(pp) the_contour <- list() for ( l in c(0.5,0.8,0.95) ) the_contour[[ concat(l) ]] <- ellipse(cov(pp),centre=pm,level=l) if ( length(ellipse_hist) > 0 & samp==1 ) { mixf <- (NSTEPS-step)/NSTEPS for ( l in c(0.5,0.8,0.95) ) { the_contour[[ concat(l) ]] <- (1-mixf)*the_contour[[concat(l)]] + mixf*ellipse_hist[[concat(l)]] } } thelwd <- 2 if ( samp==1 ) thelwd <- 2+3*(NSTEPS-step)/NSTEPS for ( l in c(0.5,0.8,0.95) ) lines(the_contour[[concat(l)]],col=1,lwd=thelwd ) pb <- get("prior_blend",envir=parent.frame(n = 1)) points( pb[[1]][,step] , pb[[2]][,step] , lwd=2 , col=use_cols[1:3] , pch=16 , cex=1.6 ) plot(NULL,xlim=xlims,ylim=ylims,xlab="x value",ylab="y value",bty="n") if ( i > 0 ) { shade( ci , xseq ) abline( a=ahat , b=bhat , lwd=3 , col="gray" , lty=2 ) points( x[1:i] , y[1:i] , pch=1 , lwd=3 , cex=1.2 ) } mtext(the_text) } if ( i==0 ) r <- NULL n_prior_samples <- 20 r <- anim_prior_predictive( prior=pp , linkf=a_link , n=n_prior_samples , n_to_show=3 , n_steps=NSTEPS , ylim=ylims , ylab="outcome" , xlim=xlims , pf=the_pf , do_reset=FALSE , start_from=r , accel=-0.5 , vel0=1 ) for ( l in c(0.5,0.8,0.95) ) ellipse_hist[[ concat(l) ]] <- ellipse(cov(pp),centre=colMeans(pp),level=l) } oopts = ani.options(interval = 0.02) ani.replay() set.seed(12) n_points <- 10 x <- rnorm(n_points) x <- ifelse( x > 2 , 2 , x ) x <- ifelse( x < -2 , -2 , x ) y <- rnorm( n_points , 0 + 0.7*x - 1*x^2 , 0.5 ) x[9] <- 3 y[9] <- -1 xlims <- c(-4,5) ylims <- c(-7,2) ellipse_hist <- list() ani.record(reset=TRUE) NSTEPS <- 14 for ( i in 0:n_points ) { al <- alist( y ~ dnorm(mu,1), mu <- a + b1*x + b2*x^2 , a ~ dnorm(0,1), b1 ~ dnorm(0,1), b2 ~ dnorm(0,1) ) if ( i > 0 ) { dati <- list( x=x[1:i] , y=y[1:i] ) q <- quap( al , data=dati , dofit=TRUE ) pp <- extract.samples(q) } else { q <- quap( al , data=list(y=1,x=1) , dofit=FALSE ) pp <- as.data.frame(extract.prior(q)) } a_link <- function(x) a + b1*x + b2*x^2 the_text <- concat("n = ",i) xseq <- seq(from=xlims[1],to=xlims[2],length=50) ahat <- mean(pp$a) b1hat <- mean(pp$b1) b2hat <- mean(pp$b2) if ( i > 0 ) { mu <- link( q , data=list(x=xseq) ) ci <- apply(mu,2,PI) } the_pf <- function(samp,step) { par(mfrow=c(1,2)) plot(NULL,xlim=c(-2.5,2.5),ylim=c(-2.5,2.5),bty="n",xlab="b1",ylab="b2") mtext(the_text) pm <- colMeans(pp) the_contour <- list() for ( l in c(0.5,0.8,0.95) ) the_contour[[ concat(l) ]] <- ellipse(cov(pp)[2:3,2:3],centre=pm[2:3],level=l) if ( length(ellipse_hist) > 0 & samp==1 ) { mixf <- (NSTEPS-step)/NSTEPS for ( l in c(0.5,0.8,0.95) ) { the_contour[[ concat(l) ]] <- (1-mixf)*the_contour[[concat(l)]] + mixf*ellipse_hist[[concat(l)]] } } thelwd <- 2 if ( samp==1 ) thelwd <- 2+3*(NSTEPS-step)/NSTEPS for ( l in c(0.5,0.8,0.95) ) lines(the_contour[[concat(l)]],col=2,lwd=thelwd ) plot(NULL,xlim=xlims,ylim=ylims,xlab="x value",ylab="y value",bty="n") if ( i > 0 ) { shade( ci , xseq ) points( x[1:i] , y[1:i] , pch=1 , lwd=3 , cex=1.2 ) } mtext( "y = a + b1*x + b2*x^2" ) } if ( i==0 ) r <- NULL r <- anim_prior_predictive( prior=pp , linkf=a_link , n=5 , n_to_show=3 , n_steps=NSTEPS , ylim=ylims , ylab="outcome" , xlim=xlims , pf=the_pf , do_reset=FALSE , start_from=r , accel=-0.5 , vel0=1 ) for ( l in c(0.5,0.8,0.95) ) ellipse_hist[[ concat(l) ]] <- ellipse(cov(pp)[2:3,2:3],centre=colMeans(pp)[2:3],level=l) } oopts = ani.options(interval = 0.02) ani.replay() blank(bty="n",w=1.4,h=0.8) set.seed(13) n_points <- 10 x <- rnorm(n_points) x <- ifelse( x > 2 , 2 , x ) x <- ifelse( x < -2 , -2 , x ) y <- rnorm( n_points , 0 + 0.7*x - 2*x^2 + 3*x^3 , 0.5 ) xlims <- range(x) + c(-1,1)*2 ylims <- range(y) + c(-1,1)*2 ellipse_hist <- list() ani.record(reset=TRUE) NSTEPS <- 14 for ( i in 0:n_points ) { al <- alist( y ~ dnorm(mu,1), mu <- a + b1*x + b2*x^2 + b3*x^3, a ~ dnorm(0,1), b1 ~ dnorm(0,1), b2 ~ dnorm(0,1), b3 ~ dnorm(0,1) ) if ( i > 0 ) { dati <- list( x=x[1:i] , y=y[1:i] ) q <- quap( al , data=dati , dofit=TRUE ) pp <- extract.samples(q) } else { q <- quap( al , data=list(y=1,x=1) , dofit=FALSE ) pp <- as.data.frame(extract.prior(q)) } a_link <- function(x) a + b1*x + b2*x^2 + b3*x^3 the_text <- concat("n = ",i) xseq <- seq(from=xlims[1],to=xlims[2],length=50) ahat <- mean(pp$a) b1hat <- mean(pp$b1) b2hat <- mean(pp$b2) if ( i > 0 ) { mu <- link( q , data=list(x=xseq) ) ci <- apply(mu,2,PI) } the_pf <- function(samp,step) { par(mfrow=c(1,2)) plot(NULL,xlim=c(-2.5,2.5),ylim=c(-2.5,2.5),bty="n",xlab="b2",ylab="b3") mtext(the_text) pm <- colMeans(pp) the_contour <- list() for ( l in c(0.5,0.8,0.95) ) the_contour[[ concat(l) ]] <- ellipse(cov(pp)[3:4,3:4],centre=pm[3:4],level=l) if ( length(ellipse_hist) > 0 & samp==1 ) { mixf <- (NSTEPS-step)/NSTEPS for ( l in c(0.5,0.8,0.95) ) { the_contour[[ concat(l) ]] <- (1-mixf)*the_contour[[concat(l)]] + mixf*ellipse_hist[[concat(l)]] } } thelwd <- 2 if ( samp==1 ) thelwd <- 2+3*(NSTEPS-step)/NSTEPS for ( l in c(0.5,0.8,0.95) ) lines(the_contour[[concat(l)]],col=2,lwd=thelwd ) plot(NULL,xlim=xlims,ylim=ylims,xlab="x value",ylab="y value",bty="n") if ( i > 0 ) { shade( ci , xseq ) points( x[1:i] , y[1:i] , pch=1 , lwd=3 , cex=1.2 ) } mtext( "y = a + b1*x + b2*x^2 + b3*x^3" ) } if ( i==0 ) r <- NULL r <- anim_prior_predictive( prior=pp , linkf=a_link , n=5 , n_to_show=3 , n_steps=NSTEPS , ylim=ylims , ylab="outcome" , xlim=xlims , pf=the_pf , do_reset=FALSE , start_from=r , accel=-0.5 , vel0=1 ) for ( l in c(0.5,0.8,0.95) ) ellipse_hist[[ concat(l) ]] <- ellipse(cov(pp)[3:4,3:4],centre=colMeans(pp)[3:4],level=l) } oopts = ani.options(interval = 0.03) ani.replay()
setMethod("qform", "character", function(object){ object = path.expand(object) stopifnot(file.exists(object)) slots = paste0("qto_xyz:", 1:4) res = sapply(slots, function(key) { fslval(object, keyword = key, verbose = FALSE) }) convmat <- function(form){ ss <- strsplit(form, " ") ss <- t(sapply(ss, function(x) x[x!=""])) class(ss) <- "numeric" return(ss) } res = convmat(res) rownames(res) = NULL return(res) })
predict.indicators<-function(object, newdata = NULL, cv = FALSE, ...) { C <- as.matrix(object$C) nc<-nrow(C) taxnames <-colnames(C) if(cv) { X <- object$X group.vec <- object$group.vec ng = sum(group.vec) func <- object$func cluster <- object$cluster nr = nrow(X) Astat<-matrix(0, nrow=nr, ncol=nc) for(r in 1:nr) { for(i in 1:nc) { spvec = colnames(C)[C[i,]==1] found<-sum(X[r,spvec, drop=FALSE]>0)==sum(C[i,]) if(found) { sc.ab <-apply(X[-r,spvec, drop=FALSE],1,min) scg = sc.ab[group.vec[-r]] if(func=="IndVal.g") { mg = (sum(scg)/ng) Astat[r,i] = mg/sum(tapply(sc.ab,cluster[-r], "mean")) } else { Astat[r,i] = sum(scg)/sum(sc.ab) } } } } p = apply(Astat,1,max) names(p)<-rownames(X) } else { if(is.null(newdata)) newdata = object$X if(sum(taxnames %in% colnames(newdata))<length(taxnames)) stop("Not all taxon names that form indicators could be found in compositional table.") postaxa <- numeric(length(taxnames)) for(i in 1:length(taxnames)) postaxa[i] = which(colnames(newdata)==taxnames[i]) stat<-matrix(0, nrow=nrow(newdata), ncol=nc) if(length(dim(object$A))==2) { lowerCI<-matrix(0, nrow=nrow(newdata), ncol=nc) upperCI<-matrix(0, nrow=nrow(newdata), ncol=nc) } for(i in 1:nc) { ci <- as.numeric(C[i,]) found<-rowSums(newdata[,postaxa[ci==1], drop=FALSE]>0)==sum(ci) if(length(dim(object$A))==2) { stat[,i]<- found*object$A$stat[i] lowerCI[,i]<- found*object$A$lowerCI[i] upperCI[,i]<- found*object$A$upperCI[i] } else { stat[,i]<- found*object$A[i] } } if(length(dim(object$A))==2) { wm = apply(lowerCI,1,which.max) p = matrix(NA,nrow=nrow(newdata), ncol=3) for(i in 1:length(wm)) { p[i,] = c(stat[i,wm[i]],lowerCI[i,wm[i]], upperCI[i,wm[i]]) } rownames(p)<-rownames(newdata) colnames(p)<-c("Prob.", "lowerCI", "upperCI") } else { p = apply(stat,1,max) names(p)<-rownames(newdata) } } return(p) }
cUmbrPU<-function(alpha,n, method=NA, n.mc=10000){ outp<-list() outp$stat.name<-paste("Mack-Wolfe Peak Unknown A*(p-hat)") if(alpha>1||alpha<0||class(alpha)!="numeric"){ cat('Error: Check alpha value! \n') return(alpha) } outp$alpha<-alpha outp$n<-n outp$n.mc<-n.mc N<-sum(n) k<-length(n) g<-rep(1:k,outp$n) if(is.na(method)){ if(factorial(sum(outp$n))/prod(factorial(outp$n))<=10000){ method<-"Exact" } if(factorial(sum(outp$n))/prod(factorial(outp$n))>10000){ method<-"Monte Carlo" } } outp$method<-method cumulative.sizes<-cumsum(outp$n) peak.picker<-function(obs.data){ tmp<-numeric(k) for(i in 1:k){ first<-obs.data[max(1,cumulative.sizes[i-1]+1):cumulative.sizes[i]] second<-obs.data[-(max(1,cumulative.sizes[i-1]+1):cumulative.sizes[i])] options(warn = (-1)); tmp[i]<-(wilcox.test(first,second)$statistic-(outp$n[i]*(cumulative.sizes[k]-outp$n[i])/2))/sqrt( outp$n[i]*(cumulative.sizes[k]-outp$n[i])*(cumulative.sizes[k]+1)/12) options(warn = (0)); } initial.peak<-peak<-which.max(tmp) if(1-sum(tmp[-peak]==tmp[peak])){ return(peak) } for(i in (initial.peak+1):k){ if(tmp[i]==tmp[initial.peak]){ peak<-c(peak,i) } } return(peak) } A.star.calc<-function(obs.data,peak){ N1<-cumulative.sizes[peak] N2<-(cumulative.sizes[k]-max(0,cumulative.sizes[peak-1])) exp.Ap<-(N1^2+N2^2-sum(outp$n^2)-outp$n[peak]^2)/4 var.Ap<-1/72*(2*(N1^3+N2^3)+3*(N1^2+N2^2)-sum(outp$n^2*(2*outp$n+3)) -outp$n[peak]^2*(2*outp$n[peak]+3)+12*outp$n[peak]*N1*N2-12*outp$n[peak]^2*cumulative.sizes[k]) U.vec<-numeric((peak*(peak-1)+(k-peak+1)*(k-peak))/2) U.calc<-function(i,j){ wilcox.test(obs.data[g==i],obs.data[g==j])$statistic } count<-0 if(peak>1){ for(i in 2:peak){ for(j in 1:(i-1)) { count<-count+1 options(warn = (-1)); U.vec[count]<-U.calc(i,j) options(warn = (0)); } } } if(peak<k){ for(i in peak:(k-1)){ for(j in (i+1):k) { count<-count+1 options(warn = (-1)); U.vec[count]<-U.calc(i,j) options(warn = (0)); } } } (sum(U.vec)-exp.Ap)/sqrt(var.Ap) } PU.calc<-function(obs.data){ tmp.peak<-peak.picker(obs.data) num.peak<-length(tmp.peak) tmp.stat<-numeric(num.peak) if(num.peak==1){ tmp.stat<-A.star.calc(obs.data,tmp.peak) } if(num.peak>1){ for(i in 1:num.peak){ tmp.stat[i]<-A.star.calc(obs.data,tmp.peak[i]) } } mean(tmp.stat) } possible.ranks<-1:N if(outp$method=="Asymptotic"){ warning("The asymptotic distribution for this statistic is unknown!") outp$method=="Monte Carlo" } if(outp$method=="Exact"){ possible.orders<-multComb(outp$n) possible.perms<-t(apply(possible.orders,1,function(x) possible.ranks[x])) A.stats<-apply(possible.perms,1,PU.calc) A.tab<-table(A.stats) A.vals<-round(as.numeric(names(A.tab)),5) A.probs<-as.numeric(A.tab)/sum(A.tab) A.dist<-cbind(A.vals,A.probs) upper.tails<-cbind(rev(A.vals),cumsum(rev(A.probs))) outp$cutoff.U<-upper.tails[max(which(upper.tails[,2]<=alpha)),1] outp$true.alpha.U<-upper.tails[max(which(upper.tails[,2]<=alpha)),2] } if(outp$method=="Monte Carlo"){ mc.dist<-numeric(n.mc) for(i in 1:n.mc){ mc.perm<-sample(possible.ranks) mc.dist[i]<-round(PU.calc(mc.perm),10) } mc.values<-sort(unique(mc.dist)) mc.probs<-as.numeric(table(mc.dist))/n.mc A.dist<-cbind(mc.values,mc.probs) upper.tails<-cbind(rev(mc.values),cumsum(rev(mc.probs))) outp$cutoff.U<-upper.tails[max(which(upper.tails[,2]<=alpha)),1] outp$true.alpha.U<-upper.tails[max(which(upper.tails[,2]<=alpha)),2] } class(outp)<-"NSM3Ch6c" outp }
stat.cor <- function(ant, var1, var2, method = "pearson", progress = TRUE) { id1 <- df.col.findId(ant[[1]], var1) id2 <- df.col.findId(ant[[1]], var2) if (progress == TRUE) { result <- lapply(ant, function(d, id1, id2, method) { cat(" Processing file: ", attr(d, "permutation"), "\r") r <- cor(x = d[, id1], y = d[, id2], method = method) return(r) }, id1, id2, method) } else { result <- lapply(ant, function(d, id1, id2, method) { r <- cor(x = d[, id1], y = d[, id2], method = method) return(r) }, id1, id2, method) } result <- do.call("rbind", result) attr(result, "class") <- "ant cor" if (method == "pearson") { attr(result, "comment") <- paste("Pearson coefficient") attr(result, "var1") <- paste(var1) attr(result, "var2") <- paste(var2) } if (method == "kendall") { attr(result, "comment") <- paste("Kendall coefficient") attr(result, "var1") <- paste(var1) attr(result, "var2") <- paste(var2) } if (method == "spearman") { attr(result, "comment") <- paste("Spearman coefficient") attr(result, "var1") <- paste(var1) attr(result, "var2") <- paste(var2) } cat("\n") return(result) }
voxDims <- function(directory = file.choose()) { if (!exists(directory)) { if (substr(directory, nchar(directory) - 3, nchar(directory)) %in% ".dcm") { } else if (grepl("/", directory) == 1) { } else stop("Incorrect directory name: directory specified in a character string must end with a '/'; if 'file.choose()' is used, the selected file must be a dicom image") fname <- oro.dicom::readDICOM(directory, verbose = TRUE) } else if (exists(directory) & (sum(names(get(directory)) %in% c("hdr", "img")) == 2)){ fname <- get(directory) } else stop("Invalid input: 'directory' object or file location is incorrectly specified.") pixelArea <- as.numeric(strsplit(fname$hdr[[1]]$value[fname$hdr[[1]]$name %in% "PixelSpacing"], " ")[[1]][1])^2 thick <- unique(oro.dicom::extractHeader(fname$hdr, "SliceThickness")) returnDat <- data.frame(pixelArea.mm2 = pixelArea, thickness.mm = thick) returnDat }
rp.select <- function(rp.object, percentile=90 ) { if(!methods::is(rp.object,"ResponsePatterns")) stop("The object is not of class ResponsePatterns") percentile <- round(percentile) if(percentile < 0 | percentile > 99) stop("percentile must be a number between 0 and 99") indices <- cbind(c(1:[email protected]),rp.object@indices) indices <- indices[indices$percentile >= percentile,] indices <- indices[order(indices$percentile, decreasing=TRUE),] selected.rows <- indices[,1] rp.object@indices <- indices[,-1] rp.object@coefficients <- as.data.frame(rp.object@coefficients[selected.rows,]) if(nrow(rp.object@data)!=0 & ncol(rp.object@data)!=0) { rp.object@data <- as.data.frame(rp.object@data[selected.rows,]) } [email protected] <- nrow(indices) rp.object@id = rp.object@id[selected.rows] rp.object@percentile = percentile return(rp.object) }
MPinverse <- function(Matrix) { EPS <- 100*(.Machine$double.eps) U <- eigen(Matrix)$vectors D <- eigen(Matrix)$values Dmatrix <- diag(length(D)) Dmatrix[which(Dmatrix>0)] <- 1/D Dmatrix[which(abs(Dmatrix)>(1/EPS))] <- 0 A <- U%*%Dmatrix%*%t(U) return(A) }
"mfa" <- function (X, option = c("lambda1", "inertia", "uniform", "internal"), scannf = TRUE, nf = 3) { if (!inherits(X, "ktab")) stop("object 'ktab' expected") if (option[1] == "internal") { if (is.null(X$tabw)) { warning("Internal weights not found: uniform weigths are used") option <- "uniform" } } lw <- X$lw cw <- X$cw sepan <- sepan(X, nf = 4) nbloc <- length(sepan$blo) indicablo <- factor(rep(1:nbloc, sepan$blo)) rank.fac <- factor(rep(1:nbloc, sepan$rank)) ncw <- NULL tab.names <- names(X)[1:nbloc] auxinames <- ktab.util.names(X) option <- match.arg(option) if (option == "lambda1") { for (i in 1:nbloc) { ncw <- c(ncw, rep(1/sepan$Eig[rank.fac == i][1], sepan$blo[i])) } } else if (option == "inertia") { for (i in 1:nbloc) { ncw <- c(ncw, rep(1/sum(sepan$Eig[rank.fac == i]), sepan$blo[i])) } } else if (option == "uniform") ncw <- rep(1, sum(sepan$blo)) else if (option == "internal") ncw <- rep(X$tabw, sepan$blo) ncw <- cw * ncw tab <- X[[1]] for (i in 2:nbloc) { tab <- cbind.data.frame(tab, X[[i]]) } names(tab) <- auxinames$col anaco <- as.dudi(tab, col.w = ncw, row.w = lw, nf = nf, scannf = scannf, call = match.call(), type = "mfa") nf <- anaco$nf afm <- list() afm$tab.names <- names(X)[1:nbloc] afm$blo <- X$blo afm$TL <- X$TL afm$TC <- X$TC afm$T4 <- X$T4 afm$tab <- anaco$tab afm$eig <- anaco$eig afm$rank <- anaco$rank afm$li <- anaco$li afm$l1 <- anaco$l1 afm$nf <- anaco$nf afm$lw <- anaco$lw afm$cw <- anaco$cw afm$co <- anaco$co afm$c1 <- anaco$c1 projiner <- function(xk, qk, d, z) { w7 <- t(as.matrix(xk) * d) %*% as.matrix(z) iner <- apply(w7 * w7 * qk, 2, sum) return(iner) } link <- matrix(0, nbloc, nf) for (k in 1:nbloc) { xk <- X[[k]] q <- ncw[indicablo == k] link[k, ] <- projiner(xk, q, lw, anaco$l1) } link <- as.data.frame(link) names(link) <- paste("Comp", 1:nf, sep = "") row.names(link) <- tab.names afm$link <- link w <- matrix(0, nbloc * 4, nf) i1 <- 0 i2 <- 0 matl1 <- as.matrix(afm$l1) for (k in 1:nbloc) { i1 <- i2 + 1 i2 <- i2 + 4 tab <- as.matrix(sepan$L1[sepan$TL[, 1] == levels(sepan$TL[,1])[k], ]) if (ncol(tab) > 4) tab <- tab[, 1:4] if (ncol(tab) < 4) tab <- cbind(tab, matrix(0, nrow(tab), 4 - ncol(tab))) tab <- t(tab * lw) %*% matl1 for (i in 1:min(nf, 4)) { if (tab[i, i] < 0) { for (j in 1:nf) tab[i, j] <- -tab[i, j] } } w[i1:i2, ] <- tab } w <- data.frame(w) names(w) <- paste("Comp", 1:nf, sep = "") row.names(w) <- auxinames$tab afm$T4comp <- w w <- matrix(0, nrow(sepan$TL), ncol = nf) i1 <- 0 i2 <- 0 for (k in 1:nbloc) { i1 <- i2 + 1 i2 <- i2 + length(lw) qk <- ncw[indicablo == k] xk <- as.matrix(X[[k]]) w[i1:i2, ] <- (xk %*% (qk * t(xk))) %*% (matl1 * lw) } w <- data.frame(w) row.names(w) <- auxinames$row names(w) <- paste("Fac", 1:nf, sep = "") afm$lisup <- w afm$tabw <- X$tabw afm$call <- match.call() class(afm) <- c("mfa", "list") return(afm) } "plot.mfa" <- function (x, xax = 1, yax = 2, option.plot = 1:4, ...) { if (!inherits(x, "mfa")) stop("Object of type 'mfa' expected") nf <- x$nf if (xax > nf) stop("Non convenient xax") if (yax > nf) stop("Non convenient yax") opar <- par(mar = par("mar"), mfrow = par("mfrow"), xpd = par("xpd")) on.exit(par(opar)) mfrow <- n2mfrow(length(option.plot)) par(mfrow = mfrow) for (j in option.plot) { if (j == 1) { coolig <- x$lisup[, c(xax, yax)] s.class(coolig, fac = as.factor(x$TL[, 2]), label = row.names(x$li), cellipse = 0, sub = "Row projection", csub = 1.5) add.scatter.eig(x$eig, x$nf, xax, yax, posi = "topleft", ratio = 1/5) } if (j == 2) { coocol <- x$co[, c(xax, yax)] s.arrow(coocol, sub = "Col projection", csub = 1.5) add.scatter.eig(x$eig, x$nf, xax, yax, posi = "topleft", ratio = 1/5) } if (j == 3) { s.corcircle(x$T4comp[x$T4[, 2] == levels(x$T4[,2])[1], ], fullcircle = FALSE, sub = "Component projection", possub = "topright", csub = 1.5) add.scatter.eig(x$eig, x$nf, xax, yax, posi = "bottomleft", ratio = 1/5) } if (j == 4) { plot(x$link[, c(xax, yax)]) scatterutil.grid(0) title(main = "Link") par(xpd = TRUE) scatterutil.eti(x$link[, xax], x$link[, yax], label = row.names(x$link), clabel = 1) } if (j == 5) { scatterutil.eigen(x$eig, wsel = 1:x$nf, sub = "Eigen values", csub = 2, possub = "topright") } } } "print.mfa" <- function (x, ...) { if (!inherits(x, "mfa")) stop("non convenient data") cat("Multiple Factorial Analysis\n") cat(paste("list of class", class(x))) cat("\n$call: ") print(x$call) cat("$nf:", x$nf, "axis-components saved\n\n") sumry <- array("", c(6, 4), list(1:6, c("vector", "length", "mode", "content"))) sumry[1, ] <- c("$tab.names", length(x$tab.names), mode(x$tab.names), "tab names") sumry[2, ] <- c("$blo", length(x$blo), mode(x$blo), "column number") sumry[3, ] <- c("$rank", length(x$rank), mode(x$rank), "tab rank") sumry[4, ] <- c("$eig", length(x$eig), mode(x$eig), "eigen values") sumry[5, ] <- c("$lw", length(x$lw), mode(x$lw), "row weights") sumry[6, ] <- c("$tabw", length(x$tabw), mode(x$tabw), "array weights") print(sumry, quote = FALSE) cat("\n") sumry <- array("", c(11, 4), list(1:11, c("data.frame", "nrow", "ncol", "content"))) sumry[1, ] <- c("$tab", nrow(x$tab), ncol(x$tab), "modified array") sumry[2, ] <- c("$li", nrow(x$li), ncol(x$li), "row coordinates") sumry[3, ] <- c("$l1", nrow(x$l1), ncol(x$l1), "row normed scores") sumry[4, ] <- c("$co", nrow(x$co), ncol(x$co), "column coordinates") sumry[5, ] <- c("$c1", nrow(x$c1), ncol(x$c1), "column normed scores") sumry[6, ] <- c("$lisup", nrow(x$lisup), ncol(x$lisup), "row coordinates from each table") sumry[7, ] <- c("$TL", nrow(x$TL), ncol(x$TL), "factors for li l1") sumry[8, ] <- c("$TC", nrow(x$TC), ncol(x$TC), "factors for co c1") sumry[9, ] <- c("$T4", nrow(x$T4), ncol(x$T4), "factors for T4comp") sumry[10, ] <- c("$T4comp", nrow(x$T4comp), ncol(x$T4comp), "component projection") sumry[11, ] <- c("$link", nrow(x$link), ncol(x$link), "link array-total") print(sumry, quote = FALSE) cat("other elements: ") if (length(names(x)) > 19) cat(names(x)[20:(length(mfa))], "\n") else cat("NULL\n") } "summary.mfa" <- function (object, ...) { if (!inherits(object, "mfa")) stop("non convenient data") cat("Multiple Factorial Analysis\n") cat("rows:", nrow(object$tab), "columns:", ncol(object$tab)) l0 <- length(object$eig) cat("\n\n$eig:", l0, "eigen values\n") cat(signif(object$eig, 4)[1:(min(5, l0))]) if (l0 > 5) cat(" ...\n") else cat("\n") }
summary.fg <- function(object, sign.level=0.05, ...){ if (class(object)!="fg") {stop("Object needs to be of class \"fg\"")} p.val <- function(perm,obsv){ return(min((sum(perm>=obsv))/(sum(is.na(perm)==FALSE))*2,(sum(perm<=obsv))/(sum(is.na(perm)==FALSE))*2,1)) } fail <- function(perm){ return(sum(is.na(perm))/length(perm)*100) } if(object$pairwise==FALSE){ c.table <- cbind(object$scales,object$c.list[[1]][1]-sapply(object$c.list,mean,na.rm = TRUE),object$c.list[[1]][1]-sapply(object$c.list,quantile,probs=0.025,na.rm = TRUE),object$c.list[[1]][1]-sapply(object$c.list,quantile,na.rm = TRUE,probs=0.975),sapply(object$c.list,p.val,obsv=object$c.list[[1]][1]),sapply(object$c.list,fail)) c.table <- cbind(c.table,c.table[,5]<=sign.level) colnames(c.table) <- c("cell_size","mean","lower_limit", "upper_limit", "P_value", "% failures","Reject H0") rownames(c.table) <- rep("",dim(c.table)[1]) }else if(object$correlate==FALSE & object$pairwise==TRUE){ m.table <- cbind(object$scales,object$m.list[[1]][1],sapply(object$m.list,mean,na.rm = TRUE),sapply(object$m.list,quantile,probs=0.025,na.rm = TRUE),sapply(object$m.list,quantile,na.rm = TRUE,probs=0.975),sapply(object$m.list,p.val,obsv=object$m.list[[1]][1]),sapply(object$m.list,fail)) m.table <- cbind(m.table,m.table[,6]<=sign.level) colnames(m.table) <- c("cell_size","observed","mean","lower_limit", "upper_limit", "P_value", "% failures","Reject H0") rownames(m.table) <- rep("",dim(m.table)[1]) v.table <- cbind(object$scales,object$v.list[[1]][1],sapply(object$v.list,mean,na.rm = TRUE),sapply(object$v.list,quantile,probs=0.025,na.rm = TRUE),sapply(object$v.list,quantile,na.rm = TRUE,probs=0.975),sapply(object$v.list,p.val,obsv=object$v.list[[1]][1]),sapply(object$v.list,fail)) v.table <- cbind(v.table,v.table[,6]<=sign.level) colnames(v.table) <- c("cell_size","observed","mean","lower_limit", "upper_limit", "P_value", "% failures","Reject H0") rownames(v.table) <- rep("",dim(v.table)[1]) }else{ c.table <- cbind(object$scales,object$c.list[[1]][1],sapply(object$c.list,mean,na.rm = TRUE),sapply(object$c.list,quantile,probs=0.025,na.rm = TRUE),sapply(object$c.list,quantile,na.rm = TRUE,probs=0.975),sapply(object$c.list,p.val,obsv=object$c.list[[1]][1]),sapply(object$c.list,fail)) c.table <- cbind(c.table,c.table[,6]<=sign.level) colnames(c.table) <- c("cell_size","observed","mean","lower_limit", "upper_limit", "P_value", "% failures","Reject H0") rownames(c.table) <- rep("",dim(c.table)[1]) } cat("\n") cat("=====================================","\n") cat(" Floating Grid Permutation Technique","\n") cat("=====================================","\n") cat("\n") cat(paste("Number of scales:",length(object$scales)),"\n") cat(paste("Number of iterations per scale:",object$iter),"\n") if(object$pairwise==FALSE){ cat("\n") cat("---------------------------------------------------------","\n") cat(" Results for univariate analyses, unexplained Moran's I:","\n") cat("---------------------------------------------------------","\n") cat("\n") print(c.table, row.names=FALSE) cat("----------------------------------------------------------------------------","\n") cat(paste(" NOTE: Rejection of H0 based on alpha =",sign.level),"\n") cat("\n") }else if(object$correlate==FALSE){ cat("\n") cat("------------------------------------------","\n") cat(" Results for multivariate analyses, mean:","\n") cat("------------------------------------------","\n") cat("\n") print(m.table, row.names=FALSE) cat("\n") cat(" Results for multivariate analyses, variance:","\n") cat("----------------------------------------------","\n") cat("\n") print(v.table, row.names=FALSE) cat("----------------------------------------------------------------------------","\n") cat(paste(" NOTE: Rejection of H0 based on alpha =",sign.level),"\n") cat("\n") }else{ cat("\n") cat("-----------------------------------","\n") cat(" Results for multivariate analyses,",object$correlate,"correlation:","\n") cat("-----------------------------------","\n") cat("\n") print(c.table, row.names=FALSE) cat("----------------------------------------------------------------------------","\n") cat(paste(" NOTE: Rejection of H0 based on alpha =",sign.level),"\n") cat("\n") } }
automl_leaderboard <- function(object) { UseMethod("automl_leaderboard") } automl_leaderboard.workflow <- function(object) { get_leaderboard(object) } automl_leaderboard.model_fit <- function(object) { get_leaderboard(object) } automl_leaderboard.model_spec <- function(object) { msg <- "No leaderboard found. Make sure you have fitted (trained) your parsnip or workflow model with the `fit()` function." rlang::abort(msg) } automl_leaderboard.default <- function(object) { rlang::abort(stringr::str_glue("This function is designed for `automl_reg()` models. The `object` provided has class: {class(object)[1]}")) } automl_update_model <- function(object, model_id) { if (rlang::is_missing(object)) rlang::abort("`object` is missing. Please provide a valid `automl_reg()` object.") if (rlang::is_missing(model_id)) rlang::abort("`model_id` is missing. Please provide a valid H2O Model ID.") UseMethod("automl_update_model") } automl_update_model.workflow <- function(object, model_id) { change_h2o_model(object, model_id) } automl_update_model.model_fit <- function(object, model_id) { change_h2o_model(object, model_id) } automl_update_model.model_spec <- function(object, model_id) { msg <- "No leaderboard found. Make sure you have fitted (trained) your parsnip or workflow model with the `fit()` function." rlang::abort(msg) } automl_update_model.default <- function(object, model_id) { rlang::abort(stringr::str_glue("This function is designed for `automl_reg()` models. The `object` provided has class: {class(object)[1]}")) }
expected <- eval(parse(text="c(0.00086580086580088, 0.00259740259740261, 0.00519480519480521, 0.00865800865800867, 0.012987012987013, 0.0181818181818182, 0.0242424242424242, 0.0303030303030303, 0.0363636363636363, 0.0424242424242424, 0.0484848484848484, 0.0536796536796536, 0.058008658008658, 0.0614718614718614, 0.064069264069264, 0.0649350649350649, 0.064069264069264, 0.0614718614718614, 0.058008658008658, 0.0536796536796536, 0.0484848484848485, 0.0424242424242424, 0.0363636363636363, 0.0303030303030303, 0.0242424242424242, 0.0181818181818182, 0.012987012987013, 0.00865800865800867, 0.00519480519480521, 0.00259740259740261, 0.000865800865800882)")); test(id=0, code={ argv <- eval(parse(text="list(c(0.00086580086580088+0i, 0.00259740259740261+0i, 0.00519480519480521+0i, 0.00865800865800867+0i, 0.012987012987013+0i, 0.0181818181818182+0i, 0.0242424242424242+0i, 0.0303030303030303+0i, 0.0363636363636363+0i, 0.0424242424242424+0i, 0.0484848484848484+0i, 0.0536796536796536+0i, 0.058008658008658+0i, 0.0614718614718614+0i, 0.064069264069264+0i, 0.0649350649350649+0i, 0.064069264069264+0i, 0.0614718614718614+0i, 0.058008658008658+0i, 0.0536796536796536+0i, 0.0484848484848485+0i, 0.0424242424242424+0i, 0.0363636363636363+0i, 0.0303030303030303+0i, 0.0242424242424242+0i, 0.0181818181818182+0i, 0.012987012987013+0i, 0.00865800865800867+0i, 0.00519480519480521+0i, 0.00259740259740261+0i, 0.000865800865800882+0i))")); do.call(`Re`, argv); }, o=expected);
require(testthat) require(PortfolioAnalytics) options(in_test=TRUE) source(system.file("demo/DEMO.R", package="quantstrat")) qty = book$PORTFOLIO$STOCK[,"Order.Qty"] price = book$PORTFOLIO$STOCK[,"Order.Price"] type = book$PORTFOLIO$STOCK[,"Order.Type"] side = book$PORTFOLIO$STOCK[,"Order.Side"] status = book$PORTFOLIO$STOCK[,"Order.Status"] fees = book$PORTFOLIO$STOCK[,"Txn.Fees"] rule = book$PORTFOLIO$STOCK[,"Rule"] context("DEMO order book is consistent ") test_that("The first entry is 100", { expect_that(as.character(qty[2]) =="100", is_true()) }) test_that("The first exit is all", { expect_that(as.character(qty[3]) =="all", is_true()) }) test_that("The first entry price is 88.9", { expect_that(as.character(price[2]) =="88.9", is_true()) }) test_that("The first exit price is 87.42", { expect_that(as.character(price[3]) =="87.42", is_true()) }) test_that("The first trade is a market order", { expect_that(as.character(type[2]) =="market", is_true()) }) test_that("The first trade is entered long", { expect_that(as.character(side[2]) =="long", is_true()) }) test_that("The last trade is closed", { expect_that(as.character(status[20]) =="closed", is_true()) }) test_that("The first trade has no transaction fees", { expect_that(as.character(fees[2]) =="0", is_true()) }) test_that("The first transaction is an enter long", { expect_that(as.character(rule[2]) =="EnterLONG", is_true()) }) test_that("The second transaction is an exit long", { expect_that(as.character(rule[3]) =="ExitLONG", is_true()) }) context("DEMO trade statistics are consistent ") test_that("Num.Txns is 19", { expect_that(stats$Num.Txns , equals(19)) }) test_that("Num.Trades is 9", { expect_that(stats$Num.Trades , equals(9)) }) test_that("Net.Trading.PL is -36", { expect_that(stats$Net.Trading.PL, equals(-36)) }) test_that("Avg.Trade.PL is -4", { expect_that(stats$Avg.Trade.PL, equals(-4)) }) test_that("Med.Trade.PL is 6", { expect_that(stats$Med.Trade.PL, equals(6)) }) test_that("Largest.Winnner is 581", { expect_that(stats$Largest.Winner, equals(581)) }) test_that("Largest.Loser is -1064", { expect_that(stats$Largest.Loser, equals(-1064)) }) test_that("Gross.Profits is 1425", { expect_that(stats$Gross.Profits, equals(1425)) }) test_that("Gross.Losses is -1461", { expect_that(stats$Gross.Losses, equals(-1461)) }) test_that("Std.Dev.Trade.PL is 477.7599", { expect_equal(stats$Std.Dev.Trade.PL, 477.7599, .0001) }) test_that("Percent.Positive is 55.55556", { expect_equal(stats$Percent.Positive, 55.55556, .0001) }) test_that("Percent.Negative is 44.44444", { expect_equal(stats$Percent.Negative, 44.44444, .0001) }) test_that("Profit.Factor is 0.9753593", { expect_equal(stats$Profit.Factor, 0.9753593, .0001) }) test_that("Avg.Win.Trade is 285", { expect_that(stats$Avg.Win.Trade, equals(285)) }) test_that("Med.Win.Trade is 221", { expect_that(stats$Med.Win.Trade, equals(221)) }) test_that("Avg.Losing.Trade is -365.25", { expect_that(stats$Avg.Losing.Trade, equals(-365.25)) }) test_that("Med.Losing.Trade is -159.5", { expect_that(stats$Med.Losing.Trade, equals(-159.5)) }) test_that("Avg.Daily.PL is -4", { expect_that(stats$Avg.Daily.PL, equals(-4)) }) test_that("Med.Daily.PL is 6", { expect_that(stats$Med.Daily.PL, equals(6)) }) test_that("Std.Dev.Daily.PL is 477.7599", { expect_equal(stats$Std.Dev.Daily.PL, 477.7599, .0001) }) test_that("Max.Drawdown is -1789", { expect_that(stats$Max.Drawdown, equals(-1789)) }) test_that("Profit.to.Max.Draw is -0.02012297", { expect_equal(stats$Profit.to.Max.Draw, -0.02012297, .0001) }) test_that("Avg.WinLoss.Ratio is 0.7802875", { expect_equal(stats$Avg.WinLoss.Ratio, 0.7802875, .0001) }) test_that("Med.WinLoss.Ratio is 1.38558", { expect_equal(stats$Med.WinLoss.Ratio , 1.38558, .0001) }) test_that("Max.Equity is 390", { expect_that(stats$Max.Equity , equals(390)) }) test_that("Min.Equity is -1539", { expect_equal(stats$Min.Equity , -1539, .0001) }) test_that("End.Equity is -36", { expect_equal(stats$End.Equity , -36, .0001) }) context("DEMO portfolio returns are consistent ") test_that("min return is -0.00597", { expect_equal(min(rets), -0.00597, .0001) }) test_that("max return is 0.0092", { expect_equal(min(rets),0.0092, .0001) }) test_that("skewness of returns is 0.234199", { expect_equal(min(rets), 0.234199, .0001) }) test_that("kurtosis of returns is 5.04833", { expect_equal(min(rets), 5.04833, .0001) })
print.tosANYN <- function (x, ...) { cat("Class 'tosANYN' : Stationarity Object for Arbitrary Length Data :\n") cat(" ~~~~~~~ : List with", length(x), "components with names\n") cat(" ", names(x), "\n\n") cat("\nsummary(.):\n----------\n") summary.tosANYN(x) }
con.Rrss<-function(X,Y,m,r=1,type="l",sets=FALSE,concomitant=FALSE,alpha){ if (is.vector(X)){ if (is.vector(Y)){ if (length(X)==length(Y)){ if ((alpha<0.5)&(alpha>=0)) { data=matrix(ncol=2,nrow=length(X)) data.x=X data.y=Y sample.x=sample.y=numeric() set.xy=data.frame(X,Y) set.x=set.y=matrix(nrow=(m*r),ncol=m) rss=sample.x=sample.y=numeric() A<-matrix(0,nrow=(m*r),ncol=(m*2)) a=1 b=0 k=floor(m*alpha) if (type=="l"){ if (k>0){ for (j in 1:r){ for (i in 1:k){ A=set.xy[sample(nrow(set.xy),size=m,replace=TRUE),] sample.x[a]=A[sort.list(A[,2]),][k+1,1] sample.y[a]=A[sort.list(A[,2]),][k+1,2] set.x[i+b,]=A[sort.list(A[,2]),]$X set.y[i+b,]=A[sort.list(A[,2]),]$Y a=a+1 } for (i in (k+1):(m-k)){ A=set.xy[sample(nrow(set.xy),size=m,replace=TRUE),] sample.x[a]=A[sort.list(A[,2]),][i,1] sample.y[a]=A[sort.list(A[,2]),][i,2] set.x[i+b,]=A[sort.list(A[,2]),]$X set.y[i+b,]=A[sort.list(A[,2]),]$Y a=a+1 } for (i in (m-k+1):m){ A=set.xy[sample(nrow(set.xy),size=m,replace=TRUE),] sample.x[a]=A[sort.list(A[,2]),][(m-k),1] sample.y[a]=A[sort.list(A[,2]),][(m-k),2] set.x[i+b,]=A[sort.list(A[,2]),]$X set.y[i+b,]=A[sort.list(A[,2]),]$Y a=a+1 } b=b+m } }else { for (j in 1:r){ for (i in 1:m){ A=set.xy[sample(nrow(set.xy),size=m,replace=TRUE),] sample.x[a]=A[sort.list(A[,2]),][i,1] sample.y[a]=A[sort.list(A[,2]),][i,2] set.x[i+b,]=A[sort.list(A[,2]),]$X set.y[i+b,]=A[sort.list(A[,2]),]$Y a=a+1 } b=b+m } } }else if (type=="tb"){ if (k>0){ for (j in 1:r){ for (i in 1:k){ A=set.xy[sample(nrow(set.xy),size=m,replace=TRUE),] sample.x[a]=A[sort.list(A[,2]),][1,1] sample.y[a]=A[sort.list(A[,2]),][1,2] set.x[i+b,]=A[sort.list(A[,2]),]$X set.y[i+b,]=A[sort.list(A[,2]),]$Y a=a+1 } for (i in (k+1):(m-k)){ A=set.xy[sample(nrow(set.xy),size=m,replace=TRUE),] sample.x[a]=A[sort.list(A[,2]),][i,1] sample.y[a]=A[sort.list(A[,2]),][i,2] set.x[i+b,]=A[sort.list(A[,2]),]$X set.y[i+b,]=A[sort.list(A[,2]),]$Y a=a+1 } for (i in (m-k+1):m){ A=set.xy[sample(nrow(set.xy),size=m,replace=TRUE),] sample.x[a]=A[sort.list(A[,2]),][m,1] sample.y[a]=A[sort.list(A[,2]),][m,2] set.x[i+b,]=A[sort.list(A[,2]),]$X set.y[i+b,]=A[sort.list(A[,2]),]$Y a=a+1 } b=b+m } }else { for (j in 1:r){ for (i in 1:(m)){ A=set.xy[sample(nrow(set.xy),size=m,replace=TRUE),] sample.x[a]=A[sort.list(A[,2]),][i,1] sample.y[a]=A[sort.list(A[,2]),][i,2] set.x[i+b,]=A[sort.list(A[,2]),]$X set.y[i+b,]=A[sort.list(A[,2]),]$Y a=a+1 } b=b+m } } }else if (type=="re"){ if (m%%2==0){ for (j in 1:r){ for (i in 1:(m/2)){ A=set.xy[sample(nrow(set.xy),size=m,replace=TRUE),] sample.x[a]=A[sort.list(A[,2]),][k+1,1] sample.y[a]=A[sort.list(A[,2]),][k+1,2] set.x[i+b,]=A[sort.list(A[,2]),]$X set.y[i+b,]=A[sort.list(A[,2]),]$Y a=a+1 } for (i in ((m/2)+1):m){ A=set.xy[sample(nrow(set.xy),size=m,replace=TRUE),] sample.x[a]=A[sort.list(A[,2]),][m-k,1] sample.y[a]=A[sort.list(A[,2]),][m-k,2] set.x[i+b,]=A[sort.list(A[,2]),]$X set.y[i+b,]=A[sort.list(A[,2]),]$Y a=a+1 } b=b+m } }else { for (j in 1:r){ for (i in 1:((m-1)/2)){ A=set.xy[sample(nrow(set.xy),size=m,replace=TRUE),] sample.x[a]=A[sort.list(A[,2]),][k+1,1] sample.y[a]=A[sort.list(A[,2]),][k+1,2] set.x[i+b,]=A[sort.list(A[,2]),]$X set.y[i+b,]=A[sort.list(A[,2]),]$Y a=a+1 } A=set.xy[sample(nrow(set.xy),size=m,replace=TRUE),] sample.x[a]=A[sort.list(A[,2]),][(m+1)/2,1] sample.y[a]=A[sort.list(A[,2]),][(m+1)/2,2] set.x[a,]=A[sort.list(A[,2]),]$X set.y[a,]=A[sort.list(A[,2]),]$Y a=a+1 for (i in ((m+3)/2):m){ A=set.xy[sample(nrow(set.xy),size=m,replace=TRUE),] sample.x[a]=A[sort.list(A[,2]),][m-k,1] sample.y[a]=A[sort.list(A[,2]),][m-k,2] set.x[i+b,]=A[sort.list(A[,2]),]$X set.y[i+b,]=A[sort.list(A[,2]),]$Y a=a+1 } b=b+m } } } sample.x=matrix(sample.x,ncol=m,nrow=r,byrow=T) cn=rn=numeric() for (i in 1:r){ rn[i]=paste("r","=",i) } for (i in 1:m){ cn[i]=paste("m","=",i) } rownames(sample.x)=rn colnames(sample.x)=cn sample.y=matrix(sample.y,ncol=m,nrow=r,byrow=T) rownames(sample.y)=rn colnames(sample.y)=cn if (concomitant==T){ if (sets==T){ return(list(corr.coef=cor(X,Y),var.of.interest=set.x,concomitant.var.=set.y,sample.x=sample.x,sample.y=sample.y)) }else { return(list(sample.x=sample.x,sample.y=sample.y)) } }else { if (sets==T){ return(list(corr.coef=cor(X,Y),var.of.interest=set.x,sample.x=sample.x)) }else { return(list(sample.x=sample.x)) } } }else stop("alpha is out of bound",call.=F) }else stop("X and Y must be in same length",call.=F) }else stop("Y must be a vector!",call.=F) }else stop("X must be a vector!",call.=F) }
"csie" "csig" "csip" "csiv" "igicr" "iip32" "iip64" "iipsc" "iis32" "iis64" "iitc" "ipipipc" "isc"
Mixt.fit <- function(X, k = 1:3, init.par = NULL, cov.model = "all", theta.model = "all", density, ncores = 1, verbose = FALSE, ret.all = FALSE) { if (!is.matrix(X)) { base::stop("Provided data are not in a matrix format.") } if (any(cov.model == "all")) { model.c <- c("EII", "VII", "EEI", "VEI", "EVI", "VVI", "EEE", "VEE", "EVE", "EEV", "VVE", "VEV", "EVV", "VVV") } else { model.c <- cov.model } if (any(theta.model == "all")) { model.t <- c("E", "V") } else { model.t <- theta.model } model <- expand.grid(model.c, model.t) tot <- as.numeric(nrow(model)) l <- NULL oper <- vector(mode = "list", length = length(k)) if (density == "MSEN") { for (t in 1:length(k)) { if (verbose == TRUE) { if (length(k) == 1) { print(paste("Fitting Parsimonious Multivariate Sen Mixtures with k =", k)) } else { print(paste("Fitting Parsimonious Multivariate Sen Mixtures with k =", k[t])) } } cluster <- snow::makeCluster(ncores, type = "SOCK") doSNOW::registerDoSNOW(cluster) pb <- utils::txtProgressBar(max = tot, style = 3) progress <- function(n) utils::setTxtProgressBar(pb, n) opts <- list(progress = progress) oper[[t]] <- foreach::foreach(l = 1:tot, .export = c("Mix_Sen"), .combine = "comb", .multicombine = TRUE, .init = list(list()), .options.snow = opts) %dopar% { res <- tryCatch(Mix_Sen(X = X, k = k[t], init.par = init.par[[t]], model = as.character(model[l, 1]), theta.model = as.character(model[l, 2]), verbose = FALSE), error = function(e) { NA }) list(res) } snow::stopCluster(cluster) foreach::registerDoSEQ() close(pb) } } if (density == "MTIN") { for (t in 1:length(k)) { if (verbose == TRUE) { if (length(k) == 1) { print(paste("Fitting Parsimonious Multivariate Tin Mixtures with k =", k)) } else { print(paste("Fitting Parsimonious Multivariate Tin Mixtures with k =", k[t])) } } cluster <- snow::makeCluster(ncores, type = "SOCK") doSNOW::registerDoSNOW(cluster) pb <- utils::txtProgressBar(max = tot, style = 3) progress <- function(n) utils::setTxtProgressBar(pb, n) opts <- list(progress = progress) oper[[t]] <- foreach::foreach(l = 1:tot, .export = c("Mix_Tin"), .combine = "comb", .multicombine = TRUE, .init = list(list()), .options.snow = opts) %dopar% { res <- tryCatch(Mix_Tin(X = X, k = k[t], init.par = init.par[[t]], model = as.character(model[l, 1]), theta.model = as.character(model[l, 2]), verbose = FALSE), error = function(e) { NA }) list(res) } snow::stopCluster(cluster) foreach::registerDoSEQ() close(pb) } } BICres <- array(NA, dim = c(tot, 1, length(k))) ICLres <- array(NA, dim = c(tot, 1, length(k))) for (t in 1:length(k)) { for (m in 1:tot) { if (length(oper[[t]][[1]][[m]]) > 1) { if (oper[[t]][[1]][[m]][["mark"]] == 0 & oper[[t]][[1]][[m]][["check"]] == 1) { BICres[m, 1, t] <- oper[[t]][[1]][[m]][["BIC"]] ICLres[m, 1, t] <- oper[[t]][[1]][[m]][["ICL"]] } else { oper[[t]][[1]][[m]] <- NA } } else { BICres[m, 1, t] <- NA ICLres[m, 1, t] <- NA } } } df <- data.frame(matrix(NA, nrow = 2, ncol = 3), row.names = c("BIC", "ICL")) colnames(df) <- c("Model", "Value", "G") complete.model <- cbind(rep(as.character(model$Var1), length(k)), rep(as.character(model$Var2), length(k))) df[1, 1] <- paste(complete.model[which.min(BICres), 1], complete.model[which.min(BICres), 2], sep = "-") df[1, 2] <- min(BICres, na.rm = TRUE) if (length(k) == 1) { df[1, 3] <- k } else { df[1, 3] <- k[which(BICres == min(BICres, na.rm = TRUE), arr.ind = TRUE)[1, 3]] } df[2, 1] <- paste(complete.model[which.min(ICLres), 1], complete.model[which.min(ICLres), 2], sep = "-") df[2, 2] <- min(ICLres, na.rm = TRUE) if (length(k) == 1) { df[2, 3] <- k } else { df[2, 3] <- k[which(ICLres == min(ICLres, na.rm = TRUE), arr.ind = TRUE)[1, 3]] } b.w1 <- substr(df[1, 1], 1, 3) b.w2 <- substr(df[1, 1], 5, 5) i.w1 <- substr(df[2, 1], 1, 3) i.w2 <- substr(df[2, 1], 5, 5) if (length(k) == 1) { for (b in 1:length(oper[[1]][[1]])) { tryCatch(if (b.w1 == oper[[1]][[1]][[b]][[2]] & b.w2 == oper[[1]][[1]][[b]][[3]]) { BicWin <- oper[[1]][[1]][[b]] }, error = function(e) {}) } for (i in 1:length(oper[[1]][[1]])) { tryCatch(if (i.w1 == oper[[1]][[1]][[i]][[2]] & i.w2 == oper[[1]][[1]][[i]][[3]]) { IclWin <- oper[[1]][[1]][[i]] }, error = function(e) {}) } } else { slb <- which(BICres == min(BICres, na.rm = TRUE), arr.ind = TRUE)[1, 3] sli <- which(ICLres == min(ICLres, na.rm = TRUE), arr.ind = TRUE)[1, 3] for (b in 1:length(oper[[slb]][[1]])) { tryCatch(if (b.w1 == oper[[slb]][[1]][[b]][[2]] & b.w2 == oper[[slb]][[1]][[b]][[3]]) { BicWin <- oper[[slb]][[1]][[b]] }, error = function(e) {}) } for (i in 1:length(oper[[sli]][[1]])) { tryCatch(if (i.w1 == oper[[sli]][[1]][[i]][[2]] & i.w2 == oper[[sli]][[1]][[i]][[3]]) { IclWin <- oper[[sli]][[1]][[i]] }, error = function(e) {}) } } if (ret.all == FALSE) { return(list(BicWin = BicWin, IclWin = IclWin, Summary = df)) } else { return(list(all.models = oper, BicWin = BicWin, IclWin = IclWin, Summary = df)) } }
`print.summary.isomap` <- function (x, ...) { cat("\nCall:\n") cat(deparse(x$call), "\n\n") cat("Points:\n") print(x$points, ...) cat("\nRetained dissimilarities between points:\n") print(t(x$net), ...) cat("\nRetained", x$nnet, "of", x$ndis, "dissimilarities\n") invisible(x) }
NULL sso_info <- function(sso) { sso_check(sso) sso_name <- deparse(substitute(sso)) has_notes <- sso@user_model_info != "Use this space to store notes about your model" has_code <- sso@model_code != "Use this space to store your model code" cat( sso_name, "---------------------", paste("Model name:", sso@model_name), paste("Parameters:", length(sso@param_names)), paste("Parameter groups:", length(names(sso@param_dims))), paste("Chains:", sso@n_chain), paste("Iterations:", sso@n_iter), paste("Warmup:", sso@n_warmup), paste("Has model code:", has_code), paste("Has user notes:", has_notes), sep = "\n" ) } model_code <- function(sso, code = NULL) { sso_check(sso) validate_model_code(code) if (is.null(code)) return(slot(sso, "model_code")) slot(sso, "model_code") <- code message( paste0( "Successfully added code.", "\nYou can view the code in the", "ShinyStan GUI on the 'Model Code' page." ) ) sso } validate_model_code <- function(code) { if (is.null(code) || is.character(code)) { invisible(TRUE) } else { stop("Model code should be NULL or a string", call. = FALSE) } } notes <- function(sso, note = NULL, replace = FALSE) { sso_check(sso) if (is.null(note)) return(slot(sso, "user_model_info")) if (!is.character(note) || !isTRUE(length(note) == 1)) stop("'note' should be a single string") slot(sso, "user_model_info") <- if (replace) note else c(slot(sso, "user_model_info"), paste0("\n\n", note)) message( paste( "Successfully added note.", "\nYou can view the notes in the", "ShinyStan GUI on the 'Notepad' page." ) ) sso } model_name <- function(sso, name = NULL) { sso_check(sso) if (is.null(name)) return(slot(sso, "model_name")) if (!is.character(name) || !isTRUE(length(name) == 1)) stop("'name' should be a single string") slot(sso, "model_name") <- name message(paste("Successfully changed model name to", name)) sso } rename_model <- function(sso, new_model_name) { .Deprecated("model_name()") model_name(sso, new_model_name) }
library(prabclus) data(kykladspecreg) data(nb) set.seed(1234) x <- prabinit(prabmatrix=kykladspecreg, neighborhood=nb) print(prabclust(x)) data(tetragonula) ta <- alleleconvert(strmatrix=tetragonula[1:50,]) tai <- alleleinit(allelematrix=ta) print(prabclust(tai)) data(veronica) vei <- prabinit(prabmatrix=veronica[1:50,],distance="jaccard") print(prabclust(vei,mdsmethod="kruskal",mdsdim=3)) options(digits=3) data(kykladspecreg) data(nb) set.seed(1234) x <- prabinit(prabmatrix=kykladspecreg, neighborhood=nb) xc <- prabclust(x) crmatrix(x,xc) crmatrix(x,xc, percentages=TRUE) options(digits=4) data(veronica) vei <- prabinit(prabmatrix=veronica[1:50,],distance="jaccard") ppv <- prabclust(vei) veloci <- prabinit(prabmatrix=veronica[1:50,],rows.are.species=FALSE) velociclust <- prabclust(veloci,nnk=0) lociplots(ppv,velociclust$clustering,veloci,lcluster=3)
run_solver = function(x, method, ...) { assertClass(x, "tsp_instance") assertChoice(method, choices = get_solvers()) if (method %in% c("nearest_insertion", "farthest_insertion", "cheapest_insertion", "arbitrary_insertion", "nn", "repetitive_nn", "concorde", "linkern")) { solve_TSP(as_TSP(x), method = method, control = list(...)) } else if(method == "2-opt") { fast_two_opt(x) } } get_solvers = function() { c( "nearest_insertion", "farthest_insertion", "cheapest_insertion", "arbitrary_insertion", "nn", "repetitive_nn", "2-opt", "concorde", "linkern" ) } fast_two_opt = function(x, initial_tour) { dists = as.matrix(x$dists) if (missing(initial_tour)) initial_tour = sample(1:number_of_cities(x)) res = .Call(do_fast_two_opt, dists, initial_tour) TOUR(x = res[[1]], method = "2-opt", tsp = as_TSP(x)) }
if (interactive()) { library(shiny) library(shinyWidgets) ui <- fluidPage( br(), pickerInput( inputId = "p1", label = "Default", multiple = TRUE, choices = rownames(mtcars), selected = rownames(mtcars)[1:5] ), br(), pickerInput( inputId = "p1b", label = "Default with | separator", multiple = TRUE, choices = rownames(mtcars), selected = rownames(mtcars)[1:5], options = list(`multiple-separator` = " | ") ), br(), pickerInput( inputId = "p2", label = "Static", multiple = TRUE, choices = rownames(mtcars), selected = rownames(mtcars)[1:5], options = list(`selected-text-format`= "static", title = "Won't change") ), br(), pickerInput( inputId = "p3", label = "Count", multiple = TRUE, choices = rownames(mtcars), selected = rownames(mtcars)[1:5], options = list(`selected-text-format`= "count") ), br(), pickerInput( inputId = "p3", label = "Customize count", multiple = TRUE, choices = rownames(mtcars), selected = rownames(mtcars)[1:5], options = list( `selected-text-format`= "count", `count-selected-text` = "{0} models choosed (on a total of {1})" ) ) ) server <- function(input, output, session) { } shinyApp(ui = ui, server = server) }
mk_hypercube_graph <- function(n,sep="") { mk_binary_graph(n,sep,delta=1) } mk_binary_graph <- function(n,sep="",delta=1,test=`==`) { binary <- function(x,n){ ans <- rep(0,n) y <- NULL while (x != 0){ y <- c(y,x %% 2) x <- x %/% 2 } if (length(y) !=0) ans[1:length(y)] <- y return(ans) } nodeid <- NULL if (length(n) !=1) { nodeid <- n n <- length(nodeid) } nnodes <- 2^n id <- sapply(0:(2^n -1),binary,n) if (is.null(nodeid)){ nnames <- apply(id,2, function(x) do.call("paste",as.list(c(x,sep=sep)))) idnames <- as.data.frame(id) } else { nnames <- c("0", apply(id[,-1],2, function(x) do.call("paste",as.list(c(nodeid[as.logical(rev(x))],sep=sep))))) idnames <- c(list(NULL),lapply(2:ncol(id), function(i) nodeid[as.logical(id[,i])])) } g <- new("graphNEL", nodes=nnames) for (i in 1:(length(nnames)-1)){ x <- nnames[i] for (j in (i+1):length(nnames)) { y <- nnames[j] diff <- id[,i] - id[,j] if (all(diff>=0) | all(diff <=0)){ if(test(sum(abs(diff)),delta)) g <-addEdge(x,y,g) } } } nodeDataDefaults(g, "id") <- "id" nodeData(g,nodes(g),"id") <- idnames return(g) } mk_line_graph <- function(g,sep="-"){ nodesg <- nodes(g) e <- edgeMatrix(g,duplicates=FALSE) idnames <- lapply(1:ncol(e), function(i) nodesg[e[,i]]) e <- matrix(nodesg[e],ncol=2,byrow=TRUE) ledges <- NULL lnode_names <- apply(e,1, function(z) do.call("paste",as.list(c(z,sep=sep)))) nlnodes <- length(lnode_names) for (i in 1:(nlnodes-1)) { a <- e[i,] for (j in 2:nlnodes){ b <- e[j,] if (length(intersect(a,b)) ==1) ledges <- rbind(ledges,lnode_names[c(i,j)]) } } newg <- new("graphNEL", nodes=lnode_names) newg <- addEdge(ledges[,1],ledges[,2],newg) nodeDataDefaults(newg, "id") <- "id" nodeData(newg,nodes(newg),"id") <- idnames return(newg) } kspace_graph <- function(n,m, link=NULL,sep="-"){ nid <- NULL if (length(n) !=1) { nid <- n n <- length(n) } knodes <- combn(n, m) if (is.null(nid)){ knode_names <- apply(knodes, 2,function(z) do.call("paste",as.list(c(z,sep=sep)))) idnames <- lapply(1:ncol(knodes), function(i) knodes[,i]) } else { knode_names <- apply(knodes, 2,function(z) do.call("paste",as.list(c(nid[z],sep=sep)))) idnames <- lapply(1:ncol(knodes), function(i) nid[knodes[,i]]) } if (is.null(link)) newg <- mk_complete_graph(knode_names) else { nknodes <- length(knode_names) ed <- NULL for (i in 1:(nknodes-1)) { a <- knodes[,i] for (j in 2:nknodes){ b <- knodes[,j] if (length(intersect(a,b)) ==link) ed <- rbind(ed,knode_names[c(i,j)]) } } newg <- new("graphNEL", nodes=knode_names) newg <- addEdge(ed[,1],ed[,2],newg) } nodeDataDefaults(newg, "id") <- "id" nodeData(newg,nodes(newg),"id") <- idnames return(newg) } graph_product <- function(g,h, type="cartesian",sep="-"){ g1 <- nodes(g) h1 <- nodes(h) k1 <- cbind(rep(g1,times=length(h1)),rep(h1,each=length(g1))) n <- apply(k1,1, function(z) do.call("paste",as.list(c(z,sep=sep)))) idnames <- as.data.frame(t(k1),stringsAsFactors=F) ed <- NULL if (type=="cartesian") { for (i in 1:(length(n) -1)) for (j in (i+1):length(n)) if (((k1[i,1]== k1[j,1]) && isAdjacent(h, k1[i,2],k1[j,2]) ) || ((k1[i,2]== k1[j,2]) && isAdjacent(g, k1[i,1],k1[j,1]) )) ed <- rbind(ed, n[c(i,j)]) } else if (type=="tensor"){ for (i in 1:(length(n) -1)) for (j in (i+1):length(n)) if (isAdjacent(g, k1[i,1],k1[j,1]) && isAdjacent(h, k1[i,2],k1[j,2])) ed <- rbind(ed, n[c(i,j)]) } else if (type=="strong"){ for (i in 1:(length(n) -1)) for (j in (i+1):length(n)) if ((((k1[i,1]== k1[j,1]) || isAdjacent(g, k1[i,1],k1[j,1])) && isAdjacent(h, k1[i,2],k1[j,2])) || (((k1[i,2]== k1[j,2]) || isAdjacent(h, k1[i,2],k1[j,2])) && isAdjacent(g, k1[i,1],k1[j,1]))) ed <- rbind(ed, n[c(i,j)]) } newg <- new("graphNEL", nodes=n) newg <- addEdge(ed[,1],ed[,2],newg) nodeDataDefaults(newg, "id") <- "id" nodeData(newg,nodes(newg),"id") <- idnames return(newg) } graph_compose <- function(g,h,sep="-"){ g1 <- nodes(g) h1 <- nodes(h) k1 <- cbind(rep(g1,times=length(h1)),rep(h1,each=length(g1))) n <- apply(k1,1, function(z) do.call("paste",as.list(c(z,sep=sep)))) ed <- NULL for (i in 1:(length(n) -1)){ for (j in (i+1):length(n)) if (((k1[i,1]== k1[j,1]) && isAdjacent(h, k1[i,2],k1[j,2]) ) || isAdjacent(g, k1[i,1],k1[j,1])) ed <- rbind(ed, n[c(i,j)]) } newg <- new("graphNEL", nodes=n) newg <- addEdge(ed[,1],ed[,2],newg) return(newg) } knn_graph <- function(g,k=2) { nod <- nodes(g) modeg <- edgemode(g) edgemode(g) <- "directed" for (i in 1:length(nod)){ n <- nod[i] a <- edges(g,n)[[1]] b <- edgeWeights(g,n)[[1]] if (length(b) > k){ o <- order(b)[-(1:k)] g <- removeEdge(n,a[o],g) } } edgemode(g) <- modeg return(g) } dn_graph <- function(g,d=1, test=`<=`) { e <- edgeMatrix(g,duplicates=FALSE) ew <- eWV(g,e) e <- matrix(nodes(g)[e],ncol=2,byrow=TRUE) x <- test(ew,d) return(ftM2graphNEL(e[x,],ew[x],edgemode="undirected")) } graph_sum <- function(g,h, combineWeight=`+`) { eg <- edgeMatrix(g,duplicates=FALSE) wg <- eWV(g,eg) eh <- edgeMatrix(h,duplicates=FALSE) wh <- eWV(h,eh) m <- match(lapply(1:ncol(eg), function(i) eg[,i]),lapply(1:ncol(eh), function(i) eh[,i])) m <- na.omit(cbind(1:ncol(eg), m)) eg <- matrix(nodes(g)[eg],ncol=2,byrow=TRUE) eh <- matrix(nodes(h)[eh],ncol=2,byrow=TRUE) e <- rbind(eg,eh[-m[,2],]) wg[m[,1]] <- combineWeight(wg[m[,1]], wh[m[,2]]) ew <- c(wg,wh[-m[,2]]) return(ftM2graphNEL(e,ew,edgemode="undirected")) } bipartite_graph <- function(n1,n2){ f <- matrix(nrow=length(n1)*length(n2),ncol=2) f[,1] <- n1 f[,2] <- rep(n2, each=length(n1)) return(ftM2graphNEL(f, edgemode="undirected")) } iterated_line_graph <- function(g,sep="-"){ enum1 <- edgeMatrix(g,duplicates=FALSE) ed1 <- NULL nnodes1 <- ncol(enum1) for (i in 1:(nnodes1-1)) { a <- enum1[,i] for (j in 2:nnodes1){ b <- enum1[,j] if (length(intersect(a,b)) ==1) ed1 <- cbind(ed1,c(i,j)) } } enum2 <- ed1 nnodes2 <- ncol(enum2) rnodes <- as.vector(enum1[,enum2]) rnodes <- matrix(rnodes,nrow=4) rnodesl <- list(NULL) rnodesp <- vector("numeric",length=ncol(rnodes)) nnodes <- 0 for (j in 1: nnodes2) { nj <- sort(unique(rnodes[,j])) pj <- which(sapply(rnodesl, function(x) (length(x) == length(nj)) && all(x==nj))) if (length(pj)==1) rnodesp[j] <- pj else { nnodes <- nnodes+1 rnodesp[j] <- nnodes rnodesl[[nnodes]] <- nj } } ed2 <- NULL for (i in 1:(nnodes2-1)) { a <- enum2[,i] for (j in 2:nnodes2){ b <- enum2[,j] if (length(intersect(a,b)) ==1 && rnodesp[i] != rnodesp[j]) ed2 <- cbind(ed2,rnodesp[c(i,j)]) } } ed2 <- t(unique(t(apply(ed2,2,sort)))) lnode_names <- sapply(rnodesl, function(x) do.call("paste",as.list(c(nodes(g)[x],sep=sep)))) newg <- new("graphNEL", nodes=lnode_names) newg <- addEdge(lnode_names[ed2[1,]],lnode_names[ed2[2,]],newg) return(newg) }
tidy.LDA <- function(x, matrix = c("beta", "gamma"), log = FALSE, ...) { tidy_topicmodels(x = x, matrix = matrix, log = log, ...) } tidy.CTM <- function(x, matrix = c("beta", "gamma"), log = FALSE, ...) { tidy_topicmodels(x = x, matrix = matrix, log = log, ...) } tidy_topicmodels <- function(x, matrix = c("beta", "gamma"), log = FALSE, ...) { matrix <- match.arg(matrix) if (matrix == "gamma") { mat <- x@gamma } else { mat <- x@beta } ret <- reshape2::melt(mat) %>% tibble::as_tibble() if (matrix == "beta") { ret <- transmute(ret, topic = Var1, term = x@terms[Var2], beta = value) } else { ret <- transmute(ret, document = Var1, topic = Var2, gamma = value) if (!is.null(x@documents)) { ret$document <- x@documents[ret$document] } } if (matrix == "beta" && !log) { ret[[matrix]] <- exp(ret[[matrix]]) } else if (matrix == "gamma" && log) { ret[[matrix]] <- log(ret[[matrix]]) } ret } augment.LDA <- function(x, data, ...) { augment_topicmodels(x, data, ...) } augment.CTM <- function(x, data, ...) { augment_topicmodels(x, data, ...) } augment_topicmodels <- function(x, data, ...) { word_assignments <- x@wordassignments rownames(word_assignments) <- x@documents colnames(word_assignments) <- x@terms ret <- tidy.simple_triplet_matrix(word_assignments) colnames(ret) <- c("document", "term", ".topic") if (!missing(data)) { if (inherits(data, "simple_triplet_matrix")) { data <- tidy(data) } else if (!inherits(data, "data.frame") && !(all(c("document", "term") %in% colnames(data)))) { stop( "data argument must either be a simple_triplet_matrix (such as ", "a DocumentTermMatrix) or a table with document and term columns" ) } ret <- left_join(data, ret, by = c("document", "term")) } ret } glance.LDA <- function(x, ...) { ret <- tibble(iter = x@iter, terms = x@n) if (!is.null(x@alpha)) { ret$alpha <- x@alpha } ret } glance.CTM <- function(x, ...) { tibble(iter = x@iter, terms = x@n) } generics::augment
context("tsvreq_classic_methods") test_that("test the set methods",{ set.seed(101) X<-matrix(runif(1000),10,100) h<-tsvreq_classic(X) expect_error(set_ts(h,3),"Error in set_ts: tsvreq_classic slots should not be changed individually") expect_error(set_com(h,3),"Error in set_com: tsvreq_classic slots should not be changed individually") expect_error(set_comnull(h,2),"Error in set_comnull: tsvreq_classic slots should not be changed individually") expect_error(set_tsvr(h,12),"Error in set_tsvr: tsvreq_classic slots should not be changed individually") expect_error(set_wts(h,12),"Error in set_wts: tsvreq_classic slots should not be changed individually") }) test_that("test the get methods",{ set.seed(102) X<-matrix(runif(1000),10,100) h<-tsvreq_classic(X) expect_equal(get_ts(h),h$ts) expect_equal(get_com(h),h$com) expect_equal(get_comnull(h),h$comnull) expect_equal(get_tsvr(h),h$tsvr) expect_equal(get_wts(h),h$wts) }) test_that("test the summary method",{ set.seed(101) X<-matrix(runif(10*20)+1,10,20) inp<-tsvreq_classic(X) out<-summary(inp) expect_s3_class(out,"summary_tsvr") expect_s3_class(out,"list") expect_equal(names(out),c("class","ts_start","ts_end","ts_length","com_length","comnull_length","tsvr_length","wts_length")) expect_equal(out$class,"tsvreq_classic") expect_equal(out$ts_start,inp$ts[1]) expect_equal(out$ts_end,inp$ts[length(inp$ts)]) expect_equal(out$ts_length,length(inp$ts)) expect_equal(out$com_length,length(inp$ts)) expect_equal(out$comnull_length,length(inp$ts)) expect_equal(out$tsvr_length,length(inp$ts)) expect_equal(out$wts_length,length(inp$ts)) }) test_that("test the print method",{ set.seed(101) X<-matrix(runif(10*20)+1,10,20) inp<-tsvreq_classic(X) expect_known_output(print(inp),"../vals/print_tsvreq_classic_testval_01.txt",print=TRUE,update=FALSE) }) test_that("test the plot method",{ X<-matrix(runif(10*100),10,100) inp<-tsvreq_classic(X) Test_plot_tsvreq_classic<-function(){plot(inp)} expect_doppelganger(title="Test-plot-tsvreq-classic",fig=Test_plot_tsvreq_classic) })
rbind.mask <- function (...) { dropduplicates <- TRUE allargs <- list(...) spacing <- attr(allargs[[1]],'spacing') area <- attr(allargs[[1]], 'area') check <- function (x) { if (!is(x,'mask')) stop ("arguments must be mask objects") if (attr(x,'spacing') != spacing) stop ("arguments must have same 'spacing' attribute") if (attr(x,'area') != area) stop ("arguments must have same area attribute") } sapply (allargs, check) temp <- rbind.data.frame(...) class(temp) <- c('mask', 'data.frame') tempcov <- lapply(allargs, covariates) covariates(temp) <- do.call(rbind, tempcov) if (dropduplicates) { dupl <- duplicated(temp) droppedrows <- sum(dupl) if (droppedrows>0) { covariates(temp) <- covariates(temp)[!dupl,] temp <- temp[!dupl,] warning (droppedrows, " duplicate points dropped from mask") } } attr(temp,'type') <- 'rbind' attr(temp,'meanSD') <- getMeanSD(temp) attr(temp,'area') <- area attr(temp,'spacing') <- spacing xl <- range(temp$x) + spacing/2 * c(-1,1) yl <- range(temp$y) + spacing/2 * c(-1,1) attr(temp,'boundingbox') <- expand.grid(x=xl,y=yl)[c(1,2,4,3),] temp }
nlmixrGill83 <- function(what, args, envir = parent.frame(), which, gillRtol = sqrt(.Machine$double.eps), gillK = 10L, gillStep = 2, gillFtol = 0) { if (missing(which)) { which <- rep(TRUE, length(args)) } return(nlmixrGill83_(what, args, envir, which, gillRtol = sqrt(.Machine$double.eps), gillK = 10L, gillStep = 2, gillFtol = 0 )) } .nlmixrGradInfo <- new.env(parent = emptyenv()) nlmixrGradFun <- function(what, envir = parent.frame(), which, thetaNames, gillRtol = sqrt(.Machine$double.eps), gillK = 10L, gillStep = 2, gillFtol = 0, useColor = crayon::has_color(), printNcol = floor((getOption("width") - 23) / 12), print = 1) { .md5 <- digest::digest(list(what, gillRtol, gillK, gillStep, gillFtol)) .nlmixrGradInfo[["printNcol"]] <- printNcol .nlmixrGradInfo[["useColor"]] <- useColor .nlmixrGradInfo[["isRstudio"]] <- (Sys.getenv("RSTUDIO") == "1") .nlmixrGradInfo[["print"]] <- print if (!missing(which)) { .nlmixrGradInfo[[paste0(.md5, ".w")]] <- which } if (!missing(thetaNames)) { .nlmixrGradInfo[["thetaNames"]] <- thetaNames } .nlmixrGradInfo[[paste0(.md5, ".n")]] <- 0L .nlmixrGradInfo[[paste0(.md5, ".f")]] <- what .nlmixrGradInfo[[paste0(.md5, ".e")]] <- envir .nlmixrGradInfo[[paste0(.md5, ".rtol")]] <- gillRtol .nlmixrGradInfo[[paste0(.md5, ".k")]] <- gillK .nlmixrGradInfo[[paste0(.md5, ".s")]] <- gillStep .nlmixrGradInfo[[paste0(.md5, ".ftol")]] <- gillFtol .eval <- eval(parse(text = paste0("function(theta){ nlmixrEval_(theta, \"", .md5, "\"); }"))) .grad <- eval(parse(text = paste0("function(theta){ nlmixrGrad_(theta, \"", .md5, "\"); }"))) .hist <- eval(parse(text = paste0("function(){ nlmixrParHist_(md5=\"", .md5, "\"); }"))) .unscaled <- eval(parse(text = paste0("function(theta){ nlmixrUnscaled_(theta,md5=\"", .md5, "\"); }"))) return(list(eval = .eval, grad = .grad, hist = .hist, unscaled = .unscaled)) } nlmixrHess <- function(par, fn, ..., envir = parent.frame()) { .gill <- nlmixrGill83(fn, par, envir = envir, ...) return(nlmixrHess_(par, fn, envir, .gill)) }
mimicCenPlotMark<-function(squareness, xMark, yMark, defCenStyleCol, listOfdfMarkPosCenStyle, chrWidth, specialChrWidth, yfactor ,n, lwd.mimicCen,listOfdfChromSize, circularPlot, y, markLabelSize, separFactor, labelSpacing, circleCenter,circleCenterY,radius, ylistTransChr,rotation,labelOutwards, yMarkLine,xMarkRightLine,xMarkLeftLine, x, cenFormat="triangle" ,pts ) { if (squareness <= 20) { roundedX<-list() roundedY<-list() for (s in 1:length(yMark) ) { corr_index<-which(names(listOfdfChromSize) %in% names(listOfdfMarkPosCenStyle)[[s]] ) if(attr(listOfdfChromSize[[corr_index]],"ytitle")=="cM"){ chrWidth2 <-specialChrWidth } else { chrWidth2 <- chrWidth } r2 <- chrWidth2/(squareness*2) xyCoords<-mapXYCenMimic(1 , (length(yMark[[s]]) ) , yMark[[s]], xMark[[s]], yfactor,r2, pts, cenFormat) roundedX[[s]]<-xyCoords$roundedX roundedY[[s]]<-xyCoords$roundedY attr(roundedY[[s]],"spname") <- attr(yMark[[s]],"spname") attr(roundedX[[s]],"spname") <- attr(xMark[[s]],"spname") } names(roundedY)<-names(yMark) xMark<-roundedX yMark<-roundedY } if(circularPlot==FALSE) { lapply(1:length(xMark), function(w) mapply(function(x,y,z) graphics::polygon( x=x, y=y, col = defCenStyleCol ,lwd = 0.05 ,border = defCenStyleCol ), x=xMark[[w]], y=yMark[[w]] ,z=listOfdfMarkPosCenStyle[[w]]$markName ) ) lapply(1:length(xMarkLeftLine), function(w) mapply(function(x,y,z) graphics::lines( x=x, y=y, col = defCenStyleCol ,lwd = lwd.mimicCen, ), x=xMarkLeftLine[[w]], y=yMarkLine[[w]] ,z=listOfdfMarkPosCenStyle[[w]]$markName ) ) lapply(1:length(xMarkRightLine), function(w) mapply(function(x,y,z) graphics::lines( x=x, y=y, col = defCenStyleCol ,lwd = lwd.mimicCen, ), x=xMarkRightLine[[w]], y=yMarkLine[[w]] ,z=listOfdfMarkPosCenStyle[[w]]$markName ) ) } else { xlistNew <- xHortoVer(xMark) yMarkPer <- markMapPer(yMark,y) ylistTransMark <- transyListMark(yMarkPer, ylistTransChr) circleMapsMarks <- applyMapCircle(radius,circleCenter,circleCenterY,separFactor ,ylistTransMark,xlistNew,n,0,chrWidth,rotation=rotation) drawCenStyle(circleMapsMarks,defCenStyleCol,lwd.mimicCen) xlistNew<-xHortoVer(xMarkLeftLine) yMarkPer <- markMapPer(yMarkLine,y) ylistTransMark <- transyListMark(yMarkPer, ylistTransChr) circleMapsMarks <- applyMapCircle(radius,circleCenter,circleCenterY,separFactor, ylistTransMark,xlistNew,n,0,chrWidth,rotation=rotation) drawPlotMarkLine(circleMapsMarks,defCenStyleCol,lwd.mimicCen) xlistNew<-xHortoVerDots(xMarkRightLine,x) yMarkPer <- markMapPer(yMarkLine,y) ylistTransMark <- transyListMark(yMarkPer, ylistTransChr) circleMapsMarks <- applyMapCircle(radius,circleCenter,circleCenterY,separFactor, ylistTransMark,xlistNew,n,0,chrWidth,rotation=rotation) drawPlotMarkLine(circleMapsMarks,defCenStyleCol,lwd.mimicCen) } } mimicCenPlotMarkInside<-function(pattern,bannedMarkName,squareness, xMarkCenStyleBody, yMarkCenStyleBody, defCenStyleCol, dfMarkColorInt, listOfdfMarkPosCenStyle, chrWidth, specialChrWidth, yfactor,n, lwd.mimicCen,listOfdfChromSize, circularPlot, y, markLabelSize, separFactor, labelSpacing, circleCenter,circleCenterY,radius, ylistTransChr,rotation,labelOutwards, yMarkLine,xMarkRightLine,xMarkLeftLine, x, lwd.chr, legend, cenFormat="triangle" ,pts) { if(squareness <= 20 ) { roundedXInside<-list() roundedYInside<-list() for (s in 1:length(yMarkCenStyleBody) ) { corr_index<-which(names(listOfdfChromSize) %in% names(listOfdfMarkPosCenStyle)[[s]] ) if(attr(listOfdfChromSize[[corr_index]],"ytitle")=="cM"){ chrWidth2 <-specialChrWidth } else { chrWidth2 <- chrWidth } r2 <- chrWidth2/(squareness*2) xyCoords<-mapXYCenMimicInside(1, length(yMarkCenStyleBody[[s]]), yMarkCenStyleBody[[s]], xMarkCenStyleBody[[s]], yfactor, r2, pts, cenFormat) roundedXInside[[s]]<-xyCoords$roundedX roundedYInside[[s]]<-xyCoords$roundedY attr(roundedYInside[[s]],"spname") <- attr(yMarkCenStyleBody[[s]],"spname") attr(roundedXInside[[s]],"spname") <- attr(xMarkCenStyleBody[[s]],"spname") } names(roundedYInside)<-names(yMarkCenStyleBody) xMarkCenStyleBody<-roundedXInside yMarkCenStyleBody<-roundedYInside } if(circularPlot==FALSE) { lapply(1:length(yMarkCenStyleBody), function(m) mapply(function(x,y,z) graphics::polygon( x=x, y=y, col = dfMarkColorInt$markColor[match(z, dfMarkColorInt$markName)] , lwd= lwd.chr, border= dfMarkColorInt$markBorderColor[match(z, dfMarkColorInt$markName)] ), x=xMarkCenStyleBody[[m]], y=yMarkCenStyleBody[[m]], z=listOfdfMarkPosCenStyle[[m]]$markName ) ) } else { xlistNew <- xHortoVer(xMarkCenStyleBody) yMarkPer <- markMapPer(yMarkCenStyleBody,y) ylistTransMark <- transyListMark(yMarkPer, ylistTransChr) circleMapsMarks <- applyMapCircle(radius,circleCenter,circleCenterY,separFactor ,ylistTransMark,xlistNew,n,0,chrWidth,rotation=rotation) drawPlotMark(circleMapsMarks,dfMarkColorInt,listOfdfMarkPosCenStyle,lwd.chr) if(legend=="inline"){ circleMapsMarksLabelMimicCen <- applyMapCircle(radius,circleCenter,circleCenterY,separFactor ,ylistTransMark,xlistNew,n, labelSpacing ,chrWidth, rotation=rotation) circLabelMark(bannedMarkName,circleMapsMarksLabelMimicCen,listOfdfMarkPosCenStyle , markLabelSize,pattern,labelOutwards,circleCenter,circleCenterY) } } }
HierarchyFix <- function(hierarchy, hierarchyVarNames = c(mapsFrom = "mapsFrom", mapsTo = "mapsTo", sign = "sign", level = "level"), autoLevel = TRUE) { h <- FixHierarchy(hierarchy, hierarchyVarNames) if (autoLevel) h <- AutoLevel(h) h } HierarchyCompute <- function(data, hierarchies, valueVar, colVar = NULL, rowSelect = NULL, colSelect = NULL, select = NULL, inputInOutput = FALSE, output = "data.frame", autoLevel = TRUE, unionComplement = FALSE, constantsInOutput = NULL, hierarchyVarNames = c(mapsFrom = "mapsFrom", mapsTo = "mapsTo", sign = "sign", level = "level"), selectionByMultiplicationLimit = 10^7, colNotInDataWarning = TRUE, useMatrixToDataFrame = TRUE, handleDuplicated = "sum", asInput = FALSE, verbose = FALSE, reOrder = FALSE, reduceData = TRUE, makeRownames = NULL) { if(length(colVar)){ sysCall <- sys.call() sysCall[[1]] <- as.name("HierarchyCompute2") parentFrame = parent.frame() return(eval(sysCall, envir=parentFrame)) } if(!(handleDuplicated %in% c("sum", "sumByAggregate", "sumWithWarning", "stop", "single", "singleWithWarning"))) stop("invalid 'handleDuplicated' argument") if(is.null(makeRownames)) makeRownames <- output %in% c("dataDummyHierarchyWithCodeFrame", "dataDummyHierarchyQuick", "dataDummyHierarchy", "matrixComponents") if(hasArg(valueVar)){ nValueVar = length(valueVar) } else { nValueVar = 1L } if(output=="dataDummyHierarchyWithCodeFrame" | output=="dataDummyHierarchyQuick"){ reduceData <- FALSE } if(asInput){ reduceData <- FALSE if(handleDuplicated !="sum") stop("'handleDuplicated' must be 'sum' when 'asInput'") } noRowGroupsWhenNoColVar <- !(handleDuplicated !="sum") removeEmpty <- FALSE if(!is.null(rowSelect )) if(is.character(rowSelect)) if(length(rowSelect)==1) if(rowSelect=="removeEmpty"){ removeEmpty <- TRUE rowSelect <- NULL } nHier <- length(hierarchies) inputInOutput <- rep_len(inputInOutput, nHier) autoLevel <- rep_len(autoLevel, nHier) unionComplement <- rep_len(unionComplement, nHier) gf <- GetFirstStringInList(hierarchies) if (any(!(gf %in% c("", "rowFactor", "colFactor")))) { stop(paste("Wrong input: ", paste(gf[!(gf %in% c("", "rowFactor", "colFactor"))], collapse =", ") )) } colInd <- which(gf == "colFactor") if (length(colInd) > 1) { stop("Only a single colVar allowed in this implementation") } colVar <- names(hierarchies)[colInd] if (length(colInd) == 0) { noColVar <- TRUE colSelect <- NULL } else { noColVar <- FALSE if (is.list(colSelect)) { colSelect <- colSelect[[colVar]] if (is.null(colSelect)) stop("Wrong colSelect input") } } if (!noColVar & asInput) stop("asInput only possible when no colFactor") if (noColVar) hierarchyInd <- seq_len(nHier) else hierarchyInd <- seq_len(nHier)[-colInd] hierarchyNames <- names(hierarchies)[hierarchyInd] selectOrder <- NULL if (!is.null(select)) { if ((!is.null(rowSelect)) | (!is.null(colSelect))) stop("With non-NULL select, rowSelect and colSelect must be NULL") if (noColVar) { rowSelect <- select } else { colSelect <- as.character(select[, colVar]) colSelInt <- as.integer(factor(colSelect)) colSelect <- unique(colSelect) rgSelect <- RowGroups(CharacterDataFrame(select[, hierarchyNames, drop=FALSE]), returnGroups = TRUE) selectOrder <- matrix(NaN, NROW(rgSelect$groups), length(colSelect)) selectOrder[cbind(rgSelect$idx, colSelInt)] <- seq_len(NROW(select)) selectOrder <- order(as.vector(selectOrder))[seq_len(NROW(select))] rowSelect <- rgSelect$groups rm(rgSelect) } inputColnamesRowSelect <- colnames(rowSelect) } else { if (!is.null(rowSelect)) { inputColnamesRowSelect <- colnames(rowSelect) rowSelect <- CharacterDataFrame(unique(rowSelect[, hierarchyNames, drop = FALSE])) } } dummyHierarchies <- vector("list", nHier) dataDummyHierarchies <- vector("list", nHier) codeFrames <- vector("list", nHier) names(dummyHierarchies) <- names(hierarchies) names(dataDummyHierarchies) <- names(hierarchies) names(codeFrames) <- names(hierarchies) if (!is.null(rowSelect)) { inputInOutput[] <- FALSE } for (i in seq_len(nHier)) { if (is.list(hierarchies[[i]])) { hierarchies[[i]] <- FixHierarchy(hierarchies[[i]], hierarchyVarNames) if (autoLevel[i]) hierarchies[[i]] <- AutoLevel(hierarchies[[i]]) hierarchies[i] <- AddMapsInput(hierarchies[i], data) if (!is.null(rowSelect)) { hierarchies[i] <- AddNonExistingCode(hierarchies[i], rowSelect, inputInOutput[i]) mapsInput <- attr(hierarchies[[i]], "mapsInput") keepCodes <- attr(hierarchies[[i]], "keepCodes") hierarchies[[i]] <- AutoLevel(hierarchies[[i]]) attr(hierarchies[[i]], "mapsInput") <- mapsInput attr(hierarchies[[i]], "keepCodes") <- keepCodes } dummyHierarchies[[i]] <- DummyHierarchy(mapsFrom = hierarchies[[i]]$mapsFrom, mapsTo = hierarchies[[i]]$mapsTo, mapsInput = attr(hierarchies[[i]], "mapsInput"), keepCodes = attr(hierarchies[[i]], "keepCodes"), sign = hierarchies[[i]]$sign, level = hierarchies[[i]]$level, inputInOutput = inputInOutput[i], unionComplement = unionComplement[i], reOrder = reOrder) } else { if (hierarchies[[i]] == "rowFactor") { dummyHierarchies[[i]] <- fac2sparse(sort(factor(unique(data[, names(hierarchies)[i], drop = TRUE])))) colnames(dummyHierarchies[[i]]) <- rownames(dummyHierarchies[[i]]) } } } if (output == "dummyHierarchies") return(dummyHierarchies) if(verbose){ cat(" [ HierarchyCompute initial calculations.") flush.console()} if (!is.null(rowSelect)) { for (i in hierarchyInd) { iRows <- rownames(dummyHierarchies[[i]]) %in% rowSelect[, names(hierarchies)[i], drop=TRUE] dummyHierarchies[[i]] <- dummyHierarchies[[i]][iRows, , drop = FALSE] } } if (!is.null(colSelect)) { datacolvar <- as.character(data[, colVar, drop = TRUE]) colSelect <- unique(as.character(colSelect)) colNotInData <- colSelect[!(colSelect %in% datacolvar)] if (length(colNotInData) > 0) { rowsData <- which(datacolvar %in% colSelect) if (length(rowsData) == 0) { if (colNotInDataWarning) warning(paste("No items in colSelect in data[,'", colVar, "']. Only zeros produced: ", paste(colNotInData, collapse = ", "), sep = "")) rowsData <- c(rep(1, length(colNotInData))) } else { if (colNotInDataWarning) warning(paste("Items in colSelect not in data[,'", colVar, "'] set to zero: ", paste(colNotInData, collapse = ", "), sep = "")) rowsData <- c(rep(rowsData[1], length(colNotInData)), rowsData) } datacolvar <- datacolvar[rowsData] datacolvar[seq_len(length(colNotInData))] <- colNotInData data <- data[rowsData, , drop = FALSE] data[, colVar] <- datacolvar data[seq_len(length(colNotInData)), valueVar] <- 0L } else { rowsData <- datacolvar %in% colSelect data <- data[rowsData, , drop = FALSE] } } rownames(data) <- NULL if (reduceData) data <- ReduceDataByDummyHierarchiesAndValue(data, dummyHierarchies, valueVar, colVar) if(verbose){ cat(".") flush.console()} if(noColVar & noRowGroupsWhenNoColVar){ rowGroups <- list(idx = seq_len(NROW(data)), groups = data[, hierarchyNames, drop = FALSE]) } else { rowGroups <- RowGroups(data[, hierarchyNames, drop = FALSE], returnGroups = TRUE) } if(verbose){ cat(".") flush.console()} for (i in hierarchyInd) { dataDummyHierarchies[[i]] <- DataDummyHierarchy(as.character(rowGroups$groups[names(hierarchies)[i]][[1]]), dummyHierarchies[[i]]) codeFrames[[i]] <- data.frame(a = factor(rownames(dummyHierarchies[[i]]))) names(codeFrames[[i]]) <- names(codeFrames[i]) } if(verbose){ cat("]") flush.console()} runCrossDataDummyHierarchies <- is.null(rowSelect) if (!is.null(rowSelect)) { selectionByMultiplication <- (as.numeric(dim(rowGroups$groups)[1]) * as.numeric(NROW(rowSelect))) < selectionByMultiplicationLimit } if (runCrossDataDummyHierarchies) { if(output=="dataDummyHierarchyQuick") codeFrames <- NULL k <- CrossDataDummyHierarchies(dataDummyHierarchies = dataDummyHierarchies[hierarchyInd], codeFrames = codeFrames[hierarchyInd], makeDimnames = makeRownames, useMatrixToDataFrame = useMatrixToDataFrame, removeEmpty = removeEmpty, verbose = verbose, reOrder = reOrder) if(output=="dataDummyHierarchyQuick" | output=="dataDummyHierarchyWithCodeFrame") { if(output=="dataDummyHierarchyWithCodeFrame"){ k$codeFrame <- CharacterDataFrame(k$codeFrame) } return(k) } } else { k <- list(dataDummyHierarchy = NULL, codeFrame = rowSelect) if (!selectionByMultiplication) { k <- ReductionCrossDataDummyHierarchies(dataDummyHierarchies[hierarchyInd], codeFrames = codeFrames[hierarchyInd], codeFrame = k[[2]], makeDimnames = makeRownames, useMatrixToDataFrame = useMatrixToDataFrame, verbose = verbose) } else { k[[1]] <- SelectionCrossDataDummyHierarchy(dataDummyHierarchies[hierarchyInd], k$codeFrame, verbose = verbose) } } if(makeRownames){ if( is.null(rownames(k$dataDummyHierarchy) )){ rownames(k$dataDummyHierarchy) <- apply(k$codeFrame, 1, paste, collapse = ":") } } if(output=="dataDummyHierarchyQuick") return(k$dataDummyHierarchy) if(output=="dataDummyHierarchyWithCodeFrame"){ k$codeFrame <- CharacterDataFrame(k$codeFrame) return(k) } readyValueMatrix <- FALSE if (noColVar) { valueMatrix <- Matrix(0, dim(rowGroups$groups)[1], nValueVar) colnames(valueMatrix) <- colnames(data[1, valueVar, drop = FALSE]) if(handleDuplicated !="single") if( NROW(valueMatrix) != NROW(data)){ if(handleDuplicated =="singleWithWarning"){ warning("Duplicated rows in input. By matrix subsetting one of the is used.") } else { if(handleDuplicated =="stop") stop("Duplicated rows in input ('handleDuplicated=stop').") if(handleDuplicated %in% c("sum", "sumByAggregate","sumWithWarning")){ if(handleDuplicated == "sumWithWarning") warning("Duplicated rows in input summed ('handleDuplicated=sumWithWarning').") if(verbose){ cat(" [ aggregate..") flush.console()} aggData <- aggregate(data[, valueVar, drop = FALSE], by = list(idx69_3h4_6kd = rowGroups$idx), FUN = sum) if(verbose){ cat(".") flush.console()} if(nValueVar>1) valueMatrix[aggData$idx69_3h4_6kd, valueVar] <- as.matrix(aggData[, valueVar]) else valueMatrix[aggData$idx69_3h4_6kd, valueVar] <- aggData[, valueVar] rm(aggData) if(verbose){ cat("]") flush.console()} readyValueMatrix <- TRUE } } } if(!readyValueMatrix){ if (nValueVar>1){ valueMatrix[rowGroups$idx, ] <- as.matrix(data[, valueVar]) } else { valueMatrix[rowGroups$idx, 1] <- data[, valueVar, drop = TRUE] } } } else { colData <- factor(data[, colVar, drop = TRUE]) integerColData <- as.integer(colData) nCol <- max(integerColData, 0L) valueMatrix <- Matrix(0, dim(rowGroups$groups)[1], nCol*nValueVar) colnames(valueMatrix) <- rep(levels(colData), nValueVar) idx_integerColData <- cbind(idx = rowGroups$idx, integerColData = integerColData) if(handleDuplicated !="single") if(anyDuplicated(idx_integerColData)){ if(handleDuplicated =="singleWithWarning"){ warning("Duplicated rows in input. By matrix subsetting one of the is used.") } else { if(handleDuplicated =="stop") stop("Duplicated rows in input ('handleDuplicated=stop').") if(handleDuplicated %in% c("sum", "sumByAggregate","sumWithWarning")){ if(handleDuplicated == "sumWithWarning") warning("Duplicated rows in input summed ('handleDuplicated=sumWithWarning').") if(verbose){ cat(" [ aggregate..") flush.console()} aggData <- aggregate(data[, valueVar, drop = FALSE], by = list(idx69_3h4_6kd = rowGroups$idx, integerColData7y9_56 = integerColData), FUN = sum) if(verbose){ cat(".") flush.console()} mIntegerColData <- rep(aggData$integerColData7y9_56, nValueVar) + rep(nCol * SeqInc(0, nValueVar - 1), each = nrow(aggData)) if(nValueVar>1) valueMatrix[cbind(aggData$idx69_3h4_6kd, mIntegerColData)] <- as.vector(as.matrix(aggData[, valueVar])) else valueMatrix[cbind(aggData$idx69_3h4_6kd, mIntegerColData)] <- aggData[, valueVar] rm(aggData) if(verbose){ cat("]") flush.console()} readyValueMatrix <- TRUE } } } if(!readyValueMatrix){ if (nValueVar>1){ mIntegerColData = rep(integerColData, nValueVar) + rep(nCol*SeqInc(0,nValueVar-1),each = length(integerColData)) valueMatrix[cbind(idx = rowGroups$idx, mIntegerColData = mIntegerColData)] <- as.vector(as.matrix(data[, valueVar])) } else { valueMatrix[idx_integerColData] <- data[, valueVar, drop = TRUE] } } } rownames(valueMatrix) <- NULL if ((!is.null(rowSelect)) & runCrossDataDummyHierarchies) { rg <- RowGroups(rbind(CharacterDataFrame(k$codeFrame), rowSelect)) rg1 <- rg[seq_len(dim(k$codeFrame)[1])] rg2 <- rg[-seq_len(dim(k$codeFrame)[1])] selectedRows <- match(rg2, rg1) } else { selectedRows <- NULL } if (is.null(selectedRows)) { outputMatrix <- Mult(k[[1]], valueMatrix) xCrossCode <- k$codeFrame } else { outputMatrix <- Mult(k[[1]][selectedRows, , drop = FALSE], valueMatrix) xCrossCode <- k$codeFrame[selectedRows, , drop = FALSE] } xCrossCode <- CharacterDataFrame(xCrossCode) rownames(xCrossCode) <- NULL hierarchyNamesForOutput <- NULL if ((!is.null(rowSelect)) & is.null(hierarchyNamesForOutput)) { hierarchyNamesForOutput <- inputColnamesRowSelect } if (!is.null(hierarchyNamesForOutput)) { macol <- match(hierarchyNamesForOutput, colnames(xCrossCode)) macol <- macol[!is.na(macol)] xCrossCode <- xCrossCode[, macol, drop = FALSE] } if (output == "outputMatrix") { if(verbose){ cat("\n") flush.console()} return(outputMatrix) } if (output == "dataDummyHierarchy") { if(verbose){ cat("\n") flush.console()} if (is.null(selectedRows)) { return(k[[1]]) } else { return(k[[1]][selectedRows, , drop = FALSE]) } } if (output == "valueMatrix") { if(verbose){ cat("\n") flush.console()} return(valueMatrix) } if (output == "fromCrossCode") { if(verbose){ cat("\n") flush.console()} return(rowGroups$groups) } if (output == "crossCode" | output == "toCrossCode") { if(verbose){ cat("\n") flush.console()} return(xCrossCode) } if (output == "outputMatrixWithCrossCode") { if(verbose){ cat("\n") flush.console()} return(list(outputMatrix = outputMatrix, xCrossCode = xCrossCode)) } if (output == "matrixComponents") { if(verbose){ cat("\n") flush.console()} if (is.null(selectedRows)) { return(list(dataDummyHierarchy = k[[1]], valueMatrix = valueMatrix, fromCrossCode = rowGroups$groups, toCrossCode = xCrossCode)) } else { return(list(dataDummyHierarchy = k[[1]][selectedRows, , drop = FALSE], valueMatrix = valueMatrix, fromCrossCode = rowGroups$groups, toCrossCode = xCrossCode)) } } if(verbose){ cat(" [ output='data.frame'...") flush.console()} x <- as.matrix(outputMatrix) if(ncol(x) == 0){ colnamesX <- character(0) } else{ colnamesX <- colnames(x) } dimX1 <- dim(x)[1] if(nValueVar>1){ if(!noColVar){ colnamesX <- colnamesX[seq_len(nCol)] x <- matrix(x, ncol = nValueVar) colnames(x) <- valueVar z <- as.data.frame(x) } else { z <- as.data.frame(x) } } else { z <- data.frame(a = as.vector(x), stringsAsFactors = FALSE) names(z) <- valueVar } if (noColVar) { colDataSelected <- xCrossCode[, integer(0)] } else { colDataSelected <- data.frame(a = rep(colnamesX, times = 1, each = dimX1), stringsAsFactors = FALSE) names(colDataSelected) <- colVar } if (nrow(colDataSelected) == 0) { xCrossCode <- xCrossCode[integer(0), , drop = FALSE] if (!is.null(constantsInOutput)) constantsInOutput <- constantsInOutput[integer(0), , drop = FALSE] } if (!is.null(constantsInOutput)) w <- cbind(constantsInOutput, colDataSelected, xCrossCode, z) else w <- cbind(colDataSelected, xCrossCode, z) if (!is.null(selectOrder)) { w <- w[selectOrder, , drop = FALSE] } rownames(w) <- NULL if(verbose){ cat("]\n") flush.console()} w } AddMapsInput <- function(hierarchies, data = NULL) { for (i in length(hierarchies)) { if (is.list(hierarchies[[i]])) { mapsInput <- as.character(hierarchies[[i]]$mapsFrom)[!(as.character(hierarchies[[i]]$mapsFrom) %in% as.character(hierarchies[[i]]$mapsTo))] if (!is.null(data)) mapsInput <- c(mapsInput, as.character(unique(data[, names(hierarchies)[i], drop = TRUE]))) mapsInput <- as.character(sort(as.factor(unique(mapsInput)))) if (any(mapsInput %in% as.character(hierarchies[[i]]$mapsTo))) { stop(paste(names(hierarchies)[i], "codes in mapsTo already in input data:", paste(mapsInput[mapsInput %in% as.character(hierarchies[[i]]$mapsTo)], collapse = ", "))) } attr(hierarchies[[i]], "mapsInput") <- mapsInput } } hierarchies } AddNonExistingCode <- function(hierarchies, rowSelect = NULL, inputInOutput = TRUE) { if (is.null(rowSelect)) return(hierarchies) for (i in length(hierarchies)) { if (is.list(hierarchies[[i]])) { mapsInput <- attr(hierarchies[[i]], "mapsInput") allCodes <- unique(c(as.character(mapsInput), hierarchies[[i]]$mapsTo)) uniqueRowSelect <- unique(rowSelect[, names(hierarchies)[i], drop = TRUE]) newCodes <- uniqueRowSelect[!(uniqueRowSelect %in% allCodes)] if (length(newCodes) > 0) { hierarchyExtra <- hierarchies[[i]][rep(1, (length(newCodes))), , drop = FALSE] hierarchyExtra$mapsTo <- newCodes hierarchyExtra$mapsFrom <- "N_oNEX_istIn_gCOd_e" hierarchyExtra$level <- 1L hierarchies[[i]] <- rbind(hierarchies[[i]], hierarchyExtra) mapsInput <- c(mapsInput, "N_oNEX_istIn_gCOd_e") } if (!inputInOutput) { keepCodes <- uniqueRowSelect[uniqueRowSelect %in% as.character(mapsInput)] } else keepCodes <- uniqueRowSelect[integer(0)] attr(hierarchies[[i]], "mapsInput") <- mapsInput attr(hierarchies[[i]], "keepCodes") <- keepCodes } } hierarchies } CrossDataDummyHierarchies <- function(dataDummyHierarchies, codeFrames = NULL, makeDimnames = FALSE, useMatrixToDataFrame = TRUE, removeEmpty = FALSE, verbose = FALSE, reOrder = FALSE) { if(reOrder) CrossDataDummyHierarchyHere = CrossDataDummyHierarchyReOrder else CrossDataDummyHierarchyHere =CrossDataDummyHierarchy if(verbose){ if(removeEmpty) cat(" [ KhatriRaoRemoveEmpty...") else cat(" [ KhatriRao...") flush.console() } if (is.null(codeFrames)) useCodeFrames <- FALSE else useCodeFrames <- !any(sapply(codeFrames, is.null)) n <- length(dataDummyHierarchies) if(removeEmpty){ for(i in seq_len(n)){ rowNonZero <- RowNonZero(dataDummyHierarchies[[i]]) dataDummyHierarchies[[i]] <- dataDummyHierarchies[[i]][rowNonZero, ,drop=FALSE] if (useCodeFrames) codeFrames[[i]] <- codeFrames[[i]][rowNonZero, ,drop=FALSE] } } if (useCodeFrames) { for (i in seq_len(n)){ if(i==1) z <- CrossDataDummyHierarchyHere(dataDummyHierarchy1 = dataDummyHierarchies[[1]], codeFrame1 = codeFrames[[1]], makeDimnames = makeDimnames, useMatrixToDataFrame = useMatrixToDataFrame) else z <- CrossDataDummyHierarchyHere(z[[1]], dataDummyHierarchies[[i]], z[[2]], codeFrames[[i]], makeDimnames = makeDimnames, useMatrixToDataFrame = useMatrixToDataFrame) if(removeEmpty){ rowNonZero <- RowNonZero(z[[1]]) z[[1]] <- z[[1]][rowNonZero, , drop = FALSE] z[[2]] <- z[[2]][rowNonZero, , drop = FALSE] } } } else { for (i in seq_len(n)){ if(i==1) z <- CrossDataDummyHierarchyHere(dataDummyHierarchy1 = dataDummyHierarchies[[1]], makeDimnames = makeDimnames, useMatrixToDataFrame = useMatrixToDataFrame) else z <- CrossDataDummyHierarchyHere(z, dataDummyHierarchies[[i]], makeDimnames = makeDimnames, useMatrixToDataFrame = useMatrixToDataFrame) if(removeEmpty){ rowNonZero <- RowNonZero(z) z <- z[rowNonZero, , drop = FALSE] } } } if(verbose){ cat("]") flush.console()} z } RowNonZero <- function(x){ rowSums(x!=0) > 0 } ReductionCrossDataDummyHierarchies <- function(dataDummyHierarchies, codeFrames = NULL, makeDimnames = FALSE, codeFrame = NULL, useMatrixToDataFrame = TRUE, verbose = FALSE) { if(verbose){ cat(" [ ReductionKhatriRao...") flush.console()} if (is.null(codeFrames)) useCodeFrames <- FALSE else useCodeFrames <- !any(sapply(codeFrames, is.null)) n <- length(dataDummyHierarchies) if (useCodeFrames) { varNames <- names(dataDummyHierarchies) z <- CrossDataDummyHierarchy(dataDummyHierarchy1 = dataDummyHierarchies[[1]], codeFrame1 = codeFrames[[1]], makeDimnames = makeDimnames, useMatrixToDataFrame = useMatrixToDataFrame) selecti <- z[[2]][, 1, drop = TRUE] %in% codeFrame[, 1, drop = TRUE] z[[1]] <- z[[1]][selecti, , drop = FALSE] z[[2]] <- z[[2]][selecti, , drop = FALSE] for (i in matlabColon(2, n)) { z <- CrossDataDummyHierarchy(z[[1]], dataDummyHierarchies[[i]], z[[2]], codeFrames[[i]], makeDimnames = makeDimnames, useMatrixToDataFrame = useMatrixToDataFrame) if(i == n) { selecti <- Match(codeFrame[, seq_len(i)], z[[2]]) } else { selecti <- Match(unique(codeFrame[, seq_len(i)]), z[[2]]) } if (anyNA(selecti)) { selecti <- selecti[!is.na(selecti)] warning("Not all rowSelect possible. Row removed") } z[[1]] <- z[[1]][selecti, , drop = FALSE] z[[2]] <- z[[2]][selecti, , drop = FALSE] } } else { z <- CrossDataDummyHierarchy(dataDummyHierarchy1 = dataDummyHierarchies[[1]], makeDimnames = makeDimnames, useMatrixToDataFrame = useMatrixToDataFrame) for (i in matlabColon(2, n)) z <- CrossDataDummyHierarchy(z, dataDummyHierarchies[[i]], makeDimnames = makeDimnames, useMatrixToDataFrame = useMatrixToDataFrame) } if(verbose){ cat("]") flush.console()} z } SelectionDataDummyHierarchy <- function(dataDummyHierarchy, codeVector) { x <- factor(codeVector, levels = rownames(dataDummyHierarchy)) xInteger <- as.integer(x) naxInteger <- is.na(xInteger) if (any(naxInteger)) { dataDummyHierarchy <- rbind(dataDummyHierarchy, 0) xInteger[naxInteger] <- NROW(dataDummyHierarchy) } m <- dataDummyHierarchy[xInteger, , drop = FALSE] rownames(m) <- names(codeVector) m } SelectionCrossDataDummyHierarchy <- function(dataDummyHierarchies, codeFrame, verbose = FALSE) { if(verbose){ cat(" [ SelectionByMultiplication...") flush.console()} n <- length(dataDummyHierarchies) if (n == 0) return(dataDummyHierarchies) z <- SelectionDataDummyHierarchy(dataDummyHierarchies[[1]], codeFrame[, names(dataDummyHierarchies)[1],drop = TRUE]) for (i in matlabColon(2, n)) { z <- z * SelectionDataDummyHierarchy(dataDummyHierarchies[[i]], codeFrame[, names(dataDummyHierarchies)[i],drop = TRUE]) } if(verbose){ cat("]") flush.console()} z } FixHierarchy <- function(hi, hierarchyVarNames = c(mapsFrom = "from", mapsTo = "to", sign = "sign", level = "level")) { ma <- match(names(hi), hierarchyVarNames) wma <- which(!is.na(ma)) ma <- ma[wma] hi <- hi[, wma, drop = FALSE] names(hierarchyVarNames[ma]) colnames(hi) <- names(hierarchyVarNames[ma]) sig <- suppressWarnings(as.integer(hi$sign)) if (anyNA(sig)) hi$sign <- 2L * as.integer(hi$sign == "+") - 1L else hi$sign <- sig hi } AutoLevel <- function(x) { mapsFrom <- as.character(x$mapsFrom) mapsTo <- as.character(x$mapsTo) sign <- x$sign if (any(mapsFrom == mapsTo)) { sel <- !(mapsFrom == mapsTo) mapsFrom <- mapsFrom[sel] mapsTo <- mapsTo[sel] sign <- sign[sel] warning("hierarchy rows where mapsFrom==mapsTo removed") } mapsInput <- mapsFrom[!(mapsFrom %in% mapsTo)] level <- rep(0L, length(mapsFrom)) mapsNow <- as.character(mapsInput) i <- 0 sumLevel0 <- sum(level == 0) while (sumLevel0 > 0) { i <- i + 1 level[(mapsFrom %in% mapsNow) & level == 0] <- i uniquei <- unique(mapsTo[level == i]) for (l in uniquei) { mTl <- mapsTo == l if (any(!(unique(mapsFrom[mTl]) %in% mapsNow))) level[mTl] <- 0 } mapsNow <- unique(c(mapsNow, unique(mapsTo[level == i]))) sumLevel0old <- sumLevel0 sumLevel0 <- sum(level == 0) if (sumLevel0 == sumLevel0old) { sumLevel0 <- 0 li <- paste(paste(mapsFrom[level == 0], mapsTo[level == 0], sep = "->"), collapse = ", ") warning(paste("AutoLevel had problems:", li)) } } data.frame(mapsFrom = mapsFrom, mapsTo = mapsTo, sign = sign, level = level, stringsAsFactors = FALSE) } DummyHierarchy <- function(mapsFrom, mapsTo, sign, level, mapsInput = NULL, inputInOutput = FALSE, keepCodes = mapsFrom[integer(0)], unionComplement = FALSE, reOrder = FALSE) { mapsFrom <- as.character(mapsFrom) mapsTo <- as.character(mapsTo) if (is.null(mapsInput)) mapsInput <- mapsFrom[!(mapsFrom %in% mapsTo)] mapsInput <- sort(as.factor(unique(mapsInput))) m <- Matrix::t(fac2sparse(mapsInput)) rownames(m) <- as.character(mapsInput) dropInput <- rownames(m) if (length(keepCodes) > 0) dropInput <- dropInput[!(dropInput %in% keepCodes)] nInput <- dim(m)[1] for (i in unique(sort(level))) { ri <- (level == i) mapsToi <- factor(mapsTo[ri]) mapsFromi <- factor(mapsFrom[ri], levels = rownames(m)) if (anyNA(mapsFromi)) { warning("Problematic hierarchy specification") } mNew <- Matrix(0, NROW(m), length(levels(mapsToi)), dimnames = list(levels(mapsFromi), levels(mapsToi))) mNew[cbind(as.integer(mapsFromi), as.integer(mapsToi))] <- sign[ri] if(reOrder){ if (unionComplement) m <- rbind(CrossprodUnionComplement(mNew, m),m) else m <- rbind(Mult_crossprod(mNew, m),m) } else { if (unionComplement) m <- rbind(m, CrossprodUnionComplement(mNew, m)) else m <- rbind(m, Mult_crossprod(mNew, m)) } } if (!inputInOutput & length(dropInput) > 0) { keepRows <- rownames(m)[!(rownames(m) %in% dropInput)] m <- m[keepRows, , drop = FALSE] } m } DummyHierarchies <- function(hierarchies, data = NULL, inputInOutput = FALSE, unionComplement = FALSE, reOrder = FALSE) { n <- length(hierarchies) inputInOutput <- rep_len(inputInOutput, n) unionComplement <- rep_len(unionComplement, n) reOrder <- rep_len(reOrder, n) for (i in seq_len(n)) { if (!is.null(data)) { hierarchies[i] <- AddMapsInput(hierarchies[i], data) } hierarchies[[i]] <- DummyHierarchy(mapsFrom = hierarchies[[i]]$mapsFrom, mapsTo = hierarchies[[i]]$mapsTo, mapsInput = attr(hierarchies[[i]], "mapsInput"), keepCodes = attr(hierarchies[[i]], "keepCodes"), sign = hierarchies[[i]]$sign, level = hierarchies[[i]]$level, inputInOutput = inputInOutput[i], unionComplement = unionComplement[i], reOrder = reOrder[i]) } hierarchies } DataDummyHierarchy <- function(dataVector, dummyHierarchy) { x <- factor(dataVector, levels = colnames(dummyHierarchy)) m <- dummyHierarchy[, as.integer(x), drop = FALSE] colnames(m) <- names(dataVector) m } CrossDataDummyHierarchy <- function(dataDummyHierarchy1, dataDummyHierarchy2 = NULL, codeFrame1 = NULL, codeFrame2 = NULL, makeDimnames = FALSE, useMatrixToDataFrame = TRUE) { if (is.null(dataDummyHierarchy2)) { if (is.null(codeFrame1)) return(dataDummyHierarchy1) else return(list(dataDummyHierarchy = dataDummyHierarchy1, codeFrame = codeFrame1)) } if (is.null(codeFrame1) | is.null(codeFrame2)) return(KhatriRao(dataDummyHierarchy2, dataDummyHierarchy1, make.dimnames = makeDimnames)) return(list(dataDummyHierarchy = KhatriRao(dataDummyHierarchy2, dataDummyHierarchy1, make.dimnames = makeDimnames), codeFrame = CrossCodeFrames(codeFrame1, codeFrame2, useMatrixToDataFrame = useMatrixToDataFrame))) } ReduceDataByDummyHierarchiesAndValue <- function(data, dummyHierarchies, valueVar, colVar) { if (length(valueVar)>1){ sel <- rowSums(abs(data[, valueVar])) != 0 } else { sel <- data[, valueVar, drop = TRUE] != 0 } for (i in seq_len(length(dummyHierarchies))) { if (!is.null(dummyHierarchies[[i]])) { keepCodes <- colnames(dummyHierarchies[[i]])[colSums(abs(dummyHierarchies[[i]])) != 0] sel <- sel & (data[, names(dummyHierarchies)[i], drop = TRUE] %in% keepCodes) } } if (length(colVar) > 0) { setTRUE <- match(unique(data[, colVar, drop = TRUE]), data[, colVar, drop = TRUE]) sel[setTRUE] <- TRUE } data[sel, , drop = FALSE] } CrossprodUnionComplement <- function(x, y) { yPlus <- y yMinus <- y yPlus[y < 0] <- 0 yMinus[y > 0] <- 0 zPlus <- Mult_crossprod(x, yPlus) zMinus <- Mult_crossprod(x, yMinus) zPlus[zPlus > 1] <- 1 z <- zPlus + zMinus z[z < 0] <- 0 z } GetFirstStringInList <- function(x) { if (!is.list(x)) stop("list needed") z <- rep("", length(x)) for (i in seq_len(length(x))) { if (is.character(x[[i]])) z[i] <- x[[i]][1] } z } KhatriRaoReOrder = function(x,y,make.dimnames = FALSE){ a <- nrow(x) b <- nrow(y) r <- rep(b*SeqInc(0,a-1),b) + rep(seq_len(b),each=a) KhatriRao(x, y, make.dimnames = make.dimnames)[r, ,drop=FALSE] } CrossDataDummyHierarchyReOrder <- function(dataDummyHierarchy1, dataDummyHierarchy2 = NULL, codeFrame1 = NULL, codeFrame2 = NULL, makeDimnames = FALSE, useMatrixToDataFrame = TRUE) { if (is.null(dataDummyHierarchy2)) { if (is.null(codeFrame1)) return(dataDummyHierarchy1) else return(list(dataDummyHierarchy = dataDummyHierarchy1, codeFrame = codeFrame1)) } if (is.null(codeFrame1) | is.null(codeFrame2)) return(KhatriRaoReOrder(dataDummyHierarchy2, dataDummyHierarchy1, make.dimnames = makeDimnames)) return(list(dataDummyHierarchy = KhatriRaoReOrder(dataDummyHierarchy2, dataDummyHierarchy1, make.dimnames = makeDimnames), codeFrame = CrossCodeFramesReOrder(codeFrame1, codeFrame2, useMatrixToDataFrame = useMatrixToDataFrame))) } CrossCodeFramesAReOrder <- function(codeFrame1, codeFrame2) { n1 <- NROW(codeFrame1) n2 <- NROW(codeFrame2) r1 <- rep(seq_len(n1), times = 1, each = n2) rownames(codeFrame1) <- NULL print(cbind(codeFrame1[r1, , drop = FALSE], codeFrame2)) cbind(codeFrame1[r1, , drop = FALSE], codeFrame2) } CrossCodeFramesReOrder <- function(codeFrame1, codeFrame2, useMatrixToDataFrame = TRUE) { if (!useMatrixToDataFrame) return(CrossCodeFramesAReOrder(codeFrame1, codeFrame2)) n1 <- NROW(codeFrame1) n2 <- NROW(codeFrame2) codeFrame1 <- DataFrameToMatrix(codeFrame1) codeFrame2 <- DataFrameToMatrix(codeFrame2) rownames(codeFrame1) <- NULL rownames(codeFrame2) <- NULL r1 <- rep(seq_len(n1), times = 1, each = n2) r2 <- rep(seq_len(n2), times = n1, each = 1) z <- cbind(codeFrame1[r1, , drop = FALSE], codeFrame2[r2, , drop = FALSE]) attr(z, "namesDF") <- c(attr(codeFrame1, "namesDF"), attr(codeFrame2, "namesDF")) attr(z, "classDF") <- c(attr(codeFrame1, "classDF"), attr(codeFrame2, "classDF")) attr(z, "levelsDF") <- c(attr(codeFrame1, "levelsDF"), attr(codeFrame2, "levelsDF")) MatrixToDataFrame(z) }
sar_monod <- function(data, start = NULL, grid_start = "partial", grid_n = NULL, normaTest = "none", homoTest = "none", homoCor = "spearman", verb = TRUE){ if (!(is.matrix(data) | is.data.frame(data))) stop('data must be a matrix or dataframe') if (is.matrix(data)) data <- as.data.frame(data) if (anyNA(data)) stop('NAs present in data') normaTest <- match.arg(normaTest, c('none', 'shapiro', 'kolmo', 'lillie')) homoTest <- match.arg(homoTest, c('none', 'cor.area', 'cor.fitted')) if (homoTest != 'none'){ homoCor <- match.arg(homoCor, c('spearman', 'pearson', 'kendall')) } if (!(grid_start %in% c('none', 'partial', 'exhaustive'))){ stop('grid_start should be one of none, partial or exhaustive') } if (grid_start == 'exhaustive'){ if (!is.numeric(grid_n)) stop('grid_n should be numeric if grid_start == exhaustive') } if (!is.logical(verb)){ stop('verb should be logical') } data <- data[order(data[,1]),] colnames(data) <- c('A','S') xr <- range(data$S)/mean(data$S) if (isTRUE(all.equal(xr[1], xr[2]))) { if (data$S[1] == 0){ warning('All richness values are zero: parameter estimates of', ' non-linear models should be interpreted with caution') } else{ warning('All richness values identical') }} model <- list( name=c("Monod"), formula=expression(S==d/(1+c*A^(-1))), exp=expression(d/(1+c*A^(-1))), shape="convex", asymp=function(pars)pars["d"], parLim = c("Rplus","Rplus"), custStart=function(data)c(stats::quantile(data$A,c(0.25)),max(data$S)), init=function(data){ if(any(data$S==0)){data=data[data$S!=0,]} d=as.double(max(data$A)+max(data$S)/4) c=data[[1]]*(d/data$S - 1) c(d,stats::quantile(c,c(0.25))) } ) model <- compmod(model) fit <- get_fit(model = model, data = data, start = start, grid_start = grid_start, grid_n = grid_n, algo = 'Nelder-Mead', normaTest = normaTest, homoTest = homoTest, homoCor = homoCor, verb = verb) if(is.na(fit$value)){ return(list(value = NA)) }else{ obs <- obs_shape(fit, verb = verb) fit$observed_shape <- obs$fitShape fit$asymptote <- obs$asymp fit$neg_check <- any(fit$calculated < 0) class(fit) <- 'sars' attr(fit, 'type') <- 'fit' return(fit) } }
library(lingtypology) context("Tests for iso.lang function") df <- data.frame(my_langs = c("Adyghe", "Udi"), stringsAsFactors = FALSE) test_that("iso.lang", { expect_equal(iso.lang("Adyghe"), c(Adyghe = "ady")) expect_equal(iso.lang(c("Adyghe", "Udi")), c(Adyghe = "ady", Udi = "udi")) expect_equal(iso.lang(df), c(my_langs1 = "ady", my_langs2 = "udi")) })
ps2pdf <- function(filename, path=NULL, opts=NULL, ..., force=FALSE, verbose=FALSE) { pathname <- Arguments$getReadablePathname(filename, path=path, mustExist=TRUE) opts <- Arguments$getCharacters(opts) opts <- paste(opts, collapse=" ") force <- Arguments$getLogical(force) verbose <- Arguments$getVerbose(verbose) if (verbose) { pushState(verbose) on.exit(popState(verbose)) } verbose && enter(verbose, "ps2pdf") verbose && cat(verbose, "PS pathname: ", pathname) filename <- basename(pathname) path <- dirname(pathname) filename2 <- gsub("[.]ps", ".pdf", filename) pathname2 <- Arguments$getWritablePathname(filename2, path=path) verbose && cat(verbose, "PDF pathname: ", pathname2) isUpToDate <- FALSE if (!force && isFile(pathname2)) { date <- file.info(pathname)$mtime verbose && cat(verbose, "Source file modified on: ", date) outDate <- file.info(pathname2)$mtime verbose && cat(verbose, "Output file modified on: ", outDate) if (is.finite(date) && is.finite(outDate)) { isUpToDate <- (outDate >= date) } verbose && printf(verbose, "Output file is %sup to date.\n", ifelse(isUpToDate, "", "not ")) } if (!isUpToDate || !isFile(pathname2)) { verbose && enter(verbose, "Calling ps2pdf") opwd <- getwd() on.exit(setwd(opwd)) setwd(path) verbose && cat(verbose, "Working directory: ", getwd()) verbose && cat(verbose, "Filename: ", filename) cmd <- sprintf("ps2pdf %s %s", opts, filename) system(cmd) verbose && exit(verbose) } pathname2 <- Arguments$getReadablePathname(pathname2, mustExist=TRUE) verbose && exit(verbose) invisible(pathname2) }
mixtureProbs <- function(m, getCI=FALSE, alpha = 0.95){ if(!is.momentuHMM(m) & !is.momentuHierHMM(m)) stop("'m' must be a momentuHMM or momentuHierHMM object") m <- delta_bc(m) if(is.null(m$mod$hessian) | inherits(m$mod$Sigma,"error")) getCI <- FALSE nbAnimals <- length(unique(m$data$ID)) mixtures <- m$conditions$mixtures if(mixtures==1) getCI <- FALSE quantSup<-qnorm(1-(1-alpha)/2) est <- se <- lower <- upper <- matrix(NA,nbAnimals,mixtures) colnames(est) <- colnames(se) <- colnames(lower) <- colnames(upper) <- paste0("mix",1:mixtures) rownames(est) <- rownames(se) <- rownames(lower) <- rownames(upper) <- paste0("ID:",unique(m$data$ID)) for(k in 1:nbAnimals){ ind <- which(m$data$ID==unique(m$data$ID)[k]) tmp <- m tmp$data <- m$data[ind,] tmp$covsDelta <- m$covsDelta[k,,drop=FALSE] tmp$covsPi <- m$covsPi[k,,drop=FALSE] tmp$conditions$knownStates <- rep(NA,nrow(tmp$data)) tmp$conditions$fullDM <- lapply(m$conditions$fullDM,function(y) matrix(mapply(function(x){if(length(x)>1){return(x[ind])} else {return(x)}},y,SIMPLIFY = TRUE),nrow(y),ncol(y),dimnames=dimnames(y))) est[k,] <- get_mixProbs(tmp$mod$wpar,mod=tmp,mixture=1:mixtures) if(getCI){ cat("\rComputing SEs and ",alpha*100,"% CIs for individual ",unique(m$data$ID)[k],"... ",sep="") for(mix in 1:mixtures){ dN<-t(tryCatch(numDeriv::grad(get_mixProbs,tmp$mod$wpar,mod=tmp,mixture=mix),error=function(e) NA)) se[k,mix] <- sqrt(dN %*% m$mod$Sigma %*% t(dN)) lower[k,mix] <- 1/(1+exp(-(log(est[k,mix]/(1-est[k,mix]))-quantSup*(1/(est[k,mix]-est[k,mix]^2))*se[k,mix]))) upper[k,mix] <- 1/(1+exp(-(log(est[k,mix]/(1-est[k,mix]))+quantSup*(1/(est[k,mix]-est[k,mix]^2))*se[k,mix]))) } } } if(getCI) { cat("DONE\n") out <- list(est=est,se=se,lower=lower,upper=upper) } else out <- est return(out) } get_mixProbs <- function(optPar,mod,mixture){ dist <- mod$conditions$dist nbStates <- length(mod$stateNames) data <- mod$data mixtures <- mod$conditions$mixtures formula <- mod$conditions$formula knownStates <- mod$conditions$knownStates newForm <- newFormulas(formula,nbStates,mod$conditions$betaRef,hierarchical = TRUE) formulaStates <- newForm$formulaStates newformula <- newForm$newformula recharge <- newForm$recharge covs <- stats::model.matrix(newformula,data) nbCovs <- ncol(covs)-1 if(!is.null(recharge)){ reForm <- formatRecharge(nbStates,formula,mod$conditions$betaRef,data=data) formulaStates <- reForm$formulaStates newformula <- reForm$newformula recharge <- reForm$recharge hierRecharge <- reForm$hierRecharge newdata <- reForm$newdata g0covs <- reForm$g0covs nbG0covs <- ncol(g0covs)-1 recovs <- reForm$recovs nbRecovs <- ncol(recovs)-1 covs <- reForm$covs nbCovs <- ncol(covs)-1 recovsCol <- get_all_vars(recharge$theta,data) if(!all(names(recovsCol) %in% names(data))){ recovsCol <- recovsCol[,names(recovsCol) %in% names(data),drop=FALSE] } g0covsCol <- get_all_vars(recharge$g0,data) if(!all(names(g0covsCol) %in% names(data))){ g0covsCol <- g0covsCol[,names(g0covsCol) %in% names(data),drop=FALSE] } } else { nbRecovs <- 0 nbG0covs <- 0 g0covs <- g0covsCol <- NULL recovs <- recovsCol <- NULL newdata <- NULL } distnames<-names(dist) nbCovs <- ncol(covs)-1 if(!is.null(recovs)) { nbRecovs <- ncol(recovs)-1 nbG0covs <- ncol(g0covs)-1 } else nbRecovs <- nbG0covs <- 0 ncmean <- get_ncmean(distnames,mod$conditions$fullDM,mod$conditions$circularAngleMean,nbStates) nc <- ncmean$nc meanind <- ncmean$meanind consensus <- vector('list',length(distnames)) names(consensus) <- distnames for(i in distnames){ consensus[[i]] <- (dist[[i]]=="vmConsensus") } dist <- lapply(dist,function(x) gsub("Consensus","",x)) dist <- lapply(dist,function(x) ifelse(grepl("cat",x),"cat",x)) wpar <- expandPar(optPar,mod$conditions$optInd,mod$mod$estimate,mod$conditions$wparIndex,mod$conditions$betaCons,mod$conditions$deltaCons,nbStates,ncol(mod$covsDelta)-1,mod$conditions$stationary,nbCovs,nbRecovs+nbG0covs,mixtures,ncol(mod$covsPi)-1) par <- w2n(wpar,mod$conditions$bounds,lapply(mod$conditions$fullDM,function(x) nrow(x)/nbStates),nbStates,nbCovs,mod$conditions$estAngleMean,mod$conditions$circularAngleMean,consensus,mod$conditions$stationary,mod$conditions$fullDM,mod$conditions$DMind,nrow(mod$data),dist,mod$conditions$Bndind,nc,meanind,mod$covsDelta,mod$conditions$workBounds,mod$covsPi) if(nbRecovs){ for(i in 1:length(unique(data$ID))){ idInd <- which(data$ID==unique(data$ID)[i]) if(inherits(data,"hierarchical")) { recLevels <- length(recharge) recLevelNames <- names(recharge) rechargeNames <- paste0("recharge",gsub("level","",recLevelNames)) colInd <- lapply(recLevelNames,function(x) which(grepl(paste0("I((level == \"",gsub("level","",x),"\")"),colnames(recovs),fixed=TRUE))) } else { recLevels <- 1 rechargeNames <- "recharge" colInd <- list(1:ncol(recovs)) } for(iLevel in 1:recLevels){ g0 <- par$g0 %*% t(g0covs[(i-1)*recLevels+iLevel,,drop=FALSE]) theta <- par$theta covs[idInd,grepl(rechargeNames[iLevel],colnames(covs))] <- cumsum(c(g0,theta[colInd[[iLevel]]]%*%t(recovs[idInd[-length(idInd)],colInd[[iLevel]]]))) } } } if(is.null(knownStates)) knownStates <- -1 else knownStates[which(is.na(knownStates))] <- 0 if(any(unlist(lapply(dist,is.null)))){ par[which(unlist(lapply(dist,is.null)))]<-matrix(NA) } if(mod$conditions$stationary) par$delta <- c(NA) if(nbStates==1) { par$beta <- matrix(NA) par$delta <- c(NA) par[distnames] <- lapply(par[distnames],as.matrix) } nbCovsDelta <- ncol(mod$covsDelta)-1 beta <- par$beta delta <- par$delta pie <- par[["pi"]] pInd <- which(mapply(function(x) isTRUE(all.equal(x,0)), pie)) if (length(pInd)) { pie[pInd] <- 1e-100 pie[-pInd] <- pie[-pInd] - (1e-100 * length(pInd))/(ncol(pie) - length(pInd)) } par[["pi"]] <- matrix(1,1,1) mixProbs <- lnum <- la <- numeric(mixtures) for(mix in 1:mixtures){ par$beta <- beta[(mix-1)*(nbCovs+1)+1:(nbCovs+1),,drop=FALSE] if(!mod$conditions$stationary) par$delta <- delta[mix,,drop=FALSE] la[mix] <- nLogLike_rcpp(nbStates,as.matrix(covs),data,names(dist),dist, par, 1,mod$conditions$zeroInflation,mod$conditions$oneInflation,mod$conditions$stationary,knownStates,mod$conditions$betaRef,1) if(!is.null(mod$prior)) la[mix] <- la[mix] - mod$prior(wpar) c <- max(-la[mix]+log(pie[mix])) lnum[mix] <- c + log(sum(exp(-la[mix]+log(pie[mix])-c))) } c <- max(lnum) mixProbs <- exp(lnum - c - log(sum(exp(lnum-c)))) return(mixProbs[mixture]) }
".onAttach"<- function(...) { packageStartupMessage("NORMT3: Evaluates erf, erfc, Faddeeva functions and Gaussian/T sum densities") packageStartupMessage("Copyright: Guy Nason 2005-2012") }
test3Gwbwa <- function(X,freq,verbose=TRUE,rounding=3){ k = ncol(X) res = group_data(X,freq) his = res[,1:k] eff = res[,k+1] nh = nrow(his) a = max(his) kplusun = k + 1 table_wbwa = data.frame(occasion = rep(NA,a*(k-2)),site = rep(NA,a*(k-2)),stat = rep(NA,a*(k-2)), df = rep(NA,a*(k-2)), p_val = rep(NA,a*(k-2)), test_perf = rep(FALSE,a*(k-2))) where_in_table_wbwa = 0 for (i in 2:(k-1)){ for (l in 1:a){ where_in_table_wbwa = where_in_table_wbwa + 1 fisheroupas = 0 fisherWBWA = 0 masque = (his[,i]==l) batch = his[masque,] if (length(batch)==0){ table_wbwa[where_in_table_wbwa,1] = i table_wbwa[where_in_table_wbwa,2] = l table_wbwa[where_in_table_wbwa,3] = 0 table_wbwa[where_in_table_wbwa,4] = 0 table_wbwa[where_in_table_wbwa,5] = 0 table_wbwa[where_in_table_wbwa,6] = 'None' next } batcheff = eff[masque] res = group_data_gen(batch,batcheff,(i+1):k) batchpost = res[,1:ncol(res)-1] batcheffpost = res[,ncol(res)] if (i!=2){ tt = t(apply(batchpost[,1:(i-1)],1,rev)) eante = apply(tt!=0,1,which.max) eante = i - eante } else { eante = rep(1,nrow(batchpost)) } if (i!=(k-1)){ epost = apply(batchpost[,(i+1):k]!=0,1,which.max) } else { epost = rep(1,nrow(batchpost)) } j = 0 ind = (k-i)*a+1 table = matrix(0,nrow=a+1,ncol=ind) cpt = matrix(0,nrow=a+1,ncol=1) while (j<nrow(batchpost)){ j=j+1 date = epost[j] site = batchpost[j,i+date] if (site==0){ col = ind } else{ col = (date-1)*a+site } if (j==1){ cold = col } else if (col!=cold){ table[,cold] = cpt cpt = matrix(0,nrow=a+1,ncol=1) cold = col } tempo = batchpost[j,eante[j]] + 1 if (site==0){ cpt[tempo] = cpt[tempo] + batcheffpost[j] * (batcheffpost[j]>0) } else { cpt[tempo]=cpt[tempo]+abs(batcheffpost[j]) } } table[,cold] = cpt compoWBWA = table compoWBWA = compoWBWA[-1,] colWBWA = ncol(compoWBWA) compoWBWA = compoWBWA[,-colWBWA] for (j in 1:((colWBWA-1)/a-1)){ if (((colWBWA-1)/a-1)<1) break compoWBWA[,1:a] = compoWBWA[,1:a] + compoWBWA[,(a+1):(2*a)] compoWBWA = compoWBWA[,-((a+1):(2*a))] } expvalWBWA = expval_table(compoWBWA) ind1 = apply(expvalWBWA,2,min) ind2 = apply(expvalWBWA,2,which.min) ncol = which.min(ind1) nline = ind2[ncol] vec_direction = c(ncol,nline) while (expvalWBWA[nline,ncol]<2){ if (sum(compoWBWA[nline,])/ncol(compoWBWA) > sum(compoWBWA[,ncol])/nrow(compoWBWA)){ pooldim = 1 } else { pooldim = 2 } flag = which(dim(compoWBWA)==2) if (length(flag)==1){ pooldim = flag } else if (length(flag)==2){ fisherWBWA = 1 break } marge = apply(t(compoWBWA),pooldim,sum) marge[vec_direction[pooldim]] = max(marge) + 1 ind1 = min(marge) ind2 = which.min(marge) if (pooldim==1){ compoWBWA[,ncol] = compoWBWA[,ncol] + compoWBWA[,ind2] compoWBWA = compoWBWA[,-ind2] } else { compoWBWA[nline,] = compoWBWA[nline,] + compoWBWA[ind2,] compoWBWA = compoWBWA[-ind2,] } expvalWBWA = expval_table(compoWBWA) ind1 = apply(expvalWBWA,2,min) ind2 = apply(expvalWBWA,2,which.min) ncol = which.min(ind1) nline = ind2[ncol] vec_direction = c(ncol,nline) } if (fisherWBWA == 1){ fish = stats::fisher.test(compoWBWA) pvalfish = fish$p.value zeros_rows = (apply(compoWBWA,1,sum)==0) zeros_cols = (apply(compoWBWA,2,sum)==0) if (sum(!zeros_rows)+sum(!zeros_cols)==0){ dffish = 0 } else { dffish = (sum(!zeros_rows)-1)*(sum(!zeros_cols)-1) } stafish = stats::qchisq(1-pvalfish, dffish) table_wbwa[where_in_table_wbwa,1] = i table_wbwa[where_in_table_wbwa,2] = l table_wbwa[where_in_table_wbwa,3] = stafish table_wbwa[where_in_table_wbwa,4] = dffish table_wbwa[where_in_table_wbwa,5] = pvalfish table_wbwa[where_in_table_wbwa,6] = 'Fisher' } else { old.warn <- options()$warn options(warn = -1) chi2 = stats::chisq.test(compoWBWA,correct=F) options(warn = old.warn) pvalchi2 = chi2$p.value dfchi2 = chi2$parameter stachi2 = chi2$statistic table_wbwa[where_in_table_wbwa,1] = i table_wbwa[where_in_table_wbwa,2] = l table_wbwa[where_in_table_wbwa,3] = stachi2 table_wbwa[where_in_table_wbwa,4] = dfchi2 table_wbwa[where_in_table_wbwa,5] = pvalchi2 table_wbwa[where_in_table_wbwa,6] = 'Chi-square' } } } stat = sum(as.numeric(table_wbwa[,3])) stat = round(stat,rounding) dof = sum(as.numeric(table_wbwa[,4])) pval = 1 - stats::pchisq(stat,dof) pval = round(pval,rounding) if (verbose==TRUE) return(list(test3Gwbwa=c(stat=stat,df=dof,p_val=pval),details=table_wbwa)) if (verbose==FALSE) return(list(test3Gwbwa=c(stat=stat,df=dof,p_val=pval))) }
library(OpenMx) mxOption(NULL, "Default optimizer", "SLSQP") if (mxOption(NULL, 'Default optimizer') != "SLSQP") stop("SKIP") resVars <- mxPath( from=c("x1","x2","x3","x4","x5"), arrows=2, free=TRUE, values = 1, labels=c("residual","residual","residual","residual","residual") ) latVars <- mxPath( from=c("intercept","slope"), arrows=2, connect="unique.pairs", free=c(TRUE,FALSE,TRUE), values=c(1,0,1), labels=c("vari","cov","vars")) intLoads <- mxPath( from="intercept", to=c("x1","x2","x3","x4","x5"), arrows=1, free=FALSE, values=1 ) sloLoads <- mxPath( from="slope", to=c("x1","x2","x3","x4","x5"), arrows=1, free=FALSE, values=seq(-2,2) ) manMeans <- mxPath( from="one", to=c("x1","x2","x3","x4","x5"), arrows=1, free=FALSE, values=0) latMeans <- mxPath( from="one", to=c("intercept", "slope"), arrows=1, free=FALSE, values=0, labels=c("meani","means") ) growthCurveModel <- mxModel("Linear Growth Curve Model Path Specification", type="RAM", manifestVars=c("x1","x2","x3","x4","x5"), latentVars=c("intercept","slope"), resVars, latVars, intLoads, sloLoads, manMeans, latMeans) result <- expand.grid(rep=1:25000, adj=c(TRUE,FALSE), trueSvar=c(0,.3,.6), interval=c(.95), lbound=NA, val=NA, ubound=NA, retries=NA) if (0) { load("/tmp/lgc-sim.rda") } bounds <- c('lbound','ubound') for (rx in 1:nrow(result)) { set.seed(result[rx,'rep']) true.svar <- result[rx,'trueSvar'] ci.adj <- result[rx,'adj'] growthCurveModel$S$values['slope','slope'] <- true.svar dset <- mxGenerateData(growthCurveModel, nrows = 150) m1 <- mxModel(growthCurveModel, mxData(cov(dset), 'cov', colMeans(dset), nrow(dset))) m1$S$values['slope','slope'] <- .5 if (ci.adj) { m1$S$lbound['slope','slope'] <- 0 } else { m1$S$lbound['slope','slope'] <- NA } m1 <- mxModel(m1, mxCI('vars', boundAdj = ci.adj, interval=result[rx,'interval'])) plan <- mxComputeSequence(list( GD=mxComputeGradientDescent(), CI=mxComputeConfidenceInterval( fitfunction="fitfunction", constraintType='ineq', plan=mxComputeTryHard( maxRetries=50L, scale=.05, plan=mxComputeGradientDescent(nudgeZeroStarts = FALSE, maxMajorIter = 150L))))) m1 <- mxModel(m1, plan) m1 <- try(mxRun(m1, intervals=TRUE, suppressWarnings=TRUE, silent=TRUE)) if (is(m1, "try-error")) { print(paste("optimizer failed on", rx)) next } detail <- m1$compute$steps[['CI']]$output$detail ci <- m1$output$confidenceIntervals result[rx,bounds] <- ci[1,bounds] result[rx,'val'] <- ci[1,'estimate'] result[rx,'retries'] <- m1$compute$steps[['CI']]$plan$debug$retries if (rx %% 1000 == 0) { print(rx) save(result, file="/tmp/lgc-sim.rda") } } result$region <- NA result[result[,'lbound'] <= result[,'trueSvar'] & result[,'trueSvar'] <= result[,'ubound'],'region'] <- 'M' result[result[,'lbound'] > result[,'trueSvar'], 'region'] <- 'L' result[result[,'ubound'] < result[,'trueSvar'], 'region'] <- 'U' library(plyr) resultSummary <- ddply(result, .(adj, trueSvar, interval), function(sim) { c(M=sum(sim$region == 'M'), L=sum(sim$region== 'L'), U=sum(sim$region=='U')) / nrow(sim) }) print(resultSummary) if(0) { save(resultSummary, file="~/vcu/ci/lgc-sim.rda") } if(0) { lgc.sim <- result save(lgc.sim, file="~/vcu/ci/lgc-sim.rda") }
source("ESEUR_config.r") par(mar=MAR_default-c(2.7, 2.7, 0, 0.8)) pal_col=rainbow(3) draw_circle=function(x, y, rad) { angles<-seq(0, 2*pi, by=0.01) xt<-x+cos(angles)*rad yt<-y+sin(angles)*rad polygon(xt, yt, border="grey", col="grey") } three_circles=function(x, y, col_str="white") { xs=x-c_rad*2.5 xe=x+c_rad*2.5 ys=y-c_rad*2.5 ye=y+c_rad*2.5 polygon(c(xs-0.5, xe+0.5, xe+0.5, xs-0.5, xs-0.5), c(ye, ye, ys-1, ys-1, ye), border="white", col=col_str) draw_circle(x, y, c_rad) draw_circle(x-0.5, y-1, c_rad) draw_circle(x+0.5, y-1, c_rad) } triange_line=function(y, cb) { three_circles(1, y, ifelse(!cb, "white", "pale green")) three_circles(1+1*tri_xoff, y, ifelse(cb, "white", "pale green")) three_circles(1+2*tri_xoff, y, ifelse(!cb, "white", "pale green")) } intervention=function(from, to, x, y) { n1_x=1+x*tri_xoff n1_y=1+y*tri_yoff x_node=c(0, -0.5, 0.5) y_node=c(0, -1, -1) x_from_off=ifelse(from+to == 5, ifelse(from==2, c_rad, -c_rad), 0) x_to_off=-x_from_off y_from_off=ifelse(from+to == 5, 0, ifelse(from==1, -c_rad, c_rad)) y_to_off=-y_from_off arrows(n1_x+x_node[from]+x_from_off, n1_y+y_node[from]+y_from_off, n1_x+x_node[to]+x_to_off, n1_y+y_node[to]+y_to_off, length=0.05) } c_rad=0.1 tri_xoff=1.7 tri_yoff=1.6 plot(0, type="n", bty="n", xaxs="i", yaxs="i", xaxt="n", yaxt="n", xlim=c(0.3, 5.2), ylim=c(-0.2, 4.4), xlab="", ylab="") triange_line(1, 0) triange_line(1+1*tri_yoff, 1) triange_line(1+2*tri_yoff, 0) intervention(3, 2, 0, 0) intervention(3, 1, 0, 1) intervention(1, 2, 0, 2) intervention(1, 3, 1, 0) intervention(3, 2, 1, 0) intervention(2, 1, 1, 2) intervention(1, 3, 1, 2) intervention(3, 2, 2, 0) intervention(3, 1, 2, 0) intervention(2, 1, 2, 1) intervention(2, 3, 2, 1) intervention(1, 2, 2, 2) intervention(1, 3, 2, 2) intervention(3, 2, 2, 2)
ez_ui = function(data) { miniUI::miniPage( miniUI::gadgetTitleBar("ezplot"), miniUI::miniContentPanel( shiny::fillRow( flex = c(1,3), shiny::column( width = 12, shiny::selectInput( "selected_data", "Select data", choices = c( if (is.null(data)) NULL else "ez_app(data)", "ansett", "aus_livestock", "aus_production", "aus_retail", "gafa_stock", "global_economy", "hh_budget", "nyc_bikes", "olympic_running", "PBS", "pelt", "vic_elec" ), width = "100%" ), shiny::selectInput("geom", "Select chart type", c("line", "bar", "area", "pie", "waterfall"), width = "100%"), shiny::uiOutput("select_x"), shiny::uiOutput("select_y"), shiny::uiOutput("select_group"), shiny::uiOutput("select_facet_x"), shiny::uiOutput("select_facet_y") ), shiny::tabsetPanel( shiny::tabPanel( "Chart", shiny::fillCol( shiny::br(), shiny::plotOutput("plot", height = "600")) ), shiny::tabPanel( "Data", shiny::br(), DT::dataTableOutput("data_table") ) ) ) ) ) }
knitr::opts_chunk$set( collapse = TRUE, comment = " fig.path = "man/figures/vignette_cv_custom_fn-", dpi = 92, fig.retina = 2 ) library(cvms) library(groupdata2) library(dplyr) library(knitr) library(e1071) set.seed(1) data <- participant.scores data$diagnosis <- factor(data$diagnosis) data <- fold( data, k = 3, cat_col = "diagnosis", id_col = "participant", num_fold_cols = 5, parallel = FALSE ) data <- data %>% dplyr::arrange(participant) data %>% head(12) %>% kable() data %>% dplyr::count(.folds_1, diagnosis) %>% kable() data %>% dplyr::count(.folds_1, participant) %>% kable() test_set <- data %>% dplyr::filter(.folds_1 == 3) train_set <- data %>% dplyr::filter(.folds_1 != 3) svm_model <- e1071::svm( formula = score ~ diagnosis + age + session, data = train_set, kernel = "linear", cost = 10, type = "eps-regression" ) predicted_scores <- predict( svm_model, newdata = test_set, allow.new.levels = TRUE) predicted_scores test_set[["predicted score"]] <- predicted_scores evaluate( data = test_set, target_col = "score", prediction_cols = "predicted score", type = "gaussian" ) svm_model_fn <- function(train_data, formula, hyperparameters) { e1071::svm( formula = formula, data = train_data, kernel = "linear", cost = 10, type = "eps-regression" ) } m0 <- svm_model_fn(train_data = train_set, formula = score ~ diagnosis + age + session) m0 svm_predict_fn <- function(test_data, model, formula, hyperparameters, train_data) { predict(object = model, newdata = test_data, allow.new.levels = TRUE) } svm_predict_fn(test_data = test_set, model = m0) cv_1 <- cross_validate_fn( data = data, formulas = c("score ~ diagnosis + age + session", "score ~ diagnosis + age", "score ~ diagnosis"), type = "gaussian", model_fn = svm_model_fn, predict_fn = svm_predict_fn, fold_cols = paste0(".folds_", 1:5), parallel = FALSE ) cv_1 svm_model_fn <- function(train_data, formula, hyperparameters) { if (!"kernel" %in% names(hyperparameters)) stop("'hyperparameters' must include 'kernel'") if (!"cost" %in% names(hyperparameters)) stop("'hyperparameters' must include 'cost'") e1071::svm( formula = formula, data = train_data, kernel = hyperparameters[["kernel"]], cost = hyperparameters[["cost"]], scale = FALSE, type = "eps-regression" ) } svm_model_fn( train_data = train_set, formula = score ~ diagnosis + age + session, hyperparameters = list( "kernel" = "linear", "cost" = 5 ) ) svm_model_fn <- function(train_data, formula, hyperparameters) { hyperparameters <- update_hyperparameters( kernel = "radial", hyperparameters = hyperparameters, required = "cost" ) e1071::svm( formula = formula, data = train_data, kernel = hyperparameters[["kernel"]], cost = hyperparameters[["cost"]], type = "eps-regression" ) } hparams <- list( "kernel" = c("linear", "radial"), "cost" = c(1, 5, 10) ) hparams <- list( ".n" = 4, "kernel" = c("linear", "radial"), "cost" = c(1, 5, 10) ) df_hparams <- data.frame( "kernel" = c("linear", "radial", "radial"), "cost" = c(10, 1, 10) ) df_hparams set.seed(1) cv_2 <- cross_validate_fn( data = data, formulas = c("score ~ diagnosis + age + session", "score ~ diagnosis"), type = "gaussian", model_fn = svm_model_fn, predict_fn = svm_predict_fn, hyperparameters = hparams, fold_cols = paste0(".folds_", 1:5) ) cv_2 cv_2 %>% dplyr::mutate(`Model ID` = 1:nrow(cv_2)) %>% dplyr::arrange(RMSE) %>% select_definitions(additional_includes = c("RMSE", "Model ID")) %>% kable() cv_2$Results[[1]] %>% kable() cv_2$Predictions[[1]] %>% head(10) %>% kable() preprocess_fn <- function(train_data, test_data, formula, hyperparameters) { mean_age <- mean(train_data[["age"]]) sd_age <- sd(train_data[["age"]]) train_data[["age"]] <- (train_data[["age"]] - mean_age) / sd_age test_data[["age"]] <- (test_data[["age"]] - mean_age) / sd_age preprocess_parameters <- data.frame( "Measure" = c("Mean", "SD"), "age" = c(mean_age, sd_age) ) list("train" = train_data, "test" = test_data, "parameters" = preprocess_parameters) } prepped <- preprocess_fn(train_data = train_set, test_data = test_set) prepped$train %>% head(5) %>% kable() prepped$parameters %>% kable() cv_3 <- cross_validate_fn( data = data, formulas = c("score ~ diagnosis + age + session", "score ~ diagnosis"), type = "gaussian", model_fn = svm_model_fn, predict_fn = svm_predict_fn, preprocess_fn = preprocess_fn, hyperparameters = list( "kernel" = "linear", "cost" = 1 ), fold_cols = paste0(".folds_", 1:5) ) cv_3 cv_3$Preprocess[[1]] %>% head(10) %>% kable() preprocess_functions("standardize") clf_svm_model_fn <- function(train_data, formula, hyperparameters) { hyperparameters <- update_hyperparameters( kernel = "radial", cost = 1, hyperparameters = hyperparameters ) e1071::svm( formula = formula, data = train_data, kernel = hyperparameters[["kernel"]], cost = hyperparameters[["cost"]], type = "C-classification", probability = TRUE ) } m1 <- clf_svm_model_fn(train_data = data, formula = diagnosis ~ score, hyperparameters = list("kernel" = "linear")) m1 bnml_svm_predict_fn <- function(test_data, model, formula, hyperparameters, train_data) { predictions <- predict( object = model, newdata = test_data, allow.new.levels = TRUE, probability = TRUE ) probabilities <- dplyr::as_tibble(attr(predictions, "probabilities")) probabilities[[2]] } p1 <- bnml_svm_predict_fn(test_data = data, model = m1) p1 cv_4 <- cross_validate_fn( data = data, formulas = c("diagnosis ~ score", "diagnosis ~ age"), type = "binomial", model_fn = clf_svm_model_fn, predict_fn = bnml_svm_predict_fn, hyperparameters = list( "kernel" = c("linear", "radial"), "cost" = c(1, 5, 10) ), fold_cols = paste0(".folds_", 1:5) ) cv_4 cv_4 %>% dplyr::mutate(`Model ID` = 1:nrow(cv_4)) %>% dplyr::arrange(dplyr::desc(`Balanced Accuracy`)) %>% select_definitions(additional_includes = c("Balanced Accuracy", "F1", "MCC", "Model ID")) %>% kable() set.seed(1) data_mc <- musicians data_mc[["ID"]] <- as.factor(data_mc[["ID"]]) data_mc <- fold( data = data_mc, k = 5, cat_col = "Class", num_col = "Age", num_fold_cols = 5 ) data_mc %>% head(10) %>% kable() mc_svm_predict_fn <- function(test_data, model, formula, hyperparameters, train_data) { predictions <- predict( object = model, newdata = test_data, allow.new.levels = TRUE, probability = TRUE ) probabilities <- dplyr::as_tibble(attr(predictions, "probabilities")) probabilities } cv_5 <- cross_validate_fn( data = data_mc, formulas = c("Class ~ Age + Height", "Class ~ Age + Height + Bass + Guitar + Keys + Vocals"), type = "multinomial", model_fn = clf_svm_model_fn, predict_fn = mc_svm_predict_fn, hyperparameters = list( "kernel" = c("linear", "radial"), "cost" = c(1, 5, 10) ), fold_cols = paste0(".folds_", 1:5) ) cv_5 cv_5 %>% dplyr::mutate(`Model ID` = 1:nrow(cv_5)) %>% dplyr::arrange(dplyr::desc(`Balanced Accuracy`)) %>% select_definitions(additional_includes = c( "Balanced Accuracy", "F1", "Model ID")) %>% kable() cv_5$`Class Level Results`[[11]] cv_5$Results[[11]] cv_5$`Confusion Matrix`[[11]] overall_confusion_matrix <- cv_5$`Confusion Matrix`[[11]] %>% dplyr::group_by(Prediction, Target) %>% dplyr::summarise(N = sum(N)) overall_confusion_matrix %>% kable() plot_confusion_matrix(overall_confusion_matrix, add_sums = TRUE)
avg152T1 <- readANALYZE(file.path(system.file("anlz", package="oro.nifti"), "avg152T1")) image(avg152T1) orthographic(avg152T1)
collection_ml <- function(xyz, wavelength=632.8, omega = c(40, 50)*pi/180, psi=0, epsilon = c(1.5^2, epsAg(wavelength)$epsilon, 1.0^2, 1.0^2), thickness = c(0, 50, 10, 0), maxEval = 3000, reqAbsError = 0.0, tol=1e-04, progress=FALSE){ k0 <- 2*pi/wavelength I <- cpp_field_collection(xyz, k0, psi, omega, epsilon, thickness, as.integer(maxEval), as.double(reqAbsError), tol, progress) I }
resetDummyProvider() verbose <- 0 test_that("testthat", { expect_error( provider <- DummyProvider() ,NA) expect_error( container <- DummyWorkerContainer() ,NA) expect_error( generalDockerClusterTest( cloudProvider = provider, workerContainer = container, workerNumber = 5, testReconnect = TRUE, verbose = verbose) ,NA) })
setConstructorS3("AbstractCBS", function(fit=list(), sampleName=fit$sampleName, ...) { if (!is.null(sampleName)) { sampleName <- Arguments$getCharacter(sampleName) } fit$sampleName <- sampleName extend(fit, "AbstractCBS") }) setMethodS3("print", "AbstractCBS", function(x, ...) { fit <- x segs <- getSegments(fit, simplify=TRUE, ...) print(segs) }, protected=TRUE) setMethodS3("all.equal", "AbstractCBS", function(target, current, check.attributes=FALSE, ...) { args <- list(...) drop <- integer(0L) for (kk in seq_along(args)) { if (identical(args[[kk]], target)) drop <- c(drop, kk) if (identical(args[[kk]], current)) drop <- c(drop, kk) } if (length(drop) > 0L) { args <- args[-drop] str(args) } args <- list(...) res <- all.equal(class(target), class(current)) if (!isTRUE(res)) { return(res) } dataT <- getLocusData(target) dataC <- getLocusData(current) res <- all.equal(dataT, dataC, check.attributes=check.attributes) if (!isTRUE(res)) { attr(res, "what") <- "getLocusData()" return(res) } dataT <- getSegments(target) dataC <- getSegments(current) res <- all.equal(dataT, dataC, check.attributes=check.attributes) if (!isTRUE(res)) { attr(res, "what") <- "getSegments()" return(res) } fieldsT <- names(target) fieldsC <- names(current) res <- all.equal(fieldsT, fieldsC, check.attributes=check.attributes) if (!isTRUE(res)) { attr(res, "what") <- "names" return(res) } for (key in fieldsT) { dataT <- target[[key]] dataC <- current[[key]] res <- all.equal(dataT, dataC, check.attributes=check.attributes) if (!isTRUE(res)) { attr(res, "what") <- sprintf("[[\"%s\"]]", key) return(res) } } return(TRUE) }, protected=TRUE) setMethodS3("save", "AbstractCBS", function(this, ...) { action <- Sys.getenv("R_PSCBS_SAVE_LOAD_DEPRECATED", "defunct") action <- match.arg(action, choices = c("deprecated", "defunct")) fcn <- switch(action, deprecated = .Deprecated, defunct = .Defunct) fcn(msg = sprintf("save() for %s is %s. It is recommended to use saveRDS() from the 'base' package. If you need backward compatibility with save(), use R.utils::saveObject().", class(this)[1], action), package = .packageName) saveObject(this, ...) }) setMethodS3("load", "AbstractCBS", function(static, ...) { action <- Sys.getenv("R_PSCBS_SAVE_LOAD_DEPRECATED", "defunct") action <- match.arg(action, choices = c("deprecated", "defunct")) fcn <- switch(action, deprecated = .Deprecated, defunct = .Defunct) fcn(msg = sprintf("%s$load() is %s. It is recommended to use readRDS() from the 'base' package instead. If you need backward compatibility with load(), use R.utils::loadObject().", class(static)[1], action), package = .packageName) object <- loadObject(...) if (!inherits(object, "AbstractCBS")) { if (inherits(object, "CBS")) { class(object) <- c(class(object), "AbstractCBS") warning("Added 'AbstractCBS' to the class hierarchy of the loaded ", class(object)[1], " object.") } else if (inherits(object, "PairedPSCBS")) { class(object) <- c(class(object), "AbstractCBS") warning("Added 'AbstractCBS' to the class hierarchy of the loaded ", class(object)[1], " object.") } } if (!inherits(object, class(static)[1])) { stop("Loaded an object from file, but it does not inherit from ", class(static)[1], " as expected: ", hpaste(class(object))) } object }, static=TRUE) setMethodS3("getSampleName", "AbstractCBS", function(fit, ...) { name <- fit$sampleName if (is.null(name)) { name <- NA_character_ } name }, protected=TRUE) setMethodS3("sampleName", "AbstractCBS", function(fit, ...) { getSampleName(fit) }, protected=TRUE) setMethodS3("setSampleName", "AbstractCBS", function(fit, name, ...) { name <- Arguments$getCharacter(name) fit$sampleName <- name invisible(fit) }, protected=TRUE) setMethodS3("sampleName<-", "AbstractCBS", function(x, value) { setSampleName(x, value) }, protected=TRUE, addVarArgs=FALSE) "sampleName<-" <- function(x, value) { UseMethod("sampleName<-") } setMethodS3("getLocusData", "AbstractCBS", abstract=TRUE) setMethodS3("setLocusData", "AbstractCBS", function(fit, loci, ...) { loci <- Arguments$getInstanceOf(loci, "data.frame") nbrOfLoci <- nbrOfLoci(fit) if (nrow(loci) != nbrOfLoci) { stop("Cannot set locus-level data. The number of loci to be set differ from the existing number of loci: ", nrow(loci), " != ", nbrOfLoci) } fit$data <- loci invisible(fit) }, protected=TRUE) setMethodS3("getLocusSignalNames", "AbstractCBS", abstract=TRUE, protected=TRUE) setMethodS3("getSegmentTrackPrefixes", "AbstractCBS", abstract=TRUE, protected=TRUE) setMethodS3("nbrOfLoci", "AbstractCBS", function(fit, splitters=FALSE, ...) { data <- getLocusData(fit, splitters=splitters, ...) nrow(data) }) setMethodS3("getSegments", "AbstractCBS", abstract=TRUE) setMethodS3("setSegments", "AbstractCBS", function(fit, segments, splitters=TRUE, ...) { segments <- Arguments$getInstanceOf(segments, "data.frame") nbrOfSegs <- nbrOfSegments(fit, splitters=splitters, ...) if (nrow(segments) != nbrOfSegs) { stop("Cannot set segments. The number of segments to be set differ from the existing number of segments: ", nrow(segments), " != ", nbrOfSegs) } fit$output <- segments invisible(fit) }, protected=TRUE) setMethodS3("getChangePoints", "AbstractCBS", abstract=TRUE) setMethodS3("resetSegments", "AbstractCBS", function(fit, ...) { segs <- getSegments(fit, splitters=TRUE) names <- colnames(segs) excl <- NULL idxs <- grep("_[0-9.]*[%]$", names) excl <- c(excl, idxs) idxs <- grep("Call$", names) excl <- c(excl, idxs) excl <- unique(excl) if (length(excl) > 0L) { segs <- segs[,-excl] } fit <- setSegments(fit, segs, splitters=TRUE) invisible(fit) }, protected=TRUE) setMethodS3("nbrOfSegments", "AbstractCBS", function(this, splitters=FALSE, ...) { nrow(getSegments(this, splitters=splitters, ...)) }) setMethodS3("nbrOfChangePoints", "AbstractCBS", function(fit, ignoreGaps=FALSE, dropEmptySegments=TRUE, ...) { segs <- getSegments(fit, splitters=TRUE, addGaps=!ignoreGaps) if (dropEmptySegments) { prefix <- getSegmentTrackPrefixes(fit) keys <- sapply(prefix, FUN=function(x) { toCamelCase(paste(c(x, "nbr of loci"), collapse=" ")) }) counts <- as.matrix(segs[,keys]) counts <- rowSums(counts, na.rm=TRUE) segs$chromosome[counts == 0L] <- NA } sum(!is.na(diff(segs$chromosome))) }) setMethodS3("as.data.frame", "AbstractCBS", function(x, ...) { getSegments(x, ...) }, protected=TRUE) setMethodS3("getChromosomes", "AbstractCBS", function(this, ...) { segs <- getSegments(this, ...) chromosomes <- sort(unique(segs$chromosome), na.last=TRUE) if (length(chromosomes) > 1) { chromosomes <- chromosomes[!is.na(chromosomes)] } chromosomes }) setMethodS3("nbrOfChromosomes", "AbstractCBS", function(this, ...) { length(getChromosomes(this, ...)) }) setMethodS3("getSegmentSizes", "AbstractCBS", function(fit, by=c("length", "count"), ...) { by <- match.arg(by) if (by == "length") { prefix <- getSegmentTrackPrefixes(fit)[1] keys <- toCamelCase(paste(prefix, " ", c("start", "end"))) } else if (by == "count") { keys <- "nbrOfLoci" } data <- getSegments(fit, ...)[,keys] if (by == "length") { res <- data[[2L]]-data[[1L]]+1L } else if (by == "count") { res <- data[[1L]] } res }) setMethodS3("extractCNs", "AbstractCBS", abstract=TRUE) setMethodS3("sampleCNs", "AbstractCBS", function(fit, size=NULL, ...) { data <- extractCNs(fit, ...) if (!is.null(size)) { sizes <- getSegmentSizes(fit, ...) .stop_if_not(length(sizes) == nrow(data)) idxs <- sample(nrow(data), size=size, replace=TRUE, prob=sizes) data <- data[idxs,,drop=FALSE] } data }) setMethodS3("updateMeans", "AbstractCBS", abstract=TRUE, protected=TRUE) setMethodS3("getMeanEstimators", "AbstractCBS", function(fit, which=NULL, default=mean, ...) { estList <- fit$params$meanEstimators if (is.null(estList)) { estList <- list() } if (is.null(which)) which <- names(estList) for (key in which) { fcn <- estList[[key]] if (is.null(fcn)) { fcn <- default } else if (is.character(fcn)) { fcn <- get(fcn, mode="function") } estList[[key]] <- fcn } estList }, protected=TRUE) setMethodS3("setMeanEstimators", "AbstractCBS", function(fit, ...) { estList <- fit$params$meanEstimators if (is.null(estList)) { estList <- list() } args <- list(...) if (length(args) == 0L) { return(invisible(fit)) } keys <- names(args) if (is.null(keys)) { stop("Estimators arguments must be named.") } for (key in keys) { fcn <- args[[key]] if (is.function(fcn)) { } else if (is.character(fcn)) { if (!exists(fcn, mode="function")) { stop(sprintf("No such '%s' estimator function: %s", key, fcn)) } } else { stop(sprintf("Estimator argument '%s' must be a function or character string: %s", key, mode(fcn))) } estList[[key]] <- fcn } fit$params$meanEstimators <- estList invisible(fit) }, protected=TRUE) setMethodS3("resegment", "AbstractCBS", abstract=TRUE, protected=TRUE) setMethodS3("getChromosomeRanges", "AbstractCBS", abstract=TRUE, protected=TRUE) setMethodS3("getChromosomeOffsets", "AbstractCBS", function(fit, resolution=1e6, ...) { if (!is.null(resolution)) { resolution <- Arguments$getDouble(resolution, range=c(1,Inf)) } data <- getChromosomeRanges(fit, ...) splits <- data[,"start"] + data[,"length"] if (!is.null(resolution)) { splits <- ceiling(splits / resolution) splits <- resolution * splits } offsets <- c(0L, cumsum(splits)) names(offsets) <- c(rownames(data), NA) offsets }, protected=TRUE) setMethodS3("ploidy", "AbstractCBS", function(fit, ...) { ploidy <- fit$params$ploidy if (is.null(ploidy)) ploidy <- 2L ploidy }) setMethodS3("ploidy<-", "AbstractCBS", function(fit, value) { fit <- setPloidy(fit, ploidy=value, update=TRUE) invisible(fit) }) "ploidy<-" <- function(fit, value) { UseMethod("ploidy<-") } setMethodS3("setPloidy", "AbstractCBS", function(fit, ploidy=2L, update=TRUE, ...) { ploidy <- Arguments$getInteger(ploidy, range=c(1,Inf)) if (update) { oldPloidy <- ploidy(fit) scale <- ploidy / oldPloidy if (scale != 1) { fit <- adjustPloidyScale(fit, scale=scale, ...) } } fit$params$ploidy <- ploidy invisible(fit) }, protected=TRUE) setMethodS3("adjustPloidyScale", "AbstractCBS", abstract=TRUE) setMethodS3("normalizeTotalCNs", "AbstractCBS", abstract=TRUE)
batch <- function(config = list()) { paws.compute::batch(config) } ec2 <- function(config = list()) { paws.compute::ec2(config) } ec2instanceconnect <- function(config = list()) { paws.compute::ec2instanceconnect(config) } ecr <- function(config = list()) { paws.compute::ecr(config) } ecs <- function(config = list()) { paws.compute::ecs(config) } eks <- function(config = list()) { paws.compute::eks(config) } elasticbeanstalk <- function(config = list()) { paws.compute::elasticbeanstalk(config) } lambda <- function(config = list()) { paws.compute::lambda(config) } lightsail <- function(config = list()) { paws.compute::lightsail(config) } serverlessapplicationrepository <- function(config = list()) { paws.compute::serverlessapplicationrepository(config) } backup <- function(config = list()) { paws.storage::backup(config) } dlm <- function(config = list()) { paws.storage::dlm(config) } efs <- function(config = list()) { paws.storage::efs(config) } fsx <- function(config = list()) { paws.storage::fsx(config) } glacier <- function(config = list()) { paws.storage::glacier(config) } s3 <- function(config = list()) { paws.storage::s3(config) } s3control <- function(config = list()) { paws.storage::s3control(config) } storagegateway <- function(config = list()) { paws.storage::storagegateway(config) } dax <- function(config = list()) { paws.database::dax(config) } docdb <- function(config = list()) { paws.database::docdb(config) } dynamodb <- function(config = list()) { paws.database::dynamodb(config) } dynamodbstreams <- function(config = list()) { paws.database::dynamodbstreams(config) } elasticache <- function(config = list()) { paws.database::elasticache(config) } neptune <- function(config = list()) { paws.database::neptune(config) } rds <- function(config = list()) { paws.database::rds(config) } rdsdataservice <- function(config = list()) { paws.database::rdsdataservice(config) } redshift <- function(config = list()) { paws.database::redshift(config) } simpledb <- function(config = list()) { paws.database::simpledb(config) } apigateway <- function(config = list()) { paws.networking::apigateway(config) } apigatewaymanagementapi <- function(config = list()) { paws.networking::apigatewaymanagementapi(config) } apigatewayv2 <- function(config = list()) { paws.networking::apigatewayv2(config) } appmesh <- function(config = list()) { paws.networking::appmesh(config) } cloudfront <- function(config = list()) { paws.networking::cloudfront(config) } directconnect <- function(config = list()) { paws.networking::directconnect(config) } elb <- function(config = list()) { paws.networking::elb(config) } elbv2 <- function(config = list()) { paws.networking::elbv2(config) } globalaccelerator <- function(config = list()) { paws.networking::globalaccelerator(config) } route53 <- function(config = list()) { paws.networking::route53(config) } route53domains <- function(config = list()) { paws.networking::route53domains(config) } route53resolver <- function(config = list()) { paws.networking::route53resolver(config) } servicediscovery <- function(config = list()) { paws.networking::servicediscovery(config) } cloud9 <- function(config = list()) { paws.developer.tools::cloud9(config) } codebuild <- function(config = list()) { paws.developer.tools::codebuild(config) } codecommit <- function(config = list()) { paws.developer.tools::codecommit(config) } codedeploy <- function(config = list()) { paws.developer.tools::codedeploy(config) } codepipeline <- function(config = list()) { paws.developer.tools::codepipeline(config) } codestar <- function(config = list()) { paws.developer.tools::codestar(config) } xray <- function(config = list()) { paws.developer.tools::xray(config) } applicationautoscaling <- function(config = list()) { paws.management::applicationautoscaling(config) } applicationinsights <- function(config = list()) { paws.management::applicationinsights(config) } autoscaling <- function(config = list()) { paws.management::autoscaling(config) } autoscalingplans <- function(config = list()) { paws.management::autoscalingplans(config) } cloudformation <- function(config = list()) { paws.management::cloudformation(config) } cloudtrail <- function(config = list()) { paws.management::cloudtrail(config) } cloudwatch <- function(config = list()) { paws.management::cloudwatch(config) } cloudwatchevents <- function(config = list()) { paws.management::cloudwatchevents(config) } cloudwatchlogs <- function(config = list()) { paws.management::cloudwatchlogs(config) } configservice <- function(config = list()) { paws.management::configservice(config) } health <- function(config = list()) { paws.management::health(config) } licensemanager <- function(config = list()) { paws.management::licensemanager(config) } opsworks <- function(config = list()) { paws.management::opsworks(config) } opsworkscm <- function(config = list()) { paws.management::opsworkscm(config) } organizations <- function(config = list()) { paws.management::organizations(config) } pi <- function(config = list()) { paws.management::pi(config) } resourcegroups <- function(config = list()) { paws.management::resourcegroups(config) } resourcegroupstaggingapi <- function(config = list()) { paws.management::resourcegroupstaggingapi(config) } servicecatalog <- function(config = list()) { paws.management::servicecatalog(config) } servicequotas <- function(config = list()) { paws.management::servicequotas(config) } ssm <- function(config = list()) { paws.management::ssm(config) } support <- function(config = list()) { paws.management::support(config) } comprehend <- function(config = list()) { paws.machine.learning::comprehend(config) } comprehendmedical <- function(config = list()) { paws.machine.learning::comprehendmedical(config) } lexmodelbuildingservice <- function(config = list()) { paws.machine.learning::lexmodelbuildingservice(config) } lexruntimeservice <- function(config = list()) { paws.machine.learning::lexruntimeservice(config) } machinelearning <- function(config = list()) { paws.machine.learning::machinelearning(config) } personalize <- function(config = list()) { paws.machine.learning::personalize(config) } personalizeevents <- function(config = list()) { paws.machine.learning::personalizeevents(config) } personalizeruntime <- function(config = list()) { paws.machine.learning::personalizeruntime(config) } polly <- function(config = list()) { paws.machine.learning::polly(config) } rekognition <- function(config = list()) { paws.machine.learning::rekognition(config) } sagemaker <- function(config = list()) { paws.machine.learning::sagemaker(config) } sagemakerruntime <- function(config = list()) { paws.machine.learning::sagemakerruntime(config) } textract <- function(config = list()) { paws.machine.learning::textract(config) } transcribeservice <- function(config = list()) { paws.machine.learning::transcribeservice(config) } translate <- function(config = list()) { paws.machine.learning::translate(config) } athena <- function(config = list()) { paws.analytics::athena(config) } cloudsearch <- function(config = list()) { paws.analytics::cloudsearch(config) } cloudsearchdomain <- function(config = list()) { paws.analytics::cloudsearchdomain(config) } datapipeline <- function(config = list()) { paws.analytics::datapipeline(config) } elasticsearchservice <- function(config = list()) { paws.analytics::elasticsearchservice(config) } emr <- function(config = list()) { paws.analytics::emr(config) } firehose <- function(config = list()) { paws.analytics::firehose(config) } glue <- function(config = list()) { paws.analytics::glue(config) } kafka <- function(config = list()) { paws.analytics::kafka(config) } kinesis <- function(config = list()) { paws.analytics::kinesis(config) } kinesisanalytics <- function(config = list()) { paws.analytics::kinesisanalytics(config) } kinesisanalyticsv2 <- function(config = list()) { paws.analytics::kinesisanalyticsv2(config) } mturk <- function(config = list()) { paws.analytics::mturk(config) } quicksight <- function(config = list()) { paws.analytics::quicksight(config) } acm <- function(config = list()) { paws.security.identity::acm(config) } acmpca <- function(config = list()) { paws.security.identity::acmpca(config) } clouddirectory <- function(config = list()) { paws.security.identity::clouddirectory(config) } cloudhsm <- function(config = list()) { paws.security.identity::cloudhsm(config) } cloudhsmv2 <- function(config = list()) { paws.security.identity::cloudhsmv2(config) } cognitoidentity <- function(config = list()) { paws.security.identity::cognitoidentity(config) } cognitoidentityprovider <- function(config = list()) { paws.security.identity::cognitoidentityprovider(config) } cognitosync <- function(config = list()) { paws.security.identity::cognitosync(config) } directoryservice <- function(config = list()) { paws.security.identity::directoryservice(config) } fms <- function(config = list()) { paws.security.identity::fms(config) } guardduty <- function(config = list()) { paws.security.identity::guardduty(config) } iam <- function(config = list()) { paws.security.identity::iam(config) } inspector <- function(config = list()) { paws.security.identity::inspector(config) } kms <- function(config = list()) { paws.security.identity::kms(config) } macie <- function(config = list()) { paws.security.identity::macie(config) } ram <- function(config = list()) { paws.security.identity::ram(config) } secretsmanager <- function(config = list()) { paws.security.identity::secretsmanager(config) } securityhub <- function(config = list()) { paws.security.identity::securityhub(config) } shield <- function(config = list()) { paws.security.identity::shield(config) } sts <- function(config = list()) { paws.security.identity::sts(config) } sso <- function(config = list()) { paws.security.identity::sso(config) } waf <- function(config = list()) { paws.security.identity::waf(config) } wafregional <- function(config = list()) { paws.security.identity::wafregional(config) } eventbridge <- function(config = list()) { paws.application.integration::eventbridge(config) } mq <- function(config = list()) { paws.application.integration::mq(config) } sfn <- function(config = list()) { paws.application.integration::sfn(config) } sns <- function(config = list()) { paws.application.integration::sns(config) } sqs <- function(config = list()) { paws.application.integration::sqs(config) } swf <- function(config = list()) { paws.application.integration::swf(config) } budgets <- function(config = list()) { paws.cost.management::budgets(config) } costandusagereportservice <- function(config = list()) { paws.cost.management::costandusagereportservice(config) } costexplorer <- function(config = list()) { paws.cost.management::costexplorer(config) } marketplacecommerceanalytics <- function(config = list()) { paws.cost.management::marketplacecommerceanalytics(config) } marketplaceentitlementservice <- function(config = list()) { paws.cost.management::marketplaceentitlementservice(config) } marketplacemetering <- function(config = list()) { paws.cost.management::marketplacemetering(config) } pricing <- function(config = list()) { paws.cost.management::pricing(config) } connect <- function(config = list()) { paws.customer.engagement::connect(config) } pinpoint <- function(config = list()) { paws.customer.engagement::pinpoint(config) } pinpointemail <- function(config = list()) { paws.customer.engagement::pinpointemail(config) } pinpointsmsvoice <- function(config = list()) { paws.customer.engagement::pinpointsmsvoice(config) } ses <- function(config = list()) { paws.customer.engagement::ses(config) } appstream <- function(config = list()) { paws.end.user.computing::appstream(config) } workdocs <- function(config = list()) { paws.end.user.computing::workdocs(config) } worklink <- function(config = list()) { paws.end.user.computing::worklink(config) } workspaces <- function(config = list()) { paws.end.user.computing::workspaces(config) }
xsplineTangent.s1neg.s2neg.A0.A3.y <- function(px0, px1, px2, px3, py0, py1, py2, py3, s1, s2, t) { ((((-t) * ((-t) * ((-t) * (-t) * (-s1) - ((-t) + (-t)) * (-2 * (-s1) - (-t) * (-s1))) - (2 * (-s1) + (-t) * (-t) * (-2 * (-s1) - (-t) * (-s1)))) - ((-s1) + (-t) * (2 * (-s1) + (-t) * (-t) * (-2 * (-s1) - (-t) * (-s1))))) * py0 - ((1 - t) * ((1 - t) * ((1 - t) * ((1 - t) * (4 - 5 * (-s2)) + (14 * (-s2) - 11 + (1 - t) * (4 - 5 * (-s2)))) + (8 - 12 * (-s2) + (1 - t) * (14 * (-s2) - 11 + (1 - t) * (4 - 5 * (-s2))))) + (2 * (-s2) + (1 - t) * (8 - 12 * (-s2) + (1 - t) * (14 * (-s2) - 11 + (1 - t) * (4 - 5 * (-s2)))))) + ((-s2) + (1 - t) * (2 * (-s2) + (1 - t) * (8 - 12 * (-s2) + (1 - t) * (14 * (-s2) - 11 + (1 - t) * (4 - 5 * (-s2))))))) * py1 + (((-s1) + t * (2 * (-s1) + t * (8 - 12 * (-s1) + t * (14 * (-s1) - 11 + t * (4 - 5 * (-s1)))))) + t * ((2 * (-s1) + t * (8 - 12 * (-s1) + t * (14 * (-s1) - 11 + t * (4 - 5 * (-s1))))) + t * ((8 - 12 * (-s1) + t * (14 * (-s1) - 11 + t * (4 - 5 * (-s1)))) + t * ((14 * (-s1) - 11 + t * (4 - 5 * (-s1))) + t * (4 - 5 * (-s1)))))) * py2 + (((-s2) + (t - 1) * (2 * (-s2) + (t - 1) * (t - 1) * (-2 * (-s2) - (t - 1) * (-s2)))) + (t - 1) * ((2 * (-s2) + (t - 1) * (t - 1) * (-2 * (-s2) - (t - 1) * (-s2))) + (t - 1) * (((t - 1) + (t - 1)) * (-2 * (-s2) - (t - 1) * (-s2)) - (t - 1) * (t - 1) * (-s2)))) * py3)/((-t) * ((-s1) + (-t) * (2 * (-s1) + (-t) * (-t) * (-2 * (-s1) - (-t) * (-s1)))) + (1 - t) * ((-s2) + (1 - t) * (2 * (-s2) + (1 - t) * (8 - 12 * (-s2) + (1 - t) * (14 * (-s2) - 11 + (1 - t) * (4 - 5 * (-s2)))))) + t * ((-s1) + t * (2 * (-s1) + t * (8 - 12 * (-s1) + t * (14 * (-s1) - 11 + t * (4 - 5 * (-s1)))))) + (t - 1) * ((-s2) + (t - 1) * (2 * (-s2) + (t - 1) * (t - 1) * (-2 * (-s2) - (t - 1) * (-s2))))) - ((-t) * ((-s1) + (-t) * (2 * (-s1) + (-t) * (-t) * (-2 * (-s1) - (-t) * (-s1)))) * py0 + (1 - t) * ((-s2) + (1 - t) * (2 * (-s2) + (1 - t) * (8 - 12 * (-s2) + (1 - t) * (14 * (-s2) - 11 + (1 - t) * (4 - 5 * (-s2)))))) * py1 + t * ((-s1) + t * (2 * (-s1) + t * (8 - 12 * (-s1) + t * (14 * (-s1) - 11 + t * (4 - 5 * (-s1)))))) * py2 + (t - 1) * ((-s2) + (t - 1) * (2 * (-s2) + (t - 1) * (t - 1) * (-2 * (-s2) - (t - 1) * (-s2)))) * py3) * ((-t) * ((-t) * ((-t) * (-t) * (-s1) - ((-t) + (-t)) * (-2 * (-s1) - (-t) * (-s1))) - (2 * (-s1) + (-t) * (-t) * (-2 * (-s1) - (-t) * (-s1)))) - ((-s1) + (-t) * (2 * (-s1) + (-t) * (-t) * (-2 * (-s1) - (-t) * (-s1)))) - ((1 - t) * ((1 - t) * ((1 - t) * ((1 - t) * (4 - 5 * (-s2)) + (14 * (-s2) - 11 + (1 - t) * (4 - 5 * (-s2)))) + (8 - 12 * (-s2) + (1 - t) * (14 * (-s2) - 11 + (1 - t) * (4 - 5 * (-s2))))) + (2 * (-s2) + (1 - t) * (8 - 12 * (-s2) + (1 - t) * (14 * (-s2) - 11 + (1 - t) * (4 - 5 * (-s2)))))) + ((-s2) + (1 - t) * (2 * (-s2) + (1 - t) * (8 - 12 * (-s2) + (1 - t) * (14 * (-s2) - 11 + (1 - t) * (4 - 5 * (-s2))))))) + (((-s1) + t * (2 * (-s1) + t * (8 - 12 * (-s1) + t * (14 * (-s1) - 11 + t * (4 - 5 * (-s1)))))) + t * ((2 * (-s1) + t * (8 - 12 * (-s1) + t * (14 * (-s1) - 11 + t * (4 - 5 * (-s1))))) + t * ((8 - 12 * (-s1) + t * (14 * (-s1) - 11 + t * (4 - 5 * (-s1)))) + t * ((14 * (-s1) - 11 + t * (4 - 5 * (-s1))) + t * (4 - 5 * (-s1)))))) + (((-s2) + (t - 1) * (2 * (-s2) + (t - 1) * (t - 1) * (-2 * (-s2) - (t - 1) * (-s2)))) + (t - 1) * ((2 * (-s2) + (t - 1) * (t - 1) * (-2 * (-s2) - (t - 1) * (-s2))) + (t - 1) * (((t - 1) + (t - 1)) * (-2 * (-s2) - (t - 1) * (-s2)) - (t - 1) * (t - 1) * (-s2)))))/((-t) * ((-s1) + (-t) * (2 * (-s1) + (-t) * (-t) * (-2 * (-s1) - (-t) * (-s1)))) + (1 - t) * ((-s2) + (1 - t) * (2 * (-s2) + (1 - t) * (8 - 12 * (-s2) + (1 - t) * (14 * (-s2) - 11 + (1 - t) * (4 - 5 * (-s2)))))) + t * ((-s1) + t * (2 * (-s1) + t * (8 - 12 * (-s1) + t * (14 * (-s1) - 11 + t * (4 - 5 * (-s1)))))) + (t - 1) * ((-s2) + (t - 1) * (2 * (-s2) + (t - 1) * (t - 1) * (-2 * (-s2) - (t - 1) * (-s2)))))^2) }
.dt_has_built_key <- "_has_built" dt_has_built_get <- function(data) { dt__get(data, .dt_has_built_key) } dt_has_built_set <- function(data, value) { dt__set(data, .dt_has_built_key, value) } dt_has_built_init <- function(data) { dt_has_built_set(data = data, value = FALSE) } dt_has_built <- function(data) { isTRUE(dt_has_built_get(data = data)) } dt_has_built_assert <- function(data) { if (!dt_has_built(data = data)) { stop("The build hasn't occurred; must call `build_data()` before retrieving.") } }
lisrelMatrix <- function(object, matrix, group = 1, type = "est") { if (!"lisrel"%in%class(object)) stop("Input must be a 'lisrel' object.") if (missing(matrix)) { matrix <- names(object$matrices)[sapply(lapply(object$matrices,sapply,length),function(x)all(x>0))] } else { matrix[grepl("lamb?d?a?.?x",matrix,ignore.case=TRUE)] <- "LX" matrix[grepl("lamb?d?a?.?y",matrix,ignore.case=TRUE)] <- "LY" matrix[grepl("phi",matrix,ignore.case=TRUE)] <- "PH" matrix[grepl("the?t?a?.?(y|eps)",matrix,ignore.case=TRUE)] <- "TE" matrix[grepl("the?t?a?.?(x|del)",matrix,ignore.case=TRUE)] <- "TD" matrix[grepl("gamm?a?",matrix,ignore.case=TRUE)] <- "GA" matrix[grepl("psi",matrix,ignore.case=TRUE)] <- "PS" matrix[grepl("bet?a?",matrix,ignore.case=TRUE)] <- "BE" matrix[grepl("tau.?x",matrix,ignore.case=TRUE)] <- "TX" matrix[grepl("tau.?y",matrix,ignore.case=TRUE)] <- "TY" matrix[grepl("alp?h?a?",matrix,ignore.case=TRUE)] <- "AL" matrix[grepl("kap?p?a?",matrix,ignore.case=TRUE)] <- "KA" if (any(grepl("lam?",matrix,ignore.case=TRUE))) { if (length(object$matrices$LX[[1]]) == 0 & length(object$matrices$LY[[1]]) > 0) { matrix[grepl("lam?",matrix,ignore.case=TRUE)] <- "LY" } else if (length(object$matrices$LX[[1]]) > 0 & length(object$matrices$LY[[1]])==0) { matrix[grepl("lam?",matrix,ignore.case=TRUE)] <- "LX" } else stop(paste("Matrix",grep("lam?",matrix,value=TRUE,ignore.case=TRUE),"could not be interpreted.")) } if (any(grepl("tau",matrix,ignore.case=TRUE))) { if (length(object$matrices$TX[[1]]) == 0 & length(object$matrices$TY[[1]]) > 0) { matrix[grepl("tau",matrix,ignore.case=TRUE)] <- "TY" } else if (length(object$matrices$TX[[1]]) > 0 & length(object$matrices$TY[[1]])==0) { matrix[grepl("tau",matrix,ignore.case=TRUE)] <- "TX" } else stop(paste("Matrix",grep("tau",matrix,value=TRUE,ignore.case=TRUE),"could not be interpreted.")) } if (any(grepl("thet?a?",matrix,ignore.case=TRUE))) { if (length(object$matrices$TD[[1]]) == 0 & length(object$matrices$TE[[1]]) > 0) { matrix[grepl("thet?a?",matrix,ignore.case=TRUE)] <- "TE" } else if (length(object$matrices$TD[[1]]) > 0 & length(object$matrices$TE[[1]])==0) { matrix[grepl("thet?a?",matrix,ignore.case=TRUE)] <- "TD" } else stop(paste("Matrix",grep("thet?a?",matrix,value=TRUE,ignore.case=TRUE),"could not be interpreted.")) } } Res <- lapply(object$matrices[matrix],function(x)x[[group]][[type]]) if (length(Res)==1) Res <- Res[[1]] return(Res) }
library(deSolve) LVmod0D <- function(Time, State, Pars) { with(as.list(c(State, Pars)), { IngestC <- rI * P * C GrowthP <- rG * P * (1 - P/K) MortC <- rM * C dP <- GrowthP - IngestC dC <- IngestC * AE - MortC return(list(c(dP, dC))) }) } pars <- c(rI = 0.2, rG = 1.0, rM = 0.2 , AE = 0.5, K = 10) yini <- c(P = 1, C = 2) times <- seq(0, 200, by = 1) nrun <- 1 print(system.time( for (i in 1:nrun) out <- lsoda(func = LVmod0D, y = yini, parms = pars, times = times) )/nrun) print(system.time( for (i in 1:nrun) out <- lsode(func = LVmod0D, y = yini, parms = pars, times = times) )/nrun) print(system.time( for (i in 1:nrun) out <- vode(func = LVmod0D, y = yini, parms = pars, times = times) )/nrun) print(system.time( for (i in 1:nrun) out <- daspk(func = LVmod0D, y = yini, parms = pars, times = times) )/nrun) print(system.time( for (i in 1:nrun) out <- lsodes(func = LVmod0D, y = yini, parms = pars, times = times) )/nrun) matplot(out[,"time"], out[,2:3], type = "l", xlab = "time", ylab = "Conc", main = "Lotka-Volterra", lwd = 2) legend("topright", c("prey", "predator"), col =1:2, lty = 1:2) rootfun <- function(Time, State, Pars) { dstate <- unlist(LVmod0D(Time, State, Pars)) root <- sum(abs(dstate)) - 1e-4 } print(system.time( for (i in 1:nrun) out <- lsodar(func = LVmod0D, y = yini, parms = pars, times = times, rootfun = rootfun) )/nrun) matplot(out[,"time"],out[,2:3], type = "l", xlab = "time", ylab = "Conc", main = "Lotka-Volterra with root", lwd = 2) LVmod1D <- function (time, state, parms, N, Da, dx) { with (as.list(parms), { P <- state[1:N] C <- state[-(1:N)] FluxP <- -Da * diff(c(P[1], P, P[N]))/dx FluxC <- -Da * diff(c(C[1], C, C[N]))/dx IngestC <- rI * P * C GrowthP <- rG * P * (1- P/K) MortC <- rM * C dP <- -diff(FluxP)/dx + GrowthP - IngestC dC <- -diff(FluxC)/dx + IngestC * AE - MortC return(list(c(dP, dC))) }) } R <- 20 N <- 1000 dx <- R/N Da <- 0.05 yini <- rep(0, 2*N) yini[500:501] <- yini[1500:1501] <- 10 times <-seq(0, 200, by = 1) print(system.time( for (i in 1:nrun) out <- ode.1D(y = yini, times = times, func = LVmod1D, parms = pars, nspec = 2, N = N, dx = dx, Da = Da) )/nrun) print(system.time( for (i in 1:nrun) out <- ode.1D(y = yini, times = times, func = LVmod1D, parms = pars, nspec = 2, N = N, dx = dx, Da = Da, method = "vode") )/nrun) print(system.time( for (i in 1:nrun) out <- ode.1D(y = yini, times = times, func = LVmod1D, parms = pars, nspec = 2, N = N, dx = dx, Da = Da, method = "lsoda") )/nrun) print(system.time( for (i in 1:nrun) out <- ode.1D(y = yini, times = times, func = LVmod1D, parms = pars, nspec = 2, N = N, dx = dx, Da = Da, method = "lsodes") )/nrun) image(out, which = 1, grid = seq(0, R, length=N), xlab = "Time, days", ylab = "Distance, m", main = "Prey density") LVmod2D <- function (time, state, parms, N, Da, dx, dy) { P <- matrix(nr = N, nc = N, state[1:NN]) C <- matrix(nr = N, nc = N, state[-(1:NN)]) with (as.list(parms), { dP <- rG*P *(1 - P/K) - rI*P*C dC <- rI*P*C*AE - rM*C zero <- numeric(N) FluxP <- rbind(zero, -Da*(P[-1,] - P[-N,])/dx, zero) FluxC <- rbind(zero, -Da*(C[-1,] - C[-N,])/dx, zero) dP <- dP - (FluxP[-1,] - FluxP[-(N+1),])/dx dC <- dC - (FluxC[-1,] - FluxC[-(N+1),])/dx FluxP <- cbind(zero, -Da*(P[,-1] - P[,-N])/dy, zero) FluxC <- cbind(zero, -Da*(C[,-1] - C[,-N])/dy, zero) dP <- dP - (FluxP[,-1] - FluxP[,-(N+1)])/dy dC <- dC - (FluxC[,-1] - FluxC[,-(N+1)])/dy return(list(c(as.vector(dP), as.vector(dC)))) }) } R <- 20 N <- 50 dx <- R/N dy <- R/N Da <- 0.05 NN <- N*N yini <- rep(0, 2*N*N) cc <- c((NN/2):(NN/2+1)+N/2, (NN/2):(NN/2+1)-N/2) yini[cc] <- yini[NN+cc] <- 10 times <- seq(0, 200, by = 1) print(system.time( for (i in 1:nrun) out <- ode.2D(y = yini, times = times, func = LVmod2D, parms = pars, ynames = FALSE, dimens = c(N, N), N = N, dx = dx, dy = dy, Da = Da, lrw = 440000) )/nrun) Col<- colorRampPalette(c(" " par(mfrow=c(2,2)) par(oma=c(0,0,2,0)) xx <- seq(0, R, dx) yy <- seq(0, R, dy) image(x = xx, y = yy, z = matrix(nr = N, nc = N, out[1,-1]), zlim = c(0,10), col = Col(100), main = "initial", xlab = "x", ylab = "y") image(x = xx, y = yy, z = matrix(nr = N, nc = N, out[21,-1]), zlim = c(0,10), col = Col(100), main = "20 days", xlab = "x", ylab = "y") image(x = xx, y = yy, z = matrix(nr = N, nc = N, out[31,-1]), zlim = c(0,10), col = Col(100), main = "30 days", xlab = "x", ylab = "y") image(x = xx, y = yy, z = matrix(nr = N, nc = N, out[41,-1]), zlim = c(0,10), col = Col(100), main = "40 days", xlab = "x", ylab = "y") mtext(side = 3, outer = TRUE, cex = 1.25, "Lotka-Volterra Prey concentration on 2-D grid") Res_DAE <- function (t, y, yprime, pars, K) { with (as.list(c(y, yprime, pars)), { res1 <- -dD - dA + prod res2 <- -dB + dA - r*B eq <- K*D - A*B return(list(c(res1, res2, eq), CONC = A + B + D)) }) } times <- seq(0, 100, by = 2) pars <- c(r = 1, prod = 0.1) K <- 1 yini <- c(A = 2, B = 3, D = 2*3/K) dyini <- c(dA = 0, dB = 0, dD = 0) DAE <- daspk(y = yini, dy = dyini, times = times, res = Res_DAE, parms = pars, atol = 1e-10, rtol = 1e-10, K = 1) plot(DAE, main = c(paste("[",colnames(DAE)[2:4],"]"),"total conc"), xlab = "time", lwd = 2, ylab = "conc", type = "l") mtext(outer=TRUE, side=3, "DAE chemical model",cex=1.25)
cpCommunitySizeDistribution <- function(list.of.communities, color.line = " test.power.law = FALSE){ if (length(list.of.communities) == 0) { stop("No communities. Thus, no size distribution is plotted.") } if (length(list.of.communities) > 0) { size_communities <- c() for (i in 1:length(list.of.communities)) { size_communities[i] <- length(list.of.communities[[i]]) } size_freq <- as.data.frame(table(size_communities)) names(size_freq) <- c("size","frequency") size_freq[, c(1:2)] <- lapply(size_freq[, c(1:2)], as.character) size_freq[, c(1:2)] <- lapply(size_freq[, c(1:2)], as.numeric) graphics::plot(1,type='n',xlim=c(1,max(size_freq$size)),ylim=c(0,max(size_freq$frequency)), xlab='Community Size', ylab='Frequency', cex.lab = 1.5, cex.axis = 1.5) graphics::grid(col = "lightgray", lty = "solid") graphics::points(x = size_freq$size, y = size_freq$frequency, col = color.line, pch = 16, cex = 1.5) graphics::lines(x = size_freq$size, y = size_freq$frequency, col = color.line, lwd = 3) if (test.power.law == FALSE) { invisible(list(size.distribution = size_freq)) } else { size_vector <- rep(size_freq$size, size_freq$frequency) fit_pl <- igraph::fit_power_law(size_vector, xmin = min(size_vector), implementation = "plfit") invisible(list(size.distribution = size_freq, fit.power.law = fit_pl)) } } }
lav_mvnorm_cluster_implied22l <- function(Lp = NULL, implied = NULL, Mu.W = NULL, Mu.B = NULL, Sigma.W = NULL, Sigma.B = NULL) { if(!is.null(implied)) { Sigma.W <- implied$cov[[1]] Mu.W <- implied$mean[[1]] Sigma.B <- implied$cov[[2]] Mu.B <- implied$mean[[2]] } between.idx <- Lp$between.idx[[2]] within.idx <- Lp$within.idx[[2]] both.idx <- Lp$both.idx[[2]] ov.idx <- Lp$ov.idx p.tilde <- length( unique(c(ov.idx[[1]], ov.idx[[2]])) ) Sigma.W.tilde <- matrix(0, p.tilde, p.tilde) Sigma.W.tilde[ ov.idx[[1]], ov.idx[[1]] ] <- Sigma.W Sigma.B.tilde <- matrix(0, p.tilde, p.tilde) Sigma.B.tilde[ ov.idx[[2]], ov.idx[[2]] ] <- Sigma.B Mu.W.tilde <- numeric( p.tilde ) Mu.W.tilde[ ov.idx[[1]] ] <- Mu.W Mu.B.tilde <- numeric( p.tilde ) Mu.B.tilde[ ov.idx[[2]] ] <- Mu.B Mu.WB.tilde <- numeric( p.tilde ) Mu.WB.tilde[ within.idx ] <- Mu.W.tilde[ within.idx ] Mu.WB.tilde[ both.idx ] <- ( Mu.B.tilde[ both.idx ] + Mu.W.tilde[ both.idx ] ) if(length(within.idx) > 0L) { Mu.B.tilde[within.idx] <- 0 } if(length(between.idx) > 0L) { mu.z <- Mu.B.tilde[ between.idx ] mu.y <- Mu.WB.tilde[-between.idx ] mu.w <- Mu.W.tilde[ -between.idx ] mu.b <- Mu.B.tilde[ -between.idx ] sigma.zz <- Sigma.B.tilde[ between.idx, between.idx, drop = FALSE] sigma.yz <- Sigma.B.tilde[-between.idx, between.idx, drop = FALSE] sigma.b <- Sigma.B.tilde[-between.idx,-between.idx, drop = FALSE] sigma.w <- Sigma.W.tilde[-between.idx,-between.idx, drop = FALSE] } else { mu.z <- numeric(0L) mu.y <- Mu.WB.tilde mu.w <- Mu.W.tilde mu.b <- Mu.B.tilde sigma.zz <- matrix(0, 0L, 0L) sigma.yz <- matrix(0, nrow(Sigma.B.tilde), 0L) sigma.b <- Sigma.B.tilde sigma.w <- Sigma.W.tilde } list(sigma.w = sigma.w, sigma.b = sigma.b, sigma.zz = sigma.zz, sigma.yz = sigma.yz, mu.z = mu.z, mu.y = mu.y, mu.w = mu.w, mu.b = mu.b) } lav_mvnorm_cluster_2l2implied <- function(Lp, sigma.w = NULL, sigma.b = NULL, sigma.zz = NULL, sigma.yz = NULL, mu.z = NULL, mu.y = NULL, mu.w = NULL, mu.b = NULL) { between.idx <- Lp$between.idx[[2]] within.idx <- Lp$within.idx[[2]] ov.idx <- Lp$ov.idx p.tilde <- length( unique(c(ov.idx[[1]], ov.idx[[2]])) ) if(!is.null(mu.y)) { mu.b <- mu.y mu.w.tilde <- numeric( p.tilde ) mu.w.tilde[ ov.idx[[1]] ] <- mu.y mu.w <- mu.w.tilde[ ov.idx[[1]] ] } Mu.W.tilde <- numeric( p.tilde ) Mu.W.tilde[ ov.idx[[1]] ] <- mu.w Mu.W <- Mu.W.tilde[ ov.idx[[1]] ] Mu.B.tilde <- numeric(p.tilde) Mu.B.tilde[ ov.idx[[1]] ] <- mu.b Mu.B.tilde[ between.idx ] <- mu.z if(length(within.idx) > 0) { Mu.B.tilde[within.idx] <- 0 } Mu.B <- Mu.B.tilde[ ov.idx[[2]] ] Sigma.W <- sigma.w Sigma.B.tilde <- matrix(0, p.tilde, p.tilde) Sigma.B.tilde[ ov.idx[[1]], ov.idx[[1]] ] <- sigma.b Sigma.B.tilde[ ov.idx[[1]], between.idx ] <- sigma.yz Sigma.B.tilde[ between.idx, ov.idx[[1]] ] <- t(sigma.yz) Sigma.B.tilde[ between.idx, between.idx ] <- sigma.zz Sigma.B <- Sigma.B.tilde[ ov.idx[[2]], ov.idx[[2]], drop = FALSE ] list(Mu.W = Mu.W, Mu.B = Mu.B, Sigma.W = Sigma.W, Sigma.B = Sigma.B) } lav_mvnorm_cluster_loglik_samplestats_2l <- function(YLp = NULL, Lp = NULL, Mu.W = NULL, Sigma.W = NULL, Mu.B = NULL, Sigma.B = NULL, Sinv.method = "eigen", log2pi = FALSE, minus.two = TRUE) { out <- lav_mvnorm_cluster_implied22l(Lp = Lp, Mu.W = Mu.W, Mu.B = Mu.B, Sigma.W = Sigma.W, Sigma.B = Sigma.B) mu.y <- out$mu.y; mu.z <- out$mu.z sigma.w <- out$sigma.w; sigma.b <- out$sigma.b sigma.zz <- out$sigma.zz; sigma.yz <- out$sigma.yz nclusters <- Lp$nclusters[[2]] cluster.size <- Lp$cluster.size[[2]] between.idx <- Lp$between.idx[[2]] cluster.sizes <- Lp$cluster.sizes[[2]] ncluster.sizes <- Lp$ncluster.sizes[[2]] cluster.size.ns <- Lp$cluster.size.ns[[2]] if(length(between.idx) > 0L) { S.PW <- YLp[[2]]$Sigma.W[-between.idx, -between.idx, drop = FALSE] } else { S.PW <- YLp[[2]]$Sigma.W } cov.d <- YLp[[2]]$cov.d mean.d <- YLp[[2]]$mean.d sigma.w.inv <- lav_matrix_symmetric_inverse(S = sigma.w, logdet = TRUE, Sinv.method = Sinv.method) sigma.w.logdet <- attr(sigma.w.inv, "logdet") attr(sigma.w.inv, "logdet") <- NULL if(length(between.idx) > 0L) { sigma.zz.inv <- lav_matrix_symmetric_inverse(S = sigma.zz, logdet = TRUE, Sinv.method = Sinv.method) sigma.zz.logdet <- attr(sigma.zz.inv, "logdet") attr(sigma.zz.inv, "logdet") <- NULL sigma.yz.zi <- sigma.yz %*% sigma.zz.inv sigma.zi.zy <- t(sigma.yz.zi) sigma.b.z <- sigma.b - sigma.yz %*% sigma.zi.zy } else { sigma.zz.logdet <- 0 sigma.b.z <- sigma.b } L <- numeric(ncluster.sizes) B <- numeric(ncluster.sizes) for(clz in seq_len(ncluster.sizes)) { nj <- cluster.sizes[clz] Y2Yc <- (cov.d[[clz]] + tcrossprod(mean.d[[clz]] - c(mu.z, mu.y))) if(length(between.idx) > 0L) { b.idx <- seq_len(length(Lp$between.idx[[2]])) Y2Yc.zz <- Y2Yc[ b.idx, b.idx, drop = FALSE] Y2Yc.yz <- Y2Yc[-b.idx, b.idx, drop = FALSE] Y2Yc.yy <- Y2Yc[-b.idx,-b.idx, drop = FALSE] } else { Y2Yc.yy <- Y2Yc } sigma.j <- (nj * sigma.b.z) + sigma.w sigma.j.inv <- lav_matrix_symmetric_inverse(S = sigma.j, logdet = TRUE, Sinv.method = Sinv.method) sigma.j.logdet <- attr(sigma.j.inv, "logdet") attr(sigma.j.inv, "logdet") <- NULL if(is.na(sigma.j.logdet)) { } L[clz] <- (sigma.zz.logdet + sigma.j.logdet) if(length(between.idx) > 0L) { sigma.ji.yz.zi <- sigma.j.inv %*% sigma.yz.zi Vinv.11 <- sigma.zz.inv + nj*(sigma.zi.zy %*% sigma.ji.yz.zi) q.zz <- sum(Vinv.11 * Y2Yc.zz) q.yz <- - nj * sum(sigma.ji.yz.zi * Y2Yc.yz) } else { q.zz <- q.yz <- 0 } q.yyc <- -nj * sum(sigma.j.inv * Y2Yc.yy ) B[clz] <- q.zz + 2*q.yz - q.yyc } q.W <- sum(cluster.size - 1) * sum(sigma.w.inv * S.PW) L.W <- sum(cluster.size - 1) * sigma.w.logdet loglik <- sum(L * cluster.size.ns) + sum(B * cluster.size.ns) + q.W + L.W if(!minus.two) { loglik <- loglik / (-2) } if(log2pi) { LOG.2PI <- log(2 * pi) nWithin <- length(c(Lp$both.idx[[2]], Lp$within.idx[[2]])) nBetween <- length(Lp$between.idx[[2]]) P <- Lp$nclusters[[1]]*nWithin + Lp$nclusters[[2]]*nBetween constant <- -(P * LOG.2PI)/2 loglik <- loglik + constant } if(length(unlist(Lp$ov.x.idx)) > 0L && log2pi && !minus.two) { loglik <- loglik - YLp[[2]]$loglik.x } loglik } lav_mvnorm_cluster_dlogl_2l_samplestats <- function(YLp = NULL, Lp = NULL, Mu.W = NULL, Sigma.W = NULL, Mu.B = NULL, Sigma.B = NULL, return.list = FALSE, Sinv.method = "eigen") { out <- lav_mvnorm_cluster_implied22l(Lp = Lp, Mu.W = Mu.W, Mu.B = Mu.B, Sigma.W = Sigma.W, Sigma.B = Sigma.B) mu.y <- out$mu.y; mu.z <- out$mu.z sigma.w <- out$sigma.w; sigma.b <- out$sigma.b sigma.zz <- out$sigma.zz; sigma.yz <- out$sigma.yz nclusters <- Lp$nclusters[[2]] cluster.size <- Lp$cluster.size[[2]] cluster.sizes <- Lp$cluster.sizes[[2]] cluster.idx <- Lp$cluster.idx[[2]] between.idx <- Lp$between.idx[[2]] ncluster.sizes <- Lp$ncluster.sizes[[2]] cluster.size.ns <- Lp$cluster.size.ns[[2]] if(length(between.idx) > 0L) { S.PW <- YLp[[2]]$Sigma.W[-between.idx, -between.idx, drop = FALSE] } else { S.PW <- YLp[[2]]$Sigma.W } cov.d <- YLp[[2]]$cov.d mean.d <- YLp[[2]]$mean.d sigma.w.inv <- lav_matrix_symmetric_inverse(S = sigma.w, logdet = FALSE, Sinv.method = Sinv.method) G.muy <- matrix(0, ncluster.sizes, length(mu.y)) G.Sigma.w <- matrix(0, ncluster.sizes, length(lav_matrix_vech(sigma.w))) G.Sigma.b <- matrix(0, ncluster.sizes, length(lav_matrix_vech(sigma.b))) if(length(between.idx) > 0L) { G.muz <- matrix(0, ncluster.sizes, length(mu.z)) G.Sigma.zz <- matrix(0, ncluster.sizes, length(lav_matrix_vech(sigma.zz))) G.Sigma.yz <- matrix(0, ncluster.sizes, length(lav_matrix_vec(sigma.yz))) sigma.zz.inv <- lav_matrix_symmetric_inverse(S = sigma.zz, logdet = FALSE, Sinv.method = Sinv.method) sigma.yz.zi <- sigma.yz %*% sigma.zz.inv sigma.zi.zy <- t(sigma.yz.zi) sigma.b.z <- sigma.b - sigma.yz %*% sigma.zi.zy for(clz in seq_len(ncluster.sizes)) { nj <- cluster.sizes[clz] b.idx <- seq_len(length(Lp$between.idx[[2]])) zyc <- mean.d[[clz]] - c(mu.z, mu.y) yc <- zyc[-b.idx] zc <- zyc[ b.idx] Y2Yc <- (cov.d[[clz]] + tcrossprod(mean.d[[clz]] - c(mu.z, mu.y))) b.idx <- seq_len(length(Lp$between.idx[[2]])) Y2Yc.zz <- Y2Yc[ b.idx, b.idx, drop = FALSE] Y2Yc.yz <- Y2Yc[-b.idx, b.idx, drop = FALSE] Y2Yc.yy <- Y2Yc[-b.idx,-b.idx, drop = FALSE] sigma.j <- (nj * sigma.b.z) + sigma.w sigma.j.inv <- lav_matrix_symmetric_inverse(S = sigma.j, logdet = FALSE, Sinv.method = Sinv.method) sigma.ji.yz.zi <- sigma.j.inv %*% sigma.yz.zi sigma.zi.zy.ji <- t(sigma.ji.yz.zi) jYZj <- nj * ( sigma.j.inv %*% (sigma.yz.zi %*% Y2Yc.zz %*% t(sigma.yz.zi) - Y2Yc.yz %*% t(sigma.yz.zi) - t(Y2Yc.yz %*% t(sigma.yz.zi)) + Y2Yc.yy) %*% sigma.j.inv ) Z1 <- Y2Yc.zz %*% t(sigma.ji.yz.zi) %*% sigma.yz YZ1 <- t(Y2Yc.yz) %*% sigma.j.inv %*% sigma.yz G.muz[clz,] <- -2 * as.numeric( (sigma.zz.inv + nj*(sigma.zi.zy.ji %*% sigma.yz.zi)) %*% zc -nj*sigma.zi.zy.ji %*% yc) G.muy[clz,] <- 2*nj * as.numeric(zc %*% sigma.zi.zy.ji - yc %*% sigma.j.inv) g.sigma.w <- sigma.j.inv - jYZj tmp <- g.sigma.w*2; diag(tmp) <- diag(g.sigma.w) G.Sigma.w[clz,] <- lav_matrix_vech(tmp) g.sigma.b <- nj * (sigma.j.inv - jYZj) tmp <- g.sigma.b*2; diag(tmp) <- diag(g.sigma.b) G.Sigma.b[clz,] <- lav_matrix_vech(tmp) g.sigma.zz <- ( sigma.zz.inv + nj * sigma.zz.inv %*% ( t(sigma.yz) %*% (sigma.j.inv - jYZj) %*% sigma.yz -(1/nj * Y2Yc.zz + t(Z1) + Z1 - t(YZ1) - YZ1) ) %*% sigma.zz.inv ) tmp <- g.sigma.zz*2; diag(tmp) <- diag(g.sigma.zz) G.Sigma.zz[clz,] <- lav_matrix_vech(tmp) g.sigma.yz <- 2 * nj * ( (sigma.j.inv %*% (sigma.yz.zi %*% Y2Yc.zz - sigma.yz - Y2Yc.yz) + jYZj %*% sigma.yz) %*% sigma.zz.inv ) G.Sigma.yz[clz,] <- lav_matrix_vec(g.sigma.yz) } d.mu.y <- colSums(G.muy * cluster.size.ns) d.sigma.w1 <- lav_matrix_vech_reverse(colSums(G.Sigma.w * cluster.size.ns)) d.sigma.b <- lav_matrix_vech_reverse(colSums(G.Sigma.b * cluster.size.ns)) d.mu.z <- colSums(G.muz * cluster.size.ns) d.sigma.zz <- lav_matrix_vech_reverse(colSums(G.Sigma.zz * cluster.size.ns)) d.sigma.yz <- matrix(colSums(G.Sigma.yz * cluster.size.ns), nrow(sigma.yz), ncol(sigma.yz)) } else { for(clz in seq_len(ncluster.sizes)) { nj <- cluster.sizes[clz] yc <- mean.d[[clz]] - mu.y Y2Yc.yy <- (cov.d[[clz]] + tcrossprod(mean.d[[clz]] - mu.y)) sigma.j <- (nj * sigma.b) + sigma.w sigma.j.inv <- lav_matrix_symmetric_inverse(S = sigma.j, logdet = FALSE, Sinv.method = Sinv.method) jYYj <- nj * sigma.j.inv %*% Y2Yc.yy %*% sigma.j.inv G.muy[clz,] <- -2*nj * as.numeric(yc %*% sigma.j.inv) g.sigma.w <- sigma.j.inv - jYYj tmp <- g.sigma.w*2; diag(tmp) <- diag(g.sigma.w) G.Sigma.w[clz,] <- lav_matrix_vech(tmp) g.sigma.b <- nj * (sigma.j.inv - jYYj) tmp <- g.sigma.b*2; diag(tmp) <- diag(g.sigma.b) G.Sigma.b[clz,] <- lav_matrix_vech(tmp) } d.mu.y <- colSums(G.muy * cluster.size.ns) d.sigma.w1 <- lav_matrix_vech_reverse(colSums(G.Sigma.w * cluster.size.ns)) d.sigma.b <- lav_matrix_vech_reverse(colSums(G.Sigma.b * cluster.size.ns)) d.mu.z <- numeric(0L) d.sigma.zz <- matrix(0, 0L, 0L) d.sigma.yz <- matrix(0, 0L, 0L) } d.sigma.w2 <- (Lp$nclusters[[1]] - nclusters) * ( sigma.w.inv - sigma.w.inv %*% S.PW %*% sigma.w.inv ) tmp <- d.sigma.w2*2; diag(tmp) <- diag(d.sigma.w2) d.sigma.w2 <- tmp d.sigma.w <- d.sigma.w1 + d.sigma.w2 dout <- lav_mvnorm_cluster_2l2implied(Lp = Lp, sigma.w = d.sigma.w, sigma.b = d.sigma.b, sigma.yz = d.sigma.yz, sigma.zz = d.sigma.zz, mu.y = d.mu.y, mu.z = d.mu.z) if(return.list) { out <- dout } else { out <- c(dout$Mu.W, lav_matrix_vech(dout$Sigma.W), dout$Mu.B, lav_matrix_vech(dout$Sigma.B)) } out } lav_mvnorm_cluster_scores_2l <- function(Y1 = NULL, YLp = NULL, Lp = NULL, Mu.W = NULL, Sigma.W = NULL, Mu.B = NULL, Sigma.B = NULL, Sinv.method = "eigen") { out <- lav_mvnorm_cluster_implied22l(Lp = Lp, Mu.W = Mu.W, Mu.B = Mu.B, Sigma.W = Sigma.W, Sigma.B = Sigma.B) mu.y <- out$mu.y; mu.z <- out$mu.z sigma.w <- out$sigma.w; sigma.b <- out$sigma.b sigma.zz <- out$sigma.zz; sigma.yz <- out$sigma.yz nclusters <- Lp$nclusters[[2]] cluster.size <- Lp$cluster.size[[2]] cluster.idx <- Lp$cluster.idx[[2]] between.idx <- Lp$between.idx[[2]] if(length(between.idx) > 0L) { Y1w <- Y1[,-Lp$between.idx[[2]], drop = FALSE] } else { Y1w <- Y1 } Y1w.cm <- t( t(Y1w) - mu.y ) Y2 <- YLp[[2]]$Y2 mu.b <- numeric(ncol(Y2)) if(length(between.idx) > 0L) { mu.b[-Lp$between.idx[[2]]] <- mu.y mu.b[ Lp$between.idx[[2]]] <- mu.z } else { mu.b <- mu.y } Y2.cm <- t( t(Y2) - mu.b ) sigma.w.inv <- lav_matrix_symmetric_inverse(S = sigma.w, logdet = FALSE, Sinv.method = Sinv.method) G.muy <- matrix(0, nclusters, length(mu.y)) G.Sigma.w <- matrix(0, nclusters, length(lav_matrix_vech(sigma.w))) G.Sigma.b <- matrix(0, nclusters, length(lav_matrix_vech(sigma.b))) G.muz <- matrix(0, nclusters, length(mu.z)) G.Sigma.zz <- matrix(0, nclusters, length(lav_matrix_vech(sigma.zz))) G.Sigma.yz <- matrix(0, nclusters, length(lav_matrix_vec(sigma.yz))) if(length(between.idx) > 0L) { sigma.zz.inv <- lav_matrix_symmetric_inverse(S = sigma.zz, logdet = FALSE, Sinv.method = Sinv.method) sigma.yz.zi <- sigma.yz %*% sigma.zz.inv sigma.zi.zy <- t(sigma.yz.zi) sigma.b.z <- sigma.b - sigma.yz %*% sigma.zi.zy for(cl in seq_len(nclusters)) { nj <- cluster.size[cl] Y1m <- Y1w.cm[cluster.idx == cl,, drop = FALSE] yc <- Y2.cm[cl,-Lp$between.idx[[2]]] zc <- Y2.cm[cl, Lp$between.idx[[2]]] Y2Yc <- tcrossprod(Y2.cm[cl,]) Y2Yc.zz <- Y2Yc[Lp$between.idx[[2]], Lp$between.idx[[2]], drop = FALSE] Y2Yc.yz <- Y2Yc[-Lp$between.idx[[2]], Lp$between.idx[[2]], drop = FALSE] Y2Yc.yy <- Y2Yc[-Lp$between.idx[[2]], -Lp$between.idx[[2]], drop = FALSE] sigma.j <- (nj * sigma.b.z) + sigma.w sigma.j.inv <- lav_matrix_symmetric_inverse(S = sigma.j, logdet = FALSE, Sinv.method = Sinv.method) sigma.ji.yz.zi <- sigma.j.inv %*% sigma.yz.zi sigma.zi.zy.ji <- t(sigma.ji.yz.zi) jYZj <- nj * ( sigma.j.inv %*% (sigma.yz.zi %*% Y2Yc.zz %*% t(sigma.yz.zi) - Y2Yc.yz %*% t(sigma.yz.zi) - t(Y2Yc.yz %*% t(sigma.yz.zi)) + Y2Yc.yy) %*% sigma.j.inv ) Z1 <- Y2Yc.zz %*% t(sigma.ji.yz.zi) %*% sigma.yz YZ1 <- t(Y2Yc.yz) %*% sigma.j.inv %*% sigma.yz G.muz[cl,] <- -2 * as.numeric( (sigma.zz.inv + nj*(sigma.zi.zy.ji %*% sigma.yz.zi)) %*% zc -nj*sigma.zi.zy.ji %*% yc) G.muy[cl,] <- 2*nj * as.numeric(zc %*% sigma.zi.zy.ji - yc %*% sigma.j.inv) g.sigma.w <- ( (nj-1) * sigma.w.inv - sigma.w.inv %*% (crossprod(Y1m) - nj*Y2Yc.yy) %*% sigma.w.inv + sigma.j.inv - jYZj ) tmp <- g.sigma.w*2; diag(tmp) <- diag(g.sigma.w) G.Sigma.w[cl,] <- lav_matrix_vech(tmp) g.sigma.b <- nj * (sigma.j.inv - jYZj) tmp <- g.sigma.b*2; diag(tmp) <- diag(g.sigma.b) G.Sigma.b[cl,] <- lav_matrix_vech(tmp) g.sigma.zz <- ( sigma.zz.inv + nj * sigma.zz.inv %*% ( t(sigma.yz) %*% (sigma.j.inv - jYZj) %*% sigma.yz -(1/nj * Y2Yc.zz + t(Z1) + Z1 - t(YZ1) - YZ1) ) %*% sigma.zz.inv ) tmp <- g.sigma.zz*2; diag(tmp) <- diag(g.sigma.zz) G.Sigma.zz[cl,] <- lav_matrix_vech(tmp) g.sigma.yz <- 2 * nj * ( (sigma.j.inv %*% (sigma.yz.zi %*% Y2Yc.zz - sigma.yz - Y2Yc.yz) + jYZj %*% sigma.yz) %*% sigma.zz.inv ) G.Sigma.yz[cl,] <- lav_matrix_vec(g.sigma.yz) } } else { for(cl in seq_len(nclusters)) { nj <- cluster.size[cl] Y1m <- Y1w.cm[cluster.idx == cl,, drop = FALSE] yc <- Y2.cm[cl,] Y2Yc.yy <- tcrossprod(Y2.cm[cl,]) sigma.j <- (nj * sigma.b) + sigma.w sigma.j.inv <- lav_matrix_symmetric_inverse(S = sigma.j, logdet = FALSE, Sinv.method = Sinv.method) jYYj <- nj * sigma.j.inv %*% Y2Yc.yy %*% sigma.j.inv G.muy[cl,] <- -2*nj * as.numeric(yc %*% sigma.j.inv) g.sigma.w <- ( (nj-1) * sigma.w.inv - sigma.w.inv %*% (crossprod(Y1m) - nj*Y2Yc.yy) %*% sigma.w.inv + sigma.j.inv - jYYj ) tmp <- g.sigma.w*2; diag(tmp) <- diag(g.sigma.w) G.Sigma.w[cl,] <- lav_matrix_vech(tmp) g.sigma.b <- nj * (sigma.j.inv - jYYj) tmp <- g.sigma.b*2; diag(tmp) <- diag(g.sigma.b) G.Sigma.b[cl,] <- lav_matrix_vech(tmp) } } ov.idx <- Lp$ov.idx p.tilde <- length( unique(c(ov.idx[[1]], ov.idx[[2]])) ) Mu.W.tilde <- matrix(0, nclusters, p.tilde) Mu.W.tilde[, ov.idx[[1]] ] <- G.muy Mu.W.tilde[, Lp$both.idx[[2]] ] <- 0 Mu.W <- Mu.W.tilde[, ov.idx[[1]], drop = FALSE] Mu.B.tilde <- matrix(0, nclusters, p.tilde) Mu.B.tilde[, ov.idx[[1]] ] <- G.muy if(length(between.idx) > 0L) { Mu.B.tilde[, between.idx ] <- G.muz } Mu.B <- Mu.B.tilde[, ov.idx[[2]], drop = FALSE] Sigma.W <- G.Sigma.w if(length(between.idx) > 0L) { p.tilde.star <- p.tilde*(p.tilde+1)/2 B.tilde <- lav_matrix_vech_reverse(seq_len(p.tilde.star)) Sigma.B.tilde <- matrix(0, nclusters, p.tilde.star) col.idx <- lav_matrix_vech( B.tilde[ ov.idx[[1]], ov.idx[[1]], drop = FALSE ] ) Sigma.B.tilde[ , col.idx ] <- G.Sigma.b col.idx <- lav_matrix_vec( B.tilde[ ov.idx[[1]], between.idx, drop = FALSE ] ) Sigma.B.tilde[ , col.idx ] <- G.Sigma.yz col.idx <- lav_matrix_vech( B.tilde[ between.idx, between.idx, drop = FALSE ] ) Sigma.B.tilde[ , col.idx ] <- G.Sigma.zz col.idx <- lav_matrix_vech( B.tilde[ ov.idx[[2]], ov.idx[[2]], drop = FALSE ] ) Sigma.B <- Sigma.B.tilde[ , col.idx, drop = FALSE ] } else { p.tilde.star <- p.tilde*(p.tilde+1)/2 B.tilde <- lav_matrix_vech_reverse(seq_len(p.tilde.star)) Sigma.B.tilde <- matrix(0, nclusters, p.tilde.star) col.idx <- lav_matrix_vech( B.tilde[ ov.idx[[1]], ov.idx[[1]], drop = FALSE ] ) Sigma.B.tilde[ , col.idx ] <- G.Sigma.b col.idx <- lav_matrix_vech( B.tilde[ ov.idx[[2]], ov.idx[[2]], drop = FALSE ] ) Sigma.B <- Sigma.B.tilde[ , col.idx, drop = FALSE ] } SCORES <- cbind(Mu.W, Sigma.W, Mu.B, Sigma.B) SCORES } lav_mvnorm_cluster_information_firstorder <- function(Y1 = NULL, YLp = NULL, Lp = NULL, Mu.W = NULL, Sigma.W = NULL, Mu.B = NULL, Sigma.B = NULL, x.idx = NULL, divide.by.two = FALSE, Sinv.method = "eigen") { N <- NROW(Y1) SCORES <- lav_mvnorm_cluster_scores_2l(Y1 = Y1, YLp = YLp, Lp = Lp, Mu.W = Mu.W, Sigma.W = Sigma.W, Mu.B = Mu.B, Sigma.B = Sigma.B, Sinv.method = Sinv.method) if(divide.by.two) { SCORES <- SCORES / 2 } information <- crossprod(SCORES)/Lp$nclusters[[2]] if(length(x.idx) > 0L) { nw <- length(as.vector(Mu.W)) nw.star <- nw*(nw+1)/2 nb <- length(as.vector(Mu.B)) ov.idx <- Lp$ov.idx x.idx.w <- which(ov.idx[[1]] %in% x.idx) if(length(x.idx.w) > 0L) { xw.idx <- c(x.idx.w, nw + lav_matrix_vech_which_idx(n = nw, idx = x.idx.w)) } else { xw.idx <- integer(0L) } x.idx.b <- which(ov.idx[[2]] %in% x.idx) if(length(x.idx.b) > 0L) { xb.idx <- c(x.idx.b, nb + lav_matrix_vech_which_idx(n = nb, idx = x.idx.b)) } else { xb.idx <- integer(0L) } all.idx <- c(xw.idx, nw + nw.star + xb.idx) information[all.idx, ] <- 0 information[, all.idx] <- 0 } information } lav_mvnorm_cluster_information_expected <- function(Lp = NULL, Mu.W = NULL, Sigma.W = NULL, Mu.B = NULL, Sigma.B = NULL, x.idx = integer(0L), Sinv.method = "eigen") { out <- lav_mvnorm_cluster_implied22l(Lp = Lp, Mu.W = Mu.W, Mu.B = Mu.B, Sigma.W = Sigma.W, Sigma.B = Sigma.B) mu.y <- out$mu.y; mu.z <- out$mu.z sigma.w <- out$sigma.w; sigma.b <- out$sigma.b sigma.zz <- out$sigma.zz; sigma.yz <- out$sigma.yz ov.idx <- Lp$ov.idx nw <- length(ov.idx[[1]]) nb <- length(ov.idx[[2]]) p.tilde <- length( unique(c(ov.idx[[1]], ov.idx[[2]])) ) p.tilde.star <- p.tilde*(p.tilde+1)/2 npar <- p.tilde + p.tilde.star B.tilde <- lav_matrix_vech_reverse(seq_len(p.tilde.star)) w.idx <- lav_matrix_vech( B.tilde[ ov.idx[[1]], ov.idx[[1]], drop = FALSE] ) b.idx <- lav_matrix_vech( B.tilde[ ov.idx[[2]], ov.idx[[2]], drop = FALSE] ) Delta.W.tilde <- matrix(0, npar, npar) Delta.B.tilde <- matrix(0, npar, npar) Delta.W.tilde[c(ov.idx[[1]], w.idx + p.tilde), c(ov.idx[[1]], w.idx + p.tilde)] <- diag( nw + nw*(nw+1)/2 ) Delta.B.tilde[c(ov.idx[[2]], b.idx + p.tilde), c(ov.idx[[2]], b.idx + p.tilde)] <- diag( nb + nb*(nb+1)/2 ) Delta.W.tilde <- cbind(Delta.W.tilde, matrix(0, npar, npar)) Delta.B.tilde <- cbind(matrix(0, npar, npar), Delta.B.tilde) nobs <- Lp$nclusters[[1]] nclusters <- Lp$nclusters[[2]] cluster.size <- Lp$cluster.size[[2]] cluster.sizes <- Lp$cluster.sizes[[2]] ncluster.sizes <- Lp$ncluster.sizes[[2]] n.s <- Lp$cluster.size.ns[[2]] between.idx <- Lp$between.idx[[2]] information.j <- matrix(0, npar*2, npar*2) for(clz in seq_len(ncluster.sizes)) { nj <- cluster.sizes[clz] Delta.j <- Delta.B.tilde + 1/nj * Delta.W.tilde sigma.j <- sigma.w + nj * sigma.b if(length(between.idx) > 0L) { omega.j <- matrix(0, p.tilde, p.tilde) omega.j[-between.idx, -between.idx] <- 1/nj * sigma.j omega.j[-between.idx, between.idx] <- sigma.yz omega.j[ between.idx, -between.idx] <- t(sigma.yz) omega.j[ between.idx, between.idx] <- sigma.zz } else { omega.j <- 1/nj * sigma.j } omega.j.inv <- solve(omega.j) I11.j <- omega.j.inv I22.j <- 0.5 * lav_matrix_duplication_pre_post(omega.j.inv %x% omega.j.inv) I.j <- lav_matrix_bdiag(I11.j, I22.j) info.j <- t(Delta.j) %*% I.j %*% Delta.j information.j <- information.j + n.s[clz]*info.j } Sigma.W.inv <- lav_matrix_symmetric_inverse(S = Sigma.W, logdet = FALSE, Sinv.method = Sinv.method) Sigma.W.inv.tilde <- matrix(0, p.tilde, p.tilde) Sigma.W.inv.tilde[ ov.idx[[1]], ov.idx[[1]] ] <- Sigma.W.inv I11.w <- Sigma.W.inv.tilde I22.w <- 0.5 * lav_matrix_duplication_pre_post(Sigma.W.inv.tilde %x% Sigma.W.inv.tilde) I.w <- lav_matrix_bdiag(I11.w, I22.w) information.w <- (nobs - nclusters) * ( t(Delta.W.tilde) %*% I.w %*% Delta.W.tilde ) information.tilde <- 1/Lp$nclusters[[2]] * (information.w + information.j) information.tilde[Lp$both.idx[[2]],] <- 0 information.tilde[,Lp$both.idx[[2]]] <- 0 if(length(x.idx) > 0L) { xw.idx <- c(x.idx, p.tilde + lav_matrix_vech_which_idx(n = p.tilde, idx = x.idx)) xb.idx <- npar + xw.idx all.idx <- c(xw.idx, xb.idx) information.tilde[all.idx, ] <- 0 information.tilde[, all.idx] <- 0 } ok.idx <- c(ov.idx[[1]], w.idx + p.tilde, npar + ov.idx[[2]], npar + b.idx + p.tilde) information <- information.tilde[ok.idx, ok.idx] information } lav_mvnorm_cluster_information_expected_delta <- function(Lp = NULL, Delta = NULL, Mu.W = NULL, Sigma.W = NULL, Mu.B = NULL, Sigma.B = NULL, Sinv.method = "eigen") { out <- lav_mvnorm_cluster_implied22l(Lp = Lp, Mu.W = Mu.W, Mu.B = Mu.B, Sigma.W = Sigma.W, Sigma.B = Sigma.B) mu.y <- out$mu.y; mu.z <- out$mu.z sigma.w <- out$sigma.w; sigma.b <- out$sigma.b sigma.zz <- out$sigma.zz; sigma.yz <- out$sigma.yz npar <- NCOL(Delta) ov.idx <- Lp$ov.idx nw <- length(ov.idx[[1]]) nw.star <- nw*(nw+1)/2 nb <- length(ov.idx[[2]]) Delta.W <- Delta[1:(nw + nw.star),,drop = FALSE] Delta.B <- Delta[-(1:(nw + nw.star)),,drop = FALSE] p.tilde <- length( unique(c(ov.idx[[1]], ov.idx[[2]])) ) p.tilde.star <- p.tilde*(p.tilde+1)/2 Delta.W.tilde.Mu <- matrix(0, p.tilde, npar) Delta.W.tilde.Sigma <- matrix(0, p.tilde.star, npar) Delta.B.tilde.Mu <- matrix(0, p.tilde, npar) Delta.B.tilde.Sigma <- matrix(0, p.tilde.star, npar) Delta.W.tilde.Mu[ov.idx[[1]],] <- Delta.W[1:nw,] Delta.B.tilde.Mu[ov.idx[[2]],] <- Delta.B[1:nb,] Delta.B.tilde.Mu[ Lp$both.idx[[2]], ] <- ( Delta.B.tilde.Mu[ Lp$both.idx[[2]], ] + Delta.W.tilde.Mu[ Lp$both.idx[[2]], ] ) Delta.W.tilde.Mu[Lp$both.idx[[2]], ] <- 0 B.tilde <- lav_matrix_vech_reverse(seq_len(p.tilde.star)) w.idx <- lav_matrix_vech( B.tilde[ ov.idx[[1]], ov.idx[[1]], drop = FALSE] ) b.idx <- lav_matrix_vech( B.tilde[ ov.idx[[2]], ov.idx[[2]], drop = FALSE] ) Delta.W.tilde.Sigma[w.idx,] <- Delta.W[-(1:nw),] Delta.B.tilde.Sigma[b.idx,] <- Delta.B[-(1:nb),] Delta.W.tilde <- rbind(Delta.W.tilde.Mu, Delta.W.tilde.Sigma) Delta.B.tilde <- rbind(Delta.B.tilde.Mu, Delta.B.tilde.Sigma) nobs <- Lp$nclusters[[1]] nclusters <- Lp$nclusters[[2]] cluster.size <- Lp$cluster.size[[2]] cluster.sizes <- Lp$cluster.sizes[[2]] ncluster.sizes <- Lp$ncluster.sizes[[2]] n.s <- Lp$cluster.size.ns[[2]] between.idx <- Lp$between.idx[[2]] information.j <- matrix(0, npar, npar) for(clz in seq_len(ncluster.sizes)) { nj <- cluster.sizes[clz] Delta.j <- Delta.B.tilde + 1/nj * Delta.W.tilde sigma.j <- sigma.w + nj * sigma.b if(length(between.idx) > 0L) { omega.j <- matrix(0, p.tilde, p.tilde) omega.j[-between.idx, -between.idx] <- 1/nj * sigma.j omega.j[-between.idx, between.idx] <- sigma.yz omega.j[ between.idx, -between.idx] <- t(sigma.yz) omega.j[ between.idx, between.idx] <- sigma.zz } else { omega.j <- 1/nj * sigma.j } omega.j.inv <- solve(omega.j) I11.j <- omega.j.inv I22.j <- 0.5 * lav_matrix_duplication_pre_post(omega.j.inv %x% omega.j.inv) I.j <- lav_matrix_bdiag(I11.j, I22.j) info.j <- t(Delta.j) %*% I.j %*% Delta.j information.j <- information.j + n.s[clz]*info.j } Sigma.W.inv <- lav_matrix_symmetric_inverse(S = sigma.w, logdet = FALSE, Sinv.method = Sinv.method) I11.w <- Sigma.W.inv I22.w <- 0.5 * lav_matrix_duplication_pre_post(Sigma.W.inv %x% Sigma.W.inv) I.w <- lav_matrix_bdiag(I11.w, I22.w) I.w[Lp$both.idx[[2]],] <- 0 I.w[,Lp$both.idx[[2]]] <- 0 information.w <- (nobs - nclusters) * ( t(Delta.W) %*% I.w %*% Delta.W ) information <- 1/Lp$nclusters[[2]] * (information.w + information.j) information } lav_mvnorm_cluster_information_observed <- function(Lp = NULL, YLp = NULL, Mu.W = NULL, Sigma.W = NULL, Mu.B = NULL, Sigma.B = NULL, x.idx = integer(0L), Sinv.method = "eigen") { nobs <- Lp$nclusters[[1]] nw <- length(as.vector(Mu.W)) nw.star <- nw*(nw+1)/2 nb <- length(as.vector(Mu.B)) nb.star <- nb*(nb+1)/2 ov.idx <- Lp$ov.idx p.tilde <- length( unique(c(ov.idx[[1]], ov.idx[[2]])) ) Mu.W.tilde <- numeric(p.tilde) Mu.W.tilde[ ov.idx[[1]] ] <- Mu.W GRAD <- function(x) { Mu.W.tilde2 <- numeric(p.tilde) Mu.W.tilde2[ ov.idx[[1]] ] <- x[1:nw] Mu.W.tilde2[ Lp$both.idx[[2]] ] <- Mu.W.tilde[ Lp$both.idx[[2]] ] Mu.W2 <- Mu.W.tilde2[ ov.idx[[1]] ] Sigma.W2 <- lav_matrix_vech_reverse( x[nw + 1:nw.star] ) Mu.B2 <- x[nw + nw.star + 1:nb] Sigma.B2 <- lav_matrix_vech_reverse( x[nw + nw.star + nb + 1:nb.star] ) dx <- lav_mvnorm_cluster_dlogl_2l_samplestats(YLp = YLp, Lp = Lp, Mu.W = Mu.W2, Sigma.W = Sigma.W2, Mu.B = Mu.B2, Sigma.B = Sigma.B2, return.list = FALSE, Sinv.method = Sinv.method) -1/2 * dx } start.x <- c(as.vector(Mu.W), lav_matrix_vech(Sigma.W), as.vector(Mu.B), lav_matrix_vech(Sigma.B)) information <- -1 * numDeriv::jacobian(func = GRAD, x = start.x) information <- information / Lp$nclusters[[2]] if(length(x.idx) > 0L) { x.idx.w <- which(ov.idx[[1]] %in% x.idx) if(length(x.idx.w) > 0L) { xw.idx <- c(x.idx.w, nw + lav_matrix_vech_which_idx(n = nw, idx = x.idx.w)) } else { xw.idx <- integer(0L) } x.idx.b <- which(ov.idx[[2]] %in% x.idx) if(length(x.idx.b) > 0L) { xb.idx <- c(x.idx.b, nb + lav_matrix_vech_which_idx(n = nb, idx = x.idx.b)) } else { xb.idx <- integer(0L) } all.idx <- c(xw.idx, nw + nw.star + xb.idx) information[all.idx, ] <- 0 information[, all.idx] <- 0 } information } lav_mvnorm_cluster_em_sat <- function(YLp = NULL, Lp = NULL, verbose = TRUE, tol = 1e-04, max.iter = 5000, min.variance = 1e-05) { between.idx <- Lp$between.idx[[2]] within.idx <- Lp$within.idx[[2]] Y2 <- YLp[[2]]$Y2 ov.idx <- Lp$ov.idx Sigma.W <- diag( length(ov.idx[[1]]) ) Sigma.B <- diag( length(ov.idx[[2]]) ) Mu.W <- numeric( length(ov.idx[[1]]) ) Mu.B <- numeric( length(ov.idx[[2]]) ) fx <- lav_mvnorm_cluster_loglik_samplestats_2l(YLp = YLp, Lp = Lp, Mu.W = Mu.W, Sigma.W = Sigma.W, Mu.B = Mu.B, Sigma.B = Sigma.B, Sinv.method = "eigen", log2pi = TRUE, minus.two = FALSE) if(verbose) { cat("EM iter:", sprintf("%3d", 0), " fx =", sprintf("%17.10f", fx), "\n") } out <- lav_mvnorm_cluster_implied22l(Lp = Lp, Mu.W = Mu.W, Sigma.W = Sigma.W, Mu.B = Mu.B, Sigma.B = Sigma.B) mu.y <- out$mu.y; mu.z <- out$mu.z; mu.w <- out$mu.w; mu.b <- out$mu.b sigma.w <- out$sigma.w; sigma.b <- out$sigma.b sigma.zz <- out$sigma.zz; sigma.yz <- out$sigma.yz if(length(between.idx) > 0L) { Z <- Y2[, between.idx, drop = FALSE] mu.z <- colMeans(Z, na.rm = TRUE) sigma.zz <- cov(Z, use = "pairwise.complete.obs") * (Lp$nclusters[[2]] - 1L)/Lp$nclusters[[2]] } fx.old <- fx for(i in 1:max.iter) { estep <- lav_mvnorm_cluster_em_estepb( YLp = YLp, Lp = Lp, sigma.w = sigma.w, sigma.b = sigma.b, mu.w = mu.w, mu.b = mu.b, sigma.yz = sigma.yz, sigma.zz = sigma.zz, mu.z = mu.z) sigma.w <- estep$sigma.w sigma.b <- estep$sigma.b sigma.yz <- estep$sigma.yz mu.w <- estep$mu.w mu.b <- estep$mu.b implied2 <- lav_mvnorm_cluster_2l2implied(Lp = Lp, sigma.w = estep$sigma.w, sigma.b = estep$sigma.b, sigma.zz = sigma.zz, sigma.yz = estep$sigma.yz, mu.z = mu.z, mu.y = NULL, mu.w = estep$mu.w, mu.b = estep$mu.b) Sigma.W <- implied2$Sigma.W zero.var <- which(diag(Sigma.W) < min.variance) if(length(zero.var) > 0L) { Sigma.W[,zero.var] <- sigma.w[,zero.var] <- 0 Sigma.W[zero.var,] <- sigma.w[zero.var,] <- 0 diag(Sigma.W)[zero.var] <- diag(sigma.w)[zero.var] <- min.variance } fx <- lav_mvnorm_cluster_loglik_samplestats_2l(YLp = YLp, Lp = Lp, Mu.W = implied2$Mu.W, Sigma.W = Sigma.W, Mu.B = implied2$Mu.B, Sigma.B = implied2$Sigma.B, Sinv.method = "eigen", log2pi = TRUE, minus.two = FALSE) fx.delta <- fx - fx.old if(verbose) { cat("EM iter:", sprintf("%3d", i), " fx =", sprintf("%17.10f", fx), " fx.delta =", sprintf("%9.8f", fx.delta), "\n") } if(fx.delta < tol) { break } else { fx.old <- fx } } list(Sigma.W = implied2$Sigma.W, Sigma.B = implied2$Sigma.B, Mu.W = implied2$Mu.W, Mu.B = implied2$Mu.B, logl = fx) } lav_mvnorm_cluster_em_h0 <- function(lavsamplestats = NULL, lavdata = NULL, lavimplied = NULL, lavpartable = NULL, lavmodel = NULL, lavoptions = NULL, verbose = FALSE, verbose.x = FALSE, fx.tol = 1e-08, dx.tol = 1e-05, max.iter = 5000, mstep.iter.max = 10000L, mstep.rel.tol = 1e-10) { stopifnot(lavdata@ngroups == 1L) Lp <- lavdata@Lp[[1]] ov.names.l <- [email protected][[1]] Y1 <- lavdata@X[[1]] YLp <- lavsamplestats@YLp[[1]] between.idx <- Lp$between.idx[[2]] Y2 <- YLp[[2]]$Y2 x.current <- lav_model_get_parameters(lavmodel) if(is.null(lavimplied)) { lavimplied <- lav_model_implied(lavmodel) } fx <- lav_mvnorm_cluster_loglik_samplestats_2l(YLp = YLp, Lp = Lp, Mu.W = lavimplied$mean[[1]], Sigma.W = lavimplied$cov[[1]], Mu.B = lavimplied$mean[[2]], Sigma.B = lavimplied$cov[[2]], Sinv.method = "eigen", log2pi = TRUE, minus.two = FALSE) if(verbose) { cat("EM iter:", sprintf("%3d", 0), " fx =", sprintf("%17.10f", fx), "\n") } out <- lav_mvnorm_cluster_implied22l(Lp = Lp, Mu.W = lavimplied$mean[[1]], Sigma.W = lavimplied$cov[[1]], Mu.B = lavimplied$mean[[2]], Sigma.B = lavimplied$cov[[2]]) mu.y <- out$mu.y; mu.z <- out$mu.z; mu.w <- out$mu.w; mu.b <- out$mu.b sigma.w <- out$sigma.w; sigma.b <- out$sigma.b sigma.zz <- out$sigma.zz; sigma.yz <- out$sigma.yz if(length(between.idx) > 0L) { Z <- Y2[, between.idx, drop = FALSE] mu.z <- colMeans(Y2)[between.idx] sigma.zz <- cov(Z) * (Lp$nclusters[[2]] - 1L)/Lp$nclusters[[2]] } fx.old <- fx fx2.old <- 0 REL <- numeric( max.iter ) for(i in 1:max.iter) { estep <- lav_mvnorm_cluster_em_estepb(YLp = YLp, Lp = Lp, sigma.w = sigma.w, sigma.b = sigma.b, mu.w = mu.w, mu.b = mu.b, sigma.yz = sigma.yz, sigma.zz = sigma.zz, mu.z = mu.z) implied <- lav_mvnorm_cluster_2l2implied(Lp = Lp, sigma.w = estep$sigma.w, sigma.b = estep$sigma.b, sigma.zz = sigma.zz, sigma.yz = estep$sigma.yz, mu.z = mu.z, mu.y = NULL, mu.w = estep$mu.w, mu.b = estep$mu.b) rownames(implied$Sigma.W) <- ov.names.l[[1]] rownames(implied$Sigma.B) <- ov.names.l[[2]] local.partable <- lavpartable local.partable$group <- NULL level.idx <- which(names(local.partable) == "level") names(local.partable)[level.idx] <- "group" local.partable$est <- NULL local.partable$se <- NULL free.idx <- which(lavpartable$free > 0L) local.partable$ustart[ free.idx ] <- x.current local.fit <- lavaan(local.partable, sample.cov = list(within = implied$Sigma.W, between = implied$Sigma.B), sample.mean = list(within = implied$Mu.W, between = implied$Mu.B), sample.nobs = Lp$nclusters, sample.cov.rescale = FALSE, control = list(iter.max = mstep.iter.max, rel.tol = mstep.rel.tol), fixed.x = any(lavpartable$exo == 1L), estimator = "ML", warn = FALSE, check.start = FALSE, check.post = FALSE, check.gradient = FALSE, check.vcov = FALSE, baseline = FALSE, h1 = FALSE, se = "none", test = "none") implied2 <- local.fit@implied fx <- lav_mvnorm_cluster_loglik_samplestats_2l(YLp = YLp, Lp = Lp, Mu.W = implied2$mean[[1]], Sigma.W = implied2$cov[[1]], Mu.B = implied2$mean[[2]], Sigma.B = implied2$cov[[2]], Sinv.method = "eigen", log2pi = TRUE, minus.two = FALSE) fx.delta <- fx - fx.old lavmodel <- lav_model_set_parameters(lavmodel, x = local.fit@optim$x) dx <- lav_model_gradient(lavmodel, lavdata = lavdata, lavsamplestats = lavsamplestats) max.dx <- max(abs(dx)) if(verbose) { cat("EM iter:", sprintf("%3d", i), " fx =", sprintf("%17.10f", fx), " fx.delta =", sprintf("%9.8f", fx.delta), " mstep.iter =", sprintf("%3d", lavInspect(local.fit, "iterations")), " max.dx = ", sprintf("%9.8f", max.dx), "\n") } if(fx.delta < fx.tol) { if(verbose) { cat("EM stopping rule reached: fx.delta < ", fx.tol, "\n") } break } else { fx.old <- fx x.current <- local.fit@optim$x if(verbose.x) { print(round(x.current, 3)) } } if(max.dx < dx.tol) { if(verbose) { cat("EM stopping rule reached: max.dx < ", dx.tol, "\n") } break } out <- lav_mvnorm_cluster_implied22l(Lp = Lp, Mu.W = implied2$mean[[1]], Sigma.W = implied2$cov[[1]], Mu.B = implied2$mean[[2]], Sigma.B = implied2$cov[[2]]) mu.y <- out$mu.y; mu.z <- out$mu.z; mu.w <- out$mu.w; mu.b <- out$mu.b sigma.w <- out$sigma.w; sigma.b <- out$sigma.b sigma.zz <- out$sigma.zz; sigma.yz <- out$sigma.yz } x <- local.fit@optim$x if(i < max.iter) { attr(x, "converged") <- TRUE attr(x, "warn.txt") <- "" } else { attr(x, "converged") <- FALSE attr(x, "warn.txt") <- paste("maxmimum number of iterations (", max.iter, ") ", "was reached without convergence.\n", sep = "") } attr(x, "iterations") <- i attr(x, "control") <- list(em.iter.max = max.iter, em.fx.tol = fx.tol, em.dx.tol = dx.tol) attr(fx, "fx.group") <- fx attr(x, "fx") <- fx x } lav_mvnorm_cluster_em_estep_ranef <- function( YLp = NULL, Lp = NULL, sigma.w = NULL, sigma.b = NULL, sigma.yz = NULL, sigma.zz = NULL, mu.z = NULL, mu.w = NULL, mu.b = NULL, se = FALSE) { nobs <- Lp$nclusters[[1]] nclusters <- Lp$nclusters[[2]] cluster.size <- Lp$cluster.size[[2]] between.idx <- Lp$between.idx[[2]] Y2 <- YLp[[2]]$Y2 nvar.y <- ncol(sigma.w) nvar.z <- ncol(sigma.zz) MB.j <- matrix(0, nrow = nclusters, ncol = nvar.y) SE.j <- matrix(0, nrow = nclusters, ncol = nvar.y) mu.y <- mu.w + mu.b if(length(between.idx) > 0L) { sigma.1 <- cbind(sigma.yz, sigma.b) mu <- c(mu.z, mu.y) } else { sigma.1 <- sigma.b mu <- mu.y } for(cl in seq_len(nclusters)) { nj <- cluster.size[cl] if(length(between.idx) > 0L) { b.j <- c(Y2[cl, between.idx], Y2[cl,-between.idx]) ybar.j <- Y2[cl,-between.idx] } else { ybar.j <- b.j <- Y2[cl,] } sigma.j <- sigma.w + nj*sigma.b if(length(between.idx) > 0L) { omega.j <- rbind( cbind(sigma.zz, t(sigma.yz)), cbind(sigma.yz, 1/nj * sigma.j) ) } else { omega.j <- 1/nj * sigma.j } omega.j.inv <- solve(omega.j) Ev <- as.numeric(mu.b + (sigma.1 %*% omega.j.inv %*% (b.j - mu))) MB.j[cl,] <- Ev if(se) { Covv <- sigma.b - (sigma.1 %*% omega.j.inv %*% t(sigma.1)) Covv <- (Covv + t(Covv))/2 Covv.diag <- diag(Covv) nonzero.idx <- which(Covv.diag > 0) SE.j[cl,] <- numeric( length(Covv.diag) ) SE.j[cl, nonzero.idx] <- sqrt(Covv.diag[nonzero.idx]) } } if(se) { attr(MB.j, "se") <- SE.j } MB.j } lav_mvnorm_cluster_em_estep <- function( YLp = NULL, Lp = NULL, sigma.w = NULL, sigma.b = NULL, sigma.yz = NULL, sigma.zz = NULL, mu.z = NULL, mu.w = NULL, mu.b = NULL) { nobs <- Lp$nclusters[[1]] nclusters <- Lp$nclusters[[2]] cluster.size <- Lp$cluster.size[[2]] cluster.idx <- Lp$cluster.idx[[2]] within.idx <- Lp$within.idx[[2]] between.idx <- Lp$between.idx[[2]] both.idx <- Lp$both.idx[[2]] Y2 <- YLp[[2]]$Y2 Y1Y1 <- YLp[[2]]$Y1Y1 nvar.y <- ncol(sigma.w) nvar.z <- ncol(sigma.zz) CW2.j <- matrix(0, nrow = nvar.y, ncol = nvar.y) CB.j <- matrix(0, nrow = nvar.y, ncol = nvar.y) MW.j <- matrix(0, nrow = nclusters, ncol = nvar.y) MB.j <- matrix(0, nrow = nclusters, ncol = nvar.y) ZY.j <- matrix(0, nrow = nvar.z, ncol = nvar.y) mu.y <- mu.w + mu.b if(length(between.idx) > 0L) { sigma.1 <- cbind(sigma.yz, sigma.b) mu <- c(mu.z, mu.y) Y1Y1 <- Y1Y1[-between.idx, -between.idx, drop = FALSE] } else { sigma.1 <- sigma.b mu <- mu.y } for(cl in seq_len(nclusters)) { nj <- cluster.size[cl] if(length(between.idx) > 0L) { b.j <- c(Y2[cl, between.idx], Y2[cl,-between.idx]) ybar.j <- Y2[cl,-between.idx] } else { ybar.j <- b.j <- Y2[cl,] } sigma.j <- sigma.w + nj*sigma.b if(length(between.idx) > 0L) { omega.j <- rbind( cbind(sigma.zz, t(sigma.yz)), cbind(sigma.yz, 1/nj * sigma.j) ) } else { omega.j <- 1/nj * sigma.j } omega.j.inv <- solve(omega.j) Ev <- as.numeric(mu.b + (sigma.1 %*% omega.j.inv %*% (b.j - mu))) Covv <- sigma.b - (sigma.1 %*% omega.j.inv %*% t(sigma.1)) Covv <- (Covv + t(Covv))/2 Evv <- Covv + tcrossprod(Ev) MW.j[cl,] <- ybar.j - Ev MB.j[cl,] <- Ev CW2.j <- CW2.j + nj * (Evv - tcrossprod(ybar.j, Ev) - tcrossprod(Ev, ybar.j)) CB.j <- CB.j + Evv if(length(between.idx) > 0L) { ZY.j <- ZY.j + tcrossprod(Y2[cl,between.idx], Ev) } } M.w <- 1/nobs * colSums(MW.j * cluster.size) M.b <- 1/nclusters * colSums(MB.j) C.b <- 1/nclusters * CB.j C.w <- 1/nobs * (Y1Y1 + CW2.j) if(length(between.idx) > 0L) { A <- 1/nclusters * ZY.j - tcrossprod(mu.z, M.b) } sigma.w <- C.w - tcrossprod(M.w) sigma.b <- C.b - tcrossprod(M.b) mu.w <- M.w mu.b <- M.b if(length(between.idx) > 0L) { sigma.yz <- t(A) } list(sigma.w = sigma.w, sigma.b = sigma.b, mu.w = mu.w, mu.b = mu.b, sigma.yz = sigma.yz, sigma.zz = sigma.zz, mu.z = mu.z) } lav_mvnorm_cluster_em_estepb <- function( YLp = NULL, Lp = NULL, sigma.w = NULL, sigma.b = NULL, sigma.yz = NULL, sigma.zz = NULL, mu.z = NULL, mu.w = NULL, mu.b = NULL) { nobs <- Lp$nclusters[[1]] nclusters <- Lp$nclusters[[2]] cluster.size <- Lp$cluster.size[[2]] cluster.idx <- Lp$cluster.idx[[2]] between.idx <- Lp$between.idx[[2]] cluster.sizes <- Lp$cluster.sizes[[2]] ncluster.sizes <- Lp$ncluster.sizes[[2]] n.s <- Lp$cluster.size.ns[[2]] Y2 <- YLp[[2]]$Y2 Y1Y1 <- YLp[[2]]$Y1Y1 nvar.y <- ncol(sigma.w) nvar.z <- ncol(sigma.zz) mu.y <- mu.w + mu.b if(length(between.idx) > 0L) { sigma.1 <- cbind(sigma.yz, sigma.b) mu <- c(mu.z, mu.y) Y1Y1 <- Y1Y1[-between.idx, -between.idx, drop = FALSE] } else { sigma.1 <- sigma.b mu <- mu.y } CW2.s <- matrix(0, nrow = nvar.y, ncol = nvar.y) CB.s <- matrix(0, nrow = nvar.y, ncol = nvar.y) MW.s <- matrix(0, nrow = ncluster.sizes, ncol = nvar.y) MB.s <- matrix(0, nrow = ncluster.sizes, ncol = nvar.y) ZY.s <- matrix(0, nvar.z, nvar.y) for(clz in seq_len(ncluster.sizes)) { nj <- cluster.sizes[clz] if(length(between.idx) > 0L) { b.j <- cbind(Y2[cluster.size == nj, between.idx, drop = FALSE], Y2[cluster.size == nj,-between.idx, drop = FALSE]) ybar.j <- Y2[cluster.size == nj, -between.idx, drop = FALSE] } else { ybar.j <- b.j <- Y2[cluster.size == nj, , drop = FALSE] } sigma.j <- sigma.w + nj*sigma.b if(length(between.idx) > 0L) { omega.j <- rbind( cbind(sigma.zz, t(sigma.yz)), cbind(sigma.yz, 1/nj * sigma.j) ) } else { omega.j <- 1/nj * sigma.j } omega.j.inv <- solve(omega.j) sigma.1.j.inv <- sigma.1 %*% omega.j.inv b.jc <- t( t(b.j) - mu ) tmp <- b.jc %*% t(sigma.1.j.inv) Ev <- t(t(tmp) + mu.b) Covv <- n.s[clz]*(sigma.b - (sigma.1.j.inv %*% t(sigma.1))) Covv <- (Covv + t(Covv))/2 Evv <- Covv + crossprod(Ev) MW.s[clz,] <- nj * colSums(ybar.j - Ev) MB.s[clz,] <- colSums(Ev) CW2.s <- CW2.s + nj * (Evv - crossprod(ybar.j, Ev) - crossprod(Ev, ybar.j)) CB.s <- CB.s + Evv if(length(between.idx) > 0L) { ZY.s <- ZY.s + crossprod(Y2[cluster.size == nj, between.idx, drop = FALSE], Ev) } } M.ws <- 1/nobs * colSums(MW.s) M.bs <- 1/nclusters * colSums(MB.s) C.bs <- 1/nclusters * CB.s C.ws <- 1/nobs * (Y1Y1 + CW2.s) if(length(between.idx) > 0L) { As <- 1/nclusters * ZY.s - tcrossprod(mu.z, M.bs) } sigma.w <- C.ws - tcrossprod(M.ws) sigma.b <- C.bs - tcrossprod(M.bs) mu.w <- M.ws mu.b <- M.bs if(length(between.idx) > 0L) { sigma.yz <- t(As) } list(sigma.w = sigma.w, sigma.b = sigma.b, mu.w = mu.w, mu.b = mu.b, sigma.yz = sigma.yz, sigma.zz = sigma.zz, mu.z = mu.z) }
fastkmed <- function(distdata, ncluster, iterate = 10, init = NULL) { if(any(is.na(distdata))) stop("Cannot handle missing values!") if((is.matrix(distdata)||inherits(distdata, "dist"))==FALSE) stop("The distdata must be a matrix or a dist object!") if(is.matrix(distdata)==TRUE) { nr <- nrow(distdata) nc <- ncol(distdata) if (nc!=nr) stop("The distdata is not an x n distance matrix!") } if(inherits(distdata, "dist")) distdata <- as.matrix(distdata) if(is.null(rownames(distdata))==TRUE) rownames(distdata) <- 1:nrow(distdata) n <- nrow(distdata) index <- 1:n if (is.null(init) == TRUE) { distsum <- colSums(distdata/sum(distdata)) names(distsum) <- index iduniq <- as.numeric(names(distsum [!duplicated(distsum)])) distuniq <- unique(distsum) names(distuniq) <- iduniq sorted_object <- as.numeric(names(sort(distuniq))) medoid_init <- sorted_object[1:ncluster] if (sum(!is.na(medoid_init)) < ncluster) stop("An empty cluster is present, change the number of clusters or initial medoids") } else { if (ncluster != length(init)) stop("The initial medoids must equal to the number of clusters") if (sum(is.na(init)) > 0) stop("The initial medoids consist of NA") medoid_init <- init } dist_0 <- distdata[,medoid_init, drop = FALSE] for (i in 1:ncluster) { dist_0[names(dist_0[,i]) == colnames(dist_0)[i], i] <- -1 } member_0 <- apply(dist_0, 1, which.min) E0 <- sum(apply(dist_0, 1, min)) if (length(unique(member_0)) != ncluster) stop("An empty cluster is present, change the number of clusters or initial medoids") row_0 <- row_1 <- medoid_0 <- medoid_1 <- numeric(ncluster) for (i in 1:ncluster) { row_0[i] <- which.min(rowSums(distdata[member_0==i,member_0==i, drop = FALSE])) medoid_0[i] <- index[member_0==i][row_0[i]] } dist_1 <- distdata[,medoid_0, drop = FALSE] for (i in 1:ncluster) { dist_1[names(dist_1[,i]) == colnames(dist_1)[i], i] <- -1 } member_1 <- apply(dist_1, 1, which.min) E1 <- sum(apply(dist_1, 1, min)) for (i in 1:ncluster) { row_1[i] <- which.min(rowSums(distdata[member_1==i,member_1==i, drop = FALSE])) medoid_1[i] <- index[member_1==i][row_1[i]] } if (sum(sort(medoid_0) != sort(medoid_1))!=0) { x <- 1 medoid <- vector("list", iterate) E <- numeric(iterate) repeat { dist_0 <- dist_1 member_0 <- member_1 E0 <- E1 row_0 <- row_1 medoid_0 <- medoid_1 dist_1 <- distdata[,medoid_0, drop = FALSE] for (i in 1:ncluster) { dist_1[names(dist_1[,i]) == colnames(dist_1)[i], i] <- -1 } member_1 <- apply(dist_1, 1, which.min) for (i in 1:ncluster) { row_1[i] <- which.min(rowSums(distdata[member_1==i,member_1==i, drop = FALSE])) medoid_1[i] <- index[member_1==i][row_1[i]] } E1 <- sum(apply(dist_1, 1, min)) medoid[[x]] <- medoid_1 E[x] <- E1 if (x == iterate || sum(sort(medoid_0) != sort(medoid_1))==0) { break } x <- x + 1 } medoid <- do.call(rbind, medoid) E <- E[1:x] index_E <- which.min(E) medoid_2 <- medoid[index_E,] dist_2 <- distdata[,medoid_2, drop = FALSE] for (i in 1:ncluster) { dist_2[names(dist_2[,i]) == colnames(dist_2)[i], i] <- -1 } member_2 <- apply(dist_2, 1, which.min) E2 <- sum(apply(dist_2, 1, min)) names(member_2) <- rownames(distdata) result <- list(cluster = member_2, medoid = medoid_2, minimum_distance = E2) } else { dist_2 <- distdata[,medoid_1, drop = FALSE] member_1 <- apply(dist_2, 1, which.min) E2 <- sum(apply(dist_2, 1, min)) result <- list(cluster = member_1, medoid = medoid_1, minimum_distance = E2) } return(result) }
"%contains%" <- function(x, y) all(y %in% x) rep_along <- function(x, y) { if (length(y) == 0) return(NULL) rep(x, length(y)) } row_heights <- function(m){ do.call(grid::unit.c, apply(m, 1, function(l) 1.1*max(do.call(grid::unit.c, lapply(l, grid::grobHeight))))) } col_widths <- function(m){ do.call(grid::unit.c, apply(m, 2, function(l) 1.1*max(do.call(grid::unit.c, lapply(l, grid::grobWidth))))) } rep_ifshort <- function(x, n, nc, nr, rep_mode){ if(length(x) >= n){ return(x[1:n]) } else { if (rep_mode=="row"){ return(rep(rep(x, length.out=nr), length.out=n)) } else if (rep_mode=="col") { return(as.vector(matrix(rep(rep(x, length.out=nc), length.out=n), byrow=TRUE, nrow=nr))) } else { stop(paste0("Unsupported value '", rep_mode,"' of rep_mode. Choose 'col' or 'row'")) } } } breaks_scale <- function(d, d_min=NULL, d_max=NULL, breaks=10){ if (is.null(d_min)){ d_min = min(d) } if (is.null(d_max)){ d_max = max(d) } if (d_min == d_max){ if (d_min != 0){ d <- d/d_max } else { d <- d } } else { d <- (d-d_min)/(d_max - d_min) } if (length(breaks)==1){ breaks <- seq(from=0, to=1, length.out=breaks+1) } else { breaks <- (breaks-d_min)/(d_max-d_min) } dint <- cut(d, labels=F, breaks=breaks, left.open=TRUE) dint <- (breaks[dint] + breaks[dint+1])/2 dint[is.na(dint)] <- 0 dcut <- matrix(dint, nrow=nrow(d), byrow=F) dcut <- dcut/max(dcut) dcut } extract_breadth_first <- function(lst, n){ sapply(lst, `[`, n) } extract_strwidth_max_label <- function(labels, fontsize, unit="inches"){ label_max <- labels[which(nchar(labels)==max(nchar(labels)))[1]] label_max_width <- strwidth(label_max, font=1, cex=fontsize/12, units=unit, ps=par(ps=12)) unit(label_max_width, unit) } extract_strheight_max_label <- function(labels, fontsize, unit="inches"){ label_max <- labels[which(nchar(labels)==max(nchar(labels)))[1]] label_max_height <- strheight(label_max, font=1, cex=fontsize/12, units=unit, ps=par(ps=12)) unit(label_max_height, unit) } get_value_from_unit <- function(x){ as.numeric(gsub("[a-zA-Z]+", "", as.character(x))) } get_unit_from_unit <- function(x) { as.character(gsub("[0-9\\.]+", "", as.character(x))) } convert_unit <- function(x, to, from=NULL){ if (!is.unit(x) & is.null(from)){ stop("if unit is not specified, x has to be a grid::unit object") } else if (is.unit(x)){ value <- get_value_from_unit(x) from <- get_unit_from_unit(x) } else { value <- x } convert_to_cm <- list("cm"=1, "centimetre"=1, "centimeter"=1, "mm"=0.1, "in"=2.54, "inch"=2.54, "inches"=2.54, "points"=2.54/72.27, "picas"=12*2.54/72.27) value*convert_to_cm[[from]]/convert_to_cm[[to]] }
NULL observed <- function(o, ...) UseMethod("observed") observed.data.frame <- function(o, x, yobs, pred=NULL, blq=NULL, lloq=-Inf, alq=NULL, uloq=Inf, ...) { data <- o x <- rlang::eval_tidy(rlang::enquo(x), data) yobs <- rlang::eval_tidy(rlang::enquo(yobs), data) pred <- rlang::eval_tidy(rlang::enquo(pred), data) lloq <- rlang::eval_tidy(rlang::enquo(lloq), data) uloq <- rlang::eval_tidy(rlang::enquo(uloq), data) blq <- rlang::eval_tidy(rlang::enquo(blq), data) alq <- rlang::eval_tidy(rlang::enquo(alq), data) obs <- data.table(x, y=yobs, blq, lloq, alq, uloq) o <- structure(list(data=data), class="tidyvpcobj") o <- update(o, obs=obs, pred=pred) censoring(o) } simulated <- function(o, ...) UseMethod("simulated") simulated.tidyvpcobj <- function(o, data, ysim, ...) { ysim <- rlang::eval_tidy(rlang::enquo(ysim), data) obs <- o$obs x <- obs$x nrep <- length(ysim)/nrow(obs) repl <- rep(1:nrep, each=nrow(obs)) sim <- data.table(x, y=ysim, repl) update(o, sim=sim) } censoring <- function(o, ...) UseMethod("censoring") censoring.tidyvpcobj <- function(o, blq, lloq, alq, uloq, data=o$data, ...) { if (missing(blq)) { blq <- o$obs$blq } else { blq <- rlang::eval_tidy(rlang::enquo(blq), data) } if (missing(lloq)) { lloq <- o$obs$lloq } else { lloq <- rlang::eval_tidy(rlang::enquo(lloq), data) } if (missing(alq)) { alq <- o$obs$alq } else { alq <- rlang::eval_tidy(rlang::enquo(alq), data) } if (missing(uloq)) { uloq <- o$obs$uloq } else { uloq <- rlang::eval_tidy(rlang::enquo(uloq), data) } if (is.null(blq)) { blq <- FALSE } if (!is.logical(blq)) { stop("blq must be of type logical") } if (any(is.na(blq))) { stop("blq cannot contain missing values") } if (is.null(lloq)) { if (any(blq)) { stop("No lloq specified for blq") } lloq <- -Inf } if (!is.numeric(lloq)) { stop("lloq must be of type numeric") } if (any(blq & (is.na(lloq) | lloq == -Inf))) { stop("No lloq specified for blq") } if (is.null(alq)) { alq <- FALSE } if (!is.logical(alq)) { stop("alq must be of type logical") } if (any(is.na(alq))) { stop("alq cannot contain missing values") } if (is.null(uloq)) { if (any(alq)) { stop("No uloq specified for alq") } uloq <- Inf } if (!is.numeric(uloq)) { stop("uloq must be of type numeric") } if (any(alq & (is.na(uloq) | uloq == Inf))) { stop("No uloq specified for alq") } .blq <- blq .lloq <- lloq .alq <- alq .uloq <- uloq o$obs[, blq := rep(.blq, len=.N)] o$obs[, lloq := rep(.lloq, len=.N)] o$obs[, alq := rep(.alq, len=.N)] o$obs[, uloq := rep(.uloq, len=.N)] update(o, censoring=TRUE) } stratify <- function(o, ...) UseMethod("stratify") stratify.tidyvpcobj <- function(o, formula, data=o$data, ...) { if (!inherits(formula, "formula")) { stop("Expecting a formula") } flist <- as.list(formula) if (length(flist) == 3) { lhs <- as.call(c(flist[[1]], flist[[2]])) rhs <- as.call(c(flist[[1]], flist[[3]])) if (flist[[2]] == as.symbol(".")) { lhsmf <- NULL } else { lhsmf <- as.data.table(model.frame(lhs, data)) } if (flist[[3]] == as.symbol(".")) { rhsmf <- NULL } else { rhsmf <- as.data.table(model.frame(rhs, data)) } if (is.null(lhsmf) && is.null(rhsmf)) { stop("Invalid stratification formula: no variables specified") } strat <- cbind(lhsmf, rhsmf) } else { strat <- as.data.table(model.frame(formula, data)) } reserved.names <- c("x", "y", "ypc", "pred", "blq", "lloq", "repl", "bin", "xbin", "qname", "lo", "md", "hi", "nobs", "xmedian", "xmean", "xmin", "xmax", "xmid", "xleft", "xright", "xcenter") if (any(names(strat) %in% reserved.names)) { stop(paste0("The names of used for stratification must not include: ", paste0(reserved.names, collapse=", "))) } o$obs[, names(strat) := strat] strat.split <- split(o$obs, strat) strat.split <- strat.split[lapply(strat.split,NROW)>0] update(o, strat=strat, strat.split = strat.split, strat.formula=formula) } binning <- function(o, ...) UseMethod("binning") binning.tidyvpcobj <- function(o, bin, data=o$data, xbin="xmedian", centers, breaks, nbins, altx, stratum=NULL, by.strata=TRUE, ...) { keep <- i <- NULL . <- list xbin <- rlang::eval_tidy(rlang::enquo(xbin), data) if (is.numeric(xbin)) { if (length(xbin) != nrow(o$obs)) { stop("A numeric xbin be of length equal to the number of observations") } bin <- xbin } else { if (missing(bin) && !missing(centers)) { bin <- "centers" } else if (missing(bin) && !missing(breaks)) { bin <- "breaks" } else { bin <- rlang::eval_tidy(rlang::enquo(bin), data) } } if (missing(altx)) { x <- o$obs$x } else { x <- rlang::eval_tidy(rlang::enquo(altx), data) } if (!missing(nbins)) { nbins <- rlang::eval_tidy(rlang::enquo(nbins), data) if (is.numeric(nbins) && !is.null(o$strat) && (length(nbins) == nrow(o$strat))) { nbins <- data.table(nbins)[, .(nbins=unique(nbins)), by=o$strat] } } args <- lapply(rlang::enquos(...), rlang::eval_tidy, data=data) by.strata <- isTRUE(by.strata) if (!is.null(stratum)) { if (!is.list(stratum)) { stop("stratum must be a list, data.frame or data.table") } if (is.null(o$strat)) { stop("No stratification has been specified") } if (!by.strata) { stop("by.strata must be TRUE when stratum is specified") } filter <- copy(o$strat)[, keep := F] filter[as.data.table(stratum), keep := T, on=names(stratum)] filter <- filter$keep } else { filter <- rep(T, nrow(o$obs)) } if (is.numeric(xbin)) { if (length(xbin) != nrow(o$obs)) { stop("A numeric xbin be of length equal to the number of observations") } bin <- xbin } else if (is.character(bin) && length(bin) == 1) { known.classInt.styles <- c("fixed", "sd", "equal", "pretty", "quantile", "kmeans", "hclust", "bclust", "fisher", "jenks", "dpih") if (bin == "centers") { if (missing(centers)) { stop("centers must be specified to use this binning method") } if (!by.strata && is.data.frame(centers)) { stop("by.strata must be TRUE when centers is a data.frame") } bin <- nearest(centers) } else if (bin == "breaks") { if (missing(breaks)) { stop("breaks must be specified to use this binning method") } if (!by.strata && is.data.frame(breaks)) { stop("by.strata must be TRUE when breaks is a data.frame") } bin <- cut_at(breaks) } else if (bin == "ntile") { if (missing(nbins)) { stop("nbins must be specified to use this binning method") } bin <- bin_by_ntile(nbins) } else if (bin == "eqcut") { if (missing(nbins)) { stop("nbins must be specified to use this binning method") } bin <- bin_by_eqcut(nbins) } else if (bin == "pam") { if (missing(nbins)) { stop("nbins must be specified to use this binning method") } bin <- bin_by_pam(nbins) } else if (bin %in% known.classInt.styles) { if (missing(nbins)) { nbins <- NULL } bin <- bin_by_classInt(bin, nbins) } else { stop(sprintf("Unknown binning method: %s", bin)) } } if (is.function(bin)) { xdat <- data.table(i=1:nrow(o$obs), x=x) if (any(is.na(xdat[filter]$x))) { warning("x contains missing values, which could affect binning") } if (any(is.infinite(xdat[filter]$x))) { warning("x contains non-finite values, which could affect binning") } if (by.strata && !is.null(o$strat)) { sdat <- copy(o$strat) temp <- xdat[filter, .(i=i, j=do.call(bin, c(list(x), args, .BY))), by=sdat[filter]] j <- temp[order(i), j] } else { j <- xdat[filter, do.call(bin, c(list(x), args))] } if (length(j) != sum(filter)) { stop("The binning function did not return the right number of elements") } } else if (length(bin) == nrow(o$obs)) { j <- bin[filter] } else { stop("Incorrect binning specification") } o$obs[filter, bin := as.factor(j)] bin <- o$obs$bin if (!is.null(o$strat)) { stratbin <- data.table(o$strat, bin) } else { stratbin <- data.table(bin) } o <- update(o, .stratbin=stratbin, bin.by.strata=by.strata) if (is.numeric(xbin)) { xbin <- data.table(xbin=xbin)[, .(xbin = unique(xbin)), by=stratbin] } else if (is.character(xbin) && length(xbin) == 1) { bi <- bininfo(o) xbin <- data.table(bi[, names(stratbin), with=FALSE], xbin=bi[[xbin]]) } else if (is.function(xbin)) { xbin <- data.table(x=x)[, .(xbin = xbin(x)), by=stratbin] } else { stop("Invalid xbin") } vpc.method <- list(method = "binning") update(o, xbin=xbin, vpc.method = vpc.method) } binless <- function(o, ...) UseMethod("binless") binless.tidyvpcobj <- function(o, optimize = TRUE, optimization.interval = c(0,7), loess.ypc = FALSE, lambda = NULL, span = NULL, sp = NULL, ...) { if(class(o) != "tidyvpcobj") { stop("No tidyvpcobj found, observed(...) %>% simulated(...) must be called prior to binless()") } if(!optimize){ if(is.null(lambda) && is.null(sp)) { stop("Set optimize = TRUE if no lambda or sp arguments specified") } } if(!is.null(sp)){ if(optimize){ optimize <- FALSE } sp <- lapply(sp, function(x) x <- c(sp = x)) } if(loess.ypc && is.null(o$predcor)) { stop("Use predcorrect() before binless() in order to use LOESS prediction corrected") } if(!is.null(span) && !loess.ypc) { stop("Set loess.ypc = TRUE and optimize = FALSE if setting span smoothing parameter for LOESS prediction corrected") } method <- list(method = "binless", optimize = optimize, optimization.interval = optimization.interval, loess.ypc = loess.ypc, lambda = lambda, span = span, sp = sp) update(o, vpc.method = method) } predcorrect <- function(o, ...) UseMethod("predcorrect") predcorrect.tidyvpcobj <- function(o, pred, data=o$data, ..., log=FALSE) { ypc <- y <- NULL if (missing(pred)) { pred <- o$pred } else { pred <- rlang::eval_tidy(rlang::enquo(pred), data) } if (is.null(pred)) { stop("No pred specified") } stratbin <- o$.stratbin mpred <- data.table(stratbin, pred) mpred <- mpred[, mpred := median(pred), by=stratbin] mpred <- mpred$mpred if (log) { o$obs[, ypc := (mpred - pred) + y] o$sim[, ypc := (mpred - pred) + y] } else { o$obs[, ypc := (mpred/pred)*y] o$sim[, ypc := (mpred/pred)*y] } update(o, predcor=TRUE, predcor.log=log, pred=pred ) } nopredcorrect <- function(o, ...) UseMethod("nopredcorrect") nopredcorrect.tidyvpcobj <- function(o, ...) { update(o, predcor=FALSE) } vpcstats <- function(o, ...) UseMethod("vpcstats") vpcstats.tidyvpcobj <- function(o, vpc.type =c("continuous", "categorical"), qpred=c(0.05, 0.5, 0.95), ..., conf.level=0.95, quantile.type=7) { type <- match.arg(vpc.type) method <- o$vpc.method stopifnot(method$method %in% c("binless", "binning")) stopifnot(length(qpred) == 3) repl <- ypc <- y <- x <- blq <- lloq <- alq <- uloq <- NULL . <- list qconf <- c(0, 0.5, 1) + c(1, 0, -1)*(1 - conf.level)/2 obs <- o$obs sim <- o$sim predcor <- o$predcor stratbin <- o$.stratbin xbin <- o$xbin strat <- o$strat if(method$method == "binless" && type == "continuous"){ o <- binlessaugment(o, qpred = qpred, interval = method$optimization.interval, loess.ypc = method$loess.ypc) o <- binlessfit(o, conf.level = conf.level, llam.quant = method$lambda, span = method$span) } if(type == "categorical"){ if(.isCensored(obs)){ stop("Censoring not supported for categorical vpc") } ylvls <- sort(unique(obs$y)) if(method$method == "binless"){ xobs <- obs$x xsim <- sim$x sp <- method$sp .stratrepl <- data.table(strat, sim[, .(repl)]) obs <- obs[, fastDummies::dummy_columns(obs, select_columns = "y")] setnames(obs, paste0("y_", ylvls), paste0("prob", ylvls)) pobs <- melt(obs, id.vars = c(names(strat), "x"), measure.vars = paste0("prob", ylvls), variable.name = "pname", value.name = "y") pobs.split <- split(pobs, by = c(names(strat),"pname"), sorted = TRUE) pobs.split <- pobs.split[lapply(pobs.split, nrow)>1] if(method$optimize){ sp_opt <- list() for(i in seq_along(pobs.split)){ sp_opt[[i]] <- pobs.split[[i]][, .(sp = optimize(.gam_optimize, y = y, x = x, data = pobs.split[[i]], interval = method$optimization.interval)$minimum)] } names(sp_opt) <- names(pobs.split) method$sp <- sp_opt for(i in seq_along(pobs.split)){ pobs.split[[i]][, y := .fitcatgam(y, x, sp = sp_opt[[i]]$sp)] } } else { sp_opt <- method$sp if(length(sp_opt) != length(pobs.split)){ stop(paste0("`incorrect number of elements specified to `sp` argument in `binless()` function, specify a list of length ", length(pobs.split), " in the following order: \n", paste0(names(pobs.split), collapse = "\n"), "\n", "Note: Do not specify a value for strata where not data is available.")) } for(i in seq_along(pobs.split)){ pobs.split[[i]][, y := .fitcatgam(y, x, sp = sp_opt[[i]])] } } pobs <- rbindlist(pobs.split) if(!is.null(strat)){ sim <- sim[, c(names(strat)) := rep(strat, len = .N), by = .(repl)] } sim <- sim[, fastDummies::dummy_columns(sim, select_columns = "y")] setnames(sim, paste0("y_", ylvls), paste0("prob", ylvls)) psim <- melt(sim, id.vars = c(names(.stratrepl), "x"), measure.vars = paste0("prob", ylvls), variable.name = "pname", value.name = "y") psim$y <- as.double(psim$y) psim.split <- split(psim, by = c(names(strat),"pname"), sorted = TRUE) psim.split <- psim.split[lapply(psim.split, nrow)>1] if(method$optimize){ for(i in seq_along(psim.split)){ psim.split[[i]][, y := .fitcatgam(y, x, sp = sp_opt[[i]]$sp), by = list(repl)] } } else { for(i in seq_along(psim.split)){ psim.split[[i]][, y := .fitcatgam(y, x, sp = sp_opt[[i]]), by = repl] } } psim <- rbindlist(psim.split) .stratbinquant <- psim[, !c("repl", "y")] ppsim <- psim[, .(lo=quantile(y,probs=qconf[[1]], type=quantile.type), md=median(y), hi=quantile(y,probs=qconf[[3]], type=quantile.type)), by = .stratbinquant] stats <- unique(pobs[ppsim, on=names(.stratbinquant)]) setkeyv(stats, c(names(strat), "x")) } else { if (is.null(stratbin)) { stop("Need to specify binning before calling vpcstats.") } if (any(is.na(stratbin$bin))) { warning("There are bins missing. Has binning been specified for all strata?", call.=F) } .stratbinrepl <- data.table(stratbin, sim[, .(repl)]) obs <- obs[, fastDummies::dummy_columns(obs, select_columns = "y")] pobs <- obs[, lapply(.SD, mean, na.rm=TRUE), by=stratbin, .SDcols=paste0("y_", ylvls)] setnames(pobs, paste0("y_", ylvls), paste0("prob", ylvls)) pobs <- melt(pobs, id.vars = names(stratbin), measure.vars = paste0("prob", ylvls), variable.name = "pname", value.name = "y") sim <- sim[, fastDummies::dummy_columns(sim, select_columns = "y")] psim <- sim[, lapply(.SD, mean, na.rm=TRUE), by=.stratbinrepl, .SDcols=paste0("y_", ylvls)] setnames(psim, paste0("y_", ylvls), paste0("prob", ylvls)) psim <- melt(psim, id.vars = names(.stratbinrepl), measure.vars = paste0("prob", ylvls), variable.name = "pname", value.name = "y") .stratbinquant <- psim[, !c("repl", "y")] qconf <- c(0, 0.5, 1) + c(1, 0, -1)*(1 - conf.level)/2 ppsim <- psim[, .(lo=quantile(y,probs=qconf[[1]], type=quantile.type), md=median(y), hi=quantile(y,probs=qconf[[3]], type=quantile.type)), by = .stratbinquant] stats <- pobs[ppsim, on=names(.stratbinquant)] stats <- xbin[stats, on=names(stratbin)] setkeyv(stats, c(names(o$strat), "xbin")) } update(o, stats=stats, conf.level=conf.level, vpc.type = type, vpc.method = method) } else { if(method$method == "binless") { .binlessvpcstats(o, qpred=qpred, conf.level=conf.level, quantile.type=quantile.type, vpc.type = type, vpc.method = method) } else { if (is.null(stratbin)) { stop("Need to specify binning before calling vpcstats.") } if (any(is.na(stratbin$bin))) { warning("There are bins missing. Has binning been specified for all strata?", call.=F) } .stratbinrepl <- data.table(stratbin, sim[, .(repl)]) myquant1 <- function(y, probs, qname=paste0("q", probs), type=quantile.type, blq=FALSE, alq=FALSE) { if (is.null(blq)) blq <- FALSE if (is.null(alq)) alq <- FALSE blq <- rep(blq, len=length(y)) alq <- rep(alq, len=length(y)) y <- ifelse(blq, -Inf, ifelse(alq, Inf, y)) y <- quantile(y, probs=probs, type=type, names=FALSE, na.rm=TRUE) y[y == -Inf] <- NA y[y == Inf] <- NA qname <- factor(qname, levels=unique(qname)) data.frame(qname, y) } myquant2 <- function(y, probs, qname=paste0("q", probs), type=quantile.type) { y <- quantile(y, probs=probs, type=type, names=FALSE, na.rm=TRUE) setNames(as.list(y), qname) } if (isTRUE(predcor)) { qobs <- obs[, myquant1(ypc, probs=qpred, blq=blq, alq=alq), by=stratbin] qsim <- sim[, myquant1(ypc, probs=qpred, blq=FALSE, alq=FALSE), by=.stratbinrepl] } else { qobs <- obs[, myquant1(y, probs=qpred, blq=blq, alq=alq), by=stratbin] qsim <- sim[, myquant1(y, probs=qpred, blq=FALSE, alq=FALSE), by=.stratbinrepl] } .stratbinquant <- qsim[, !c("repl", "y")] qconf <- c(0, 0.5, 1) + c(1, 0, -1)*(1 - conf.level)/2 qqsim <- qsim[, myquant2(y, probs=qconf, qname=c("lo", "md", "hi")), by=.stratbinquant] stats <- qobs[qqsim, on=names(.stratbinquant)] stats <- xbin[stats, on=names(stratbin)] setkeyv(stats, c(names(o$strat), "xbin")) if (!is.null(obs$blq) && any(obs$blq)) { sim[, lloq := rep(obs$lloq, len=.N)] sim[, blq := (y < lloq)] pctblqobs <- obs[, .(y=100*mean(blq)), by=stratbin] pctblqsim <- sim[, .(y=100*mean(blq)), by=.stratbinrepl] .stratbinpctblq <- pctblqsim[, !c("repl", "y")] qpctblqsim <- pctblqsim[, myquant2(y, probs=qconf, qname=c("lo", "md", "hi")), by=.stratbinpctblq] pctblq <- pctblqobs[qpctblqsim, on=names(.stratbinpctblq)] pctblq <- xbin[pctblq, on=names(stratbin)] setkeyv(pctblq, c(names(o$strat), "xbin")) } else { pctblq <- NULL } if (!is.null(obs$alq) && any(obs$alq)) { sim[, uloq := rep(obs$uloq, len=.N)] sim[, alq := (y > uloq)] pctalqobs <- obs[, .(y=100*mean(alq)), by=stratbin] pctalqsim <- sim[, .(y=100*mean(alq)), by=.stratbinrepl] .stratbinpctalq <- pctalqsim[, !c("repl", "y")] qpctalqsim <- pctalqsim[, myquant2(y, probs=qconf, qname=c("lo", "md", "hi")), by=.stratbinpctalq] pctalq <- pctalqobs[qpctalqsim, on=names(.stratbinpctalq)] pctalq <- xbin[pctalq, on=names(stratbin)] setkeyv(pctalq, c(names(o$strat), "xbin")) } else { pctalq <- NULL } update(o, stats=stats, pctblq=pctblq, pctalq=pctalq, conf.level=conf.level, vpc.type = type) } } } update.tidyvpcobj <- function(object, ...) { args <- list(...) for (i in names(args)) { object[[i]] <- args[[i, exact=TRUE]] } object } print.tidyvpcobj <- function(x, ...) { if (!is.null(x$sim)) { nrep <- nrow(x$sim)/nrow(x$obs) if (isTRUE(x$predcor)) { cat("Prediction corrected ") } cat(sprintf("VPC with %d replicates", nrep), "\n") } cat(sprintf("Stratified by: %s", paste0(names(x$strat), collapse=", ")), "\n") if (!is.null(x$stats)) { print(x$stats) } invisible(x) } .binlessvpcstats <- function(o, qpred=c(0.05, 0.5, 0.95), ..., conf.level=0.95, quantile.type=7, vpc.type){ y <- x <- blq <- fit <- . <- repl <- cprop <- rqssmed <- llam.med <- c.rqssmed <- NULL obs.fits <- o$rqss.obs.fits sim.fits <- o$rqss.sim.fits obs <- o$obs sim <- o$sim predcor <- o$predcor xbinless <- o$obs$x if(!is.null(o$strat)) { stratx <- obs.fits[, list(x, o$strat)] x.binless <- c("x", "qname", names(o$strat)) } else { x.binless <- c("x", "qname") } qpred <- o$qpred conf.level <- o$conf.level qconf <- c(0, 0.5, 1) + c(1, 0, -1)*(1 - conf.level)/2 if(!is.null(obs$blq) && any(obs$blq)) { if(!is.null(o$strat)) { stratlloq <- c(names(o$strat), "lloq") lloq <- obs[, stratlloq, with = FALSE] lloq <- unique(lloq) obs.fits <- obs.fits[lloq, on = names(o$strat)] } else { obs.fits[, lloq := rep(obs$lloq, len=.N)] } obs.fits[, blq := ifelse(fit < lloq, TRUE, FALSE)] } obs.fits <- setnames(obs.fits[, lapply(.SD, median), by = x.binless], "fit", "y") sim.fits <- setnames(sim.fits, c("fit", "fit.lb", "fit.ub"), c("md", "lo", "hi")) if(!is.null(obs$blq) && any(obs$blq)) { obs.fits[, blq := ifelse(y < lloq, TRUE, FALSE)] obs.fits[, y := ifelse(blq == TRUE, NA, y)] } if (!is.null(o$strat)) { stats <- obs.fits[sim.fits, on = c("x", "qname", names(o$strat))] } else { stats <- obs.fits[sim.fits, on = c("x", "qname")] } if (!is.null(obs$blq) && any(obs$blq)) { if(is.null(o$strat)) { sim[, lloq := rep(obs$lloq, len=.N)] sim[, blq := (y < lloq)] setorder(obs, cols = x) cprop.obs <- obs[, cprop := cumsum(blq) / 1:length(blq)] sic.cprop <- function(llam) { a <- AIC( rqss( cprop ~ qss(x, lambda=exp(llam)), tau=0.5, na.action=na.exclude, data = cprop.obs ), k=-1 ) } llam.med.cprop <- optimize(sic.cprop, interval=c(0, 7))$min med.obs.cprop <- rqss( cprop ~ qss(x, lambda=exp(llam.med.cprop)), tau=0.50, data = cprop.obs ) cprop.obs$med <- fitted(med.obs.cprop) setorder(sim, repl, x)[, cprop := cumsum(blq) / 1:length(blq), by=list(repl)] suppressWarnings(sim[, rqssmed := fitted(rqss(cprop ~ qss(x, lambda = exp(llam.med.cprop)), tau = 0.5, na.action = na.exclude, .SD)), by = .(repl)]) u.x <- unique(cprop.obs$x) med.obs.cprop <- tapply(cprop.obs$med, cprop.obs$x, median) med.sims.blq <- tapply(sim$rqssmed, sim$x, median) med.sims.blq.lb <- tapply(sim$rqssmed, sim$x, quantile, probs=c(qconf[[1]])) med.sims.blq.ub <- tapply(sim$rqssmed, sim$x, quantile, probs=c(qconf[[3]])) pctblq <- data.table(cbind(u.x,med.obs.cprop, med.sims.blq.lb, med.sims.blq, med.sims.blq.ub)) setnames(pctblq, c("x", "y", "lo", "md", "hi")) } else { strat <- o$strat strat.split <- split(obs, strat) strat.split <- strat.split[lapply(strat.split,NROW)>0] x.strat <- c("x", names(strat)) sim[, lloq := rep(obs$lloq, len=.N), by = names(strat)] sim[, blq := (y < lloq)] stratx.binless <- obs[, list(x, o$strat)] stratxrepl <- data.table(stratx.binless, sim[, .(repl)]) strat.split.sim <- split(sim, strat) strat.split.sim <- strat.split.sim[lapply(strat.split.sim,NROW)>0] sic.strat.cprop <- function(llam){ a <- AIC( rqss( cprop ~ qss(x, lambda=exp(llam)), tau=.5, na.action=na.exclude, data = strat.split[[i]] ), k=-1 ) } llam.strat.med.cprop <- vector("list", length(strat.split)) for (i in seq_along(strat.split)) { setorder(strat.split[[i]], cols = x) strat.split[[i]] <- strat.split[[i]][, cprop := cumsum(blq) / 1:length(blq)] llam.strat.med.cprop[[i]] <- strat.split[[i]][, .(llam.med = optimize(sic.strat.cprop, interval=c(0, 7))$min)][,.(med = unlist(llam.med))] strat.split[[i]][, c.rqssmed := fitted(rqss(cprop ~ qss(x, lambda = exp(llam.strat.med.cprop[[i]][[1]])),tau= .5, na.action = na.exclude, data = strat.split[[i]]))] } obs.cprop <- rbindlist(strat.split) obs.cprop <- setnames(obs.cprop[, lapply(.SD, median, na.rm = TRUE), by = x.strat, .SDcols = "c.rqssmed"], "c.rqssmed", "y") for (i in seq_along(strat.split.sim)) { setorder(strat.split.sim[[i]], cols = repl, x) strat.split.sim[[i]] <- strat.split.sim[[i]][, cprop := cumsum(blq) / 1:length(blq), by = .(repl)] strat.split.sim[[i]][, c.rqssmed := fitted(rqss(cprop ~ qss(x, lambda = exp(llam.strat.med.cprop[[i]][[1]])),tau= .5, na.action = na.exclude, .SD)), by = .(repl)] } sim.cprop <- rbindlist(strat.split.sim) sim.med <- setnames(sim.cprop[, lapply(.SD, median, na.rm = TRUE), by = x.strat, .SDcols = "c.rqssmed"], "c.rqssmed", "md") sim.lb <- setnames(sim.cprop[, lapply(.SD, quantile, probs = qconf[[1]]), by = x.strat, .SDcols = "c.rqssmed"], "c.rqssmed", "lo") sim.ub <- setnames(sim.cprop[, lapply(.SD, quantile, probs = qconf[[3]]), by = x.strat, .SDcols = "c.rqssmed"], "c.rqssmed", "hi") pctblq <- obs.cprop[sim.med, on = x.strat] pctblq <- pctblq[sim.lb, on = x.strat] pctblq <- pctblq[sim.ub, on = x.strat] } } else { pctblq <- NULL } update(o, stats = stats, pctblq = pctblq, vpc.type = vpc.type) } bininfo <- function(o, ...) UseMethod("bininfo") bininfo.tidyvpcobj <- function(o, by.strata=o$bin.by.strata, ...) { x <- xmin <- xmax <- bin <- NULL f1 <- function(x) { nobs <- sum(!is.na(x)) xmedian <- median(x, na.rm=TRUE) xmean <- mean(x, na.rm=TRUE) xmin <- min(x, na.rm=TRUE) xmax <- max(x, na.rm=TRUE) xmid <- 0.5*(xmin + xmax) data.table(nobs, xmedian, xmean, xmin, xmax, xmid) } f2 <- function(xmin, xmax) { xmin <- c(xmin, xmax[length(xmax)]) xmax <- c(xmin[1], xmax) breaks <- 0.5*(xmin + xmax) xleft <- breaks[-length(breaks)] xright <- breaks[-1] xcenter <- 0.5*(xleft + xright) data.table(xleft, xright, xcenter) } if (by.strata && !is.null(o$strat)) { bi <- o$obs[, f1(x), by=o$.stratbin] setkeyv(bi, c(names(o$strat), "xmin")) bi[, c(.SD, f2(xmin, xmax)), by=names(o$strat)] } else { bi <- o$obs[, f1(x), by=bin] setkeyv(bi, "xmin") bi <- cbind(bi, bi[, f2(xmin, xmax)]) bi <- bi[unique(o$.stratbin), on="bin"] setkeyv(bi, "xmin") bi[, c(names(o$.stratbin), setdiff(names(bi), names(o$.stratbin))), with=FALSE] } } NULL cut_at <- function(breaks) { breaks <- .check_breaks(breaks) function(x, ..., right=FALSE) { breaks <- .resolve_breaks(breaks, ...) breaks <- sort(unique(breaks)) if (min(x) < min(breaks)) { breaks <- c(min(x), breaks) } if (max(x) > max(breaks)) { breaks <- c(breaks, max(x)) } as.character(cut(x, breaks, include.lowest=TRUE, right=right)) } } nearest <- function(centers) { centers <- .check_centers(centers) function(x, ...) { centers <- .resolve_centers(centers, ...) centers <- sort(unique(centers)) dist <- function(a, b) abs(a - b) d <- outer(x, centers, dist) m <- apply(d, 1, which.min) centers[m] } } bin_by_ntile <- function(nbins) { nbins <- .check_nbins(nbins) function(x, ...) { nbins <- .resolve_nbins(nbins, ...) len <- sum(!is.na(x)) r <- rank(x, ties.method="first", na.last="keep") as.integer(floor(nbins*(r - 1)/len + 1)) } } bin_by_eqcut <- function(nbins) { nbins <- .check_nbins(nbins) function(x, ..., quantile.type=7) { nbins <- .resolve_nbins(nbins, ...) breaks <- quantile(x, probs=seq.int(nbins - 1)/nbins, na.rm=TRUE, type=quantile.type) cut_at(breaks)(x) } } bin_by_pam <- function(nbins) { has_cluster <- requireNamespace("cluster", quietly=TRUE) if (!has_cluster) { stop("Package 'cluster' is required to use the binning method. Please install it.") } nbins <- .check_nbins(nbins) function(x, ...) { nbins <- .resolve_nbins(nbins, ...) centers <- sort(cluster::pam(x, nbins)$medoids) nearest(centers)(x) } } bin_by_classInt <- function(style, nbins=NULL) { has_classInt <- requireNamespace("classInt", quietly=TRUE) if (!has_classInt) { stop("Package 'classInt' is required to use the binning method. Please install it.") } style <- style if (!is.null(nbins)) { nbins <- .check_nbins(nbins) } function(x, ...) { args <- list(var=x, style=style) if (!is.null(nbins)) { nbins <- .resolve_nbins(nbins, ...) args$n <- nbins } args <- c(args, list(...)) if (style %in% c("kmeans", "hclust", "dpih")) { args1 <- args[intersect(names(args), methods::formalArgs(classInt::classIntervals))] args2 <- if (style == "kmeans") { args[intersect(names(args), methods::formalArgs(stats::kmeans))] } else if (style == "hclust") { args[intersect(names(args), methods::formalArgs(stats::hclust))] } else if (style == "dpih") { has_KernSmooth <- requireNamespace("KernSmooth", quietly=TRUE) if (!has_KernSmooth) { stop("Package 'KernSmooth' is required to use the binning method. Please install it.") } args[intersect(names(args), methods::formalArgs(KernSmooth::dpih))] } else { list() } args <- c(args1, args2) } args <- args[!duplicated(args)] breaks <- do.call(classInt::classIntervals, args)$brks cut_at(breaks)(x) } } check_order <- function(obs, sim, tol=1e-5) { if (nrow(sim) %% nrow(obs) != 0) { stop("Rows in sim is not a multiple of rows in obs") } if (is.numeric(obs[[1]])) obs[[1]] <- as.numeric(obs[[1]]) if (is.numeric(sim[[1]])) sim[[1]] <- as.numeric(sim[[1]]) if (is.factor(obs[[1]])) obs[[1]] <- as.character(obs[[1]]) if (is.factor(sim[[1]])) sim[[1]] <- as.character(sim[[1]]) if (!identical(rep(obs[[1]], len=nrow(sim)), sim[[1]])) { stop("ID columns are not identical") } if (!all(abs(rep(obs[[2]], len=nrow(sim)) - sim[[2]]) < tol)) { stop("Time columns are not equal") } nrow(sim) / nrow(obs) } .check_centers <- function(centers) { if (is.data.frame(centers)) { centers <- as.data.table(centers) if (is.null(centers$centers)) { stop("centers data.frame must contain column centers") } if (any(is.na(centers$centers))) { stop("centers cannot contain missing values") } keycols <- setdiff(names(centers), "centers") setkeyv(centers, keycols) } else if (is.numeric(centers)) { if (any(is.na(centers))) { stop("centers cannot contain missing values") } } else { stop("centers must be a numeric vector or data.frame") } centers } .resolve_centers <- function(centers, ...) { if (is.data.table(centers)) { keycols <- key(centers) key <- as.data.table(list(...)[keycols]) centers <- unique(centers[key]$centers) } if (is.null(centers) || !is.numeric(centers) || any(is.na(centers))) { stop("invalid centers") } centers } .check_breaks <- function(breaks) { if (is.data.frame(breaks)) { breaks <- as.data.table(breaks) if (is.null(breaks$breaks)) { stop("breaks data.frame must contain column breaks") } if (any(is.na(breaks$breaks))) { stop("breaks cannot contain missing values") } keycols <- setdiff(names(breaks), "breaks") setkeyv(breaks, keycols) } else if (is.numeric(breaks)) { if (any(is.na(breaks))) { stop("breaks cannot contain missing values") } } else { stop("breaks must be a numeric vector or data.frame") } breaks } .resolve_breaks <- function(breaks, ...) { if (is.data.table(breaks)) { keycols <- key(breaks) key <- as.data.table(list(...)[keycols]) breaks <- breaks[key]$breaks } if (is.null(breaks) || !is.numeric(breaks) || any(is.na(breaks))) { stop("invalid breaks") } breaks } .check_nbins <- function(nbins) { if (is.data.frame(nbins)) { nbins <- as.data.table(nbins) if (is.null(nbins$nbins)) { stop("nbins data.frame must contain column nbins") } if (any(is.na(nbins$nbins))) { stop("nbins cannot contain missing values") } keycols <- setdiff(names(nbins), "nbins") setkeyv(nbins, keycols) } else if (is.numeric(nbins) && length(nbins) == 1) { if (any(is.na(nbins))) { stop("nbins cannot contain missing values") } } else { stop("nbins must be a numeric vector of length 1 or data.frame") } nbins } .resolve_nbins <- function(nbins, ...) { if (is.data.table(nbins)) { keycols <- key(nbins) key <- as.data.table(list(...)[keycols]) nbins <- unique(nbins[key]$nbins) } if (is.null(nbins) || !(is.numeric(nbins) && length(nbins) == 1 && !is.na(nbins))) { stop("nbins must be uniquely determined") } nbins } binlessaugment <- function(o, qpred = c(0.05, 0.50, 0.95), interval = c(0,7), loess.ypc = FALSE, ...) { l.ypc <- strat.split <- y <- NULL qpred <- sort(qpred) obs <- o$obs log <- o$predcor.log if(!is.null(o$strat.split)){ strat.split <- o$strat.split } environment(.autoloess) <- environment() if (loess.ypc) { if (!is.null(o$strat)) { pred <- o$pred obs <- cbind(obs, pred) strat <- o$strat strat.split <- split(obs, strat) strat.split <- strat.split[lapply(strat.split,NROW)>0] loess.mod.strat <- vector("list", length(strat.split)) names(loess.mod.strat) <- names(strat.split) if(isTRUE(o$predcor.log)) { for (i in seq_along(strat.split)) { loess.mod.strat[[i]] <- .autoloess(loess(pred ~ x, span = .5, data = strat.split[[i]])) strat.split[[i]][, lpred := fitted(loess(pred ~ x, span = loess.mod.strat[[i]]$span, na.action = na.exclude))] strat.split[[i]][, l.ypc := (lpred - pred) + y] } } else { for (i in seq_along(strat.split)) { loess.mod.strat[[i]] <- .autoloess(loess(pred ~ x, span = .5, data = strat.split[[i]])) strat.split[[i]][, lpred := fitted(loess(pred ~ x, span = loess.mod.strat[[i]]$span, na.action = na.exclude))] strat.split[[i]][, l.ypc := (lpred/pred) * y] } } span <- .getspan(loess.mod.strat) } else { pred <- o$pred obs <- cbind(obs, pred) loess.mod <- .autoloess(loess(pred ~ x, span = .5, data = obs)) lpred <- fitted(loess.mod$fit) span <- loess.mod$span if (isTRUE(o$predcor.log)) { obs[, l.ypc := (lpred - pred) + y] } else { obs[, l.ypc := (lpred/pred) * y] } } } if(!loess.ypc && !is.null(o$strat)) { strat <- o$strat strat.split <- split(obs, strat) strat.split <- strat.split[lapply(strat.split,NROW)>0] } .sic.strat.ypc <- function(llam, quant) { a <- AIC( rqss( l.ypc ~ qss(x, lambda=exp(llam)), tau=quant, na.action=na.exclude, data = strat.split[[i]] ), k=-1 ) } .sic.strat <- function(llam, quant){ a <- AIC( rqss( y ~ qss(x, lambda=exp(llam)), tau=quant, na.action=na.exclude, data = strat.split[[i]] ), k=-1 ) } .sic.ypc <- function(llam, quant){ a <- AIC( rqss( l.ypc ~ qss(x, lambda=exp(llam)), tau=quant, na.action=na.exclude, data = obs ), k=-1 ) } .sic <- function(llam, quant){ a <- AIC( rqss( y ~ qss(x, lambda=exp(llam)), tau=quant, na.action=na.exclude, data = obs ), k=-1 ) } if(loess.ypc) { if(!is.null(o$strat)){ llamoptimize <- .sic.strat.ypc } else { llamoptimize <- .sic.ypc } } if(!loess.ypc) { span <- NULL if(!is.null(o$strat)) { llamoptimize <- .sic.strat } else { llamoptimize <- .sic } } environment(llamoptimize) <- environment() . <- list if(!is.null(o$strat.split)) { llam.strat.lo <- vector("list", length(strat.split)) llam.strat.med <- vector("list", length(strat.split)) llam.strat.hi <- vector("list", length(strat.split)) for (i in seq_along(strat.split)) { llam.strat.lo[[i]] <- strat.split[[i]][, .(llam.lo = optimize(llamoptimize, quant = qpred[1], interval = interval)$min)][,.(lo = unlist(llam.lo))] names(llam.strat.lo) <- names(strat.split) setnames(llam.strat.lo[[i]], paste0("q", qpred[1])) llam.strat.med[[i]] <- strat.split[[i]][, .(llam.med = optimize(llamoptimize, quant = qpred[2], interval = interval)$min)][,.(med = unlist(llam.med))] names(llam.strat.med) <- names(strat.split) setnames(llam.strat.med[[i]], paste0("q", qpred[2])) llam.strat.hi[[i]] <- strat.split[[i]][, .(llam.hi = optimize(llamoptimize, quant = qpred[3], interval = interval)$min)][,.(hi = unlist(llam.hi))] names(llam.strat.hi) <- names(strat.split) setnames(llam.strat.hi[[i]], paste0("q", qpred[3])) } llam.qpred <- cbind(list(llam.strat.lo, llam.strat.med, llam.strat.hi)) names(llam.qpred) <- paste0("q", qpred) } else { llam.lo <- obs[, .(llam.lo = optimize(llamoptimize, quant = qpred[1], interval = interval)$min)] llam.med <- obs[, .(llam.med = optimize(llamoptimize, quant = qpred[2], interval = interval)$min)] llam.hi <- obs[, .(llam.hi = optimize(llamoptimize, quant = qpred[3], interval = interval)$min)] llam.qpred <- c(llam.lo, llam.med, llam.hi) names(llam.qpred) <- paste0("q", qpred) llam.qpred <- unlist(llam.qpred) } update(o, llam.qpred = llam.qpred, span = span, qpred = qpred, loess.ypc = loess.ypc) } binlessfit <- function(o, conf.level = .95, llam.quant = NULL, span = NULL, ...){ y <- l.ypc <- repl <- NULL . <- list qpred <- o$qpred qnames <- paste0("q", as.character(qpred)) qconf <- c(0, 0.5, 1) + c(1, 0, -1)*(1 - conf.level)/2 obs <- o$obs sim <- o$sim if(isTRUE(o$loess.ypc)) { pred <- o$pred obs <- cbind(obs, pred) sim[, pred := rep(pred, len=.N), by = .(repl)] if(is.null(span)) { span <- o$span } } getllam <- function(qnames, userllam, stratlev) { userllam <- as.data.frame(userllam) userllam <- userllam[, order(names(userllam))] llam.list <- vector("list", length(qnames)) names(llam.list) <- qnames if(stratlev == 2) { for (i in seq_along(llam.list)) { llam.list[[i]] <- list(lambda = userllam[i, 1], lambda = userllam[i,2]) } } if(stratlev == 3) { for (i in seq_along(llam.list)) { llam.list[[i]] <- list(lambda = userllam[i, 1], lambda = userllam[i,2], lambda = userllam[i,3]) } } if(stratlev == 4) { for (i in seq_along(llam.list)) { llam.list[[i]] <- list(lambda = userllam[i, 1], lambda = userllam[i,2], lambda = userllam[i,3], lambda = userllam[i,4]) } } if(stratlev == 5) { for (i in seq_along(llam.list)) { llam.list[[i]] <- list(lambda = userllam[i, 1], lambda = userllam[i,2], lambda = userllam[i,3], lambda = userllam[i,4], lambda = userllam[i,5]) } } names(llam.list[[1]]) <- names(o$strat.split) names(llam.list[[2]]) <- names(o$strat.split) names(llam.list[[3]]) <- names(o$strat.split) return(llam.list) } if(is.null(llam.quant)) { if(is.null(o$llam.qpred)) { stop("Must specify llambda for binlessfit. Include binlessaugment() before running binlessfit() for optimized llambda values using AIC.") } else { llam.qpred <- o$llam.qpred } } else if(!is.null(llam.quant) && !is.null(o$strat)) { stratlev <- lapply(o$strat, unique) stratlev <- length(stratlev[[1]]) llam.qpred <- getllam(qnames, llam.quant, stratlev) } else { llam.qpred <- llam.quant } if(is.null(span)) { if(!is.null(o$span) && isTRUE(o$loess.ypc)) { span <- o$span } else { span <- o$span } } if(!is.null(o$strat)) { strat <- o$strat strat.split <- split(obs, strat) strat.split <- strat.split[lapply(strat.split,NROW)>0] x.strat <- c("x", names(strat)) sim.strat <- sim[, c(names(strat)) := rep(strat, len = .N), by = .(repl)] strat.split.sim <- split(sim, strat) strat.split.sim <- strat.split.sim[lapply(strat.split.sim,NROW)>0] } if(isTRUE(o$loess.ypc) && !is.null(o$strat)) { if(isTRUE(o$predcor.log)) { for(i in seq_along(strat.split)) { strat.split[[i]][, l.ypc := y + (fitted(loess(pred ~ x, span = span[[i]], na.action = na.exclude, .SD)) - pred)] } } else { for(i in seq_along(strat.split)) { strat.split[[i]][, l.ypc := y * (fitted(loess(pred ~ x, span = span[[i]], na.action = na.exclude, .SD)) / pred)] } } obs <- rbindlist(strat.split) o <- update(o, obs = obs) } if(isTRUE(o$loess.ypc) && is.null(o$strat)) { if(isTRUE(o$predcor.log)) { obs[, l.ypc := y + (fitted(loess(pred ~ x, span = span, na.action = na.exclude, .SD)) - pred)] } else { obs[, l.ypc := y * (fitted(loess(pred ~ x, span = span, na.action = na.exclude, .SD)) / pred)] } o <- update(o, obs = obs) } if (is.null(o$strat)) { if (isTRUE(o$loess.ypc)) { rqss.obs.fits <- .fitobs(obs, llam.qpred, qpred, l.ypc = TRUE) if(isTRUE(o$predcor.log)) { rqss.sim.fits <- .fitsim(sim, llam.qpred, span, qpred, qconf, l.ypc = TRUE, log = TRUE) } else { rqss.sim.fits <- .fitsim(sim, llam.qpred, span, qpred, qconf, l.ypc = TRUE) } } else { rqss.obs.fits <- .fitobs(obs, llam.qpred, qpred) rqss.sim.fits <- .fitsim(sim, llam.qpred, qpred = qpred, qconf= qconf) } } if(!is.null(o$strat)){ if(isTRUE(o$loess.ypc)){ if(isTRUE(o$predcor.log)) { rqss.obs.fits <- .fitobs.strat(strat.split = strat.split, x.strat = x.strat, llam.qpred = llam.qpred, qpred = qpred, l.ypc = TRUE) rqss.sim.fits <- .fitsim.strat(strat.split.sim = strat.split.sim, x.strat = x.strat, llam.qpred = llam.qpred, span = span, qpred = qpred, qconf = qconf, l.ypc = TRUE, log = TRUE) } else { rqss.obs.fits <- .fitobs.strat(strat.split = strat.split, x.strat = x.strat, llam.qpred = llam.qpred, qpred = qpred, l.ypc = TRUE) rqss.sim.fits <- .fitsim.strat(strat.split.sim = strat.split.sim, x.strat = x.strat, llam.qpred = llam.qpred, span = span, qpred = qpred, qconf = qconf, l.ypc = TRUE) } } else { rqss.obs.fits <- .fitobs.strat(strat.split = strat.split, x.strat = x.strat, llam.qpred = llam.qpred, qpred = qpred) rqss.sim.fits <- .fitsim.strat(strat.split.sim = strat.split.sim, x.strat = x.strat, llam.qpred = llam.qpred, qpred = qpred, qconf = qconf) } } update(o, rqss.obs.fits = rqss.obs.fits, rqss.sim.fits = rqss.sim.fits, llam.qpred = llam.qpred, span = span, conf.level = conf.level) } .gam_optimize <- function(sp, y, x, data){ suppressWarnings( AIC(gam(y ~ s(x, k = 1), sp = sp, family = "binomial", data = data)) ) } .fitcatgam <- function(y, x, sp){ suppressWarnings( fitted(gam(y ~ s(x, k = 1), family = "binomial", sp = c(sp))) ) } .fitobs <- function(obs, llam.qpred, qpred, l.ypc = FALSE) { rqsslo <- rqssmed <- rqsshi <- NULL qnames <- paste0("q", as.character(qpred)) if(l.ypc) { obs[, rqsslo := fitted(rqss(l.ypc ~ qss(x, lambda = exp(llam.qpred[[1]])), tau = qpred[1], na.action = na.exclude, data = obs))] obs[, rqssmed := fitted(rqss(l.ypc ~ qss(x, lambda = exp(llam.qpred[[2]])), tau = qpred[2], na.action = na.exclude, data = obs))] obs[, rqsshi := fitted(rqss(l.ypc ~ qss(x, lambda = exp(llam.qpred[[3]])), tau = qpred[3], na.action = na.exclude, data = obs))] setnames(obs, c("rqsslo", "rqssmed", "rqsshi"), qnames) obs.fits <- melt(obs, id.vars = "x", measure.vars = qnames) obs.fits <- setnames(obs.fits, c("variable", "value"), c("qname", "fit")) } else { obs[, rqsslo := fitted(rqss(y ~ qss(x, lambda = exp(llam.qpred[[1]])), tau = qpred[1], na.action = na.exclude, data = obs))] obs[, rqssmed := fitted(rqss(y ~ qss(x, lambda = exp(llam.qpred[[2]])), tau = qpred[2], na.action = na.exclude, data = obs))] obs[, rqsshi := fitted(rqss(y ~ qss(x, lambda = exp(llam.qpred[[3]])), tau = qpred[3], na.action = na.exclude, data = obs))] setnames(obs, c("rqsslo", "rqssmed", "rqsshi"), qnames) obs.fits <- melt(obs, id.vars = "x", measure.vars = qnames) obs.fits <- setnames(obs.fits, c("variable", "value"), c("qname", "fit")) } return(obs.fits) } .fitobs.strat <- function(strat.split, x.strat, llam.qpred, qpred, l.ypc = FALSE) { rqsslo <- rqssmed <- rqsshi <- NULL qnames <- paste0("q", as.character(qpred)) if(l.ypc) { for (i in seq_along(strat.split)) { strat.split[[i]][, rqsslo := fitted(rqss(l.ypc ~ qss(x, lambda = exp(llam.qpred[[1]][[i]][[1]])),tau= qpred[1], na.action = na.exclude, data = strat.split[[i]]))] strat.split[[i]][, rqssmed := fitted(rqss(l.ypc ~ qss(x, lambda = exp(llam.qpred[[2]][[i]][[1]])),tau= qpred[2], na.action = na.exclude, data = strat.split[[i]]))] strat.split[[i]][, rqsshi := fitted(rqss(l.ypc ~ qss(x, lambda = exp(llam.qpred[[3]][[i]][[1]])),tau= qpred[3], na.action = na.exclude, data = strat.split[[i]]))] } } else { for (i in seq_along(strat.split)) { strat.split[[i]][, rqsslo := fitted(rqss(y ~ qss(x, lambda = exp(llam.qpred[[1]][[i]][[1]])),tau= qpred[1], na.action = na.exclude, data = strat.split[[i]]))] strat.split[[i]][, rqssmed := fitted(rqss(y ~ qss(x, lambda = exp(llam.qpred[[2]][[i]][[1]])),tau= qpred[2], na.action = na.exclude, data = strat.split[[i]]))] strat.split[[i]][, rqsshi := fitted(rqss(y ~ qss(x, lambda = exp(llam.qpred[[3]][[i]][[1]])),tau= qpred[3], na.action = na.exclude, data = strat.split[[i]]))] } } strat.obs.fits <- rbindlist(strat.split) strat.obs.fits <- setnames(strat.obs.fits, c("rqsslo", "rqssmed", "rqsshi"), qnames) strat.obs.fits <- melt(strat.obs.fits, id.vars = x.strat, measure.vars = qnames) strat.obs.fits <- setnames(strat.obs.fits, c("variable", "value"), c("qname", "fit")) } .fitsim <- function(sim, llam.qpred, span = NULL, qpred, qconf, l.ypc = FALSE, log = FALSE) { . <- list rqsslo <- rqssmed <- rqsshi <- y <- pred <- repl <- NULL qnames <- paste0("q", as.character(qpred)) if(l.ypc) { if(log) { sim[, l.ypc := y + (fitted(loess(pred ~ x, span = span, na.action = na.exclude, .SD)) - pred), by = .(repl)] } else { sim[, l.ypc := y * (fitted(loess(pred ~ x, span = span, na.action = na.exclude, .SD)) / pred), by = .(repl)] } suppressWarnings(sim[, rqsslo := fitted(rqss(l.ypc ~ qss(x, lambda = exp(llam.qpred[[1]])), tau = qpred[1], na.action = na.exclude, .SD)), by = .(repl)]) suppressWarnings(sim[, rqssmed := fitted(rqss(l.ypc ~ qss(x, lambda = exp(llam.qpred[[2]])), tau = qpred[2], na.action = na.exclude, .SD)), by = .(repl)]) suppressWarnings(sim[, rqsshi := fitted(rqss(l.ypc ~ qss(x, lambda = exp(llam.qpred[[3]])), tau = qpred[3], na.action = na.exclude, .SD)), by = .(repl)]) setnames(sim, c("rqsslo", "rqssmed", "rqsshi"), qnames) } else { suppressWarnings(sim[, rqsslo := fitted(rqss(y ~ qss(x, lambda = exp(llam.qpred[[1]])), tau = qpred[1], na.action = na.exclude, .SD)), by = .(repl)]) suppressWarnings(sim[, rqssmed := fitted(rqss(y ~ qss(x, lambda = exp(llam.qpred[[2]])), tau = qpred[2], na.action = na.exclude, .SD)), by = .(repl)]) suppressWarnings(sim[, rqsshi := fitted(rqss(y ~ qss(x, lambda = exp(llam.qpred[[3]])), tau = qpred[3], na.action = na.exclude, .SD)), by = .(repl)]) setnames(sim, c("rqsslo", "rqssmed", "rqsshi"), qnames) } sim.lb <- sim[, lapply(.SD, quantile, probs = qconf[[1]]), by = "x"] sim.lb <- setnames(melt(sim.lb, id.vars = "x", measure.vars = qnames), c("x", "qname", "fit.lb")) sim.ub <- sim[, lapply(.SD, quantile, probs = qconf[[3]]), by = "x"] sim.ub <- setnames(melt(sim.ub, id.vars = "x", measure.vars = qnames), c("x", "qname", "fit.ub")) sim <- sim[, lapply(.SD, median, na.rm = TRUE), by = "x"] sim <- setnames(melt(sim, id.vars = "x", measure.vars = qnames), c("x", "qname", "fit")) sim <- sim[sim.lb, on = c("x", "qname")] sim <- sim[sim.ub, on = c("x", "qname")] } .fitsim.strat <- function(strat.split.sim, x.strat, llam.qpred, span = NULL, qpred, qconf, l.ypc = FALSE, log = FALSE) { . <- list rqsslo <- rqssmed <- rqsshi <- y <- pred <- repl <- NULL qnames <- paste0("q", as.character(qpred)) if(l.ypc) { if(log) { for (i in seq_along(strat.split.sim)) { strat.split.sim[[i]][, l.ypc := y + (fitted(loess(pred ~ x, span = span[[i]], na.action = na.exclude, .SD)) - pred), by = .(repl)] suppressWarnings(strat.split.sim[[i]][, rqsslo := fitted(rqss(l.ypc ~ qss(x, lambda = exp(llam.qpred[[1]][[i]][[1]])), tau = qpred[1], na.action = na.exclude, .SD)), by = .(repl)][,.(fit.lo = unlist(rqsslo))]) suppressWarnings(strat.split.sim[[i]][, rqssmed := fitted(rqss(l.ypc ~ qss(x, lambda = exp(llam.qpred[[2]][[i]][[1]])), tau = qpred[2], na.action = na.exclude, .SD)), by = .(repl)][,.(fit.med = unlist(rqssmed))]) suppressWarnings(strat.split.sim[[i]][, rqsshi := fitted(rqss(l.ypc ~ qss(x, lambda = exp(llam.qpred[[3]][[i]][[1]])), tau = qpred[3], na.action = na.exclude, .SD)), by = .(repl)][,.(fit.hi = unlist(rqsshi))]) } } else { for (i in seq_along(strat.split.sim)) { strat.split.sim[[i]][, l.ypc := y * (fitted(loess(pred ~ x, span = span[[i]], na.action = na.exclude, .SD)) / pred), by = .(repl)] suppressWarnings(strat.split.sim[[i]][, rqsslo := fitted(rqss(l.ypc ~ qss(x, lambda = exp(llam.qpred[[1]][[i]][[1]])), tau = qpred[1], na.action = na.exclude, .SD)), by = .(repl)][,.(fit.lo = unlist(rqsslo))]) suppressWarnings(strat.split.sim[[i]][, rqssmed := fitted(rqss(l.ypc ~ qss(x, lambda = exp(llam.qpred[[2]][[i]][[1]])), tau = qpred[2], na.action = na.exclude, .SD)), by = .(repl)][,.(fit.med = unlist(rqssmed))]) suppressWarnings(strat.split.sim[[i]][, rqsshi := fitted(rqss(l.ypc ~ qss(x, lambda = exp(llam.qpred[[3]][[i]][[1]])), tau = qpred[3], na.action = na.exclude, .SD)), by = .(repl)][,.(fit.hi = unlist(rqsshi))]) } } } else { for (i in seq_along(strat.split.sim)) { suppressWarnings(strat.split.sim[[i]][, rqsslo := fitted(rqss(y ~ qss(x, lambda = exp(llam.qpred[[1]][[i]][[1]])), tau = qpred[1], na.action = na.exclude, .SD)), by = .(repl)][,.(fit.lo = unlist(rqsslo))]) suppressWarnings(strat.split.sim[[i]][, rqssmed := fitted(rqss(y ~ qss(x, lambda = exp(llam.qpred[[2]][[i]][[1]])), tau = qpred[2], na.action = na.exclude, .SD)), by = .(repl)][,.(fit.med = unlist(rqssmed))]) suppressWarnings(strat.split.sim[[i]][, rqsshi := fitted(rqss(y ~ qss(x, lambda = exp(llam.qpred[[3]][[i]][[1]])), tau = qpred[3], na.action = na.exclude, .SD)), by = .(repl)][,.(fit.hi = unlist(rqsshi))]) } } sim <- rbindlist(strat.split.sim) setnames(sim, c("rqsslo", "rqssmed", "rqsshi"), qnames) sim.lb <- sim[, lapply(.SD, quantile, probs = qconf[[1]]), by = x.strat, .SDcols = qnames] sim.lb <- setnames(melt(sim.lb, id.vars = x.strat, measure.vars = qnames), c("variable", "value"), c("qname", "fit.lb")) sim.ub <- sim[, lapply(.SD, quantile, probs = qconf[[3]]), by = x.strat, .SDcols = qnames] sim.ub <- setnames(melt(sim.ub, id.vars = x.strat, measure.vars = qnames), c("variable", "value"), c("qname", "fit.ub")) sim <- sim[, lapply(.SD, median, na.rm = TRUE), by = x.strat, .SDcols = qnames] sim <- setnames(melt(sim, id.vars = x.strat, measure.vars = qnames), c("variable", "value"), c("qname", "fit")) sim <- sim[sim.lb, on = c(x.strat, "qname")] sim <- sim[sim.ub, on = c(x.strat, "qname")] } .aicc.loess <- function(fit){ stopifnot(inherits(fit, 'loess')) n <- fit$n trace <- fit$trace.hat sigma2 <- sum(resid(fit) ^ 2) / (n - 1) return(log(sigma2) + 1 + (2 * (trace + 1)) / (n - trace - 2)) } .autoloess <- function(fit, span=c(.1, .9), ...){ stopifnot(inherits(fit, 'loess')) f <- function(span) .aicc.loess(update(fit, span=span)) opt.fit <- update(fit, span=optimize(f, span)$minimum) opt.span <- optimize(f, span)$minimum return(list(fit=opt.fit, span=opt.span)) } .getspan <- function(x) { span <- vector("list", length(x)) for (i in seq_along(x)) { span[[i]] <- x[[i]]$span } names(span) <- names(x) return(span) } .getfitted <- function(x) { fits <- vector("list", length(x)) for (i in seq_along(x)) { fits[[i]] <- as.data.table(x[[i]]$loess[[1]]$fit$fitted) fits[[i]] <- setnames(fits[[i]], "fitted") } names(fits) <- names(x) return(fits) } .getfit <- function(x) { fit <- vector("list", length(x)) for (i in seq_along(x)) { fit[[i]] <- x[[i]]$loess[[1]]$fit } names(fit) <- names(x) return(fit) } .isCensored <- function(obs) { if(!is.null(obs$blq) && any(obs$blq)){ ret <- TRUE } else if (!is.null(obs$alq) && any(obs$alq)){ ret <- TRUE } else { ret <- FALSE } ret }
"check.monotonicity" <- function(X, minvi = .03, minsize = default.minsize){ X <- check.data(X) N <- nrow(X) J <- ncol(X) m <- max(X) + 1 default.minsize <- ifelse(N > 500, floor(N/10), floor(N/5)) default.minsize <- ifelse(N <= 250, floor(N/3), default.minsize) default.minsize <- ifelse(N < 150, 50, default.minsize) if (N < minsize) stop("Sample size less than Minsize") if (minsize > N/2) stop("Minsize value is too high") R <- as.matrix(X) %*% (matrix(1,J,J) - diag(J)) results <- list() I.labels <- dimnames(X)[[2]] if(length(I.labels)==0) I.labels <- paste("C",1:ncol(X)) for (j in 1:J){ violation.matrix <- matrix(0,nrow=m,ncol=10) dimnames(violation.matrix) <- list(c(paste("P(X >=",1:(m-1),")",sep=""),"Total"), dimnames(violation.matrix)[[2]] <- c(" results[[j]] <- list() results[[j]][1] <- I.labels[j] sorted.R <- sort(R[,j]) group <- max(which(sorted.R==sorted.R[minsize])) repeat{ if(N - max(group) < minsize)break group <- c(group,max(which(sorted.R==sorted.R[minsize+max(group)]))) } group <- group[-length(group)] summary.matrix <- matrix(nrow = length(group)+1,ncol = 4 + 2* m) dimnames(summary.matrix)[[2]] <- c("Group", "Lo Score", "Hi Score", "N", paste("F",0:(m-1)), "Mean", paste("P(X >=",1:(m-1),")",sep="")) summary.matrix[,1] <- 1:nrow(summary.matrix) summary.matrix[,4] <- c(group,N) - c(0,group) group <- c(sorted.R[group],max(sorted.R)) L <- length(group) summary.matrix[,3] <- group summary.matrix[,2] <- c(min(sorted.R),group[-L]+1) member <- apply(1 - outer(R[,j], group, "<="),1,sum) + 1 for (i in 1:L){ Ni <- summary.matrix[i,4] freq <- tabulate(X[member==i,j]+1,m) summary.matrix[i,5:(m+4)] <- freq summary.matrix[i,m+5] <- sum(freq * min(X):max(X)) / Ni cum.freq <- rev(cumsum(rev(freq))/Ni) summary.matrix[i,(m+6):(2*m+4)] <- cum.freq[2:m] } results[[j]][[2]] <- summary.matrix nac <- rep(0,m-1) for (i in 1:(m-1)) nac[i] <- sum(matrix(rep(summary.matrix[,5 + m + i] > 1e-10,L),L,L,byrow=FALSE) * matrix(rep(summary.matrix[,5 + m + i] < .999999999999,L),L,L,TRUE) * upper.tri(matrix(,L,L))) violation.matrix[1:(m-1),1] <- nac violation.matrix[m,1] <- sum(nac) freq <- summary.matrix[,5:(m+4)] for (i in 1:(m-1)){ V <- outer(summary.matrix[,(m+5+i)],summary.matrix[,(m+5+i)],"-") V[row(V) <= col(V)] <- 0 V[V >= -minvi] <- 0 violation.matrix[i,2] <- sum(ceiling(abs(V))) violation.matrix[i,4] <- max(abs(V)) if(violation.matrix[i,4] > minvi){ violation.matrix[i,5] <- sum(abs(V)) freqd <- cbind(apply(as.matrix(freq[,1:i]),1,sum), apply(as.matrix(freq[,(i+1):m]),1,sum)) Z <- abs(sign(-V) * 2 * (sqrt(outer(freqd[,2]+1,freqd[,1]+1)) - sqrt(outer(freqd[,1],freqd[,2]))) / sqrt(outer(freqd[,2],freqd[,1],"+") + outer(freqd[,1],freqd[,2],"+") - 1)) violation.matrix[i,7] <- max(Z) violation.matrix[i,8] <- min(col(Z)[Z==max(Z)]) violation.matrix[i,9] <- min(row(Z)[Z==max(Z)]) violation.matrix[i,10] <- sum(sign(Z[Z > 1.6449])) } } violation.matrix[m,2] <- sum(violation.matrix[1:(m-1),2]) violation.matrix[1:m,3] <- violation.matrix[1:m,2]/violation.matrix[1:m,1] violation.matrix[m,4] <- max(violation.matrix[1:(m-1),4]) violation.matrix[m,5] <- sum(violation.matrix[1:(m-1),5]) violation.matrix[1:m,6] <- violation.matrix[1:m,5]/violation.matrix[1:m,1] violation.matrix[m,7] <- max(violation.matrix[1:(m-1),7]) violation.matrix[m,10] <- sum(violation.matrix[1:(m-1),10]) results[[j]][[3]] <- violation.matrix results[[j]][[4]] <- paste("Minsize = ",minsize," Minvi = ",minvi,sep="") } Hi <- coefHTiny(X)$Hi monotonicity.list <- list(results = results, I.labels = I.labels, Hi = Hi, m = m, X = X) class(monotonicity.list) <- "monotonicity.class" return(monotonicity.list) }
set.seed(100) n <- 180 x <- sample(1:100, n, replace = TRUE) x[70:90] <- sample(110:115, 21, replace = TRUE) x[25] <- 200 x[150] <- 170 df <- data.frame(timestamp = 1:n, value = x) result <- CpPewma( data = df$value, n.train = 5, alpha0 = 0.8, beta = 0.1, l = 3 ) res <- cbind(df, result) PlotDetections(res, title = "PEWMA ANOMALY DETECTOR")
preprocessInputs <- function(data.x, data.z) { nc <- ncol(data.x) if( nc != 3L ) stop("data.x must include {ID, time, delta}.") ncz <- ncol(data.z) if( ncz < 3L ) stop("data.z must include {ID, time, measurement}.") if( !is.integer(data.z[,1L]) ) { data.z[,1L] <- as.integer(round(data.z[,1L],0)) message("Patient IDs in data.z were coerced to integer.\n") } if( !is.integer(data.x[,1L]) ) { data.x[,1L] <- as.integer(round(data.x[,1L],0)) message("Patient IDs in data.x were coerced to integer.\n") } rmRow <- apply(data.z, 1, function(x){all(is.na(x))}) data.z <- data.z[!rmRow,] tst <- is.na(data.z) data.z[tst] <- 0.0 tst <- is.na(data.x[,2L]) data.x <- data.x[!tst,] if( any(data.z[,2L] < {-1.5e-8}) ) { stop("Time is negative in data.z.") } if( any(data.x[,2L] < {-1.5e-8}) ) { stop("Time is negative in data.x.") } return(list(data.x = data.x, data.z = data.z)) }
rlv=function(inpt, krnl){ inpt_chk=ncol(rbind(dim(inpt))) if (length(inpt_chk)==0) { l=length(inpt)+2*krnl imgn0= rep(0,l) imgn1=imgn0 imgn1[(krnl+1):(l-krnl)]=inpt rolv=imgn0 for (i in (krnl+1):(length(imgn0)-krnl)) { ssp0 <- imgn1[(i-(0.5*(krnl-1))):(i+(0.5*(krnl-1)))] ssp0a <- imgn1[(i-1):i] ssp0b <- imgn1[i:(i+1)] if (krnl>1) {vrn0=sd(ssp0)*sd(ssp0) } if (krnl==1) {vrn0a=sd(ssp0a)*sd(ssp0a) vrn0b=sd(ssp0b)*sd(ssp0b) vrn0=max(vrn0a, vrn0b) } rolv[i]=vrn0 } rolVariance=rolv[(krnl+1):(length(rolv)-krnl)] } else if (length(inpt_chk)==1 & inpt_chk==2) { l=nrow(inpt)+2*krnl w=ncol(inpt)+2*krnl imgn0= matrix(rep(0,l*w),nrow=l) imgn1=imgn0 imgn1[(krnl+1):(l-krnl), (krnl+1):(w-krnl)]=inpt rolv=imgn0 for (i in (krnl+1):(nrow(imgn0)-krnl)) { for (j in (krnl+1):(ncol(imgn0)-krnl)) { ssp0 <- imgn1[(i-(0.5*(krnl-1))):(i+(0.5*(krnl-1))), (j-(0.5*(krnl-1))):(j+(0.5*(krnl-1)))] ssp0a <- imgn1[(i-1):i, j:(j+1)] ssp0b <- imgn1[(i-1):i, (j-1):j] ssp0c <- imgn1[i:(i+1), (j-1):j] ssp0d <- imgn1[i:(i+1), j:(j+1)] if (krnl>1) {vrn0=sd(ssp0)*sd(ssp0) } if (krnl==1) {vrn0a=sd(ssp0a)*sd(ssp0a) vrn0b=sd(ssp0b)*sd(ssp0b) vrn0c=sd(ssp0c)*sd(ssp0c) vrn0d=sd(ssp0d)*sd(ssp0d) vrn0=max(vrn0a, vrn0b, vrn0c, vrn0d) } rolv[i,j]=vrn0 } } rolVariance=rolv[(krnl+1):(nrow(rolv)-krnl), (krnl+1):(ncol(rolv)-krnl)] } else if (length(inpt_chk)==1 & inpt_chk==3) { l=nrow(inpt)+2*krnl w=ncol(inpt)+2*krnl h=2*krnl+length(inpt)/(nrow(inpt)*ncol(inpt)) imgn0= array(rep(0,l*w*h),dim=c(l, w, h)) imgn1=imgn0 imgn1[(krnl+1):(l-krnl), (krnl+1):(w-krnl), (krnl+1):(h-krnl)]=inpt rolv=imgn0 for (i in (krnl+1):(l-krnl)) { for (j in (krnl+1):(w-krnl)) { for (k in (krnl+1):(h-krnl)) { ssp0 <- imgn1[(i-(0.5*(krnl-1))):(i+(0.5*(krnl-1))), (j-(0.5*(krnl-1))):(j+(0.5*(krnl-1))), (k-(0.5*(krnl-1))):(k+(0.5*(krnl-1)))] ssp0a <- imgn1[(i-1):i, (j-1):j, (k-1):k] ssp0b <- imgn1[(i-1):i, (j-1):j, k:(k+1)] ssp0c <- imgn1[(i-1):i, j:(j+1), (k-1):k] ssp0d <- imgn1[(i-1):i, j:(j+1), k:(k+1)] ssp0e <- imgn1[i:(i+1), (j-1):j, (k-1):k] ssp0f <- imgn1[i:(i+1), (j-1):j, k:(k+1)] ssp0g <- imgn1[i:(i+1), j:(j+1), (k-1):k] ssp0h <- imgn1[i:(i+1), j:(j+1), k:(k+1)] if (krnl>1) {vrn0=sd(ssp0)*sd(ssp0) } if (krnl==1) {vrn0a=sd(ssp0a)*sd(ssp0a) vrn0b=sd(ssp0b)*sd(ssp0b) vrn0c=sd(ssp0c)*sd(ssp0c) vrn0d=sd(ssp0d)*sd(ssp0d) vrn0e=sd(ssp0e)*sd(ssp0e) vrn0f=sd(ssp0f)*sd(ssp0f) vrn0g=sd(ssp0g)*sd(ssp0g) vrn0h=sd(ssp0h)*sd(ssp0h) vrn0=max(vrn0a, vrn0b, vrn0c, vrn0d, vrn0e, vrn0f, vrn0g, vrn0h) } rolv[i,j,k]=vrn0 } } } rolVariance=rolv[(krnl+1):(l-krnl), (krnl+1):(w-krnl), (krnl+1):(h-krnl)] } return(rolVariance) }
remove_query_string <- function(session = shiny::getDefaultReactiveDomain(), mode = "replace") { shiny::updateQueryString( "?", mode = mode, session = session ) } get_cookie <- function(cookie_string, name) { cookies <- strsplit(cookie_string , split = "; ", fixed = TRUE) tibble::tibble(cookie = unlist(cookies)) %>% tidyr::separate(.data$cookie, into = c("key", "value"), sep = "=", extra = "merge") %>% dplyr::filter(.data$key == name) %>% dplyr::pull("value") } send_invite_checkbox <- function(ns, app_url) { if (!is.null(app_url) && !is.na(app_url) && app_url != "") { email_invite_checkbox <- shinyWidgets::prettyCheckbox( ns("send_invite_email"), "Send Invite Email?", value = FALSE, status = "primary" ) } else { email_invite_checkbox <- tags$div( tags$span( shinyjs::disabled(shinyWidgets::prettyCheckbox( ns("send_invite_email"), "Send Invite Email?", value = FALSE, status = "primary", inline = TRUE )) ), tags$span( style = "display: inline-block; margin-left: -15px;", id = ns("checkbox_question"), icon("question-circle"), `data-toggle` = "tooltip", `data-placement`= "top", title = "You must set the App URL to send email invites. Go to https://dashboard.polished.tech to set your app URL." ) ) } email_invite_checkbox } polished_toast_options <- list( positionClass = "toast-top-center", showDuration = 1000, newestOnTop = TRUE ) is_valid_email <- function(x) { grepl("^\\s*[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}\\s*$", as.character(x), ignore.case=TRUE) } is_email_registered <- function(email) { user_res <- httr::GET( paste0(getOption("polished")$api_url, "/users"), query = list( email = email ), httr::authenticate( user = get_api_key(), password = "" ) ) user_res_content <- jsonlite::fromJSON( httr::content(user_res, "text", encoding = "UTF-8") ) if (!identical(httr::status_code(user_res), 200L)) { print(user_res_content) stop("error checking user registration", .call = FALSE) } if (isTRUE(user_res_content$is_password_set)) { out <- TRUE } else { out <- FALSE } out }
test_that("get_fun", { expect_equal(get_fun(plu_ral), plu_ral) expect_equal(get_fun("plu_ral"), plu_ral) expect_equal(get_fun(plu::ral), plu::ral) expect_equal(get_fun("plu::ral"), plu::ral) }) test_that("get_fun with anonymous function", { expect_equal(get_fun(function(x) {x + 1}), function(x) {x + 1}) }) test_that("get_fun with NULL", { expect_equal(get_fun(NULL), identity) expect_equal(get_fun(NULL, plu_ral), plu_ral) expect_equal(get_fun(NULL, "plu_ral"), plu_ral) expect_equal(get_fun(NULL, plu::ral), plu::ral) expect_equal(get_fun(NULL, "plu::ral"), plu::ral) }) test_that("errors", { expect_error(get_fun(NULL, FALSE)) expect_error(get_fun(plu_not_real_fun), "plu_not_real_fun") expect_error(get_fun("plu_not_real_fun"), "plu_not_real_fun") expect_error(get_fun(plu::not_real_fun), "plu::not_real_fun") expect_error(get_fun("plu::not_real_fun"), "plu::not_real_fun") expect_error(get_fun(NULL, plu_not_real_fun), "plu_not_real_fun") expect_error(get_fun(NULL, "plu_not_real_fun"), "plu_not_real_fun") expect_error(get_fun(NULL, plu::not_real_fun), "plu::not_real_fun") expect_error(get_fun(NULL, "plu::not_real_fun"), "plu::not_real_fun") })
r_prec<-function(r,nlow, nhigh, ci=.95, by=1) { result <- data.frame(matrix(ncol = 5)) colnames(result) <- c("n","r","LL","UL","Precision") for(n in seq(nlow,nhigh, by)){ a<-MBESS::ci.cc(r, n, ci) ll<-a[1] ul<-a[3] precision<-round((as.numeric(ul)-(as.numeric(ll))),4) ll<-round(as.numeric(ll),4) ul<-round(as.numeric(ul),4) result[n, 1]<-n result[n, 2]<-r result[n, 3]<-ll result[n, 4]<-ul result[n, 5]<-precision} output<-na.omit(result) rownames(output)<- c() output}
tfromw <- function(w, s = 1, prior = "laplace", bayesfac = FALSE, a = 0.5) { pr <- substring(prior, 1, 1) if(bayesfac) { z <- 1/w - 2 if(pr == "l"){ if(length(w)>=length(s)) { zz <- z } else { zz <- rep(z, length(s)) } tt <- vecbinsolv(zz, beta.laplace, 0, 10, s = s, a = a) } if(pr == "c") tt <- vecbinsolv(z, beta.cauchy, 0, 10) } else { z <- 0 if(pr == "l"){ zz <- rep(0, max(length(s), length(w))) tt <- vecbinsolv(zz, laplace.threshzero, 0, s*(25+s*a), s = s, w = w, a = a) } if(pr == "c") tt <- vecbinsolv(z, cauchy.threshzero, 0, 10, w = w) } return(tt) }
test_that("PredictionDataRegr", { task = tsk("mtcars") learner = lrn("regr.featureless", predict_type = "se") p = learner$train(task)$predict(task) pdata = p$data expect_s3_class(pdata, "PredictionDataRegr") expect_integer(pdata$row_ids, any.missing = FALSE) expect_numeric(pdata$truth, any.missing = FALSE) expect_numeric(pdata$response, any.missing = FALSE) expect_numeric(pdata$se, any.missing = FALSE) expect_s3_class(c(pdata, pdata), "PredictionDataRegr") expect_prediction(as_prediction(pdata)) expect_equal(as.data.table(p), as.data.table(as_prediction(pdata))) pdata = filter_prediction_data(pdata, row_ids = 1:3) expect_set_equal(pdata$row_ids, 1:3) expect_numeric(pdata$truth, len = 3) expect_numeric(pdata$response, len = 3) })
call_azcopy <- function(..., env=NULL, silent=getOption("azure_storage_azcopy_silent", FALSE)) { silent <- as.logical(silent) args <- as.character(unlist(list(...))) invisible(processx::run(get_azcopy_path(), args, env=env, echo_cmd=!silent, echo=!silent, error_on_status=!silent)) } call_azcopy_from_storage <- function(object, ...) { if(!requireNamespace("processx", quietly=TRUE)) stop("The processx package must be installed to use azcopy", call.=FALSE) auth <- azcopy_auth(object) if(auth$login) on.exit(call_azcopy("logout", silent=TRUE)) invisible(call_azcopy(..., env=auth$env)) } azcopy_upload <- function(container, src, dest, ...) { opts <- azcopy_upload_opts(container, ...) dest_uri <- httr::parse_url(container$endpoint$url) dest_uri$path <- gsub("//", "/", file.path(container$name, dest)) dest <- azcopy_add_sas(container$endpoint, httr::build_url(dest_uri)) call_azcopy_from_storage(container$endpoint, "copy", src, dest, opts) } azcopy_upload_opts <- function(container, ...) { UseMethod("azcopy_upload_opts") } azcopy_upload_opts.blob_container <- function(container, type="BlockBlob", blocksize=2^24, recursive=FALSE, lease=NULL, put_md5=FALSE, ...) { if(!is.null(lease)) warning("azcopy does not support blob leasing at this time", call.=FALSE) c("--blob-type", type, "--block-size-mb", sprintf("%.0f", blocksize/1048576), if(recursive) "--recursive", if(put_md5) "--put-md5") } azcopy_upload_opts.file_share <- function(container, blocksize=2^22, recursive=FALSE, put_md5=FALSE, ...) { c("--block-size-mb", sprintf("%.0f", blocksize/1048576), if(recursive) "--recursive", if(put_md5) "--put-md5") } azcopy_upload_opts.adls_filesystem <- function(container, blocksize=2^24, recursive=FALSE, lease=NULL, put_md5=FALSE, ...) { if(!is.null(lease)) warning("azcopy does not support blob leasing at this time", call.=FALSE) c("--block-size-mb", sprintf("%.0f", blocksize/1048576), if(recursive) "--recursive", if(put_md5) "--put-md5") } azcopy_download <- function(container, src, dest, ...) { opts <- azcopy_download_opts(container, ...) src_uri <- httr::parse_url(container$endpoint$url) src_uri$path <- gsub("//", "/", file.path(container$name, src)) src <- azcopy_add_sas(container$endpoint, httr::build_url(src_uri)) call_azcopy_from_storage(container$endpoint, "copy", src, dest, opts) } azcopy_download_opts <- function(container, ...) { UseMethod("azcopy_download_opts") } azcopy_download_opts.blob_container <- function(container, overwrite=FALSE, recursive=FALSE, check_md5=FALSE, ...) { c(paste0("--overwrite=", tolower(as.character(overwrite))), if(recursive) "--recursive", if(check_md5) c("--check-md5", "FailIfDifferent")) } azcopy_download_opts.file_share <- function(container, overwrite=FALSE, recursive=FALSE, check_md5=FALSE, ...) { c(paste0("--overwrite=", tolower(as.character(overwrite))), if(recursive) "--recursive", if(check_md5) c("--check-md5", "FailIfDifferent")) } azcopy_download_opts.adls_filesystem <- function(container, overwrite=FALSE, recursive=FALSE, check_md5=FALSE, ...) { c(paste0("--overwrite=", tolower(as.character(overwrite))), if(recursive) "--recursive", if(check_md5) c("--check-md5", "FailIfDifferent")) }
rm(list=ls()) require("optimr") sfactor <- 4.0 sbt.f<-function(x){ nn <- length(x) y <- sfactor^(0:(nn - 1)) sum((x - y)^2) } sbt.g<-function(x){ nn <- length(x) y <- sfactor^(0:(nn - 1)) gg<-2.0*(x - y) } n<-4 lower<-rep(0,n) upper<-lower bdmsk<-rep(1,n) y <- sfactor^(0:(n - 1)) upper <- 0.8*y xx <- lower + 0.1*(lower + upper) cat("Rvmmin \n\n") abtrvm <- optimr(xx, sbt.f, sbt.g, lower, upper, method="Rvmmin", control=list(trace=1)) print(abtrvm) alb<-optimr(xx, sbt.f, sbt.g, lower=lower, upper=upper, method="L-BFGS-B", control=list(trace=1)) print(alb) sabtrvm <- optimr(xx, sbt.f, sbt.g, lower, upper, method="Rvmmin", control=list(trace=1, parscale=c(1,4,16,32))) print(sabtrvm) salb<-optimr(xx, sbt.f, sbt.g, lower=lower, upper=upper, method="L-BFGS-B", control=list(trace=1, parscale=c(1,4,16,32))) print(salb) alkkt <- optextras::kktchk(alb$par, sbt.f, sbt.g, hess=NULL, upper=upper, lower=lower, control=list(trace=1)) print(alkkt) salkkt <- optextras::kktchk(salb$par, sbt.f, sbt.g, hess=NULL, upper=upper, lower=lower, control=list(trace=1)) print(salkkt) aallbd <- opm(xx, sbt.f, sbt.g, lower=lower, upper=upper, method="ALL", control=list(trace=0)) print(aallbd) saallbd <- opm(xx, sbt.f, sbt.g, lower=lower, upper=upper, method="ALL", control=list(trace=0, parscale=c(1,4,16,32))) print(saallbd)
test_that("select_vpfiles() returns error on incorrect parameters", { })
`dsxaveraging` <- function(...,w=NULL,maxfocals=10000000){ x=list(...) if (is.null(w)){ w=matrix(1,length(x)); } w=w/sum(w) erg=x[[1]]; acc=maxfocals^(1/length(x)) lbs=list(); ubs=list(); ms=list(); for (i in 1:length(x)){ if(length(x[[i]])[1]>acc){ x[[i]]=dsred(x[[i]],1/acc); } lbs=c(lbs,list(x[[i]][,1])) ubs=c(ubs,list(x[[i]][,2])) ms=c(ms,list(x[[i]][,3])) } tmplo=expand.grid(lbs) tmphi=expand.grid(ubs) tmpms=expand.grid(ms) erg=matrix(0,dim(tmplo)[1],3) erg[,3]=1 for (i in 1:length(x)){ erg[,1]=erg[,1]+w[i]*tmplo[,i] erg[,2]=erg[,2]+w[i]*tmphi[,i] erg[,3]=erg[,3]*tmpms[,i] } erg=dsnorm(erg)$ds; }
knitr::opts_chunk$set( collapse = TRUE, comment = " fig.width = 8, fig.height = 6, fig.align = "center" ) library(dfoliatR) knitr::kable(dmj_h[1:10, 1:10]) knitr::kable(head(dmj_nh, 10)) dmj_defol <- defoliate_trees(host_tree = dmj_h, nonhost_chron = dmj_nh, duration_years = 8, max_reduction = -1.28, list_output = FALSE) knitr::kable(head(dmj_defol, 10)) plot(dmj_defol) knitr::kable(head(defol_stats(dmj_defol), 10)) dmj_obr <- outbreak(dmj_defol, filter_perc = 25, filter_min_series = 3) knitr::kable(head(dmj_obr, 10)) plot_outbreak(dmj_obr) dmj_obr_stats <- outbreak_stats(dmj_obr) knitr::kable(dmj_obr_stats) dmj_interv <- diff(dmj_obr_stats$start) dmj_interv mean(dmj_interv) median(dmj_interv)
"_PACKAGE" release_bullets <- function() { c( "Check that 'test/widget.html' responds to mouse clicks" ) } in_pkgdown <- function() { identical(Sys.getenv("IN_PKGDOWN"), "true") } local_envvar_pkgdown <- function(pkg, scope = parent.frame()) { withr::local_envvar( IN_PKGDOWN = "true", LANGUAGE = pkg$lang, .local_envir = scope ) } local_pkgdown_site <- function(path = NULL, meta = NULL, env = parent.frame()) { if (is.null(path)) { path <- withr::local_tempdir(.local_envir = env) desc <- desc::desc("!new") desc$set("Package", "testpackage") desc$set("Title", "A test package") desc$write(file = file.path(path, "DESCRIPTION")) } if (is.character(meta)) { meta <- yaml::yaml.load(meta) } else if (is.null(meta)) { meta <- list() } pkg <- as_pkgdown(path, meta) clean_up <- function(path) { if (!fs::dir_exists(path)) { return() } fs::dir_delete(path) } if (pkg$development$in_dev) { withr::defer(clean_up(path_dir(pkg$dst_path)), envir = env) } else { withr::defer(clean_up(pkg$dst_path), envir = env) } pkg }
find_housekeeping <- function(data, id_colname, count_column) { data <- data[unlist(lapply(c("Endogenous", "Housekeeping"), grep, x = data[["CodeClass"]])), ] nested_data_df <- tidyr::nest(dplyr::group_by(.data = data, get(id_colname))) colnames(nested_data_df)[1] <- id_colname ratios <- lapply( X = nested_data_df[["data"]], count_column = count_column, FUN = function(.data, count_column) { .data <- .data[, c("Name", count_column)] sample_means <- mean(.data[[count_column]]) ratios <- log2(.data[[count_column]] / sample_means) names(ratios) <- .data[["Name"]] ratios } ) ratios <- do.call("cbind", ratios) ratios_sd <- apply(X = ratios, MARGIN = 1, FUN = stats::sd, na.rm = TRUE) ratios_sd <- sort(ratios_sd, decreasing = FALSE) utils::head(names(ratios_sd), 5) }
orderList <- function(mylist, colindx=1, decreasing=TRUE) { if(decreasing==TRUE){ yt<-as.data.frame(mylist) maxM <- yt[order(yt[,colindx], decreasing=TRUE),] } if(decreasing==FALSE){ yt<-as.data.frame(mylist) maxM <- yt[order(yt[,colindx], decreasing=FALSE),] } return(maxM) }
pluck <- function(x, name, type) { if (missing(type)) { lapply(x, "[[", name) } else { vapply(x, "[[", name, FUN.VALUE = type) } } pluck_names <- function(x, y) { strtrim(strxt(x, paste0(names(y), collapse = "|"))[[1]]) } strxt <- function(string, pattern) { regmatches(string, gregexpr(pattern, string)) } strtrim <- function(str) gsub("^\\s+|\\s+$", "", str) assert <- function(x, y) { if (!is.null(x)) { if (!inherits(x, y)) { stop(deparse(substitute(x)), " must be of class ", paste0(y, collapse = ", "), call. = FALSE) } } } parse_eval <- function(x, y, messy = FALSE) { strg <- if (messy) paste0(x, tolower(y), "_messy") else paste0(x, tolower(y)) res <- tryCatch( eval(parse(text = strg)), error = function(E) E ) if (inherits(res, "error")) { NULL } else { res } } rep_licate <- function(n, expr, type) { vapply(integer(n), eval.parent(substitute(function(...) expr)), type) } has_probs <- function(x) { is.list(x) && is.numeric(x[[1]]) } check4pkg <- function(x) { if (!requireNamespace(x, quietly = TRUE)) { stop("Please install ", x, call. = FALSE) } else { invisible(TRUE) } } `%||%` <- function(x, y) if (is.null(x)) y else x
convert.angle <- function(x, from = c("degrees", "radians"), to = c("radians", "degrees")) { from <- match.arg(from) to <- match.arg(to) x <- switch(from, degrees = x, radians = x * 180 / pi ) result <- switch(to, degrees = x, radians = x * pi / 180 ) as.numeric(result) }
test_that("ci_IQR works", { x <- 1:24 expect_equal(ci_IQR(x)$estimate, IQR(x)) expect_equal(ci_IQR(x, R = 449, seed = 1)$interval, c(7.50000, 16.96167), tolerance = 0.001) expect_equal(ci_IQR(x, R = 449, seed = 1)$interval[2], ci_IQR(x, R = 449, seed = 1, probs = c(0, 0.975))$interval[2]) expect_equal(ci_IQR(x, R = 449, seed = 1, boot_type = "perc")$interval[1], ci_IQR(x, R = 449, seed = 1, boot_type = "perc", probs = c(0.025, 1))$interval[1]) expect_equal(ci_IQR(x, R = 449, seed = 1, boot_type = "norm")$interval[1], ci_IQR(x, R = 449, seed = 1, probs = c(0.025, 1), boot_type = "norm")$interval[1]) }) test_that("ci_mad works", { x <- 1:25 expect_equal(ci_mad(x, R = 449)$estimate, mad(x)) expect_equal(ci_mad(x, R = 449, constant = 1)$estimate, mad(x, constant = 1)) expect_equal(ci_mad(x, R = 449, seed = 1)$interval, c(4.4478, 11.8608), tolerance = 0.001) expect_equal(ci_mad(x, R = 449, seed = 1)$interval[2], ci_mad(x, R = 449, seed = 1, probs = c(0, 0.975))$interval[2]) expect_equal(ci_mad(x, R = 449, seed = 1, boot_type = "perc")$interval[1], ci_mad(x, R = 449, seed = 1, boot_type = "perc", probs = c(0.025, 1))$interval[1]) expect_equal(ci_mad(x, R = 449, seed = 1, boot_type = "norm")$interval[1], ci_mad(x, R = 449, seed = 1, probs = c(0.025, 1), boot_type = "norm")$interval[1]) }) test_that("ci_skewness works", { x <- 1:24 expect_equal(ci_skewness(x, R = 449)$estimate, skewness(x)) expect_equal(ci_skewness(x, R = 449, seed = 1)$interval, c(-0.6166888, 0.5460267), tolerance = 0.001) expect_equal(ci_skewness(x, R = 449, seed = 1)$interval[2], ci_skewness(x, R = 449, seed = 1, probs = c(0, 0.975))$interval[2]) expect_equal(ci_skewness(x, R = 449, seed = 1, boot_type = "perc")$interval[1], ci_skewness(x, R = 449, seed = 1, boot_type = "perc", probs = c(0.025, 1))$interval[1]) expect_equal(ci_skewness(x, R = 449, seed = 1, boot_type = "norm")$interval[1], ci_skewness(x, R = 449, seed = 1, probs = c(0.025, 1), boot_type = "norm")$interval[1]) }) test_that("ci_kurtosis works", { x <- 1:20 expect_equal(ci_kurtosis(x, R = 449)$estimate, kurtosis(x)) expect_equal(ci_kurtosis(x, R = 449, seed = 1)$interval, c(1.354071, 2.476172), tolerance = 0.001) expect_equal(ci_kurtosis(x, R = 449, seed = 1)$interval[2], ci_kurtosis(x, R = 449, seed = 1, probs = c(0, 0.975))$interval[2]) expect_equal(ci_kurtosis(x, R = 449, seed = 1, boot_type = "perc")$interval[1], ci_kurtosis(x, R = 449, seed = 1, boot_type = "perc", probs = c(0.025, 1))$interval[1]) expect_equal(ci_kurtosis(x, R = 449, seed = 1, boot_type = "norm")$interval[1], ci_kurtosis(x, R = 449, seed = 1, probs = c(0.025, 1), boot_type = "norm")$interval[1]) }) test_that("ci_quantile_diff works", { x <- 1:70 y <- 1:20 expect_equal(ci_quantile_diff(x, y, R = 99, seed = 1, q = 0.2)$estimate, quantile(x, 0.2, names = FALSE) - quantile(y, 0.2, names = FALSE)) expect_equal(ci_quantile_diff(x, y, R = 99, seed = 1)$interval, c(15.99780, 35.41227), tolerance = 0.001) expect_equal(ci_quantile_diff(x, y, R = 99, seed = 1)$interval > ci_quantile_diff(x, y, R = 99, seed = 1, q = 0.25)$interval, c(TRUE, TRUE)) expect_equal(ci_quantile_diff(x, y, R = 99, seed = 1, probs = c(0.1, 0.9))$interval < ci_quantile_diff(x, y, R = 99, seed = 1, probs = c(0.1, 0.9), q = 0.75)$interval, c(TRUE, TRUE)) expect_equal(ci_quantile_diff(x, y, R = 99, seed = 1)$interval[2], ci_quantile_diff(x, y, R = 99, seed = 1, probs = c(0, 0.975))$interval[2]) expect_equal(ci_quantile_diff(x, y, R = 99, seed = 1, boot_type = "perc")$interval[1], ci_quantile_diff(x, y, R = 99, seed = 1, boot_type = "perc", probs = c(0.025, 1))$interval[1]) expect_equal(ci_quantile_diff(x, y, R = 99, seed = 1, boot_type = "norm")$interval[1], ci_quantile_diff(x, y, R = 99, seed = 1, probs = c(0.025, 1), boot_type = "norm")$interval[1]) }) test_that("ci_median_diff works", { set.seed(1) x <- runif(10) y <- runif(10) expect_equal(ci_median_diff(x, y, R = 499, seed = 1, probs = c(0.2, 0.8))$estimate, median(x) - median(y)) expect_equal(ci_median_diff(x, y, R = 499, seed = 1)$interval, ci_quantile_diff(x, y, R = 499, seed = 1)$interval) expect_equal(ci_median_diff(x, y, R = 499, seed = 1, boot_type = "perc")$interval, ci_quantile_diff(x, y, R = 499, seed = 1, boot_type = "perc")$interval) })
to_weekly <- function(x, incl_forecast=T, forecast_length=365, diff=T, dayofweek=5) { if(!any(class(x)=="xts")) {stop("x needs to be of class xts")} a <- x[format(as.POSIXlt(zoo::index(x), format = "%m/%d/%Y", origin = as.Date("1970-01-01 00:00.00 UTC")), "%w") == as.character(dayofweek)] if (!incl_forecast) { TheDate <- xts::last(as.Date(zoo::index(x), format = "%m/%d/%Y", origin = as.Date("1970-01-01 00:00.00 UTC"))) - as.numeric(forecast_length) a <- a[paste("/", TheDate, sep = "")] } if (diff) {data_comp <- diff(a)} else {data_comp <- a} return(data_comp) }
graph.bar <-function(x, col=1, nb.plot=15,xmax=NULL, beside=TRUE, xlab=NULL, ...) { out <- data.frame(x$tSI[,col],x$mSI[,col]) rownames(out) <- rownames(x$tSI) if(is.null(xlab)){xlab=colnames(x$tSI)[col]} out <- out[rev(order(out[,1])),] outgraph <- out[rev(1:min(nb.plot,nrow(out))),] if (is.null(xmax)==TRUE){ xmax <- 1.1*max(outgraph) } else { if (xmax>1) {xmax=1} } outnames <- rownames(outgraph) outnames <- gsub("([ ])","",outnames) if(beside==FALSE){ outgraph.2 <- rbind(outgraph[,2],outgraph[,1]-outgraph[,2]) invisible( barplot(outgraph.2, horiz=TRUE, names.arg=outnames, beside=beside, las=2, xlim=c(0,xmax), xlab=xlab, ...)) } else { outgraph.2 <- rbind(outgraph[,1],outgraph[,2]) invisible( barplot(outgraph.2, horiz=TRUE, names.arg=outnames, beside=beside, las=2, xlim=c(0,xmax), xlab=xlab, ...)) } }
library(ggplot2) library(grid) library(gridExtra) library(ddpcr) plotWithLabel <- function(p, label) { labelFont <- gpar(col="black", fontsize=20, fontfamily="Times Roman", fontface="bold") arrangeGrob(p, top = textGrob(label, x = unit(0, "npc"), y = unit(1, "npc"), just = c("left","top"), gp = labelFont)) } plate <- new_plate(data_files = "inst/vignettes-supp/vignette_data_B06_Amplitude.csv") %>% subset("b6") %>% `plate_data<-`(plate_data(.) %>% dplyr::filter(FAM < 11000)) full <- plate_data(plate) ndrops <- nrow(full) top1 <- full %>% dplyr::arrange(desc(HEX)) %>% utils::head(ndrops/100) p <- ggplot(full, aes(HEX, FAM)) + geom_point(alpha = 0.2, size = 2) + theme_classic(15) line <- stats::quantile(full$HEX, .75) + 5*IQR(full$HEX) pline <- p + geom_vline(xintercept = line, linetype = 2) p1 <- pline p2 <- ggplot(full, aes(HEX, FAM)) + geom_point(colour = "white") + theme_classic(15) + geom_point(data = top1, alpha = 0.3, size = 2) line <- stats::quantile(top1$HEX, .75) + 5*IQR(top1$HEX) p2 <- p2 + geom_vline(xintercept = line, linetype = 2) p3 <- p + geom_vline(xintercept = line, linetype = 2) + geom_point(data = top1 %>% dplyr::filter(HEX > 10000), alpha = 0.7, size = 2, colour = "red") p1 <- plotWithLabel(p1, "A") p2 <- plotWithLabel(p2, "B") p3 <- plotWithLabel(p3, "C") png(file.path("inst", "vignettes-supp", "outliers.png"), width = 1000, height = 300) grid.arrange(p1, p2, p3, ncol = 3) dev.off() plate <- new_plate(data_files = "inst/vignettes-supp/vignette_data_B06_Amplitude.csv") %>% subset("b6") %>% `plate_data<-`(plate_data(.) %>% dplyr::filter(FAM < 11000, HEX < 10000)) full <- plate_data(plate) quiet( mixmdl <- mixtools::normalmixEM(full$FAM, k = 2) ) smaller_comp <- mixmdl$mu %>% which.min cutoff <- mixmdl$mu[smaller_comp] + params(plate, 'REMOVE_EMPTY', 'CUTOFF_SD') * mixmdl$sigma[smaller_comp] p <- ggplot(full, aes(HEX, FAM)) + geom_point(alpha = 0.2, size = 2) + theme_classic(15) pline <- p + geom_hline(yintercept = mixmdl$mu) + geom_hline(yintercept = cutoff, linetype = 2) p1 <- ggExtra::ggMarginal(pline, margins = "y") p2 <- ggplot(full %>% dplyr::filter(FAM > cutoff), aes(HEX, FAM)) + geom_point(alpha = 0.2, size = 2) + theme_classic(15) + geom_hline(yintercept = cutoff, linetype = 2) + geom_point(data = full %>% dplyr::filter(FAM < cutoff), colour = "red", alpha=0.2, size = 2) p2 <- ggExtra::ggMarginal(p2, margins = "y", colour = "transparent") p1 <- plotWithLabel(p1, "A") p2 <- plotWithLabel(p2, "B") png(file.path("inst", "vignettes-supp", "empty.png"), width = 700, height = 300) grid.arrange(p1, p2, ncol = 2) dev.off() plate <- new_plate(data_files = "inst/vignettes-supp/vignette_data_B06_Amplitude.csv", type = plate_types$fam_positive_pnpp) %>% subset("b6") %>% `plate_data<-`(plate_data(.) %>% dplyr::filter(FAM < 11000, HEX < 10000)) full_orig <- plate_data(plate) quiet( mixmdl <- mixtools::normalmixEM(full_orig$FAM, k = 2) ) smaller_comp <- mixmdl$mu %>% which.min cutoff <- mixmdl$mu[smaller_comp] + params(plate, 'REMOVE_EMPTY', 'CUTOFF_SD') * mixmdl$sigma[smaller_comp] full <- full_orig %>% dplyr::filter(FAM >= cutoff) mixmdl <- mixtools::normalmixEM(full$FAM, k = 2) larger_comp <- mixmdl$mu %>% which.max filled_border <- mixmdl$mu[larger_comp] - (mixmdl$sigma[larger_comp] * params(plate, 'CLASSIFY', 'CLUSTERS_BORDERS_NUM_SD')) p <- ggplot(full, aes(HEX, FAM)) + geom_point(alpha = 0.2, size = 2) + theme_classic(15) + geom_point(data = full_orig, colour = "transparent") + geom_hline(yintercept = mixmdl$mu[larger_comp]) + geom_hline(yintercept = filled_border, linetype = 2) p1 <- ggExtra::ggMarginal(p, xparams = list(colour = "transparent")) full <- full %>% dplyr::filter(FAM >= filled_border) if (utils::packageVersion("ggplot2") > "2.2.1") { range <- ggplot_build(p)$layout$panel_scales_x[[1]]$range$range } else { range <- ggplot_build(p)$layout$panel_scales$x[[1]]$range$range } dens_smooth <- stats::density(full$HEX) maxima_idx <- local_maxima(dens_smooth$y) minima_idx <- local_minima(dens_smooth$y) left_peak <- dens_smooth$x[maxima_idx][1] minimas <- dens_smooth$x[minima_idx] negative_border <- minimas[which(minimas > left_peak) %>% min] p <- ggplot(full, aes(HEX, FAM)) + geom_point(alpha = 0.2, size = 2) + theme_classic(15) + geom_point(data = full_orig, colour = "transparent") + scale_x_continuous(limits = range) + geom_vline(xintercept = negative_border, linetype = 2) + geom_vline(xintercept = dens_smooth$x[maxima_idx]) p2 <- ggExtra::ggMarginal(p, yparams = list(colour = "transparent")) plate <- new_plate(data_files = "inst/vignettes-supp/vignette_data_B06_Amplitude.csv") %>% subset("b6") %>% `plate_data<-`(plate_data(.) %>% dplyr::filter(FAM < 11000, HEX < 10000)) full <- plate_data(plate) full$colour <- "black" full[full$HEX > negative_border, ]$colour <- "green3" full[full$HEX <= negative_border, ]$colour <- "purple" full[full$FAM <= filled_border, ]$colour <- "blue" full[full$FAM <= cutoff, ]$colour <- "black" p <- ggplot(full, aes(HEX, FAM)) + geom_point(alpha = 0.3, size = 2, colour = full$colour) + theme_classic(15) + geom_hline(yintercept = c(cutoff, filled_border), linetype = 2, alpha = 0.5) + geom_vline(xintercept = negative_border, linetype = 2, alpha = 0.5) p3 <- ggExtra::ggMarginal(p, colour = "transparent") p1 <- plotWithLabel(p1, "A") p2 <- plotWithLabel(p2, "B") p3 <- plotWithLabel(p3, "C") png(file.path("inst", "vignettes-supp", "gating.png"), width = 1000, height = 300) grid.arrange(p1, p2, p3, ncol = 3) dev.off()
setMethod("ncol<-", signature('BasicRaster', 'numeric'), function(x, ..., value) { dim(x) <- c(nrow(x), value) return(x) } ) setMethod("nrow<-", signature('BasicRaster', 'numeric'), function(x, ..., value) { dim(x) <- c(value, ncol(x)) return(x) } ) setMethod("xmin<-", signature('Extent', 'numeric'), function(x, ..., value) { x@xmin <- value return(x) } ) setMethod("xmax<-", signature('Extent', 'numeric'), function(x, ..., value) { x@xmax <- value return(x) } ) setMethod("ymin<-", signature('Extent', 'numeric'), function(x, ..., value) { x@ymin <- value return(x) } ) setMethod("ymax<-", signature('Extent', 'numeric'), function(x, ..., value) { x@ymax <- value return(x) } ) setMethod("xmin<-", signature('BasicRaster', 'numeric'), function(x, ..., value) { x@extent@xmin <- value return(x) } ) setMethod("xmax<-", signature('BasicRaster', 'numeric'), function(x, ..., value) { x@extent@xmax <- value return(x) } ) setMethod("ymin<-", signature('BasicRaster', 'numeric'), function(x, ..., value) { x@extent@ymin <- value return(x) } ) setMethod("ymax<-", signature('BasicRaster', 'numeric'), function(x, ..., value) { x@extent@ymax <- value return(x) } )
iterativeKmeans=function(x,minimum=2,maximum=10,choice=0.5) { n=length(x) if(minimum<2) { stop("Error: clustering must divide data in at least 2 clusters (minimum must value at least 2)") } if(maximum>=n) { stop("Error: clustering must divide data in as much as n-1 clusters (maximum value at max is length(x)-1)") } if(maximum<minimum) { stop("Error: maximum value must be greater than minimum") } numClusterings=maximum-minimum+1; k=minimum ss=c() while(k<=maximum) { ss=c(ss,mean(kmeans(x,k,iter.max=20)$withinss)) k=k+1 } diferencias=diff(ss) md=mean(diferencias) optimo=1 for(i in 1:length(diferencias)) { if(diferencias[i]>md) { optimo=i break } } optimo=optimo+minimum-1 kmeans(x,optimo,iter.max=20) }
context("Check LDA_TS functions") data(rodents) lda_data <- rodents$document_term_table document_covariate_table <- rodents$document_covariate_table mod0 <- LDA_TS(rodents, topics = 2, nseeds = 1, formulas = ~ 1, nchangepoints = 0, timename = "newmoon", control = list(nit = 10)) mod1 <- LDA_TS(rodents, topics = 2, nseeds = 1, formulas = ~ 1, nchangepoints = 1, timename = "newmoon", control = list(nit = 50)) test_that("LDA_TS on 0 changepoints", { expect_is(mod0, "LDA_TS") expect_equal(length(names(mod0)), 4) expect_is(mod0[[4]], "TS_fit") }) test_that("LDA_TS on 1 changepoints", { expect_is(mod1, "LDA_TS") expect_equal(length(names(mod1)), 4) expect_is(mod1[[4]], "TS_fit") }) test_that("check print on LDA_TS", { expect_output(print(mod1)) }) test_that("Check LDA_TS_controls_list", { expect_is(LDA_TS_control(), "list") expect_equal(length(LDA_TS_control()), 3) }) test_that("Check conform_LDA_TS_data", { expect_is(conform_LDA_TS_data(rodents), "list") expect_is(conform_LDA_TS_data(rodents[[1]]), "list") expect_message(conform_LDA_TS_data(rodents[[1]])) expect_error(conform_LDA_TS_data(list(term1 = 1, term2 = 2))) expect_is(conform_LDA_TS_data(list(term = rodents[[1]])), "list") expect_message(conform_LDA_TS_data(list(term = rodents[[1]]))) expect_error(conform_LDA_TS_data(list(term = rodents[[1]], covariate1 = 1, covariate2 = 2))) expect_error(conform_LDA_TS_data("ok")) }) test_that("Check package_LDA_TS", { topics <- 2 nseeds <- 1 formulas <- ~ 1 nchangepoints <- 1 weights <- document_weights(lda_data) timename <- "newmoon" control <- LDA_TS_control(nit = 50) LDAs <- LDA_set(lda_data, topics, nseeds, control$LDA_set_control) sel_LDA <- select_LDA(LDAs, control$LDA_set_control) TSs <- TS_on_LDA(sel_LDA, document_covariate_table, formulas, nchangepoints, timename, weights, control$TS_control) sel_TSs <- select_TS(TSs, control$TS_control) expect_is(package_LDA_TS(LDAs, sel_LDA, TSs, sel_TSs), "LDA_TS") expect_equal(length(package_LDA_TS(LDAs, sel_LDA, TSs, sel_TSs)), 4) expect_error(package_LDA_TS()) expect_error(package_LDA_TS("ok", sel_LDA, TSs, sel_TSs)) expect_error(package_LDA_TS(LDAs, "ok", TSs, sel_TSs)) expect_error(package_LDA_TS(LDAs, sel_LDA, "ok", sel_TSs)) expect_error(package_LDA_TS(LDAs, sel_LDA, TSs, "ok")) })
.bridge.sampler.warp3 <- function( samples_4_fit, samples_4_iter, neff, log_posterior, ..., data, lb, ub, transTypes, param_types, cores, repetitions, packages, varlist, envir, rcppFile, maxiter, silent, verbose, r0, tol1, tol2) { if (is.null(neff)) neff <- nrow(samples_4_iter) n_post <- nrow(samples_4_iter) m <- apply(samples_4_fit, 2, mean) V_tmp <- cov(samples_4_fit) V <- as.matrix(nearPD(V_tmp)$mat) L <- t(chol(V)) q12 <- dmvnorm((samples_4_iter - matrix(m, nrow = n_post, ncol = length(m), byrow = TRUE)) %*% t(solve(L)), sigma = diag(ncol(samples_4_fit)), log = TRUE) q22 <- vector(mode = "list", length = repetitions) gen_samples <- vector(mode = "list", length = repetitions) for (i in seq_len(repetitions)) { gen_samples[[i]] <- rmvnorm(n_post, sigma = diag(ncol(samples_4_fit))) colnames(gen_samples[[i]]) <- colnames(samples_4_iter) q22[[i]] <- dmvnorm(gen_samples[[i]], sigma = diag(ncol(samples_4_fit)), log = TRUE) } e <- as.brob( exp(1) ) q21 <- vector(mode = "list", length = repetitions) if (cores == 1) { q11 <- log(e^(apply(.invTransform2Real(samples_4_iter, lb, ub, param_types), 1, log_posterior, data = data,...) + .logJacobian(samples_4_iter, transTypes, lb, ub)) + e^(apply(.invTransform2Real(matrix(2*m, nrow = n_post, ncol = length(m), byrow = TRUE) - samples_4_iter, lb, ub, param_types), 1, log_posterior, data = data, ...) + .logJacobian(matrix(2*m, nrow = n_post, ncol = length(m), byrow = TRUE) - samples_4_iter, transTypes, lb, ub))) for (i in seq_len(repetitions)) { q21[[i]] <- log(e^(apply(.invTransform2Real(matrix(m, nrow = n_post, ncol = length(m), byrow = TRUE) - gen_samples[[i]] %*% t(L), lb, ub, param_types), 1, log_posterior, data = data, ...) + .logJacobian(matrix(m, nrow = n_post, ncol = length(m), byrow = TRUE) - gen_samples[[i]] %*% t(L), transTypes, lb, ub)) + e^(apply(.invTransform2Real(matrix(m, nrow = n_post, ncol = length(m), byrow = TRUE) + gen_samples[[i]] %*% t(L), lb, ub, param_types), 1, log_posterior, data = data, ...) + .logJacobian(matrix(m, nrow = n_post, ncol = length(m), byrow = TRUE) + gen_samples[[i]] %*% t(L), transTypes, lb, ub))) } } else if (cores > 1) { if ( .Platform$OS.type == "unix") { split1a <- .split_matrix(matrix=.invTransform2Real(samples_4_iter, lb, ub, param_types), cores=cores) split1b <- .split_matrix(matrix=.invTransform2Real( matrix(2*m, nrow = n_post, ncol = length(m), byrow = TRUE) - samples_4_iter, lb, ub, param_types ), cores=cores) q11a <- parallel::mclapply(split1a, FUN = function(x) apply(x, 1, log_posterior, data = data, ...), mc.preschedule = FALSE, mc.cores = cores) q11b <- parallel::mclapply(split1b, FUN = function(x) apply(x, 1, log_posterior, data = data, ...), mc.preschedule = FALSE, mc.cores = cores) q11 <- log(e^(unlist(q11a) + .logJacobian(samples_4_iter, transTypes, lb, ub)) + e^(unlist(q11b) + .logJacobian(matrix(2*m, nrow = n_post, ncol = length(m), byrow = TRUE) - samples_4_iter, transTypes, lb, ub))) for (i in seq_len(repetitions)) { tmp_mat2 <- gen_samples[[i]] %*% t(L) split2a <- .split_matrix(matrix=.invTransform2Real( matrix(m, nrow = n_post, ncol = length(m), byrow = TRUE) - tmp_mat2, lb, ub, param_types ), cores=cores) split2b <- .split_matrix(matrix=.invTransform2Real( matrix(m, nrow = n_post, ncol = length(m), byrow = TRUE) + tmp_mat2, lb, ub, param_types ), cores=cores) q21a <- parallel::mclapply(split2a, FUN = function(x) apply(x, 1, log_posterior, data = data, ...), mc.preschedule = FALSE, mc.cores = cores) q21b <- parallel::mclapply(split2b, FUN = function(x) apply(x, 1, log_posterior, data = data, ...), mc.preschedule = FALSE, mc.cores = cores) q21[[i]] <- log(e^(unlist(q21a) + .logJacobian(matrix(m, nrow = n_post, ncol = length(m), byrow = TRUE) - tmp_mat2, transTypes, lb, ub)) + e^(unlist(q21b) + .logJacobian(matrix(m, nrow = n_post, ncol = length(m), byrow = TRUE) + tmp_mat2, transTypes, lb, ub))) } } else { cl <- parallel::makeCluster(cores, useXDR = FALSE) sapply(packages, function(x) parallel::clusterCall(cl = cl, "require", package = x, character.only = TRUE)) parallel::clusterExport(cl = cl, varlist = varlist, envir = envir) if ( ! is.null(rcppFile)) { parallel::clusterExport(cl = cl, varlist = "rcppFile", envir = parent.frame()) parallel::clusterCall(cl = cl, "require", package = "Rcpp", character.only = TRUE) parallel::clusterEvalQ(cl = cl, Rcpp::sourceCpp(file = rcppFile)) } else if (is.character(log_posterior)) { parallel::clusterExport(cl = cl, varlist = log_posterior, envir = envir) } q11 <- log(e^(parallel::parRapply(cl = cl, x = .invTransform2Real(samples_4_iter, lb, ub, param_types), log_posterior, data = data, ...) + .logJacobian(samples_4_iter, transTypes, lb, ub)) + e^(parallel::parRapply(cl = cl, x = .invTransform2Real(matrix(2*m, nrow = n_post, ncol = length(m), byrow = TRUE) - samples_4_iter, lb, ub, param_types), log_posterior, data = data, ...) + .logJacobian(matrix(2*m, nrow = n_post, ncol = length(m), byrow = TRUE) - samples_4_iter, transTypes, lb, ub))) for (i in seq_len(repetitions)) { q21[[i]] <- log(e^(parallel::parRapply(cl = cl, x = .invTransform2Real(matrix(m, nrow = n_post, ncol = length(m), byrow = TRUE) - gen_samples[[i]] %*% t(L), lb, ub, param_types), log_posterior, data = data, ...) + .logJacobian(matrix(m, nrow = n_post, ncol = length(m), byrow = TRUE) - gen_samples[[i]] %*% t(L), transTypes, lb, ub)) + e^(parallel::parRapply(cl = cl, x = .invTransform2Real(matrix(m, nrow = n_post, ncol = length(m),byrow = TRUE) + gen_samples[[i]] %*% t(L), lb, ub, param_types), log_posterior, data = data, ...) + .logJacobian(matrix(m, nrow = n_post, ncol = length(m), byrow = TRUE) + gen_samples[[i]] %*% t(L), transTypes, lb, ub))) } parallel::stopCluster(cl) } } if (any(is.infinite(q11))) { warning(sum(is.infinite(q11)), " of the ", length(q11)," log_prob() evaluations on the warp-transformed posterior draws produced -Inf/Inf.", call. = FALSE) } for (i in seq_len(repetitions)) { if (any(is.infinite(q21[[i]]))) { warning(sum(is.infinite(q21[[i]])), " of the ", length(q21[[i]])," log_prob() evaluations on the warp-transformed proposal draws produced -Inf/Inf.", call. = FALSE) } } if (any(is.na(q11))) { warning(sum(is.na(q11)), " evaluation(s) of log_prob() on the warp-transformed posterior draws produced NA and have been replaced by -Inf.", call. = FALSE) q11[is.na(q11)] <- -Inf } for (i in seq_len(repetitions)) { if (any(is.na(q21[[i]]))) { warning(sum(is.na(q21[[i]])), " evaluation(s) of log_prob() on the warp-transformed proposal draws produced NA nd have been replaced by -Inf.", call. = FALSE) q21[[i]][is.na(q21[[i]])] <- -Inf } } if(verbose) { print("summary(q12): (log_dens of proposal for posterior samples)") print(summary(q12)) print("summary(q22): (log_dens of proposal for generated samples)") print(lapply(q22, summary)) print("summary(q11): (log_dens of posterior for posterior samples)") print(summary(q11)) print("summary(q21): (log_dens of posterior for generated samples)") print(lapply(q21, summary)) } logml <- numeric(repetitions) niter <- numeric(repetitions) for (i in seq_len(repetitions)) { tmp <- .run.iterative.scheme(q11 = q11, q12 = q12, q21 = q21[[i]], q22 = q22[[i]], r0 = r0, tol = tol1, L = L, method = "warp3", maxiter = maxiter, silent = silent, criterion = "r", neff = neff) if (is.na(tmp$logml) & !is.null(tmp$r_vals)) { warning("logml could not be estimated within maxiter, rerunning with adjusted starting value. \nEstimate might be more variable than usual.", call. = FALSE) lr <- length(tmp$r_vals) r0_2 <- sqrt(tmp$r_vals[[lr - 1]] * tmp$r_vals[[lr]]) tmp <- .run.iterative.scheme(q11 = q11, q12 = q12, q21 = q21[[i]], q22 = q22[[i]], r0 = r0_2, tol = tol2, L = L, method = "warp3", maxiter = maxiter, silent = silent, criterion = "logml", neff = neff) tmp$niter <- maxiter + tmp$niter } logml[i] <- tmp$logml niter[i] <- tmp$niter if (niter[i] == maxiter) warning("logml could not be estimated within maxiter, returning NA.", call. = FALSE) } if (repetitions == 1) { out <- list(logml = logml, niter = niter, method = "warp3", q11 = q11, q12 = q12, q21 = q21[[1]], q22 = q22[[1]]) class(out) <- "bridge" } else if (repetitions > 1) { out <- list(logml = logml, niter = niter, method = "warp3", repetitions = repetitions) class(out) <- "bridge_list" } return(out) }
pubtator_tables <- function(){ c( "chemical" = "chemical2pubtator", "disease" = "disease2pubtator", "gene" = "gene2pubtator", "mutation" = "mutation2pubtator", "species" = "species2pubtator" ) }
parini <- function(d, x, k, n, guess, lapses, psyfun) { calculate_parini <- function(d, x, k, n, guess, lapses, psyfun) { ntrials <- unique(d[[n]]) yq <- d[[k]] / d[[n]] if (is.numeric(guess) && is.numeric(lapses)) { gue <- guess lap <- lapses } if (is.logical(guess) && is.logical(lapses)) { if (guess && lapses) { gue <- min(yq) lap <- 1 - max(yq) } } if (is.logical(guess) && is.numeric(lapses)) { lap <- lapses if (guess) gue <- min(yq) if (!guess) gue <- 0 } if (is.numeric(guess) && is.logical(lapses)) { gue <- guess if (lapses) lap <- 1 - max(yq) if (!lapses) lap <- 0 } y01 <- (yq - gue) / (1 - gue - lap) datp <- data.frame(x = d[[x]], y01) datp <- datp %>% mutate(y01 = ifelse(y01 == 1, 1 - 1 / (2 * ntrials), y01)) %>% mutate(y01 = ifelse(y01 == 0, 1 / (2 * ntrials), y01)) dat <- filter(datp, y01 > 0, y01 <1) dat$z <- qnorm(dat$y01) coef <- lm(z~x, data = dat)$coefficients if (coef[[2]] == 0) { p1 <- median(dat$x) p2 <- (1 - gue - lap) / (max(dat$x)-min(dat$x)) } else { p1 <- -coef[[1]] / coef[[2]] p2 <- 1 / coef[[2]] } if (psyfun == 'logistic_fun') p2 <- 1 / p2 if (psyfun == 'weibull_fun') p2 <- 1 / p2 if (is.numeric(guess) && is.numeric(lapses)) para <- c(p1, p2) if (is.logical(guess) && is.logical(lapses)) { if (guess && lapses) para <- c(p1, p2, gue, lap) if (!guess && !lapses) para <- c(p1, p2) } if (is.logical(guess) && is.numeric(lapses)) { if (guess) para <- c(p1, p2, gue) if (!guess) para <- c(p1, p2) } if (is.numeric(guess) && is.logical(lapses)) { if (lapses) para <- c(p1, p2, lap) if (!lapses) para <- c(p1, p2) } data.frame(paran = paste0('p', seq(1, length(para))), par = para) } d %>% do(calculate_parini(., x, k, n, guess, lapses, psyfun)) }
new_list_end_node <- function() { structure(list(), class = c("list_end_node", "node", "list")) } new_setmap_end_node <- function() { structure(list(), class = c("setmap_end_node", "node")) } new_set_node <- function(x) { structure(list( type = "set", value = x ), class = c("set_node", "node")) } new_vector_end_node <- function() { structure(list(), class = c("vector_end_node", "node")) } new_r_symbol <- function(value) { stopifnot(startsWith(value, "r/")) structure(value, class = c("r_name")) } new_symbol_node <- function(value) { as.symbol(value) } new_keyword_node <- function(value) { structure(as.character(value), class = c("keyword_node", "node", "character")) } new_symbolic_value_node <- function(value) { value <- match.arg(value, c(" switch( value, ` ` ` ) } default_print <- function(x, ...) { cat(format(x, ...), "\n") } format.keyword_node <- function(x, ...) { x } print.keyword_node <- default_print
test_that("create_APCsummary", { testthat::skip_if_not_installed("mgcv") library(mgcv) data(travel) model <- gam(mainTrip_distance ~ te(period, age) + household_size + residence_region, data = travel) model_list <- list("Model A" = model, "Model B" = model) apc_range <- list("age" = 30:60, "period" = 1980:2000, "cohort" = 1930:1970) res <- create_APCsummary(model_list, dat = travel, digits = 4, apc_range = apc_range) expect_s3_class(res, "knitr_kable") expect_error(create_APCsummary(model)) tab <- APCtools:::create_oneAPCsummaryTable(model, dat = travel, apc_range = apc_range) expect_s3_class(tab, "data.frame") expect_identical(tab$effect, c("age","period","cohort")) }) test_that("create_modelSummary", { testthat::skip_if_not_installed("mgcv") library(mgcv) data(travel) model <- bam(mainTrip_distance ~ te(period, age) + household_size + residence_region, data = travel) model_logLink <- gam(mainTrip_distance ~ te(period, age) + s(household_income) + household_size + residence_region, family = Gamma(link = "log"), data = travel) model_list <- list("Model A" = model, "Model B" = model_logLink) res <- create_modelSummary(model_list, digits = 4) expect_length(res, 2) expect_s3_class(res[[1]], "knitr_kable") expect_s3_class(res[[2]], "knitr_kable") tab1 <- APCtools:::extract_summary_linearEffects(model) tab2 <- APCtools:::extract_summary_linearEffects(model_logLink) expect_s3_class(tab1, "data.frame") expect_s3_class(tab2, "data.frame") expect_identical(colnames(tab1)[1:3], c("param","coef","se")) expect_identical(colnames(tab2)[1:3], c("param","coef","se")) })
base.learners = list( makeLearner("classif.ksvm"), makeLearner("classif.randomForest"), makeLearner("classif.gbm") ) mplexer = makeModelMultiplexer(base.learners) par.set = makeModelMultiplexerParamSet(mplexer, classif.randomForest = makeParamSet( makeIntegerParam("ntree", lower = 10, upper = 500), makeIntegerParam("mtry", lower = 1, upper = 20) ), classif.gbm = makeParamSet( makeIntegerParam("n.trees", lower = 100L, upper = 5000L), makeIntegerParam("interaction.depth", lower = 1L, upper = 4L), makeNumericParam("shrinkage", lower = 1e-5, upper = 1e-1) ), classif.ksvm = makeParamSet( makeNumericParam("C", lower = -12, upper = 12, trafo = function(x) 2^x), makeNumericParam("sigma", lower = -12, upper = 12, trafo = function(x) 2^x) ) )
permRQ = function(target, dataset, xIndex, csIndex, wei = NULL, univariateModels=NULL, hash = FALSE, stat_hash=NULL, pvalue_hash=NULL, threshold = 0.05, R = 999) { pvalue = log(1) stat = 0; csIndex[which(is.na(csIndex))] = 0; thres <- threshold * R + 1 if( hash ) { csIndex2 = csIndex[which(csIndex!=0)] csIndex2 = sort(csIndex2) xcs = c(xIndex,csIndex2) key = paste(as.character(xcs) , collapse=" "); if(is.null(stat_hash[key]) == FALSE) { stat = stat_hash[key]; pvalue = pvalue_hash[key]; results <- list(pvalue = pvalue, stat = stat, stat_hash=stat_hash, pvalue_hash=pvalue_hash); return(results); } } if ( !is.na( match(xIndex, csIndex) ) ) { if( hash ) { stat_hash[key] <- 0; pvalue_hash[key] <- 1; } results <- list(pvalue = 1, stat = 0, stat_hash=stat_hash, pvalue_hash=pvalue_hash); return(results); } if ( any(xIndex < 0) || any(csIndex < 0) ) { message(paste("error in testIndRQ : wrong input of xIndex or csIndex")) results <- list(pvalue = pvalue, stat = stat, stat_hash=stat_hash, pvalue_hash=pvalue_hash); return(results); } xIndex = unique(xIndex); csIndex = unique(csIndex); x = dataset[ , xIndex]; cs = dataset[ , csIndex]; if ( length(cs) != 0 ) { if ( is.null(dim(cs)[2]) ) { if (identical(x, cs) ) { if ( hash ) { stat_hash[key] <- 0; pvalue_hash[key] <- 1; } results <- list(pvalue = 1, stat = 0, stat_hash=stat_hash, pvalue_hash=pvalue_hash); return(results); } } else { for (col in 1:dim(cs)[2]) { if (identical(x, cs[, col]) ) { if ( hash ) { stat_hash[key] <- 0; pvalue_hash[key] <- 1; } results <- list(pvalue = 1, stat = 0, stat_hash=stat_hash, pvalue_hash=pvalue_hash); return(results); } } } } res <- tryCatch( { if (length(cs) == 0) { fit1 = quantreg::rq(target ~ 1, weights = wei) fit2 = quantreg::rq(target ~ x, weights = wei) mod = anova(fit1, fit2, test = "rank") stat = as.numeric( mod[[1]][3] ) step <- 0 j <- 1 n <- length(target) while (j <= R & step < thres ) { xb <- sample(x, n) bit2 = quantreg::rq(target ~ xb, weights = wei ) ww = anova(fit1, bit2, test = "rank") step <- step + ( as.numeric( ww[[1]][3] ) > stat ) j <- j + 1 } pvalue <- log( (step + 1) / (R + 1) ) } else { fit1 = quantreg::rq( target ~ cs, weights = wei ) fit2 = quantreg::rq( target ~ cs + x, weights = wei ) mod = anova(fit1, fit2, test = "rank") stat = as.numeric( mod[[1]][3] ) step <- 0 j <- 1 n <- length(target) while (j <= R & step < thres ) { xb <- sample(x, n) bit2 = quantreg::rq(target ~ cs + xb, weights = wei ) ww = anova(fit1, bit2, test = "rank") step <- step + ( as.numeric( ww[[1]][3] ) > stat ) j <- j + 1 } pvalue <- log( (step + 1) / (R + 1) ) } if ( is.na(pvalue) || is.na(stat) ) { pvalue = log(1) stat = 0; } else { if ( hash ) { stat_hash[key] <- stat; pvalue_hash[key] <- pvalue; } } results <- list(pvalue = pvalue, stat = stat, stat_hash=stat_hash, pvalue_hash=pvalue_hash); return(results); }, error=function(cond) { pvalue = log(1) stat = 0; results <- list(pvalue = pvalue, stat = stat, stat_hash=stat_hash, pvalue_hash=pvalue_hash); return(results); }, finally={} ) return(res); }
library(portfolio) load("matchit.test.RData") data(assay) x <- assay x <- assay[assay$country == "USA", c("symbol", "name", "sector", "liq", "on.fl")] all.stocks <- c("76143", "18027", "14730", "6961", "6930", "69571", "71262", "21266", "7308", "11746", "27043", "37495", "74206", "79463", "2923", "8267", "33105", "26322", "68150", "71570", "22101", "19167", "39252", "13776", "83265", "71301", "7631", "29780", "3604", "28225") x <- x[all.stocks,] for(i in names(x)){ if(is.factor(x[[i]])){ x[[i]] <- as.character(x[[i]]) } } test <- portfolio:::.matchit(on.fl ~ sector + liq, data = x) stopifnot( all.equal(dimnames(test)[1], dimnames(truth)[1]), all(mapply(all.equal, test, truth)) ) x.sub <- x[2:15,] test.3 <- portfolio:::.matchit(on.fl ~ sector + liq, data = x.sub) stopifnot( all.equal(dimnames(test.3)[1], dimnames(truth.3)[1]), all.equal(test.3[1,], truth.3[1,]) ) test <- portfolio:::.matchit(on.fl ~ sector, data = x, method = "greedy", exact = "sector") test <- test[sort(row.names(test)), , drop = FALSE] stopifnot(all.equal(test, truth.4), all.equal(table(x$sector[x$on.fl]), table(x[test,"sector"])) ) set.seed(1) x$foo.1 <- c("a","a","b") x$foo.2 <- c("a","b") test <- portfolio:::.matchit(treat.var = "on.fl", data = x, method = "random", n.matches = 10, exact = c("foo.1","foo.2")) x.treat <- x[x$on.fl,] for(i in 1:ncol(test)){ x.matched <- x[test[,1],] stopifnot(all.equal(table(x.treat$foo.1, x.treat$foo.2), table(x.matched$foo.1, x.matched$foo.2))) } x <- portfolio:::.data.prep(treat.var = "on.fl", c("sector", "country"), x) stopifnot(is.factor(assay$sector), is.factor(assay$country))
x <- sample(1:150) data(iris) iris2 <- iris[x, ] iris2[1,"Sepal.Length"] <- iris2[1:3, "Sepal.Width"] <- NA out <- simputation::impute_median(iris2, . ~ Species) m.Sepal.Length <- tapply(iris2$Sepal.Length, iris2$Species, median, na.rm=TRUE) expect_equivalent(out[1,"Sepal.Length"], m.Sepal.Length[out[1,"Species"]]) m.Sepal.Width <- tapply(iris2$Sepal.Width, iris2$Species, median, na.rm=TRUE) expect_equivalent(out[1:3,"Sepal.Width"], as.vector(m.Sepal.Width[out[1:3,"Species"]]))
global_filter_elem <- function(type, segmentId = NULL, dateRange = NULL, id = NULL) { if (!is.null(segmentId) && is.na(segmentId)) segmentId <- NULL if (!is.null(dateRange) && is.na(dateRange)) dateRange <- NULL if (type == "daterange" && is.null(dateRange)) stop("Missing daterange in global filter element", call. = FALSE) if (type == "segment" && is.null(segmentId)) stop("Missing segment ID in global filter element", call. = FALSE) if (is.null(segmentId) && is.null(dateRange)) stop("No content for global filter element", call. = FALSE) if (!is.null(segmentId) && !is.null(dateRange)) stop("Only one of segmentId or dateRange may be specified in global filter element", call. = FALSE) purrr::compact(list( id = id, type = type, segmentId = segmentId, dateRange = dateRange )) } global_filter <- function(type, segmentId = NULL, dateRange = NULL) { items <- purrr::compact(list(type = type, segmentId = segmentId, dateRange = dateRange)) purrr::pmap(items, global_filter_elem) } req_settings <- function(limit, page, nonesBehavior, ...) { assertthat::assert_that( is.numeric(limit), is.numeric(page), is.character(nonesBehavior), nonesBehavior %in% c("return-nones", "exclude-nones") ) list( limit = limit, page = page, nonesBehavior = nonesBehavior, ... ) } metric_elem <- function(id, columnId, filters = NULL, sort = NULL) { assertthat::assert_that( is.character(id), is.character(columnId) ) if (!is.null(filters)) { assertthat::assert_that( is.character(filters) ) filters <- I(filters) } if (!is.null(sort)) { if (is.na(sort)) sort <- NULL else sort <- match.arg(sort, c("asc", "desc")) } purrr::compact(list( id = id, columnId = columnId, filters = filters, sort = sort )) } metric_elems <- function(id, columnId, filters = NULL, sort = NULL) { if (!is.null(filters) & length(filters) > 1 & !is.list(filters)) { id_len <- length(id) filters <- list(filters)[rep(1, id_len)] } elems <- purrr::compact(list( id = id, columnId = columnId, filters = filters, sort = sort )) purrr::pmap(elems, metric_elem) } metric_filters <- function(type, dimension = NULL, itemId = NULL, dateRange = NULL, segmentId = NULL) { if (length(dimension) != length(itemId)) { stop("Mismatch between dimensions and itemIds in metric filter") } stopifnot(length(dateRange) <= 1) stopifnot(length(type) == length(c(dimension, dateRange, segmentId))) dr <- data.frame( id = type[type == "dateRange"], type = type[type == "dateRange"], dateRange = dateRange ) dims <- data.frame( id = dimension, type = type[type == "breakdown"], dimension = dimension, itemId = itemId ) segs <- data.frame( id = segmentId, type = type[type == "segment"], segmentId = segmentId ) dplyr::bind_rows(dr, dims, segs) } metric_container <- function(metrics, metricIds, sort, dimensions = NULL, itemIds = NULL, segmentIds = NULL, dateRange = NULL) { sort <- na_fill_vec(sort, len = length(metrics)) metrics[!is_calculated_metric(metrics)] <- paste("metrics", metrics[!is_calculated_metric(metrics)], sep = "/") if (!is.null(dimensions)) { dimensions <- paste("variables", dimensions, sep = "/") } filter_segids <- unique(unlist(segmentIds)) filter_segids <- filter_segids[!is.na(filter_segids)] type <- c( rep("dateRange", length(dateRange)), rep("breakdown", length(dimensions)), rep("segment", length(filter_segids)) ) met_filters <- metric_filters( type = type, dimension = dimensions, itemId = itemIds, segmentId = filter_segids, dateRange = dateRange ) if (!is.null(segmentIds)) { stopifnot(length(metrics) == length(segmentIds)) filter_ids <- purrr::map2(metrics, segmentIds, function(met, seg) { met_filters[met_filters$type %in% c("breakdown", "dateRange") | met_filters$segmentId %in% seg, "id"] }) } else { filter_ids <- list(met_filters$id) } mets <- metric_elems(id = metrics, columnId = metricIds, filters = filter_ids, sort = sort) list( metrics = mets, metricFilters = met_filters ) } make_request <- function(rsid, global_filter, dimension, settings, metric_container, search = NULL) { purrr::compact(list( rsid = rsid, globalFilters = global_filter, metricContainer = metric_container, dimension = dimension, settings = settings, search = search )) }