code
stringlengths
1
13.8M
context("testcorr") test_that("Correlation CorrMatCauchy works", { x1 <- runif(5) x2 <- runif(4) th <- c(.05,.9,-.3) th <- runif(3,-1,1) expect_equal(CGGP_internal_CorrMatCauchy(return_numpara=TRUE), 3) expect_error(CGGP_internal_CorrMatCauchy(x1=x1, x2=x2, theta = c(.1,.1))) cauchy1 <- CGGP_internal_CorrMatCauchy(x1=x1, x2=x2, theta=th) expect_is(cauchy1, "matrix") expect_equal(dim(cauchy1), c(5,4)) cauchyfunc <- function(a,b,theta) { expLS <- exp(3*theta[1]) expHE <- exp(3*theta[2]) alpha = 2*exp(3*theta[3]+2)/(1+exp(3*theta[3]+2)) diffmat <- outer(a, b, Vectorize(function(aa,bb) abs(aa-bb))) h = diffmat/expLS halpha = h^alpha pow = -expHE/alpha (1+halpha)^pow } cauchy2 <- cauchyfunc(x1, x2, theta=th) expect_equal(cauchy1, cauchy2, tol=1e-5) cauchy_C_dC <- CGGP_internal_CorrMatCauchy(x1=x1, x2=x2, theta=th, return_dCdtheta=TRUE) eps <- 1e-6 for (i in 1:3) { thd <- c(0,0,0) thd[i] <- eps numdC <- (CGGP_internal_CorrMatCauchy(x1=x1, x2=x2, theta=th+thd) - CGGP_internal_CorrMatCauchy(x1=x1, x2=x2, theta=th-thd)) / (2*eps) expect_equal(numdC, cauchy_C_dC$dCdtheta[,(1+4*i-4):(4*i)], info = paste("theta dimension with error is",i)) } }) test_that("Correlation CorrMatCauchySQT works", { x1 <- runif(5) x2 <- runif(4) th <- c(.05,.9,-.3) th <- runif(3,-1,1) expect_equal(CGGP_internal_CorrMatCauchySQT(return_numpara=TRUE), 3) expect_error(CGGP_internal_CorrMatCauchySQT(x1=x1, x2=x2, theta = c(.1,.1))) cauchy1 <- CGGP_internal_CorrMatCauchySQT(x1=x1, x2=x2, theta=th) expect_is(cauchy1, "matrix") expect_equal(dim(cauchy1), c(5,4)) cauchyfunc <- function(x1,x2,theta) { expTILT = exp((theta[3])) expLS = exp(3*(theta[1])) x1t = (x1+10^(-2))^expTILT x2t = (x2+10^(-2))^expTILT x1ts = x1t/expLS x2ts = x2t/expLS diffmat =abs(outer(x1ts,x2ts,'-')); expHE = exp(3*(theta[2])) h = diffmat alpha = 2*exp(5)/(1+exp(5)) halpha = h^alpha pow = -expHE/alpha (1+halpha)^pow } cauchy2 <- cauchyfunc(x1, x2, theta=th) expect_equal(cauchy1, cauchy2) cauchy_C_dC <- CGGP_internal_CorrMatCauchySQT(x1=x1, x2=x2, theta=th, return_dCdtheta=TRUE) eps <- 1e-6 for (i in 1:3) { thd <- c(0,0,0) thd[i] <- eps numdC <- (CGGP_internal_CorrMatCauchySQT(x1=x1, x2=x2, theta=th+thd) - CGGP_internal_CorrMatCauchySQT(x1=x1, x2=x2, theta=th-thd)) / (2*eps) expect_equal(numdC, cauchy_C_dC$dCdtheta[,(1+4*i-4):(4*i)], info = paste("theta dimension with error is",i)) } }) test_that("Correlation CorrMatCauchySQ works", { x1 <- runif(5) x2 <- runif(4) th <- runif(2,-1,1) expect_equal(CGGP_internal_CorrMatCauchySQ(return_numpara=TRUE), 2) expect_error(CGGP_internal_CorrMatCauchySQ(x1=x1, x2=x2, theta = c(.1,.1,.4))) cauchy1 <- CGGP_internal_CorrMatCauchySQ(x1=x1, x2=x2, theta=th) expect_is(cauchy1, "matrix") expect_equal(dim(cauchy1), c(5,4)) cauchyfunc <- function(x1,x2,theta) { diffmat =abs(outer(x1,x2,'-')); expLS = exp(3*theta[1]) expHE = exp(3*theta[2]) h = diffmat/expLS alpha = 2*exp(0+6)/(1+exp(0+6)) halpha = h^alpha pow = -expHE/alpha (1-10^(-10))*(1+halpha)^pow+10^(-10)*(diffmat<10^(-4)) } cauchy2 <- cauchyfunc(x1, x2, theta=th) expect_equal(cauchy1, cauchy2) cauchy_C_dC <- CGGP_internal_CorrMatCauchySQ(x1=x1, x2=x2, theta=th, return_dCdtheta=TRUE) eps <- 1e-6 for (i in 1:2) { thd <- c(0,0) thd[i] <- eps numdC <- (CGGP_internal_CorrMatCauchySQ(x1=x1, x2=x2, theta=th+thd) - CGGP_internal_CorrMatCauchySQ(x1=x1, x2=x2, theta=th-thd)) / (2*eps) expect_equal(numdC, cauchy_C_dC$dCdtheta[,(1+4*i-4):(4*i)], info = paste("theta dimension with error is",i)) } }) test_that("Correlation CorrMatGaussian works", { x1 <- runif(5) x2 <- runif(4) th <- runif(1,-1,1) expect_equal(CGGP_internal_CorrMatGaussian(return_numpara=TRUE), 1) expect_error(CGGP_internal_CorrMatGaussian(x1=x1, x2=x2, theta = c(.1,.1))) corr1 <- CGGP_internal_CorrMatGaussian(x1=x1, x2=x2, theta=th) expect_is(corr1, "matrix") expect_equal(dim(corr1), c(5,4)) gaussianfunc <- function(x1,x2,theta) { diffmat =abs(outer(x1,x2,'-')); diffmat2 <- diffmat^2 expLS = exp(3*theta[1]) h = diffmat2/expLS C = (1-10^(-10))*exp(-h) + 10^(-10)*(diffmat<10^(-4)) C } corr2 <- gaussianfunc(x1, x2, theta=th) expect_equal(corr1, corr2) corr_C_dC <- CGGP_internal_CorrMatGaussian(x1=x1, x2=x2, theta=th, return_dCdtheta=TRUE) eps <- 1e-6 for (i in 1:1) { thd <- c(0) thd[i] <- eps numdC <- (CGGP_internal_CorrMatGaussian(x1=x1, x2=x2, theta=th+thd) - CGGP_internal_CorrMatGaussian(x1=x1, x2=x2, theta=th-thd)) / (2*eps) expect_equal(numdC, corr_C_dC$dCdtheta[,(1+4*i-4):(4*i)], info = paste("theta dimension with error is",i)) } }) test_that("Correlation CorrMatMatern32 works", { x1 <- runif(5) x2 <- runif(4) th <- runif(1,-1,1) expect_equal(CGGP_internal_CorrMatMatern32(return_numpara=TRUE), 1) expect_error(CGGP_internal_CorrMatMatern32(x1=x1, x2=x2, theta = c(.1,.1))) corr1 <- CGGP_internal_CorrMatMatern32(x1=x1, x2=x2, theta=th) expect_is(corr1, "matrix") expect_equal(dim(corr1), c(5,4)) matern32func <- function(x1,x2,theta) { diffmat =abs(outer(x1,x2,'-')) expLS = exp(3*theta[1]) h = diffmat/expLS C = (1-10^(-10))*(1+sqrt(3)*h)*exp(-sqrt(3)*h) + 10^(-10)*(diffmat<10^(-4)) C } corr2 <- matern32func(x1, x2, theta=th) expect_equal(corr1, corr2) corr_C_dC <- CGGP_internal_CorrMatMatern32(x1=x1, x2=x2, theta=th, return_dCdtheta=TRUE) eps <- 1e-6 for (i in 1:1) { thd <- c(0) thd[i] <- eps numdC <- (CGGP_internal_CorrMatMatern32(x1=x1, x2=x2, theta=th+thd) - CGGP_internal_CorrMatMatern32(x1=x1, x2=x2, theta=th-thd)) / (2*eps) expect_equal(numdC, corr_C_dC$dCdtheta[,(1+4*i-4):(4*i)], info = paste("theta dimension with error is",i)) } }) test_that("Correlation CorrMatMatern52 works", { x1 <- runif(5) x2 <- runif(4) th <- runif(1,-1,1) expect_equal(CGGP_internal_CorrMatMatern52(return_numpara=TRUE), 1) expect_error(CGGP_internal_CorrMatMatern52(x1=x1, x2=x2, theta = c(.1,.1))) corr1 <- CGGP_internal_CorrMatMatern52(x1=x1, x2=x2, theta=th) expect_is(corr1, "matrix") expect_equal(dim(corr1), c(5,4)) matern52func <- function(x1,x2,theta) { diffmat =abs(outer(x1,x2,'-')) expLS = exp(3*theta[1]) h = diffmat/expLS C = (1-10^(-10))*(1+sqrt(5)*h+5/3*h^2)*exp(-sqrt(5)*h) + 10^(-10)*(diffmat<10^(-4)) C } corr2 <- matern52func(x1, x2, theta=th) expect_equal(corr1, corr2) corr_C_dC <- CGGP_internal_CorrMatMatern52(x1=x1, x2=x2, theta=th, return_dCdtheta=TRUE) eps <- 1e-6 for (i in 1:1) { thd <- c(0) thd[i] <- eps numdC <- (CGGP_internal_CorrMatMatern52(x1=x1, x2=x2, theta=th+thd) - CGGP_internal_CorrMatMatern52(x1=x1, x2=x2, theta=th-thd)) / (2*eps) expect_equal(numdC, corr_C_dC$dCdtheta[,(1+4*i-4):(4*i)], info = paste("theta dimension with error is",i)) } }) test_that("Correlation CorrMatPowerExp works", { nparam <- 2 x1 <- runif(5) x2 <- runif(4) th <- runif(nparam,-1,1) expect_equal(CGGP_internal_CorrMatPowerExp(return_numpara=TRUE), nparam) expect_error(CGGP_internal_CorrMatPowerExp(x1=x1, x2=x2, theta = rep(0, nparam-1))) expect_error(CGGP_internal_CorrMatPowerExp(x1=x1, x2=x2, theta = rep(0, nparam+1))) corr1 <- CGGP_internal_CorrMatPowerExp(x1=x1, x2=x2, theta=th) expect_is(corr1, "matrix") expect_equal(dim(corr1), c(5,4)) PowerExpfunc <- function(x1,x2,theta) { diffmat =abs(outer(x1,x2,'-')) expLS = exp(3*theta[1]) minpower <- 1 maxpower <- 1.95 alpha <- minpower + (theta[2]+1)/2 * (maxpower - minpower) h = diffmat/expLS C = (1-10^(-10))*exp(-(h)^alpha) + 10^(-10)*(diffmat<10^(-4)) C } corr2 <- PowerExpfunc(x1, x2, theta=th) expect_equal(corr1, corr2) corr_C_dC <- CGGP_internal_CorrMatPowerExp(x1=x1, x2=x2, theta=th, return_dCdtheta=TRUE) eps <- 1e-6 for (i in 1:nparam) { thd <- rep(0, nparam) thd[i] <- eps numdC <- (CGGP_internal_CorrMatPowerExp(x1=x1, x2=x2, theta=th+thd) - CGGP_internal_CorrMatPowerExp(x1=x1, x2=x2, theta=th-thd)) / (2*eps) expect_equal(numdC, corr_C_dC$dCdtheta[,(1+4*i-4):(4*i)], info = paste("theta dimension with error is",i)) } }) test_that("Correlation CorrMatWendland0 works", { x1 <- runif(5) x2 <- runif(4) th <- runif(1,-1,1) expect_equal(CGGP_internal_CorrMatWendland0(return_numpara=TRUE), 1) expect_error(CGGP_internal_CorrMatWendland0(x1=x1, x2=x2, theta = c(.1,.1))) corr1 <- CGGP_internal_CorrMatWendland0(x1=x1, x2=x2, theta=th) expect_is(corr1, "matrix") expect_equal(dim(corr1), c(5,4)) wendland0func <- function(x1,x2,theta) { diffmat =abs(outer(x1,x2,'-')) expLS = exp(3*theta[1]) h = diffmat/expLS C = pmax(1 - h, 0) C } corr2 <- wendland0func(x1, x2, theta=th) expect_equal(corr1, corr2) corr_C_dC <- CGGP_internal_CorrMatWendland0(x1=x1, x2=x2, theta=th, return_dCdtheta=TRUE) eps <- 1e-6 for (i in 1:1) { thd <- c(0) thd[i] <- eps numdC <- (CGGP_internal_CorrMatWendland0(x1=x1, x2=x2, theta=th+thd) - CGGP_internal_CorrMatWendland0(x1=x1, x2=x2, theta=th-thd)) / (2*eps) expect_equal(numdC, corr_C_dC$dCdtheta[,(1+4*i-4):(4*i)], info = paste("theta dimension with error is",i)) } }) test_that("Correlation CorrMatWendland1 works", { x1 <- runif(5) x2 <- runif(4) th <- runif(1,-1,1) expect_equal(CGGP_internal_CorrMatWendland1(return_numpara=TRUE), 1) expect_error(CGGP_internal_CorrMatWendland1(x1=x1, x2=x2, theta = c(.1,.1))) corr1 <- CGGP_internal_CorrMatWendland1(x1=x1, x2=x2, theta=th) expect_is(corr1, "matrix") expect_equal(dim(corr1), c(5,4)) wendland1func <- function(x1,x2,theta) { diffmat =abs(outer(x1,x2,'-')) expLS = exp(3*theta[1]) h = diffmat/expLS C = pmax(1 - h, 0)^3 * (3*h+1) C } corr2 <- wendland1func(x1, x2, theta=th) expect_equal(corr1, corr2) corr_C_dC <- CGGP_internal_CorrMatWendland1(x1=x1, x2=x2, theta=th, return_dCdtheta=TRUE) eps <- 1e-6 for (i in 1:1) { thd <- c(0) thd[i] <- eps numdC <- (CGGP_internal_CorrMatWendland1(x1=x1, x2=x2, theta=th+thd) - CGGP_internal_CorrMatWendland1(x1=x1, x2=x2, theta=th-thd)) / (2*eps) expect_equal(numdC, corr_C_dC$dCdtheta[,(1+4*i-4):(4*i)], info = paste("theta dimension with error is",i)) } }) test_that("Correlation CorrMatWendland2 works", { x1 <- runif(5) x2 <- runif(4) th <- runif(1,-1,1) expect_equal(CGGP_internal_CorrMatWendland2(return_numpara=TRUE), 1) expect_error(CGGP_internal_CorrMatWendland2(x1=x1, x2=x2, theta = c(.1,.1))) corr1 <- CGGP_internal_CorrMatWendland2(x1=x1, x2=x2, theta=th) expect_is(corr1, "matrix") expect_equal(dim(corr1), c(5,4)) wendland2func <- function(x1,x2,theta) { diffmat =abs(outer(x1,x2,'-')) expLS = exp(3*theta[1]) h = diffmat/expLS C = pmax(1 - h, 0)^5 * (8*h^2 + 5*h + 1) C } corr2 <- wendland2func(x1, x2, theta=th) expect_equal(corr1, corr2) corr_C_dC <- CGGP_internal_CorrMatWendland2(x1=x1, x2=x2, theta=th, return_dCdtheta=TRUE) eps <- 1e-6 for (i in 1:1) { thd <- c(0) thd[i] <- eps numdC <- (CGGP_internal_CorrMatWendland2(x1=x1, x2=x2, theta=th+thd) - CGGP_internal_CorrMatWendland2(x1=x1, x2=x2, theta=th-thd)) / (2*eps) expect_equal(numdC, corr_C_dC$dCdtheta[,(1+4*i-4):(4*i)], info = paste("theta dimension with error is",i)) } }) test_that("Logs work for all", { corrs <- list(CGGP_internal_CorrMatCauchySQ, CGGP_internal_CorrMatCauchySQT, CGGP_internal_CorrMatCauchy, CGGP_internal_CorrMatGaussian, CGGP_internal_CorrMatMatern32, CGGP_internal_CorrMatMatern52, CGGP_internal_CorrMatPowerExp, CGGP_internal_CorrMatWendland0, CGGP_internal_CorrMatWendland1, CGGP_internal_CorrMatWendland2 ) works_well_on_log_scales <- c(rep(T, 7), rep(F, 3)) n1 <- 5 n2 <- 6 for (use_log_scale in c(T,F)) { for (icorr in rev(1:length(corrs))) { corr <- corrs[[icorr]] numpara <- corr(return_numpara = T) x1 <- runif(n1) x2 <- runif(n2) theta <- runif(numpara)*2-1 c1 <- corr(x1 = x1, x2 = x2, theta = theta) c1_log <- corr(x1 = x1, x2 = x2, theta = theta, returnlogs = T) expect_is(c1, "matrix") expect_is(c1_log, "matrix") expect_equal(c1, exp(c1_log)) d1_log <- corr(x1 = x1, x2 = x2, theta = theta, returnlogs = T, return_dCdtheta = T) expect_is(d1_log$dCdtheta, "matrix") expect_is(d1_log, "list") expect_equal(d1_log$C, c1_log) corr_C_dC <- corr(x1 = x1, x2 = x2, theta = theta, return_dCdtheta=T) eps <- 1e-6 for (i in 1:numpara) { thd <- rep(0, numpara) thd[i] <- eps numdC <- (corr(x1=x1, x2=x2, theta=theta+thd) - corr(x1=x1, x2=x2, theta=theta-thd)) / (2*eps) expect_equal(numdC, corr_C_dC$dCdtheta[,(1+n2*i-n2):(n2*i)], info = paste("theta dimension with error is",i, ", icor is", icorr, "use_log_scale is", use_log_scale, "theta is", theta)) } corr_C_dC_logs <- corr(x1 = x1, x2 = x2, theta = theta, return_dCdtheta=T, returnlogs=use_log_scale) eps <- 1e-6 for (i in 1:numpara) { thd <- rep(0, numpara) thd[i] <- eps numdC <- (corr(x1=x1, x2=x2, theta=theta+thd, returnlogs = use_log_scale) - corr(x1=x1, x2=x2, theta=theta-thd, returnlogs = use_log_scale)) / (2*eps) numdC <- ifelse(is.nan(numdC), 0, numdC) if (F) { plot(numdC, corr_C_dC_logs$dCdtheta[,(1+n2*i-n2):(n2*i)]) cbind(c(numdC), c(corr_C_dC_logs$dCdtheta[,(1+n2*i-n2):(n2*i)])) (c(numdC) / c(corr_C_dC_logs$dCdtheta[,(1+n2*i-n2):(n2*i)])) } expect_equal(numdC, corr_C_dC_logs$dCdtheta[,(1+n2*i-n2):(n2*i)], info = paste("theta dimension with error is", i, ", icor is", icorr, "use_log_scale is", use_log_scale, "theta is", theta), tolerance = if (!use_log_scale || works_well_on_log_scales[icorr]) {1e-8} else {1e-4}) } rm(numpara, c1, c1_log) } } })
cdm_pem_include_ll_args <- function(ll_args, pem_parm, pem_pars, pem_parameter_index) { for (pp in pem_pars){ ll_args[[ pp ]] <- cdm_pem_extract_parameters( parm=pem_parm, parmgroup=pp, pem_parameter_index=pem_parameter_index ) } return(ll_args) }
plot.nplr <- function(x, pcol="aquamarine1", lcol="red3", showEstim=FALSE, showCI=TRUE, showGOF=TRUE, showInfl=FALSE, showPoints = TRUE, showSDerr = FALSE, B=1e4, conf.level=.95, unit="", ...){ .plot(x, ...) if(showPoints) .addPoints(x, pcol, ...) if(showSDerr) .addErr(x, pcol, ...) if(showGOF) .addGOF(x) if(!(!showEstim)) .addEstim(x, showEstim, unit, B, conf.level) if(showCI) .addPolygon(x) if(showInfl) points(getInflexion(x), pch=19, cex=2, col="blue") .addCurve(x, lcol, ...) if(x@LPweight != 0){ Sub = sprintf("Weighted %s-P logistic regr. (nplr package, version: %s)", x@npars, packageVersion("nplr")) } else{ Sub = sprintf("Non-weighted %s-P logistic regr. (nplr package, version: %s)", x@npars, packageVersion("nplr")) } title(sub = Sub, cex.sub = .75) }
expected <- eval(parse(text="TRUE")); test(id=0, code={ argv <- eval(parse(text="list(structure(list(`/home/lzhao/tmp/Rtmpe5iuYI/R.INSTALL2aa854a74188/foreign/man/lookup.xport.Rd` = structure(c(\"read.xport\", \"\"), .Dim = 1:2, .Dimnames = list(NULL, c(\"Target\", \"Anchor\"))), `/home/lzhao/tmp/Rtmpe5iuYI/R.INSTALL2aa854a74188/foreign/man/read.S.Rd` = structure(character(0), .Dim = c(0L, 2L), .Dimnames = list(NULL, c(\"Target\", \"Anchor\"))), `/home/lzhao/tmp/Rtmpe5iuYI/R.INSTALL2aa854a74188/foreign/man/read.arff.Rd` = structure(c(\"connection\", \"write.arff\", \"\", \"\"), .Dim = c(2L, 2L), .Dimnames = list( NULL, c(\"Target\", \"Anchor\"))), `/home/lzhao/tmp/Rtmpe5iuYI/R.INSTALL2aa854a74188/foreign/man/read.dbf.Rd` = structure(c(\"make.names\", \"write.dbf\", \"\", \"\"), .Dim = c(2L, 2L), .Dimnames = list(NULL, c(\"Target\", \"Anchor\"))), `/home/lzhao/tmp/Rtmpe5iuYI/R.INSTALL2aa854a74188/foreign/man/read.dta.Rd` = structure(c(\"write.dta\", \"attributes\", \"Date\", \"factor\", \"\", \"\", \"\", \"\"), .Dim = c(4L, 2L), .Dimnames = list(NULL, c(\"Target\", \"Anchor\"))), `/home/lzhao/tmp/Rtmpe5iuYI/R.INSTALL2aa854a74188/foreign/man/read.epiinfo.Rd` = structure(c(\"Date\", \"DateTimeClasses\", \"\", \"\"), .Dim = c(2L, 2L), .Dimnames = list(NULL, c(\"Target\", \"Anchor\"))), `/home/lzhao/tmp/Rtmpe5iuYI/R.INSTALL2aa854a74188/foreign/man/read.mtp.Rd` = structure(character(0), .Dim = c(0L, 2L), .Dimnames = list(NULL, c(\"Target\", \"Anchor\"))), `/home/lzhao/tmp/Rtmpe5iuYI/R.INSTALL2aa854a74188/foreign/man/read.octave.Rd` = structure(character(0), .Dim = c(0L, 2L), .Dimnames = list(NULL, c(\"Target\", \"Anchor\"))), `/home/lzhao/tmp/Rtmpe5iuYI/R.INSTALL2aa854a74188/foreign/man/read.spss.Rd` = structure(c(\"sub\", \"iconv\", \"iconvlist\", \"\", \"\", \"\"), .Dim = c(3L, 2L), .Dimnames = list(NULL, c(\"Target\", \"Anchor\"))), `/home/lzhao/tmp/Rtmpe5iuYI/R.INSTALL2aa854a74188/foreign/man/read.ssd.Rd` = structure(c(\"read.xport\", \"\"), .Dim = 1:2, .Dimnames = list(NULL, c(\"Target\", \"Anchor\"))), `/home/lzhao/tmp/Rtmpe5iuYI/R.INSTALL2aa854a74188/foreign/man/read.systat.Rd` = structure(character(0), .Dim = c(0L, 2L), .Dimnames = list(NULL, c(\"Target\", \"Anchor\"))), `/home/lzhao/tmp/Rtmpe5iuYI/R.INSTALL2aa854a74188/foreign/man/read.xport.Rd` = structure(c(\"lookup.xport\", \"\"), .Dim = 1:2, .Dimnames = list(NULL, c(\"Target\", \"Anchor\"))), `/home/lzhao/tmp/Rtmpe5iuYI/R.INSTALL2aa854a74188/foreign/man/write.arff.Rd` = structure(c(\"make.names\", \"read.arff\", \"\", \"\"), .Dim = c(2L, 2L), .Dimnames = list(NULL, c(\"Target\", \"Anchor\"))), `/home/lzhao/tmp/Rtmpe5iuYI/R.INSTALL2aa854a74188/foreign/man/write.dbf.Rd` = structure(c(\"read.dbf\", \"\"), .Dim = 1:2, .Dimnames = list(NULL, c(\"Target\", \"Anchor\"))), `/home/lzhao/tmp/Rtmpe5iuYI/R.INSTALL2aa854a74188/foreign/man/write.dta.Rd` = structure(c(\"drop\", \"read.dta\", \"attributes\", \"DateTimeClasses\", \"abbreviate\", \"\", \"\", \"\", \"\", \"\"), .Dim = c(5L, 2L), .Dimnames = list(NULL, c(\"Target\", \"Anchor\"))), `/home/lzhao/tmp/Rtmpe5iuYI/R.INSTALL2aa854a74188/foreign/man/write.foreign.Rd` = structure(character(0), .Dim = c(0L, 2L), .Dimnames = list(NULL, c(\"Target\", \"Anchor\")))), .Names = c(\"/home/lzhao/tmp/Rtmpe5iuYI/R.INSTALL2aa854a74188/foreign/man/lookup.xport.Rd\", \"/home/lzhao/tmp/Rtmpe5iuYI/R.INSTALL2aa854a74188/foreign/man/read.S.Rd\", \"/home/lzhao/tmp/Rtmpe5iuYI/R.INSTALL2aa854a74188/foreign/man/read.arff.Rd\", \"/home/lzhao/tmp/Rtmpe5iuYI/R.INSTALL2aa854a74188/foreign/man/read.dbf.Rd\", \"/home/lzhao/tmp/Rtmpe5iuYI/R.INSTALL2aa854a74188/foreign/man/read.dta.Rd\", \"/home/lzhao/tmp/Rtmpe5iuYI/R.INSTALL2aa854a74188/foreign/man/read.epiinfo.Rd\", \"/home/lzhao/tmp/Rtmpe5iuYI/R.INSTALL2aa854a74188/foreign/man/read.mtp.Rd\", \"/home/lzhao/tmp/Rtmpe5iuYI/R.INSTALL2aa854a74188/foreign/man/read.octave.Rd\", \"/home/lzhao/tmp/Rtmpe5iuYI/R.INSTALL2aa854a74188/foreign/man/read.spss.Rd\", \"/home/lzhao/tmp/Rtmpe5iuYI/R.INSTALL2aa854a74188/foreign/man/read.ssd.Rd\", \"/home/lzhao/tmp/Rtmpe5iuYI/R.INSTALL2aa854a74188/foreign/man/read.systat.Rd\", \"/home/lzhao/tmp/Rtmpe5iuYI/R.INSTALL2aa854a74188/foreign/man/read.xport.Rd\", \"/home/lzhao/tmp/Rtmpe5iuYI/R.INSTALL2aa854a74188/foreign/man/write.arff.Rd\", \"/home/lzhao/tmp/Rtmpe5iuYI/R.INSTALL2aa854a74188/foreign/man/write.dbf.Rd\", \"/home/lzhao/tmp/Rtmpe5iuYI/R.INSTALL2aa854a74188/foreign/man/write.dta.Rd\", \"/home/lzhao/tmp/Rtmpe5iuYI/R.INSTALL2aa854a74188/foreign/man/write.foreign.Rd\")))")); do.call(`is.list`, argv); }, o=expected);
library(lmerTest) has_pbkrtest <- requireNamespace("pbkrtest", quietly = TRUE) && getRversion() >= "3.3.3" load(system.file("testdata","test_paper_objects.RData", package="lmerTest")) tv <- lmer(Sharpnessofmovement ~ TVset * Picture + (1 | Assessor) + (1 | Assessor:TVset) + (1 | Assessor:Picture), data = TVbo, control=lmerControl(optimizer="bobyqa")) (an8.2 <- anova(tv)) if(has_pbkrtest) (ankr8.2 <- anova(tv, type=2, ddf="Kenward-Roger")) m.carrots <- lmer(Preference ~ sens1 + sens2 + (1 + sens1 + sens2 | Consumer) + (1 | Product), data=carrots, control=lmerControl(optimizer="bobyqa")) (sum8.3 <- coef(summary(m.carrots))) tv <- lmer(Sharpnessofmovement ~ TVset * Picture + (1 | Assessor:TVset) + (1 | Assessor:Picture) + (1 | Assessor:Picture:TVset) + (1 | Repeat) + (1 | Repeat:Picture) + (1 | Repeat:TVset) + (1 | Repeat:TVset:Picture) + (1 | Assessor), data = TVbo, control=lmerControl(optimizer="bobyqa")) st <- step(tv) (elim_tab_random8.4 <- st$random) (elim_tab_fixed8.4 <- st$fixed) (an8.4 <- anova(get_model(st))) L <- cbind(array(0, dim=c(6, 6)), diag(6)) (con1_8.5 <- calcSatterth(tv, L)) (con2_8.5 <- contest(tv, L)) (ran_C <- ranova(m.carrots)) TOL <- 1e-4 stopifnot( isTRUE(all.equal(an8.2_save, an8.2, check.attributes = FALSE, tolerance=TOL)), isTRUE(all.equal(sum8.3_save, sum8.3, check.attributes = FALSE, tolerance=TOL)), isTRUE(all.equal(elim_tab_random8.4_save, elim_tab_random8.4, check.attributes = FALSE, tolerance=TOL)), isTRUE(all.equal(elim_tab_fixed8.4_save, elim_tab_fixed8.4, check.attributes = FALSE, tolerance=TOL)), isTRUE(all.equal(an8.4_save, an8.4, check.attributes = FALSE, tolerance=TOL)), isTRUE(all.equal(con1_8.5_save, con1_8.5, check.attributes = FALSE, tolerance=TOL)), isTRUE(all.equal(con2_8.5_save, con2_8.5, check.attributes = FALSE, tolerance=TOL)) ) if(has_pbkrtest) { stopifnot( isTRUE(all.equal(ankr8.2_save, ankr8.2, check.attributes = FALSE, tolerance=TOL)) ) }
RVtest <- function(Dx, Dy, nperm){ n <- dim(Dx)[1] C <- diag(n) - ((rep(1, n) %*% t(rep(1, n)))/n) RVObs <- as.vector(RVcoeff(mDx = Dx, mDy = Dy, mC = C)) if(nperm != 0 ){ permStats <- rep(NA, nperm) s <-lapply(1:nperm, function(x) c(sample(nrow(Dy)))) for(i in 1:nperm){ permStats[i] <- as.vector(RVcoeff(mDx = Dx, mDy = Dy[s[[i]], s[[i]]], mC = C)) } pVal <- (sum(permStats > RVObs) + 1)/(nperm + 1) return(list(Stat = RVObs, pValue = pVal, permStats = permStats)) } else{ return(list(Stat = RVObs)) } }
"Brainsz"
context("Spectral methods") test_that("get_first_eigs returns correct values on dense matrix", { G <- matrix(c(7, -4, 14, 0, -4, 19, 10, 0, 14, 10, 10, 0, 0, 0, 0, 100), nrow = 4) ans_vals <- c(-9, 18, 27) ans_vects <- matrix( c(-2, -1, 2, 0, -2, 2, -1, 0, -1, -2, -2, 0) / 3, nrow = 4) spect <- get_first_eigs(G, 3) vals <- spect$vals vects <- spect$vects for (i in seq_len(length(vals))) { if (sign(vects[1, i]) != sign(ans_vects[1, i])) { vects[, i] <- -vects[, i] } } expect_equal(vals, ans_vals) expect_equal(vects, ans_vects) }) test_that("get_first_eigs returns correct values on sparse matrix", { G <- drop0(matrix(c(7, -4, 14, 0, -4, 19, 10, 0, 14, 10, 10, 0, 0, 0, 0, 100), nrow = 4)) ans_vals <- c(-9, 18, 27) ans_vects <- matrix(c( -2, -1, 2, 0, -2, 2, -1, 0, -1, -2, -2, 0) / 3, nrow = 4) spect <- get_first_eigs(G, 3) vals <- spect$vals vects <- spect$vects for (i in seq_len(length(vals))) { if (sign(vects[1, i]) != sign(ans_vects[1, i])) { vects[, i] <- -vects[, i] } } expect_equal(vals, ans_vals) expect_equal(vects, ans_vects) }) test_that("build_laplacian returns correct matrices on dense matrix", { G <- matrix(c(0:8), nrow = 3) G <- G + t(G) degs_mat <- diag(c(12, 24, 36)) comb_lap <- drop0(degs_mat - G) rw_lap <- drop0(solve(degs_mat) %*% (degs_mat - G)) expect_equal(build_laplacian(G, type_lap = "comb"), comb_lap) expect_equal(build_laplacian(G, type_lap = "rw"), rw_lap) }) test_that("build_laplacian returns correct matrices on sparse matrix", { G <- matrix(c(0:8), nrow = 3) G <- drop0(G + t(G)) degs_mat <- diag(c(12, 24, 36)) comb_lap <- degs_mat - G rw_lap <- drop0(solve(degs_mat) %*% (degs_mat - G)) expect_equal(build_laplacian(G, type_lap = "comb"), comb_lap) expect_equal(build_laplacian(G, type_lap = "rw"), rw_lap) }) test_that("build_laplacian gives correct error if row sums are zero", { G <- drop0(matrix(c(0, 1, 0, 2))) expect_error(build_laplacian(G, type_lap = "rw"), "row sums of adj_mat must be non-zero") }) test_that("run_laplace_embedding returns correct spectrum on dense matrix", { set.seed(9235) G <- matrix(c(0:8), nrow = 3) G <- G + t(G) ans_vals_comb <- c(0, 17.07) ans_vects_comb <- matrix(c( 0.577, 0.789, 0.577, -0.577, 0.577, -0.211 ), nrow = 3, byrow = TRUE) ans_vals_rw <- c(0, 1) ans_vects_rw <- matrix(c( 0.577, 0.408, 0.577, -0.816, 0.577, 0.408 ), nrow = 3, byrow = TRUE) spectrum_comb <- run_laplace_embedding(G, 2, "comb") spectrum_rw <- run_laplace_embedding(G, 2, "rw") vals_comb <- spectrum_comb$vals vects_comb <- spectrum_comb$vects vals_rw <- spectrum_rw$vals vects_rw <- spectrum_rw$vects for (i in seq_len(length(vals_comb))) { if (sign(vects_comb[1, i]) != sign(ans_vects_comb[1, i])) { vects_comb[, i] <- -vects_comb[, i] } if (sign(vects_rw[1, i]) != sign(ans_vects_rw[1, i])) { vects_rw[, i] <- -vects_rw[, i] } } expect_equal(vals_comb, ans_vals_comb, tolerance = 0.01) expect_equal(vects_comb, ans_vects_comb, tolerance = 0.01) expect_equal(vals_rw, ans_vals_rw, tolerance = 0.01) expect_equal(vects_rw, ans_vects_rw, tolerance = 0.01) }) test_that("run_laplace_embedding returns correct spectrum on sparse matrix", { set.seed(9235) G <- matrix(c(0:8), nrow = 3) G <- drop0(G + t(G)) ans_vals_comb <- c(0, 17.07) ans_vects_comb <- matrix(c( 0.577, 0.789, 0.577, -0.577, 0.577, -0.211 ), nrow = 3, byrow = TRUE) ans_vals_rw <- c(0, 1) ans_vects_rw <- matrix(c( 0.577, 0.408, 0.577, -0.816, 0.577, 0.408 ), nrow = 3, byrow = TRUE) spectrum_comb <- run_laplace_embedding(G, 2, "comb") spectrum_rw <- run_laplace_embedding(G, 2, "rw") vals_comb <- spectrum_comb$vals vects_comb <- spectrum_comb$vects vals_rw <- spectrum_rw$vals vects_rw <- spectrum_rw$vects for (i in seq_len(length(vals_comb))) { if (sign(vects_comb[1, i]) != sign(ans_vects_comb[1, i])) { vects_comb[, i] <- -vects_comb[, i] } if (sign(vects_rw[1, i]) != sign(ans_vects_rw[1, i])) { vects_rw[, i] <- -vects_rw[, i] } } expect_equal(vals_comb, ans_vals_comb, tolerance = 0.01) expect_equal(vects_comb, ans_vects_comb, tolerance = 0.01) expect_equal(vals_rw, ans_vals_rw, tolerance = 0.01) expect_equal(vects_rw, ans_vects_rw, tolerance = 0.01) }) test_that("run_motif_embedding correct on dense matrix with restrict", { set.seed(9235) adj_mat <- matrix(c( 0, 2, 0, 0, 0, 0, 3, 0, 4, 0, 0, 0, 0, 0, 0, 0 ), nrow = 4, byrow = TRUE) ans_adj_mat <- drop0(matrix(c( 0, 2, 0, 0, 0, 0, 3, 0, 4, 0, 0, 0, 0, 0, 0, 0 ), nrow = 4, byrow = TRUE)) ans_motif_adj_mat <- drop0(matrix(c( 0, 2, 4, 0, 2, 0, 3, 0, 4, 3, 0, 0, 0, 0, 0, 0 ), nrow = 4, byrow = TRUE)) ans_comps <- 1:3 ans_adj_mat_comps <- drop0(matrix(c( 0, 2, 0, 0, 0, 3, 4, 0, 0 ), nrow = 3, byrow = TRUE)) ans_motif_adj_mat_comps <- drop0(matrix(c( 0, 2, 4, 2, 0, 3, 4, 3, 0 ), nrow = 3, byrow = TRUE)) ans_vals <- c(0, 1.354) ans_vects <- matrix(c( 0.577, 0.544, 0.577, -0.830, 0.577, 0.126 ), nrow = 3, byrow = TRUE) emb_list <- run_motif_embedding(adj_mat, "Ms", "func", "mean", "dense", 2, "rw", restrict = TRUE) for (i in seq_len(length(ans_vals))) { if (sign(emb_list$vects[1, i]) != sign(ans_vects[1, i])) { emb_list$vects[, i] <- -emb_list$vects[, i] } } expect_equal(ans_adj_mat, emb_list$adj_mat) expect_equal(ans_motif_adj_mat, emb_list$motif_adj_mat) expect_equal(ans_comps, emb_list$comps) expect_equal(ans_adj_mat_comps, emb_list$adj_mat_comps) expect_equal(ans_motif_adj_mat_comps, emb_list$motif_adj_mat_comps) expect_equal(ans_vals, emb_list$vals, tolerance = 0.01) expect_equal(ans_vects, emb_list$vects, tolerance = 0.01) }) test_that("run_motif_embedding correct on sparse matrix with restrict", { set.seed(9235) adj_mat <- matrix(c( 0, 2, 0, 0, 0, 0, 3, 0, 4, 0, 0, 0, 0, 0, 0, 0 ), nrow = 4, byrow = TRUE) ans_adj_mat <- drop0(matrix(c( 0, 2, 0, 0, 0, 0, 3, 0, 4, 0, 0, 0, 0, 0, 0, 0 ), nrow = 4, byrow = TRUE)) ans_motif_adj_mat <- drop0(matrix(c( 0, 2, 4, 0, 2, 0, 3, 0, 4, 3, 0, 0, 0, 0, 0, 0 ), nrow = 4, byrow = TRUE)) ans_comps <- 1:3 ans_adj_mat_comps <- drop0(matrix(c( 0, 2, 0, 0, 0, 3, 4, 0, 0 ), nrow = 3, byrow = TRUE)) ans_motif_adj_mat_comps <- drop0(matrix(c( 0, 2, 4, 2, 0, 3, 4, 3, 0 ), nrow = 3, byrow = TRUE)) ans_vals <- c(0, 1.354) ans_vects <- matrix(c( 0.577, 0.544, 0.577, -0.830, 0.577, 0.126 ), nrow = 3, byrow = TRUE) emb_list <- run_motif_embedding(adj_mat, "Ms", "func", "mean", "dense", 2, "rw", restrict = TRUE) for (i in seq_len(length(ans_vals))) { if (sign(emb_list$vects[1, i]) != sign(ans_vects[1, i])) { emb_list$vects[, i] <- -emb_list$vects[, i] } } expect_equal(ans_adj_mat, emb_list$adj_mat) expect_equal(ans_motif_adj_mat, emb_list$motif_adj_mat) expect_equal(ans_comps, emb_list$comps) expect_equal(ans_adj_mat_comps, emb_list$adj_mat_comps) expect_equal(ans_motif_adj_mat_comps, emb_list$motif_adj_mat_comps) expect_equal(ans_vals, emb_list$vals, tolerance = 0.01) expect_equal(ans_vects, emb_list$vects, tolerance = 0.01) }) test_that("run_motif_embedding correct on dense matrix without restrict", { set.seed(9235) adj_mat <- matrix(c( 0, 2, 0, 0, 0, 3, 4, 0, 0 ), nrow = 3, byrow = TRUE) ans_adj_mat <- drop0(matrix(c( 0, 2, 0, 0, 0, 3, 4, 0, 0 ), nrow = 3, byrow = TRUE)) ans_motif_adj_mat <- drop0(matrix(c( 0, 2, 4, 2, 0, 3, 4, 3, 0 ), nrow = 3, byrow = TRUE)) ans_vals <- c(0, 1.354) ans_vects <- matrix(c( 0.577, 0.544, 0.577, -0.830, 0.577, 0.126 ), nrow = 3, byrow = TRUE) emb_list <- run_motif_embedding(adj_mat, "Ms", "func", "mean", "dense", 2, "rw", restrict = FALSE) for (i in seq_len(length(ans_vals))) { if (sign(emb_list$vects[1, i]) != sign(ans_vects[1, i])) { emb_list$vects[, i] <- -emb_list$vects[, i] } } expect_equal(ans_adj_mat, emb_list$adj_mat) expect_equal(ans_motif_adj_mat, emb_list$motif_adj_mat) expect_equal(ans_vals, emb_list$vals, tolerance = 0.01) expect_equal(ans_vects, emb_list$vects, tolerance = 0.01) }) test_that("run_motif_embedding correct on sparse matrix without restrict", { set.seed(9235) adj_mat <- matrix(c( 0, 2, 0, 0, 0, 3, 4, 0, 0 ), nrow = 3, byrow = TRUE) ans_adj_mat <- drop0(matrix(c( 0, 2, 0, 0, 0, 3, 4, 0, 0 ), nrow = 3, byrow = TRUE)) ans_motif_adj_mat <- drop0(matrix(c( 0, 2, 4, 2, 0, 3, 4, 3, 0 ), nrow = 3, byrow = TRUE)) ans_vals <- c(0, 1.354) ans_vects <- matrix(c( 0.577, 0.544, 0.577, -0.830, 0.577, 0.126 ), nrow = 3, byrow = TRUE) emb_list <- run_motif_embedding(adj_mat, "Ms", "func", "mean", "dense", 2, "rw", restrict = FALSE) for (i in seq_len(length(ans_vals))) { if (sign(emb_list$vects[1, i]) != sign(ans_vects[1, i])) { emb_list$vects[, i] <- -emb_list$vects[, i] } } expect_equal(ans_adj_mat, emb_list$adj_mat) expect_equal(ans_motif_adj_mat, emb_list$motif_adj_mat) expect_equal(ans_vals, emb_list$vals, tolerance = 0.01) expect_equal(ans_vects, emb_list$vects, tolerance = 0.01) })
"estDesign" <- function( n, smax, p.tr, biasrest=0.05) { if(length(n)!=1 || (n<=1 | abs(round(n)-n) > 1e-07)){stop("number of groups n must be specified as a single integer greater than 1")} if(length(p.tr)!=1 || p.tr>1 || p.tr<0){stop("true proportion p.tr must be specified as a single number between 0 and 1")} if(length(smax)!=1 || (smax<=1 | abs(round(smax)-smax) > 1e-07)){stop("the maximal group size allowed in calculations must be a single integer greater than 1")} if(length(biasrest)!=1 || biasrest>=1 || biasrest<0){stop("the maximally allowed bias(p) specified in biasrest must be a single number between 0 and 1, usually should be close to 0")} for (i in 2:smax) { temp<-msep(n=n, p.tr=p.tr,s=i) if(temp$bias > biasrest) {cat("maximal group size within bias restriction is s =",i-1,"\n") return(msep(n=n, p.tr=p.tr,s=i-1))} if(i>=2 && temp$mse > msep(n=n, p.tr=p.tr,s=i-1)$mse) {cat("group size s with minimal mse(p) =",i-1,"\n") return(msep(n=n, p.tr=p.tr,s=i-1))} if (i==smax && temp$mse <= msep(n=n, p.tr=p.tr,s=i-1)$mse) {cat(" minimal mse(p) is achieved with group size s >= smax","\n") return(msep(n=n, p.tr=p.tr,s=i-1))} } }
library(tinytest) .runThisTest <- Sys.getenv("RunRblpapiUnitTests") == "yes" if (!.runThisTest) exit_file("Skipping this file") library(Rblpapi) isweekend <- as.POSIXlt(Sys.Date())$wday %in% c(0,6) res <- getTicks("ESA Index", startTime=Sys.time() - isweekend*48*60*60 - 60*60, endTime=Sys.time() - isweekend*48*60*60, returnAs="data.frame") expect_true(inherits(res, "data.frame"), info = "checking return type") expect_true(dim(res)[1] > 10, info = "check return of at least ten rows") expect_true(dim(res)[2] == 5, info = "check return of five columns") expect_true(all(c("times", "value", "size") %in% colnames(res)), info = "check column names") isweekend <- as.POSIXlt(Sys.Date())$wday %in% c(0,6) res <- getTicks("ESA Index", startTime=Sys.time() - isweekend*48*60*60 - 60*60, endTime=Sys.time() - isweekend*48*60*60, returnAs="xts") expect_true(inherits(res, "xts"), info = "checking return type") expect_true(dim(res)[1] > 10, info = "check return of at least ten rows") expect_true(dim(res)[2] == 2, info = "check return of two columns") expect_true(all(c("value", "size") %in% colnames(res)), info = "check column names") isweekend <- as.POSIXlt(Sys.Date())$wday %in% c(0,6) res <- getTicks("ESA Index", startTime=Sys.time() - isweekend*48*60*60 - 60*60, endTime=Sys.time() - isweekend*48*60*60, returnAs="data.table") expect_true(inherits(res, "data.table"), info = "checking return type") expect_true(dim(res)[1] > 10, info = "check return of at least ten rows") expect_true(dim(res)[2] == 7, info = "check return of seven columns") expect_true(all(c("pt", "date", "time", "type", "value", "size", "condcode") %in% colnames(res)), info = "check column names")
if(requireNamespace("limma", quietly = TRUE) & requireNamespace("SDMTools", quietly = TRUE)){ testFmod <- function(counts, group, a = .05){ library(propr) library(limma) M <- counts gr <- group ce=which(group == unique(group)[1]) co=which(group == unique(group)[2]) cere=ce cort=co nce=length(cere) nco=length(cort) design=matrix(0,dim(M)[1],2) design[1:length(cere),1]=rep(1,length(cere)) design[(length(cere)+1):dim(M)[1],2]=rep(1,length(cort)) z=exp(apply(log(M),1,mean)) Mz=M/z scaledcounts=t(Mz*mean(z)) u=voom(scaledcounts, design=design, plot=TRUE) param=lmFit(u,design) param=eBayes(param) dz=param$df.prior s2z=param$s2.prior counts=t(M[c(cere,cort),]) v=voom(counts, design=design, plot=TRUE) colnames(v$weights)=rownames(M) su=apply(v$weights,2,sum) w=t(v$weights)/su zw=exp(apply(w*log(M)*dim(M)[2],1,mean)) wz=log(zw)/log(z) res=propd(counts=M, group=gr, p = 1) Res=propd(counts=M, group=gr, p = 1, weighted = TRUE) resa=propd(counts=M, group=gr, p = 1, alpha = a) Resa=propd(counts=M, group=gr, p = 1, weighted = TRUE, alpha = a) st=res@results[,c("lrv","theta")] stw=Res@results[,c("lrv","theta")] sta=resa@results[,c("lrv","theta")] stwa=Resa@results[,c("lrv","theta")] mod=dz*s2z/st[,"lrv"] Fpmod=(1-st[,"theta"])*(dz+nce+nco)/((nce+nco)*st[,"theta"]+mod) thetamod=1/(1+Fpmod) Fmod=(nce+nco+dz-2)*Fpmod modw=dz*s2z/stw[,"lrv"] Fpmodw=(1-stw[,"theta"])*(dz+nce+nco)/((nce+nco)*stw[,"theta"]+modw) thetamodw=1/(1+Fpmodw) Fmodw=(nce+nco+dz-2)*Fpmodw moda=dz*s2z/sta[,"lrv"] Fpmoda=(1-sta[,"theta"])*(dz+nce+nco)/((nce+nco)*sta[,"theta"]+moda) thetamoda=1/(1+Fpmoda) Fmoda=(nce+nco+dz-2)*Fpmoda modwa=dz*s2z/stwa[,"lrv"] Fpmodwa=(1-stwa[,"theta"])*(dz+nce+nco)/((nce+nco)*stwa[,"theta"]+modwa) thetamodwa=1/(1+Fpmodwa) Fmodwa=(nce+nco+dz-2)*Fpmodwa return(list(thetamod, thetamodw, thetamoda, thetamodwa, Fmod, Fmodw, Fmoda, Fmodwa)) } library(propr) data(iris) keep <- iris$Species %in% c("setosa", "versicolor") counts <- iris[keep, 1:4] * 10 group <- ifelse(iris[keep, "Species"] == "setosa", "A", "B") pd.nn <- propd(counts, group) pd.wn <- propd(counts, group, weighted = TRUE) pd.na <- propd(counts, group, alpha = .05) pd.wa <- propd(counts, group, weighted = TRUE, alpha = .05) pd.nn <- updateF(pd.nn, moderated = TRUE) pd.wn <- updateF(pd.wn, moderated = TRUE) pd.na <- updateF(pd.na, moderated = TRUE) pd.wa <- updateF(pd.wa, moderated = TRUE) ref <- testFmod(counts, group, a = .05) test_that("updateF matches code provided by Ionas", { expect_equal( pd.nn@results$theta_mod, ref[[1]] ) expect_equal( pd.nn@results$Fstat, ref[[5]] ) expect_equal( pd.na@results$theta_mod, ref[[3]] ) expect_equal( pd.na@results$Fstat, ref[[7]] ) }) }
ProDenICA <- function(x, k=p, W0=NULL, whiten=FALSE, maxit = 20, thresh = 1e-7, restarts = 0, trace = FALSE, Gfunc=GPois, eps.rank=1e-7, ...) { this.call=match.call() p <- ncol(x) n <- nrow(x) x <- scale(x, T, F) if(whiten){ sx <- svd(x) condnum=sx$d;condnum=condnum/condnum[1] good=condnum >eps.rank rank=sum(good) if(k>rank){ warning(paste("Rank of x is ",rank,"; k reduced from",k," to ",rank,sep="")) k=rank } x <- sqrt(n) * sx$u[,good] whitener=sqrt(n)*scale(sx$v[,good],FALSE,sx$d[good]) } else whitener=NULL if(is.null(W0)) W0 <- matrix(rnorm(p * k), p, k) else k=ncol(W0) W0 <- ICAorthW(W0) GS <- matrix(0., n, k) gS <- GS gpS <- GS s <- x %*% W0 flist <- as.list(1.:k) for(j in 1.:k) flist[[j]] <- Gfunc(s[, j], ...) flist0 <- flist crit0 <- mean(sapply(flist0, "[[", "Gs")) while(restarts) { W1 <- matrix(rnorm(p * k), p, k) W1 <- ICAorthW(W1) s <- x %*% W1 for(j in 1.:k) flist[[j]] <- Gfunc(s[, j], ...) crit <- mean(sapply(flist, "[[", "Gs")) if(trace) cat("old crit", crit0, "new crit", crit, "\n") if(crit > crit0) { crit0 <- crit W0 <- W1 flist0 <- flist } restarts <- restarts - 1. } nit <- 0 nw <- 10 repeat { nit <- nit + 1 gS <- sapply(flist0, "[[", "gs") gpS <- sapply(flist0, "[[", "gps") t1 <- t(x) %*% gS/n t2 <- apply(gpS, 2, mean) W1 <- t1 - scale(W0, F, 1/t2) W1 <- ICAorthW(W1) nw <- amari(W0, W1) if(trace) cat("Iter", nit, "G", crit0, "crit", nw, "\n") W0 <- W1 if((nit > maxit) | (nw < thresh)) break s <- x %*% W0 for(j in 1:k) flist0[[j]] <- Gfunc(s[, j], ...) crit0 <- mean(sapply(flist0, "[[", "Gs")) } rl=list(W = W0, negentropy = crit0,s= x %*% W0,whitener=whitener,call=this.call) rl$density=lapply(flist0,"[[","density") class(rl)="ProDenICA" rl }
as_nlist <- function(x, ...) { UseMethod("as_nlist") } as.nlist <- function(x, ...) { deprecate_soft("0.1.1", what = "nlist::as.nlist()", with = "nlist::as_nlist()" ) UseMethod("as_nlist") } as_nlist.numeric <- function(x, ...) { chk_named(x) chk_term(as_term(names(x)), validate = "consistent", x_name = "`names(x)`") chk_not_any_na(names(x)) chk_unique(names(x)) chk_unused(...) if (!length(x)) { return(nlist()) } terms <- as_term(names(x)) if (is_incomplete_terms(terms)) { terms <- complete_terms(terms) y <- rep(NA_integer_, length(terms)) names(y) <- terms y[names(x)] <- x x <- y } x <- split(x, pars_terms(terms)) x <- lapply(x, function(x) x[order(as_term(names(x)))]) x <- lapply(x, function(x) set_dim(x, pdims(as_term(names(x)))[[1]])) as_nlist(x) } as_nlist.list <- function(x, ...) { chk_unused(...) if (!length(x)) { return(nlist()) } x <- numericise(x) class(x) <- "nlist" chk_nlist(x) x } as_nlist.data.frame <- function(x, ...) as_nlist(as.list(x)) as_nlist.mcmc <- function(x, ...) { chk_unused(...) if(!identical(nrow(x), 1L)) abort_chk("`x` must have one iteration.") x <- complete_terms(x) pars <- pars(x) x <- lapply(pars, function(p, x) subset(x, pars = p), x = x) names(x) <- pars x <- lapply(x, function(x) set_dim(as.vector(x), pdims(x)[[1]])) as_nlist(x) } as_nlist.mcmc.list <- function(x, ...) { as_nlist(as_mcmc(x), ...) } as_nlist.nlist <- function(x, ...) x
CatDynPred <- function(x, method,partial=TRUE) { fleet.name <- x$Data$Properties$Fleets$Fleet; p <- x$Model[[method]]$Type; options(warn=-1) if(class(x) != "catdyn") {stop("Pass an object of class 'catdyn' to CatDynPred")} if(class(method) != "character") {stop("method must be a character corresponding to one of the numerical methods passed to the CatDyn function")} if(length(method) != 1) {stop("Provide the name of just one the numerical methods used to fit the model")} if(sum(method == names(x$Model)) == 0) {stop("The method provided in 'method' was not used to numerically fit the model")} if(is.na(x$Model[[method]]$AIC)) {stop("The selected method failed. Consider trying a different method")} if(length(fleet.name) == 1) { parlist <- list(par=log(as.numeric(x$Model[[method]]$bt.par)), dates=x$Model[[method]]$Dates, obscat1=x$Data$Data[[fleet.name]][,5], obseff1=x$Data$Data[[fleet.name]][,2], obsmbm1=x$Data$Data[[fleet.name]][,4], distr=x$Model[[method]]$Distr, properties=x$Data$Properties, output="predict", partial=partial) if(p == 0) { results <- do.call(.CDMN0P, parlist); } else if(p == 1) { results <- do.call(.CDMN1P, parlist); } else if(p == -1) { results <- do.call(.CDMNT1P, parlist); } else if(p == 2) { results <- do.call(.CDMN2P, parlist); } else if(p == -2) { results <- do.call(.CDMNT2P, parlist); } else if(p == 3) { results <- do.call(.CDMN3P, parlist); } else if(p == -3) { results <- do.call(.CDMNT3P, parlist); } else if(p == 4) { results <- do.call(.CDMN4P, parlist); } else if(p == -4) { results <- do.call(.CDMNT4P, parlist); } else if(p == 5) { results <- do.call(.CDMN5P, parlist); } else if(p == -5) { results <- do.call(.CDMNT5P, parlist); } else if(p == 6) { results <- do.call(.CDMN6P, parlist); } else if(p == -6) { results <- do.call(.CDMNT6P, parlist); } else if(p == 7) { results <- do.call(.CDMN7P, parlist); } else if(p == -7) { results <- do.call(.CDMNT7P, parlist); } else if(p == 8) { results <- do.call(.CDMN8P, parlist); } else if(p == -8) { results <- do.call(.CDMNT8P, parlist); } else if(p == 9) { results <- do.call(.CDMN9P, parlist); } else if(p == -9) { results <- do.call(.CDMNT9P, parlist); } else if(p == 10) { results <- do.call(.CDMN10P, parlist); } else if(p == -10) { results <- do.call(.CDMNT10P, parlist); } else if(p == 11) { results <- do.call(.CDMN11P, parlist); } else if(p == -11) { results <- do.call(.CDMNT11P, parlist); } else if(p == 12) { results <- do.call(.CDMN12P, parlist); } else if(p == -12) { results <- do.call(.CDMNT12P, parlist); } else if(p == 13) { results <- do.call(.CDMN13P, parlist); } else if(p == -13) { results <- do.call(.CDMNT13P, parlist); } else if(p == 14) { results <- do.call(.CDMN14P, parlist); } else if(p == -14) { results <- do.call(.CDMNT14P, parlist); } else if(p == 15) { results <- do.call(.CDMN15P, parlist); } else if(p == -15) { results <- do.call(.CDMNT15P, parlist); } else if(p == 16) { results <- do.call(.CDMN16P, parlist); } else if(p == -16) { results <- do.call(.CDMNT16P, parlist); } else if(p == 17) { results <- do.call(.CDMN17P, parlist); } else if(p == -17) { results <- do.call(.CDMNT17P, parlist); } else if(p == 18) { results <- do.call(.CDMN18P, parlist); } else if(p == -18) { results <- do.call(.CDMNT18P, parlist); } else if(p == 19) { results <- do.call(.CDMN19P, parlist); } else if(p == -19) { results <- do.call(.CDMNT19P, parlist); } else if(p == 20) { results <- do.call(.CDMN20P, parlist); } else if(p == -20) { results <- do.call(.CDMNT20P, parlist); } else if(p == 21) { results <- do.call(.CDMN21P, parlist); } else if(p == -21) { results <- do.call(.CDMNT21P, parlist); } else if(p == 22) { results <- do.call(.CDMN22P, parlist); } else if(p == -22) { results <- do.call(.CDMNT22P, parlist); } else if(p == 23) { results <- do.call(.CDMN23P, parlist); } else if(p == -23) { results <- do.call(.CDMNT23P, parlist); } else if(p == 24) { results <- do.call(.CDMN24P, parlist); } else if(p == -24) { results <- do.call(.CDMNT24P, parlist); } else if(p == 25) { results <- do.call(.CDMN25P, parlist); } else if(p == -25) { results <- do.call(.CDMNT25P, parlist); } } else if(length(fleet.name) == 2) { parlist <- list(par=log(as.numeric(x$Model[[method]]$bt.par)), dates=x$Model[[method]]$Dates, obscat1=x$Data$Data[[fleet.name[1]]][,5], obseff1=x$Data$Data[[fleet.name[1]]][,2], obsmbm1=x$Data$Data[[fleet.name[1]]][,4], obscat2=x$Data$Data[[fleet.name[2]]][,5], obseff2=x$Data$Data[[fleet.name[2]]][,2], obsmbm2=x$Data$Data[[fleet.name[2]]][,4], distr=x$Model[[method]]$Distr, properties=x$Data$Properties, output="predict") if(sum(p==c(0,0)) == length(p)) { results <- do.call(.CDMN0P0P, parlist); } else if(sum(p==c(0,1)) == length(p)) { results <- do.call(.CDMN0P1P, parlist); } else if(sum(p==c(0,2)) == length(p)) { results <- do.call(.CDMN0P2P, parlist); } else if(sum(p==c(0,3)) == length(p)) { results <- do.call(.CDMN0P3P, parlist); } else if(sum(p==c(0,4)) == length(p)) { results <- do.call(.CDMN0P4P, parlist); } else if(sum(p==c(0,5)) == length(p)) { results <- do.call(.CDMN0P5P, parlist); } else if(sum(p==c(1,1)) == length(p)) { results <- do.call(.CDMN1P1P, parlist); } else if(sum(p==c(1,2)) == length(p)) { results <- do.call(.CDMN1P2P, parlist); } else if(sum(p==c(1,3)) == length(p)) { results <- do.call(.CDMN1P3P, parlist); } else if(sum(p==c(1,4)) == length(p)) { results <- do.call(.CDMN1P4P, parlist); } else if(sum(p==c(1,5)) == length(p)) { results <- do.call(.CDMN1P5P, parlist); } else if(sum(p==c(2,2)) == length(p)) { results <- do.call(.CDMN2P2P, parlist); } else if(sum(p==c(2,3)) == length(p)) { results <- do.call(.CDMN2P3P, parlist); } else if(sum(p==c(2,4)) == length(p)) { results <- do.call(.CDMN2P4P, parlist); } else if(sum(p==c(2,5)) == length(p)) { results <- do.call(.CDMN2P5P, parlist); } else if(sum(p==c(3,3)) == length(p)) { results <- do.call(.CDMN3P3P, parlist); } else if(sum(p==c(3,4)) == length(p)) { results <- do.call(.CDMN3P4P, parlist); } else if(sum(p==c(3,5)) == length(p)) { results <- do.call(.CDMN3P5P, parlist); } else if(sum(p==c(4,4)) == length(p)) { results <- do.call(.CDMN4P4P, parlist); } else if(sum(p==c(4,5)) == length(p)) { results <- do.call(.CDMN4P5P, parlist); } else if(sum(p==c(5,5)) == length(p)) { results <- do.call(.CDMN5P5P, parlist); } else if(sum(p==c(6,6)) == length(p)) { results <- do.call(.CDMN6P6P, parlist); } else if(sum(p==c(7,7)) == length(p)) { results <- do.call(.CDMN7P7P, parlist); } else if(sum(p==c(8,8)) == length(p)) { results <- do.call(.CDMN8P8P, parlist); } else if(sum(p==c(9,9)) == length(p)) { results <- do.call(.CDMN9P9P, parlist); } else if(sum(p==c(10,10)) == length(p)) { results <- do.call(.CDMN10P10P, parlist); } else if(sum(p==c(11,11)) == length(p)) { results <- do.call(.CDMN11P11P, parlist); } else if(sum(p==c(12,12)) == length(p)) { results <- do.call(.CDMN12P12P, parlist); } else if(sum(p==c(13,13)) == length(p)) { results <- do.call(.CDMN13P13P, parlist); } else if(sum(p==c(14,14)) == length(p)) { results <- do.call(.CDMN14P14P, parlist); } else if(sum(p==c(15,15)) == length(p)) { results <- do.call(.CDMN15P15P, parlist); } else if(sum(p==c(16,16)) == length(p)) { results <- do.call(.CDMN16P16P, parlist); } else if(sum(p==c(17,17)) == length(p)) { results <- do.call(.CDMN17P17P, parlist); } else if(sum(p==c(18,18)) == length(p)) { results <- do.call(.CDMN18P18P, parlist); } else if(sum(p==c(19,19)) == length(p)) { results <- do.call(.CDMN19P19P, parlist); } else if(sum(p==c(20,20)) == length(p)) { results <- do.call(.CDMN20P20P, parlist); } else if(sum(p==c(21,21)) == length(p)) { results <- do.call(.CDMN21P21P, parlist); } else if(sum(p==c(22,22)) == length(p)) { results <- do.call(.CDMN22P22P, parlist); } else if(sum(p==c(23,23)) == length(p)) { results <- do.call(.CDMN23P23P, parlist); } else if(sum(p==c(24,24)) == length(p)) { results <- do.call(.CDMN24P24P, parlist); } else if(sum(p==c(25,25)) == length(p)) { results <- do.call(.CDMN25P25P, parlist); } } results$Model$Method <- method; results$Model$AIC <- x$Model[[method]]$AIC; class(results) <- "CatDynMod"; return(results); }
library("testthat") library("tidywikidatar") test_that("check if image returned when valid id given", { testthat::skip_if_offline() expect_true( object = { tw_get_image( id = "Q2", cache = FALSE ) %>% tidyr::drop_na() %>% nrow() %>% as.logical() } ) tw_set_cache_folder(path = tempdir()) expect_true( object = { tw_get_image( id = "Q2", cache = TRUE ) %>% tidyr::drop_na() %>% nrow() %>% as.logical() } ) }) test_that("check if image returned when invalid id given", { testthat::skip_if_offline() expect_true( object = { tw_get_image(id = "non_qid_string") %>% is.null() } ) expect_true( object = { tw_get_image_same_length(id = "non_qid_string") %>% is.na() } ) expect_equal( object = { tw_get_image_same_length(id = c("non_qid_string", NA)) %>% is.na() %>% sum() }, expected = 2 ) expect_equal( object = { tw_get_image_same_length(id = c("non_qid_string", "Q2", "non_qid_string", NA)) %>% is.na() %>% which() }, expected = c(1, 3, 4) ) }) test_that("check if image metadata returned correctly with or without cache", { testthat::skip_if_offline() testthat::skip_on_cran() expect_equal( object = { df <- tw_get_image_metadata_single( id = c("Q2"), only_first = TRUE, cache = FALSE ) list( ncol = ncol(df), nrow = nrow(df), id = df %>% dplyr::pull(id) ) }, expected = list( ncol = 19, nrow = 1, id = "Q2" ) ) expect_equal( object = { tw_set_cache_folder(path = tempdir()) df <- tw_get_image_metadata( id = c("Q2", NA, "not_an_id", "Q5"), only_first = TRUE, cache = TRUE ) list( ncol = ncol(df), nrow = nrow(df), id = df %>% dplyr::pull(id), missing_image = which(is.na(df$image_filename)) ) }, expected = list( ncol = 19, nrow = 4, id = c("Q2", NA, "not_an_id", "Q5"), missing_image = c(2, 3) ) ) expect_equal( object = { tw_set_cache_folder(path = tempdir()) df <- tw_get_image_metadata( id = c("Q2", NA, "not_an_id", "Q5"), only_first = TRUE, cache = FALSE ) list( ncol = ncol(df), nrow = nrow(df), id = df %>% dplyr::pull(id) ) }, expected = list( ncol = 19, nrow = 4, id = c("Q2", NA, "not_an_id", "Q5") ) ) })
CovInfo <- function(data_part, sigma) { n0 <- data_part$Dims$n0 n1 <- data_part$Dims$n1 n2 <- data_part$Dims$n2 sigma_inv <- matInv(sigma) out <- array(0, dim = c(3, 3)) if (n0 > 0) { obs_info <- array(0, dim = c(3, 3)) obs_info[1, 1] <- sigma_inv[1, 1]^2 obs_info[2, 2] <- 2 * (sigma_inv[1, 2]^2 + sigma_inv[1, 1] * sigma_inv[2, 2]) obs_info[3, 3] <- sigma_inv[2, 2]^2 obs_info[1, 2] <- obs_info[2, 1] <- 2 * sigma_inv[1, 1] * sigma_inv[1, 2] obs_info[2, 3] <- obs_info[3, 2] <- 2 * sigma_inv[1, 2] * sigma_inv[2, 2] obs_info[1, 3] <- obs_info[3, 1] <- sigma_inv[1, 2]^2 out <- out + 0.5 * n0 * obs_info } if (n1 > 0) { out[3, 3] <- out[3, 3] + 0.5 * n1 / (sigma[2, 2]^2) } if (n2 > 0) { out[1, 1] <- out[1, 1] + 0.5 * n2 / (sigma[1, 1]^2) } return(out) }
diffquo <- function(data,tobs) { n = length(tobs); dtobs = diff(tobs); data = as.matrix(data); N = dim(data)[1]; n = dim(data)[2]; YI = matrix(nrow=N,ncol=(n-1)); diffdatak = rep(0,(n-1)); for (k in 1:N) { YI[k,] = diff(data[k,])/dtobs; } Xtilda = matrix(nrow=n,ncol=N); w = rep(0,n-2); for (i in 2:(n-1)) { w[i] = dtobs[i]/(dtobs[i-1]+dtobs[i]); for (j in 1:N) { Xtilda[i,j] = w[i]*YI[j,i-1]+(1-w[i])*YI[j,i]; } } for (j in 1:N) { Xtilda[1,j] = YI[j,1]; Xtilda[n,j] = YI[j,n-1]; } result = list(YI=YI,Xtilda=Xtilda); return(result); }
msdecompose <- function(y, lags=c(12), type=c("additive","multiplicative")){ type <- match.arg(type); ma <- function(y, order){ if (order%%2 == 0){ weigths <- c(0.5, rep(1, order - 1), 0.5) / order; } else { weigths <- rep(1, order) / order; } return(filter(y, weigths)) } obsInSample <- length(y); yNAValues <- is.na(y); if(type=="multiplicative"){ shiftedData <- FALSE; if(any(y[!yNAValues]<=0)){ yNAValues[] <- yNAValues | y<=0; } yInsample <- suppressWarnings(log(y)); } else{ yInsample <- y; } if(any(yNAValues)){ X <- cbind(1,poly(c(1:obsInSample),degree=min(max(trunc(obsInSample/10),1),5)), sinpi(matrix(c(1:obsInSample)*rep(c(1:max(lags)),each=obsInSample)/max(lags), ncol=max(lags)))); lmFit <- .lm.fit(X[!yNAValues,,drop=FALSE], matrix(yInsample[!yNAValues],ncol=1)); yInsample[yNAValues] <- (X %*% coef(lmFit))[yNAValues]; rm(X) } yName <- paste0(deparse(substitute(y)),collapse=""); obs <- length(y); lags <- sort(unique(lags)); lagsLength <- length(lags); ySmooth <- vector("list",lagsLength+1); ySmooth[[1]] <- yInsample; yClear <- vector("list",lagsLength); for(i in 1:lagsLength){ ySmooth[[i+1]] <- ma(yInsample,lags[i]); } trend <- ySmooth[[lagsLength+1]]; for(i in 1:lagsLength){ yClear[[i]] <- ySmooth[[i]] - ySmooth[[i+1]]; } patterns <- vector("list",lagsLength); for(i in 1:lagsLength){ patterns[[i]] <- vector("numeric",lags[i]); for(j in 1:lags[i]){ patterns[[i]][j] <- mean(yClear[[i]][(1:(obs/lags[i])-1)*lags[i]+j],na.rm=TRUE); } patterns[[i]][] <- patterns[[i]] - mean(patterns[[i]]); } initial <- c(ySmooth[[lagsLength]][!is.na(ySmooth[[lagsLength]])][1], mean(diff(ySmooth[[lagsLength]]),na.rm=T)); initial[1] <- initial[1] - initial[2]*floor(max(lags)/2); names(initial) <- c("level","trend"); if(type=="multiplicative"){ initial[] <- exp(initial); trend <- exp(trend); patterns[] <- lapply(patterns,exp); if(shiftedData){ initial[1] <- initial[1] - 1; trend[] <- trend -1; } } return(structure(list(y=y, initial=initial, trend=trend, seasonal=patterns, loss="MSE", lags=lags, type=type, yName=yName), class=c("msdecompose","smooth"))); } actuals.msdecompose <- function(object, ...){ return(object$y); } errorType.msdecompose <- function(object, ...){ if(object$type=="additive"){ return("A"); } else{ return("M"); } } fitted.msdecompose <- function(object, ...){ yFitted <- object$trend; obs <- nobs(object); if(object$type=="additive"){ for(i in 1:length(object$lags)){ yFitted <- yFitted + rep(object$seasonal[[i]],ceiling(obs/object$lags[i]))[1:obs]; } } else{ for(i in 1:length(object$lags)){ yFitted <- yFitted * rep(object$seasonal[[i]],ceiling(obs/object$lags[i]))[1:obs]; } } return(yFitted); } forecast.msdecompose <- function(object, h=10, interval=c("parametric","semiparametric","nonparametric","none"), level=0.95, model=NULL, ...){ interval <- match.arg(interval,c("parametric","semiparametric","nonparametric","none")); if(is.null(model)){ model <- switch(errorType(object), "A"="XXX", "M"="YYY"); } obs <- nobs(object); yDeseasonalised <- actuals(object); yForecastStart <- time(yDeseasonalised)[length(time(yDeseasonalised))]+1/frequency(yDeseasonalised); if(errorType(object)=="A"){ for(i in 1:length(object$lags)){ yDeseasonalised <- yDeseasonalised - rep(object$seasonal[[i]],ceiling(obs/object$lags[i]))[1:obs]; } } else{ for(i in 1:length(object$lags)){ yDeseasonalised <- yDeseasonalised / rep(object$seasonal[[i]],ceiling(obs/object$lags[i]))[1:obs]; } } yesModel <- suppressWarnings(es(yDeseasonalised,model=model,h=h,interval=interval,level=level,initial="b",...)); yValues <- ts(c(yDeseasonalised,yesModel$forecast),start=start(yDeseasonalised),frequency=frequency(yDeseasonalised)); if(interval!="none"){ lower <- ts(c(yDeseasonalised,yesModel$lower),start=start(yDeseasonalised),frequency=frequency(yDeseasonalised)); upper <- ts(c(yDeseasonalised,yesModel$upper),start=start(yDeseasonalised),frequency=frequency(yDeseasonalised)); } else{ lower <- upper <- NA; } if(errorType(object)=="A"){ for(i in 1:length(object$lags)){ yValues <- yValues + rep(object$seasonal[[i]],ceiling((obs+h)/object$lags[i]))[1:(obs+h)]; if(interval!="none"){ lower <- lower + rep(object$seasonal[[i]],ceiling((obs+h)/object$lags[i]))[1:(obs+h)]; upper <- upper + rep(object$seasonal[[i]],ceiling((obs+h)/object$lags[i]))[1:(obs+h)]; } } } else{ for(i in 1:length(object$lags)){ yValues <- yValues * rep(object$seasonal[[i]],ceiling((obs+h)/object$lags[i]))[1:(obs+h)]; if(interval!="none"){ lower <- lower * rep(object$seasonal[[i]],ceiling((obs+h)/object$lags[i]))[1:(obs+h)]; upper <- upper * rep(object$seasonal[[i]],ceiling((obs+h)/object$lags[i]))[1:(obs+h)]; } } } yForecast <- window(yValues,yForecastStart); if(interval!="none"){ lower <- window(lower,yForecastStart); upper <- window(upper,yForecastStart); } return(structure(list(model=object, esmodel=yesModel, method=paste0("ETS(",modelType(yesModel),") with decomposition"), mean=yForecast, forecast=yForecast, lower=lower, upper=upper, level=level, interval=interval),class=c("msdecompose.forecast","smooth.forecast","forecast"))); } is.msdecompose <- function(x){ return(inherits(x,"msdecompose")) } is.msdecompose.forecast <- function(x){ return(inherits(x,"msdecompose.forecast")) } lags.msdecompose <- function(object, ...){ return(object$lags); } modelType.msdecompose <- function(object, ...){ return("Multiple Seasonal Decomposition"); } nobs.msdecompose <- function(object, ...){ return(length(actuals(object))); } nparam.msdecompose <- function(object, ...){ return(length(object$lags)+1); } plot.msdecompose <- function(x, which=c(1,2,4,6), level=0.95, legend=FALSE, ask=prod(par("mfcol")) < length(which) && dev.interactive(), lowess=TRUE, ...){ ellipsis <- list(...); obs <- nobs(x); if(ask){ oask <- devAskNewPage(TRUE); on.exit(devAskNewPage(oask)); } if(any(which %in% c(1:6))){ plot.smooth(x, which=which[which %in% c(1:6)], level=level, legend=legend, ask=FALSE, lowess=lowess, ...); } if(any(which==7)){ ellipsis$x <- actuals(x); if(!any(names(ellipsis)=="ylab")){ ellipsis$ylab <- x$yName; } yFitted <- fitted(x); do.call(plot,ellipsis); lines(yFitted, col="red"); } if(any(which %in% c(8:11))){ plot.smooth(x, which=which[which %in% c(8:11)], level=level, legend=legend, ask=FALSE, lowess=lowess, ...); } if(any(which==12)){ yDecomposed <- cbind(actuals(x),x$trend); for(i in 1:length(x$seasonal)){ yDecomposed <- cbind(yDecomposed,rep(x$seasonal[[i]],ceiling(obs/x$lags[i]))[1:obs]); } yDecomposed <- cbind(yDecomposed, residuals(x)); colnames(yDecomposed) <- c("Actuals","Trend",paste0("Seasonal ",c(1:length(x$seasonal))),"Residuals"); if(!any(names(ellipsis)=="main")){ ellipsis$main <- paste0("Decomposition of ", x$yName); } ellipsis$x <- yDecomposed; do.call(plot,ellipsis); } } print.msdecompose <- function(x, ...){ cat(paste0("Multiple seasonal decomposition of ",x$yName," using c(",paste0(x$lags,collapse=","),") lags.\n")); cat("Type of decomposition:",x$type); } residuals.msdecompose <- function(object, ...){ if(errorType(object)=="A"){ return(actuals(object)-fitted(object)); } else{ return(log(actuals(object)/fitted(object))); } } sigma.msdecompose <- function(object, ...){ if(errorType(object)=="A"){ return(sqrt(mean(residuals(object)^2,na.rm=TRUE))); } else{ return(sqrt(mean(residuals(object)^2,na.rm=TRUE))); } }
ex_data_table_step.relop_set_indicator <- function(optree, ..., tables = list(), source_usage = NULL, source_limit = NULL, env = parent.frame()) { force(env) wrapr::stop_if_dot_args(substitute(list(...)), "rqdatatable::ex_data_table_step.relop_set_indicator") if(is.null(source_usage)) { source_usage <- columns_used(optree) } x <- ex_data_table_step(optree$source[[1]], tables = tables, source_usage = source_usage, source_limit = source_limit, env = env) x[[optree$rescol]] <- ifelse(x[[optree$testcol]] %in% optree$testvalues, 1, 0) x }
get_UT <- function(network, comid, distance = NULL) { if ("sf" %in% class(network)) network <- sf::st_set_geometry(network, NULL) network <- network %>% check_names("get_UT") %>% dplyr::select(get("get_UT_attributes", nhdplusTools_env)) start_comid <- get_start_comid(network, comid) if (!is.null(distance)) { if (distance < start_comid$LENGTHKM) return(comid) } all <- private_get_UT(network, comid) if (!is.null(distance)) { stop_pathlength <- start_comid$Pathlength - start_comid$LENGTHKM + distance network <- filter(network, COMID %in% all) return(filter(network, Pathlength <= stop_pathlength)$COMID) } else { return(all) } } private_get_UT <- function(network, comid) { main <- filter(network, COMID %in% comid) if (length(main$Hydroseq) == 1) { full_main <- filter(network, LevelPathI %in% main$LevelPathI & Hydroseq >= main$Hydroseq) trib_lpid <- filter(network, DnHydroseq %in% full_main$Hydroseq & !LevelPathI %in% main$LevelPathI & Hydroseq >= main$Hydroseq)$LevelPathI } else { full_main <- filter(network, LevelPathI %in% main$LevelPathI) trib_lpid <- filter(network, DnHydroseq %in% full_main$Hydroseq & !LevelPathI %in% main$LevelPathI)$LevelPathI } trib_comid <- filter(network, LevelPathI %in% trib_lpid)$COMID if (length(trib_comid) > 0) { return(c(full_main$COMID, private_get_UT(network, trib_comid))) } else { return(full_main$COMID) } } get_UM <- function(network, comid, distance = NULL, sort = FALSE, include = TRUE) { network <- check_names(network, "get_UM") main <- network %>% filter(COMID %in% comid) %>% select(COMID, LevelPathI, Hydroseq, Pathlength, LENGTHKM) main_us <- network %>% filter(LevelPathI %in% main$LevelPathI & Hydroseq >= main$Hydroseq) %>% select(COMID, Hydroseq, Pathlength, LENGTHKM) if (!is.null(distance)) { if (length(main$LENGTHKM) == 1) { if (main$LENGTHKM > distance) { return(main$COMID) } } stop_pathlength <- main$Pathlength - main$LENGTHKM + distance main_us <- filter(main_us, Pathlength <= stop_pathlength) } if(sort) { main_us <- arrange(main_us, Hydroseq) } if(!include) { main_us = filter(main_us, COMID != comid) } return(main_us$COMID) } get_DM <- function(network, comid, distance = NULL, sort = FALSE, include = TRUE) { if ("sf" %in% class(network)) { network <- sf::st_set_geometry(network, NULL) } type <- ifelse(is.null(distance), "get_DM_nolength", "get_DM") network <- network %>% check_names(type) %>% select(get(paste0(type, "_attributes"), nhdplusTools_env)) start_comid <- get_start_comid(network, comid) if (!is.null(distance)) { if (distance < start_comid$LENGTHKM){ return(comid) } } main_ds <- private_get_DM(network, comid) if (!is.null(distance)) { stop_pathlength <- start_comid$Pathlength + start_comid$LENGTHKM - distance main_ds <- network %>% filter(COMID %in% main_ds$COMID, (Pathlength + LENGTHKM) >= stop_pathlength) } if(sort){ main_ds <- arrange(main_ds, desc(Hydroseq)) } if(!include){ main_ds <- filter(main_ds, COMID != comid) } return(main_ds$COMID) } private_get_DM <- function(network, comid) { main <- ds_main <- filter(network, COMID %in% comid) if (length(main$Hydroseq) == 1) { ds_main <- network %>% filter(LevelPathI %in% main$LevelPathI & Hydroseq <= main$Hydroseq) } ds_hs <- ds_main %>% filter(!DnLevelPat %in% main$LevelPathI) %>% select(DnHydroseq) if (nrow(ds_hs) > 0) { ds_lpid <- network %>% filter(Hydroseq == ds_hs$DnHydroseq) %>% select(LevelPathI) if (nrow(ds_lpid) > 0) { ds_comid <- network %>% filter(LevelPathI == ds_lpid$LevelPathI & Hydroseq <= ds_hs$DnHydroseq) %>% select(COMID) return(rbind( select(ds_main, COMID, Hydroseq), private_get_DM(network, comid = ds_comid$COMID) )) } } return(select(ds_main, COMID, Hydroseq)) } get_DD <- function(network, comid, distance = NULL) { if ("sf" %in% class(network)) network <- sf::st_set_geometry(network, NULL) network <- network %>% check_names("get_DD") %>% dplyr::select(get("get_DD_attributes", nhdplusTools_env)) start_comid <- get_start_comid(network, comid) stop_pathlength <- 0 if (!is.null(distance)) { if (distance < start_comid$LENGTHKM) return(comid) stop_pathlength <- start_comid$Pathlength + start_comid$LENGTHKM - distance } all <- private_get_DD(network, comid, stop_pathlength) if (!is.null(distance)) { network <- filter(network, COMID %in% unique(all)) return(filter(network, (Pathlength + LENGTHKM) >= stop_pathlength)$COMID) } else { return(unique(all)) } } private_get_DD <- function(network, comid, stop_pathlength = 0) { main <- ds_main <- filter(network, COMID %in% comid) if (length(main$Hydroseq) == 1) { ds_main <- filter(network, LevelPathI %in% main$LevelPathI & Hydroseq <= main$Hydroseq) } ds_hs <- c(filter(ds_main, !DnLevelPat %in% main$LevelPathI)$DnHydroseq, filter(ds_main, !DnMinorHyd == 0)$DnMinorHyd) ds_lpid <- filter(network, Hydroseq %in% ds_hs)$LevelPathI if (length(ds_lpid) > 0) { if (length(ds_hs) == 1) { ds_comid <- filter(network, LevelPathI %in% ds_lpid & Hydroseq <= ds_hs)$COMID } else { ds_hs <- filter(network, Hydroseq %in% ds_hs) ds_comid <- filter(network, LevelPathI %in% ds_lpid) %>% dplyr::left_join(select(ds_hs, LevelPathI, max_Hydroseq = Hydroseq), by = "LevelPathI") %>% filter(Hydroseq <= .data$max_Hydroseq) ds_comid <- ds_comid$COMID } if (all(ds_main$Pathlength <= stop_pathlength)) return(ds_main$COMID) c(ds_main$COMID, private_get_DD(network, ds_comid, stop_pathlength)) } else { return(ds_main$COMID) } } get_start_comid <- function(network, comid) { start_comid <- filter(network, COMID == comid) if(nrow(start_comid) > 1) { stop("Found duplicate ID for starting catchment. Duplicate rows in network?") } start_comid }
make.directories <- function(homedir) { dir <- paste0(homedir, "/FAMoS-Results") if(!dir.exists(dir)){ dir.create(dir, showWarnings = F) } if(!dir.exists(paste0(dir, "/BestModel"))){ dir.create(paste0(dir, "/BestModel"), showWarnings = F) } if(!dir.exists(paste0(dir, "/Figures"))){ dir.create(paste0(dir, "/Figures"), showWarnings = F) } if(!dir.exists(paste0(dir, "/Fits"))){ dir.create(paste0(dir, "/Fits"), showWarnings = F) } if(!dir.exists(paste0(dir, "/TestedModels"))){ dir.create(paste0(dir, "/TestedModels"), showWarnings = F) } }
.runge_kutta4<- function(t, biomasses, model){ bioms <- matrix(NA, ncol = length(biomasses), nrow = length(t)) biom.step<- biomasses delta.t <- t[2] - t[1] for (i in 1:length(t)){ bioms[i, ] <- biom.step k1 <- model$ODE(biom.step, i*delta.t) k2 <- model$ODE(biom.step + 0.5*delta.t * k1, (i+0.5)*delta.t) k3 <- model$ODE(biom.step + 0.5*delta.t * k2, (i+0.5)*delta.t) k4 <- model$ODE(biom.step + delta.t * k3, i*delta.t) biom.step <- biom.step + (delta.t/6) * (k1 + 2*k2 + 2*k3 + k4) } return(cbind(t, bioms)) }
rln_clock_model_to_xml_mean_rate_prior <- function(rln_clock_model) { testit::assert(beautier::is_rln_clock_model(rln_clock_model)) id <- rln_clock_model$id testit::assert(beautier::is_id(id)) text <- NULL text <- c(text, paste0("<prior id=\"MeanRatePrior.c:", id, "\" ", "name=\"distribution\" x=\"@ucldMean.c:", id, "\">")) text <- c(text, beautier::indent( beautier::distr_to_xml( distr = rln_clock_model$mean_rate_prior_distr ) ) ) text <- c(text, paste0("</prior>")) text }
stepbins <- function(bEdges, bCounts, m=NULL, tailShape = c("onebin", "pareto", "exponential"), nTail=16, numIterations=20, pIndex=1.160964, tbRatio=0.8) { L <- length(bCounts) if(!(is.na(bEdges[L]) | is.infinite(bEdges[L]))) warning("Top bin is bounded. Expect inaccurate results.\n") if(is.null(m)) { warning("No mean provided: expect inaccurate results.\n") m <- sum(0.5*(c(bEdges[1:(L-1)],2.0*bEdges[L-1])+c(0, bEdges[1:(L-1)]))*bCounts/sum(bCounts)) } tailShape <- match.arg(tailShape) if(tailShape == "onebin") stepbinsNotail(bEdges, bCounts, m) else stepbinsTail(bEdges, bCounts, m, tailShape, nTail, numIterations, pIndex, tbRatio) } stepbinsTail <- function(bEdges, bCounts, m, tailShape = c("pareto", "exponential"), nTail, numIterations, pIndex, tbRatio) { tailShape <- match.arg(tailShape) L <- length(bCounts) tot <- sum(bCounts) e <- c(0,bEdges[1:(L-1)],numeric(nTail)) shrinkFactor <- 1 shrinkMultiplier <- 0.995 tailCount <- bCounts[L] bbtot <- tot-tailCount bbMean <- sum((e[2:(L)]+e[1:(L-1)])*bCounts[1:(L-1)])/(2*bbtot) while(m<bbMean) { e <- e*shrinkMultiplier bbMean <- sum((e[2:(L)]+e[1:(L-1)])*bCounts[1:(L-1)])/(2*bbtot) shrinkFactor <- shrinkFactor*shrinkMultiplier } if(tailCount>0) { L <- L+nTail-1 tailArea <- tailCount/tot bAreas <- c(bCounts/tot, numeric(nTail-1)) tbWidth <- e[L-nTail+1]-e[L-nTail] h <- bAreas[L-nTail]/tbWidth if(tailShape=="pareto") tailUnscaled <- (1:nTail)^(-1-pIndex) else tailUnscaled <- tbRatio^(1:nTail) bAreas[(L-nTail+1):(L)] <- tailUnscaled/sum(tailUnscaled)*tailArea repeat { e[(L-nTail+2):(L+1)] <- e[L-nTail+1]+(1:(nTail))*tbWidth bMean <- sum((e[2:(L+1)]+e[1:L])*bAreas)/2 if(bMean>m) break tbWidth <- tbWidth*2 } l <- 0 r <- tbWidth for(i in 1:numIterations) { tbWidth <- (l+r)/2 e[(L-nTail+2):(L+1)] <- e[L-nTail+1]+(1:(nTail))*tbWidth bMean <- sum((e[2:(L+1)]+e[1:L])*bAreas)/2 if (bMean<m) l <- tbWidth else r <- tbWidth } } else { L <- L-1 bAreas <- bCounts[1:L]/tot e <- e[1:(L+1)] } cAreas <- vapply(1:length(bAreas), function(x){sum(bAreas[1:x])}, numeric(1)) bHeights <- bAreas/(e[2:(L+1)]-e[1:L]) stepCDF <- approxfun(e, c(0, cAreas), yleft=0, yright=1, rule=2) stepPDF <- stepfun(e, c(0, bHeights, 0)) return(list(stepPDF=stepPDF, stepCDF=stepCDF, E=e[L+1], shrinkFactor=shrinkFactor)) } stepbinsNotail <- function(bEdges, bCounts, m) { L <- length(bCounts) tot <- sum(bCounts) p <- c(1,1-vapply(1:(L-1), function(x){sum(bCounts[1:x])}, numeric(1))/tot) e <- c(0,bEdges[1:(L-1)],0) A <- 0.5*sum((e[2:L]-e[1:(L-1)])*(p[2:L]+p[1:(L-1)])) shrinkFactor <- 1 shrinkMultiplier <- 0.995 while(m<A) { e <- e*shrinkMultiplier A <- 0.5*sum((e[2:L]-e[1:(L-1)])*(p[2:L]+p[1:(L-1)])) shrinkFactor <- shrinkFactor*shrinkMultiplier } E <- ifelse(p[L]>0, bEdges[L-1]+2*(m-A)/p[L], bEdges[L-1]*1.001) e[L+1] <- E bAreas <- bCounts/tot cAreas <- vapply(1:length(bAreas), function(x){sum(bAreas[1:x])}, numeric(1)) bHeights <- bAreas/(e[2:(L+1)]-e[1:L]) stepCDF <- approxfun(e, c(0, cAreas), yleft=0, yright=1, rule=2) stepPDF <- stepfun(e, c(0, bHeights, 0)) return(list(stepPDF=stepPDF, stepCDF=stepCDF, E=E, shrinkFactor=shrinkFactor)) }
`deg.theta` <- function(LC,degen.r,degen.x.i,degen.theta,steps, maxchange=1){ Pxji <- array(apply(LC$item.par$delta,2,P.xj, th=degen.theta), dim=c(steps,length(degen.theta),LC$i.stat$n.i)) degen.x.i <- matrix(! is.na(degen.x.i), nrow=length(degen.r)) der <- d.v(Pxji, degen.r, degen.x.i) der$d1d2 <- ifelse(abs(der$d1d2) > maxchange, sign(der$d1d2)*maxchange, der$d1d2) degen.theta <- degen.theta - der$d1d2 degen.theta }
listonator<-function(check=TRUE){ blend <- getOption("blend") homefolder <- getOption("homefolder") if(!exists("liston") & blend & check){ liston<-readecad(paste0(homefolder,'raw/stations.txt')) names(liston)<-c('STAID','STANAME','CN','LAT','LON','HGHT') }else{ if(!exists("liston") & isTRUE(check)){ liston<-listas() } } lat<-apply(as.data.frame(liston$LAT),1,FUN=decimaldegrees) lon<-apply(as.data.frame(liston$LON),1,FUN=decimaldegrees) coordinates<-data.frame(lat,lon) liston$LAT<-lat liston$LON<-lon options("liston"=liston) }
computeLeafColorIdxs<-function ( df ) { leafColorIdxs<-rep(0,df$n) for (i in seq(along=df$clusters)) { if (!is.null(df$clusters[[i]]) && length(df$clusters[[i]]$indices)>0) { members<-computeMemberIndices(df$h,max(df$clusters[[i]]$indices)) leafColorIdxs[members]<-i } } return(leafColorIdxs) }
get_city_issues <- function(city=NULL, lat=NULL,long=NULL, status = "open,acknowledged,closed,archived", limit = 100) { total <- 0 page <- 1 pagelimit <- min(100,limit) if(length(city)>0 & (length(lat)>0 | length(long)>0)){ lat <- NULL long <- NULL warning("Cannot specify both city and lat/long locations. Using city...") } if((length(lat)>0 & length(long)<1) | length(lat)<1 & length(long)>0){ stop("Specify valid lat/long pair or city") } url <- paste("https://seeclickfix.com/api/v2/issues?", ifelse(length(city)>0,paste("place_url=",city,sep=""),""),ifelse(length(lat)>0,paste("lat=", lat,"&lng=",long,sep=""),""),"&status=",status, "&per_page=",pagelimit,"&page=",page, sep = "") url <- gsub(" ","%20",x=url) rawdata <- RCurl::getURL(url) scf <- jsonlite::fromJSON(txt=rawdata,simplifyDataFrame = T,flatten=F) issue_id = scf$issues$id issue_status = scf$issues$status summary = scf$issues$summary description = scf$issues$description rating = scf$issues$rating lat = scf$issues$lat lng = scf$issues$lng issue_address = scf$issues$address created_at = scf$issues$created_at acknowledged_at = scf$issues$acknowledged_at closed_at = scf$issues$closed_at reopened_at = scf$issues$reopened_at updated_at = scf$issues$updated_at shortened_url = scf$issues$shortened_url video_url = scf$issues$media$video_url image_full = scf$issues$media$image_full image_square_100x100 = scf$issues$media$image_square_100x100 representative_image_url = scf$issues$media$representative_image_url issue_types = scf$issues$point$type url = scf$issues$url html_url = scf$issues$html_url comment_url = scf$issues$comment_url flag_url = scf$issues$flag_url close_url = if(length(scf$issues$transitions$close_url)>0){scf$issues$transitions$close_url} else{NA} open_url = if(length(scf$issues$transitions$open_url)>0){scf$issues$transitions$open_url} else{NA} reporter_id = scf$issues$reporter$id reporter_name = scf$issues$reporter$name reporter_wittytitle = scf$issues$reporter$witty_title reporter_role = scf$issues$reporter$role reporter_civicpoints = scf$issues$reporter$civic_points reporter_avatar_full = scf$issues$reporter$avatar$full reporter_avatar_square = scf$issues$reporter$avatar$square_100x100 allout <- data.frame( issue_id, issue_status, summary, description, rating, lat, lng, issue_address, created_at, acknowledged_at, closed_at, reopened_at, updated_at, shortened_url, video_url, image_full, image_square_100x100, representative_image_url, issue_types, url, html_url, comment_url, flag_url, close_url, open_url, reporter_id, reporter_name, reporter_wittytitle, reporter_role, reporter_civicpoints, reporter_avatar_full, reporter_avatar_square ) total <- nrow(allout) limit <- min(limit,scf$metadata$pagination$entries) while(limit>total){ page <- page+1 if((limit-total)<100){pagelimit <- (limit-total)} url <- paste("https://seeclickfix.com/api/v2/issues?place_url=", city,"&status=",status, "&per_page=",pagelimit,"&page=",page, sep = "") rawdata <- readLines(url, warn = F) scf <- jsonlite::fromJSON(txt=rawdata,simplifyDataFrame = T,flatten=F) issue_id = scf$issues$id issue_status = scf$issues$status summary = scf$issues$summary description = scf$issues$description rating = scf$issues$rating lat = scf$issues$lat lng = scf$issues$lng issue_address = scf$issues$address created_at = scf$issues$created_at acknowledged_at = scf$issues$acknowledged_at closed_at = scf$issues$closed_at reopened_at = scf$issues$reopened_at updated_at = scf$issues$updated_at shortened_url = scf$issues$shortened_url video_url = scf$issues$media$video_url image_full = scf$issues$media$image_full image_square_100x100 = scf$issues$media$image_square_100x100 representative_image_url = scf$issues$media$representative_image_url issue_types = scf$issues$point$type url = scf$issues$url html_url = scf$issues$html_url comment_url = scf$issues$comment_url flag_url = scf$issues$flag_url close_url = if(length(scf$issues$transitions$close_url)>0){scf$issues$transitions$close_url} else{NA} open_url = if(length(scf$issues$transitions$open_url)>0){scf$issues$transitions$open_url} else{NA} reporter_id = scf$issues$reporter$id reporter_name = scf$issues$reporter$name reporter_wittytitle = scf$issues$reporter$witty_title reporter_role = scf$issues$reporter$role reporter_civicpoints = scf$issues$reporter$civic_points reporter_avatar_full = scf$issues$reporter$avatar$full reporter_avatar_square = scf$issues$reporter$avatar$square_100x100 holder <- data.frame( issue_id, issue_status, summary, description, rating, lat, lng, issue_address, created_at, acknowledged_at, closed_at, reopened_at, updated_at, shortened_url, video_url, image_full, image_square_100x100, representative_image_url, issue_types, url, html_url, comment_url, flag_url, close_url, open_url, reporter_id, reporter_name, reporter_wittytitle, reporter_role, reporter_civicpoints, reporter_avatar_full, reporter_avatar_square ) allout <- rbind(allout,holder) total <- nrow(allout) } return(allout) }
ActivePathways <- function(scores, gmt, background = makeBackground(gmt), geneset.filter = c(5, 1000), cutoff = 0.1, significant = 0.05, merge.method = c("Brown", "Fisher"), correction.method = c("holm", "fdr", "hochberg", "hommel", "bonferroni", "BH", "BY", "none"), cytoscape.file.tag = NA, color_palette = NULL, custom_colors = NULL, color_integrated_only = " merge.method <- match.arg(merge.method) correction.method <- match.arg(correction.method) if (!(is.matrix(scores) && is.numeric(scores))) stop("scores must be a numeric matrix") if (any(is.na(scores))) stop("scores may not contain missing values") if (any(scores < 0) || any(scores > 1)) stop("All values in scores must be in [0,1]") if (any(duplicated(rownames(scores)))) stop("Scores matrix contains duplicated genes - rownames must be unique.") stopifnot(length(cutoff) == 1) stopifnot(is.numeric(cutoff)) if (cutoff < 0 || cutoff > 1) stop("cutoff must be a value in [0,1]") stopifnot(length(significant) == 1) stopifnot(is.numeric(significant)) if (significant < 0 || significant > 1) stop("significant must be a value in [0,1]") if (!is.GMT(gmt)) gmt <- read.GMT(gmt) if (length(gmt) == 0) stop("No pathways in gmt made the geneset.filter") if (!(is.character(background) && is.vector(background))) { stop("background must be a character vector") } if (!is.null(geneset.filter)) { if (!(is.numeric(geneset.filter) && is.vector(geneset.filter))) { stop("geneset.filter must be a numeric vector") } if (length(geneset.filter) != 2) stop("geneset.filter must be length 2") if (!is.numeric(geneset.filter)) stop("geneset.filter must be numeric") if (any(geneset.filter < 0, na.rm=TRUE)) stop("geneset.filter limits must be positive") } if (!is.null(custom_colors)){ if(!(is.character(custom_colors) && is.vector(custom_colors))){ stop("colors must be provided as a character vector") } if(length(colnames(scores)) != length(custom_colors)) stop("incorrect number of colors is provided") } if (!is.null(custom_colors) & !is.null(color_palette)){ stop("Both custom_colors and color_palette are provided. Specify only one of these parameters for node coloring.") } if (!is.null(color_palette)){ if (!(color_palette %in% rownames(RColorBrewer::brewer.pal.info))) stop("palette must be from the RColorBrewer package") } if(!(is.character(color_integrated_only) && is.vector(color_integrated_only))){ stop("color must be provided as a character vector") } if(1 != length(color_integrated_only)) stop("only a single color must be specified") contribution <- TRUE if (ncol(scores) == 1) { contribution <- FALSE message("Scores matrix contains only one column. Column contributions will not be calculated.") } if(!is.null(geneset.filter)) { orig.length <- length(gmt) if (!is.na(geneset.filter[1])) { gmt <- Filter(function(x) length(x$genes) >= geneset.filter[1], gmt) } if (!is.na(geneset.filter[2])) { gmt <- Filter(function(x) length(x$genes) <= geneset.filter[2], gmt) } if (length(gmt) == 0) stop("No pathways in gmt made the geneset.filter") if (length(gmt) < orig.length) { message(paste(orig.length - length(gmt), "terms were removed from gmt", "because they did not make the geneset.filter")) } } orig.length <- nrow(scores) scores <- scores[rownames(scores) %in% background, , drop=FALSE] if (nrow(scores) == 0) { stop("scores does not contain any genes in the background") } if (nrow(scores) < orig.length) { message(paste(orig.length - nrow(scores), "rows were removed from scores", "because they are not found in the background")) } merged.scores <- merge_p_values(scores, merge.method) merged.scores <- merged.scores[merged.scores <= cutoff] if (length(merged.scores) == 0) stop("No genes made the cutoff") ordered.scores <- names(merged.scores)[order(merged.scores)] res <- enrichmentAnalysis(ordered.scores, gmt, background) adjusted_p <- stats::p.adjust(res$adjusted.p.val, method = correction.method) res[, "adjusted.p.val" := adjusted_p] significant.indeces <- which(res$adjusted.p.val <= significant) if (length(significant.indeces) == 0) { warning("No significant terms were found.") return() } if (contribution) { sig.cols <- columnSignificance(scores, gmt, background, cutoff, significant, correction.method, res$adjusted.p.val) res <- cbind(res, sig.cols[, -1]) } else { sig.cols <- NULL } if (length(significant.indeces) > 0 & !is.na(cytoscape.file.tag)) { prepareCytoscape(res[significant.indeces, c("term.id", "term.name", "adjusted.p.val")], gmt[significant.indeces], cytoscape.file.tag, sig.cols[significant.indeces,], color_palette, custom_colors, color_integrated_only) } res[significant.indeces] } enrichmentAnalysis <- function(genelist, gmt, background) { dt <- data.table(term.id=names(gmt)) for (i in 1:length(gmt)) { term <- gmt[[i]] tmp <- orderedHypergeometric(genelist, background, term$genes) overlap <- genelist[1:tmp$ind] overlap <- overlap[overlap %in% term$genes] if (length(overlap) == 0) overlap <- NA set(dt, i, 'term.name', term$name) set(dt, i, 'adjusted.p.val', tmp$p.val) set(dt, i, 'term.size', length(term$genes)) set(dt, i, 'overlap', list(list(overlap))) } dt } columnSignificance <- function(scores, gmt, background, cutoff, significant, correction.method, pvals) { dt <- data.table(term.id=names(gmt), evidence=NA) for (col in colnames(scores)) { col.scores <- scores[, col, drop=TRUE] col.scores <- col.scores[col.scores <= cutoff] col.scores <- names(col.scores)[order(col.scores)] res <- enrichmentAnalysis(col.scores, gmt, background) set(res, i = NULL, "adjusted.p.val", stats::p.adjust(res$adjusted.p.val, correction.method)) set(res, i = which(res$adjusted.p.val > significant), "overlap", list(list(NA))) set(dt, i=NULL, col, res$overlap) } ev_names = colnames(dt[,-1:-2]) set_evidence <- function(x) { ev <- ev_names[!is.na(dt[x, -1:-2])] if(length(ev) == 0) { if (pvals[x] <= significant) { ev <- 'combined' } else { ev <- 'none' } } ev } evidence <- lapply(1:nrow(dt), set_evidence) set(dt, i=NULL, "evidence", evidence) colnames(dt)[-1:-2] = paste0("Genes_", colnames(dt)[-1:-2]) dt } export_as_CSV = function (res, file_name) { data.table::fwrite(res, file_name) }
iucn_getname <- function(name, verbose = TRUE, ...) { mssg(verbose, "searching Global Names ...") all_names <- gni_search(sci = name, parse_names = TRUE) if (NROW(all_names) == 0) { stop("No names found matching ", name, call. = FALSE) } mssg(verbose, "searching IUCN...") out <- suppressWarnings(iucn_summary(all_names$canonical, ...)) x <- all_names$canonical[!sapply(out, function(x) x$status) %in% NA] unique(as.character(x)) }
xtraR <- system.file("xtraR", package="robustlmm") source(file.path(xtraR, "unitTestBase.R")) source(file.path(xtraR, "unitTestObjects.R")) test.s <- function(i) { cat("test.s for", names(rPDs)[i],"...") ltest <- function() { actual <- rPDASs[[i]]$s_e() expected <- .s(theta = FALSE, pp = rPDASTests[[i]]) stopifnot(all.equal(actual, expected, check.attributes = FALSE, tolerance = 5e-6)) } lsetTheta <- function(theta) { rPDASs[[i]]$setTheta(theta) rPDASTests[[i]]$setTheta(theta) } on.exit({ lsetTheta(getME(fms[[i]], "theta")) gc() }) ltest() testBlocks(fms[[i]], ltest, lsetTheta) if (i == 4) { lsetTheta(c(1.46725, 0.5210227, 0.1587546)) ltest() lsetTheta(c(0.2533617, 0.6969634, 0.5566632 )) ltest() } cat("ok\n") } for (i in seq_along(rPDASs)) test.s(i) test.kappaTau <- function(i) { cat("test.kappaTau for", names(rPDs)[i],"...") ltest <- function() { expected <- rPDASTests[[i]]$kappa_e actual <- rPDASs[[i]]$kappa_e() stopifnot(all.equal(actual, expected, check.attributes = FALSE, tolerance = 5e-6)) expected <- rPDASTests[[i]]$kappa_b actual <- rPDASs[[i]]$kappa_b() stopifnot(all.equal(actual, expected, check.attributes = FALSE, tolerance = 5e-5)) } ltest() gc() cat("ok\n") } for (i in seq_along(rPDASs)) test.kappaTau(i) test.updateMatrices <- function(i) { cat("test.updateMatrices for", names(rPDs)[i],"...") ltest <- function() { expected <- as.matrix(rPDASTests[[i]]$A) actual <- rPDASs[[i]]$A() stopifnot(all.equal(actual, expected, check.attributes = FALSE)) expected <- as.matrix(rPDASTests[[i]]$Kt) actual <- rPDASs[[i]]$Kt() stopifnot(all.equal(actual, expected, check.attributes = FALSE)) expected <- as.matrix(rPDASTests[[i]]$L) actual <- rPDASs[[i]]$L() stopifnot(all.equal(actual, expected, check.attributes = FALSE, tolerance = 1e-6)) } lsetTheta <- function(theta) { rPDASs[[i]]$setTheta(theta) rPDASTests[[i]]$setTheta(theta) } on.exit({ lsetTheta(getME(fms[[i]], "theta")) gc() }) ltest() testBlocks(fms[[i]], ltest, lsetTheta) if (i == 4) { lsetTheta(c(1.46725, 0.5210227, 0.1587546)) ltest() lsetTheta(c(0.2533617, 0.6969634, 0.5566632 )) ltest() } cat("ok\n") } for (i in seq_along(rPDASs)) test.updateMatrices(i) test.tau_e <- function(i) { cat("test.tau_e for", names(rPDs)[i], "...") ltest <- function() { Tau <- with(rPDASTests[[i]], V_e - EDpsi_e * (t(A) + A) + Epsi2_e * tcrossprod(A) + B() %*% tcrossprod(Epsi_bpsi_bt, B())) expected <- sqrt(diag(Tau)) actual <- rPDASs[[i]]$tau_e() stopifnot(all.equal(actual, expected, check.attributes = FALSE, tolerance = 5e-6)) } lsetTheta <- function(theta) { rPDASs[[i]]$setTheta(theta) rPDASTests[[i]]$setTheta(theta) } on.exit({ lsetTheta(getME(fms[[i]], "theta")) gc() }) ltest() testBlocks(fms[[i]], ltest, lsetTheta) if (i == 4) { lsetTheta(c(1.46725, 0.5210227, 0.1587546)) ltest() lsetTheta(c(0.2533617, 0.6969634, 0.5566632 )) ltest() } cat("ok\n") } for (i in seq_along(rPDASs)) test.tau_e(i) test.Tau_b <- function(i) { cat("test.Tau_b for", names(rPDs)[i], "...") ltest <- function() { expected <- as.matrix(rPDASTests[[i]]$Tb()) actual <- as.matrix(rPDASs[[i]]$Tb()) stopifnot(all.equal(actual, expected, check.attributes = FALSE, tolerance = 5e-5)) } lsetTheta <- function(theta) { rPDASs[[i]]$setTheta(theta) rPDASTests[[i]]$setTheta(theta) } on.exit({ lsetTheta(getME(fms[[i]], "theta")) gc() }) ltest() testBlocks(fms[[i]], ltest, lsetTheta) if (i == 4) { lsetTheta(c(1.46725, 0.5210227, 0.1587546)) ltest() lsetTheta(c(0.2533617, 0.6969634, 0.5566632 )) ltest() } cat("ok\n") } for (i in seq_along(rPDASs)) test.Tau_b(i)
fpd <- function (state,phy) { m<-sum(state) nspecies<-length(state) aa<-order(phy$edge[,1],decreasing=T) phy$edge<-phy$edge[aa,] phy$edge.length<-phy$edge.length[aa] anc<-phy$edge[seq(from=1,by=2,length.out=length(phy$edge[,1])/2),1] des<-matrix(phy$edge[,2],ncol=2,byrow=T) DES<-matrix(0,phy$Nnode,nspecies) for (i in 1:phy$Nnode) { tmp<-des[i,] offs<-which(anc %in% des[i,]) while (length(offs)>0) { tmp<-c(tmp,des[offs,]) offs<-which(anc %in% des[offs,]) } tmp<-tmp[tmp<=nspecies] DES[i,tmp]<-1 } DES<-rbind(diag(nspecies),DES) BL<-phy$edge.length[c(order(phy$edge[,2])[1:nspecies],order(phy$edge[,2],decreasing=T)[-c((nspecies-1):(2*nspecies-2))])] BL<-c(BL,0) V<-crossprod(DES,DES*BL) bmstate<-mvtnorm::rmvnorm(n=1000,sigma=V) bmthred<-apply(bmstate,1,quantile,m/nspecies) bmstate<-sweep(bmstate,1,bmthred,'<') bmstate<-matrix(as.numeric(bmstate),1000,nspecies) rdstate<-replicate(1000,sample(state,size=nspecies,replace=F)) rdstate<-t(rdstate) calD <- function (state,anc,des,phy) { I<-rep(NA,phy$Nnode) I<-c(state,I) for (i in 1:phy$Nnode) { I[anc[i]]<-mean(I[des[i,]]) } out<-I[des] out<-abs(out[1:phy$Nnode]-out[(phy$Nnode+1):(2*phy$Nnode)]) sum(out) } obsD<-calD(state,anc,des,phy) bmD<-apply(bmstate,1,calD,anc,des,phy) rdD<-apply(rdstate,1,calD,anc,des,phy) (obsD-mean(bmD))/(mean(rdD)-mean(bmD)) }
structure(list(url = "https://api.scryfall.com/cards/search?q=asdf&unique=cards&order=name&dir=auto&include_extras=false&include_multilingual=false&include_variations=false", status_code = 404L, headers = structure(list(date = "Wed, 05 Jan 2022 05:17:46 GMT", `content-type` = "application/json; charset=utf-8", `x-frame-options` = "DENY", `x-xss-protection` = "1; mode=block", `x-content-type-options` = "nosniff", `x-download-options` = "noopen", `x-permitted-cross-domain-policies` = "none", `referrer-policy` = "strict-origin-when-cross-origin", `access-control-allow-origin` = "*", `access-control-allow-methods` = "GET, POST, DELETE, OPTIONS", `access-control-allow-headers` = "Accept, Accept-Charset, Accept-Language, Authorization, Cache-Control, Content-Language, Content-Type, DNT, Host, If-Modified-Since, Keep-Alive, Origin, Referer, User-Agent, X-Requested-With", `access-control-max-age` = "300", `x-robots-tag` = "none", `cache-control` = "public, max-age=7200", `x-action-cache` = "MISS", vary = "Accept-Encoding", `content-encoding` = "gzip", `strict-transport-security` = "max-age=31536000; includeSubDomains; preload", via = "1.1 vegur", `cf-cache-status` = "HIT", age = "5039", `expect-ct` = "max-age=604800, report-uri=\"https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct\"", `report-to` = "{\"endpoints\":[{\"url\":\"https:\\/\\/a.nel.cloudflare.com\\/report\\/v3?s=u%2BUnCP4pW5E702xi3kPH%2FZgBgRZy%2FyOW8hvvWYIPR1q9crsX0MMntgvnmKyI4pWNNsna210iqzUQQJPCFQ9bwCfIQ2CFx0e3OAOWrnFx%2FyPf8VN4bpXxH0Rrre16j3KdSS2PUY7Y5Cal%2Fr4gMwE%3D\"}],\"group\":\"cf-nel\",\"max_age\":604800}", nel = "{\"success_fraction\":0,\"report_to\":\"cf-nel\",\"max_age\":604800}", server = "cloudflare", `cf-ray` = "6c8a3dfc28674edd-GRU", `alt-svc` = "h3=\":443\"; ma=86400, h3-29=\":443\"; ma=86400, h3-28=\":443\"; ma=86400, h3-27=\":443\"; ma=86400"), class = c("insensitive", "list")), all_headers = list(list(status = 404L, version = "HTTP/2", headers = structure(list(date = "Wed, 05 Jan 2022 05:17:46 GMT", `content-type` = "application/json; charset=utf-8", `x-frame-options` = "DENY", `x-xss-protection` = "1; mode=block", `x-content-type-options` = "nosniff", `x-download-options` = "noopen", `x-permitted-cross-domain-policies` = "none", `referrer-policy` = "strict-origin-when-cross-origin", `access-control-allow-origin` = "*", `access-control-allow-methods` = "GET, POST, DELETE, OPTIONS", `access-control-allow-headers` = "Accept, Accept-Charset, Accept-Language, Authorization, Cache-Control, Content-Language, Content-Type, DNT, Host, If-Modified-Since, Keep-Alive, Origin, Referer, User-Agent, X-Requested-With", `access-control-max-age` = "300", `x-robots-tag` = "none", `cache-control` = "public, max-age=7200", `x-action-cache` = "MISS", vary = "Accept-Encoding", `content-encoding` = "gzip", `strict-transport-security` = "max-age=31536000; includeSubDomains; preload", via = "1.1 vegur", `cf-cache-status` = "HIT", age = "5039", `expect-ct` = "max-age=604800, report-uri=\"https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct\"", `report-to` = "{\"endpoints\":[{\"url\":\"https:\\/\\/a.nel.cloudflare.com\\/report\\/v3?s=u%2BUnCP4pW5E702xi3kPH%2FZgBgRZy%2FyOW8hvvWYIPR1q9crsX0MMntgvnmKyI4pWNNsna210iqzUQQJPCFQ9bwCfIQ2CFx0e3OAOWrnFx%2FyPf8VN4bpXxH0Rrre16j3KdSS2PUY7Y5Cal%2Fr4gMwE%3D\"}],\"group\":\"cf-nel\",\"max_age\":604800}", nel = "{\"success_fraction\":0,\"report_to\":\"cf-nel\",\"max_age\":604800}", server = "cloudflare", `cf-ray` = "6c8a3dfc28674edd-GRU", `alt-svc` = "h3=\":443\"; ma=86400, h3-29=\":443\"; ma=86400, h3-28=\":443\"; ma=86400, h3-27=\":443\"; ma=86400"), class = c("insensitive", "list")))), cookies = structure(list(domain = ".api.scryfall.com", flag = TRUE, path = "/", secure = FALSE, expiration = structure(1641440572, class = c("POSIXct", "POSIXt")), name = "heroku-session-affinity", value = "REDACTED"), row.names = c(NA, -1L), class = "data.frame"), content = charToRaw("{\n \"object\": \"error\",\n \"code\": \"not_found\",\n \"status\": 404,\n \"details\": \"Your query didn’t match any cards. Adjust your search terms or refer to the syntax guide at https://scryfall.com/docs/reference\"\n}"), date = structure(1641359866, class = c("POSIXct", "POSIXt" ), tzone = "GMT"), times = c(redirect = 0, namelookup = 5.4e-05, connect = 5.4e-05, pretransfer = 0.000165, starttransfer = 0.016477, total = 0.016545)), class = "response")
computeDistancesToNearestClusterCenter = function(cluster.centers) { n = nrow(cluster.centers) min.distance.idx = numeric(n) max.distance.idx = numeric(n) min.distance = numeric(n) max.distance = numeric(n) for (i in seq(n)) { distances = apply(cluster.centers, 1, function(x) { sqrt(sum((x - cluster.centers[i, ])^2)) }) distances[i] = Inf min.distance.idx[i] = which.min(distances) min.distance[i] = min(distances) distances[i] = 0 max.distance[i] = max(distances) max.distance.idx[i] = which.max(distances) } return(list( min.distance = min.distance, min.distance.idx = min.distance.idx, max.distance = max.distance, max.distance.idx = max.distance.idx )) }
pkg_ref_cache.license <- function(x, ...) { UseMethod("pkg_ref_cache.license") } pkg_ref_cache.license.default <- function(x, ...) { if ("License" %in% colnames(x$description)) unname(x$description[,"License"]) else NA_character_ } pkg_ref_cache.license.pkg_cran_remote <- function(x, ...) { license_xpath <- "//td[.='License:']/following::td[1]" license_nodes <- xml_find_all(x$web_html, xpath = license_xpath) xml_text(license_nodes) } pkg_ref_cache.license.pkg_bioc_remote <- function(x, ...) { license_xpath <- "//td[.='License']/following::td[1]" license_nodes <- xml_find_all(x$web_html, xpath = license_xpath) xml_text(license_nodes) }
ComDim <- function(X, group, algo="eigen", ncompprint=NULL, scale="none", option="uniform", nstart=10, threshold=1e-8, plotgraph=TRUE, axes=c(1,2)){ if (any(is.na(X))) stop("No NA values are allowed") if (sum(group) != ncol(X)) stop("The sum of group must be equal to the total number of variables of in all the blocks") if (!algo %in% c("eigen", "nipals")) stop("algo must be either eigen or nipals") if (is.character(scale)) { if (!scale %in% c("none","sd")) stop("scale must be either none or sd") } else { if (!is.numeric(scale) | length(scale)!=ncol(X)) stop("Non convenient scaling parameter") } if (!option %in% c("none","uniform")) stop("option must be either none or uniform") X <- as.matrix(X) if (is.null(rownames(X))) rownames(X) <- paste("Ind.", seq_len(nrow(X)), sep="") if (is.null(colnames(X))) colnames(X) <- paste("X", seq_len(ncol(X)), sep=".") if (is.null(names(group))) names(group) <- paste("Block", 1:length(group), sep=" ") ntab <- length(group); nind <- nrow(X) ncolX <- sum(group) ncomp <- min(nind-1, ncolX) if (is.null(ncompprint)) ncompprint=ncomp if (ncompprint > ncomp) stop(cat("\n ncompprint should be less or equal to", ncomp,".\n")) J <- rep(1:ntab,group) critnstart <- matrix(0,nstart,ncomp) niteration <- matrix(0,nstart,ncomp) dimnames(critnstart) <- dimnames(niteration) <- list(paste("Iter.",1:nstart,sep=""), paste("Dim.",1:ncomp,sep="")) optimalcrit <- vector("numeric",length=ncomp) names(optimalcrit) <- paste("Dim.",1:ncomp,sep="") contrib <- matrix(0,ntab,ncomp) dimnames(contrib) <- list(names(group), paste("Dim.",1:ncomp,sep="")) Trace <- vector("numeric",length=ntab) criterion <- vector("numeric",length=ntab) saliences <- LAMBDA <- NNLAMBDA <- matrix(1,ntab,ncomp) dimnames(saliences) <-dimnames(LAMBDA) <- dimnames(NNLAMBDA) <- list(names(group), paste("Dim.",1:ncomp,sep="")) T <- matrix(0,nrow=nind,ncol=ncomp) C <- matrix(0,nrow=nind,ncol=ncomp) dimnames(T) <- dimnames(C) <- list(rownames(X), paste("Dim.",1:ncomp,sep="")) T.b <- array(0,dim=c(nind,ncomp,ntab)) dimnames(T.b)<- list(rownames(X), paste("Dim.",1:ncomp,sep=""), names(group)) cor.g.b <- array(0,dim=c(ncomp,ncomp,ntab)) dimnames(cor.g.b) <- list(paste("Dim.",1:ncomp,sep=""), paste("Dim.",1:ncomp,sep=""), names(group)) W.b <- vector("list",length=ntab) blockcor <- vector("list",length=ntab) for (j in 1:ntab) { W.b[[j]] <- blockcor[[j]] <- matrix(0,nrow=group[j],ncol=ncomp) dimnames(W.b[[j]]) <- dimnames(blockcor[[j]]) <- list(colnames(X[,J==j]), paste("Dim.",1:ncomp,sep="")) } Px <- matrix(0,nrow=ncolX,ncol=ncomp) W <- matrix(0,nrow=ncolX,ncol=ncomp) Wm <- matrix(0,nrow=ncolX,ncol=ncomp) dimnames(Px) <- dimnames(W)<- dimnames(Wm) <- list(colnames(X), paste("Dim.",1:ncomp,sep="")) IT.X <- vector("numeric",length=ntab+1) explained.X <- matrix(0,nrow=ntab+1,ncol=ncomp) dimnames(explained.X)<- list(c(names(group),'Global'), paste("Dim.",1:ncomp, sep="")) cumexplained <- matrix(0,nrow=ncomp,ncol=2) rownames(cumexplained) <- paste("Dim.",1:ncomp,sep="") colnames(cumexplained) <- c("%explX", "cum%explX") tb <- matrix(0,nrow=nind,ncol=ntab) components <- vector("numeric",length=2) Xscale <- NULL Block <- NULL res <- NULL Xscale$mean <- apply(X, 2, mean) X <-scale(X,center=Xscale$mean, scale=FALSE) if (scale=="none") { Xscale$scale <-rep(1,times=ncol(X)) } else { if (scale=="sd") { sd.tab <- apply(X, 2, function (x) {return(sqrt(sum(x^2)/length(x)))}) temp <- sd.tab < 1e-14 if (any(temp)) { warning("Variables with null variance not standardized.") sd.tab[temp] <- 1 } X <- sweep(X, 2, sd.tab, "/") Xscale$scale <-sd.tab } else { X <- sweep(X, 2, scale, "/") Xscale$scale <-scale } } if (option=="uniform") { inertia <- sapply(1:ntab, function(j) inertie(X[, J==j])) w.tab <- rep(sqrt(inertia) , times = group ) X <- sweep(X, 2, w.tab, "/") Xscale$scale<- Xscale$scale*w.tab } IT.X[1:ntab] <- sapply(1:ntab, function(j) {inertie(X[,J==j]) }) IT.X[ntab+1] <- sum(IT.X[1:ntab]) X00=X X <- lapply(seq_len(ntab),function(j) {as.matrix(X[,J==j])}) Trace <- sapply(seq_len(ntab), function(j) {sum(diag(tcrossprod(X[[j]])))}) X0=X Itot <- 0 for (comp in 1:ncomp) { if (algo=="eigen"){ critt <- 0 deltacrit <- 1 while(deltacrit>threshold) { P <- matrix(0,nrow=nind,ncol=nind) for(j in 1:ntab) { P <- P + LAMBDA[j,comp]*tcrossprod(X[[j]]) } reseig <- eigen(P) t <- reseig$vectors[,1] T[,comp]<- t optimalcrit[comp] <- reseig$values[1] LAMBDA[,comp] <- matrix(sapply(seq_len(ntab),function(j){t(t)%*%tcrossprod(X[[j]])%*%t}),nrow=ntab,byrow=FALSE) LAMBDA[,comp] <- normv(LAMBDA[,comp]) criterion <- reseig$values[1] deltacrit <- criterion- critt critt <- criterion } } else { critt.opt <- 0 for (i in seq_len(nstart)) { index <- sample(1:ncolX,1) t <- X00[,index] t <- normv(abs(t)) critt <- 0 deltacrit <- 1 iNIPALS <- 0 while(deltacrit>threshold) { tb <- matrix(unlist(lapply(seq_len(ntab),function(j){tcrossprod(X[[j]])%*%t})),nrow=nind,byrow=FALSE) LAMBDA[,comp] <- matrix(sapply(seq_len(ntab),function(j){t(t)%*%tb[,j]}),nrow=ntab,byrow=FALSE) LAMBDA[,comp] <- normv(LAMBDA[,comp]) t <- rowSums(t(t(tb)*LAMBDA[,comp])) t <- normv(t) criterion <- sum(sapply(seq_len(ntab),function(j){LAMBDA[j,comp]*t(t)%*%tb[,j]})) deltacrit <- criterion- critt critt <- criterion iNIPALS <- iNIPALS + 1 } if (critt > critt.opt) { T[,comp] <- t critt.opt <- critt } critnstart[i,comp] <- critt niteration[i,comp] <- iNIPALS } optimalcrit[comp] <- max(critnstart[,comp]) } for(j in 1:ntab) { W.b[[j]][,comp] <- t(X[[j]])%*%T[,comp] T.b[,comp,j] <- X[[j]]%*%W.b[[j]][,comp] } LAMBDA[,comp] <- matrix(sapply(seq_len(ntab),function(j){t(T[,comp] )%*%T.b[,comp,j]}),nrow=ntab,byrow=FALSE) NNLAMBDA[,comp] <- LAMBDA[,comp] LAMBDA[,comp] <- normv(LAMBDA[,comp]) Px[,comp] <- unlist(sapply(1:ntab, function(j){W.b[[j]][,comp]})) W[,comp] <- unlist(sapply(1:ntab,function(j){LAMBDA[j,comp]*W.b[[j]][,comp]})) W[,comp] <- normv(W[,comp]) X.exp <- lapply(X,function(Xj) {tcrossprod(T[,comp]) %*% Xj}) X0.exp <- lapply(X0,function(Xj){tcrossprod(T[,comp]) %*% Xj}) explained.X[1:ntab,comp] <- sapply(X0.exp,function(x) {sum(x^2)}) explained.X[ntab+1,comp] <- sum(explained.X[1:ntab,comp]) X <- lapply(seq_len(ntab),function(j) {X[[j]]-X.exp[[j]]}) } explained.X <- sweep(explained.X[,1:ncomp,drop=FALSE] ,1,IT.X,"/") cumexplained[,1] <- explained.X[ntab+1,1:ncomp] cumexplained[,2] <- cumsum(cumexplained[,1]) contrib <- t(t(NNLAMBDA)/colSums(NNLAMBDA)) Wm <- W %*% solve(t(Px)%*%W,tol=1e-150) if (ncomp==1) { LambdaMoyen<-apply(NNLAMBDA^2,2,sum) C=T*LambdaMoyen } else { LambdaMoyen<-apply(NNLAMBDA^2,2,sum) C=T%*%sqrt(diag(LambdaMoyen)) } globalcor <- cor(X00, C) for(j in 1:ntab) { cor.g.b[,,j] <- cor(T, T.b[,,j]) blockcor[[j]] <- cor(X0[[j]],T.b[,1:ncompprint,j]) if (is.null(rownames(blockcor[[j]]))) rownames(blockcor[[j]]) <- names(group[j]) } res$components <- c(ncomp=ncomp, ncompprint=ncompprint) res$optimalcrit <- optimalcrit[1:ncompprint] res$saliences <- round(LAMBDA[,1:ncompprint,drop=FALSE]^2,2) res$T <- T[,1:ncompprint,drop=FALSE] res$C <- C[,1:ncompprint,drop=FALSE] res$explained.X <- round(100*explained.X[1:ntab,1:ncompprint],2) res$cumexplained <- round(100*cumexplained[1:ncompprint,],2) res$contrib <- round(100*contrib[1:ntab,1:ncompprint],2) res$globalcor <- globalcor[,1:ncompprint] res$cor.g.b <- cor.g.b[1:ncompprint,1:ncompprint,] Block$T.b <- T.b[,1:ncompprint,] Block$blockcor <- blockcor res$Block <- Block res$Xscale <- Xscale res$call <- match.call() class(res) <- c("ComDim","list") if (plotgraph) { plot.ComDim(res,graphtype="saliences", axes=axes) plot.ComDim(res,graphtype="globalscores", axes=axes) plot.ComDim(res,graphtype="globalcor", axes=axes) plot.ComDim(res,graphtype="contrib", axes=axes) } return(res) }
getDefaultSystemOptions<-function() { return(options()) } removeFunctionVariablesFromRAM<-function(){ print.and.log('cleaning workspace...','info') if(exists("reference.data",envir = .QC)) if(is(.QC$reference.data, "SQLiteConnection")) RSQLite::dbDisconnect(.QC$reference.data) rm(.QC) invisible(gc()) if(.QC$verbose) { cat('\n=============================================', fill = TRUE) cat('============= FINISHED QC ===================', fill = TRUE) cat('=============================================', fill = TRUE) } } resetDefaultSystemOptions<-function(user.options) { options(user.options) }
context("Test fastNaiveBayes") test_that("fastNaiveBayes wraps", { real_probs <- matrix(c( 0.9535044256, 0.9999633454, 0.0009301696, 0.1435557348, 0.0009301696, 1 - 0.9535044256, 1 - 0.9999633454, 1 - 0.0009301696, 1 - 0.1435557348, 1 - 0.0009301696 ), nrow = 5, ncol = 2) y <- as.factor(c("Ham", "Ham", "Spam", "Spam", "Spam")) x1 <- matrix(c(2, 3, 2, 4, 3), nrow = 5, ncol = 1) colnames(x1) <- c("wo") x2 <- matrix(c(1, 0, 1, 0, 1), nrow = 5, ncol = 1) colnames(x2) <- c("no") x3 <- matrix(c(2.8, 2.7, 3.0, 2.9, 3.0), nrow = 5, ncol = 1) colnames(x3) <- c("go") x <- cbind(x1, x2, x3) col_names <- c("wo", "no", "go") colnames(x) <- col_names mixed_mod <- fnb.train(x, y, laplace = 0, sparse = FALSE) fastNaiveBayesMod <- fastNaiveBayes(x, y, laplace = 0, sparse = FALSE) expect_equal(mixed_mod, fastNaiveBayesMod) })
context('basic bridge sampling behavior normal Rcpp parallel') test_that("bridge sampler matches anlytical value normal example", { testthat::skip_on_cran() testthat::skip_on_travis() library(mvtnorm) if(require(RcppEigen)) { x <- rmvnorm(1e4, mean = rep(0, 2), sigma = diag(2)) colnames(x) <- c("x1", "x2") lb <- rep(-Inf, 2) ub <- rep(Inf, 2) names(lb) <- names(ub) <- colnames(x) Rcpp::sourceCpp(file = "unnormalized_normal_density.cpp") Rcpp::sourceCpp(file = "unnormalized_normal_density.cpp", env = .GlobalEnv) bridge_normal <- bridge_sampler(samples = x, log_posterior = "log_densityRcpp", data = NULL, lb = lb, ub = ub, method = "normal", packages = "RcppEigen", rcppFile = "unnormalized_normal_density.cpp", cores = 2, silent = TRUE) bridge_warp3 <- bridge_sampler(samples = x, log_posterior = "log_densityRcpp", data = NULL, lb = lb, ub = ub, method = "warp3", packages = "RcppEigen", rcppFile = "unnormalized_normal_density.cpp", cores = 2, silent = TRUE) expect_equal(bridge_normal$logml, expected = log(2*pi), tolerance = 0.01) expect_equal(bridge_warp3$logml, expected = log(2*pi), tolerance = 0.01) mu <- c(1, 2) x <- rmvnorm(1e4, mean = mu, sigma = diag(2)) colnames(x) <- c("x1", "x2") lb <- rep(-Inf, 2) ub <- rep(Inf, 2) names(lb) <- names(ub) <- colnames(x) Rcpp::sourceCpp(file = "unnormalized_normal_density_mu.cpp") Rcpp::sourceCpp(file = "unnormalized_normal_density_mu.cpp", env = .GlobalEnv) bridge_normal_dots <- bridge_sampler(samples = x, log_posterior = "log_densityRcpp_mu", mu, data = NULL, lb = lb, ub = ub, method = "normal", packages = "RcppEigen", rcppFile = "unnormalized_normal_density_mu.cpp", cores = 2, silent = TRUE) bridge_warp3_dots <- bridge_sampler(samples = x, log_posterior = "log_densityRcpp_mu", mu, data = NULL, lb = lb, ub = ub, method = "warp3", packages = "RcppEigen", rcppFile = "unnormalized_normal_density_mu.cpp", cores = 2, silent = TRUE) expect_equal(bridge_normal_dots$logml, expected = log(2*pi), tolerance = 0.01) expect_equal(bridge_warp3_dots$logml, expected = log(2*pi), tolerance = 0.01) } })
LRstats <- function(object, ...) { UseMethod("LRstats") } LRstats.glmlist <- function(object, ..., saturated = NULL, sortby=NULL) { ns <- sapply(object, function(x) length(x$residuals)) if (any(ns != ns[1L])) stop("models were not all fitted to the same size of dataset") nmodels <- length(object) if (nmodels == 1) return(LRstats.default(object[[1L]], saturated=saturated)) rval <- lapply(object, LRstats.default, saturated=saturated) rval <- do.call(rbind, rval) if (!is.null(sortby)) { rval <- rval[order(rval[,sortby], decreasing=TRUE),] } rval } LRstats.loglmlist <- function(object, ..., saturated = NULL, sortby=NULL) { ns <- sapply(object, function(x) length(x$residuals)) if (any(ns != ns[1L])) stop("models were not all fitted to the same size of dataset") nmodels <- length(object) if (nmodels == 1) return(LRstats.default(object[[1L]], saturated=saturated)) rval <- lapply(object, LRstats.default, saturated=saturated) rval <- do.call(rbind, rval) if (!is.null(sortby)) { rval <- rval[order(rval[,sortby], decreasing=TRUE),] } rval } LRstats.default <- function(object, ..., saturated = NULL, sortby=NULL) { logLik0 <- if("stats4" %in% loadedNamespaces()) stats4::logLik else logLik nobs0 <- function(x, ...) { nobs1 <- if("stats4" %in% loadedNamespaces()) stats4::nobs else nobs nobs2 <- function(x, ...) NROW(residuals(x, ...)) rval <- try(nobs1(x, ...), silent = TRUE) if(inherits(rval, "try-error") | is.null(rval)) rval <- nobs2(x, ...) return(rval) } dof <- function(x) { if (inherits(x, "loglm")) { rval <- x$df } else { rval <- try(x$df.residual, silent=TRUE) } if (inherits(rval, "try-error") || is.null(rval)) stop(paste("Can't determine residual df for a", class(x), "object")) rval } objects <- list(object, ...) nmodels <- length(objects) ns <- sapply(objects, nobs0) if(any(ns != ns[1L])) stop("models were not all fitted to the same size of dataset") ll <- lapply(objects, logLik0) par <- as.numeric(sapply(ll, function(x) attr(x, "df"))) df <- as.numeric(sapply(objects, function(x) dof(x))) ll <- sapply(ll, as.numeric) if(is.null(saturated)) { dev <- try(sapply(objects, deviance), silent = TRUE) if(inherits(dev, "try-error") || any(sapply(dev, is.null))) { saturated <- 0 } else { saturated <- ll + dev/2 } } rval <- matrix(rep(NA, 5 * nmodels), ncol = 5) colnames(rval) <- c("AIC", "BIC", "LR Chisq", "Df", "Pr(>Chisq)") rownames(rval) <- as.character(sapply(match.call(), deparse)[-1L])[1:nmodels] rval[,1] <- -2 * ll + 2 * par rval[,2] <- -2 * ll + log(ns) * par rval[,3] <- -2 * (ll - saturated) rval[,4] <- df rval[,5] <- pchisq(rval[,3], df, lower.tail = FALSE) if (!is.null(sortby)) { rval <- rval[order(rval[,sortby], decreasing=TRUE),] } structure(as.data.frame(rval), heading = "Likelihood summary table:", class = c("anova", "data.frame")) }
round_df <- function(x, digits) { numeric_columns <- sapply(x, class) == 'numeric' x[numeric_columns] <- round(x[numeric_columns], digits) x }
siarproportionbygroupplot <- function (siardata, siarversion = 0, probs = c(95, 75, 50), xlabels = NULL, grp = NULL, type = "boxes", clr = gray((9:1)/10), scl = 1, xspc = 0.5, prn = FALSE, leg = FALSE) { if (siardata$SHOULDRUN == FALSE && siardata$GRAPHSONLY == FALSE) { cat("You must load in some data first (via option 1) in order to use \n") cat("this feature of the program. \n") cat("Press <Enter> to continue") readline() invisible() return(NULL) } if (length(siardata$output) == 0) { cat("No output found - check that you have run the SIAR model. \n \n") return(NULL) } cat("Plot of proportions by group \n") cat("Producing plot..... \n \n") groupnames <- as.character(1:siardata$numgroups) if (is.null(grp)) { cat("Enter the group number you wish to plot \n") cat("The choices are:\n") title <- "The available options are:" choose2 <- menu(groupnames) } else { choose2 <- grp } groupseq <- seq(1, siardata$numsources, by = 1) shift <- siardata$numsources + siardata$numiso usepars <- siardata$output[, ((choose2-1)*(shift) + 1) : ((choose2-1)*(shift) + shift - siardata$numiso)] newgraphwindow() if (siardata$TITLE != "SIAR data") { plot(1, 1, xlab = "Source", ylab = "Proportion", main = paste(siardata$TITLE, " by group: ", groupnames[choose2], sep = ""), xlim = c(min(groupseq) - xspc, max(groupseq) + xspc), ylim = c(0, 1), type = "n", xaxt = "n") if (is.null(xlabels)) { axis(side = 1, at = min(groupseq):max(groupseq), labels = (as.character(siardata$sources[,1]))) } else { axis(side = 1, at = min(groupseq):max(groupseq), labels = (xlabels)) } } else { plot(1, 1, xlab = "Source", ylab = "Proportion", main = paste("Proportions by group: ", groupnames[choose2], sep = ""), xlim = c(min(groupseq) - xspc, max(groupseq) + xspc), ylim = c(0, 1), type = "n", xaxt = "n") if (is.null(xlabels)) { axis(side = 1, at = min(groupseq):max(groupseq), labels = (as.character(siardata$sources[,1]))) } else { axis(side = 1, at = min(groupseq):max(groupseq), labels = (xlabels)) } } if (siarversion > 0) mtext(paste("siar v", siarversion), side = 1, line = 4, adj = 1, cex = 0.6) clrs <- rep(clr, 5) for (j in 1:ncol(usepars)) { temp <- hdr(usepars[, j], probs, h = bw.nrd0(usepars[, j]))$hdr line_widths <- seq(2, 20, by = 4) * scl bwd <- c(0.1, 0.15, 0.2, 0.25, 0.3) * scl if (prn == TRUE) { cat(paste("Probability values for Group", j, "\n")) } for (k in 1:length(probs)) { temp2 <- temp[k, ] if (type == "boxes") { polygon(c(groupseq[j] - bwd[k], groupseq[j] - bwd[k], groupseq[j] + bwd[k], groupseq[j] + bwd[k]), c(max(min(temp2[!is.na(temp2)]), 0), min(max(temp2[!is.na(temp2)]), 1), min(max(temp2[!is.na(temp2)]), 1), max(min(temp2[!is.na(temp2)]), 0)), col = clrs[k]) } if (type == "lines") { lines(c(groupseq[j], groupseq[j]), c(max(min(temp2[!is.na(temp2)]), 0), min(max(temp2[!is.na(temp2)]), 1)), lwd = line_widths[k], lend = 2) } if (prn == TRUE) { cat(paste("\t", probs[k], "% lower =", format(max(min(temp2[!is.na(temp2)]), 0), digits = 2, scientific = FALSE), "upper =", format(min(max(temp2[!is.na(temp2)]), 1), digits = 2, scientific = FALSE), "\n")) } } } if (leg == TRUE) { if (type == "lines") { legnames <- character(length = length(probs)) for (i in 1:length(probs)) { legnames[i] <- paste(probs[i], "%", sep = "") } legend(mean(c(min(groupseq), max(groupseq))), 1.02, legend = legnames, lwd = c(2, 6, 10), ncol = length(probs), xjust = 0.5, text.width = strwidth(legnames)/2, bty = "n") } if (type == "boxes") { print("Legends not yet supported for box style graph. Use type=lines with leg=TRUE instead.") } } cat("Please maximise this graph before saving or printing. \n") cat("Press <Enter> to continue") readline() invisible() }
test_that("plotYieldObservedVsModel works", { local_edition(3) params <- NS_params expect_message( expect_error(plotYieldObservedVsModel(params), "You have not provided values")) species_params(params)$yield_observed <- c(0.8, 61, 12, 35, 1.6, 20, 10, 7.6, 135, 60, 30, 78) params <- calibrateYield(params) expect_message(dummy <- plotYieldObservedVsModel(params, return_data = T)) expect_equal(dummy$observed, species_params(params)$yield_observed[4:12]) expect_error(plotYieldObservedVsModel(params, species = rep(F, 12)), "No species selected, please fix.") params2 = params species_params(params2)$yield_observed[c(1, 7, 10)] = NA expect_message(dummy <- plotYieldObservedVsModel(params2, return_data = T)) expect_equal(as.character(dummy$species), species_params(params)$species[c(4,5,6,8,9,11,12)]) expect_equal(dummy$observed, species_params(params2)$yield_observed[c(4,5,6,8,9,11,12)]) expect_message(dummy <- plotYieldObservedVsModel(params2, return_data = T, show_unobserved = TRUE)) expect_equal(as.character(dummy$species), species_params(params)$species[4:12]) sp_select = c(4, 7, 10, 11, 12) dummy <- plotYieldObservedVsModel(params, species = sp_select, return_data = T) expect_equal(nrow(dummy), length(sp_select)) expect_equal(dummy$observed, species_params(params)$yield_observed[sp_select]) expect_message(p <- plotYieldObservedVsModel(params)) expect_true(is.ggplot(p)) expect_identical(p$labels$x, "observed yield [g/year]") expect_identical(p$labels$y, "model yield [g/year]") vdiffr::expect_doppelganger("plotYieldObservedVsModel", p) })
covariance_commonControl <- function (aDataFrame, control_ID, X_t, SD_t, N_t, X_c, SD_c, N_c, metric = "RR") { controlList <- split(aDataFrame, as.factor(aDataFrame[, control_ID])) listV <- list(); dataAlignedWithV <- data.frame(); for(i in 1:length(controlList)) { dataAlignedWithV <- rbind(dataAlignedWithV, controlList[[i]]) if(metric == "RR") { covar <- (controlList[[i]][, SD_c] ^ 2) / (controlList[[i]][, N_c] * (controlList[[i]][, X_c] ^ 2)) var <- covar + (controlList[[i]][, SD_t] ^ 2) / (controlList[[i]][, N_t] * (controlList[[i]][, X_t] ^ 2)) } V <- matrix(covar, nrow = length(var), ncol = length(var)) diag(V) <- var listV <- unlist(list(listV, list(V)), recursive = FALSE) } V <- as.matrix(bdiag(listV)) return(list(V, dataAlignedWithV)) }
mice_imputation_input_data_frame <- function(x, y, vname, trafo=NULL) { res <- mice_imputation_smcfcs_clean_input(x=x, y=y, state_data=NULL, sm=NULL, vname=vname, trafo=trafo) return(res) }
logt.error <- function(parameters, values, probabilities, weights, degreesfreedom){ sum(weights * (pt((log(values) - parameters[1]) / exp(parameters[2]), degreesfreedom) - probabilities)^2) }
"_PACKAGE" dt_vars <- c( "Elapsed", "ElapsedAccum", "Km", "Vmax", "actual", "avg_decay_rate", "bestModRF", "channel", "channels", "country", "cpa_total", "decay_accumulated", "decomp.rssd", "decompAbsScaled", "decomp_perc", "decomp_perc_prev", "depVarHat", "dep_var", "ds", "dsMonthStart", "dsWeekStart", "duration", "effect_share", "effect_share_refresh", "error_dis", "exposure", "halflife", "holiday", "i.effect_share_refresh", "i.robynPareto", "i.solID", "i.spend_share_refresh", "id", "initResponseUnit", "initResponseUnitTotal", "initSpendUnit", "iterNG", "iterPar", "iterations", "label", "liftAbs", "liftEndDate", "liftMedia", "liftStart", "liftStartDate", "mape", "mape.qt10", "mape_lift", "mean_response", "mean_spend", "mean_spend_scaled", "models", "next_unit_response", "nrmse", "optmResponseUnit", "optmResponseUnitTotal", "optmResponseUnitTotalLift", "optmSpendUnit", "optmSpendUnitTotalDelta", "param", "perc", "percentage", "pos", "predicted", "refreshStatus", "response", "rn", "robynPareto", "roi", "roi_mean", "roi_total", "rsq_lm", "rsq_nls", "rsq_train", "s0", "scale_shape_halflife", "season", "shape", "solID", "spend", "spend_share", "spend_share_refresh", "sid", "theta", "theta_halflife", "total_spend", "trend", "trial", "type", "value", "variable", "weekday", "x", "xDecompAgg", "xDecompMeanNon0", "xDecompMeanNon0Perc", "xDecompMeanNon0PercRF", "xDecompMeanNon0RF", "xDecompPerc", "xDecompPercRF", "y", "yhat", "respN","iteration","variables","iter_bin", "thetas", "cut_time", "exposure_vars", "OutputModels", "exposure_pred" ) if (getRversion() >= "2.15.1") { globalVariables(c(".", dt_vars)) }
hlp_to_py_mat <- function(x) { z <- paste0("[", apply(x, 1, paste0, collapse = ", "), "]") z <- paste0("Matrix([", paste0(z, collapse = ", "), "])") return(z) } hlp_to_py_vec <- function(x) { z <- paste0("Matrix([", paste0(x, collapse = ", "), "])") return(z) } hlp_to_py_scalar <- function(x) { z <- as.character(x) return(z) } as_py_string <- function(x) { if (is.matrix(x)) { return(hlp_to_py_mat(x)) } if (is.vector(x) && length(x) == 1L) { return(hlp_to_py_scalar(x)) } return(hlp_to_py_vec(x)) } as_sym <- function(x, declare_symbols = TRUE) { ensure_sympy() if (is.expression(x)) { x <- as.character(x) } varnames_exclude <- c("S", "sqrt", "log", "I", "exp", "sin", "cos", "Matrix", "Function") if (declare_symbols) { xele <- as.vector(x) m <- gregexpr(pattern = PATTERN_PYHTON_VARIABLE, text = xele) varnames <- regmatches(x = xele, m = m, invert = FALSE) varnames <- unique(unlist(varnames[unlist(lapply(varnames, length)) > 0])) varnames <- setdiff(varnames, varnames_exclude) for (varname in varnames) { cmd <- paste0(varname, " = symbols('", varname, "')") reticulate::py_run_string(cmd, convert = FALSE) } } if (is.character(x) && length(x) == 1L && grepl("^\\[\\[", x)) { x <- paste0("Matrix(", r_strings_to_python(x), ")") y <- eval_to_symbol(x) return(y) } cmd <- as_py_string(x) y <- eval_to_symbol(cmd) return(y) }
"seattlepets"
lambda_j_Exp <- function(tau, time, event){ k <- length(tau) aj <- rep(NA, k + 1) tau <- c(0, tau, Inf) hess.diag <- aj for (j in 2:(k + 2)){ Xtj <- sum(event[time <= tau[j]]) Xtj1 <- sum(event[time <= tau[j - 1]]) diff <- Xtj - Xtj1 nenner <- sum((pmin(time, tau[j]) - tau[j - 1]) * (time > tau[j - 1])) aj[j - 1] <- diff / nenner hess.diag[j - 1] <- - diff / aj[j - 1] ^ 2 } res <- list("aj" = aj, "hess.diag" = hess.diag) return(res) }
require('SoilR') Result<-setClass( "Result", slots=c( noException="list", notRunning="list", tested="list" ), prototype=list( noException=list(), notRunning=list(), tested=list() ) ) test.check.pass=function(){ X <- lsf.str('package:SoilR') has_pass <-function(x){"pass" %in% names(formals(x))} ind=as.vector(sapply(X,has_pass)) Xpass=X[ind] passCaller <- function(c,l){ cl=as.list(c) name=cl[[1]] print(cl) if(class(try(eval(c),silent=T))!="try-error"){ l@noException<- append(l@noException,name) } c2 <- as.call(append(cl,expression(pass=TRUE))) if(class(try(eval(c2),silent=T))=="try-error"){ l@notRunning=append(l@notRunning,name) } l@tested=append(l@tested,name) return(l) } l=Result() load("../../data/C14Atm_NH.rda") load("../../data/HarvardForest14CO2.rda") years=seq(1801,2010,by=0.5) l=passCaller(call("GaudinskiModel14",t=years,ks=c(kr=1/3,koi=1/1.5,koeal=1/4,koeah=1/80,kA1=1/3,kA2=1/75,kM=1/110),inputFc=C14Atm_NH),l) t_start=0 t_end=10 tn=50 timestep=(t_end-t_start)/tn t=seq(t_start,t_end,timestep) t_fault=seq(t_start-10,t_end,timestep) n=3 At=new("BoundLinDecompOp", t_start, t_end, function(t0){ matrix(nrow=n,ncol=n,byrow=TRUE, c(-0.2, 0, 0, 0 , -0.3, 0, 0, 0, -0.4) ) } ) c0=c(0.5, 0.5, 0.5) inputFluxes=TimeMap.new( t_start, t_end, function(t0){matrix(nrow=n,ncol=1,c(0.0,0,0))} ) l=passCaller(call("GeneralModel",t_fault,At,c0,inputFluxes),l) t_start=1960 t_end=2010 tn=220 timestep=(t_end-t_start)/tn t=seq(t_start,t_end,timestep) t_fault=seq(t_start-10,t_end,timestep) n=3 At=new(Class="BoundLinDecompOp", t_start, t_end, function(t0){ matrix(nrow=n,ncol=n,byrow=TRUE, c(-1, 0.1, 0, 0.5 , -0.4, 0, 0, 0.2, -0.1) ) } ) c0=c(100, 100, 100) F0=ConstFc(c(0,10,10),"Delta14C") inputFluxes=new( "TimeMap", t_start, t_end, function(t0){matrix(nrow=n,ncol=1,c(10,10,10))} ) load("../../data/C14Atm_NH.rda") Fc=BoundFc(C14Atm_NH,format="Delta14C") th=5730 k=log(0.5)/th l=passCaller(call("Model_14",t=t_fault,A=At,ivList=c0,initialValF=F0,inputFluxes=inputFluxes,inputFc=Fc,c14DecayRate=k),l) t_start=1960 t_end=2010 tn=220 timestep=(t_end-t_start)/tn t=seq(t_start,t_end,timestep) t_fault=seq(t_start-10,t_end,timestep) n=3 At=new(Class="BoundLinDecompOp", t_start, t_end, function(t0){ matrix(nrow=n,ncol=n,byrow=TRUE, c(-1, 0.1, 0, 0.5 , -0.4, 0, 0, 0.2, -0.1) ) } ) c0=c(100, 100, 100) F0=ConstFc(c(0,10,10),"Delta14C") inputFluxes=new( "TimeMap", t_start, t_end, function(t0){matrix(nrow=n,ncol=1,c(10,10,10))} ) load("../../data/C14Atm_NH.rda") Fc=BoundFc(C14Atm_NH,format="Delta14C") th=5730 k=log(0.5)/th l=passCaller(call("GeneralModel_14",t=t_fault,A=At,ivList=c0,initialValF=F0,inputFluxes=inputFluxes,inputFc=Fc,di=k),l) t_start=0 t_end=10 tn=3e1 timestep=(t_end-t_start)/tn t=seq(t_start,t_end,timestep) t_fault=seq(t_start-10,t_end,timestep) nr=2 alpha=list() alpha[["1_to_2"]]=function(C,t){ 1 } k1=3/5 k2=3/5 f=function(C,t){ N=matrix( nrow=nr, ncol=nr, c( k1, 0, 0 , k2 ) ) return(N%*%C) } fac=2e2 inputrates=new("TimeMap",t_start,t_end,function(t){return(matrix( nrow=nr, rep( c( 2*fac, 0*fac ), length(t) ) ))}) c0= c( fac, 0 ) A=new("TransportDecompositionOperator",t_start,t_end,nr,alpha,f) l=passCaller(call("GeneralNlModel",t_fault,A,c0,inputrates),l) times=seq(0,20,by=0.1) ks=c(k1=-0.8,k2=0.00605) l=passCaller(call("ICBMModel",t=times, ks=ks,h=0.125, r=1, c0=c(0.3,4.11), In=0.19+0.095),l) t_start=0 t_end=10 tn=50 timestep=(t_end-t_start)/tn t=seq(t_start,t_end,timestep) t_fault=seq(t_start-10,t_end,timestep) In=data.frame(t,rep(100,length(t))) t=seq(t_start,t_end,timestep) k=0.8 C0=100 l=passCaller(call("OnepModel",t_fault,k,C0,In),l) load("../../data/C14Atm_NH.rda") years=seq(1901,2009,by=0.5) years_fault=seq(1901,2019,by=0.5) LitterInput=700 l=passCaller(call("OnepModel14",t=years_fault,k=1/10,C0=500, F0=0,In=LitterInput, inputFc=C14Atm_NH),l) t_start=0 t_end=10 tn=50 timestep=(t_end-t_start)/tn t=seq(t_start,t_end,timestep) k=TimeMap.new(t_start,t_end,function(times){c(-0.5,-0.2,-0.3)}) c0=c(1, 2, 3) inputrates=TimeMap.new( t_start+10, t_end, function(t){matrix(nrow=3,ncol=1,c(1,1,1))} ) l=passCaller(call("ParallelModel",t,k,c0,inputrates),l) t=0:500 In=data.frame(t,rep(1.7,length(t))) FYM=data.frame(t,rep(1.7,length(t))) t_faulty=0:600 l=passCaller(call("RothCModel",t_faulty,In=In,FYM=FYM),l) t_start=0 t_end=10 tn=50 timestep=(t_end-t_start)/tn t=seq(t_start,t_end,timestep) t_fault=seq(t_start-10,t_end,timestep) ks=c(k1=0.8,k2=0.4,k3=0.2) C0=c(C10=100,C20=150, C30=50) In = 60 Temp=rep(15,length(t)) TempEffect=data.frame(t,fT.Daycent1(Temp)) l=passCaller(call("ThreepFeedbackModel",t=t_fault,ks=ks,a21=0.5,a12=0.1,a32=0.2,a23=0.1,C0=C0,In=In,xi=TempEffect),l) l=passCaller(call("SeriesLinearModel",t=t_fault,ki=ks,m.pools=3,Tij=c(0.5,0.2),C0=C0,In=In,xi=TempEffect),l) load("../../data/C14Atm_NH.rda") years=seq(1901,2009,by=0.5) years_fault=seq(1901,2019,by=0.5) LitterInput=700 l=passCaller( call("ThreepFeedbackModel14",t=years_fault,ks=c(k1=1/2.8, k2=1/35, k3=1/100),C0=c(200,5000,500), F0_Delta14C=c(0,0,0),In=LitterInput, a21=0.1,a12=0.01,a32=0.005,a23=0.001,inputFc=C14Atm_NH), l ) l=passCaller( call("SeriesLinearModel14",t=years_fault,ki=c(k1=1/2.8, k2=1/35, k3=1/100),C0=c(200,5000,500),m.pools=3, F0_Delta14C=c(0,0,0),In=LitterInput, Tij=c(0.5,0.1),inputFc=C14Atm_NH), l) t_start=0 t_end=10 tn=50 timestep=(t_end-t_start)/tn t=seq(t_start,t_end,timestep) t_fault=seq(t_start-10,t_end,timestep) In=data.frame(t,rep(1.7,length(t))) l=passCaller(call("ThreepParallelModel",t=t_fault,ks=c(k1=0.5,k2=0.2,k3=0.1),C0=c(c10=100, c20=150,c30=50),In=In,gam1=0.7,gam2=0.1,xi=0.5),l) load("../../data/C14Atm_NH.rda") years=seq(1901,2009,by=0.5) years_fault=seq(1901,2019,by=0.5) LitterInput=700 l=passCaller(call("ThreepParallelModel14",t=years_fault,ks=c(k1=1/2.8, k2=1/35, k3=1/100),C0=c(200,5000,500), F0_Delta14C=c(0,0,0),In=LitterInput, gam1=0.7, gam2=0.1, inputFc=C14Atm_NH,lag=2),l) load("../../data/C14Atm_NH.rda") years=seq(1901,2009,by=0.5) years_fault=seq(1901,2019,by=0.5) LitterInput=700 l=passCaller( call("ThreepFeedbackModel14",t=years_fault,ks=c(k1=1/2.8, k2=1/35, k3=1/100),C0=c(200,5000,500), F0_Delta14C=c(0,0,0),In=LitterInput, a21=0.1,a12=0.01,a32=0.005,a23=0.001,inputFc=C14Atm_NH), l) t_start=0 t_end=10 tn=50 timestep=(t_end-t_start)/tn t=seq(t_start,t_end,timestep) t_fault=seq(t_start-10,t_end,timestep) ks=c(k1=0.8,k2=0.4,k3=0.2) C0=c(C10=100,C20=150, C30=50) In=data.frame(t,rep(50,length(t))) l=passCaller(call("ThreepSeriesModel",t=t_fault,ks=ks,a21=0.5,a32=0.2,C0=C0,In=In,xi=fT.Q10(15)),l) load("../../data/C14Atm_NH.rda") years=seq(1901,2009,by=0.5) years_fault=seq(1901,2019,by=0.5) LitterInput=700 l=passCaller( call("ThreepSeriesModel14",t=years_fault,ks=c(k1=1/2.8, k2=1/35, k3=1/100),C0=c(200,5000,500), F0_Delta14C=c(0,0,0),In=LitterInput, a21=0.1, a32=0.01,inputFc=C14Atm_NH), l) times=seq(0,20,by=0.1) times_fault=seq(0,30,by=0.1) ks=c(k1=0.8,k2=0.00605) C0=c(C10=5,C20=5) Temp=rnorm(times,15,2) WC=runif(times,10,20) TempEffect=data.frame(times,fT=fT.Daycent1(Temp)) MoistEffect=data.frame(times, fW=fW.Daycent2(WC)[2]) Inmean=1 InSin=data.frame(times,Inmean+0.5*sin(times*pi*2)) l=passCaller(call("TwopParallelModel",t=times_fault,ks=ks,C0=C0,In=InSin,gam=0.9, xi=(fT.Daycent1(15)*fW.Demeter(15))),l) l=passCaller(call("TwopSeriesModel",t=times_fault,ks=ks,a21=0.2*ks[1],C0=C0,In=InSin, xi=(fT.Daycent1(15)*fW.Demeter(15))),l) l=passCaller(call("TwopFeedbackModel",t=times_fault,ks=ks,a21=0.2*ks[1],a12=0.5*ks[2],C0=C0, In=InSin,xi=MoistEffect),l) load("../../data/C14Atm_NH.rda") years=seq(1901,2009,by=0.5) years_fault=seq(1901,2019,by=0.5) LitterInput=data.frame(years,rep(700,length(years))) l=passCaller(call("TwopFeedbackModel14",t=years_fault,ks=c(k1=1/2.8, k2=1/35),C0=c(200,5000), F0_Delta14C=c(0,0),In=LitterInput, a21=0.1,a12=0.01,inputFc=C14Atm_NH),l) load("../../data/C14Atm_NH.rda") years=seq(1901,2009,by=0.5) years_fault=seq(1901,2019,by=0.5) LitterInput=data.frame(years,rep(700,length(years))) l=passCaller(call("TwopParallelModel14",t=years_fault,ks=c(k1=1/2.8, k2=1/35),C0=c(200,5000), F0_Delta14C=c(0,0),In=LitterInput, gam=0.7,inputFc=C14Atm_NH,lag=2),l) load("../../data/C14Atm_NH.rda") years=seq(1901,2009,by=0.5) years_fault=seq(1901,2019,by=0.5) LitterInput=data.frame(years,rep(700,length(years))) l=passCaller(call("TwopSeriesModel14",t=years_fault,ks=c(k1=1/2.8, k2=1/35),C0=c(200,5000), F0_Delta14C=c(0,0),In=LitterInput, a21=0.1,inputFc=C14Atm_NH),l) years=seq(0,50,0.1) years_fault=seq(0,60,0.1) C0=rep(100,7) xi=data.frame(years,rep(1,length(years))) l=passCaller(call("YassoModel",t=years_fault,C0=C0,xi=xi),l) years=seq(0,50,0.1) years_fault=seq(0,60,0.1) C0=rep(100,5) LitterInput=data.frame(years,rep(0,length(years))) l=passCaller(call("Yasso07Model",t=years_fault,C0=C0,In=LitterInput),l) years=seq(0,50,0.1) years_fault=seq(0,60,0.1) n=5 C0=rep(100,n) LitterInput<-BoundInFluxes(data.frame(years,rep(0,length(years)))) op<-ConstLinDecompOp(diag(rep(-1,n))) l<-passCaller(call("Model",A=op,t=years_fault,ivList=C0,inputFluxes=LitterInput),l) st=FALSE if (length(setdiff(Xpass,l@tested))!=0){ cat( paste("not all functions using the pass argument have been tested. \nThe untested functions are:\n", paste(setdiff(Xpass,l@tested),collapse=", "), "\n\n" ) ) st<-TRUE } if (length(l@noException)>0){ cat( paste( "Not all functions produce the required exception for wrong input if called without the pass argument.\nThe funtions are:\n", paste(l@noException,collapse=", "), "\n\n" ) ) st<-TRUE } if (length(l@notRunning)>0){ cat( paste("Not all functions can be made run with corrupted input by calling them with the pass argument.\nThe funtions are:\n", paste(unlist(l@notRunning),collapse=", "), "\n\n" ) ) st<-TRUE } if (st){stop()} }
context('simple_slopes function') library(nlme) library(lme4) get_coef <- function(model, row, digits=3) { return(round(coef(model)[row, 1], digits)) } get_coef.lme <- function(model, row, digits=3) { return(round(model$tTable[row, 1], digits)) } test_that('lm with 2 continuous int. works', { set.seed(123) x1 <- rnorm(100) set.seed(234) x2 <- rnorm(100) set.seed(345) y <- x1 * x2 + rnorm(100) data <- data.frame(x1, x2, y) model <- lm(y ~ x1 * x2, data) slopes <- simple_slopes(model) model_x1_m1 <- summary(lm(y ~ I((x1 - mean(x1)) + sd(x1)) * x2, data)) expect_equal(round(slopes[1, 'Test Estimate'], 3), get_coef(model_x1_m1, 'x2')) model_x1_0 <- summary(lm(y ~ I(x1 - mean(x1)) * x2, data)) expect_equal(round(slopes[2, 'Test Estimate'], 3), get_coef(model_x1_0, 'x2')) model_x1_p1 <- summary(lm(y ~ I((x1 - mean(x1)) - sd(x1)) * x2, data)) expect_equal(round(slopes[3, 'Test Estimate'], 3), get_coef(model_x1_p1, 'x2')) model_x2_m1 <- summary(lm(y ~ x1 * I((x2 - mean(x2)) + sd(x2)), data)) expect_equal(round(slopes[4, 'Test Estimate'], 3), get_coef(model_x2_m1, 'x1')) model_x2_0 <- summary(lm(y ~ x1 * I(x2 - mean(x2)), data)) expect_equal(round(slopes[5, 'Test Estimate'], 3), get_coef(model_x2_0, 'x1')) model_x2_p1 <- summary(lm(y ~ x1 * I((x2 - mean(x2)) - sd(x2)), data)) expect_equal(round(slopes[6, 'Test Estimate'], 3), get_coef(model_x2_p1, 'x1')) }) test_that('lm with continuous x 2-level categorical int. works', { set.seed(123) x1 <- rnorm(100) x2 <- c(rep(0, 50), rep(1, 50)) set.seed(345) y <- x1 * x2 + rnorm(100) x2 <- factor(x2) data <- data.frame(x1, x2, y) model <- lm(y ~ x1 * x2, data) slopes <- simple_slopes(model) model_x1_m1 <- summary(lm(y ~ I((x1 - mean(x1)) + sd(x1)) * x2, data)) expect_equal(round(slopes[1, 'Test Estimate'], 3), get_coef(model_x1_m1, 'x21')) model_x1_0 <- summary(lm(y ~ I(x1 - mean(x1)) * x2, data)) expect_equal(round(slopes[2, 'Test Estimate'], 3), get_coef(model_x1_0, 'x21')) model_x1_p1 <- summary(lm(y ~ I((x1 - mean(x1)) - sd(x1)) * x2, data)) expect_equal(round(slopes[3, 'Test Estimate'], 3), get_coef(model_x1_p1, 'x21')) model_x2_0 <- summary(lm(y ~ x1 * x2, data)) expect_equal(round(slopes[4, 'Test Estimate'], 3), get_coef(model_x2_0, 'x1')) contrasts(data$x2) <- c(1, 0) model_x2_1 <- summary(lm(y ~ x1 * x2, data)) expect_equal(round(slopes[5, 'Test Estimate'], 3), get_coef(model_x2_1, 'x1')) }) test_that('lm with continuous x 3-level categorical int. works', { set.seed(123) x1 <- rnorm(150) x2 <- c(rep(0, 50), rep(1, 50), rep(2, 50)) set.seed(345) y <- x1 * x2 + rnorm(150) x2 <- factor(x2) data <- data.frame(x1, x2, y) model <- lm(y ~ x1 * x2, data) slopes <- simple_slopes(model) model_x1_m1 <- summary(lm(y ~ I((x1 - mean(x1)) + sd(x1)) * x2, data)) expect_equal(round(slopes[1, 'Test Estimate'], 3), get_coef(model_x1_m1, 'x21')) expect_equal(round(slopes[2, 'Test Estimate'], 3), get_coef(model_x1_m1, 'x22')) model_x1_0 <- summary(lm(y ~ I(x1 - mean(x1)) * x2, data)) expect_equal(round(slopes[3, 'Test Estimate'], 3), get_coef(model_x1_0, 'x21')) expect_equal(round(slopes[4, 'Test Estimate'], 3), get_coef(model_x1_0, 'x22')) model_x1_p1 <- summary(lm(y ~ I((x1 - mean(x1)) - sd(x1)) * x2, data)) expect_equal(round(slopes[5, 'Test Estimate'], 3), get_coef(model_x1_p1, 'x21')) expect_equal(round(slopes[6, 'Test Estimate'], 3), get_coef(model_x1_p1, 'x22')) model_x2_0 <- summary(lm(y ~ x1 * x2, data)) expect_equal(round(slopes[7, 'Test Estimate'], 3), get_coef(model_x2_0, 'x1')) contrasts(data$x2) <- matrix(c(1, 0, 0, 0, 0, 1), nrow=3) model_x2_1 <- summary(lm(y ~ x1 * x2, data)) expect_equal(round(slopes[8, 'Test Estimate'], 3), get_coef(model_x2_1, 'x1')) contrasts(data$x2) <- matrix(c(1, 0, 0, 0, 1, 0), nrow=3) model_x2_1 <- summary(lm(y ~ x1 * x2, data)) expect_equal(round(slopes[9, 'Test Estimate'], 3), get_coef(model_x2_1, 'x1')) }) test_that('lm with 3 continuous int. works', { get_model <- function(data, points, test) { if (is.na(points[1])) { model <- lm(y ~ x1 * I(x2 - points[2]) * I(x3 - points[3]), data) } else if (is.na(points[2])) { model <- lm(y ~ I(x1 - points[1]) * x2 * I(x3 - points[3]), data) } else { model <- lm(y ~ I(x1 - points[1]) * I(x2 - points[2]) * x3, data) } return(get_coef(summary(model), test)) } set.seed(123) x1 <- rnorm(100) set.seed(234) x2 <- rnorm(100) set.seed(345) x3 <- rnorm(100) set.seed(456) y <- x1 * x2 * x3 + rnorm(100) data <- data.frame(x1, x2, x3, y) model <- lm(y ~ x1 * x2 * x3, data) slopes <- simple_slopes(model) pts <- list( x1=c(mean(x1) - sd(x1), mean(x1), mean(x1) + sd(x1)), x2=c(mean(x2) - sd(x2), mean(x2), mean(x2) + sd(x2)), x3=c(mean(x3) - sd(x3), mean(x3), mean(x3) + sd(x3)) ) expect_equal(round(slopes[1, 'Test Estimate'], 3), get_model(data, c(pts[['x1']][1], pts[['x2']][1], NA), 'x3')) expect_equal(round(slopes[2, 'Test Estimate'], 3), get_model(data, c(pts[['x1']][2], pts[['x2']][1], NA), 'x3')) expect_equal(round(slopes[3, 'Test Estimate'], 3), get_model(data, c(pts[['x1']][3], pts[['x2']][1], NA), 'x3')) expect_equal(round(slopes[4, 'Test Estimate'], 3), get_model(data, c(pts[['x1']][1], pts[['x2']][2], NA), 'x3')) expect_equal(round(slopes[5, 'Test Estimate'], 3), get_model(data, c(pts[['x1']][2], pts[['x2']][2], NA), 'x3')) expect_equal(round(slopes[6, 'Test Estimate'], 3), get_model(data, c(pts[['x1']][3], pts[['x2']][2], NA), 'x3')) expect_equal(round(slopes[7, 'Test Estimate'], 3), get_model(data, c(pts[['x1']][1], pts[['x2']][3], NA), 'x3')) expect_equal(round(slopes[8, 'Test Estimate'], 3), get_model(data, c(pts[['x1']][2], pts[['x2']][3], NA), 'x3')) expect_equal(round(slopes[9, 'Test Estimate'], 3), get_model(data, c(pts[['x1']][3], pts[['x2']][3], NA), 'x3')) expect_equal(round(slopes[10, 'Test Estimate'], 3), get_model(data, c(pts[['x1']][1], NA, pts[['x3']][1]), 'x2')) expect_equal(round(slopes[11, 'Test Estimate'], 3), get_model(data, c(pts[['x1']][2], NA, pts[['x3']][1]), 'x2')) expect_equal(round(slopes[12, 'Test Estimate'], 3), get_model(data, c(pts[['x1']][3], NA, pts[['x3']][1]), 'x2')) expect_equal(round(slopes[13, 'Test Estimate'], 3), get_model(data, c(NA, pts[['x2']][1], pts[['x3']][1]), 'x1')) expect_equal(round(slopes[14, 'Test Estimate'], 3), get_model(data, c(NA, pts[['x2']][2], pts[['x3']][1]), 'x1')) expect_equal(round(slopes[15, 'Test Estimate'], 3), get_model(data, c(NA, pts[['x2']][3], pts[['x3']][1]), 'x1')) expect_equal(round(slopes[16, 'Test Estimate'], 3), get_model(data, c(pts[['x1']][1], NA, pts[['x3']][2]), 'x2')) expect_equal(round(slopes[17, 'Test Estimate'], 3), get_model(data, c(pts[['x1']][2], NA, pts[['x3']][2]), 'x2')) expect_equal(round(slopes[18, 'Test Estimate'], 3), get_model(data, c(pts[['x1']][3], NA, pts[['x3']][2]), 'x2')) expect_equal(round(slopes[19, 'Test Estimate'], 3), get_model(data, c(NA, pts[['x2']][1], pts[['x3']][2]), 'x1')) expect_equal(round(slopes[20, 'Test Estimate'], 3), get_model(data, c(NA, pts[['x2']][2], pts[['x3']][2]), 'x1')) expect_equal(round(slopes[21, 'Test Estimate'], 3), get_model(data, c(NA, pts[['x2']][3], pts[['x3']][2]), 'x1')) expect_equal(round(slopes[22, 'Test Estimate'], 3), get_model(data, c(pts[['x1']][1], NA, pts[['x3']][3]), 'x2')) expect_equal(round(slopes[23, 'Test Estimate'], 3), get_model(data, c(pts[['x1']][2], NA, pts[['x3']][3]), 'x2')) expect_equal(round(slopes[24, 'Test Estimate'], 3), get_model(data, c(pts[['x1']][3], NA, pts[['x3']][3]), 'x2')) expect_equal(round(slopes[25, 'Test Estimate'], 3), get_model(data, c(NA, pts[['x2']][1], pts[['x3']][3]), 'x1')) expect_equal(round(slopes[26, 'Test Estimate'], 3), get_model(data, c(NA, pts[['x2']][2], pts[['x3']][3]), 'x1')) expect_equal(round(slopes[27, 'Test Estimate'], 3), get_model(data, c(NA, pts[['x2']][3], pts[['x3']][3]), 'x1')) }) test_that('binomial glm with interaction works', { set.seed(123) x1 <- rnorm(100) set.seed(234) x2 <- rnorm(100) set.seed(345) rand <- rnorm(100) y <- as.numeric((x1 > mean(x1) | x2 > mean(x2)) & rand > mean(rand)) data <- data.frame(x1, x2, y) model <- glm(y ~ x1 * x2, family='binomial', data) slopes <- simple_slopes(model) model_x1_m1 <- summary(glm(y ~ I((x1 - mean(x1)) + sd(x1)) * x2, family='binomial', data)) expect_equal(round(slopes[1, 'Test Estimate'], 3), get_coef(model_x1_m1, 'x2')) model_x1_0 <- summary(glm(y ~ I(x1 - mean(x1)) * x2, family='binomial', data)) expect_equal(round(slopes[2, 'Test Estimate'], 3), get_coef(model_x1_0, 'x2')) model_x1_p1 <- summary(glm(y ~ I((x1 - mean(x1)) - sd(x1)) * x2, family='binomial', data)) expect_equal(round(slopes[3, 'Test Estimate'], 3), get_coef(model_x1_p1, 'x2')) model_x2_m1 <- summary(glm(y ~ x1 * I((x2 - mean(x2)) + sd(x2)), family='binomial', data)) expect_equal(round(slopes[4, 'Test Estimate'], 3), get_coef(model_x2_m1, 'x1')) model_x2_0 <- summary(glm(y ~ x1 * I(x2 - mean(x2)), family='binomial', data)) expect_equal(round(slopes[5, 'Test Estimate'], 3), get_coef(model_x2_0, 'x1')) model_x2_p1 <- summary(glm(y ~ x1 * I((x2 - mean(x2)) - sd(x2)), family='binomial', data)) expect_equal(round(slopes[6, 'Test Estimate'], 3), get_coef(model_x2_p1, 'x1')) }) test_that('lme with interaction works', { set.seed(123) pre_treat <- rnorm(50) set.seed(234) post_treat <- 2 + rnorm(50) set.seed(345) pre_control <- rnorm(50) set.seed(456) post_control <- rnorm(50) dv <- c(pre_treat, post_treat, pre_control, post_control) pre_post <- factor(rep(c(rep(0, 50), rep(1, 50)), 2)) condition <- factor(c(rep(0, 100), rep(1, 100))) id <- c(rep(1:50, 2), rep(51:100, 2)) data <- data.frame(id, condition, pre_post, dv) model <- lme(dv ~ condition * pre_post, random=~1|id, data) slopes <- simple_slopes(model) contrasts(data$condition) <- c(0, 1) model_c_0 <- summary(lme(dv ~ condition * pre_post, random=~1|id, data)) expect_equal(round(slopes[1, 'Test Estimate'], 3), get_coef.lme(model_c_0, 'pre_post1')) contrasts(data$condition) <- c(1, 0) model_c_1 <- summary(lme(dv ~ condition * pre_post, random=~1|id, data)) expect_equal(round(slopes[2, 'Test Estimate'], 3), get_coef.lme(model_c_1, 'pre_post1')) contrasts(data$condition) <- c(0, 1) contrasts(data$pre_post) <- c(0, 1) model_p_0 <- summary(lme(dv ~ condition * pre_post, random=~1|id, data)) expect_equal(round(slopes[3, 'Test Estimate'], 3), get_coef.lme(model_p_0, 'condition1')) contrasts(data$pre_post) <- c(1, 0) model_p_1 <- summary(lme(dv ~ condition * pre_post, random=~1|id, data)) expect_equal(round(slopes[4, 'Test Estimate'], 3), get_coef.lme(model_p_1, 'condition1')) }) test_that('lmer with interaction works', { set.seed(123) pre_treat <- rnorm(50) set.seed(234) post_treat <- 2 + rnorm(50) set.seed(345) pre_control <- rnorm(50) set.seed(456) post_control <- rnorm(50) dv <- c(pre_treat, post_treat, pre_control, post_control) pre_post <- factor(rep(c(rep(0, 50), rep(1, 50)), 2)) condition <- factor(c(rep(0, 100), rep(1, 100))) id <- c(rep(1:50, 2), rep(51:100, 2)) data <- data.frame(id, condition, pre_post, dv) model <- lmer(dv ~ condition * pre_post + (1|id), data) slopes <- simple_slopes(model) contrasts(data$condition) <- c(0, 1) model_c_0 <- summary(lmer(dv ~ condition * pre_post + (1|id), data)) expect_equal(round(slopes[1, 'Test Estimate'], 3), get_coef(model_c_0, 'pre_post1')) contrasts(data$condition) <- c(1, 0) model_c_1 <- summary(lmer(dv ~ condition * pre_post + (1|id), data)) expect_equal(round(slopes[2, 'Test Estimate'], 3), get_coef(model_c_1, 'pre_post1')) contrasts(data$condition) <- c(0, 1) contrasts(data$pre_post) <- c(0, 1) model_p_0 <- summary(lmer(dv ~ condition * pre_post + (1|id), data)) expect_equal(round(slopes[3, 'Test Estimate'], 3), get_coef(model_p_0, 'condition1')) contrasts(data$pre_post) <- c(1, 0) model_p_1 <- summary(lmer(dv ~ condition * pre_post + (1|id), data)) expect_equal(round(slopes[4, 'Test Estimate'], 3), get_coef(model_p_1, 'condition1')) }) test_that('character vector works', { set.seed(123) x1 <- rnorm(100) x2 <- c(rep("first", 50), rep("second", 50)) set.seed(345) y <- x1 * (as.numeric(factor(x2))-1) + rnorm(100) data <- data.frame(x1, x2, y) model <- lm(y ~ x1 * x2, data) slopes <- simple_slopes(model) model_x1_m1 <- summary(lm(y ~ I((x1 - mean(x1)) + sd(x1)) * x2, data)) expect_equal(round(slopes[1, 'Test Estimate'], 3), get_coef(model_x1_m1, 'x2second')) model_x1_0 <- summary(lm(y ~ I(x1 - mean(x1)) * x2, data)) expect_equal(round(slopes[2, 'Test Estimate'], 3), get_coef(model_x1_0, 'x2second')) model_x1_p1 <- summary(lm(y ~ I((x1 - mean(x1)) - sd(x1)) * x2, data)) expect_equal(round(slopes[3, 'Test Estimate'], 3), get_coef(model_x1_p1, 'x2second')) model_x2_0 <- summary(lm(y ~ x1 * x2, data)) expect_equal(round(slopes[4, 'Test Estimate'], 3), get_coef(model_x2_0, 'x1')) data$x2 <- factor(data$x2) contrasts(data$x2) <- c(1, 0) model_x2_1 <- summary(lm(y ~ x1 * x2, data)) expect_equal(round(slopes[5, 'Test Estimate'], 3), get_coef(model_x2_1, 'x1')) })
censloop_em<-function(meanmodel, theta.old,beta.old, p.old, x.0, X,censor.ind, mean.intercept, maxit, eps){ n<-length(X) R2<-list() Z20<-list() Z21<-list() Y2<-rep(NA, times=n) Ca<- rep(NULL, times=n) conv<-FALSE it<-NULL p.old[p.old < 1e-10] <- 1e-10 p.old[p.old > 1e10] <- 1e10 theta.new<-theta.old z=sqrt(1/p.old) c_1<-X*z c_1[censor.ind==-1] <- NA c_2<-X*z c_2[censor.ind==1]<-NA beta.old<-NULL outmean<-mean.models(c_1, c_2, z,n, meanmodel,mean.intercept, beta.old, maxit, eps) mean.fit<-outmean$mean.fit beta.old<-outmean$beta.new beta.new<-beta.old for (q in 1:maxit) { it<-q X0<-X-mean.fit Y2[censor.ind==0]<-(theta.old[1]+(theta.old[1]**2/p.old)*(X0**2/p.old - 1))[censor.ind==0] Ca[censor.ind==-1 & round(stats::pnorm((X0)/sqrt(p.old)), digits=5)!=0]<-((stats::pnorm((X0)/sqrt(p.old)))/(-stats::dnorm((X0)/sqrt(p.old))))[censor.ind==-1 & round(stats::pnorm((X0)/sqrt(p.old)), digits=5)!=0] Ca[censor.ind==-1 & round(stats::pnorm((X0)/sqrt(p.old)), digits=5)==0]<- 1/((X0)/sqrt(p.old))[censor.ind==-1 & round(stats::pnorm((X0)/sqrt(p.old)), digits=5)==0] Y2[censor.ind==-1]<-(theta.old[1]+(theta.old[1]**2/p.old)*((X0/sqrt(p.old))/Ca))[censor.ind==-1] Ca[censor.ind==1 & round(stats::pnorm((X0)/sqrt(p.old)), digits=5)!=0]<-((1-stats::pnorm((X0)/sqrt(p.old)))/(stats::dnorm((X0)/sqrt(p.old))))[censor.ind==1 & round(stats::pnorm((X0)/sqrt(p.old)), digits=5)!=0] Ca[censor.ind==1 & round(stats::pnorm((X0)/sqrt(p.old)), digits=5)==0]<- 1/((X0)/sqrt(p.old))[censor.ind==1 & round(stats::pnorm((X0)/sqrt(p.old)), digits=5)==0] Y2[censor.ind==1]<- (theta.old[1]+(theta.old[1]**2/p.old)*((X0/sqrt(p.old))/Ca))[censor.ind==1] theta.new[1]<-mean(Y2) if (!is.null(x.0)){ X00<-X0[censor.ind==0] X01<-X0[censor.ind!=0] x00<-x.0[censor.ind==0,] x01<-x.0[censor.ind!=0,] if (length(theta.old)<3){ x00<-as.matrix(x00) x01<-as.matrix(x01) } pold0<-p.old[censor.ind==0] pold1<-p.old[censor.ind!=0] Ca1<-Ca[censor.ind!=0] Z20<-sapply(1:ncol(x00),function(x) x00[,x]*theta.old[x+1]+((theta.old[x+1]*x00[,x])**2/pold0)*(X00**2/pold0-1)) Z21<-sapply(1:ncol(x01),function(x) x01[,x]*theta.old[x+1]+((theta.old[x+1]*x01[,x])**2/pold1)*(X01/sqrt(pold1))/Ca1) zz<-rbind(Z20, Z21) xx<-rbind(x00, x01) theta.new[-1]<-sapply(1:ncol(x.0), function(x) mean(zz[,x]/xx[,x],na.rm=TRUE )) } z=1/sqrt(p.old) z[z > 1e10] <- 1e10 c_1<-X*z c_1[censor.ind==-1]<-NA c_2<-X*z c_2[censor.ind==1]<-NA outmean<-tryCatch({ mean.models(c_1, c_2, z,n, meanmodel,mean.intercept,beta.old, maxit, eps) },error=function(cond){ message("Mean model (survreg) failed to converge at maxit=", maxit, ". Attempting more iterations.") return(NULL) },warning=function(cond){ message("Mean model (survreg) failed to converge at maxit=", maxit, ". Attempting more iterations.") }) if (is.null(outmean)==TRUE || any(is.nan(outmean$beta.new))){ outmean<-tryCatch({ mean.models(c_1, c_2, z,n, meanmodel,mean.intercept,beta.old, maxit*100, eps) },error=function(cond){ message("Mean model (survreg) still failed to converge at maxit=", maxit, "*100. Review initial estimates.") return(NULL) },warning=function(cond){ message("Mean model (survreg) still failed to converge at maxit=", maxit, "*100. Review initial estimates.") }) } if (is.null(outmean)==TRUE){ break} beta.new<-outmean$beta.new mean.fit<-outmean$mean.fit if (all(is.finite(c(beta.new, theta.new)))==TRUE){ reldiff<-sqrt(sum((c(theta.new,beta.new)-c(theta.old,beta.old))**2)/sum(c(beta.old,theta.old))**2) }else { reldiff<-NaN print("Estimates are not finite. Please review initial estimates.") print(c("Mean:",beta.new)) print(c("Variance",theta.new)) break } theta.old<-theta.new beta.old<-beta.new p.old<-rep(theta.old[1], n) if (!is.null(x.0)){ p.old<-rowSums(cbind(rep(theta.new[1], n),sapply(1:ncol(x.0), function(x) theta.new[x+1]*x.0[,x]))) } if (sum(p.old<0)>0){ print("Estimates for variance/scale have gone negative. Please review initial estimates.") break } if (is.finite(reldiff)==TRUE){ if (reldiff<eps){ conv<-TRUE break } } } if (is.null(outmean)==TRUE){ list(conv=FALSE, reldiff=NA, it=it, mean=beta.old, theta.new=theta.old, fittedmean=NULL, p.old=p.old) }else{ list(conv=conv, reldiff=reldiff, it=it, mean=beta.new, theta.new=theta.new, fittedmean=mean.fit, p.old=p.old) } } mean.models<-function(c_1, c_2, z,n, meanmodel,mean.intercept,beta.old, maxit, eps){ if (is.null(meanmodel)==TRUE){ mean.fit<-rep(0,n) beta.new<-NULL }else if (is.data.frame(meanmodel)==TRUE){ if (mean.intercept==TRUE){ meanmodel2<-as.data.frame(apply(meanmodel, 2, function(x) x*z)) l<-survival::survreg(survival::Surv(c_1, c_2, type="interval2")~ -1+z+ . , data=meanmodel2, dist = "gaussian", maxiter=maxit, rel.tolerance=eps, init=beta.old) beta.new<-l$coeff mean.fit<-l$linear.predictor/z }else if (mean.intercept==FALSE){ meanmodel2<-as.data.frame(apply(meanmodel, 2, function(x) x*z)) l<-survival::survreg(survival::Surv(c_1, c_2, type="interval2")~ -1+., data=meanmodel2, dist = "gaussian", maxiter=maxit, rel.tolerance=eps, init=beta.old) beta.new<-l$coeff mean.fit<-l$linear.predictor/z } }else if (meanmodel[1]==FALSE){ l<-survival::survreg(survival::Surv(c_1, c_2, type="interval2")~ -1+z, dist = "gaussian", maxiter=maxit, rel.tolerance=eps) beta.new<-l$coeff mean.fit<-l$linear.predictor/z } return(list(mean.fit=mean.fit, beta.new=beta.new)) }
check_pkg_dependencies <- function(pkg_root = NULL, on_success = NULL, on_fail = stop, reader = readLines) { if (!exists("startsWith", mode = "function")) { stop("`startsWith` not present, possibly due to insufficient R version.\n\t", "Current:\t", getRversion(), "\n\t", "Required:\t", "3.3.0", ".") } if (!requireNamespace("rcheology", quietly = TRUE)) { stop("package:rcheology not installed, but required. ", "Run `install.packages('rcheology')` and try again.") } if (is.null(pkg_root)) { if (file.exists("DESCRIPTION")) { pkg_root <- "." } else { } } else { if (length(pkg_root) > 1L) { return(sapply(pkg_root, check_pkg_dependencies, on_success = on_success, on_fail = on_fail, reader = reader)) } if (!file.exists(file.path(pkg_root, "DESCRIPTION"))) { return(on_fail("Unable to find DESCRIPTION")) } } strSplitter <- function(x) { if (!is.character(x)) { warning("strSplitter provided with non-character object.") return("") } unlist(strsplit(x, split = "(?<=\\()\\b", perl = TRUE)) } rFunsDefined <- lapply(dir(file.path(pkg_root, "R"), pattern = "\\.R", full.names = TRUE), reader) %>% lapply(trimws) %>% lapply(function(x) x[!startsWith(x, " lapply(function(x) { sub("^([A-Za-z0-9_\\.]+)\\s*([=]|<-)\\s*function\\(.*$", "\\1", grep("^([A-Za-z0-9_\\.]+)\\s*([=]|<-)\\s*function\\(.*$", x, perl = FALSE, value = TRUE)) }) %>% unlist %>% unique RfunsUsed <- lapply(dir(file.path(pkg_root, "R"), pattern = "\\.R$", full.names = TRUE), function(x) { setdiff(all.names(parse(x)), all.vars(parse(x))) }) %>% unlist %>% unique stated_R_dep <- desc::desc_get_deps(file = pkg_root) %>% as.data.table %>% .[type == "Depends" & package == "R"] %>% .[["version"]] if (length(stated_R_dep)) { if (length(stated_R_dep) != 1L) { warning("Multiple stated R dependencies, using first...") stated_R_dep <- stated_R_dep[1] } } else { stated_R_dep <- ">= 1.0.0" } stated_R_dep <- strsplit(stated_R_dep, split = " ")[[1L]] R_dep_comparator <- stated_R_dep[1] stated_R_dep <- stated_R_dep[2] Rversion <- NULL base_funs_used_by_version_introduced <- rcheology::rcheology %>% as.data.table %>% .[package == "base"] %>% unique(by = "name") %>% .[name %chin% RfunsUsed] %>% setkey(Rversion) base_funs_introduced_later_than_stated_dep <- switch(R_dep_comparator, "<" = base_funs_used_by_version_introduced[Rversion <= stated_R_dep], "<=" = base_funs_used_by_version_introduced[Rversion < stated_R_dep], ">=" = base_funs_used_by_version_introduced[Rversion > stated_R_dep], ">" = base_funs_used_by_version_introduced[Rversion >= stated_R_dep], stop("Unexpected R dependency: ", stated_R_dep, ".")) if (nrow(base_funs_introduced_later_than_stated_dep)) { cat(basename(pkg_root), ":\n") print(base_funs_introduced_later_than_stated_dep) return(on_fail("Base function not respecting dependency:\n\t", base_funs_introduced_later_than_stated_dep[1][[1L]], "\t", base_funs_introduced_later_than_stated_dep[1][[2L]])) } on_success } skip_only_on_cran <- function() { if (identical(Sys.getenv("NOT_CRAN"), "true") || identical(Sys.getenv("TRAVIS"), "true") || identical(Sys.getenv("APPVEYOR"), "True") || nzchar(Sys.getenv("CODECOV_TOKEN"))) { return(invisible(TRUE)) } testthat::skip("On CRAN") }
makeOMLEstimationProcedure = function( type, data.splits.url = NA_character_, data.splits = NULL, parameters = NULL) { assertString(type) assertString(data.splits.url, na.ok = TRUE) if (!is.null(data.splits)) assertDataFrame(data.splits) if (!is.null(parameters)) assertList(parameters, names = "named") makeS3Obj("OMLEstimationProcedure", type = type, data.splits.url = data.splits.url, data.splits = data.splits, parameters = parameters ) } print.OMLEstimationProcedure = function(x, ...) { catf("\nEstimation Method :: %s", x$type) catf("\tParameters:") for (i in seq_along(x$parameters)) { if (!is.na(x$parameters[[i]]) && x$parameters[[i]] != "") catf("\t\t%s = %s", names(x$parameters)[i], x$parameters[[i]]) } }
update_yml <- function(template_in = NULL, template_out = NULL) { if (is.null(template_in)) { tic_ymls <- list.files(usethis::proj_path(".github/workflows"), pattern = "^tic*", full.names = TRUE ) if (length(tic_ymls) > 0) { ghactions <- tic_ymls } else { if (file.exists(usethis::proj_path(".github/workflows", "main.yml"))) { ghactions <- usethis::proj_path(".github/workflows", "main.yml") } else { ghactions <- NULL } } if (file.exists(usethis::proj_path(".circleci/", "config.yml"))) { circle <- usethis::proj_path(".circleci", "config.yml") } else { circle <- NULL } providers <- c(ghactions, circle) } else { providers <- template_in } for (instance in providers) { instance_txt <- readLines(instance) if (is.null(template_out)) { template_out <- instance } rev_date_local <- tryCatch(as.character(gsub( ".*(\\d{4}-\\d{2}-\\d{2}).*", "\\1", instance_txt[2] )), error = function(cond) { return(NA) } ) if (is.na(rev_date_local)) { cli::cli_alert_warning("{.file {basename(instance)}} does not (yet) contain a (valid) {.pkg tic} revision date (format: YYYY-MM-DD). If {.file {basename(instance)}} is managed by {.pkg tic}, please update the template manually one last time or manually add a revision date into the template as the first line of your template. Otherwise ignore this message.", wrap = TRUE ) cli::cli_alert("Skipping {.file {basename(instance)}}") template_out <- NULL next } tmpl_type <- stringr::str_split(instance_txt[1], "template: ", simplify = TRUE )[, 2] ci_provider <- stringr::str_extract_all(instance_txt[1], "(?<=tic ).+(?= template)", simplify = TRUE )[1, 1] tmpl_latest <- switch(ci_provider, "GitHub Actions" = use_ghactions_yml(tmpl_type, write = FALSE, quiet = TRUE ), "Circle CI" = use_circle_yml(tmpl_type, write = FALSE, quiet = TRUE) ) rev_date_latest <- as.character(gsub( ".*(\\d{4}-\\d{2}-\\d{2}).*", "\\1", tmpl_latest[2] ), quiet = TRUE) if (!rev_date_latest > rev_date_local) { cli::cli_alert_info( "{.file {basename(instance)}}: You already have the latest version of the {ci_provider} template (rev_date_latest).", wrap = TRUE ) next } else { cli::cli_alert("Updating {ci_provider} template {.file {basename(instance)}} from version {.field {rev_date_local}} to version {.field {rev_date_latest}}.", wrap = TRUE) } tmpl_latest <- switch(ci_provider, "GitHub Actions" = update_ghactions_yml(instance_txt, tmpl_latest), "Circle CI" = update_circle_yml(instance_txt, tmpl_latest) ) cli::cli_alert_info("Writing {.file {template_out}}.") cli::cli_par() cli::cli_end() writeLines(tmpl_latest, template_out) template_out <- NULL } } update_ghactions_yml <- function(tmpl_local, tmpl_latest) { custom_matrix_matrix_name <- stringr::str_which( tmpl_local, " ) if (length(custom_matrix_matrix_name) > 0) { cli::cli_alert_info("Found {.val {length(custom_matrix_matrix_name)}} custom matrix name variable{?s}.", wrap = TRUE) matrix_name_index_latest <- stringr::str_which( tmpl_latest, "name: \\$\\{\\{ matrix" ) custom_matrix_matrix_name_list <- purrr::map(custom_matrix_matrix_name, ~ { tmpl_local[.x:(.x + 1)] }) for (i in seq_along(custom_matrix_matrix_name_list)) { tmpl_latest <- replace( tmpl_latest, c(matrix_name_index_latest:(matrix_name_index_latest + 1)), custom_matrix_matrix_name_list[[i]] ) tmpl_latest <- append(tmpl_latest, "", after = matrix_name_index_latest + 1 ) } } custom_matrix_env_vars <- stringr::str_which( tmpl_local, " ) if (length(custom_matrix_env_vars) > 0) { cli::cli_alert_info("Found {.val {length(custom_matrix_env_vars)}} custom matrix env variable{?s}.", wrap = TRUE) matrix_env_var_index_latest <- stringr::str_which( tmpl_latest, "config:" ) + 1 custom_matrix_env_var_list <- purrr::map(custom_matrix_env_vars, ~ { tmpl_local[.x:(.x + 1)] }) for (i in seq_along(custom_matrix_env_var_list)) { tmpl_latest <- append(tmpl_latest, custom_matrix_env_var_list[[i]], after = matrix_env_var_index_latest ) } } custom_env_vars <- stringr::str_which(tmpl_local, " if (length(custom_env_vars) > 0) { cli::cli_alert_info("Found {.val {length(custom_env_vars)}} custom env variable{?s}.", wrap = TRUE) env_var_index_latest <- stringr::str_which(tmpl_latest, "env:") custom_env_var_list <- purrr::map(custom_env_vars, ~ { tmpl_local[.x:(.x + 1)] }) for (i in seq_along(custom_env_var_list)) { tmpl_latest <- append(tmpl_latest, custom_env_var_list[[i]], after = env_var_index_latest ) } tmpl_latest <- account_for_dup_env_vars( custom_env_var_list, env_var_index_latest, tmpl_latest ) } custom_blocks_start <- stringr::str_which( tmpl_local, 'name: "\\[Custom block' ) if (length(custom_blocks_start > 0)) { cli::cli_alert_info("Found {.val {length(custom_blocks_start)}} custom user block{?s}.", wrap = TRUE) stringr::str_which(tmpl_local, "^\\s*$") custom_blocks_list <- purrr::map(custom_blocks_start, ~ { block_end <- purrr::keep( stringr::str_which(tmpl_local, "^\\s*$"), function(y) y > .x )[1] - 1 append(tmpl_local[.x:block_end], "") }) tmpl_blocks_names <- purrr::map_chr(custom_blocks_start, ~ { row_inds_prev_temp_block <- tail(purrr::keep( stringr::str_which(tmpl_local, "- name"), function(y) y < .x ), n = 1) purrr::map_chr(row_inds_prev_temp_block, ~ stringr::str_extract(tmpl_local[.x], "-.*")) }) tmpl_blocks_names <- purrr::map_chr(custom_blocks_start, ~ { row_inds_prev_temp_block <- tail(purrr::keep( stringr::str_which(tmpl_local, "- name: (?!\"\\[Custom)"), function(y) y < .x ), n = 1) purrr::map_chr(row_inds_prev_temp_block, ~ stringr::str_extract(tmpl_local[.x], "-.*")) }) tmpl_blocks_names_fallback <- purrr::map_chr(custom_blocks_start, ~ { row_inds_prev_temp_block <- tail(purrr::keep( stringr::str_which(tmpl_local, "- name: (?!\"\\[Custom)"), function(y) y < .x ), n = 2)[1] purrr::map_chr(row_inds_prev_temp_block, ~ stringr::str_extract(tmpl_local[.x], "-.*")) }) for (i in rev(seq_along(tmpl_blocks_names))) { in_tmpl_latest <- purrr::map_lgl(tmpl_blocks_names[i], function(index) { any(stringr::str_detect(tmpl_latest, stringr::fixed(index))) }) if (!in_tmpl_latest) { tmpl_blocks_names[i] <- tmpl_blocks_names_fallback[i] } in_tmpl_latest <- purrr::map_lgl(tmpl_blocks_names[i], function(index) { any(stringr::str_detect(tmpl_latest, stringr::fixed(index))) }) if (!in_tmpl_latest) { cli::cli_par() cli::cli_end() cli::cli_alert_danger("Not enough unique anchor points between your local {.pkg tic} template and the newest upstream version could be found. Please update manually and try again next time. If this error persists, your local {.pkg tic} template is too different compared to the upstream template {.pkg tic} to support automatic updating.", wrap = TRUE) stopc("Not enough valid anchors points found between local and upstream template.") } tmpl_latest_index <- purrr::map_int( tmpl_blocks_names[i], function(index) { stringr::str_which(tmpl_latest, stringr::fixed(index)) } ) tmpl_latest_insert_index <- purrr::map_int( tmpl_latest_index, function(insert_index) { purrr::keep( stringr::str_which(tmpl_latest, "^\\s*$"), function(x) x > insert_index )[1] } ) tmpl_latest <- append(tmpl_latest, custom_blocks_list[[i]], after = tmpl_latest_insert_index ) } } custom_header <- stringr::str_which( tmpl_local, " ) if (length(custom_header) > 0) { cli::cli_alert_info("Found a custom header entry. Will use it instead of the header in the {.pkg tic} upstream template.", wrap = TRUE ) custom_header_local <- stringr::str_which( tmpl_local, "env:" ) custom_header_latest <- stringr::str_which( tmpl_latest, "env:" ) rev_date_latest <- as.Date(gsub( ".*(\\d{4}-\\d{2}-\\d{2}).*", "\\1", tmpl_latest[2] ), quiet = TRUE) header_local <- tmpl_local[1:custom_header_local] tmpl_latest <- tmpl_latest[-(1:custom_header_latest)] tmpl_latest <- append(tmpl_latest, header_local, after = 0) tmpl_latest[2] <- sprintf(" } return(tmpl_latest) } update_circle_yml <- function(tmpl_local, tmpl_latest) { custom_env_vars <- stringr::str_which(tmpl_local, " if (length(custom_env_vars) > 0) { cli::cli_alert_info("Found {.val {length(custom_env_vars)}} custom env variable{?s}.", wrap = TRUE) for (release in c( " " )) { env_var_index_latest <- stringr::str_which(tmpl_latest, release) + 1 block_end <- purrr::keep( stringr::str_which(tmpl_latest, "^\\s*$"), ~ .x > env_var_index_latest )[1] - 1 custom_env_var_list <- purrr::map(custom_env_vars, ~ { tmpl_local[.x:(.x + 1)] }) env_var_index_local <- stringr::str_which(tmpl_local, release) + 1 block_end_local <- purrr::keep( stringr::str_which(tmpl_local, "^\\s*$"), ~ .x > env_var_index_local )[1] - 1 sub_custom_env_var_list <- custom_env_var_list[(custom_env_vars > env_var_index_local) & (custom_env_vars < block_end_local)] if (length(sub_custom_env_var_list) > 0) { for (i in sub_custom_env_var_list) { tmpl_latest <- append(tmpl_latest, i, env_var_index_latest) } } } tmpl_latest <- account_for_dup_env_vars( custom_env_var_list, env_var_index_latest, tmpl_latest ) } custom_blocks_start <- stringr::str_which( tmpl_local, 'name: "\\[Custom block' ) - 1 if (length(custom_blocks_start > 0)) { cli::cli_alert_info("Found {.val {length(custom_blocks_start)}} custom user block{?s}.", wrap = TRUE) stringr::str_which(tmpl_local, "^\\s*$") custom_blocks_list <- purrr::map(custom_blocks_start, ~ { block_end <- purrr::keep( stringr::str_which(tmpl_local, "^\\s*$"), function(y) y > .x )[1] - 1 append(tmpl_local[.x:block_end], "") }) tmpl_blocks_names <- purrr::map_chr(custom_blocks_start, ~ { row_inds_prev_temp_block <- tail(purrr::keep( stringr::str_which(tmpl_local, "- run:"), function(y) y < .x ), n = 1) + 1 purrr::map_chr(row_inds_prev_temp_block, ~ stringr::str_extract(tmpl_local[.x], "name:.*")) }) for (i in seq_along(tmpl_blocks_names)) { tmpl_latest_index <- purrr::map_int( tmpl_blocks_names[i], function(index) { stringr::str_which(tmpl_latest, stringr::fixed(index)) } ) tmpl_latest_insert_index <- purrr::map_int( tmpl_latest_index, function(insert_index) { purrr::keep( stringr::str_which(tmpl_latest, "^\\s*$"), function(x) x > insert_index )[1] } ) tmpl_latest <- append(tmpl_latest, custom_blocks_list[[i]], after = tmpl_latest_insert_index ) } } return(tmpl_latest) } use_update_tic <- function() { tmpl <- readLines(system.file("templates/update-tic.yml", package = "tic")) writeLines(tmpl, con = ".github/workflows/update-tic.yml") cli::cli_alert("Added new file:") data <- data.frame( stringsAsFactors = FALSE, package = c( basename(getwd()), ".github", "workflows", "update-tic.yml" ), dependencies = I(list( ".github", "workflows", "update-tic.yml", character(0) )) ) print(tree(data, root = basename(getwd()))) cli::cli_alert_info("Note that you need to add a secret with 'workflow' scopes named {.var TIC_UPDATE} to your repo to make this automation work. You can use {.code tic::gha_add_secret(<secret>, 'TIC_UPDATE')} for this.", wrap = TRUE ) }
Var_approx <- function(y, pik, n, method, ...){ method <- match.arg(method, c("Hajek1", "Hajek2", "HartleyRao1", "HartleyRao2", "FixedPoint") ) N <- length(y) if( length(n)>1 ){ stop("Argument 'n' should be a scalar!") }else if( !is.numeric(n) | n != as.integer(n) ){ stop( "Argument 'n' must be an integer number") } if( !(class(y) %in% c("numeric", "integer")) ){ stop( "The argument 'y' should be a numeric vector!") }else if( N < 2 ){ stop( "The 'y' vector is too short!" ) }else if( any(y %in% c(NA, NaN, Inf)) ){ stop( "The 'y' vector contains invalid values (NA, NaN, Inf)" ) } if( any(y<0) ){ message( "Some 'y' values are negative, continuing anyway...") } if( !identical( class(pik), "numeric" ) ){ stop( "The argument 'pik' should be a numeric vector!") }else if( !identical(N, length(pik) ) ){ stop( "The 'pik' vector must have same length as 'y'!" ) }else if( any(pik<0) | any(pik>1) ){ stop( "Some values of the 'pik' vector are outside the interval [0, 1]") }else if( any(pik %in% c(NA, NaN, Inf)) ){ stop( "The 'pik' vector contains invalid values (NA, NaN, Inf)" ) }else if( !all.equal( sum(pik), n) ) stop("the sum of 'pik' values should be equal to 'n' ") if( identical(method, 'Hajek1') ){ bk <- pik * (1-pik) * N / (N-1) ys <- pik * sum( bk*y/pik ) / sum(bk) V <- sum( bk*(y-ys)^2 / (pik**2) ) }else if( identical(method, 'Hajek2') ){ d <- pik*(1-pik) ak <- n * (1-pik) / sum( d ) yt <- sum( y*ak ) V <- sum( d * (y/pik - yt/n)^2 ) }else if( identical(method, 'HartleyRao1') ){ p2 <- pik**2 sp2 <- sum(p2) Y <- sum(y) sdif <- (y/pik - Y/n)**2 V <- sum( pik * ( 1 - (n-1)*pik/n ) * sdif ) V <- V - (n-1)/(n**2) * sum( (2*pik^3 - p2*sp2/2) * sdif ) V <- V + 2*(n-1)/(n**3) * ( sum(pik*y) - Y/n * sp2 )^2 }else if( identical(method, 'HartleyRao2') ){ Y <- sum(y) sdif <- (y/pik - Y/n)**2 V <- sum( pik * (1 - (n-1)/n * pik) * sdif ) }else if( identical(method, 'FixedPoint') ){ argList <- list(...) ifelse( is.null(argList$eps), eps <- 1e-05, eps <- argList$eps ) ifelse( is.null(argList$maxIter), maxIter <- 1000, maxIter <- argList$maxIter ) d <- pik*(1-pik) necessaryCondition <- all( d/sum(d) < 0.5 ) if(necessaryCondition){ b0 <- d * N/(N-1) iter <- 1 err <- Inf while( iter<maxIter & err>eps ){ bk <- b0**2 / sum(b0) + d err <- max( abs(bk - b0) ) b0 <- bk iter <- iter + 1 } if(err > eps) stop("Did not reach convergence") }else{ bk <- N*d / ( (N-1) * sum(d) ) bk <- d * (bk + 1) } ys <- pik * sum( bk*y/pik ) / sum(bk) V <- sum( bk*(y-ys)^2 / (pik**2) ) } return(V) }
test_that("runTests works", { calls <- list() wd <- NULL filesToError <- "runner2.R" sourceStub <- function(...){ calls[[length(calls)+1]] <<- list(...) wd <<- getwd() if(list(...)[[1]] %in% filesToError){ stop("I was told to throw an error") } NULL } loadCalls <- list() loadSupportStub <- function(...){ loadCalls[[length(calls)+1]] <<- list(...) NULL } runTestsSpy <- rewire(runTests, sourceUTF8 = sourceStub, loadSupport=loadSupportStub) res <- suppressMessages( runTestsSpy(test_path("../test-helpers/app1-standard"), assert = FALSE) ) expect_length(calls, 2) expect_match(calls[[1]][[1]], "runner1\\.R$", perl=TRUE) expect_match(calls[[2]][[1]], "runner2\\.R$", perl=TRUE) env1 <- calls[[1]]$envir env2 <- calls[[2]]$envir expect_identical(parent.env(env1), parent.env(env2)) expect_true(!identical(env1, env2)) expect_equal(normalizePath(wd), normalizePath( file.path(test_path("../test-helpers/app1-standard"), "tests"))) expect_equal(all(res$pass), FALSE) expect_length(res$file, 2) expect_equal(basename(res$file[1]), "runner1.R") expect_equal(res[2,]$result[[1]]$message, "I was told to throw an error") expect_s3_class(res, "shiny_runtests") expect_length(loadCalls, 0) filesToError <- character(0) calls <- list() res <- runTestsSpy(test_path("../test-helpers/app1-standard")) expect_equal(all(res$pass), TRUE) expect_equal(basename(res$file), c("runner1.R", "runner2.R")) expect_length(calls, 2) expect_match(calls[[1]][[1]], "runner1\\.R", perl=TRUE) expect_match(calls[[2]][[1]], "runner2\\.R", perl=TRUE) }) test_that("calls out to shinytest when appropriate", { is_legacy_shinytest_val <- TRUE is_legacy_shinytest_dir_stub <- function(...){ is_legacy_shinytest_val } runTestsSpy <- rewire(runTests, is_legacy_shinytest_dir = is_legacy_shinytest_dir_stub) expect_error( runTestsSpy(test_path("../test-helpers/app1-standard"), assert = FALSE), "not supported" ) is_legacy_shinytest_val <- FALSE res <- runTestsSpy(test_path("../test-helpers/app1-standard")) expect_s3_class(res, "shiny_runtests") }) test_that("runTests filters", { calls <- list() sourceStub <- function(...){ calls[[length(calls)+1]] <<- list(...) NULL } runTestsSpy <- rewire(runTests, sourceUTF8 = sourceStub) runTestsSpy(test_path("../test-helpers/app1-standard")) expect_length(calls, 2) calls <- list() runTestsSpy(test_path("../test-helpers/app1-standard"), filter="runner1") expect_length(calls, 1) calls <- list() expect_error(runTestsSpy(test_path("../test-helpers/app1-standard"), filter="i don't exist"), "matched the given filter") }) test_that("runTests handles the absence of tests", { expect_error(runTests(test_path("../test-helpers/app2-nested")), "No tests directory found") expect_message(res <- runTests(test_path("../test-helpers/app6-empty-tests")), "No test runners found in") expect_equal(res$file, character(0)) expect_equal(res$pass, logical(0)) expect_equal(res$result, I(list())) expect_s3_class(res, "shiny_runtests") }) test_that("runTests runs as expected without rewiring", { appDir <- test_path(file.path("..", "test-helpers", "app1-standard")) df <- testthat::expect_output( print(runTests(appDir = appDir, assert = FALSE)), "Shiny App Test Results\\n\\* Success\\n - app1-standard/tests/runner1\\.R\\n - app1-standard/tests/runner2\\.R" ) expect_equal(df, data.frame( file = file.path(appDir, "tests", c("runner1.R", "runner2.R")), pass = c(TRUE, TRUE), result = I(list(1, NULL)), stringsAsFactors = FALSE ), ignore_attr = TRUE) expect_s3_class(df, "shiny_runtests") }) test_that("app template works with runTests", { suppressWarnings(testthat::skip_if_not_installed("shinytest", "1.3.1.9000")) testthat::skip_if(!shinytest::dependenciesInstalled(), "shinytest dependencies not installed. Call `shinytest::installDependencies()`") make_combos <- function(...) { args <- list(...) combo_dt <- do.call(expand.grid, args) lapply(apply(combo_dt, 1, unlist), unname) } combos <- unique(unlist( recursive = FALSE, list( "all", make_combos("app", list(NULL, "module"), "shinytest"), make_combos("app", list(NULL, "module"), list(NULL, "rdir"), list(NULL, "testthat")) ) )) for (combo in combos) { random_folder <- paste0("shinyAppTemplate-", paste0(combo, collapse = "_")) tempTemplateDir <- file.path(tempfile(), random_folder) suppressMessages(shinyAppTemplate(tempTemplateDir, combo)) on.exit(unlink(tempTemplateDir, recursive = TRUE), add = TRUE) if (any(c("all", "shinytest", "testthat") %in% combo)) { suppressMessages(capture.output({ out <- runTests(tempTemplateDir, assert = FALSE) })) expect_snapshot(out) } else { expect_error( suppressMessages(runTests(tempTemplateDir)) ) } } })
as_series <- function(x, x_class, y_class, sheetname = "sheet1" ){ dataset <- x$data_series w_x <- which( names(dataset) %in% x$x ) x_serie_range <- cell_limits(ul = c(2, w_x), lr = c(nrow(dataset)+1, w_x), sheet = sheetname) x_serie_range <- as.range(x_serie_range, fo = "A1", strict = TRUE, sheet = TRUE) x_serie <- update(x_class, region = x_serie_range, values = dataset[[x$x]]) label_columns <- get_label_names(x) series <- list() w_y_values <- which(names(dataset) %in% get_series_names(x)) w_l_values <- which(names(dataset) %in% label_columns) for( w_y_index in seq_along(w_y_values)){ w_y <- w_y_values[w_y_index] w_l <- w_l_values[w_y_index] y_colname <- names(dataset)[w_y] l_colname <- names(dataset)[w_l] serie_name_range <- ra_ref(row_ref = 1, col_ref = w_y, sheet = sheetname) serie_name_range <- to_string(serie_name_range, fo = "A1") serie_name <- str_ref(values = y_colname, region = serie_name_range) y_serie_range <- cell_limits(ul = c(2, w_y), lr = c(nrow(dataset)+1, w_y), sheet = sheetname) y_serie_range <- as.range(y_serie_range, fo = "A1", strict = TRUE, sheet = TRUE) y_serie <- update(y_class, region = y_serie_range, values = dataset[[y_colname]]) if(length(label_columns) > 0 ){ label_serie_range <- cell_limits(ul = c(2, w_l), lr = c(nrow(dataset)+1, w_l), sheet = sheetname) label_serie_range <- as.range(label_serie_range, fo = "A1", strict = TRUE, sheet = TRUE) label_serie <- label_ref(values = dataset[[l_colname]], region = label_serie_range) } else label_serie <- NULL ser <- list( idx = length(series), order = length(series), tx = serie_name, x = x_serie, y = y_serie, label = label_serie, stroke = x$series_settings$colour[y_colname], fill = x$series_settings$fill[y_colname], symbol = x$series_settings$symbol[y_colname], line_style = x$series_settings$line_style[y_colname], size = x$series_settings$size[y_colname], line_width = x$series_settings$line_width[y_colname], labels_fp = x$series_settings$labels_fp[[y_colname]], smooth = x$series_settings$smooth[y_colname] ) series <- append(series, list(ser) ) } series }
gaussian.marg <- function(link = "identity" ) { fm <- gaussian( substitute( link ) ) ans <- list() ans$start <- function(y, x, z, offset) { if( !is.null(z) ) offset <- list( as.vector(offset$mean), as.vector(offset$precision) ) eps <- sqrt(.Machine$double.eps) m <- glm.fit( x , y, offset=offset$mean, family=fm ) sigma <- max( 10*eps, sd( residuals(m) ) ) lambda <- c( coef(m), rep.int( 0, NCOL(z) ) ) lambda[ NCOL(x)+1 ] <- ifelse( is.null(z), sigma, log(sigma) ) if( is.null(z) ){ names( lambda ) <- c( dimnames( as.matrix(x) )[[ 2L ]], "sigma" ) attr( lambda, "lower" ) <- c( rep( -Inf, NCOL(x) ), eps ) } else names( lambda ) <- c( paste("mean", dimnames( as.matrix(x) )[[ 2L ]], sep="."), paste("dispersion", dimnames( as.matrix(z) )[[ 2L ]], sep=".") ) lambda } ans$npar <- function(x, z) ifelse( !is.null(z), NCOL(x)+NCOL(z), NCOL(x)+1 ) ans$dp <- function(y, x, z, offset, lambda) { nb <- length(lambda) mu <- fm$linkinv( x %*% lambda[ 1:NCOL(x) ] + offset$mean ) if( is.null(z) ) sd <- lambda[ nb ] else sd <- exp( z %*% lambda[ ( NCOL(x)+1 ):nb ] + offset$precision ) cbind( dnorm( y , mu , sd ) , pnorm( y , mu , sd ) ) } ans$q <- function(p, x, z, offset, lambda) { nb <- length(lambda) mu <- fm$linkinv( x %*% lambda[ 1:NCOL(x) ] + offset$mean ) if( is.null(z) ) sd <- lambda[ nb ] else sd <- exp( z %*% lambda[ ( NCOL(x)+1 ):nb ] + offset$precision ) qnorm( p , mu , sd ) } ans$fitted.val <- function(x, z, offset, lambda){ fm$linkinv( x %*% lambda[ 1:NCOL(x) ] + offset$mean ) } ans$type <- "numeric" class(ans) <- c( "marginal.gcmr") ans } binomial.marg <- function(link = "logit") { fm <- binomial( substitute( link ) ) ans <- list() sizes <- 1 ans$start <- function(y, x, z, offset) { if(NCOL(y)==1) { y <- as.factor(y) y <- y!=levels(y)[1L] y <- cbind(y, 1-y) } sizes <<- y[,1]+y[,2] lambda <- coef( glm.fit( x, y, offset=offset$mean, family=fm ) ) names(lambda) <- dimnames( as.matrix(x) )[[2L]] lambda } ans$npar <- function(x, z) NCOL(x) ans$dp <- function(y, x, z, offset, lambda) { if(NCOL(y)==1){ y <- as.factor(y) y <- y!=levels(y)[1L] y <- cbind(y, 1-y) } mu <- fm$linkinv( x %*% lambda + offset$mean ) cbind(dbinom( y[,1], sizes, mu ) , pbinom( y[,1], sizes, mu ) ) } ans$q <- function(p, x, z, offset, lambda) { mu <- fm$linkinv( x %*% lambda + offset$mean ) q <- qbinom( p, sizes, mu ) cbind( q, sizes-q ) } ans$fitted.val <- function(x, z, offset, lambda){ fm$linkinv( x %*% lambda + offset$mean ) } ans$type <- "integer" class(ans) <- c( "marginal.gcmr") ans } poisson.marg <- function(link = "log") { fm <- poisson( substitute( link ) ) ans <- list() ans$start <- function(y, x, z, offset) { lambda <- coef( glm.fit( x , y, offset=offset$mean, family=fm ) ) names(lambda) <- dimnames( as.matrix(x) )[[ 2L ]] lambda } ans$npar <- function(x, z) NCOL(x) ans$dp <- function(y, x, z, offset, lambda) { mu <- fm$linkinv( x %*% lambda + offset$mean ) cbind( dpois( y , mu ) , ppois( y , mu ) ) } ans$q <- function(p, x, z, offset, lambda) { mu <- fm$linkinv( x %*% lambda + offset$mean ) qpois( p , mu ) } ans$fitted.val <- function(x, z, offset, lambda){ fm$linkinv( x %*% lambda + offset$mean ) } ans$type <- "integer" class(ans) <- c( "marginal.gcmr") ans } negbin.marg <- function(link = "log" ) { fm <- poisson( substitute( link ) ) ans <- list() ans$start <- function(y, x, z, offset) { if( !is.null(z) ) offset <- list( as.vector(offset$mean), as.vector(offset$precision) ) eps <- sqrt(.Machine$double.eps) m <- glm.fit( x , y, offset=offset$mean, family=fm ) mu <- fitted(m) kappa <- max( 10*eps , mean( ( (y-mu)^2-mu )/mu^2 ) ) lambda <- c( coef(m), rep.int( 0, NCOL(z) ) ) lambda[ NCOL(x)+1 ] <- ifelse( is.null(z), kappa, log(kappa) ) if( is.null(z) ){ names( lambda ) <- c( dimnames( as.matrix(x) )[[ 2L ]], "dispersion" ) attr( lambda, "lower" ) <- c( rep(-Inf, NCOL(x) ), eps ) } else names( lambda ) <- c( paste("mean", dimnames( as.matrix(x) )[[ 2L ]], sep="."), paste("dispersion", dimnames( as.matrix(z) )[[ 2L ]], sep=".") ) lambda } ans$npar <- function(x, z) ifelse( !is.null(z), NCOL(x)+NCOL(z), NCOL(x)+1 ) ans$dp <- function(y, x, z, offset, lambda) { nb <- length(lambda) mu <- fm$linkinv( x %*% lambda[ 1:NCOL(x) ] + offset$mean ) if( is.null(z) ) size <- 1 / lambda[ nb ] else size <- 1 / exp( z %*% lambda[ ( NCOL(x)+1 ):nb ] + offset$precision ) cbind( dnbinom( y, mu=mu, size=size) , pnbinom( y, mu=mu, size=size) ) } ans$q <- function(p, x, z, offset, lambda) { nb <- length(lambda) mu <- fm$linkinv( x %*% lambda[ 1:NCOL(x) ] + offset$mean ) if( is.null(z) ) size <- 1 / lambda[ nb ] else size <- 1 / exp( z %*% lambda[ ( NCOL(x)+1 ):nb ] + offset$precision ) qnbinom( p, mu=mu, size=size) } ans$fitted.val <- function(x, z, offset, lambda){ fm$linkinv( x %*% lambda[ 1:NCOL(x) ] + offset$mean ) } ans$type <- "integer" class(ans) <- c( "marginal.gcmr") ans } gs.marg <- gaussian.marg bn.marg <- binomial.marg ps.marg <- poisson.marg nb.marg <- negbin.marg weibull.marg <- function(link = "log"){ fm <- Gamma( substitute( link ) ) ans <- list() ans$start <- function(y, x, z, offset) { if( !is.null(z) ) offset <- list( as.vector(offset$mean), as.vector(offset$precision) ) eps <- sqrt(.Machine$double.eps) m <- glm.fit(x , y, offset=offset$mean, family=fm) shape <- max( 10*eps, 1.2/sqrt( mean( log( y/fitted(m) )^2) ) ) lambda <- c( coef(m), rep.int( 0, NCOL(z) ) ) lambda[ NCOL(x)+1 ] <- ifelse( is.null(z), shape, log(shape) ) if( is.null(z) ){ names( lambda ) <- c( dimnames( as.matrix(x) )[[ 2L ]], "shape" ) attr( lambda, "lower" ) <- c( rep( -Inf, NCOL(x) ), eps ) } else names( lambda ) <- c( paste("scale", dimnames( as.matrix(x) )[[ 2L ]], sep="."), paste("shape", dimnames( as.matrix(z) )[[ 2L ]], sep=".") ) lambda } ans$npar <- function(x, z) ifelse( !is.null(z), NCOL(x)+NCOL(z), NCOL(x)+1 ) ans$dp <- function(y, x, z, offset, lambda){ nb <- length(lambda) scale <- fm$linkinv( x %*% lambda[ 1:NCOL(x) ] + offset$mean ) if( is.null(z) ) shape <- lambda[ nb ] else shape <- exp( z %*% lambda[ ( NCOL(x)+1 ):nb ] + offset$precision ) cbind(dweibull(y, shape=shape, scale=scale) , pweibull(y, shape=shape, scale=scale) ) } ans$q <- function(p, x, z, offset, lambda){ nb <- length(lambda) scale <- fm$linkinv( x %*% lambda[ 1:NCOL(x) ] + offset$mean ) if( is.null(z) ) shape <- lambda[ nb ] else shape <- exp( z %*% lambda[ ( NCOL(x)+1 ):nb ] + offset$precision ) qweibull(p, shape=shape, scale=scale) } ans$fitted.val <- function(x, z, offset, lambda){ fm$linkinv( x %*% lambda[ 1:NCOL(x) ] + offset$mean ) } ans$type <- "numeric" class(ans) <- c( "marginal.gcmr") ans } Gamma.marg <- function(link = "inverse"){ fm <- Gamma( substitute( link ) ) ans <- list() ans$start <- function(y, x, z, offset) { if( !is.null(z) ) offset <- list( as.vector(offset$mean), as.vector(offset$precision) ) eps <- sqrt(.Machine$double.eps) m <- glm.fit(x , y, offset=offset$mean, family=fm) disp <- sum( residuals(m, "pearson")^2 )/( NROW(y)-NCOL(x) ) shape <- max( 10*eps, 1/disp ) lambda <- c( coef(m), rep.int( 0, NCOL(z) ) ) lambda[ NCOL(x)+1 ] <- ifelse( is.null(z), shape, log(shape) ) if( is.null(z) ){ names( lambda ) <- c( dimnames( as.matrix(x) )[[ 2L ]], "shape" ) attr( lambda, "lower" ) <- c( rep( -Inf, NCOL(x) ), eps ) } else names( lambda ) <- c( paste("mean", dimnames( as.matrix(x) )[[ 2L ]], sep="."), paste("shape", dimnames( as.matrix(z) )[[ 2L ]], sep=".") ) lambda } ans$npar <- function(x, z) ifelse( !is.null(z), NCOL(x)+NCOL(z), NCOL(x)+1 ) ans$dp <- function(y, x, z, offset, lambda){ nb <- length(lambda) mu <- fm$linkinv( x %*% lambda[ 1:NCOL(x) ] + offset$mean ) if( is.null(z) ) shape <- lambda[ nb ] else shape <- exp( z %*% lambda[ ( NCOL(x)+1 ):nb ] + offset$precision ) cbind(dgamma(y, shape=shape, rate=shape/mu) , pgamma(y, shape=shape, rate=shape/mu) ) } ans$q <- function(p, x, z, offset, lambda){ nb <- length(lambda) mu <- fm$linkinv( x %*% lambda[ 1:NCOL(x) ] + offset$mean ) if( is.null(z) ) shape <- lambda[ nb ] else shape <- exp( z %*% lambda[ ( NCOL(x)+1 ):nb ] + offset$precision ) qgamma(p, shape=shape, rate=shape/mu) } ans$fitted.val <- function(x, z, offset, lambda){ fm$linkinv( x %*% lambda[ 1:NCOL(x) ] + offset$mean ) } ans$type <- "numeric" class(ans) <- c( "marginal.gcmr") ans } beta.marg <- function(link = "logit"){ fm <- binomial( substitute( link ) ) ans <- list() ans$start <- function(y, x, z, offset) { if( !is.null(z) ) offset <- list( as.vector(offset$mean), as.vector(offset$precision) ) m <- betareg.fit(x=x, y=as.vector(y), z=z, offset=offset, link=link ) lambda <- unlist( coef(m) ) if( is.null(z) ){ pos <- NCOL(x)+1 lambda[pos] <- exp( lambda[pos] ) names(lambda)[pos] <- "dispersion" attr(lambda, "lower") <- c( rep( -Inf, NCOL(x) ), sqrt(.Machine$double.eps) ) } lambda } ans$npar <- function(x, z) ifelse(!is.null(z), NCOL(x)+NCOL(z), NCOL(x)+1) ans$dp <- function(y, x, z, offset, lambda) { nb <- length(lambda) mu <- fm$linkinv( x %*% lambda[ 1:NCOL(x) ] + offset$mean ) if( is.null(z) ) phi <- lambda[ nb ] else phi <- exp( z %*% lambda[ ( NCOL(x)+1 ):nb ] + offset$precision ) shape1 <- phi*mu shape2 <- phi*(1-mu) cbind( dbeta(as.vector(y), shape1, shape2), pbeta(as.vector(y), shape1, shape2) ) } ans$q <- function(p, x, z, offset, lambda) { nb <- length(lambda) mu <- fm$linkinv( x %*% lambda[1:NCOL(x)] + offset$mean ) if( is.null(z) ) phi <- lambda[ nb ] else phi <- exp( z %*% lambda[ ( NCOL(x)+1 ):nb ] + offset$precision ) shape1 <- phi*mu shape2 <- phi*(1-mu) qbeta(p, shape1, shape2) } ans$fitted.val <- function(x, z, offset, lambda){ fm$linkinv( x %*% lambda[ 1:NCOL(x) ] + offset$mean ) } ans$type <- "numeric" class(ans) <- c("marginal.gcmr") ans }
"_PACKAGE" NULL NULL matrixpls <- function(S, model, W.model = NULL, weightFun = weightFun.pls, parameterEstim = parameterEstim.separate, weightSign = NULL, ..., validateInput = TRUE, standardize = TRUE) { nativeModel <- parseModelToNativeFormat(model) lvNames <- colnames(nativeModel$inner) if(any(duplicated(lvNames))) stop(paste("Each composite must have a unique name. The names contain duplicates:", lvNames)) if(! identical(lvNames, colnames(nativeModel$reflective)) || ! identical(lvNames,rownames(nativeModel$formative))){ print(nativeModel) stop("Names of composites are inconsistent between inner, reflective, and formative models.") } if(! identical(rownames(nativeModel$reflective), colnames(nativeModel$formative))){ print(nativeModel) stop("Names of observed variables are inconsistent between reflective and formative models.") } if(! identical(colnames(S), rownames(S))) stop("S must have identical row and column names.") if(! matrixcalc::is.symmetric.matrix(S)) stop("S must be symmetric to be a valid covariance matrix.") if(! matrixcalc::is.positive.semi.definite(S)) stop("S must be positive semi-definite to be a valid covariance matrix.") if(! identical(colnames(S), colnames(nativeModel$formative))){ d <- setdiff(colnames(nativeModel$formative), colnames(S)) if(length(d)>0) stop(paste("Variable(s)",paste(d,collapse=", "),"are not included in S.")) S <- S[colnames(nativeModel$formative), colnames(nativeModel$formative)] } if(is.null(W.model)) W.model <- defaultWeightModelWithModel(nativeModel) if(! identical(colnames(W.model), colnames(S))) stop("Column names of W.model do not match the variable names") if(! identical(rownames(W.model), lvNames)) stop("Row names of W.model do not match the latent variable names") if(standardize){ S <- stats::cov2cor(S) S[lower.tri(S)] <- t(S)[lower.tri(S)] } W <- weightFun(S, W.model = W.model, model = nativeModel, parameterEstim = parameterEstim.separate, ..., validateInput = validateInput, standardize = standardize) if(!is.null(weightSign)) W <- weightSign(W, S) estimates <- parameterEstim(S, model, W, ...) indices <- W.model!=0 WVect <- W[indices] names(WVect) <- paste(rownames(nativeModel$formative)[row(W)[indices]],"=+",colnames(nativeModel$formative)[col(W)[indices]], sep="") ret <- c(estimates,WVect) allAttributes <- c(attributes(W),attributes(estimates)) for(a in setdiff(names(allAttributes), c("dim", "dimnames", "class", "names"))){ attr(ret,a) <- allAttributes[[a]] attr(W,a) <- NULL } class(W) <- "numeric" attr(ret,"W") <- W attr(ret,"model") <- nativeModel attr(ret,"call") <- match.call() class(ret) <-("matrixpls") return(ret) } print.matrixpls <- function(x, ...){ cat("\n matrixpls parameter estimates\n") indices <- ! grepl("=+", names(x), fixed=TRUE) toPrint <- x[indices] estimates <- as.matrix(toPrint) colnames(estimates)[1] <- "Est." se <- attr(x,"se") boot.out <- attr(x,"boot.out") if(! is.null(boot.out)){ estimates <- cbind(estimates, apply(boot.out$t[,indices],2,stats::sd)) colnames(estimates)[2] <- "SE" } else if(! is.null(se)){ estimates <- cbind(estimates,se) colnames(estimates)[2] <- "SE" } print(estimates, ...) if(! is.null(boot.out)){ cat("\n Standard errors based on",boot.out$R,"bootstrap replications\n") } W <- attr(x,"W") attr(W,"iterations") <- attr(x,"iterations") attr(W,"converged") <- attr(x,"converged") class(W) <- "matrixplsweights" print(W, ...) } summary.matrixpls <- function(object, ...){ ret <- list(estimates = object, effects = effects(object), r2 = r2(object), residuals = stats::residuals(object), gof = gof(object), cr = cr(object), ave = ave(object), htmt = htmt(object), cei = cei(object)) class(ret) <-("matrixplssummary") return(ret) } print.matrixplssummary <- function(x, ...){ for(element in x){ print(element, ...) } }
expected <- eval(parse(text="FALSE")); test(id=0, code={ argv <- eval(parse(text="list(structure(list(weight = c(4.17, 5.58), group = structure(c(1L, 1L), .Label = c(\"Ctl\", \"Trt\"), class = \"factor\")), .Names = c(\"weight\", \"group\"), row.names = 1:2, class = \"data.frame\"))")); do.call(`is.array`, argv); }, o=expected);
quantileForecast.fitMOScsg0 <- function(fit, ensembleData, quantiles = 0.5, dates = NULL, ...) { M <- matchEnsembleMembers(fit,ensembleData) nForecasts <- ensembleSize(ensembleData) if (!all(M == 1:nForecasts)) ensembleData <- ensembleData[,M] M <- apply(ensembleForecasts(ensembleData), 1, function(z) all(is.na(z))) ensembleData <- ensembleData[!M,] nObs <- nrow(ensembleData) if (!is.null(dates)) warning("dates ignored") Quants <- matrix(NA, nObs, length(quantiles)) dimnames(Quants) <- list(ensembleObsLabels(ensembleData),as.character(quantiles)) Mu <- rep(NA,nObs) Sig.sq <- rep(NA,nObs) ensembleData <- ensembleForecasts(ensembleData) x <- c(fit$a,fit$B) A <- cbind(rep(1,nObs),ensembleData) Q <- fit$q S.sq <- apply(ensembleData,1,mean) Mu <- A%*%x Sig.sq <- rep(fit$c,nObs) + rep(fit$d,nObs)*S.sq Shp <- Mu^2/Sig.sq Scl <- Sig.sq/Mu for (i in 1:length(quantiles)) {zero.prec <- pgamma(Q,shape=Shp,scale=Scl)>=quantiles[i] Quants[is.na(zero.prec),i]<-NA Quants[(!is.na(zero.prec))&zero.prec,i]<-0 Quants[(!is.na(zero.prec))&(!zero.prec),i] <- qgamma(quantiles[i], shape=Shp[(!is.na(zero.prec))&(!zero.prec)], scale=Scl[(!is.na(zero.prec))&(!zero.prec)])-fit$q} Quants }
computeSpacingPredictors <- function(data, KCs) { if (!("CF..reltime." %in% colnames(data))) { data$CF..reltime. <- practiceTime(data) } if (!("CF..Time." %in% colnames(data))) { data$CF..Time. <- data$CF..reltime. } for (i in KCs) { data$index <- paste(eval(parse(text = paste("data$", i, sep = ""))), data$Anon.Student.Id, sep = "") eval(parse(text = paste("data$", i, "spacing <- componentspacing(data,data$index,data$CF..Time.)", sep = ""))) eval(parse(text = paste("data$", i, "relspacing <- componentspacing(data,data$index,data$CF..reltime.)", sep = ""))) eval(parse(text = paste("data$", i, "prev <- componentprev(data,data$index,data$CF..ansbin.)", sep = ""))) data$index <- paste(eval(parse(text = paste("data$", i, sep = ""))), data$Anon.Student.Id, sep = "") eval(parse(text = paste("data$", i, "meanspacing <- meanspacingf(data,data$index,data$", i, "spacing)", sep = ""))) eval(parse(text = paste("data$", i, "relmeanspacing <- meanspacingf(data,data$index,data$", i, "spacing)", sep = ""))) data$index <- paste(eval(parse(text = paste("data$", i, sep = ""))), data$Anon.Student.Id, sep = "") eval(parse(text = paste("data$", i, "spacinglagged <- laggedspacingf(data,data$index,data$", i, "spacing)", sep = ""))) } return(data) } LKT <- function(data, components, features, fixedpars = NA, seedpars = NA, covariates = NA, dualfit = FALSE, interc = FALSE, cv=FALSE, elastic = FALSE, verbose = TRUE, epsilon = 1e-4, cost = 512, type = 0, maketimes = FALSE, bias = 0) { if (maketimes) { if (!("CF..reltime." %in% colnames(data))) { data$CF..reltime. <- practiceTime(data) } if (!("CF..Time." %in% colnames(data))) { data$CF..Time. <- data$CF..reltime. } } if (!("Outcome" %in% colnames(data))) { data$Outcome <- ifelse(data$CF..ansbin. == 1, "CORRECT", "INCORRECT") } if (!("CF..ansbin." %in% colnames(data))) { data$CF..ansbin. <- ifelse(data$Outcome == "CORRECT", 1, 0) } equation <- "CF..ansbin.~ " e <- new.env() e$data <- data e$fixedpars <- fixedpars e$seedpars <- seedpars e$counter <- 0 e$flag <- FALSE modelfun <- function(seedparameters) { k <- 0 optimparcount <- 1 fixedparcount <- 1 m <- 1 if (interc == TRUE) { eq <- "1" } else { eq <- "0" } e$counter <- e$counter + 1 for (i in features) { k <- k + 1 if (gsub("[$@]", "", i) %in% c( "powafm", "recency", "recencysuc", "recencyfail", "errordec", "propdec", "propdec2", "logitdec", "base", "expdecafm", "expdecsuc", "expdecfail", "dashafm", "dashsuc", "dashfail", "base2", "base4", "basesuc", "basefail", "logit", "base2suc", "base2fail", "ppe", "base5suc", "base5fail", "clogitdec", "crecency" )) { if (is.na(e$fixedpars[m])) { para <- seedparameters[optimparcount] e$flag <- TRUE optimparcount <- optimparcount + 1 } else { if (e$fixedpars[m] >= 1 & e$fixedpars[m] %% 1 == 0) { para <- seedparameters[e$fixedpars[m]] } else { para <- e$fixedpars[m] } } m <- m + 1 } if (gsub("[$]", "", i) %in% c("base2", "base4", "base2suc", "base2fail", "ppe", "base5suc", "base5fail")) { if (is.na(e$fixedpars[m])) { parb <- seedparameters[optimparcount] optimparcount <- optimparcount + 1 } else { if (e$fixedpars[m] >= 1 & e$fixedpars[m] %% 1 == 0) { parb <- seedparameters[e$fixedpars[m]] } else { parb <- e$fixedpars[m] } } m <- m + 1 } if (gsub("[$]", "", i) %in% c("base4", "ppe", "base5suc", "base5fail")) { if (is.na(e$fixedpars[m])) { parc <- seedparameters[optimparcount] optimparcount <- optimparcount + 1 } else { if (e$fixedpars[m] >= 1 & e$fixedpars[m] %% 1 == 0) { parc <- seedparameters[e$fixedpars[m]] } else { parc <- e$fixedpars[m] } } m <- m + 1 } if (gsub("[$]", "", i) %in% c("base4", "ppe", "base5suc", "base5fail")) { if (is.na(e$fixedpars[m])) { pard <- seedparameters[optimparcount] optimparcount <- optimparcount + 1 } else { if (e$fixedpars[m] >= 1 & e$fixedpars[m] %% 1 == 0) { pard <- seedparameters[e$fixedpars[m]] } else { pard <- e$fixedpars[m] } } m <- m + 1 } if (gsub("[$]", "", i) %in% c("base5suc", "base5fail")) { if (is.na(e$fixedpars[m])) { pare <- seedparameters[optimparcount] optimparcount <- optimparcount + 1 } else { if (e$fixedpars[m] >= 1 & e$fixedpars[m] %% 1 == 0) { pare <- seedparameters[e$fixedpars[m]] } else { pare <- e$fixedpars[m] } } m <- m + 1 } if (e$flag == TRUE | e$counter < 2) { if (length(grep("%", components[k]))) { KCs <- strsplit(components[k], "%") e$data$index <- paste(eval(parse(text = paste("e$data$", KCs[[1]][1], sep = ""))), e$data$Anon.Student.Id, sep = "") e$data$indexcomp <- paste(eval(parse(text = paste("e$data$", KCs[[1]][1], sep = ""))), sep = "") e$data$cor <- as.numeric(paste(eval(parse(text = paste("countOutcomeGen(e$data,e$data$index,\"CORRECT\",e$data$", KCs[[1]][2], ",\"", KCs[[1]][3], "\")", sep = ""))))) e$data$icor <- as.numeric(paste(eval(parse(text = paste("countOutcomeGen(e$data,e$data$index,\"INCORRECT\",e$data$", KCs[[1]][2], ",\"", KCs[[1]][3], "\")", sep = ""))))) } else if (length(grep("\\?", components[k]))) { KCs <- strsplit(components[k], "\\?") e$data$indexcomp <- NULL e$data$cor <- as.numeric(paste(eval(parse(text = paste("countOutcomeOther(e$data,e$data$Anon.Student.Id,\"CORRECT\",e$data$", KCs[[1]][3], ",\"", KCs[[1]][4], "\",e$data$", KCs[[1]][1], ",\"", KCs[[1]][2], "\")", sep = ""))))) e$data$icor <- as.numeric(paste(eval(parse(text = paste("countOutcomeOther(e$data,e$data$Anon.Student.Id,\"INCORRECT\",e$data$", KCs[[1]][3], ",\"", KCs[[1]][4], "\",e$data$", KCs[[1]][1], ",\"", KCs[[1]][2], "\")", sep = ""))))) } else if (length(grep("__", components[k]))) { if (!(i %in% c("clogitdec"))) { e$data$cor <- countOutcome(e$data, e$data$index, "CORRECT") e$data$icor <- countOutcome(e$data, e$data$index, "INCORRECT") } } else { Anon.Student.Id<-index<-indexcomp<-NULL vec <- eval(parse(text = paste0("e$data$", components[k]))) e$data[, index := do.call(paste0, list(vec, Anon.Student.Id))] e$data[, indexcomp := vec] if (!(i %in% c("numer", "intercept"))) { e$data$cor <- countOutcome(e$data, e$data$index, "CORRECT") e$data$icor <- countOutcome(e$data, e$data$index, "INCORRECT") } } } if (e$flag == TRUE | e$counter < 2) { e$flag <- FALSE if (right(i, 1) == "@") { eval(parse(text = paste("e$data$", components[k], "<-computefeatures(e$data,i,para,parb,e$data$index,e$data$indexcomp, parc,pard,pare,components[k])", sep = "" ))) } else { eval(parse(text = paste("e$data$", gsub("\\$", "", i), gsub("[%]", "", components[k]), "<-computefeatures(e$data,i,para,parb,e$data$index,e$data$indexcomp, parc,pard,pare,components[k])", sep = ""))) } } if (verbose) { cat(paste( i, components[k], if (exists("para")) { para }, if (exists("parb")) { parb }, if (exists("parc")) { parc }, if (exists("pard")) { pard }, if (exists("pare")) { pare }, "\n" )) } if (exists("para")) { rm(para) } if (exists("parb")) { rm(parb) } if (exists("parc")) { rm(parc) } if (exists("pard")) { rm(pard) } if (exists("pare")) { rm(pare) } if (right(i, 1) == "$") { cleanfeat <- gsub("\\$", "", i) if (is.na(covariates[k])) { eval(parse(text = paste("eq<-paste(cleanfeat,components[k],\":e$data$\",components[k], \"+\",eq,sep=\"\")"))) } else { eval(parse(text = paste("eq<-paste(cleanfeat,components[k],\":e$data$\",components[k] ,\":\",covariates[k] ,\"+\",eq,sep=\"\")"))) } } else if (right(i, 1) == "@") { eval(parse(text = paste("eq<-paste(\"(1|\",components[k],\")+\",eq,sep=\"\")"))) } else { if (is.na(covariates[k])) { eval(parse(text = paste("eq<-paste(i,gsub('[%]','',components[k]),\"+\",eq,sep=\"\")"))) } else { eval(parse(text = paste("eq<-paste(i,gsub('[%]','',components[k]),\":\",covariates[k],\"+\",eq,sep=\"\")"))) } } } if (verbose) { cat(paste(eq, "\n")) } e$form <- as.formula(paste(equation, eq, sep = "")) if (any(grep("[@]", features)) & dualfit == FALSE) { temp <- glmer(e$form, data = e$data, family = binomial(logit)) fitstat <- logLik(temp) } else { if (elastic == "glmnet") { temp <- glmnet(e$form, data = e$data, family = "binomial") plot(temp, xvar = "lambda", label = TRUE) print(temp) } else if (elastic == "cv.glmnet") { temp <- cv.glmnet(e$form, data = e$data, family = "binomial") plot(temp) print(temp) print(coef(temp, s = "lambda.min")) } else if (elastic == "cva.glmnet") { temp <- cva.glmnet(e$form, data = e$data, family = "binomial") plot(temp) print(temp) } else { predictset <- sparse.model.matrix(e$form, e$data) predictset.csc <- new("matrix.csc", ra = predictset@x, ja = predictset@i + 1L, ia = predictset@p + 1L, dimension = predictset@Dim ) predictset.csr <- as.matrix.csr(predictset.csc) predictset2 <- predictset.csr temp <- LiblineaR(predictset2, e$data$CF..ansbin., bias = bias, cost = cost, epsilon = epsilon, type = type ) if(temp$ClassNames[1]==0){temp$W=temp$W*(-1)} modelvs <- data.frame(temp$W) colnames(modelvs) <- colnames(predictset) e$modelvs <- t(modelvs) colnames(e$modelvs) <- "coefficient" e$data$pred <- pmin(pmax(predict(temp, predictset2, proba = TRUE)$probabilities[, 1],.00001),.99999) if(cv==TRUE){ cv_rmse<-rep(0,length(unique(e$data$fold))) cv_mcfad<-rep(0,length(unique(e$data$fold))) for(i in 1:length(unique(e$data$fold))){ idx1 = which(e$data$fold!=i) e1_tmp = e$data[idx1,] predictsetf1=slice(t(predictset),idx1) predictsetf1=t(predictsetf1) predictsetf1.csc <- new("matrix.csc", ra = predictsetf1@x, ja = predictsetf1@i + 1L, ia = predictsetf1@p + 1L, dimension = predictsetf1@Dim) predictsetf1.csr <- as.matrix.csr(predictsetf1.csc) idx2 = which(e$data$fold==i) e2_tmp = e$data[idx2,] predictsetf2=slice(t(predictset),idx2) predictsetf2=t(predictsetf2) predictsetf2.csc <- new("matrix.csc", ra = predictsetf2@x, ja = predictsetf2@i + 1L, ia = predictsetf2@p + 1L, dimension = predictsetf2@Dim) predictsetf2.csr <- as.matrix.csr(predictsetf2.csc) tempTr<-LiblineaR(predictsetf1.csr,e1_tmp$CF..ansbin.,bias=0, cost=512,epsilon=.0001,type=0) if(tempTr$ClassNames[1]==0){tempTr$W=tempTr$W*(-1)} pred3<-predict(tempTr,predictsetf2.csr,proba=TRUE)$probabilities[,1] e1_ansbin <-e1_tmp$CF..ansbin. e2_ansbin <-e2_tmp$CF..ansbin. cv_fitstat<- sum(log(ifelse(e2_ansbin==1,pred3,1-pred3))) cv_nullmodel<-glm(as.formula(paste("CF..ansbin.~ 1",sep="")),data=e2_tmp,family=binomial(logit)) cv_nullfit<-logLik(cv_nullmodel) cv_mcfad[i]= round(1-cv_fitstat/cv_nullfit,6) cv_rmse[i] = sqrt(mean((e2_tmp$CF..ansbin.-pred3)^2)) } e$cv_res = data.frame("rmse" = cv_rmse,"mcfad" = cv_mcfad) }else{e$cv_res = data.frame("rmse" = rep(NA,5),"mcfad" = rep(NA,5))} fitstat <- sum(log(ifelse(e$data$CF..ansbin. == 1, e$data$pred, 1 - e$data$pred))) } } if (dualfit == TRUE && elastic == FALSE) { rt.pred <- exp(-qlogis(e$data$pred[which(e$data$CF..ansbin. == 1)])) outVals <- boxplot(e$data$Duration..sec., plot = FALSE)$out outVals <- which(e$data$Duration..sec. %in% outVals) e$data$Duration..sec. <- as.numeric(e$data$Duration..sec.) if (length(outVals) > 0) { e$data$Duration..sec.[outVals] <- quantile(e$data$Duration..sec., .95) } the.rt <- e$data$Duration..sec.[which(e$data$CF..ansbin. == 1)] e$lm.rt <- lm(the.rt ~ as.numeric(rt.pred)) fitstat2 <- cor(the.rt, predict(e$lm.rt, type = "response"))^2 if (verbose) { cat(paste("R2 (cor squared) latency: ", fitstat2, "\n", sep = "")) } } e$temp <- temp if (elastic == FALSE) { e$nullmodel <- glm(as.formula(paste("CF..ansbin.~ 1", sep = "")), data = e$data, family = binomial(logit)) e$nullfit <- logLik(e$nullmodel) e$loglike <- fitstat e$mcfad <- round(1 - fitstat[1] / e$nullfit[1], 6) if (verbose) { cat(paste("McFadden's R2 logistic:", e$mcfad, "\n")) cat(paste("LogLike logistic:", round(fitstat, 8), "\n")) } if (length(seedparameters) > 0 & verbose) { cat(paste("step par values =")) cat(seedparameters, sep = ",") cat(paste("\n\n")) } -fitstat[1] } else { NULL } } parlength <- sum("powafm" == gsub("[$]", "", features)) + sum("recency" == gsub("[$]", "", features)) + sum("crecency" == gsub("[$]", "", features)) + sum("recencysuc" == gsub("[$]", "", features)) + sum("recencyfail" == gsub("[$]", "", features)) + sum("logit" == gsub("[$]", "", features)) + sum("errordec" == gsub("[$]", "", features)) + sum("propdec" == gsub("[$]", "", features)) + sum("propdec2" == gsub("[$]", "", features)) + sum("logitdec" == gsub("[$]", "", features)) + sum("clogitdec" == gsub("[$]", "", features)) + sum("base" == gsub("[$]", "", features)) + sum("expdecafm" == gsub("[$]", "", features)) + sum("expdecsuc" == gsub("[$]", "", features)) + sum("expdecfail" == gsub("[$]", "", features)) + sum("base2" == gsub("[$]", "", features)) * 2 + sum("base4" == gsub("[$]", "", features)) * 4 + sum("ppe" == gsub("[$]", "", features)) * 4 + sum("basefail" == gsub("[$]", "", features)) + sum("basesuc" == gsub("[$]", "", features)) + sum("base2suc" == gsub("[$]", "", features)) * 2 + sum("base2fail" == gsub("[$]", "", features)) * 2 + sum("dashafm" == gsub("[$]", "", features)) + sum("dashsuc" == gsub("[$]", "", features)) + sum("dashfail" == gsub("[$]", "", features)) + sum("base5suc" == gsub("[$]", "", features)) * 5 + sum("base5fail" == gsub("[$]", "", features)) * 5 - sum(!is.na(e$fixedpars)) seeds <- e$seedpars[is.na(e$fixedpars)] seeds[is.na(seeds)] <- .5 if (parlength > 0) { optimizedpars <- optim(seeds, modelfun, method = c("L-BFGS-B"), lower = 0.00001, upper = .99999, control = list(maxit = 100)) } else { modelfun(numeric(0)) } if (dualfit == TRUE && elastic == FALSE) { failureLatency <- mean(e$data$Duration..sec.[which(e$data$CF..ansbin. == 0)]) Scalar <- coef(e$lm.rt)[2] Intercept <- coef(e$lm.rt)[1] if (verbose) { cat(paste("Failure latency: ", failureLatency, "\n")) cat(paste("Latency Scalar: ", Scalar, "\n", "Latency Intercept: ", Intercept, "\n", sep = "" )) } } results <- list( "model" = e$temp, "coefs" = e$modelvs, "r2" = e$mcfad, "prediction" = if ("pred" %in% colnames(e$data)) { e$data$pred }, "nullmodel" = e$nullmodel, "latencymodel" = if (dualfit == TRUE) { list(e$lm.rt, failureLatency) }, "optimizedpars" = if (exists("optimizedpars")) { optimizedpars }, "studentRMSE" = if ("pred" %in% colnames(e$data)) { aggregate((e$data$pred - e$data$CF..ansbin.)^2, by = list(e$data$Anon.Student.Id), FUN = mean ) }, "newdata" = e$data, "cv_res" = e$cv_res, "loglike" = e$loglike ) results$studentRMSE[,2]<-sqrt(results$studentRMSE[,2]) return(results) } computefeatures <- function(data, feat, par1, par2, index, index2, par3, par4, par5, fcomp) { mn<-Anon.Student.Id<-temptemp<-icor<-CF..ansbin.<-NULL feat <- gsub("[$@]", "", feat) if (feat == "intercept") { return(as.character(index2)) } if (feat == "numer") { temp <- eval(parse(text = paste("data$", fcomp, sep = ""))) return(temp) } if (feat == "clineafm") { data$temp <- 0 data$div <- 0 for (m in strsplit(fcomp, "__")[[1]]) { data[, mn := do.call(paste0, list(eval(parse(text = paste("data$", m, sep = "")))))] data[, index := do.call(paste, list(mn, Anon.Student.Id, sep = "-"))] data$cor <- countOutcome(data, data$index, "CORRECT") data$icor <- countOutcome(data, data$index, "INCORRECT") data[, temptemp := cor + icor, by = index] data[, temp := temp + temptemp * as.numeric(mn)] data$div <- data$div + as.numeric(data$mn) } data$temp <- fifelse(data$div != 0, data$temp / data$div, 0) return(data$temp) } if (feat == "clogafm") { data$temp <- 0 data$div <- 0 for (m in strsplit(fcomp, "__")[[1]]) { data[, mn := do.call(paste0, list(eval(parse(text = paste("data$", m, sep = "")))))] data[, index := do.call(paste, list(mn, Anon.Student.Id, sep = "-"))] data$cor <- countOutcome(data, data$index, "CORRECT") data$icor <- countOutcome(data, data$index, "INCORRECT") data[, temptemp := log(1 + icor + cor), by = index] data[, temp := temp + temptemp * as.numeric(mn)] data$div <- data$div + as.numeric(data$mn) } data$temp <- fifelse(data$div != 0, data$temp / data$div, 0) return(data$temp) } if (feat == "lineafm") { return((data$cor + data$icor)) } if (feat == "logafm") { return(log(1 + data$cor + data$icor)) } if (feat == "powafm") { return((data$cor + data$icor)^par1) } if (feat == "crecency") { data$temp <- 0 data$div <- 0 for (m in strsplit(fcomp, "_")[[1]]) { eval(parse(text = paste("data$rec <- data$", m, "spacing", sep = ""))) data$temp <- data$temp + ifelse(data$rec == 0, 0, data$rec^-par1) * eval(parse( text = paste("data$", m, sep = "") )) data$div <- data$div + eval(parse(text = paste("data$", m, sep = ""))) } data$temp <- ifelse(data$div != 0, data$temp / data$div, 0) return(data$temp) } if (feat == "recency") { eval(parse(text = paste("data$rec <- data$", fcomp, "spacing", sep = ""))) return(ifelse(data$rec == 0, 0, data$rec^-par1)) } if (feat == "expdecafm") { return(ave(rep(1, length(data$CF..ansbin.)), index, FUN = function(x) slideexpdec(x, par1))) } if (feat == "base") { data$mintime <- ave(data$CF..Time., index, FUN = min) data$CF..age. <- data$CF..Time. - data$mintime return(log(1 + data$cor + data$icor) * ave(data$CF..age., index, FUN = function(x) baselevel(x, par1))) } if (feat == "base2") { data$mintime <- ave(data$CF..Time., index, FUN = min) data$minreltime <- ave(data$CF..reltime., index, FUN = min) data$CF..trueage. <- data$CF..Time. - data$mintime data$CF..intage. <- data$CF..reltime. - data$minreltime data$CF..age. <- (data$CF..trueage. - data$CF..intage.) * par2 + data$CF..intage. return(log(1 + data$cor + data$icor) * ave(data$CF..age., index, FUN = function(x) baselevel(x, par1))) } if (feat == "base4") { data$mintime <- ave(data$CF..Time., index, FUN = min) data$minreltime <- ave(data$CF..reltime., index, FUN = min) data$CF..trueage. <- data$CF..Time. - data$mintime data$CF..intage. <- data$CF..reltime. - data$minreltime data$CF..age. <- (data$CF..trueage. - data$CF..intage.) * par2 + data$CF..intage. eval(parse(text = paste("data$meanspace <- data$", fcomp, "meanspacing", sep = ""))) eval(parse(text = paste("data$meanspacerel <- data$", fcomp, "relmeanspacing", sep = ""))) data$meanspace2 <- par2 * (data$meanspace - data$meanspacerel) + data$meanspacerel return(ifelse(data$meanspace <= 0, par4 * log(1 + data$cor + data$icor) * ave(data$CF..age., index, FUN = function(x) baselevel(x, par1)), data$meanspace2^par3 * log(1 + data$cor + data$icor) * ave(data$CF..age., index, FUN = function(x) baselevel(x, par1)) )) } if (feat == "ppe") { data$Nc <- (data$cor + data$icor)^par1 data$mintime <- ave(data$CF..Time., index, FUN = min) data$Tn <- data$CF..Time. - data$mintime eval(parse(text = paste("data$space <- data$", fcomp, "spacinglagged", sep = ""))) data$space <- ifelse(data$space == 0, 0, 1 / log(data$space + exp(1))) data$space <- ave(data$space, index, FUN = function(x) cumsum(x)) data$space <- ifelse((data$cor + data$icor) <= 1, 0, data$space / (data$cor + data$icor - 1)) data$tw <- ave(data$Tn, index, FUN = function(x) slideppetw(x, par4)) return(data$Nc * data$tw^-(par2 + par3 * data$space)) } if (feat == "base5suc") { data$mintime <- ave(data$CF..Time., index, FUN = min) data$minreltime <- ave(data$CF..reltime., index, FUN = min) data$CF..trueage. <- data$CF..Time. - data$mintime data$CF..intage. <- data$CF..reltime. - data$minreltime data$CF..age. <- (data$CF..trueage. - data$CF..intage.) * par2 + data$CF..intage. eval(parse(text = paste("data$meanspace <- data$", fcomp, "meanspacing", sep = ""))) eval(parse(text = paste("data$meanspacerel <- data$", fcomp, "relmeanspacing", sep = ""))) data$meanspace2 <- par2 * (data$meanspace - data$meanspacerel) + (data$meanspacerel) return(ifelse(data$meanspace <= 0, par4 * 10 * (log((par5 * 10) + data$cor)) * ave(data$CF..age., index, FUN = function(x) baselevel(x, par1)), data$meanspace2^par3 * (log((par5 * 10) + data$cor)) * ave(data$CF..age., index, FUN = function(x) baselevel(x, par1)) )) } if (feat == "base5fail") { data$mintime <- ave(data$CF..Time., index, FUN = min) data$minreltime <- ave(data$CF..reltime., index, FUN = min) data$CF..trueage. <- data$CF..Time. - data$mintime data$CF..intage. <- data$CF..reltime. - data$minreltime data$CF..age. <- (data$CF..trueage. - data$CF..intage.) * par2 + data$CF..intage. eval(parse(text = paste("data$meanspace <- data$", fcomp, "meanspacing", sep = ""))) eval(parse(text = paste("data$meanspacerel <- data$", fcomp, "relmeanspacing", sep = ""))) data$meanspace2 <- par2 * (data$meanspace - data$meanspacerel) + (data$meanspacerel) return(ifelse(data$meanspace <= 0, par4 * 10 * (log((par5 * 10) + data$icor)) * ave(data$CF..age., index, FUN = function(x) baselevel(x, par1)), data$meanspace2^par3 * (log((par5 * 10) + data$icor)) * ave(data$CF..age., index, FUN = function(x) baselevel(x, par1)) )) } if (feat == "dashafm") { data$x <- ave(data$CF..Time., index, FUN = function(x) countOutcomeDash(x, par1)) return(log(1 + data$x)) } if (feat == "dashsuc") { dataV <- data.frame(data$CF..Time., data$Outcome, index) h <- countOutcomeDashPerf(dataV, "CORRECT", par1) return(log(1 + h)) } if (feat == "diffrelcor1") { return(countRelatedDifficulty1(data, data$index, "CORRECT")) } if (feat == "diffrelcor2") { return(countRelatedDifficulty2(data, data$index, "CORRECT")) } if (feat == "diffcor1") { return(countOutcomeDifficulty1(data, data$index, "CORRECT")) } if (feat == "diffcor2") { return(countOutcomeDifficulty2(data, data$index, "CORRECT")) } if (feat == "diffcorComp") { return(countOutcomeDifficulty1(data, data$index, "CORRECT") - countOutcomeDifficulty2(data, data$index, "CORRECT")) } if (feat == "diffincorComp") { return(countOutcomeDifficulty1(data, data$index, "INCORRECT") - countOutcomeDifficulty2(data, data$index, "INCORRECT")) } if (feat == "diffallComp") { return(countOutcomeDifficultyAll1(data, data$index) - countOutcomeDifficultyAll2(data, data$index)) } if (feat == "diffincor1") { return(countOutcomeDifficulty1(data, data$index, "INCORRECT")) } if (feat == "diffincor2") { return(countOutcomeDifficulty2(data, data$index, "INCORRECT")) } if (feat == "diffall1") { return(countOutcomeDifficultyAll1(data, data$index)) } if (feat == "diffall2") { return(countOutcomeDifficultyAll2(data, data$index)) } if (feat == "logsuc") { return(log(1 + data$cor)) } if (feat == "linesuc") { return(data$cor) } if (feat == "clogsuc") { data$temp <- 0 data$div <- 0 for (m in strsplit(fcomp, "__")[[1]]) { data[, mn := do.call(paste0, list(eval(parse(text = paste("data$", m, sep = "")))))] data[, index := do.call(paste, list(mn, Anon.Student.Id, sep = "-"))] data$cor <- countOutcome(data, data$index, "CORRECT") data[, temptemp := log(1 + cor), by = index] data[, temp := temp + temptemp * as.numeric(mn)] data$div <- data$div + as.numeric(data$mn) } data$temp <- fifelse(data$div != 0, data$temp / data$div, 0) return(data$temp) } if (feat == "clinesuc") { data$temp <- 0 data$div <- 0 for (m in strsplit(fcomp, "__")[[1]]) { data[, mn := do.call(paste0, list(eval(parse(text = paste("data$", m, sep = "")))))] data[, index := do.call(paste, list(mn, Anon.Student.Id, sep = "-"))] data$cor <- countOutcome(data, data$index, "CORRECT") data[, temptemp := cor, by = index] data[, temp := temp + temptemp * as.numeric(mn)] data$div <- data$div + as.numeric(data$mn) } data$temp <- fifelse(data$div != 0, data$temp / data$div, 0) return(data$temp) } if (feat == "logfail") { return(log(1 + data$icor)) } if (feat == "linefail") { return(data$icor) } if (feat == "clogfail") { data$temp <- 0 data$div <- 0 for (m in strsplit(fcomp, "__")[[1]]) { data[, mn := do.call(paste0, list(eval(parse(text = paste("data$", m, sep = "")))))] data[, index := do.call(paste, list(mn, Anon.Student.Id, sep = "-"))] data$icor <- countOutcome(data, data$index, "INCORRECT") data[, temptemp := log(1 + icor), by = index] data[, temp := temp + temptemp * as.numeric(mn)] data$div <- data$div + as.numeric(data$mn) } data$temp <- fifelse(data$div != 0, data$temp / data$div, 0) return(data$temp) } if (feat == "clinefail") { data$temp <- 0 data$div <- 0 for (m in strsplit(fcomp, "__")[[1]]) { data[, mn := do.call(paste0, list(eval(parse(text = paste("data$", m, sep = "")))))] data[, index := do.call(paste, list(mn, Anon.Student.Id, sep = "-"))] data$icor <- countOutcome(data, data$index, "INCORRECT") data[, temptemp := icor, by = index] data[, temp := temp + temptemp * as.numeric(mn)] data$div <- data$div + as.numeric(data$mn) } data$temp <- fifelse(data$div != 0, data$temp / data$div, 0) return(data$temp) } if (feat == "recencyfail") { eval(parse(text = paste("data$rec <- data$", fcomp, "spacing", sep = ""))) eval(parse(text = paste("data$prev <- data$", fcomp, "prev", sep = ""))) return(ifelse(data$rec == 0, 0, (1 - data$prev) * data$rec^-par1)) } if (feat == "recencysuc") { eval(parse(text = paste("data$rec <- data$", fcomp, "spacing", sep = ""))) eval(parse(text = paste("data$prev <- data$", fcomp, "prev", sep = ""))) return(ifelse(data$rec == 0, 0, data$prev * data$rec^-par1)) } if (feat == "expdecsuc") { return(ave(data$CF..ansbin., index, FUN = function(x) slideexpdec(x, par1))) } if (feat == "expdecfail") { return(ave(1 - data$CF..ansbin., index, FUN = function(x) slideexpdec(x, par1))) } if (feat == "basesuc") { data$mintime <- ave(data$CF..Time., index, FUN = min) data$CF..age. <- data$CF..Time. - data$mintime return(log(1 + data$cor) * ave(data$CF..age., index, FUN = function(x) baselevel(x, par1))) } if (feat == "basefail") { data$mintime <- ave(data$CF..Time., index, FUN = min) data$CF..age. <- data$CF..Time. - data$mintime return(log(1 + data$icor) * ave(data$CF..age., index, FUN = function(x) baselevel(x, par1))) } if (feat == "base2fail") { data$mintime <- ave(data$CF..Time., index, FUN = min) data$minreltime <- ave(data$CF..reltime., index, FUN = min) data$CF..trueage. <- data$CF..Time. - data$mintime data$CF..intage. <- data$CF..reltime. - data$minreltime data$CF..age. <- (data$CF..trueage. - data$CF..intage.) * par2 + data$CF..intage. return(log(1 + data$icor) * ave(data$CF..age., index, FUN = function(x) baselevel(x, par1))) } if (feat == "base2suc") { data$mintime <- ave(data$CF..Time., index, FUN = min) data$minreltime <- ave(data$CF..reltime., index, FUN = min) data$CF..trueage. <- data$CF..Time. - data$mintime data$CF..intage. <- data$CF..reltime. - data$minreltime data$CF..age. <- (data$CF..trueage. - data$CF..intage.) * par2 + data$CF..intage. return(log(1 + data$cor) * ave(data$CF..age., index, FUN = function(x) baselevel(x, par1))) } if (feat == "linecomp") { return((data$cor - data$icor)) } if (feat == "logit") { return(log((.1 + par1 * 30 + data$cor) / (.1 + par1 * 30 + data$icor))) } if (feat == "errordec") { return(ave(data$pred_ed - data$CF..ansbin., index, FUN = function(x) slideerrordec(x, par1))) } if (feat == "propdec") { return(ave(data$CF..ansbin., index, FUN = function(x) slidepropdec(x, par1))) } if (feat == "propdec2") { return(ave(data$CF..ansbin., index, FUN = function(x) slidepropdec2(x, par1))) } if (feat == "logitdec") { return(ave(data$CF..ansbin., index, FUN = function(x) slidelogitdec(x, par1))) } if (feat == "clogitdec") { data$temp <- 0 data$div <- 0 for (m in strsplit(fcomp, "__")[[1]]) { data[, mn := do.call(paste0, list(eval(parse(text = paste("data$", m, sep = "")))))] data[, index := do.call(paste, list(mn, Anon.Student.Id, sep = "-"))] data[mn == 1, temptemp := slidelogitdec(CF..ansbin., par1), by = index] data[is.na(temptemp), temptemp := 0] data[, temp := temp + temptemp * as.numeric(mn)] data$div <- data$div + as.numeric(data$mn) } data$temp <- fifelse(data$div != 0, data$temp / data$div, 0) return(data$temp) } if (feat == "prop") { ifelse(is.nan(data$cor / (data$cor + data$icor)), .5, data$cor / (data$cor + data$icor)) } } getFeedDur <- function(data, index) { temp <- rep(0, length(data$CF..ansbin.)) for (i in unique(index)) { le <- length(data$time_to_answer[index == i]) subtemp <- data$time_since_prior_probe[index == i] - data$time_to_answer_inferred[index == i] subtemp <- subtemp[2:(le - 1)] subtemp <- c(subtemp, median(subtemp, na.rm = TRUE)) cutoff <- which(subtemp > 3600) subtemp[cutoff] <- median(subtemp[-cutoff], na.rm = TRUE) temp[index == i] <- subtemp } return(temp) } right <- function(string, char) { substr(string, nchar(string) - (char - 1), nchar(string)) } slice <- function(tSparse, index) { the_slice <- tSparse[,index] attr(the_slice, "mapping") <- attr(the_slice, "mapping") return(the_slice) } countOutcome <- function(data, index, response) { temp <- Outcome <- NULL data[, temp := cumsum(Outcome == response), by = index] data[Outcome == response, temp := temp - 1, by = index] data$temp } countOutcomeDash <- function(times, scalev) { l <- length(times) v1 <- c(rep(0, l)) v2 <- c(rep(0, l)) v1[1] <- 0 v2[1] <- v1[1] + 1 if (l > 1) { spacings <- times[2:l] - times[1:(l - 1)] for (i in 2:l) { v1[i] <- v2[i - 1] * exp(-spacings[i - 1] / (scalev * 86400)) v2[i] <- v1[i] + 1 } } return(v1) } countOutcomeDashPerf <- function(datav, seeking, scalev) { temp <- rep(0, length(datav[, 1])) for (s in unique(datav[, 3])) { l <- length(datav[, 1][datav[, 3] == s]) v1 <- c(rep(0, l)) v2 <- c(rep(0, l)) r <- as.character(datav[, 2][datav[, 3] == s]) == seeking v1[1] <- 0 v2[1] <- v1[1] + r[1] if (l > 1) { spacings <- as.numeric(datav[, 1][datav[, 3] == s][2:l]) - as.numeric(datav[, 1][datav[, 3] == s][1:(l - 1)]) for (i in 2:l) { v1[i] <- v2[i - 1] * exp(-spacings[i - 1] / (scalev * 86400)) v2[i] <- v1[i] + r[i] } } temp[datav[, 3] == s] <- v1 } return(temp) } countOutcomeDifficulty1 <- function(data, index, r) { temp <- data$pred temp <- ifelse(data$Outcome == r, temp, 0) data$temp <- ave(temp, index, FUN = function(x) as.numeric(cumsum(x))) data$temp <- data$temp - temp data$temp } countRelatedDifficulty1 <- function(data, index, r) { temp <- (data$contran) temp <- ifelse(data$Outcome == r, temp, 0) data$temp <- ave(temp, index, FUN = function(x) as.numeric(cumsum(x))) data$temp <- data$temp - temp data$temp } countRelatedDifficulty2 <- function(data, index, r) { temp <- (data$contran)^2 temp <- ifelse(data$Outcome == r, temp, 0) data$temp <- ave(temp, index, FUN = function(x) as.numeric(cumsum(x))) data$temp <- data$temp - temp data$temp } countOutcomeDifficulty2 <- function(data, index, r) { temp <- data$pred^2 temp <- ifelse(data$Outcome == r, temp, 0) data$temp <- ave(temp, index, FUN = function(x) as.numeric(cumsum(x))) data$temp <- data$temp - temp data$temp } countOutcomeDifficultyAll1 <- function(data, index) { temp <- data$pred data$temp <- ave(temp, index, FUN = function(x) as.numeric(cumsum(x))) data$temp <- data$temp - temp data$temp } countOutcomeDifficultyAll2 <- function(data, index) { temp <- data$pred^2 data$temp <- ave(temp, index, FUN = function(x) as.numeric(cumsum(x))) data$temp <- data$temp - temp data$temp } countOutcomeGen <- function(data, index, item, sourcecol, sourc) { data$tempout <- paste(data$Outcome, sourcecol) item <- paste(item, sourc) data$temp <- as.numeric(ave(as.character(data$tempout), index, FUN = function(x) as.numeric(cumsum(tolower(x) == tolower(item))))) data$temp <- data$temp - as.numeric(tolower(as.character(data$tempout)) == tolower(item)) as.numeric(data$temp) } countOutcomeOther <- function(data, index, item, sourcecol, sourc, targetcol, target) { data$tempout <- paste(data$Outcome, sourcecol) item <- paste(item, sourc) targetcol <- as.numeric(targetcol == target) data$temp <- ave(as.character(data$tempout), index, FUN = function(x) as.numeric(cumsum(tolower(x) == tolower(item)))) data$temp[tolower(as.character(data$tempout)) == tolower(item)] <- as.numeric(data$temp[tolower(as.character(data$tempout)) == tolower(item)]) - 1 as.numeric(data$temp) * targetcol } practiceTime <- function(data) { temp <- rep(0, length(data$CF..ansbin.)) for (i in unique(data$Anon.Student.Id)) { if (length(data$Duration..sec.[data$Anon.Student.Id == i]) > 1) { temp[data$Anon.Student.Id == i] <- c(0, cumsum(data$Duration..sec.[data$Anon.Student.Id == i]) [1:(length(cumsum(data$Duration..sec.[data$Anon.Student.Id == i])) - 1)]) } } return(temp) } componentspacing <- function(data, index, times) { temp <- rep(0, length(data$CF..ansbin.)) for (i in unique(index)) { lv <- length(data$CF..ansbin.[index == i]) if (lv > 1) { temp[index == i] <- c(0, times[index == i][2:(lv)] - times[index == i][1:(lv - 1)]) } } return(temp) } componentprev <- function(data, index, answers) { temp <- rep(0, length(data$CF..ansbin.)) for (i in unique(index)) { lv <- length(data$CF..ansbin.[index == i]) if (lv > 1) { temp[index == i] <- c(0, answers[index == i][1:(lv - 1)]) } } return(temp) } meanspacingf <- function(data, index, spacings) { temp <- rep(0, length(data$CF..ansbin.)) for (i in unique(index)) { j <- length(temp[index == i]) if (j > 1) { temp[index == i][2] <- -1 } if (j == 3) { temp[index == i][3] <- spacings[index == i][2] } if (j > 3) { temp[index == i][3:j] <- cumsum(spacings[index == i][2:(j - 1)]) / (1:(j - 2)) } } return(temp) } laggedspacingf <- function(data, index, spacings) { temp <- rep(0, length(data$CF..ansbin.)) for (i in unique(index)) { j <- length(temp[index == i]) if (j > 1) { temp[index == i][2] <- 0 } if (j >= 3) { temp[index == i][3:j] <- spacings[index == i][2:(j - 1)] } } return(temp) } errordec <- function(v, d) { w <- length(v) sum((c(0, v[1:w]) * d^((w):0)) / sum(d^((w + 1):0))) } slideerrordec <- function(x, d) { v <- c(rep(0, length(x))) for (i in 1:length(x)) { v[i] <- errordec(x[1:i], d) } return(c(0, v[1:length(x) - 1])) } expdec <- function(v, d) { w <- length(v) sum(v[1:w] * d^((w - 1):0)) } propdec2 <- function(v, d) { w <- length(v) sum((v[1:w] * d^((w - 1):0)) / sum(d^((w + 2):0))) } propdec <- function(v, d) { w <- length(v) sum((c(1, v[1:w]) * d^((w):0)) / sum(d^((w + 1):0))) } logitdec <- function(v, d) { w <- length(v) corv <- sum(c(1, v[1:w]) * d^(w:0)) incorv <- sum(c(1, abs(v[1:w] - 1)) * d^(w:0)) log(corv / incorv) } slideexpdec <- function(x, d) { v <- c(rep(0, length(x))) for (i in 1:length(x)) { v[i] <- expdec(x[1:i], d) } return(c(0, v[1:length(x) - 1])) } slidepropdec <- function(x, d) { v <- c(rep(0, length(x))) for (i in 1:length(x)) { v[i] <- propdec(x[1:i], d) } return(c(.5, v[1:length(x) - 1])) } slidepropdec2 <- function(x, d) { v <- c(rep(0, length(x))) for (i in 1:length(x)) { v[i] <- propdec2(x[1:i], d) } return(c(0, v[1:length(x) - 1])) } slidelogitdec <- function(x, d) { v <- c(rep(0, length(x))) for (i in 1:length(x)) { v[i] <- logitdec(x[1:i], d) } return(c(0, v[1:length(x) - 1])) } slidelogitdec <- function(x, d) { v <- c(rep(0, length(x))) for (i in 1:length(x)) { v[i] <- logitdec(x[max(1, i - 60):i], d) } return(c(0, v[1:length(x) - 1])) } ppew <- function(times, wpar) { times^-wpar * (1 / sum(times^-wpar)) } ppet <- function(times) { times[length(times)] - times } ppetw <- function(x, d) { v <- length(x) ppetv <- ppet(x)[1:(v - 1)] ppewv <- ppew(ppetv, d) ifelse(is.nan(crossprod(ppewv[1:(v - 1)], ppetv[1:(v - 1)])), 1, crossprod(ppewv[1:(v - 1)], ppetv[1:(v - 1)]) ) } slideppetw <- function(x, d) { v <- c(rep(0, length(x))) for (i in 1:length(x)) { v[i] <- ppetw(x[1:i], d) } return(c(v[1:length(x)])) } baselevel <- function(x, d) { l <- length(x) return(c(0, x[2:l]^-d)[1:l]) } splittimes <- function(times) { (match(max(rank(diff(times))), rank(diff(times)))) } smallSet <- function(data, nSub) { totsub <- length(unique(data$Anon.Student.Id)) datasub <- unique(data$Anon.Student.Id) smallSub <- datasub[sample(1:totsub)[1:nSub]] smallIdx <- which(data$Anon.Student.Id %in% smallSub) smalldata <- data[smallIdx, ] smalldata <- droplevels(smalldata) return(smalldata) } texteval <- function(stringv) { eval(parse(text = stringv)) }
test_that("custom scalar translated correctly", { local_con(simulate_postgres()) expect_equal(translate_sql(bitwXor(x, 128L)), sql("`x` expect_equal(translate_sql(log10(x)), sql("LOG(`x`)")) expect_equal(translate_sql(log(x)), sql("LN(`x`)")) expect_equal(translate_sql(log(x, 2)), sql("LOG(`x`) / LOG(2.0)")) expect_equal(translate_sql(cot(x)), sql("1 / TAN(`x`)")) expect_equal(translate_sql(round(x, digits = 1.1)), sql("ROUND((`x`) :: numeric, 1)")) expect_equal(translate_sql(grepl("exp", x)), sql("(`x`) ~ ('exp')")) expect_equal(translate_sql(grepl("exp", x, TRUE)), sql("(`x`) ~* ('exp')")) expect_equal(translate_sql(substr("test", 2 , 3)), sql("SUBSTR('test', 2, 2)")) }) test_that("custom stringr functions translated correctly", { local_con(simulate_postgres()) expect_equal(translate_sql(str_detect(x, y)), sql("`x` ~ `y`")) expect_equal(translate_sql(str_detect(x, y, negate = TRUE)), sql("!(`x` ~ `y`)")) expect_equal(translate_sql(str_replace(x, y, z)), sql("REGEXP_REPLACE(`x`, `y`, `z`)")) expect_equal(translate_sql(str_replace_all(x, y, z)), sql("REGEXP_REPLACE(`x`, `y`, `z`, 'g')")) expect_equal(translate_sql(str_squish(x)), sql("LTRIM(RTRIM(REGEXP_REPLACE(`x`, '\\s+', ' ', 'g')))")) expect_equal(translate_sql(str_remove(x, y)), sql("REGEXP_REPLACE(`x`, `y`, '')")) expect_equal(translate_sql(str_remove_all(x, y)), sql("REGEXP_REPLACE(`x`, `y`, '', 'g')")) }) test_that("two variable aggregates are translated correctly", { local_con(simulate_postgres()) expect_equal(translate_sql(cor(x, y), window = FALSE), sql("CORR(`x`, `y`)")) expect_equal(translate_sql(cor(x, y), window = TRUE), sql("CORR(`x`, `y`) OVER ()")) }) test_that("pasting translated correctly", { local_con(simulate_postgres()) expect_equal(translate_sql(paste(x, y), window = FALSE), sql("CONCAT_WS(' ', `x`, `y`)")) expect_equal(translate_sql(paste0(x, y), window = FALSE), sql("CONCAT_WS('', `x`, `y`)")) expect_error(translate_sql(paste0(x, collapse = ""), window = FALSE), "`collapse` not supported") }) test_that("postgres mimics two argument log", { local_con(simulate_postgres()) expect_equal(translate_sql(log(x)), sql('LN(`x`)')) expect_equal(translate_sql(log(x, 10)), sql('LOG(`x`) / LOG(10.0)')) expect_equal(translate_sql(log(x, 10L)), sql('LOG(`x`) / LOG(10)')) }) test_that("custom lubridate functions translated correctly", { local_con(simulate_postgres()) expect_equal(translate_sql(yday(x)), sql("EXTRACT(DOY FROM `x`)")) expect_equal(translate_sql(quarter(x)), sql("EXTRACT(QUARTER FROM `x`)")) expect_equal(translate_sql(quarter(x, with_year = TRUE)), sql("(EXTRACT(YEAR FROM `x`) || '.' || EXTRACT(QUARTER FROM `x`))")) expect_error(translate_sql(quarter(x, fiscal_start = 2))) expect_equal(translate_sql(seconds(x)), sql("CAST('`x` seconds' AS INTERVAL)")) expect_equal(translate_sql(minutes(x)), sql("CAST('`x` minutes' AS INTERVAL)")) expect_equal(translate_sql(hours(x)), sql("CAST('`x` hours' AS INTERVAL)")) expect_equal(translate_sql(days(x)), sql("CAST('`x` days' AS INTERVAL)")) expect_equal(translate_sql(weeks(x)), sql("CAST('`x` weeks' AS INTERVAL)")) expect_equal(translate_sql(months(x)), sql("CAST('`x` months' AS INTERVAL)")) expect_equal(translate_sql(years(x)), sql("CAST('`x` years' AS INTERVAL)")) expect_equal(translate_sql(floor_date(x, 'month')), sql("DATE_TRUNC('month', `x`)")) expect_equal(translate_sql(floor_date(x, 'week')), sql("DATE_TRUNC('week', `x`)")) }) test_that("custom SQL translation", { lf <- lazy_frame(x = 1, con = simulate_postgres()) expect_snapshot(left_join(lf, lf, by = "x", na_matches = "na")) }) test_that("can explain", { db <- copy_to_test("postgres", data.frame(x = 1:3)) expect_snapshot(db %>% mutate(y = x + 1) %>% explain()) }) test_that("can overwrite temp tables", { src <- src_test("postgres") copy_to(src, mtcars, "mtcars", overwrite = TRUE) expect_error(copy_to(src, mtcars, "mtcars", overwrite = TRUE), NA) })
tmap_icons <- function(file, width=48, height=48, keep.asp=TRUE, just=c("center", "center"), as.local=TRUE, ...) { icon_names <- names(file) icons <- lapply(file, tmap_one_icon, width=width, height=height, keep.asp=keep.asp, just=just, as.local=as.local, ...) merge_icons(icons, icon_names) } tmap_one_icon <- function(file, width, height, keep.asp, just, as.local, ...) { args <- list(...) args$iconUrl <- NULL pu <- is_path_or_url(file) if (is.na(pu)) { stop(file, " is neither a valid path nor url", call.=FALSE) } if (!pu) { tmpfile <- tempfile(fileext=".png") download.file(file, destfile=tmpfile, mode="wb") localfile <- tmpfile } else { localfile <- file } if (!pu && as.local) file <- localfile if (any(c("iconWidth", "iconHeight") %in% names(args))) keep.asp <- FALSE if (keep.asp) { x <- png::readPNG(localfile) xasp <- dim(x)[2]/dim(x)[1] iasp <- width/height if (xasp > iasp) { height <- floor(width/xasp) } else { width <- floor(height*xasp) } } if (!("iconWidth" %in% names(args))) args$iconWidth <- width if (!("iconHeight" %in% names(args))) args$iconHeight <- height just <- c(ifelse(is_num_string(just[1]), as.numeric(just[1]), ifelse(just[1]=="left", 1, ifelse(just[1]=="right", 0, .5))), ifelse(is_num_string(just[2]), as.numeric(just[2]), ifelse(just[2]=="bottom", 1, ifelse(just[2]=="top", 0, .5)))) if (!("iconAnchorX" %in% names(args))) args$iconAnchorX <- round(args$iconWidth * (1-just[1])) if (!("iconAnchorY" %in% names(args))) args$iconAnchorY <- round(args$iconHeight * just[2]) do.call(leaflet::icons, c(list(iconUrl=file), args)) } marker_icon <- function() { file <- system.file("htmlwidgets/lib/leaflet/images/marker-icon.png", package="leaflet") if (!file.exists(file)) stop("leaflet marker icon not found") icons(iconUrl = system.file("htmlwidgets/lib/leaflet/images/marker-icon.png", package="leaflet"), iconWidth=25, iconHeight=41, iconAnchorX = 12, iconAnchorY = 41) } pngGrob <- function(file, fix.borders=FALSE, n=NULL, height.inch=NULL, target.dpi=NULL) { if (!requireNamespace("png", quietly = TRUE)) { stop("png package needed for this function to work. Please install it.", call. = FALSE) } else { pu <- is_path_or_url(file) if (is.na(pu)) { stop(file, " is neither a valid path nor url", call.=FALSE) } if (!pu) { tmpfile <- tempfile(fileext=".png") download.file(file, destfile=tmpfile, mode="wb") file <- tmpfile } x <- png::readPNG(file) if (fix.borders) { if (dim(x)[3]==3) { x <- array(c(x, rep(1, dim(x)[1]*dim(x)[2])), dim = c(dim(x)[1], dim(x)[2], dim(x)[3]+1)) } x2 <- add_zero_borders_to_3d_array(x, n=n, height.inch=height.inch,target.dpi=target.dpi) rasterGrob(x2, interpolate=TRUE) } else { rasterGrob(x, interpolate=TRUE) } } } add_zero_borders_to_3d_array <- function(x, perc=NA, n=NULL, height.inch=NULL, target.dpi=NULL) { dims <- dim(x) if (is.na(perc)) { dpi <- dims[2] / height.inch compress <- dpi/target.dpi borders <- rep(compress * n, 2) } else { borders <- round(dims / 100 * perc) } res <- lapply(1:dims[3], function(i) { rbind(cbind(x[,,i], matrix(0, nrow=nrow(x), ncol=borders[2])), matrix(0, nrow=borders[1], ncol=ncol(x)+borders[2])) }) array(unlist(res, use.names = FALSE), dim = c(dim(x)[1]+borders[1], dim(x)[2]+borders[2], dim(x)[3])) } icon2grob <- function(icon) { if (!is.list(icon)) stop("icon is not a list") if (!"iconUrl" %in% names(icon)) stop("iconUrl not defined") if (length(icon$iconUrl)==1) { pngGrob(icon$iconUrl) } else { lapply(icon$iconUrl, pngGrob) } } grob2icon <- function(grob, grob.dim, just) { tmp <- tempfile(fileext=".png") png(filename=tmp, width=grob.dim[3], height=grob.dim[4], bg = "transparent") grid.draw(grob) dev.off() w <- grob.dim[1] h <- grob.dim[2] icons(iconUrl = tmp, iconWidth = w, iconHeight = h, iconAnchorX = w * (1-just[1]), iconAnchorY = h * just[2]) } split_icon <- function(icon) { ni <- max(vapply(icon, length, integer(1))) icon_max <- lapply(icon, function(ic) { rep(ic, length.out=ni) }) if ("iconNames" %in% names(icon_max)) { icon_names <- icon_max$iconNames icon_max$iconNames <- NULL } else { icon_names <- NULL } res <- lapply(1:ni, function(i) { lapply(icon_max, function(ic) { ic[i] }) }) if (!is.null(icon_names)) names(res) <- icon_names res } merge_icons <- function(icons, icon_names = NULL) { list_names <- unique(unlist(lapply(icons, names), use.names = FALSE)) names(list_names) <- list_names res <- lapply(list_names, function(ln) { unname(sapply(icons, function(ic) { if (ln %in% names(ic)) { ic[[ln]][1] } else NA })) }) if (!is.null(icon_names)) res$iconNames <- icon_names res } is_path_or_url <- function(file) { if (file.exists(file)) { TRUE } else { con.url <- suppressWarnings(try({ u <- url(file, open='rb') close(u) }, silent=TRUE)) try.error <- inherits(con.url, "try-error") if (try.error) NA else FALSE } }
gridp4d <- function (p4d, trait = names(tdata(p4d)), center = TRUE, scale = TRUE, tree.ladderize = FALSE, tree.type = "phylogram", tree.ratio = NULL, tree.xlim = NULL, tree.open.angle = 0, tree.open.crown = TRUE, show.tip = TRUE, tip.labels = NULL, tip.col = "black", tip.cex = 1, tip.font = 3, tip.adj = 0, cell.col = topo.colors(100), show.color.scale = TRUE, show.trait = TRUE, trait.labels = NULL, trait.col = "black", trait.cex = 0.7, trait.font = 1, trait.bg.col = "grey90", show.box = FALSE, grid.vertical = FALSE, grid.horizontal = FALSE, grid.col = "grey25", grid.lty = "dashed", ...) { plot.phylo4d(x = p4d, trait = trait, center = center, scale = scale, plot.type = "gridplot", tree.ladderize = tree.ladderize, tree.type = tree.type, tree.ratio = tree.ratio, tree.xlim = tree.xlim, tree.open.angle = tree.open.angle, tree.open.crown = tree.open.crown, show.tip = show.tip, tip.labels = tip.labels, tip.col = tip.col, tip.cex = tip.cex, tip.font = tip.font, tip.adj = tip.adj, cell.col = cell.col, show.color.scale = show.color.scale, show.trait = show.trait, trait.labels = trait.labels, trait.col = trait.col, trait.cex = trait.cex, trait.font = trait.font, trait.bg.col = trait.bg.col, show.box = show.box, grid.vertical = grid.vertical, grid.horizontal = grid.horizontal, grid.col = grid.col, grid.lty = grid.lty, ...) }
BASIX.match <- function(elements, vec){ ids <- .Call("my_match_C",elements,vec, PACKAGE="BASIX") return(ids) }
setClass( Class = "Tr.label", contains = "ADEg.Tr" ) setMethod( f = "initialize", signature = "Tr.label", definition = function(.Object, data = list(dfxyz = NULL, labels = NULL, frame = 0, storeData = TRUE), ...) { .Object <- callNextMethod(.Object, data = data, ...) .Object@data$labels <- data$labels return(.Object) }) setMethod( f = "prepare", signature = "Tr.label", definition = function(object) { name_obj <- deparse(substitute(object)) if(object@data$storeData) { labels <- object@data$labels df <- object@data$dfxyz } else { labels <- eval(object@data$labels, envir = sys.frame(object@data$frame)) df <- eval(object@data$dfxyz, envir = sys.frame(object@data$frame)) } oldparamadeg <- adegpar() on.exit(adegpar(oldparamadeg)) adegtot <- adegpar([email protected]) if((is.null([email protected]$plabels$boxes$draw) & adegtot$plabels$optim) || (is.null([email protected]$plabels$boxes$draw) & length(labels) > 1000)) adegtot$plabels$boxes$draw <- FALSE if([email protected]$addmean) { default <- list(pch = 20, col = "black", cex = 2) if(is.list([email protected]$meanpar)) [email protected]$meanpar <- modifyList(default, [email protected]$meanpar, keep.null = TRUE) else { if(!is.null([email protected]$meanpar)) stop("meanpar must be a list of graphical parameters (pch, col, cex)", call. = FALSE) else [email protected]$meanpar <- default } } if([email protected]$addaxes | [email protected]$addmean) { default <- list(col = "black", lwd = 1, lty = 1) if(is.list([email protected]$axespar)) [email protected]$axespar <- modifyList(default, [email protected]$axespar, keep.null = TRUE) else { if(!is.null([email protected]$axespar)) stop("axespar must be a list of graphical parameters (lwd, col, lty)", call. = FALSE) else [email protected]$axespar <- default } default <- list(pch = 20, col = "black", cex = 2) if(is.list([email protected]$meanpar)) [email protected]$meanpar <- modifyList(default, [email protected]$meanpar, keep.null = TRUE) else { if(!is.null([email protected]$meanpar)) stop("meanpar must be a list of graphical parameters (pch, col, cex)", call. = FALSE) else [email protected]$meanpar <- default } } [email protected] <- adegtot callNextMethod() df <- sweep(df, 1, rowSums(df), "/") object@stats$coords2d <- .coordtotriangleM(df, mini3 = [email protected]$min3d, maxi3 = [email protected]$max3d)[, 2:3] assign(name_obj, object, envir = parent.frame()) }) setMethod( f = "panel", signature = "Tr.label", definition = function(object, x, y) { if(object@data$storeData) { labels <- object@data$labels df <- object@data$dfxyz } else { labels <- eval(object@data$labels, envir = sys.frame(object@data$frame)) df <- eval(object@data$dfxyz, envir = sys.frame(object@data$frame)) } if(any([email protected]$ppoints$cex > 0)) panel.points(object@stats$coords2d[, 1], object@stats$coords2d[, 2], pch = [email protected]$ppoints$pch, cex = [email protected]$ppoints$cex, col = [email protected]$ppoints$col, alpha = [email protected]$ppoints$alpha, fill = [email protected]$ppoints$fill) if(any([email protected]$plabels$cex > 0)) adeg.panel.label(object@stats$coords2d[, 1], object@stats$coords2d[, 2], labels, [email protected]$plabels) if([email protected]$addmean | [email protected]$addaxes) { df <- sweep(df, 1, rowSums(df), "/") mini3 <- [email protected]$min3d maxi3 <- [email protected]$max3d m3 <- colMeans(df) mxy <- .coordtotriangleM(t(as.matrix(m3)), mini3 = mini3, maxi3 = maxi3)[-1] if([email protected]$addmean) { axp3 <- rbind(c(m3[1], mini3[2], 1 - m3[1] - mini3[2]), c(1 - m3[2] -mini3[3], m3[2], mini3[3]), c(mini3[1], 1 - m3[3] - mini3[1], m3[3])) axpxyz <- .coordtotriangleM(axp3, mini3 = mini3, maxi3 = maxi3) apply(axpxyz, 1, FUN = function(x) { do.call("panel.lines", c(list(x = c(x[2], mxy[1]), y = c(x[3], mxy[2])), [email protected]$axespar)) }) do.call("panel.points", c(list(x = c(mxy[1], axpxyz[, 2]), y = c(mxy[2], axpxyz[, 3])), [email protected]$meanpar)) panel.text(x = axpxyz[, 2], y = axpxyz[, 3], labels = as.character(round(m3, digits = 4)), pos = c(2, 1, 4)) } if([email protected]$addaxes) { axx <- dudi.pca(df, scale = FALSE, scannf = FALSE)$c1 cornerp <- [email protected]$cornerp a1 <- axx[, 1] x1 <- a1[1] * cornerp$A + a1[2] * cornerp$B + a1[3] * cornerp$C do.call("panel.segments", c(list(x0 = mxy[1] - x1[1], x1 = mxy[1] + x1[1], y0 = mxy[2] - x1[2], y1 = mxy[2] + x1[2]), [email protected]$axespar)) a2 <- axx[, 2] x1 <- a2[1] * cornerp$A + a2[2] * cornerp$B + a2[3] * cornerp$C do.call("panel.segments", c(list(x0 = mxy[1] - x1[1], x1 = mxy[1] + x1[1], y0 = mxy[2] - x1[2], y1 = mxy[2] + x1[2]), [email protected]$axespar)) do.call("panel.points", c(list(x = mxy[1], y = mxy[2]), [email protected]$meanpar)) } } }) triangle.label <- function(dfxyz, labels = rownames(dfxyz), adjust = TRUE, min3d = NULL, max3d = NULL, addaxes = FALSE, addmean = FALSE, meanpar = NULL, axespar = NULL, showposition = TRUE, facets = NULL, plot = TRUE, storeData = TRUE, add = FALSE, pos = -1, ...) { thecall <- .expand.call(match.call()) sortparameters <- sortparamADEg(...) if(!is.null(facets)) { object <- multi.facets.Tr(thecall, samelimits = sortparameters$g.args$samelimits) } else { if(length(sortparameters$rest)) warning(c("Unused parameters: ", paste(unique(names(sortparameters$rest)), " ", sep = "")), call. = FALSE) g.args <- c(sortparameters$g.args, list(adjust = adjust, min3d = min3d, max3d = max3d, addaxes = addaxes, addmean = addmean, meanpar = meanpar, axespar = axespar)) if(storeData) tmp_data <- list(dfxyz = dfxyz, labels = labels, frame = sys.nframe() + pos, storeData = storeData) else tmp_data <- list(dfxyz = thecall$dfxyz, labels = thecall$labels, frame = sys.nframe() + pos, storeData = storeData) object <- new(Class = "Tr.label", data = tmp_data, adeg.par = sortparameters$adepar, trellis.par = sortparameters$trellis, g.args = g.args, Call = match.call()) prepare(object) setlatticecall(object) if(showposition & add) { warning("cannot show position and add") showposition <- FALSE } if(showposition) object <- new(Class = "ADEgS", ADEglist = list("triangle" = object, "positions" = .showpos(object)), positions = rbind(c(0, 0, 1, 1), c(0, 0.7, 0.3, 1)), add = matrix(0, ncol = 2, nrow = 2), Call = match.call()) if(add) object <- add.ADEg(object) } if(!add & plot) print(object) invisible(object) }
sizelegend<-function(se, am, pch=pch) { if(missing(pch)) pch= 1 u = par('usr') ex = c(u[1]+ .05*(u[2]-u[1]), u[1]+ .2*(u[2]-u[1])) why = u[3]+.95*(u[4]-u[3]) N = length(se) rect(u[1], u[3]+.9*(u[4]-u[3]) , u[1]+ .25*(u[2]-u[1]) , u[4], col="white", border=NA, xpd=TRUE) points(seq(from=ex[1], to=ex[2], length=N), rep(why, length=N), pch=pch, cex=se, xpd=TRUE) text(seq(from=ex[1], to=ex[2], length=N), rep(why, length=N),labels=am, pos=3, xpd=TRUE) }
VERBDESEMANTICIZATION <- function(agent){ distinctions=world$distinctions; minimalSpecification=world$minimalSpecification; desemanticizationCeiling=world$desemanticizationCeiling; power=world$desemanticizationPower dims=length(distinctions) steps=dims-1-minimalSpecification factor=(desemanticizationCeiling*agent$age-8)/steps^power steps=round(factor*(0:steps)^power + 8) verbs=xtabs(~agent$usageHistory$verbs$verb) verbs=names(verbs[verbs>steps[1]]) for(verb in verbs){ verbTargets=agent$usageHistory$verbs[agent$usageHistory$verbs$verb==verb,grep('^D\\d',names(agent$usageHistory$verbs))] for(i in 1:ncol(verbTargets)){ values=table(verbTargets[,i]) change=MAX(values, forceChoice=T) if(sum(values[-change])<(sum(values)/log(sum(values)))){ agent$verbs[agent$verbs$ID==verb, i]=as.numeric(names(values)[change]) graveyard$history[nrow(graveyard$history) + 1,]=c(agent$generation, 'verb meaning changed', 'VERBDESEMANTICIZATION', verb, '', '', '') } } if(agent$verbs[agent$verbs$ID==verb,]$semanticWeight>(minimalSpecification/dims)){ if(nrow(verbTargets)>steps[sum(is.na(agent$verbs[agent$verbs$ID==verb,grep('^D\\d',names(agent$verbs))])) + 1]){ actionProfile=agent$verbs[agent$verbs$ID==verb,grep('^D\\d',names(agent$verbs))] vars=rep(0, ncol(verbTargets)) for(i in 1:length(vars)){vars[i]=sum(actionProfile[,i]!=verbTargets[,i], na.rm=T)} agent$verbs[agent$verbs$ID==verb, MAX(vars, forceChoice=T)]=NA agent$verbs[agent$verbs$ID==verb, ]$semanticWeight=(length(grep('^D\\d',names(agent$verbs)))-sum(is.na(agent$verbs[agent$verbs$ID==verb, grep('^D\\d',names(agent$verbs))])))/length(grep('^D\\d',names(agent$verbs))) extProfile=agent$verbs[agent$verbs$ID==verb, grep('^Ext\\d',names(agent$verbs))] vars=rep(0, ncol(extProfile)) performerProfiles=agent$nouns[match(agent$collostructions$SV[grep(paste('^',verb, '$',sep=''),agent$collostructions$SV$V),]$S, agent$nouns$ID),grep('^D\\d',names(agent$nouns))] for(i in 1:length(vars)){vars[i]=sum(extProfile[,i]!=performerProfiles[,i], na.rm=T)} agent$verbs[agent$verbs$ID==verb, grep('^Ext\\d',names(agent$verbs))[MAX(vars, forceChoice=T)]]=NA intProfile=agent$verbs[agent$verbs$ID==verb, grep('^Int\\d',names(agent$verbs))] vars=rep(0, ncol(intProfile)) performerProfiles=agent$nouns[match(agent$collostructions$OV[grep(paste('^',verb, '$',sep=''),agent$collostructions$OV$V),]$O, agent$nouns$ID),grep('^D\\d',names(agent$nouns))] for(i in 1:length(vars)){vars[i]=sum(intProfile[,i]!=performerProfiles[,i], na.rm=T)} agent$verbs[agent$verbs$ID==verb, grep('^Int\\d',names(agent$verbs))[MAX(vars, forceChoice=T)]]=NA graveyard$history[nrow(graveyard$history) + 1,]=c(agent$generation, 'verb meaning dimension removed', 'VERBDESEMANTICIZATION', verb, '', '', '') } } } graveyard <<- graveyard agent }
NULL if(getRversion() >= "2.15.1") { utils::globalVariables(c(".", "sentence", "bytes", "bytes_sum")) }
flex_zones = function(coords, w, k = 10, longlat = FALSE, cl = NULL, loop = FALSE, verbose = FALSE, pfreq = 1) { nn = knn(coords = coords, longlat = longlat, k = k) N = nrow(coords) idx = seq_along(nn) lprimes = log(randtoolbox::get.primes(N)) if (!loop) { czones = scsg2_cpp(nn, w, idx = idx, nlevel = k, lprimes = lprimes, verbose = verbose) czones = logical2zones(czones, nn, idx) return(czones[distinct(czones)]) } else { czones = list() pri = randtoolbox::get.primes(N) czones_id = numeric(0) for (i in seq_len(N)) { if (verbose) { if ((i %% pfreq) == 0) { message(i, "/", N, ". Starting region ", i, " at ", Sys.time(), ".") } } izones = scsg2_cpp(nn, w, i, k, lprimes, verbose = FALSE) izones = logical2zones(izones, nn, idx = i) izones_id = sapply(izones, function(xi) sum(lprimes[xi])) dup_id = which(izones_id %in% czones_id) if (length(dup_id) > 0) { czones = combine.zones(czones, izones[-dup_id]) czones_id = c(czones_id, izones_id[-dup_id]) } else { czones = combine.zones(czones, izones) czones_id = c(czones_id, izones_id) } } return(czones) } } logical2zones = function(czones, nn, idx = seq_along(nn)) { unlist(lapply(seq_along(czones), function(i) { lapply(czones[[i]], function(x) { nn[[idx[i]]][x] }) }), recursive = FALSE) }
extractMandatory <- hutilscpp:::extractMandatory where_square_bracket_opens <- hutilscpp:::where_square_bracket_opens library(hutils) x <- c('a', '', 'b', 'd', '{', 'e', '}', '.', 'b', 'e') res <- extractMandatory(x, c('b', 'd'), nCommands = 1L)[[1]] expect_equal(res, if_else(nzchar(res), x, '')) xop <- strsplit("qxy[ab]{jys}", split = "")[[1]] res_op <- extractMandatory(xop, c("q", "x", "y"), nCommands = 1L)[[1]] expect_true("y" %in% res_op) x <- c('a', '', 'b', 'd', ' ', '{', 'e', '}', '.') res <- extractMandatory(x, c('b', 'd'), nCommands = 1L)[[1]] expect_true(any(nzchar(x))) x <- strsplit("a \\Def[a [b] c]{df} x", split = "")[[1]] res <- extractMandatory(x, c("D", "e", "f"), 1L) expect_false("[" %in% res$support) expect_true("d" %in% res$support) x <- strsplit("a \\Def[a [b{q}] c]{df} x", split = "")[[1]] res <- extractMandatory(x, c("D", "e", "f"), 1L) expect_false("[" %in% res$support) expect_true("d" %in% res$support) x <- strsplit("a \\Def[a [b{q{}}] c]{df} xDe", split = "")[[1]] res <- extractMandatory(x, c("D", "e", "f"), 1L) expect_false("[" %in% res$support) expect_true("d" %in% res$support) x <- strsplit("a \\Defg[a [b{q{}}] c]{df} \\Def{a} b", split = "")[[1]] res <- extractMandatory(x, c("D", "e", "f"), 1L) x <- strsplit("a{b", split = "")[[1]] res <- extractMandatory(x, c("foo"), 1L) expect_false(any(nzchar(res$support))) x <- strsplit("a[{b", split = "")[[1]] res <- extractMandatory(x, strsplit(c("foo"), split = "")[[1]], 1L) expect_false(any(nzchar(res$support))) x <- strsplit("b \\ad[s]", split = "")[[1]] res <- extractMandatory(x, c("a", "d"), 1L) expect_false(any(nzchar(res$support))) x <- strsplit(c("the \\XYZ{cliff \\za{ba} wood.} flighty."), split = "")[[1L]] res <- extractMandatory(x, strsplit("XYZ", split = "")[[1]], 1L) expect_true(all(strsplit("cliff \\za{ba} wood.", split = "")[[1L]] %in% res$support)) report.tex <- if (file.exists("~/AP-2018-retirement/report.tex")) { "~/AP-2018-retirement/report.tex" } else { system.file("extdata", "ap-2018-retirement-report.tex", package = "hutilscpp") } if (file.exists(report.tex)) { library(TeXCheckR) library(data.table) Housing <- tryCatch(read_tex_document(report.tex), error = function(e) { out <- 0L names(out) <- e$m out }) if (!is.integer(Housing)) { Housing_split = unlist(strsplit(Housing, split = "")) nFootnotes <- (length(grep("\\\\footnote(?![A-Za-z])[^\\{]*\\{", Housing, perl = TRUE))) footnote <- strsplit("footnote", split = "")[[1L]] res <- extractMandatory(Housing_split, footnote, nCommands = nFootnotes) Seq_All <- function(froms, tos) { unlist(lapply(seq_along(froms), function(i) { seq.int(from = froms[i], to = tos[i], by = 1L) })) } DT <- data.table(Ope = res$Openers, Clo = res$Closers)[, I := .I][, .(Text = paste0(res$support[.BY[[1]]:.BY[[2]]], collapse = "")), keyby = c("Ope", "Clo", "I")] expect_true(any(grepl("For example, see: \\textcites[][]{IndustrySuperAustralia2015inquiryintoeconom", DT$Text[1:10], fixed = TRUE))) } }
rhsFormula2list <- function(form){ if (is.character(form)) return(list(form)) if (is.numeric(form)) return(lapply(list(form), "as.character")) if (is.list(form)) return(lapply(form, "as.character")) .xxx. <- form[[ length( form ) ]] form1 <- unlist(strsplit(paste(deparse(.xxx.), collapse="")," *\\+ *")) form2 <- unlist(lapply(form1, strsplit, " *\\* *| *: *| *\\| *"), recursive=FALSE) form2 } rhsf2list <- rhsFormula2list rhsf2vec <- function(form){ rhsf2list(form)[[1]] } listify_dots <- function(dots){ dots <- lapply(dots, function(a) if (!is.list(a)) list(a) else a) unlist(dots, recursive=FALSE) } list2rhsFormula <- function(form){ if (inherits(form, "formula")) return(form) as.formula(paste("~",paste(unlist(lapply(form,paste, collapse='*')), collapse="+")), .GlobalEnv) } list2rhsf <- list2rhsFormula rowmat2list <- rowmat2list__ colmat2list <- colmat2list__ matrix2list <- function(X, byrow=TRUE){ if (byrow) rowmat2list__(X) else colmat2list__(X) } which.arr.index <- function(X){ nr <- nrow(X) nc <- ncol(X) rr <- rep.int(1:nr, nc) cc <- rep(1:nc, each=nr) cbind(rr[X!=0L], cc[X!=0L]) } which_matrix_index <- which_matrix_index__ rowSumsPrim <- function(X){ .Call("R_rowSums", X, PACKAGE="gRbase")} colSumsPrim <- function(X){ .Call("R_colSums", X, PACKAGE="gRbase")} colwiseProd <- function(v, X){ .Call("R_colwiseProd", v, X, PACKAGE="gRbase")} lapplyV2I <- function(setlist, item){lapply(setlist, function(elt) match(elt, item))} lapplyI2V <- function (setlist, item) {lapply(setlist, function(elt) item[elt])} pairs2num <- function(x, vn, sort=TRUE){ if (!inherits(x, "matrix")){ if (is.null(x)) return(NULL) if (inherits(x,"list")) x <- do.call(rbind,x) else { if (inherits(x,"character")) x <- matrix(x,nrow=1) } } dd <- dim(x) if (dd[1L] == 0){ return(numeric(0)) } else { if (sort){ i <- x[, 2L]< x[, 1L] c1 <- i+1L c2 <- -1L * (i - 1L) + 1L x <- cbind( x[cbind(seq_along(c1), c1)], x[cbind(seq_along(c2), c2)]) } ans <- match(x, vn) dim(ans) <- dim(x) colSumsPrim(t.default(ans) * c(100000, 1)) } }
attach(mtcars) plot(wt, mpg, main="Scatterplot Example", xlab="Car Weight ", ylab="Miles Per Gallon ", pch=19) abline(lm(mpg~wt), col="red") lines(lowess(wt,mpg), col="blue") library(car) scatterplot(mpg ~ wt | cyl, data=mtcars, xlab="Weight of Car", ylab="Miles Per Gallon", main="Enhanced Scatter Plot", labels=row.names(mtcars)) pairs(~mpg+disp+drat+wt,data=mtcars, main="Simple Scatterplot Matrix") library(lattice) splom(mtcars[c(1,3,5,6)], groups=cyl, data=mtcars, panel=panel.superpose, key=list(title="Three Cylinder Options", columns=3, points=list(pch=super.sym$pch[1:3], col=super.sym$col[1:3]), text=list(c("4 Cylinder","6 Cylinder","8 Cylinder")))) library(car) scatterplot.matrix(~mpg+disp+drat+wt|cyl, data=mtcars, main="Three Cylinder Options") library(gclus) dta <- mtcars[c(1,3,5,6)] dta.r <- abs(cor(dta)) dta.col <- dmat.color(dta.r) dta.o <- order.single(dta.r) cpairs(dta, dta.o, panel.colors=dta.col, gap=.5, main="Variables Ordered and Colored by Correlation" ) library(hexbin) x <- rnorm(1000) y <- rnorm(1000) bin<-hexbin(x, y, xbins=50) plot(bin, main="Hexagonal Binning") pdf("c:/scatterplot.pdf") x <- rnorm(1000) y <- rnorm(1000) plot(x,y, main="PDF Scatterplot Example", col=rgb(0,100,0,50,maxColorValue=255), pch=16) dev.off() library(scatterplot3d) attach(mtcars) scatterplot3d(wt,disp,mpg, main="3D Scatterplot") library(scatterplot3d) attach(mtcars) scatterplot3d(wt,disp,mpg, pch=16, highlight.3d=TRUE, type="h", main="3D Scatterplot") library(scatterplot3d) attach(mtcars) s3d <-scatterplot3d(wt,disp,mpg, pch=16, highlight.3d=TRUE, type="h", main="3D Scatterplot") fit <- lm(mpg ~ wt+disp) s3d$plane3d(fit) library(rgl) plot3d(wt, disp, mpg, col="red", size=3) library(Rcmdr) attach(mtcars) scatter3d(wt, disp, mpg)
conditionalTransform <- function(..., data, else_condition = NA, type = NULL, categories = NULL, formulas = NULL) { dots <- list(...) is_formula <- function(x) inherits(x, "formula") dot_formulas <- Filter(is_formula, dots) if (length(dot_formulas) > 0) { if (!is.null(formulas)) { halt( "Must not supply conditions in both the ", dQuote("formulas"), " argument and ", dQuote("...") ) } formulas <- dot_formulas } var_def <- Filter(Negate(is_formula), dots) if (length(formulas) == 0) { halt( "Conditions must be supplied: ", "Have you forgotten to supply conditions as formulas in either the ", dQuote("formulas"), " argument, or through ", dQuote("..."), "" ) } if (!missing(type) && !type %in% c("categorical", "text", "numeric")) { halt( "Type must be either ", dQuote("categorical"), ", ", dQuote("text"), ", or ", dQuote("numeric") ) } conditional_vals <- makeConditionalValues(formulas, data, else_condition) if (!missing(type)) { if (type == "numeric") { result <- as.numeric(conditional_vals$values) } else { result <- as.character(conditional_vals$values) } } else { result <- conditional_vals$values type <- conditional_vals$type } if (type != "categorical" & !is.null(categories)) { warning( "Type is not ", dQuote("categorical"), " ignoring ", dQuote("categories") ) } var_def$type <- type if (type == "categorical") { if (missing(categories)) { result <- factor(result) categories <- Categories(data = categoriesFromLevels(levels(result))) } else { if (!is.categories(categories)) { categories <- Categories(data = categoriesFromLevels(categories)) } uni_results <- unique(result[!is.na(result)]) results_not_categories <- !uni_results %in% names(categories) if (any(results_not_categories)) { halt( "When specifying categories, all categories in the ", "results must be included. These categories are in the ", "results that were not specified in categories: ", serialPaste(uni_results[results_not_categories]) ) } result <- factor(result, levels = names(categories)) } categories <- ensureNoDataCategory(categories) category_list <- categories var_def$categories <- category_list vals <- as.character(result) vals[is.na(vals)] <- "No Data" var_def$values <- ids(categories[vals]) } else { var_def$values <- result } class(var_def) <- "VariableDefinition" return(var_def) } makeConditionalValues <- function(formulas, data, else_condition) { n <- length(formulas) cases <- vector("list", n) values <- vector("list", n) for (i in seq_len(n)) { formula <- formulas[[i]] if (length(formula) != 3) { halt( "The condition provided must be a proper formula: ", deparseAndFlatten(formula) ) } cases[[i]] <- evalLHS(formula, data) if (!inherits(cases[[i]], c("logical", "CrunchLogicalExpr"))) { halt( "The left-hand side provided must be a logical or a ", "CrunchLogicalExpr: ", dQuote(LHS_string(formula)) ) } values[[i]] <- evalRHS(formula, data) } ds_refs <- unlist(unique(lapply(c(cases, values), datasetReference))) if (!missing(data)) { ds_refs <- unique(c(ds_refs, datasetReference(data))) } if (length(ds_refs) > 1) { halt( "There must be only one dataset referenced. Did you accidentally ", "supply more than one?" ) } else if (length(ds_refs) == 0) { halt( "There must be at least one crunch expression in the formulas ", "specifying cases or use the data argument to specify a dataset." ) } n_rows <- nrow(CrunchDataset(crGET(ds_refs))) case_indices <- lapply(cases, which) case_indices <- lapply(seq_along(case_indices), function(i) { setdiff(case_indices[[i]], unlist(case_indices[seq_len(i - 1)])) }) values_to_fill <- Map(function(ind, var) { if (inherits(var, c("CrunchVariable", "CrunchExpr"))) { return(as.vector(var)[ind]) } else { return(var) } }, ind = case_indices, var = values) pre_collation_types <- vapply(values, class, character(1)) values <- collateValues(values_to_fill, case_indices, else_condition, n_rows) if (all(pre_collation_types == "factor")) { type <- "categorical" } else if (is.numeric(values)) { type <- "numeric" } else { type <- "text" } return(list(values = values, type = type)) } collateValues <- function(values_to_fill, case_indices, else_condition, n_rows) { result <- rep(else_condition, n_rows) for (i in seq_along(case_indices)) { vals <- values_to_fill[[i]] if (is.factor(vals)) { vals <- as.character(vals) } result[case_indices[[i]]] <- vals } return(result) }
reorient_volume <- function( volume, Torig ){ order_index <- round((Torig %*% c(1,2,3,0))[1:3]) volume <- aperm(volume, abs(order_index)) sub <- sprintf(c('%d:1', '1:%d')[(sign(order_index) + 3) / 2], dim(volume)) volume <- eval(parse(text = sprintf('volume[%s]', paste(sub, collapse = ',')))) volume }
grenander = function(F, type=c("decreasing", "increasing")) { if( !any(class(F) == "ecdf") ) stop("ecdf object required as input!") type <- match.arg(type) if (type == "decreasing") { ll = gcmlcm(environment(F)$x, environment(F)$y, type="lcm") } else { l = length(environment(F)$y) ll = gcmlcm(environment(F)$x, c(0,environment(F)$y[-l]), type="gcm") } f.knots = ll$slope.knots f.knots = c(f.knots, f.knots[length(f.knots)]) g = list(F=F, x.knots=ll$x.knots, F.knots=ll$y.knots, f.knots=f.knots) class(g) <- "grenander" return(g) } plot.grenander <- function(x, ...) { if (x$f.knots[1] > x$f.knots[2]) main = "Grenander Decreasing Density" else main = "Grenander Increasing Density" par(mfrow=c(1,2)) plot(x$x.knots, x$f.knots, type="s", xlab="x", ylab="fn(x)", main=main, col=4, lwd=2, ...) plot(x$F, do.points=FALSE) lines(x$x.knots, x$F.knots, type='l', col=4, lwd=2) par(mfrow=c(1,1)) }
sarem2srREmod <- function (X, y, ind, tind, n, k, t., nT, w, w2, coef0 = rep(0, 4), hess = FALSE, trace = trace, x.tol = 1.5e-18, rel.tol = 1e-15, method="nlminb", ...) { nam.beta <- dimnames(X)[[2]] nam.errcomp <- c("phi", "psi", "rho", "lambda") myparms0 <- coef0 Vmat <- function(rho, t.) { V1 <- matrix(ncol = t., nrow = t.) for (i in 1:t.) V1[i, ] <- rho^abs(1:t. - i) V <- (1/(1 - rho^2)) * V1 } Vmat.1 <- function(rho, t.) { if(t.==1) {Vmat.1 <- 1} else { Vmat.1 <- matrix(0, ncol = t., nrow = t.) for (i in 2:(t.-1)) Vmat.1[i,i] <- (1-rho^4)/(1-rho^2) Vmat.1[1,1] <- Vmat.1[t.,t.] <- 1 for (j in 1:(t.-1)) Vmat.1[j+1,j] <- -rho for (k in 1:(t.-1)) Vmat.1[k,k+1] <- -rho } return(Vmat.1) } alfa2 <- function(rho) (1 + rho)/(1 - rho) d2 <- function(rho, t.) alfa2(rho) + t. - 1 Jt <- matrix(1, ncol = t., nrow = t.) In <- diag(1, n) det2 <- function(phi, rho, lambda, t., w) (d2(rho, t.) * (1 - rho)^2 * phi + 1) invSigma <- function(phirholambda, n, t., w) { phi <- phirholambda[1] rho <- phirholambda[2] lambda <- phirholambda[3] invVmat <- Vmat.1(rho, t.) BB <- xprodB(lambda, w) chi <- phi/(d2(rho, t.)*(1-rho)^2*phi+1) invSigma <- kronecker((invVmat-chi*(invVmat %*% Jt %*% invVmat)), BB) invSigma } ll.c <- function(phirholambda, y, X, n, t., w, w2, wy) { phi <- phirholambda[1] rho <- phirholambda[2] lambda <- phirholambda[3] psi <- phirholambda[4] sigma.1 <- invSigma(phirholambda, n, t., w2) Ay <- y - psi * wy glsres <- GLSstep(X, Ay, sigma.1) e <- glsres[["ehat"]] s2e <- glsres[["sigma2"]] zero <- t.*ldetB(psi, w) uno <- n/2 * log(1 - rho^2) due <- -n/2 * log(det2(phi, rho, lambda, t., w2)) tre <- -(n * t.)/2 * log(s2e) quattro <- (t.) * ldetB(lambda, w2) cinque <- -1/(2 * s2e) * t(e) %*% sigma.1 %*% e const <- -(n * t.)/2 * log(2 * pi) ll.c <- const + zero + uno + due + tre + quattro + cinque llc <- -ll.c } lower.bounds <- c(1e-08, -0.999, -0.999, -0.999) upper.bounds <- c(1e+09, 0.999, 0.999, 0.999) cA <- cbind(c(1, rep(0,6)), c(0,1,-1,rep(0,4)), c(rep(0,3), 1, -1, rep(0,2)), c(rep(0,5), 1, -1)) cB <- c(0, rep(1,6)) Wy <- function(y, w, tind) { wyt <- function(y, w) { if("listw" %in% class(w)) { wyt <- lag.listw(w, y) } else { wyt <- w %*% y } return(wyt) } wy<-list() for (j in 1:length(unique(tind))) { yT<-y[tind==unique(tind)[j]] wy[[j]] <- wyt(yT, w) } return(unlist(wy)) } GLSstep <- function(X, y, sigma.1) { b.hat <- solve(t(X) %*% sigma.1 %*% X, t(X) %*% sigma.1 %*% y) ehat <- y - X %*% b.hat sigma2ehat <- (t(ehat) %*% sigma.1 %*% ehat)/(n * t.) return(list(betahat=b.hat, ehat=ehat, sigma2=sigma2ehat)) } wy <- Wy(y, w, tind) parscale <- 1/max(myparms0, 0.1) if(method=="nlminb") { optimum <- nlminb(start = myparms0, objective = ll.c, gradient = NULL, hessian = NULL, y = y, X = X, n = n, t. = t., w = w, w2 = w2, wy = wy, scale = parscale, control = list(x.tol = x.tol, rel.tol = rel.tol, trace = trace), lower = lower.bounds, upper = upper.bounds) myll <- -optimum$objective myparms <- optimum$par myHessian <- fdHess(myparms, function(x) -ll.c(x, y, X, n, t., w, w2, wy))$Hessian } else { maxout<-function(x,a) ifelse(x>a, x, a) myparms0 <- maxout(myparms0, 0.01) ll.c2 <- function(phirholambda, y, X, n, t., w, w2, wy) { -ll.c(phirholambda, y, X, n, t., w, w2, wy) } optimum <- maxLik(logLik = ll.c2, grad = NULL, hess = NULL, start=myparms0, method = method, parscale = parscale, constraints=list(ineqA=cA, ineqB=cB), y = y, X = X, n = n, t. = t., w = w, w2 = w2, wy = wy) myll <- optimum$maximum myparms <- optimum$estimate myHessian <- optimum$hessian } sigma.1 <- invSigma(myparms, n, t., w2) Ay <- y - myparms[length(myparms)] * wy beta <- GLSstep(X, Ay, sigma.1) covB <- as.numeric(beta[[3]]) * solve(t(X) %*% sigma.1 %*% X) nvcovpms <- length(nam.errcomp) - 1 covTheta <- try(solve(-myHessian), silent=TRUE) if(class(covTheta) == "try-error") { covTheta <- matrix(NA, ncol=nvcovpms+1, nrow=nvcovpms+1) warning("Hessian matrix is not invertible") } covAR <- covTheta[nvcovpms+1, nvcovpms+1, drop=FALSE] covPRL <- covTheta[1:nvcovpms, 1:nvcovpms, drop=FALSE] betas <- as.vector(beta[[1]]) sigma2 <- as.numeric(beta[["sigma2"]]) arcoef <- myparms[which(nam.errcomp=="lambda")] errcomp <- myparms[which(nam.errcomp!="lambda")] names(betas) <- nam.beta names(arcoef) <- "lambda" names(errcomp) <- nam.errcomp[which(nam.errcomp!="lambda")] dimnames(covB) <- list(nam.beta, nam.beta) dimnames(covAR) <- list(names(arcoef), names(arcoef)) dimnames(covPRL) <- list(names(errcomp), names(errcomp)) RES <- list(betas = betas, arcoef=arcoef, errcomp = errcomp, covB = covB, covAR=covAR, covPRL = covPRL, ll = myll, sigma2 = sigma2) return(RES) }
library(fsdaR) set.seed(1234) n <- 45 a <- 1 b <- 0.8 sig <- 1 seq <- 1:n y <- a + b * seq + sig * rnorm(n) y[round(n/2):n] <- y[round(n/2):n] + 10 out <- ltsts(y, plot=TRUE, trace=TRUE) library(fsdaR) out <- simulate_ts(100, plot=TRUE) out1 <- ltsts(out$y, plot=TRUE, trace=TRUE)
setClass('gchol', representation(.Data= 'numeric', Dim = 'integer', Dimnames = 'list', rank = 'integer')) setGeneric('gchol', function(x, tolerance=1e-10) standardGeneric('gchol'), useAsDefault=FALSE) as.matrix.gchol <- function(x, ones=TRUE, ...) { temp <- matrix([email protected], x@Dim[1], dimnames=x@Dimnames, byrow=TRUE) if (ones) diag(temp) <- 1 temp } setAs('gchol', 'matrix', function(from) as.matrix.gchol(from)) setMethod('gchol', signature(x='matrix'), function(x, tolerance) { d <- dim(x) if (d[1] != d[2]) stop("Cholesky decomposition requires a square matrix") temp <- .C(Cgchol, as.integer(d[1]), x = as.double(x), rank= as.double(tolerance)) dnames <- dimnames(x) if (is.null(dnames)) dnames <- list(NULL, NULL) new('gchol', .Data= temp$x , Dim=d, Dimnames= dnames, rank=as.integer(temp$rank)) }) setMethod('diag', signature(x='gchol'), function(x, nrow, ncol) { d <- x@Dim[1] [email protected][ seq(1, length=d, by=d+1)] }) setMethod('show', 'gchol', function(object) show(as.matrix(object, F))) setMethod('dim', 'gchol', function(x) x@Dim) setMethod('dimnames', 'gchol', function(x) x@Dimnames) setMethod("%*%", signature(x='gchol', y='matrix'), function(x, y) { if (!is.numeric(y)) stop("Matrix multiplication is defined only for numeric objects") dy <- dim(y) dx <- dim(x) ldy <- length(dy) if (ldy!=2) dy <- c(length(y), 1) if (dx[2] != dy[1]) stop("Number of columns of x should be the same as number of rows of y") if (any(diag(x) < 0)) stop("gchol matrix does not have a Cholesky repres entation: no matrix product is possible") as.matrix(x) %*% (sqrt(diag(x)) * y) }) setMethod("%*%", signature(x='matrix', y='gchol'), function(x, y) { if (!is.numeric(x)) stop("Matrix multiplication is defined only for numeric objects") dy <- dim(y) dx <- dim(x) ldx <- length(dx) if (ldx!=2) dx <- c(length(x), 1) if (dx[2] != dy[1]) stop("Number of columns of x should be the same as number of rows of y") if (any(diag(y) < 0)) stop("gchol matrix does not have a Cholesky repres entation: no matrix product is possible") (y %*% as.matrix(x)) * rep(sqrt(diag(y)), each=ncol(y)) }) setMethod('[', "gchol", function(x, i,j, drop=TRUE) { if (missing(i) && missing(j)) return(x) temp <- matrix([email protected], nrow=x@Dim[1], dimnames=x@Dimnames) if (missing(i)) temp[,j,drop=drop] else { if (missing(j)) temp[i,,drop=drop] else { temp <- temp[i,j,drop=drop] if (length(i)==length(j) && length(i)>1 && all(i==j)) { new("gchol", .Data= as.vector(temp), Dim=dim(temp), Dimnames=dimnames(temp), rank=sum(diag(temp) !=0)) } else temp } } })
stratEst.simulate.check.coefficients <- function( coefficients , covariate_mat , num_strats , names_strategies ){ if( is.matrix( coefficients ) ){ rows_coefficients <- nrow( coefficients ) cols_coefficients <- ncol( coefficients ) if( rows_coefficients != ncol(covariate_mat) ){ stop("stratEst error: Input object 'coefficients' must have as many rows as there are covariates."); } if( cols_coefficients != num_strats ){ stop("stratEst error: Input object 'coefficients' must have as many columns as there are strategies."); } if( any( is.na( coefficients ) ) ){ stop("stratEst error: The input object 'coefficients' cannot contain NA values."); } colnames_coefficients <- colnames(coefficients) rownames_coefficients <- rownames(coefficients) if( is.null(rownames_coefficients) == FALSE ){ num.covariates <- ncol(covariate_mat) names_covariates <- colnames(covariate_mat) coefficient_mat <- coefficients for( v in 1:num.covariates){ if( names_covariates[v] %in% rownames_coefficients ){ coefficient_mat[v,] <- coefficients[names_covariates[v],] }else{ stop(paste("stratEst error: There is a column named '", names_covariates[v] , "' in 'covariates' but no row with this name in 'coefficients'.",sep="")); } } }else{ stop("stratEst error: The row names of the input object 'coefficients' must correspond to the column names of covariates."); } if( is.null(colnames_coefficients) == FALSE ){ for( s in 1:num_strats){ if( names_strategies[s] %in% colnames_coefficients ){ coefficient_mat[,s] <- coefficients[,names_strategies[s]] }else{ stop(paste("stratEst error: There is a strategy named '", names_strategies[s] , "' but no column with this name in 'coefficients'.",sep="")); } } }else{ stop("stratEst error: The column names of the input object 'coefficients' must correspond to the names of the strategies."); } }else{ stop("stratEst error: The input object 'coefficients' has to be a matrix."); } return( coefficient_mat ) }
data(arab); grp.ids = as.factor(c(1, 1, 1, 2, 2, 2)); x = model.matrix(~grp.ids); beta0 = c(NA, 0); fit = nb.glm.test(arab, x, beta0, subset=1:50); print(str(fit)); subset = order(fit$test.results$HOA$p.values)[1:10]; cbind(fit$data$counts[subset,], fit$test.results$HOA[subset,]); subset = order(fit$test.results$LR$p.values)[1:10]; cbind(fit$data$counts[subset,], fit$test.results$LR[subset,]);
ci.mm2 <- function(ind1, ind2, cs = NULL, suffStat) { dataset <- suffStat$dataset y <- dataset[, ind1] x <- dataset[, ind2] if ( is.null(cs) ) { if ( is.numeric(y) ) { mod1 <- lm(y ~., data = data.frame(x) ) a1 <- anova(mod1) p1 <- a1[1, 5] } else if ( is.ordered(y) ) { ds <- data.frame(y = y, x = x) mod1 <- ordinal.reg(y ~., data = ds) mod0 <- ordinal.reg(y ~ 1, ds) t1 <- mod0$devi - mod1$devi dof <- length( mod1$be ) - length( mod0$be ) p1 <- pchisq(t1, dof, lower.tail = FALSE) } if ( is.numeric(x) ) { mod2 <- lm(x ~., data = data.frame(y) ) a2 <- anova(mod2) p2 <- a2[1, 5] } else if ( is.ordered(x) ) { ds <- data.frame(x = x, y = y) mod2 <- ordinal.reg(x ~., data = ds) mod0 <- ordinal.reg(x ~ 1, ds) t2 <- mod0$devi - mod2$devi dof <- length( mod2$be ) - length( mod0$be ) p2 <- pchisq(t2, dof, lower.tail = FALSE) } } else { if ( is.numeric(y) ) { ds <- data.frame(y = y, dataset[, cs], x = x) mod1 <- lm(y ~., data = ds) ds0 <- data.frame(y = y, dataset[, cs]) mod0 <- lm(y ~., data = ds0) a1 <- anova(mod0, mod1) p1 <- a1[2, 6] } else if ( is.ordered(y) ) { ds1 <- data.frame(y = y, dataset[, cs], x = x) mod1 <- ordinal.reg(y ~., data = ds1) ds0 <- data.frame(y = y, dataset[, cs]) mod0 <- ordinal.reg(y ~., data = ds0 ) t1 <- mod0$devi - mod1$devi dof <- length( mod1$be ) - length( mod0$be ) p1 <- pchisq(t1, dof, lower.tail = FALSE) } if ( is.numeric(x) ) { ds <- data.frame(x = x, dataset[, cs], y = y) mod2 <- lm(x ~., data = ds) ds0 <- data.frame(x = x, dataset[, cs]) mod0 <- lm(x ~., data = ds0) a2 <- anova(mod0, mod2) p2 <- a2[2, 6] } else if ( is.ordered(x) ) { ds2 <- data.frame(x = x, dataset[, cs], y = y) mod2 <- ordinal.reg(x ~., data = ds2) ds0 <- data.frame(x = x, dataset[, cs]) mod0 <- ordinal.reg(x ~., data = ds0 ) t2 <- mod0$devi - mod2$devi dof <- length( mod2$be ) - length( mod0$be ) p2 <- pchisq(t2, dof, lower.tail = FALSE) } } min( 2 * min(p1, p2), max(p1, p2) ) }
context("aqp package environment") test_that("defaults", { expect_equal(getOption(".aqp.show.n.cols"), 10) options(.aqp.show.n.cols = 100) expect_equal(getOption(".aqp.show.n.cols"), 100) expect_silent(aqp:::.onLoad("foo","bar")) })
data <- list() data[[1]] <- as.matrix(read.csv(system.file("extdata", "dataset1.csv", package = "coca"), row.names = 1)) data[[2]] <- as.matrix(read.csv(system.file("extdata", "dataset2.csv", package = "coca"), row.names = 1)) data[[3]] <- as.matrix(read.csv(system.file("extdata", "dataset3.csv", package = "coca"), row.names = 1)) outputBuildMOC <- coca::buildMOC(data, M = 3, K = 5, distances = "cor") moc <- outputBuildMOC$moc datasetIndicator <- outputBuildMOC$datasetIndicator true_labels <- as.matrix(read.csv(system.file("extdata", "cluster_labels.csv", package = "coca"), row.names = 1)) annotations <- data.frame(true_labels = as.factor(true_labels)) coca::plotMOC(moc, datasetIndicator, annotations = annotations) true_labels <- as.matrix(read.csv(system.file("extdata", "cluster_labels.csv", package = "coca"), row.names = 1)) annotations <- data.frame(true_labels = as.factor(true_labels)) datasetNames <- c(rep("A", 5), rep("B", 5), rep("C", 5)) coca::plotMOC(moc, datasetIndicator, datasetNames = datasetNames, annotations = annotations) coca <- coca::coca(moc, K = 5) ari <- mclust::adjustedRandIndex(true_labels, coca$clusterLabels) ari annotations$coca <- as.factor(coca$clusterLabels) coca::plotMOC(moc, datasetIndicator, datasetNames = datasetNames, annotations = annotations) coca <- coca::coca(moc, maxK = 10, hclustMethod = "average") ari <- mclust::adjustedRandIndex(true_labels, coca$clusterLabels) ari annotations$coca <- as.factor(coca$clusterLabels) coca::plotMOC(moc, datasetIndicator, datasetNames = datasetNames, annotations = annotations)
aSPUsim2 <- function(Y, X, cov = NULL, model=c("gaussian","binomial"), pow=c(1:8, Inf), n.perm=1000){ model = match.arg(model) n <- length(Y) if (is.null(X) && length(X)>0) X=as.matrix(X, ncol=1) k <- ncol(X) if (is.null(cov)){ Xg <- XUs <- X U <- t(Xg) %*% (Y-mean(Y)) yresids <- Y-mean(Y) yfits <- rep(mean(Y), n) Xgb <- apply(X, 2, function(x)(x-mean(x)) ) if( model == "binomial" ) { CovS <- mean(Y)*(1-mean(Y))*(t(Xgb) %*% Xgb) } else { CovS <- var(Y)*(t(Xgb) %*% Xgb) } } else { tdat1 <- data.frame(trait=Y, cov) if(is.null(colnames(cov))) { colnames(tdat1) = c("trait", paste("cov",1:dim(cov)[2],sep="")) } else { colnames(tdat1) = c("trait", colnames(cov)) } fit1 <- glm(trait~., family = model, data=tdat1) yfits <- fitted.values(fit1) yresids <- fit1$residuals Us <- XUs <- matrix(0, nrow=n, ncol=k) Xmus = X for(i in 1:k){ tdat2 <- data.frame(X1=X[,i], cov) fit2 <- glm(X1~., data=tdat2) Xmus[,i] <- fitted.values(fit2) XUs[, i] <- (X[,i] - Xmus[,i]) } U <- t(XUs) %*% (Y - yfits) CovS<-matrix(0, nrow=k, ncol=k) for(i in 1:n) CovS<-CovS + Us[i,] %*% t(Us[i,]) } Ts <- rep(0, length(pow)) for(j in 1:length(pow)){ if (pow[j] < Inf) Ts[j] = sum(U^pow[j]) else Ts[j] = max(abs(U)) } svd.CovS<-svd(CovS) CovSsqrt<-svd.CovS$u %*% diag(sqrt(svd.CovS$d)) T0s = matrix(0, nrow=n.perm, ncol=length(pow)) Y0 = Y for(b in 1:n.perm){ U00<-rnorm(k, 0, 1) U0<-CovSsqrt %*% U00 for(j in 1:length(pow)) if (pow[j] < Inf) T0s[b, j] = sum(U0^pow[j]) else T0s[b, j] = max(abs(U0)) } pPerm0 = rep(NA,length(pow)) for ( j in 1:length(pow)) { pPerm0[j] = sum(abs(Ts[j])<=abs(T0s[,j])) / n.perm P0s = ( ( n.perm - rank( abs(T0s[,j]) ) ) + 1 ) / (n.perm ) if (j == 1 ) minp0 = P0s else minp0[which(minp0>P0s)] = P0s[which(minp0>P0s)] } Paspu <- (sum(minp0 <= min(pPerm0)) + 1) / (n.perm+1) pvs <- c(pPerm0, Paspu) Ts <- c(Ts, min(pPerm0)) names(Ts) <- c(paste("SPU", pow, sep=""), "aSPU") names(pvs) = names(Ts) list(Ts = Ts, pvs = pvs) }
context("nLTTstat") test_that("Identical trees have an nLTTstat of zero", { set.seed(314) p <- ape::rcoal(10) set.seed(314) q <- ape::rcoal(10) expect_equal( 0.0, nLTTstat(tree1 = p, tree2 = p, distance_method = "abs"), tolerance = 0.0001 ) expect_equal( 0.0, nLTTstat(tree1 = p, tree2 = p, distance_method = "squ"), tolerance = 0.0001 ) }) test_that("abs nLTTstat on known tree", { p <- ape::read.tree(text = "((A:1, B:1):2, C:3);") q <- ape::read.tree(text = "((A:2, B:2):1, C:3);") expect_equal( 0.111111, nLTTstat(tree1 = p, tree2 = q, distance_method = "abs"), tolerance = 0.0001 ) }) test_that("squ nLTTstat on known tree", { p <- ape::read.tree(text = "((A:1, B:1):2, C:3);") q <- ape::read.tree(text = "((A:2, B:2):1, C:3);") expect_equal( 0.037, nLTTstat(tree1 = p, tree2 = q, distance_method = "squ"), tolerance = 0.0001 ) }) test_that("nLTTstat abuse", { phylo <- ape::rcoal(10) expect_error( nLTTstat(tree1 = 42, tree2 = phylo, distance_method = "abs"), "nLTTstat: tree1 must be of class 'phylo'" ) expect_error( nLTTstat(tree1 = phylo, tree2 = 42, distance_method = "abs"), "nLTTstat: tree2 must be of class 'phylo'" ) expect_error( nLTTstat(tree1 = phylo, tree2 = phylo, distance_method = "nonsense"), "nLTTstat: distance method unknown" ) })
ruv_svdgridplot <- function (Y.data, Y.space = NULL, rowinfo = NULL, colinfo = NULL, k = 1:3, Z = 1, left.additions = NULL, right.additions = NULL, factor.labels = paste("S.V.", k)) { checks = check.ggplot() & check.gridExtra() if (checks) { get_legend = function(myggplot) { tmp = ggplot_gtable(ggplot_build(myggplot)) leg = which(sapply(tmp$grobs, function(x) x$name) == "guide-box") if (length(leg) != 0) return(tmp$grobs[[leg]]) else return(ggplot() + theme_void()) } if (is.data.frame(Y.space)) Y.space = data.matrix(Y.space) if (is.numeric(Z)) if (length(Z) == 1) Z = matrix(1, nrow(Y.data), 1) if (!is.null(Z)) Y.data = residop(Y.data, Z) if (is.null(Y.space)) Y.space = Y.data if (!is.list(Y.space)) { if (!is.null(Z)) Y.space = residop(Y.space, Z) Y.space = svd(Y.space) } d.scaled = Y.space$d/sqrt(sum(Y.space$d^2)) K = length(k) U = matrix(0, nrow(Y.data), K) V = matrix(0, ncol(Y.data), K) D = rep(0, K) ulim = matrix(0, K, 2) vlim = matrix(0, K, 2) for (i in 1:K) { k1 = floor(abs(k[i])) k2 = ceiling(abs(k[i])) a = c(1 - (abs(k[i]) - k1), abs(k[i]) - k1) a = a/sqrt(sum(a^2)) a[1] = a[1] * sign(k[i])^k1 a[2] = a[2] * sign(k[i])^k2 u = a[1] * Y.space$u[, k1] + a[2] * Y.space$u[, k2] v = a[1] * Y.space$v[, k1] + a[2] * Y.space$v[, k2] ulimvect = a[1] * Y.space$d[k1] * Y.space$u[, k1] + a[2] * Y.space$d[k2] * Y.space$u[, k2] vlimvect = a[1] * Y.space$d[k1] * Y.space$v[, k1] + a[2] * Y.space$d[k2] * Y.space$v[, k2] ulim[i, ] = c(min(ulimvect), max(ulimvect)) vlim[i, ] = c(min(vlimvect), max(vlimvect)) U[, i] = as.vector(Y.data %*% v) V[, i] = as.vector(t(u) %*% Y.data) D[i] = sqrt(a[1]^2 * d.scaled[k1]^2 + a[2]^2 * d.scaled[k2]^2) } if (!is.null(rowinfo)) rowinfo = data.frame(rowinfo) if (!is.null(colinfo)) colinfo = data.frame(colinfo) plots = rep(list(NA), K^2) for (i in 1:K) for (j in 1:K) { if (i == j) { df.rect = data.frame(x = 0, y = 0, xmin = -D[i], ymin = -D[i], xmax = D[i], ymax = D[i]) thisplot = ggplot() + theme_classic() + theme(axis.text.x = element_blank(), axis.ticks.x = element_blank()) + theme(axis.text.y = element_blank(), axis.ticks.y = element_blank()) + theme(axis.line = element_blank()) + xlab(factor.labels[i]) + ylab(factor.labels[i]) + scale_x_continuous(position = "top") + geom_rect(data = df.rect, aes_string(xmin = "xmin", ymin = "ymin", xmax = "xmax", ymax = "ymax"), alpha = 0.4) + coord_cartesian(xlim = c(-1, 1), ylim = c(-1, 1)) plots[[(i - 1) * K + j]] = thisplot } else if (i > j) { df = data.frame(x = U[, j], y = U[, i]) if (!is.null(rowinfo)) df = cbind(df, rowinfo) thisplot = ggplot(data = df, aes_string(x = "x", y = "y")) + theme_bw() + theme(axis.text.x = element_blank(), axis.ticks.x = element_blank(), axis.title.x = element_blank()) + theme(axis.text.y = element_blank(), axis.ticks.y = element_blank(), axis.title.y = element_blank()) + theme(legend.position = "none") + coord_cartesian(xlim = ulim[j, ], ylim = ulim[i, ]) + geom_point() if (!is.null(rowinfo) & is.null(left.additions)) { if (ncol(rowinfo) == 1) left.additions = list(aes(color = rowinfo), labs(color = "")) if (ncol(rowinfo) == 2) left.additions = list(aes(color = rowinfo[[1]], shape = rowinfo[[2]]), labs(color = "", shape = "")) } if (!is.null(left.additions)) thisplot = thisplot + left.additions plots[[(i - 1) * K + j]] = thisplot } else { df = data.frame(x = V[, j], y = V[, i]) if (!is.null(colinfo)) df = cbind(df, colinfo) thisplot = ggplot(df, aes_string(x = "x", y = "y")) + theme_bw() + theme(axis.text.x = element_blank(), axis.ticks.x = element_blank(), axis.title.x = element_blank()) + theme(axis.text.y = element_blank(), axis.ticks.y = element_blank(), axis.title.y = element_blank()) + theme(legend.position = "none") + coord_cartesian(xlim = vlim[j, ], ylim = vlim[i, ]) + geom_point() if (!is.null(colinfo) & is.null(right.additions)) { if (ncol(colinfo) == 1) right.additions = list(aes(color = colinfo, alpha = 0.2), scale_alpha_identity(), labs(color = "")) if (ncol(colinfo) == 2) right.additions = list(aes(color = colinfo[[1]], shape = colinfo[[2]], alpha = 0.2), scale_alpha_identity(), labs(color = "", shape = "")) } if (!is.null(right.additions)) thisplot = thisplot + right.additions plots[[(i - 1) * K + j]] = thisplot } } layout_matrix = kronecker(t(matrix(1:K^2, K, K)), matrix(1, 3, 3)) if (!is.null(left.additions) | !is.null(right.additions)) { layout_matrix = rbind(layout_matrix, K^2 + 1) layout_matrix = cbind(layout_matrix, K^2 + 2) layout_matrix = cbind(layout_matrix, K^2 + 2) layout_matrix[K * 3 + 1, ((K) * 3 + 1):ncol(layout_matrix)] = K^2 + 3 layout_matrix[((K) * 3 + 1):nrow(layout_matrix), K * 3 + (1:2)] = K^2 + 4 plots[[K^2 + 1]] = plots[[K^2 + 2]] = ggplot() + theme_void() if (!is.null(left.additions)) plots[[K^2 + 1]] = get_legend(plots[[K + 1]] + theme(legend.position = "bottom")) if (!is.null(right.additions)) plots[[K^2 + 2]] = get_legend(plots[[2]] + theme(legend.position = "right")) } return(grid.arrange(grobs = plots, layout_matrix = layout_matrix)) } else return(FALSE) }
expected <- eval(parse(text="logical(0)")); test(id=0, code={ argv <- eval(parse(text="list(NULL, NULL)")); do.call(`!=`, argv); }, o=expected);
col2gray <- function(col, method="BT.709") { method <- match.arg(method, c("BT.709", "BT.601", "desaturate", "average", "maximum", "minimum", "red", "green", "blue")) col <- col2rgb(col) / 255 if (method == "BT.709") out <- 0.2126*col["red",] + 0.7152*col["green",] + 0.0722*col["blue",] if (method == "BT.601") out <- 0.299*col["red",] + 0.587*col["green",] + 0.114*col["blue",] if (method == "desaturate") out <- (apply(col, 2, max) + apply(col, 2, min)) / 2 if (method == "average") out <- colMeans(col) if (method == "maximum") out <- apply(col, 2, max) if (method == "minimum") out <- apply(col, 2, min) if (method == "red") out <- col["red",] if (method == "green") out <- col["green",] if (method == "blue") out <- col["blue",] gray(out) }
massSTD <- c(0.01, 0.5, 1, 10, 20, 50, 100, 120, 150, 200, 220) indError <- c(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.2, -0.2) uncert <- c(0.1, 0.1, 0.1, 0.1, 0.1, 0.2, 0.2, 0.3, 0.3, 0.4, 0.5) d <- 0.1 traceability <- 'Set of weights class E2. Certificate number 1473 D-K 17296, 2019-05-10.' MT.XPE.204 <- calibCert(balanceID = 'MT XPE 204', serial = 'B403223982', certificate = 5143, d = d, d.units = 'mg', indError = data.frame(massSTD, indError, uncert), indError.units = c('g', 'mg', 'mg'), rep = data.frame(load = c(0.1, 100, 220), sd = c(0.00, 0.04, 0.03)), rep.units = c('g', 'mg'), eccen = c(100, 0.1), eccen.units = c('g', 'mg'), classSTD = 'E2', traceability = traceability, Temp = c(17.4, 17.9), p = c(750.4, 751.0), h = c(70.5, 71.4), unitsENV = c('deg.C', 'hPa', '%'), institution = 'Instituto Nacional de Metrologia de Colombia', date = '2021-03-18') usethis::use_data(MT.XPE.204, overwrite = TRUE)
"x2u"<- function(x, labels = seq(along = x)) { if(length(labels) != length(x)) stop( "Arguments x and labels not of equal length") rep(labels, x) }
perf_pairwise <- function(y, f, group, metric="ndcg", w=NULL, max_rank=0){ func.name <- switch(metric, conc = "ir_measure_conc", mrr = "ir_measure_mrr", map = "ir_measure_map", ndcg = "ir_measure_ndcg", stop(paste("Metric",metric,"is not supported")) ) if (metric == "conc" && all(is.element(y, 0:1))) { func.name <- "ir_measure_auc" } if (max_rank <= 0) { max_rank <- length(y)+1 } f <- f + 1E-10 * runif(length(f), min=-0.5, max=0.5) measure.by.group <- as.matrix(by(list(y, f), INDICES=group, FUN=get(func.name), max_rank=max_rank)) idx <- which((!is.null(measure.by.group)) & measure.by.group >= 0) if (is.null(w)) { return (mean(measure.by.group[idx])) } else { w.by.group <- tapply(w, group, mean) return (weighted.mean(measure.by.group[idx], w=w.by.group[idx])) } } ir_measure_conc <- function(y.f, max_rank=0) { y <- y.f[[1]] f <- y.f[[2]] tab <- table(y) csum <- cumsum(tab) total.pairs <- sum(tab * (csum - tab)) if (total.pairs == 0) { return (-1.0) } else { return (gbm_conc(y[order(-f)]) / total.pairs) } } ir_measure_auc <- function(y.f, max_rank=0){ y <- y.f[[1]] f <- y.f[[2]] num.pos <- sum(y>0) if (length(f) <= 1 || num.pos == 0 || num.pos == length(f)) { return (-1.0) } else { return (gbm_roc_area(obs=y, pred=f)) } } ir_measure_mrr <- function(y.f, max_rank) { y <- y.f[[1]] f <- y.f[[2]] num.pos <- sum(y>0) if (length(f) <= 1 || num.pos == 0 || num.pos == length(f)) { return (-1.0) } ord <- order(f, decreasing=TRUE) min.idx.pos <- min(which(y[ord]>0)) if (min.idx.pos <= max_rank) { return (1.0 / min.idx.pos) } else { return (0.0) } } ir_measure_map <- function(y.f, max_rank=0) { y <- y.f[[1]] f <- y.f[[2]] ord <- order(f, decreasing=TRUE) idx.pos <- which(y[ord]>0) num.pos <- length(idx.pos) if (length(f) <= 1 || num.pos == 0 || num.pos == length(f)) { return (-1.0) } return (sum((1:length(idx.pos))/idx.pos) / num.pos) } ir_measure_ndcg <- function(y.f, max_rank) { y <- y.f[[1]] f <- y.f[[2]] if (length(f) <= 1 || all(diff(y)==0)) return (-1.0) num.items <- min(length(f), max_rank) ord <- order(f, decreasing=TRUE) dcg <- sum(y[ord][1:num.items] / log2(2:(num.items+1))) ord.max <- order(y, decreasing=TRUE) dcg.max <- sum(y[ord.max][1:num.items] / log2(2:(num.items+1))) return (dcg / dcg.max) }
ml_lrnm <- function(...){ ml_lvm(..., within_latent = "ggm", between_latent = "ggm", within_residual = "ggm", between_residual = "ggm") }
check_sibling_order <- function(data, outcome, pair_identifiers, row) { data <- data[row,] outcome1 <- data[, base::paste0(outcome, pair_identifiers[1])] outcome2 <- data[, base::paste0(outcome, pair_identifiers[2])] if (outcome1 > outcome2) { data$order <- "s1" } else if (outcome1 < outcome2) { data$order <- "s2" } else if (outcome1 == outcome2) { p <- stats::rbinom(1,1,0.5) if (p) {data$order <- "s1" }else if (!p) {data$order <- "s2"} } return(data) } make_mean_diffs <- function(data, id, sex, race, demographics, variable, pair_identifiers, row) { S1 <- base::paste0(variable, pair_identifiers[1]) S2 <- base::paste0(variable, pair_identifiers[2]) sexS1 <- base::paste0(sex, pair_identifiers[1]) sexS2 <- base::paste0(sex, pair_identifiers[2]) raceS1 <- base::paste0(race, pair_identifiers[1]) raceS2 <- base::paste0(race, pair_identifiers[2]) data <- data[row,] if (data[, "order"] == "s1") { diff <- data[[S1]] - data[[S2]] mean <- base::mean(c(data[[S1]], data[[S2]])) output <- data.frame(id = data[[id]], variable_1 = data[[S1]], variable_2 = data[[S2]], variable_diff = diff, variable_mean = mean) } else if (data[, "order"] == "s2") { diff <- data[[S2]] - data[[S1]] mean <- base::mean(c(data[[S1]], data[[S2]])) output <- data.frame(id = data[[id]], variable_1 = data[[S2]], variable_2 = data[[S1]], variable_diff = diff, variable_mean = mean) } names(output) <- c("id", paste0(variable, "_1"), paste0(variable, "_2"), paste0(variable, "_diff"), paste0(variable, "_mean")) if (demographics == "race") { if (data[, "order"] == "s1") { output_demographics <- data.frame(race_1 = data[[raceS1]], race_2 = data[[raceS2]]) } else if (data[, "order"] == "s2") { output_demographics <- data.frame(race_1 = data[[raceS2]], race_2 = data[[raceS1]]) } } else if (demographics == "sex") { if (data[, "order"] == "s1") { output_demographics <- data.frame(sex_1 = data[[sexS1]], sex_2 = data[[sexS2]]) } else if (data[, "order"] == "s2") { output_demographics <- data.frame(sex_1 = data[[sexS2]], sex_2 = data[[sexS1]]) } } else if (demographics == "both") { if (data[, "order"] == "s1") { output_demographics <- data.frame(sex_1 = data[[sexS1]], sex_2 = data[[sexS2]], race_1 = data[[raceS1]], race_2 = data[[raceS2]]) } else if (data[, "order"] == "s2") { output_demographics <- data.frame(sex_1 = data[[sexS2]], sex_2 = data[[sexS1]], race_1 = data[[raceS2]], race_2 = data[[raceS1]]) } } if (exists("output_demographics")) { output <- base::cbind(output, output_demographics) } return(output) } check_discord_errors <- function(data, id, sex, race, pair_identifiers) { if (!id %in% base::names(data)) { stop(paste0("The kinship pair ID \"", id, "\" is not valid. Please check that you have the correct column name.")) } if (!base::is.null(sex) && base::sum(base::grepl(sex, base::names(data))) == 0) { stop(paste0("The kinship pair sex identifier \"", sex, "\" is not appropriately defined. Please check that you have the correct column name.")) } if (!base::is.null(race) && base::sum(base::grepl(race, base::names(data))) == 0) { stop(paste0("The kinship pair race identifier \"", race, "\" is not appropriately defined. Please check that you have the correct column name.")) } if (base::sum(base::grepl(pair_identifiers[1], base::names(data))) == 0 | base::sum(base::grepl(pair_identifiers[2], base::names(data))) == 0) { stop(paste0("Please check that the kinship pair identifiers \"", pair_identifiers[1], "\" and \"", pair_identifiers[2],"\" are valid, i.e. ensure that you have the correct labels for each kin.")) } if (!base::is.null(sex) & !base::is.null(race) && sex == race) { stop("Please check that your sex and race variables are not equal.") } }
run_kegg <- function(gene_up,gene_down,geneList=F,pro='test'){ gene_up=unique(gene_up) gene_down=unique(gene_down) gene_diff=unique(c(gene_up,gene_down)) kk.up <- enrichKEGG(gene = gene_up, organism = 'hsa', pvalueCutoff = 0.9, qvalueCutoff =0.9) head(kk.up)[,1:6] kk=kk.up dotplot(kk) kk=DOSE::setReadable(kk, OrgDb='org.Hs.eg.db',keytype='ENTREZID') write.csv(kk@result,paste0(pro,'_kk.up.csv')) kk.down <- enrichKEGG(gene = gene_down, organism = 'hsa', pvalueCutoff = 0.9, qvalueCutoff =0.9) head(kk.down)[,1:6] kk=kk.down dotplot(kk) kk=DOSE::setReadable(kk, OrgDb='org.Hs.eg.db',keytype='ENTREZID') write.csv(kk@result,paste0(pro,'_kk.down.csv')) kk.diff <- enrichKEGG(gene = gene_diff, organism = 'hsa', pvalueCutoff = 0.05) head(kk.diff)[,1:6] kk=kk.diff dotplot(kk) kk=DOSE::setReadable(kk, OrgDb='org.Hs.eg.db',keytype='ENTREZID') write.csv(kk@result,paste0(pro,'_kk.diff.csv')) kegg_diff_dt <- as.data.frame(kk.diff) kegg_down_dt <- as.data.frame(kk.down) kegg_up_dt <- as.data.frame(kk.up) down_kegg<-kegg_down_dt[kegg_down_dt$pvalue<0.01,];down_kegg$group=-1 up_kegg<-kegg_up_dt[kegg_up_dt$pvalue<0.01,];up_kegg$group=1 g_kegg=kegg_plot(up_kegg,down_kegg) print(g_kegg) ggsave(g_kegg,filename = paste0(pro,'_kegg_up_down.png') ) if(geneList){ kk_gse <- gseKEGG(geneList = geneList, organism = 'hsa', nPerm = 1000, minGSSize = 20, pvalueCutoff = 0.9, verbose = FALSE) head(kk_gse)[,1:6] gseaplot(kk_gse, geneSetID = rownames(kk_gse[1,])) gseaplot(kk_gse, 'hsa04110',title = 'Cell cycle') kk=DOSE::setReadable(kk_gse, OrgDb='org.Hs.eg.db',keytype='ENTREZID') tmp=kk@result write.csv(kk@result,paste0(pro,'_kegg.gsea.csv')) down_kegg<-kk_gse[kk_gse$pvalue<0.05 & kk_gse$enrichmentScore < 0,];down_kegg$group=-1 up_kegg<-kk_gse[kk_gse$pvalue<0.05 & kk_gse$enrichmentScore > 0,];up_kegg$group=1 g_kegg=kegg_plot(up_kegg,down_kegg) print(g_kegg) ggsave(g_kegg,filename = paste0(pro,'_kegg_gsea.png')) } } run_go <- function(gene_up,gene_down,pro='test'){ gene_up=unique(gene_up) gene_down=unique(gene_down) gene_diff=unique(c(gene_up,gene_down)) g_list=list(gene_up=gene_up, gene_down=gene_down, gene_diff=gene_diff) if(T){ go_enrich_results <- lapply( g_list , function(gene) { lapply( c('BP','MF','CC') , function(ont) { cat(paste('Now process ',ont )) ego <- enrichGO(gene = gene, OrgDb = org.Hs.eg.db, ont = ont , pAdjustMethod = "BH", pvalueCutoff = 0.99, qvalueCutoff = 0.99, readable = TRUE) print( head(ego) ) return(ego) }) }) save(go_enrich_results,file =paste0(pro, '_go_enrich_results.Rdata')) } load(file=paste0(pro, '_go_enrich_results.Rdata')) n1= c('gene_up','gene_down','gene_diff') n2= c('BP','MF','CC') for (i in 1:3){ for (j in 1:3){ fn=paste0(pro, '_dotplot_',n1[i],'_',n2[j],'.png') cat(paste0(fn,'\n')) png(fn,res=150,width = 1080) print( dotplot(go_enrich_results[[i]][[j]] )) dev.off() } } } kegg_plot <- function(up_kegg,down_kegg){ dat=rbind(up_kegg,down_kegg) colnames(dat) dat$pvalue = -log10(dat$pvalue) dat$pvalue=dat$pvalue*dat$group dat=dat[order(dat$pvalue,decreasing = F),] g_kegg<- ggplot(dat, aes(x=reorder(Description,order(pvalue, decreasing = F)), y=pvalue, fill=group)) + geom_bar(stat="identity") + scale_fill_gradient(low="blue",high="red",guide = FALSE) + scale_x_discrete(name ="Pathway names") + scale_y_continuous(name ="log10P-value") + coord_flip() + theme_bw()+theme(plot.title = element_text(hjust = 0.5))+ ggtitle("Pathway Enrichment") }
NULL load_mbb_pbp <- function(seasons = most_recent_mbb_season(),..., dbConnection = NULL, tablename = NULL) { old <- options(list(stringsAsFactors = FALSE, scipen = 999)) on.exit(options(old)) dots <- rlang::dots_list(...) loader <- rds_from_url if (!is.null(dbConnection) && !is.null(tablename)) in_db <- TRUE else in_db <- FALSE if(isTRUE(seasons)) seasons <- 2006:most_recent_mbb_season() stopifnot(is.numeric(seasons), seasons >= 2006, seasons <= most_recent_mbb_season()) urls <- paste0("https://raw.githubusercontent.com/saiemgilani/hoopR-data/master/mbb/pbp/rds/play_by_play_",seasons,".rds") p <- NULL if (is_installed("progressr")) p <- progressr::progressor(along = seasons) out <- lapply(urls, progressively(loader, p)) out <- data.table::rbindlist(out, use.names = TRUE, fill = TRUE) if (in_db) { DBI::dbWriteTable(dbConnection, tablename, out, append = TRUE) out <- NULL } else { class(out) <- c("tbl_df","tbl","data.table","data.frame") } out } NULL load_mbb_team_box <- function(seasons = most_recent_mbb_season(), ..., dbConnection = NULL, tablename = NULL) { old <- options(list(stringsAsFactors = FALSE, scipen = 999)) on.exit(options(old)) dots <- rlang::dots_list(...) loader <- rds_from_url if (!is.null(dbConnection) && !is.null(tablename)) in_db <- TRUE else in_db <- FALSE if(isTRUE(seasons)) seasons <- 2003:most_recent_mbb_season() stopifnot(is.numeric(seasons), seasons >= 2003, seasons <= most_recent_mbb_season()) urls <- paste0("https://raw.githubusercontent.com/saiemgilani/hoopR-data/master/mbb/team_box/rds/team_box_",seasons,".rds") p <- NULL if (is_installed("progressr")) p <- progressr::progressor(along = seasons) out <- lapply(urls, progressively(loader, p)) out <- data.table::rbindlist(out, use.names = TRUE, fill = TRUE) if (in_db) { DBI::dbWriteTable(dbConnection, tablename, out, append = TRUE) out <- NULL } else { class(out) <- c("tbl_df","tbl","data.table","data.frame") } out } NULL load_mbb_player_box <- function(seasons = most_recent_mbb_season(), ..., dbConnection = NULL, tablename = NULL) { old <- options(list(stringsAsFactors = FALSE, scipen = 999)) on.exit(options(old)) dots <- rlang::dots_list(...) loader <- rds_from_url if (!is.null(dbConnection) && !is.null(tablename)) in_db <- TRUE else in_db <- FALSE if(isTRUE(seasons)) seasons <- 2003:most_recent_mbb_season() stopifnot(is.numeric(seasons), seasons >= 2003, seasons <= most_recent_mbb_season()) urls <- paste0("https://raw.githubusercontent.com/saiemgilani/hoopR-data/master/mbb/player_box/rds/player_box_",seasons,".rds") p <- NULL if (is_installed("progressr")) p <- progressr::progressor(along = seasons) out <- lapply(urls, progressively(loader, p)) out <- data.table::rbindlist(out, use.names = TRUE, fill = TRUE) if (in_db) { DBI::dbWriteTable(dbConnection, tablename, out, append = TRUE) out <- NULL } else { class(out) <- c("tbl_df","tbl","data.table","data.frame") } out } NULL load_mbb_schedule <- function(seasons = most_recent_mbb_season(), ..., dbConnection = NULL, tablename = NULL) { old <- options(list(stringsAsFactors = FALSE, scipen = 999)) on.exit(options(old)) dots <- rlang::dots_list(...) loader <- rds_from_url if (!is.null(dbConnection) && !is.null(tablename)) in_db <- TRUE else in_db <- FALSE if(isTRUE(seasons)) seasons <- 2002:most_recent_mbb_season() stopifnot(is.numeric(seasons), seasons >= 2002, seasons <= most_recent_mbb_season()) urls <- paste0("https://raw.githubusercontent.com/saiemgilani/hoopR-data/master/mbb/schedules/rds/mbb_schedule_",seasons,".rds") p <- NULL if (is_installed("progressr")) p <- progressr::progressor(along = seasons) out <- lapply(urls, progressively(loader, p)) out <- data.table::rbindlist(out, use.names = TRUE, fill = TRUE) if (in_db) { DBI::dbWriteTable(dbConnection, tablename, out, append = TRUE) out <- NULL } else { class(out) <- c("tbl_df","tbl","data.table","data.frame") } out } load_mbb_games <- function(){ .url <- "https://raw.githubusercontent.com/saiemgilani/hoopR-data/master/mbb/mbb_games_in_data_repo.csv" dat <- hoopR::csv_from_url(.url) return (dat) } update_mbb_db <- function(dbdir = ".", dbname = "hoopR_db", tblname = "hoopR_mbb_pbp", force_rebuild = FALSE, db_connection = NULL) { old <- options(list(stringsAsFactors = FALSE, scipen = 999)) on.exit(options(old)) if (!is_installed("DBI") | !is_installed("purrr") | (!is_installed("RSQLite") & is.null(db_connection))) { usethis::ui_stop("{my_time()} | Packages {usethis::ui_value('DBI')}, {usethis::ui_value('RSQLite')} and {usethis::ui_value('purrr')} required for database communication. Please install them.") } if (any(force_rebuild == "NEW")) { usethis::ui_stop("{my_time()} | The argument {usethis::ui_value('force_rebuild = NEW')} is only for internal usage!") } if (!(is.logical(force_rebuild) | is.numeric(force_rebuild))) { usethis::ui_stop("{my_time()} | The argument {usethis::ui_value('force_rebuild')} has to be either logical or numeric!") } if (!dir.exists(dbdir) & is.null(db_connection)) { usethis::ui_oops("{my_time()} | Directory {usethis::ui_path(dbdir)} doesn't exist yet. Try creating...") dir.create(dbdir) } if (is.null(db_connection)) { connection <- DBI::dbConnect(RSQLite::SQLite(), glue::glue("{dbdir}/{dbname}")) } else { connection <- db_connection } if (!DBI::dbExistsTable(connection, tblname)) { build_mbb_db(tblname, connection, rebuild = "NEW") } else if (DBI::dbExistsTable(connection, tblname) & all(force_rebuild != FALSE)) { build_mbb_db(tblname, connection, rebuild = force_rebuild) } user_message("Checking for missing completed games...", "todo") completed_games <- load_mbb_games() %>% dplyr::filter(.data$season >= 2006) %>% dplyr::pull(.data$game_id) missing <- get_missing_mbb_games(completed_games, connection, tblname) if(length(missing) > 16) { build_mbb_db(tblname, connection, show_message = FALSE, rebuild = as.numeric(unique(stringr::str_sub(missing, 1, 4)))) missing <- get_missing_mbb_games(completed_games, connection, tblname) } message_completed("Database update completed", in_builder = TRUE) usethis::ui_info("{my_time()} | Path to your db: {usethis::ui_path(DBI::dbGetInfo(connection)$dbname)}") if (is.null(db_connection)) DBI::dbDisconnect(connection) } build_mbb_db <- function(tblname = "hoopR_mbb_pbp", db_conn, rebuild = FALSE, show_message = TRUE) { old <- options(list(stringsAsFactors = FALSE, scipen = 999)) on.exit(options(old)) valid_seasons <- load_mbb_games() %>% dplyr::filter(.data$season >= 2006) %>% dplyr::group_by(.data$season) %>% dplyr::summarise() %>% dplyr::ungroup() if (all(rebuild == TRUE)) { usethis::ui_todo("{my_time()} | Purging the complete data table {usethis::ui_value(tblname)} in your connected database...") DBI::dbRemoveTable(db_conn, tblname) seasons <- valid_seasons %>% dplyr::pull("season") usethis::ui_todo("{my_time()} | Starting download of {length(seasons)} seasons between {min(seasons)} and {max(seasons)}...") } else if (is.numeric(rebuild) & all(rebuild %in% valid_seasons$season)) { string <- paste0(rebuild, collapse = ", ") if (show_message){usethis::ui_todo("{my_time()} | Purging {string} season(s) from the data table {usethis::ui_value(tblname)} in your connected database...")} DBI::dbExecute(db_conn, glue::glue_sql("DELETE FROM {`tblname`} WHERE season IN ({vals*})", vals = rebuild, .con = db_conn)) seasons <- valid_seasons %>% dplyr::filter(.data$season %in% rebuild) %>% dplyr::pull("season") usethis::ui_todo("{my_time()} | Starting download of the {string} season(s)...") } else if (all(rebuild == "NEW")) { usethis::ui_info("{my_time()} | Can't find the data table {usethis::ui_value(tblname)} in your database. Will load the play by play data from scratch.") seasons <- valid_seasons %>% dplyr::pull("season") usethis::ui_todo("{my_time()} | Starting download of {length(seasons)} seasons between {min(seasons)} and {max(seasons)}...") } else { seasons <- NULL usethis::ui_oops("{my_time()} | At least one invalid value passed to argument {usethis::ui_code('force_rebuild')}. Please try again with valid input.") } if (!is.null(seasons)) { load_mbb_pbp(seasons, dbConnection = db_conn, tablename = tblname) } } get_missing_mbb_games <- function(completed_games, dbConnection, tablename) { db_ids <- dplyr::tbl(dbConnection, tablename) %>% dplyr::select("game_id") %>% dplyr::distinct() %>% dplyr::collect() %>% dplyr::pull("game_id") need_scrape <- completed_games[!completed_games %in% db_ids] usethis::ui_info("{my_time()} | You have {length(db_ids)} games and are missing {length(need_scrape)}.") return(need_scrape) }
multinomT <- function(Yp, Xarray, xvec, jacstack, start=NA, nobsvec, fixed.df = NA) { obs <- dim(Yp)[1]; cats <- dim(Yp)[2]; mcats <- cats-1; nvars <- dim(Xarray)[2]; if (any(xvec[,cats] != 0)) { stop("(multinomT): invalid specification of Xarray (regressors not allowed for last category"); } smdim <- dim(jacstack); stack.index <- matrix(FALSE, smdim[2], smdim[3]); for (i in 1:smdim[2]) for (j in 1:smdim[3]) { stack.index[i,j] <- !all(jacstack[,i,j] == 0); } if (sum(stack.index) != sum(xvec != 0)) { print("multinomT: xvec is:"); print(xvec); print("multinomT: stack.index is:"); print(stack.index); stop("(multinomT): jacstack structure check failed"); } kY <- matrix(nrow=obs,ncol=mcats) indx1 <- Yp==0; indx1vec <- apply(indx1,1,sum) > 0; if (sum(indx1) > 0) { cat("multinomT: Need to remove 0 in multinomT transformation\n"); } Yp[indx1] <- .5/nobsvec[indx1vec]; kY <- log(Yp[,1:mcats]/Yp[,cats]) if (is.na(start[1])) { mt.obj <- mt.mle(Xarray=Xarray, xvec=xvec, jacstack=jacstack, y=kY, stack.index=stack.index, fixed.df=fixed.df); } else { mt.obj <- mt.mle(Xarray=Xarray, xvec=xvec, jacstack=jacstack, y=kY, stack.index=stack.index, start=start, fixed.df=fixed.df); } tvec <- mnl.xvec.mapping(forward=FALSE,xvec,xvec, mt.obj$dp$beta, cats, nvars); pred <- mnl.probfunc(Yp, Yp==Yp, Xarray, tvec) return( list(call=mt.obj$call, logL=mt.obj$logL, deviance=mt.obj$deviance, par=mt.obj$dp, se=mt.obj$se, optim=mt.obj$optim, pred=pred)) } mt.mle <- function (Xarray, xvec, jacstack, y, stack.index, start = NA, freq =NA, fixed.df = NA, trace = FALSE, method = "BFGS", control = list(maxit = 600,trace=0)) { nvars <- dim(Xarray)[2]; Diag <- function(x) diag(x, nrow = length(x), ncol = length(x)) y.names <- dimnames(y)[[2]] y <- as.matrix(y) if (missing(freq) | is.na(freq)) { freq <- rep(1, nrow(y)) } d <- ncol(y) n <- sum(freq) m <- sum(xvec == 1) + length(unique(xvec[xvec>1])); if (is.na(start[1])) { cat("mt.mle: I don't know how to generate starting values in the general case\n"); stop(); } beta <- start$beta Omega <- start$Omega if (!is.na(fixed.df)) start$df <- fixed.df; df <- start$df Oinv <- solve(Omega, tol=1e-100) Oinv <- (Oinv + t(Oinv))/2 upper <- chol(Oinv) D <- diag(upper) A <- upper/D D <- D^2 if (d > 1) { param <- c(beta, -0.5 * log(D), A[!lower.tri(A, diag = TRUE)]) } else { param <- c(beta, -0.5 * log(D)) } if (is.na(fixed.df)) param <- c(param, log(df)) opt <- optim(param, fn = mt.dev, method = method, control = control, hessian = TRUE, Xarray=Xarray, xvec=xvec, jacstack=jacstack, y = y, stack.index = stack.index, nvars = nvars, freq = freq, trace = trace, fixed.df = fixed.df) dev <- opt$value param <- opt$par if (trace) { cat("mt.mle: Message from optimization routine:", opt$message, "\n") cat("mt.mle: deviance:", dev, "\n") } beta <- param[1:m] ; D <- exp(-2 * param[(m + 1):(m + d)]) if (d > 1) { A <- diag(d) A[!lower.tri(A, diag = TRUE)] <- param[(m + d + 1):(m + d + d * (d - 1)/2)] i0 <- m + d + d * (d - 1)/2 } else { i0 <- m + 1 A <- as.matrix(1) } if (is.na(fixed.df)) { df <- exp(param[i0 + 1]) } else { df <- fixed.df } Ainv <- backsolve(A, diag(d)) Omega <- Ainv %*% Diag(1/D) %*% t(Ainv) dimnames(Omega) <- list(y.names, y.names) info <- opt$hessian/2 if (all(is.finite(info))) { qr.info <- qr(info) info.ok <- (qr.info$rank == length(param)) } else { info.ok <- FALSE } if (info.ok) { se2 <- diag(solve(qr.info)) if (min(se2) < 0) { se <- NA } else { se <- sqrt(se2) se.beta <- se[1:m] ; se.df <- df * se[i0 + 1] se <- list(beta = se.beta, df = se.df, info = info) } } else { se <- NA } dp <- list(beta = beta, Omega = Omega, df = df) list(call = match.call(), logL = -0.5 * dev, deviance = dev, dp = dp, se = se, optim = opt) } mt.dev <- function (param, Xarray, xvec, jacstack, y, stack.index, nvars, freq, fixed.df = NA, trace = FALSE) { Diag <- function(x) diag(x, nrow = length(x), ncol = length(x)) d <- ncol(y) n <- sum(freq) m <- sum(xvec == 1) + length(unique(xvec[xvec>1])); beta <- param[1:m]; D <- exp(-2 * param[(m + 1):(m + d)]) if (d > 1) { A <- diag(d) A[!lower.tri(A, diag = TRUE)] <- param[(m + d + 1):(m + d + d * (d - 1)/2)] i0 <- m + d + d * (d - 1)/2 } else { i0 <- m + 1 A <- as.matrix(1) } eta <- rep(0,d); if (is.na(fixed.df)) { df <- exp(param[i0 + 1]) } else { df <- fixed.df } Oinv <- t(A) %*% Diag(D) %*% A tvec <- mnl.xvec.mapping(forward=FALSE, xvec, xvec, beta, d+1, nvars); ylinpred <- y; if (dim(tvec)[1] == 1) { for (j in 1:d) { ylinpred[,j] <- Xarray[,,j] * tvec[,j]; } } else { for (j in 1:d) { ylinpred[,j] <- Xarray[,,j] %*% tvec[,j]; } } u <- y - ylinpred ; Q <- apply((u %*% Oinv) * u, 1, sum) L <- as.vector(u %*% eta) logDet <- sum(log(df * pi/D)) dev <- (n * (2 * lgamma(df/2) + logDet - 2 * lgamma((df + d)/2)) + (df + d) * sum(freq * log(1 + Q/df)) - 2 * sum(freq * log(2 * pt(L * sqrt((df + d)/(Q + df)), df + d)))) if (trace) cat("mt.dev: ", dev, "\n") dev } mt.dev.grad <- function (param, Xarray, xvec, jacstack, y, stack.index, nvars, freq, fixed.df = NA, trace = FALSE) { Diag <- function(x) diag(x, nrow = length(x), ncol = length(x)) d <- ncol(y) n <- sum(freq) m <- sum(xvec == 1) + length(unique(xvec[xvec>1])); nvarsunique <- dim(jacstack)[2]; beta <- param[1:m]; D <- exp(-2 * param[(m + 1):(m + d)]) if (d > 1) { A <- diag(d) A[!lower.tri(A, diag = TRUE)] <- param[(m + d + 1):(m + d + d * (d - 1)/2)] i0 <- m + d + d * (d - 1)/2 } else { i0 <- m + d A <- as.matrix(1) } eta <- rep(0,d); if (is.na(fixed.df)) df <- exp(param[i0 + 1]) else df <- fixed.df tA <- t(A) Oinv <- tA %*% Diag(D) %*% A tvec <- mnl.xvec.mapping(forward=FALSE, xvec, xvec, beta, d+1, nvars); ylinpred <- y; if (dim(tvec)[1] == 1) { for (j in 1:d) { ylinpred[,j] <- Xarray[,,j] * tvec[,j]; } } else { for (j in 1:d) { ylinpred[,j] <- Xarray[,,j] %*% tvec[,j]; } } u <- y - ylinpred ; Q <- as.vector(apply((u %*% Oinv) * u, 1, sum)) L <- as.vector(u %*% eta) t. <- L * sqrt((df + d)/(Q + df)) dlogft <- -(df + d)/(2 * df * (1 + Q/df)) dt.dQ <- (-0.5) * L * sqrt(df + d)/(Q + df)^1.5 T. <- pt(t., df + d) dlogT. <- dt(t., df + d)/T. u.freq <- u * freq fooA <- matrix(0, nvarsunique, d); for (j in 1:d) { fooA[,j] <- t(jacstack[,,j]) %*% (u.freq * (dlogft + dlogT. * dt.dQ)); } Dbeta <- -2 * fooA %*% Oinv if (d > 1) { M <- 2 * (Diag(D) %*% A %*% t(u * dlogft) %*% u.freq + Diag(D) %*% A %*% t(u * dlogT. * dt.dQ) %*% u.freq) DA <- M[!lower.tri(M, diag = TRUE)] } else DA <- NULL M <- (A %*% t(u * dlogft) %*% u.freq %*% tA + A %*% t(u * dlogT. * dt.dQ) %*% u.freq %*% tA) if (d > 1) DD <- diag(M) + 0.5 * n/D else DD <- as.vector(M + 0.5 * n/D) grad <- (-2) * c(Dbeta[stack.index[,-(d+1)]], DD * (-2 * D), DA) if (is.na(fixed.df)) { dlogft.ddf <- 0.5 * (digamma((df + d)/2) - digamma(df/2) - d/df + (df + d) * Q/((1 + Q/df) * df^2) - log(1 + Q/df)) eps <- 1e-04 T.eps <- pt(L * sqrt((df + eps + d)/(Q + df + eps)), df + eps + d) dlogT.ddf <- (log(T.eps) - log(T.))/eps Ddf <- sum((dlogft.ddf + dlogT.ddf) * freq) grad <- c(grad, -2 * Ddf * df) } if (trace) cat("mt.dev.grad: norm is ", sqrt(sum(grad^2)), "\n") return(grad) }