code
stringlengths
1
13.8M
NULL if (getRversion() >= "2.15.1") utils::globalVariables(c(".", "n"))
boolSkip=F test_that("Check 25.1 - getUtopiaPayoff - 3 players",{ if(boolSkip){ skip("Test was skipped") } v <- c(0,0,0,40,50,20,100) result = getUtopiaPayoff(v) expect_equal(result, c(80,50,60) ) }) test_that("Check 25.2 - getUtopiaPayoff - 3 players",{ if(boolSkip){ skip("Test was skipped") } v <- c(0,0,0,6,5,5,10) result = getUtopiaPayoff(v) expect_equal(result, c(5,5,4) ) }) test_that("Check 25.3 - getUtopiaPayoff - 3 players",{ if(boolSkip){ skip("Test was skipped") } v <- c(0, 0, 0, 60, 60, 60, 72) result = getUtopiaPayoff(v) expect_equal(result, c(12,12,12) ) }) test_that("Check 25.4 - getUtopiaPayoff - 3 players - example from TUGLAB",{ if(boolSkip){ skip("Test was skipped") } v <- c(0, 0, 0, 9, 4, 7, 11) result = getUtopiaPayoff(v) expect_equal(result, c(4,7,2) ) }) test_that("Check 25.5 - getUtopiaPayoff - 3 players - example from TUGLAB modified I",{ if(boolSkip){ skip("Test was skipped") } v <- c(3, 0, 0, 9, 4, 7, 11) result = getUtopiaPayoff(v) expect_equal(result, c(4,7,2) ) }) test_that("Check 25.6 - getUtopiaPayoff - 3 players - example from TUGLAB modified II",{ if(boolSkip){ skip("Test was skipped") } v <- c(3, 1, 2, 9, 4, 7, 11) result = getUtopiaPayoff(v) expect_equal(result, c(4,7,2) ) }) test_that("Check 25.7 - getUtopiaPayoff - 3 players - example from TUGLAB modified III",{ if(boolSkip){ skip("Test was skipped") } v <- c(3, 6, 2, 9, 4, 7, 11) result = getUtopiaPayoff(v) expect_equal(result, c(4,7,2) ) }) test_that("Check 25.8 - getUtopiaPayoff - 3 players - example from TUGLAB modified IV",{ if(boolSkip){ skip("Test was skipped") } v <- c(3, 6, 1, 9, 4, 7, 11) result = getUtopiaPayoff(v) expect_equal(result, c(4,7,2) ) }) test_that("Check 25.9 - getUtopiaPayoff - 4 players",{ if(boolSkip){ skip("Test was skipped") } v <- c(0,0,0,0,7,7,7,7,7,7,12,12,12,12,22) result = getUtopiaPayoff(v) expect_equal(result, c(10,10,10,10) ) }) test_that("Check 25.10 - getUtopiaPayoff - 4 players",{ if(boolSkip){ skip("Test was skipped") } v <- c(2,5,2,5,7,7,7,7,7,7,12,12,12,12,22) result = getUtopiaPayoff(v) expect_equal(result, c(10,10,10,10) ) }) test_that("Check 25.11 - getUtopiaPayoff - 4 players",{ if(boolSkip){ skip("Test was skipped") } v <- c(2,5,2,5,7,7,7,7,7,7,10,11,12,13,22) result = getUtopiaPayoff(v) expect_equal(result, c(9,10,11,12) ) }) test_that("Check 25.12 - getUtopiaPayoff - 4 players",{ if(boolSkip){ skip("Test was skipped") } v <- c(2,5,2,5,7,8,7,9,7,5,10,11,12,13,22) result = getUtopiaPayoff(v) expect_equal(result, c(9,10,11,12) ) }) test_that("Check 25.13 - getUtopiaPayoff - 4 players",{ if(boolSkip){ skip("Test was skipped") } v <- c(0,0,0,0,6,8,7,9,7,5,10,11,12,13,22) result = getUtopiaPayoff(v) expect_equal(result, c(9,10,11,12) ) }) test_that("Check 25.14 - getUtopiaPayoff - 5 players",{ if(boolSkip){ skip("Test was skipped") } v <- c(0, 0, 0, 0, 0, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72) result = getUtopiaPayoff(v) expect_equal(result, c(0,0,0,0,0) ) }) test_that("Check 25.15 - getUtopiaPayoff - 5 players",{ if(boolSkip){ skip("Test was skipped") } v <- c(73, 0, 72, 74, 75, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 80) result = getUtopiaPayoff(v) expect_equal(result, c(8,8,8,8,8) ) })
RooksNeighFind <- function(vfdf) { if (is.element("PatternCt", colnames(vfdf)) == FALSE) { stop("Must run PatternDetect function first to calculate PatternCt variable") } if (sum(vfdf$PatternCt, na.rm = TRUE) < 1) { stop("Must be at least one candidate (one) in PatternCt column") } vfdfout <- vfdf vfdfout$NeighType <- rep(0, dim(vfdfout)[1]) diffx <- abs(as.numeric(outer(vfdf$colcent, vfdf$colcent, FUN = "-"))) diffx[diffx == 0] <- NA facth <- min(diffx, na.rm = TRUE) diffy <- abs(as.numeric(outer(vfdf$rowcent, vfdf$rowcent, FUN = "-"))) diffy[diffy == 0] <- NA factv <- min(diffy, na.rm = TRUE) if (factv != facth) { stop("Currently, factv must equal facth (see DispField function documentation)") } distmat <- sqrt((outer(vfdfout$colcent, vfdfout$colcent, FUN = "-")^2) + outer(vfdfout$rowcent, vfdfout$rowcent, FUN = "-") ^2) diag(distmat) <- 0 distmat[distmat > factv] <- 0 for (i in 1:dim(vfdfout)[1]) { if (is.na(vfdfout$Pattern[i]) == FALSE & vfdfout$Pattern[i] == "partconv") { vfdfout$NeighType[distmat[i,] > 0] <- 4 } if (is.na(vfdfout$Pattern[i]) == FALSE & vfdfout$Pattern[i] == "partdiv") { vfdfout$NeighType[distmat[i,] > 0] <- 3 } if (is.na(vfdfout$Pattern[i]) == FALSE & vfdfout$Pattern[i] == "convergence") { vfdfout$NeighType[distmat[i,] > 0] <- 2 } if (is.na(vfdfout$Pattern[i]) == FALSE & vfdfout$Pattern[i] == "divergence") { vfdfout$NeighType[distmat[i,] > 0] <- 1 } } return(vfdfout) }
`print.sfts` <- function (x, ...) { if (class(x)[1] == "sfts"){ cat("Sliced functional time series") cat(paste("\n y:", x$yname)) cat(paste("\n x:", x$xname, "\n")) } else { stop("object is not a sliced functional time series.") } }
boot_stat <- function(u,Y_tilde,X,D,epsilon,N3,p,prec,N,sample_mat,generalized,weights,y_grid,phi_n,M_bar,DX){ T_reps = matrix(0,prec,1) b_sample = sample_mat[u,] T_n_grid_b<- matrix(0,prec,1) D_b <- D[ b_sample] W_b <- ((1-D_b)/sum((1-D_b)) - D_b / sum(D_b))*N Y_tilde_b <-Y_tilde[ b_sample] if( generalized =="Add" | generalized =="Mult"){ yy_b <- Y_tilde_b[D_b==1] ypsi_b <- Y_tilde_b[D_b==0] if( generalized =="Add" ){ alpha_b <-mean(yy_b)-mean(ypsi_b) Y_tilde_b[D_b==1] <- Y_tilde_b[D_b==1]-alpha_b }else if( generalized =="Mult"){ alpha_b <-mean(yy_b)/mean(ypsi_b) Y_tilde_b[D_b==1] <- Y_tilde_b[D_b==1]/alpha_b } } for (i in 1:prec){ y <- y_grid[i] eq_1 <- W_b*Y_tilde_b ineq_1 <- - W_b*(y-Y_tilde_b)*(Y_tilde_b <= y) data_test <- cbind(ineq_1,eq_1) N_k = dim(data_test)[2] if( N_k >1){ M_ineq_b = data_test[,1] M_eq_b = data_test[,2] }else{ M_ineq_b = data_test } X_b = as.matrix(X[b_sample,] ) X_mean_b = colMeans(X_b) Sigma_hat_b = var(X_b) if(max(Sigma_hat_b) ==0){Sigma_hat_b =1} r_n = ceiling((N3/2)^(1/2/DX)/2) X_adj_b = pnorm((X_b-X_mean_b)%*%sqrt(Sigma_hat_b^(-1))) res <- c_cube(X_adj_b, N, DX, r_n) g_col_b <- res[[3]] Q_AR_b <- res[[4]] G_X_b <- res[[5]] N_g_b = dim(G_X_b)[2] if( N_k >1){ m_n_b = cbind(M_ineq_b,M_eq_b) }else{ m_n_b = M_ineq_b } N_k_b = dim(data_test)[2] if( is.null( N_k_b)){ N_k_b = 1 } y_b<- Y_tilde[b_sample] D_b <- D[b_sample] sig <- var( y_b) if( N_k ==1){ sigma_1_hat_b = sig }else{ sigma_1_hat_b = diag(rep(sig,N_k )) } S_m_b = matrix(0,N_g_b,1) M_g_b = matrix(0,N,N_g_b * N_k_b) M_bar_b = matrix(0,N_k_b*N_g_b,1) Sigma_bar_b = matrix(0,N_k_b*N_g_b,N_k_b*N_g_b) for (index in 1:N_g_b){ M_temp_b = m_n_b * G_X_b[,index] M_g_b[,((index-1)*N_k_b+1):(index*N_k_b)] = M_temp_b M_bar_b[(N_k*(index-1)+1):(N_k_b*index),1] = sqrt(N)*colMeans(M_temp_b) sigma_n_hat_b = var(M_temp_b) if( sum(diag(sigma_1_hat_b)==0)>0 ){ sigma_n_bar_b = diag(diag(sigma_n_hat_b)) + epsilon * diag(diag(sigma_1_hat_b)+epsilon ) }else{ if( N_k_b ==1){ sigma_n_bar_b = sigma_n_hat_b + epsilon * sigma_1_hat_b }else{ sigma_n_bar_b = diag(diag(sigma_n_hat_b)) + epsilon * diag(diag(sigma_1_hat_b)) } } Sigma_bar_b[(N_k_b*(index-1)+1):(N_k_b*index),(N_k_b*(index-1)+1):(N_k_b*index)] = sigma_n_bar_b } M_boot = (M_bar_b-M_bar[,i]) + phi_n[,i] T_reps[i,1] = T_stat(M_boot,Sigma_bar_b,Q_AR_b,N_g_b,N_k_b,p) } return( as.numeric(max(T_reps[,1])) ) }
library('TreeTools', quietly = TRUE, warn.conflicts = FALSE) library('TreeDist') treesMatchingSplit <- c( AB.CDEF = TreesMatchingSplit(2, 4), ABC.DEF = TreesMatchingSplit(3, 3) ) treesMatchingSplit proportionMatchingSplit <- treesMatchingSplit / NUnrooted(6) proportionMatchingSplit splitInformation <- -log2(proportionMatchingSplit) splitInformation treesMatchingBoth <- TreesConsistentWithTwoSplits(6, 2, 3) combinedInformation <- -log2(treesMatchingBoth / NUnrooted(6)) sharedInformation <- sum(splitInformation) - combinedInformation sharedInformation SplitSharedInformation(n = 6, 2, 3) library('TreeDist') H <- function(inBracket) { expression(paste(italic('H'), plain('('), italic(inBracket), plain(')'))) } oldPar <- par(mar = c(3.1, 0.1, 0, 0.1)) joint <- Entropy(c(1, 2, 1, 2) / 6) plot(0, type = 'n', xlim = c(0, joint), ylim = c(5, 0), axes = FALSE) axis(1, at = c(0, 0.5, 1, 1.5, round(joint, 2))) mtext('Entropy / bits', 1, 2) rect(joint - 1, 3.1, 1, 3.9, col = " rect(0, 0.1, joint - 1, 0.9, col = " rect(1, 1.1, joint, 1.9, col = " rect(joint - 1, 1.1, 1, 1.9, col = " rect(joint - 1, 0.1, 1, 0.9, col = " text(1, 3.5, pos=4, expression(paste(italic(I), plain('('), italic('A;B'), plain(')')))) rect(0, 2.1, joint, 2.9) text(joint / 2, 2.5, expression(paste(italic('H'), plain('('), italic('A, B'), plain(')')))) rect(0, 0.1, 1, 0.9) text(0.5, 0.5, expression(paste(italic('H'), plain('('), italic(A), plain(')')))) rect(joint - 1, 1.1, joint - 0, 1.9) text(joint - 0.5, 1.5, expression(paste(italic('H'), plain('('), italic(B), plain(')')))) rect(0, 4.1, joint - 1, 4.9, col = " rect(1, 4.1, joint, 4.9, col = " text(joint / 2, 4.5, expression(paste(italic('H'['D']), plain('('), italic('A, B'), plain(')')))) par(oldPar)
NHDaux <- function(r,lambdaC, lambdaD,posC,typeC, posD,typeD, T) { posWC<-posC[(posC>=r)&(posC<=(T-r))] typeWC<-typeC[(posC>=r)&(posC<=(T-r))] lambdaWC<-lambdaC[cbind(ceiling(posWC),typeWC)] lWnuC<-sum(1/lambdaWC, na.rm=TRUE) L1D<-1-min(lambdaD)/lambdaD L1C0<-sapply(posWC, FUN = prodN2, r=r,L1D=L1D,posD=posD, typeD=typeD) NHD<-sum(L1C0/lambdaWC) return(c(lWnuC,NHD)) }
layer_batch_normalization <- function(object, axis = -1L, momentum = 0.99, epsilon = 0.001, center = TRUE, scale = TRUE, beta_initializer = "zeros", gamma_initializer = "ones", moving_mean_initializer = "zeros", moving_variance_initializer = "ones", beta_regularizer = NULL, gamma_regularizer = NULL, beta_constraint = NULL, gamma_constraint = NULL, renorm = FALSE, renorm_clipping = NULL, renorm_momentum = 0.99, fused = NULL, virtual_batch_size = NULL, adjustment = NULL, input_shape = NULL, batch_input_shape = NULL, batch_size = NULL, dtype = NULL, name = NULL, trainable = NULL, weights = NULL) { stopifnot(is.null(adjustment) || is.function(adjustment)) create_layer(keras$layers$BatchNormalization, object, list( axis = as.integer(axis), momentum = momentum, epsilon = epsilon, center = center, scale = scale, beta_initializer = beta_initializer, gamma_initializer = gamma_initializer, moving_mean_initializer = moving_mean_initializer, moving_variance_initializer = moving_variance_initializer, beta_regularizer = beta_regularizer, gamma_regularizer = gamma_regularizer, beta_constraint = beta_constraint, gamma_constraint = gamma_constraint, renorm = renorm, renorm_clipping = renorm_clipping, renorm_momentum = renorm_momentum, fused = fused, input_shape = normalize_shape(input_shape), batch_input_shape = normalize_shape(batch_input_shape), batch_size = as_nullable_integer(batch_size), dtype = dtype, name = name, trainable = trainable, virtual_batch_size = as_nullable_integer(virtual_batch_size), adjustment = adjustment, weights = weights )) } layer_layer_normalization <- function( object, axis=-1, epsilon=0.001, center=TRUE, scale=TRUE, beta_initializer="zeros", gamma_initializer="ones", beta_regularizer=NULL, gamma_regularizer=NULL, beta_constraint=NULL, gamma_constraint=NULL, trainable=TRUE, name=NULL ) { create_layer(keras$layers$LayerNormalization, object, list( axis=as.integer(axis), epsilon=epsilon, center=center, scale=scale, beta_initializer=beta_initializer, gamma_initializer=gamma_initializer, beta_regularizer=beta_regularizer, gamma_regularizer=gamma_regularizer, beta_constraint=beta_constraint, gamma_constraint=gamma_constraint, trainable=trainable, name=name )) }
context("postdl_templates") test_that("canNotPostProcess", { dlfiles <- data.frame( platform = LETTERS[1:3], file = file.path( LETTERS[1:3], LETTERS[4:6] ), processed = rep(TRUE, 3), stringsAsFactors = FALSE ) procdlfiles <- noproc_dlfiles(dlfiles) expect_identical(procdlfiles[["processed"]], c("A/D", "B/E", "C/F")) }) test_that("canUnzipFile", { zipf <- system.file("exdata", "samplefiles.zip", package = "binman") ziptemp <- tempfile(fileext = ".zip") on.exit(unlink(ziptemp)) file.copy(zipf, ziptemp) dlfiles <- data.frame( platform = LETTERS[1], file = ziptemp, processed = TRUE, stringsAsFactors = FALSE ) procdlfiles <- unziptar_dlfiles(dlfiles, chmod = TRUE) zfiles <- utils::unzip(ziptemp, list = TRUE) zout <- file.path(dirname(ziptemp), basename(zfiles[["Name"]])) fmode <- file.mode(zout) expect_true(all(file.exists(zout))) if (binman:::get_os() != "win") { expect_identical(fmode, structure(c(493L, 493L), class = "octmode")) } unlink(zout) }) test_that("canUntarFile", { gzipf <- system.file("exdata", "samplefiles.tar.gz", package = "binman") gziptemp <- tempfile(fileext = ".tar.gz") on.exit(unlink(gziptemp)) file.copy(gzipf, gziptemp) dlfiles <- data.frame( platform = LETTERS[1], file = gziptemp, processed = TRUE, stringsAsFactors = FALSE ) procdlfiles <- unziptar_dlfiles(dlfiles, chmod = TRUE) gzfiles <- utils::untar(gziptemp, list = TRUE) gzout <- file.path(dirname(gziptemp), basename(gzfiles)) fmode <- file.mode(gzout) expect_true(all(file.exists(gzout))) if (binman:::get_os() != "win") { expect_identical(fmode, structure(c(493L, 493L), class = "octmode")) } unlink(gzout) })
tdmMapDesLoad <- function(tdm=list()) { if (is.null(tdm$tdmPath)) { mapPath <- find.package("TDMR"); } else { mapPath <- paste(tdm$tdmPath,"inst",sep="/"); } tdmMapFile=paste(mapPath,"tdmMapDesign.csv",sep="/") if (!file.exists(tdmMapFile)) stop(sprintf("Could not find map file %s",tdmMapFile)); tdm$map <- read.table(tdmMapFile,sep=";",header=T); cat(sprintf("Read tdmMapDesign.csv from %s\n",mapPath)); userMapFile=paste(tdm$path,"userMapDesign.csv",sep=""); if (file.exists(userMapFile)) { tdm$mapUser <- read.table(userMapFile,sep=";",header=T); cat(sprintf("Read userMapDesign.csv from %s\n",tdm$path)); } else { tdm$mapUser <- NULL; cat(sprintf("Note: No file userMapDesign.csv in %s\n",tdm$path)); } tdm; } tdmMapDesApply <- function(des,opts,k,spotConfig,tdm) { cRound <- function(n,map,x) { x <- ifelse(map$isInt[n]==1,round(x),x); x; } setMapValue <- function(n,map,des,opts,k) { cmd = paste("if(!is.null(des$",map$roiValue[n],")) ",map$optsValue[n],"=cRound(n,map,des$",map$roiValue[n],"[k])",sep=""); eval(parse(text=cmd)); opts; } pNames=row.names(spotConfig$alg.roi); for (d in pNames) { if (length(which(tdm$map$roiValue==d))+length(which(tdm$mapUser$roiValue==d))==0) stop(sprintf("tdmMapDesApply: cannot find a mapping for design variable %s.\n ",d), sprintf("Please check spelling in spotConfig$alg.roi \n"), sprintf("or extend tdmMapDesign.csv or userMapDesign.csv appropriately!\n")); } if (nrow(tdm$map)>0) { for (n in 1:nrow(tdm$map)) { opts <- setMapValue(n,tdm$map,des,opts,k); } } if (!is.null(tdm$mapUser)) { if (nrow(tdm$mapUser)>0) { for (n in 1:nrow(tdm$mapUser)) { opts <- setMapValue(n,tdm$mapUser,des,opts,k); } } } if (!is.null(opts$CLS.CLASSWT) && is.na(opts$CLS.CLASSWT[1])) opts$CLS.CLASSWT[1]=10; opts; } tdmMapDesInt <- function(des,printSummary=T,spotConfig=NULL) { if (!is.null(des$MTRY)) des$MTRY <- round(des$MTRY); if (!is.null(des$NTREE)) des$NTREE <- round(des$NTREE); if (!is.null(des$NODESIZE)) des$NODESIZE <- round(des$NODESIZE); if (!is.null(des$SAMPSIZE1)) des$SAMPSIZE1 <- round(des$SAMPSIZE1); if (!is.null(des$SAMPSIZE2)) des$SAMPSIZE2 <- round(des$SAMPSIZE2); if (!is.null(des$SAMPSIZE3)) des$SAMPSIZE3 <- round(des$SAMPSIZE3); if (!is.null(des$SAMPSIZE4)) des$SAMPSIZE4 <- round(des$SAMPSIZE4); if (!is.null(des$SAMPSIZE5)) des$SAMPSIZE5 <- round(des$SAMPSIZE5); if (!is.null(des$PRE_NPC)) des$PRE_NPC = round(des$PRE_NPC); if (printSummary) print(summary(des)); des; } tdmMapOpts <- function(umode,opts,tdm) { tdm <- tdmDefaultsFill(tdm); setOpts.RSUB <- function(opts) { opts$TST.kind <- "rand" opts$TST.valiFrac=tdm$TST.testFrac opts; } setOpts.TST <- function(opts) { opts$TST.kind <- "col" if (!is.null(tdm$U.trnFrac)) opts$TST.trnFrac=tdm$U.trnFrac opts$TST.COL=tdm$tstCol opts; } setOpts.CV <- function(opts) { opts$TST.kind <- "cv" opts$TST.NFOLD = tdm$nfold opts; } setOpts.SP_T <- function(opts) { if (!is.null(tdm$U.trnFrac)) opts$TST.trnFrac=tdm$U.trnFrac if (!is.null(tdm$TST.valiFrac)) opts$TST.valiFrac=tdm$TST.valiFrac opts$TST.NFOLD = tdm$nfold opts; } opts <- switch(umode , "RSUB" = setOpts.RSUB(opts) , "CV" = setOpts.CV(opts) , "TST" = setOpts.TST(opts) , "SP_T" = setOpts.SP_T(opts) , "INVALID" ); if (opts[1]=="INVALID") stop(sprintf("*** Invalid umode=%s ***\n",umode)); opts$NRUN = tdm$nrun opts$test2.string=tdm$test2.string opts$VERBOSE <- opts$SRF.verbose <- tdm$optsVerbosity; opts; } tdmMapOpts.OLD <- function(umode,opts,test2.string="no postproc",nfold=10) { tdm = list(); tdm$test2.string=test2.string; tdm$nfold=nfold; opts <- tdmMapOpts(umode,opts,tdm); } tdmMapCutoff <- function(des,k,spotConfig) { if (!is.null(des$CUTOFF2)) { hig=spotConfig$alg.roi["CUTOFF1","upper"]; low=spotConfig$alg.roi["CUTOFF1","lower"]; OLD.VER=F; constr=ifelse(OLD.VER,0,1); eps <- runif(1, min=0.0001, max=0.03); csum <- des$CUTOFF1[k]+des$CUTOFF2[k]; if (!is.null(des$CUTOFF3)) csum <- csum + des$CUTOFF3[k]; if (!is.null(des$CUTOFF4)) csum <- csum + des$CUTOFF4[k]; if (csum+eps>constr) { des$CUTOFF1[k] <- des$CUTOFF1[k]/(csum+eps); des$CUTOFF2[k] <- des$CUTOFF2[k]/(csum+eps); if (!is.null(des$CUTOFF3)) des$CUTOFF3[k] <- des$CUTOFF3[k]/(csum+eps); if (!is.null(des$CUTOFF4)) des$CUTOFF4[k] <- des$CUTOFF4[k]/(csum+eps); } cutoffs=c(des$CUTOFF1[k],des$CUTOFF2[k],des$CUTOFF3[k],des$CUTOFF4[k]); if (!OLD.VER) { while (any(cutoffs<low)) { cutoffs = c(cutoffs,1-sum(cutoffs)); wmin = which(cutoffs==min(cutoffs)); wmax = which(cutoffs==max(cutoffs)); delta = low-cutoffs[wmin]; cutoffs[wmin] = cutoffs[wmin]+delta; cutoffs[wmax] = cutoffs[wmax]-delta; cutoffs=cutoffs[1:(length(cutoffs)-1)]; } if (!is.null(des$CUTOFF1[k])) des$CUTOFF1[k]=cutoffs[1]; if (!is.null(des$CUTOFF2[k])) des$CUTOFF2[k]=cutoffs[2]; if (!is.null(des$CUTOFF3[k])) des$CUTOFF3[k]=cutoffs[3]; if (!is.null(des$CUTOFF4[k])) des$CUTOFF4[k]=cutoffs[4]; } if (any(cutoffs>hig)) { msg=sprintf("Some cutoffs violate high ROI constraint %f (for k=%d)",hig,k); warning(msg); print(cutoffs); } if (any(cutoffs<low)) { msg=sprintf("Some cutoffs violate low ROI constraint %f (for k=%d)",low,k); warning(msg); print(cutoffs); } } des; } tdmMapDesFromX <- function(x,envT) { des <- as.data.frame(x); names(des) <- rownames(envT$spotConfig$alg.roi); des <- tdmMapDesInt(des,printSummary=F,envT$spotConfig); if (!is.null(envT$res)) { des$CONFIG = max(envT$res$CONFIG)+1; } else des$CONFIG=1; if (!is.null(envT$bst)) { des$STEP = nrow(envT$bst); } else des$STEP=0; des$REPEATS=envT$spotConfig$replicates; des$SEED=envT$spotConfig$alg.seed + seq(1,nrow(x)); if (is.null(des$repeatsLastConfig)) des$repeatsLastConfig=1; des; }
getreadcounts <- function(hits, windowlength, chrlength){ windows <- seq(1,chrlength,windowlength) readcount <- numeric(length=length(windows)) count <- 0 i <- 1 hits <- sort(hits) for (hit in hits){ if (!isbetween(hit,windows[i],(windows[i]+windowlength-1))){ readcount[i] <- count count <- 0 while(!isbetween(hit,windows[i],(windows[i]+windowlength-1))){ i <- i + 1 } } count <- count+1 } readcount[i] <- count return(readcount) }
custom_eucast_rules <- function(...) { dots <- tryCatch(list(...), error = function(e) "error") stop_if(identical(dots, "error"), "rules must be a valid formula inputs (e.g., using '~'), see `?custom_eucast_rules`") n_dots <- length(dots) stop_if(n_dots == 0, "no custom rules were set. Please read the documentation using `?custom_eucast_rules`.") out <- vector("list", n_dots) for (i in seq_len(n_dots)) { stop_ifnot(inherits(dots[[i]], "formula"), "rule ", i, " must be a valid formula input (e.g., using '~'), see `?custom_eucast_rules`") qry <- dots[[i]][[2]] if (inherits(qry, "call")) { qry <- as.expression(qry) } qry <- as.character(qry) qry <- gsub("&&", "&", qry, fixed = TRUE) qry <- gsub("||", "|", qry, fixed = TRUE) qry <- gsub(" *([&|+-/*^><==]+) *", " \\1 ", qry) qry <- gsub(" ?, ?", ", ", qry) qry <- gsub("'", "\"", qry, fixed = TRUE) out[[i]]$query <- as.expression(qry) result <- dots[[i]][[3]] stop_ifnot(deparse(result) %like% "==", "the result of rule ", i, " (the part after the `~`) must contain `==`, such as in `... ~ ampicillin == \"R\"`, see `?custom_eucast_rules`") result_group <- as.character(result)[[2]] if (paste0("AB_", toupper(result_group), "S") %in% DEFINED_AB_GROUPS) { result_group <- paste0(result_group, "s") } if (paste0("AB_", toupper(result_group)) %in% DEFINED_AB_GROUPS) { result_group <- eval(parse(text = paste0("AB_", toupper(result_group))), envir = asNamespace("AMR")) } else { result_group <- tryCatch( suppressWarnings(as.ab(result_group, fast_mode = TRUE, flag_multiple_results = FALSE)), error = function(e) NA_character_) } stop_if(any(is.na(result_group)), "this result of rule ", i, " could not be translated to a single antimicrobial agent/group: \"", as.character(result)[[2]], "\".\n\nThe input can be a name or code of an antimicrobial agent, or be one of: ", vector_or(tolower(gsub("AB_", "", DEFINED_AB_GROUPS)), quotes = FALSE), ".") result_value <- as.character(result)[[3]] result_value[result_value == "NA"] <- NA stop_ifnot(result_value %in% c("R", "S", "I", NA), "the resulting value of rule ", i, " must be either \"R\", \"S\", \"I\" or NA") result_value <- as.rsi(result_value) out[[i]]$result_group <- result_group out[[i]]$result_value <- result_value } names(out) <- paste0("rule", seq_len(n_dots)) set_clean_class(out, new_class = c("custom_eucast_rules", "list")) } c.custom_eucast_rules <- function(x, ...) { if (length(list(...)) == 0) { return(x) } out <- unclass(x) for (e in list(...)) { out <- c(out, unclass(e)) } names(out) <- paste0("rule", seq_len(length(out))) set_clean_class(out, new_class = c("custom_eucast_rules", "list")) } as.list.custom_eucast_rules <- function(x, ...) { c(x, ...) } print.custom_eucast_rules <- function(x, ...) { cat("A set of custom EUCAST rules:\n") for (i in seq_len(length(x))) { rule <- x[[i]] rule$query <- format_custom_query_rule(rule$query) if (is.na(rule$result_value)) { val <- font_red("<NA>") } else if (rule$result_value == "R") { val <- font_rsi_R_bg(font_black(" R ")) } else if (rule$result_value == "S") { val <- font_rsi_S_bg(font_black(" S ")) } else { val <- font_rsi_I_bg(font_black(" I ")) } agents <- paste0(font_blue(ab_name(rule$result_group, language = NULL, tolower = TRUE), collapse = NULL), " (", rule$result_group, ")") agents <- sort(agents) rule_if <- word_wrap(paste0(i, ". ", font_bold("If "), font_blue(rule$query), font_bold(" then "), "set to {result}:"), extra_indent = 5) rule_if <- gsub("{result}", val, rule_if, fixed = TRUE) rule_then <- paste0(" ", word_wrap(paste0(agents, collapse = ", "), extra_indent = 5)) cat("\n ", rule_if, "\n", rule_then, "\n", sep = "") } } format_custom_query_rule <- function(query, colours = has_colour()) { query <- gsub(" & ", font_black(font_bold(" and ")), query, fixed = TRUE) query <- gsub(" | ", font_black(" or "), query, fixed = TRUE) query <- gsub(" + ", font_black(" plus "), query, fixed = TRUE) query <- gsub(" - ", font_black(" minus "), query, fixed = TRUE) query <- gsub(" / ", font_black(" divided by "), query, fixed = TRUE) query <- gsub(" * ", font_black(" times "), query, fixed = TRUE) query <- gsub(" == ", font_black(" is "), query, fixed = TRUE) query <- gsub(" > ", font_black(" is higher than "), query, fixed = TRUE) query <- gsub(" < ", font_black(" is lower than "), query, fixed = TRUE) query <- gsub(" >= ", font_black(" is higher than or equal to "), query, fixed = TRUE) query <- gsub(" <= ", font_black(" is lower than or equal to "), query, fixed = TRUE) query <- gsub(" ^ ", font_black(" to the power of "), query, fixed = TRUE) query <- gsub(" %in% ", font_black(" is one of "), query, fixed = TRUE) query <- gsub(" %like% ", font_black(" resembles "), query, fixed = TRUE) if (colours == TRUE) { query <- gsub('"R"', font_rsi_R_bg(font_black(" R ")), query, fixed = TRUE) query <- gsub('"S"', font_rsi_S_bg(font_black(" S ")), query, fixed = TRUE) query <- gsub('"I"', font_rsi_I_bg(font_black(" I ")), query, fixed = TRUE) } query <- gsub("\033[39m", "\033[34m", as.character(query), fixed = TRUE) query <- paste0("\033[34m", query) if (colours == FALSE) { query <- font_stripstyle(query) } query }
"supreme_court"
library(shiny.fluent) if (interactive()) { title <- "Long_file_name_with_underscores_used_to_separate_all_of_the_words" previewImages <- list( list( previewImageSrc = "https://picsum.photos/318/196", width = 318, height = 196 ) ) shinyApp( ui = DocumentCard( DocumentCardPreview(previewImages = previewImages), DocumentCardTitle( title = title, shouldTruncate = TRUE ), DocumentCardActivity( activity = "Created a few minutes ago", people = list(list(name = "Annie Lindqvist")) ) ), server = function(input, output) {} ) }
context("Testing 'modulePreservation' function") gn1 <- paste0("N_", 1:100) gn2 <- paste0("N_", seq(2, 200, length=100)) sn1 <- paste0("S_", 1:50) sn2 <- paste0("S_", 1:75) coexpSets <- list( a=matrix(rnorm(100*100), 100, dimnames=list(gn1, gn1)), b=matrix(rnorm(100*100), 100, dimnames=list(gn2, gn2)) ) adjSets <- coexpSets exprSets <- list( a=matrix(rnorm(50*100), 50, dimnames=list(sn1, gn1)), b=matrix(rnorm(75*100), 75, dimnames=list(sn2, gn2)) ) moduleAssignments <- list(a=sample(1:7, 100, replace=TRUE), b=NULL) names(moduleAssignments[[1]]) <- gn1 modules <- moduleAssignments[[1]][intersect(names(moduleAssignments[[1]]), colnames(adjSets[[2]]))] modules <- table(modules) modules <- names(modules[modules > 2]) nModules <- length(modules) test_that("Main routine runs and produces sane output", { res1 <- modulePreservation( adjSets, exprSets, coexpSets, moduleAssignments, modules, discovery=1, test=2, nPerm=1000, verbose=FALSE, nThreads=2 ) expect_equal(dim(res1$nulls), c(nModules , 7, 1000)) expect_equal(dim(res1$observed), c(nModules , 7)) expect_equal(dim(res1$p.values), c(nModules , 7)) expect_equal(length(res1$propVarsPresent), nModules) expect_equal(length(res1$nVarsPresent), nModules) res2 <- modulePreservation( adjSets, NULL, coexpSets, moduleAssignments, modules, discovery=1, test=2, nPerm=1000, verbose=FALSE, nThreads=2 ) expect_equal(dim(res2$nulls), c(nModules, 4, 1000)) expect_equal(dim(res2$observed), c(nModules, 4)) expect_equal(dim(res2$p.values), c(nModules, 4)) expect_equal(length(res2$propVarsPresent), nModules) expect_equal(length(res2$nVarsPresent), nModules) res1 <- modulePreservation( adjSets, exprSets, coexpSets, moduleAssignments, modules, discovery="a", test="b", nPerm=4, verbose=FALSE, nThreads=2 ) }) rm(exprSets, coexpSets, adjSets) gc()
deltaFinder <- function(a, lambda1, lambda2, gamma){ return(sqrt(sum((deltaValue(a, lambda1, lambda2, gamma))^2))-1) }
source('loadTestDataFunc.R') test_that("Test Assign Strain Traits for non pH traits",{ num=40 meanT=5 for (distn in c('normal','uniform')){ strainOptions=list(percentTraitRange=20,distribution=distn) traits=assignStrainTraits(num,meanT,strainOptions,pHtrait=FALSE) expect_equal(length(traits),num) expect_equal(mean(traits),meanT,tolerance=0.1*meanT) max.range=meanT*(1+strainOptions$percentTraitRange/100) min.range=meanT*(1-strainOptions$percentTraitRange/100) if (distn=='uniform'){ expect_true(max(traits) <= max.range) expect_true(min(traits) >= min.range) } if (distn=='normal'){ sds=NA*seq(1,1000) for (i in 1:1000){ traits=assignStrainTraits(num,meanT,strainOptions,pHtrait=FALSE) sds[i]=sd(traits) } expect_equal(mean(sds),meanT*strainOptions$percentTraitRange/200, 0.1*meanT*strainOptions$percentTraitRange/200) } } }) test_that("Test Assign Strain Traits for pH traits",{ num=40 meanT=5 for (distn in c('normal','uniform')){ strainOptions=list(distribution=distn,maxPHshift=0.7) traits=assignStrainTraits(num,meanT,strainOptions,pHtrait=TRUE) expect_equal(length(traits),num) expect_equal(mean(traits),meanT,tolerance=0.1*meanT) max.pHrange=meanT*(1+strainOptions$maxPHshift) min.pHrange=meanT*(1-strainOptions$maxPHshift) if (distn=='uniform'){ expect_true(max(traits) <= max.pHrange) expect_true(min(traits) >= min.pHrange) } if (distn=='normal'){ sds=NA*seq(1,1000) for (i in 1:1000){ traits=assignStrainTraits(num,meanT,strainOptions,pHtrait=TRUE) sds[i]=sd(traits) } expect_equal(mean(sds),strainOptions$maxPHshift/2, 0.1*strainOptions$maxPHshift/2) } } }) test_that("Test applyTraitTradeOffs",{ loadTestDataFunc(2) tradeOffParams=strainOptions$tradeOffParams traits=applyTraitTradeOffs(microbeNames,tradeOffParams,numPaths, numStrains,parms$Pmats,resourceNames) expect_true(is.list(traits)) Bac.K=c(traits$halfSat$Bacteroides.1[1,'NSP'],traits$halfSat$Bacteroides.2[1,'NSP'], traits$halfSat$Bacteroides.3[1,'NSP']) Ace.K=c(traits$halfSat$Acetogens.1[1,'NSP'],traits$halfSat$Acetogens.2[1,'NSP'], traits$halfSat$Acetogens.3[1,'NSP']) expect_true(all(diff(Bac.K)<=0)) expect_true(all(diff(Ace.K)<=0)) Bac.G=c(traits$maxGrowthRate$Bacteroides.1[1,'NSP'], traits$maxGrowthRate$Bacteroides.2[1,'NSP'], traits$maxGrowthRate$Bacteroides.3[1,'NSP']) Ace.G=c(traits$maxGrowthRate$Acetogens.1[1,'NSP'], traits$maxGrowthRate$Acetogens.2[1,'NSP'], traits$maxGrowthRate$Acetogens.3[1,'NSP']) expect_true(all(diff(Bac.G)<=0)) expect_true(all(diff(Ace.G)<=0)) }) test_that("Test non pH corners bit of getStrainParametersFromFile.R",{ filename=system.file('extdata/strainParams.csv',package='microPop') loadTestDataFunc(2) PARdata = read.csv(filename, header = TRUE, stringsAsFactors = FALSE) strainOptions = list(paramsSpecified = TRUE, paramDataName = PARdata) expect_warning(getStrainParamsFromFile(out$parms$Pmats, out$parms$strainPHcorners, strainOptions)) PARdata[2,1]='Bacteroides.3' strainOptions = list(paramsSpecified = TRUE, paramDataName = PARdata) x=getStrainParamsFromFile(out$parms$Pmats, out$parms$strainPHcorners, strainOptions) expect_true(is.list(x)) expect_equal(x[[1]][['maxGrowthRate']][['Bacteroides.1']][1,'NSP'],PARdata[1,3]) }) test_that("Test pH corners bit of getStrainParametersFromFile.R",{ filename=system.file('extdata/strainParams.csv',package='microPop') loadTestDataFunc(2) PARdata = read.csv(filename, header = TRUE, stringsAsFactors = FALSE) PARdata[2,1]='Bacteroides.3' strainOptions = list(paramsSpecified = TRUE, paramDataName = PARdata) x=getStrainParamsFromFile(out$parms$Pmats, out$parms$strainPHcorners, strainOptions) expect_warning(getStrainParamsFromFile(out$parms$Pmats, out$parms$strainPHcorners, strainOptions),NA) expect_true(is.list(x)) expect_true(x[[2]]['Acetogens.2',1]-as.numeric(PARdata[3,3])==0) expect_true(x[[2]]['Acetogens.2',2]-as.numeric(PARdata[3,4])==0) expect_true(x[[2]]['Acetogens.2',3]-as.numeric(PARdata[3,5])==0) expect_true(x[[2]]['Acetogens.2',4]-as.numeric(PARdata[3,6])==0) }) test_that("Test getStrainPHcorners.R",{ loadTestDataFunc(2) pHcorners = getPHcorners(microbeNames, pHLimit=TRUE) pHcorners[1,]=c(1,2,3,4) oneStrainRandomParams=FALSE x=getStrainPHcorners(microbeNames,allStrainNames,numStrains, pHcorners,pHLimit=TRUE, strainOptions=list(randomParams='pHtrait', distribution='uniform',maxPHshift=0.1),oneStrainRandomParams) expect_equal(dim(x),c(numStrains*length(microbeNames),4)) expect_true(diff(range(x[1:numStrains,1]))<=0.2) expect_true(diff(range(x[1:numStrains,2]))<=0.2) expect_true(diff(range(x[1:numStrains,3]))<=0.2) expect_true(diff(range(x[1:numStrains,4]))<=0.2) expect_true(mean(x[1:numStrains,1])<=1.1) expect_true(mean(x[1:numStrains,2])>=1.9) expect_true(mean(x[1:numStrains,4])<=4.1) expect_false(isTRUE(all.equal(x[1,],c(1,2,3,4)))) x=getStrainPHcorners(microbeNames,allStrainNames,numStrains=1, pHcorners,pHLimit=TRUE, strainOptions=list(randomParams='pHtrait', distribution='uniform',maxPHshift=0.1),oneStrainRandomParams) expect_equal(x[1,],c(1,2,3,4)) x=getStrainPHcorners(microbeNames,allStrainNames,numStrains=1, pHcorners,pHLimit=TRUE, strainOptions=list(randomParams='pHtrait', distribution='uniform',maxPHshift=0.1), oneStrainRandomParams=TRUE) expect_false(isTRUE(all.equal(x[1,],c(1,2,3,4)))) })
multi_regression_forest <- function(X, Y, num.trees = 2000, sample.weights = NULL, clusters = NULL, equalize.cluster.weights = FALSE, sample.fraction = 0.5, mtry = min(ceiling(sqrt(ncol(X)) + 20), ncol(X)), min.node.size = 5, honesty = TRUE, honesty.fraction = 0.5, honesty.prune.leaves = TRUE, alpha = 0.05, imbalance.penalty = 0, compute.oob.predictions = TRUE, num.threads = NULL, seed = runif(1, 0, .Machine$integer.max)) { has.missing.values <- validate_X(X, allow.na = TRUE) validate_sample_weights(sample.weights, X) Y <- validate_observations(Y, X, allow.matrix = TRUE) clusters <- validate_clusters(clusters, X) samples.per.cluster <- validate_equalize_cluster_weights(equalize.cluster.weights, clusters, sample.weights) num.threads <- validate_num_threads(num.threads) data <- create_train_matrices(X, outcome = Y, sample.weights = sample.weights) args <- list(num.trees = num.trees, clusters = clusters, samples.per.cluster = samples.per.cluster, sample.fraction = sample.fraction, mtry = mtry, min.node.size = min.node.size, honesty = honesty, honesty.fraction = honesty.fraction, honesty.prune.leaves = honesty.prune.leaves, alpha = alpha, imbalance.penalty = imbalance.penalty, compute.oob.predictions = compute.oob.predictions, num.threads = num.threads, seed = seed) forest <- do.call.rcpp(multi_regression_train, c(data, args)) class(forest) <- c("multi_regression_forest", "grf") forest[["X.orig"]] <- X forest[["Y.orig"]] <- Y forest[["sample.weights"]] <- sample.weights forest[["clusters"]] <- clusters forest[["equalize.cluster.weights"]] <- equalize.cluster.weights forest[["has.missing.values"]] <- has.missing.values forest } predict.multi_regression_forest <- function(object, newdata = NULL, num.threads = NULL, ...) { outcome.names <- if (is.null(colnames(object[["Y.orig"]]))) { paste0("Y", 1:NCOL(object[["Y.orig"]])) } else { colnames(object[["Y.orig"]]) } if (is.null(newdata) && !is.null(object$predictions)) { colnames(object$predictions) <- outcome.names return(list(predictions = object$predictions)) } num.threads <- validate_num_threads(num.threads) forest.short <- object[-which(names(object) == "X.orig")] X <- object[["X.orig"]] train.data <- create_train_matrices(X) args <- list(forest.object = forest.short, num.threads = num.threads, num.outcomes = NCOL(object[["Y.orig"]])) if (!is.null(newdata)) { validate_newdata(newdata, X, allow.na = TRUE) test.data <- create_test_matrices(newdata) ret <- do.call.rcpp(multi_regression_predict, c(train.data, test.data, args)) } else { ret <- do.call.rcpp(multi_regression_predict_oob, c(train.data, args)) } colnames(ret$predictions) <- outcome.names list(predictions = ret$predictions) }
HttpFileResourceGetter <- R6::R6Class( "HttpFileResourceGetter", inherit = FileResourceGetter, public = list( initialize = function() {}, isFor = function(resource) { if (super$isFor(resource)) { super$parseURL(resource)$scheme %in% c("http", "https") } else { FALSE } }, downloadFile = function(resource, ...) { if (self$isFor(resource)) { fileName <- super$extractFileName(resource) downloadDir <- super$makeDownloadDir() path <- file.path(downloadDir, fileName) httr::GET(resource$url, private$addHeaders(resource), write_disk(path, overwrite = TRUE)) super$newFileObject(path, temp = TRUE) } else { stop("Resource file is not located in a HTTP server") } } ), private = list( addHeaders = function(resource) { if (!is.null(resource$identity) && nchar(resource$identity)>0 && !is.null(resource$secret) && nchar(resource$secret)>0) { httr::add_headers(Authorization = jsonlite::base64_enc(paste0("Basic ", resource$identity, ":", resource$secret))) } else { httr::add_headers() } } ) )
infer_multittree_share_param = function(ptree_lst,w.shape=2,w.scale=1,ws.shape=w.shape,ws.scale=w.scale,mcmcIterations=1000, thinning=1,startNeg=100/365,startOff.r=1,startOff.p=0.5,startPi=0.5,prior_pi_a=1,prior_pi_b=1, updateNeg=TRUE,updateOff.r=TRUE,updateOff.p=FALSE,updatePi=TRUE,share=NULL, startCTree_lst=rep(NA,length(ptree_lst)),updateTTree=TRUE,optiStart=2,dateT=Inf,verbose=F) { if (length(ptree_lst)>=1) for (i in 1:length(ptree_lst)) class(ptree_lst[[i]])<-'list' ptree_lst <- purrr::map(ptree_lst, function(x) within(x, ptree[,1] <- ptree[,1]+runif(nrow(ptree))*1e-10)) neg <- startNeg off.r <- startOff.r off.p <- startOff.p pi <- startPi ctree_lst <- vector("list", length(ptree_lst)) for(k in seq_along(ptree_lst)){ if(is.na(startCTree_lst[[k]])) ctree_lst[[k]] <- makeCTreeFromPTree(ptree_lst[[k]],off.r,off.p,neg,pi,w.shape,w.scale,ws.shape,ws.scale,dateT,optiStart) else ctree_lst[[k]] <- startCTree_lst[[k]] } ntree <- length(ptree_lst) neg_lst <- as.list(rep(neg, ntree)) off.r_lst <- as.list(rep(off.r, ntree)) off.p_lst <- as.list(rep(off.p, ntree)) pi_lst <- as.list(rep(pi, ntree)) not_share <- setdiff(c("neg", "off.r", "off.p", "pi"), share) one_update <- function(ctree, pTTree, pPTree, neg, off.r, off.p, pi, not_share){ ttree <- extractTTree(ctree) if (updateTTree) { if (verbose) message("Proposing ttree update") prop <- proposal(ctree$ctree) ctree2 <- list(ctree=prop$tree,nam=ctree$nam) class(ctree2)<-'ctree' ttree2 <- extractTTree(ctree2) pTTree2 <- probTTree(ttree2$ttree,off.r,off.p,pi,w.shape,w.scale,ws.shape,ws.scale,dateT) pPTree2 <- probPTreeGivenTTree(ctree2$ctree,neg) if (log(runif(1)) < log(prop$qr)+pTTree2 + pPTree2-pTTree-pPTree) { ctree <- ctree2 ttree <- ttree2 pTTree <- pTTree2 pPTree <- pPTree2 } } if (("neg" %in% not_share) && updateNeg) { neg2 <- abs(neg + (runif(1)-0.5)*0.5) if (verbose) message(sprintf("Proposing unshared Ne*g update %f->%f",neg,neg2)) pPTree2 <- probPTreeGivenTTree(ctree$ctree,neg2) if (log(runif(1)) < pPTree2-pPTree-neg2+neg) {neg <- neg2;pPTree <- pPTree2} } if (("off.r" %in% not_share) && updateOff.r) { off.r2 <- abs(off.r + (runif(1)-0.5)*0.5) if (verbose) message(sprintf("Proposing unshared off.r update %f->%f",off.r,off.r2)) pTTree2 <- probTTree(ttree$ttree,off.r2,off.p,pi,w.shape,w.scale,ws.shape,ws.scale,dateT) if (log(runif(1)) < pTTree2-pTTree-off.r2+off.r) {off.r <- off.r2;pTTree <- pTTree2} } if (("off.p" %in% not_share) && updateOff.p) { off.p2 <- abs(off.p + (runif(1)-0.5)*0.1) if (off.p2>1) off.p2=2-off.p2 if (verbose) message(sprintf("Proposing unshared off.p update %f->%f",off.p,off.p2)) pTTree2 <- probTTree(ttree$ttree,off.r,off.p2,pi,w.shape,w.scale,ws.shape,ws.scale,dateT) if (log(runif(1)) < pTTree2-pTTree) {off.p <- off.p2;pTTree <- pTTree2} } if (("pi" %in% not_share) && updatePi) { pi2 <- pi + (runif(1)-0.5)*0.1 if (pi2<0.01) pi2=0.02-pi2 if (pi2>1) pi2=2-pi2 if (verbose) message(sprintf("Proposing unshared pi update %f->%f",pi,pi2)) pTTree2 <- probTTree(ttree$ttree,off.r,off.p,pi2,w.shape,w.scale,ws.shape,ws.scale,dateT) log_beta_ratio <- (prior_pi_a - 1) * log(pi2) + (prior_pi_b - 1) * log(1 - pi2) - (prior_pi_a - 1) * log(pi) - (prior_pi_b - 1) * log(1 - pi) if (log(runif(1)) < pTTree2-pTTree + log_beta_ratio) {pi <- pi2;pTTree <- pTTree2} } list(ctree=ctree, pTTree=pTTree, pPTree=pPTree, neg=neg, off.r=off.r, off.p=off.p, pi=pi) } one_update_share <- function(ctree_lst, pTTree_lst, pPTree_lst, neg_lst, off.r_lst, off.p_lst, pi_lst, share){ ttree_lst <- purrr::map(ctree_lst, extractTTree) ttree_lst <- purrr::map(ttree_lst, "ttree") if(("neg" %in% share) && updateNeg){ neg <- neg_lst[[1]] neg2 <- abs(neg + (runif(1)-0.5)*0.5) if (verbose) message(sprintf("Proposing shared Ne*g update %f->%f",neg,neg2)) pPTree <- purrr::flatten_dbl(pPTree_lst) pPTree2 <- purrr::map_dbl(ctree_lst, function (x,neg) probPTreeGivenTTree(x$ctree,neg), neg = neg2) if (log(runif(1)) < sum(pPTree2)-sum(pPTree)-neg2+neg){ neg_lst <- as.list(rep(neg2, ntree)) pPTree_lst <- as.list(pPTree2) } } if(("off.r" %in% share) && updateOff.r) { off.r <- off.r_lst[[1]] off.r2 <- abs(off.r + (runif(1)-0.5)*0.5) if (verbose) message(sprintf("Proposing shared off.r update %f->%f",off.r,off.r2)) pTTree <- purrr::flatten_dbl(pTTree_lst) pTTree2 <- purrr::pmap_dbl(list(ttree=ttree_lst, pOff=off.p_lst, pi=pi_lst), probTTree, rOff=off.r2, shGen=w.shape, scGen=w.scale, shSam=ws.shape, scSam=ws.scale, dateT=dateT) if (log(runif(1)) < sum(pTTree2)-sum(pTTree)-off.r2+off.r){ off.r_lst <- as.list(rep(off.r2, ntree)) pTTree_lst <- as.list(pTTree2) } } if(("off.p" %in% share) && updateOff.p) { off.p <- off.p_lst[[1]] off.p2 <- abs(off.p + (runif(1)-0.5)*0.1) if (off.p2>1) off.p2=2-off.p2 if (verbose) message(sprintf("Proposing shared off.p update %f->%f",off.p,off.p2)) pTTree <- purrr::flatten_dbl(pTTree_lst) pTTree2 <- purrr::pmap_dbl(list(ttree=ttree_lst, rOff=off.r_lst, pi=pi_lst), probTTree, pOff=off.p2, shGen=w.shape, scGen=w.scale, shSam=ws.shape, scSam=ws.scale, dateT=dateT) if (log(runif(1)) < sum(pTTree2)-sum(pTTree)){ off.p_lst <- as.list(rep(off.p2, ntree)) pTTree_lst <- as.list(pTTree2) } } if(("pi" %in% share) && updatePi){ pi <- pi_lst[[1]] pi2 <- pi + (runif(1)-0.5)*0.1 if (pi2<0.01) pi2=0.02-pi2 if (pi2>1) pi2=2-pi2 if (verbose) message(sprintf("Proposing shared pi update %f->%f",pi,pi2)) pTTree <- purrr::flatten_dbl(pTTree_lst) pTTree2 <- purrr::pmap_dbl(list(ttree=ttree_lst, rOff=off.r_lst, pOff=off.p_lst), probTTree, pi=pi2, shGen=w.shape, scGen=w.scale, shSam=ws.shape, scSam=ws.scale, dateT=dateT) log_beta_ratio <- (prior_pi_a - 1) * log(pi2) + (prior_pi_b - 1) * log(1 - pi2) - (prior_pi_a - 1) * log(pi) - (prior_pi_b - 1) * log(1 - pi) if (log(runif(1)) < sum(pTTree2) - sum(pTTree) + ntree * log_beta_ratio){ pi_lst <- as.list(rep(pi2, ntree)) pTTree_lst <- as.list(pTTree2) } } list(ctree=ctree_lst, pTTree=pTTree_lst, pPTree=pPTree_lst, neg=neg_lst, off.r=off.r_lst, off.p=off.p_lst, pi=pi_lst) } record <- vector('list', ntree) for(i in seq_along(record)){ record[[i]] <- vector("list", mcmcIterations/thinning) } pTTree_lst <- vector("list", ntree) pPTree_lst <- vector("list", ntree) for(k in 1:ntree){ ttree <- extractTTree(ctree_lst[[k]]) pTTree_lst[[k]] <- probTTree(ttree$ttree,off.r,off.p,pi,w.shape,w.scale,ws.shape,ws.scale,dateT) pPTree_lst[[k]] <- probPTreeGivenTTree(ctree_lst[[k]]$ctree,neg) } mcmc_state <- list(ctree=ctree_lst, pTTree=pTTree_lst, pPTree=pPTree_lst, neg=neg_lst, off.r=off.r_lst, off.p=off.p_lst, pi=pi_lst) if (verbose==F) pb <- utils::txtProgressBar(min=0,max=mcmcIterations,style = 3) for (i in 1:mcmcIterations) { out <- with(mcmc_state, one_update_share(ctree, pTTree, pPTree, neg, off.r, off.p, pi, share)) mcmc_state[["ctree"]] <- out[["ctree"]] mcmc_state[["pTTree"]] <- out[["pTTree"]] mcmc_state[["pPTree"]] <- out[["pPTree"]] mcmc_state[["neg"]] <- out[["neg"]] mcmc_state[["off.r"]] <- out[["off.r"]] mcmc_state[["off.p"]] <- out[["off.p"]] mcmc_state[["pi"]] <- out[["pi"]] state_new <- purrr::pmap(mcmc_state, one_update, not_share=not_share) if (i%%thinning == 0) { if (verbose==F) utils::setTxtProgressBar(pb, i) if (verbose==T) message(sprintf('it=%d',i)) for(k in seq_along(ctree_lst)){ record[[k]][[i/thinning]]$ctree <- state_new[[k]]$ctree record[[k]][[i/thinning]]$pTTree <- state_new[[k]]$pTTree record[[k]][[i/thinning]]$pPTree <- state_new[[k]]$pPTree record[[k]][[i/thinning]]$neg <- state_new[[k]]$neg record[[k]][[i/thinning]]$off.r <- state_new[[k]]$off.r record[[k]][[i/thinning]]$off.p <- state_new[[k]]$off.p record[[k]][[i/thinning]]$pi <- state_new[[k]]$pi record[[k]][[i/thinning]]$w.shape <- w.shape record[[k]][[i/thinning]]$w.scale <- w.scale record[[k]][[i/thinning]]$ws.shape <- ws.shape record[[k]][[i/thinning]]$ws.scale <- ws.scale record[[k]][[i/thinning]]$source <- with(state_new[[k]]$ctree, ctree[ctree[which(ctree[,4]==0),2],4]) if (record[[k]][[i/thinning]]$source<=length(state_new[[k]]$ctree$nam)) record[[k]][[i/thinning]]$source=state_new[[k]]$ctree$nam[record[[k]][[i/thinning]]$source] else record[[k]][[i/thinning]]$source='Unsampled' } } mcmc_state <- purrr::transpose(state_new) } class(record)<-'resTransPhylo' return(record) }
CUSUM_stream_jumpdetect_prechange <- function(stream, BL, params, mu0, sigma0){ d <- params[[1]] B <- params[[2]] streampos <- 1 N <- length(stream) detected_count <- 0 M <- 1 detect_pos_vec <- rep(0, M) jump_found <- FALSE while ((streampos < N) && (jump_found==FALSE)){ mean_j <- mu0 var_j <- sigma0^2 sd_j <- sqrt(var_j) nu_j <- d*sd_j control_j <- B*sd_j S_j <- 0 T_j <- 0 isOutOfLimitsBool <- FALSE j <- 0 timedetected <- N while ((jump_found==FALSE) && (streampos < N)) { j <- j+1 x_new <- get_nextobs_fromstream(stream, streampos) streampos <- update_streampos(streampos) S_j <- S_j + x_new - mean_j - nu_j S_j <- S_j*(S_j>0) T_j <- T_j + mean_j - x_new - nu_j T_j <- (T_j)*(T_j>0) S_isOut <- (S_j > control_j) T_isOut <- (T_j > control_j) jump_found <- S_isOut | T_isOut if (jump_found==TRUE){ detected_count <- detected_count + 1 detect_pos_vec[detected_count] <- streampos } } } detect_pos_vec <- detect_pos_vec[1:detected_count] return(detect_pos_vec) } EWMA_stream_jumpdetect_prechange <- function(stream, BL, params, mu0, sigma0){ r <- params[[1]] L <- params[2] streampos <- 1 N <- length(stream) detected_count <- 0 detect_pos_vec <- rep(0, 1) delta <- r / (2-r) rFactorSigmaZ <- 1 sigmaZ <- 1 jump_found <- FALSE while ((streampos < N) && (jump_found==FALSE)){ mu_1 <- mu0 sigma1_sq <- sigma0^2 sigma_1 <- sqrt(sigma1_sq) UL <- mu_1 + L * sigma_1 * delta LL <- mu_1 - L * sigma_1 * delta jump_found <- FALSE isOutOfLimitsBool <- FALSE timedetected <- N W <- 0 delta <- r/(2-r) rFactorSigmaZ <- 1 sigmaZ <- 1 while ((jump_found==FALSE) && (streampos < N)) { x_new <- get_nextobs_fromstream(stream, streampos) streampos <- update_streampos(streampos) W <- r * x_new + (1-r)*W rFactorSigmaZ <- rFactorSigmaZ * (1-r)^2 sigmaZ <- sqrt( delta * (1-rFactorSigmaZ) ) * sigma_1 UL <- mu_1 + L * sigmaZ LL <- mu_1 - L * sigmaZ if((W > UL) | (W < LL)){ jump_found <- TRUE detected_count <- detected_count + 1 detect_pos_vec[detected_count] <- streampos } } } detect_pos_vec <- detect_pos_vec[1:detected_count] return(detect_pos_vec) } FFF_stream_jumpdetect_prechange <- function(stream, BL, ffparams, mu0, sigma0){ lambda <- ffparams[[1]] p <- ffparams[[2]] resettozero <- ffparams[[3]] u_new <- ffparams[[4]] v_new <- ffparams[[5]] v_old <- v_new w_new <- ffparams[[6]] ffmean_new <- ffparams[[7]] ffvar_new <- ffparams[[8]] streampos <- 1 N <- length(stream) detected_count <- 0 detect_pos_vec <- rep(0, 1) jump_found <- FALSE while ( (streampos < N) && (jump_found==FALSE)){ lambda_beforeBL <- 1 w_BL_new <- 0 u_BL_new <- 0 v_BL_new <- 0 v_BL_old <- 0 mean_BL_new <- 0 var_BL_new <- 0 mean_burn <- mu0 var_burn <- sigma0^2 burnvec <- c(p, mean_burn, var_burn) if (resettozero==0){ w_new <- 0 u_new <- 0 v_new <- 0 v_old <- 0 ffmean_new <- mu0 ffvar_new <- sigma0^2 } thelimits <- c(0,0) while((jump_found==FALSE) && (streampos < N)){ x_new <- get_nextobs_fromstream(stream, streampos) streampos <- update_streampos(streampos) w_new <- update_w(w_new, lambda) u_new <- update_u(u_new, w_new) v_old <- v_new v_new <- getv_from_u_and_w(u_new, w_new) ffmean_old <- ffmean_new ffmean_new <- update_ffmean(ffmean_old, w_new, x_new) ffvar_old <- ffvar_new ffvar_new <- update_var(ffvar_old, ffmean_old, lambda, v_old, v_new, w_new, x_new) sigma_sq_u <- u_new*var_burn thelimits <- getNormalLimitsFromList(burnvec, u_new) inLimitsBool <- isInLimitsNormal(ffmean_new, thelimits) if(inLimitsBool == FALSE) { jump_found <- TRUE detected_count <- detected_count + 1 detect_pos_vec[detected_count] <- streampos-1 } } } detect_pos_vec <- detect_pos_vec[1:detected_count] return(detect_pos_vec) } AFF_scaled_stream_jumpdetect_prechange <- function(stream, BL, affparams, mu0, sigma0){ lambda <- affparams[[1]] p <- affparams[[2]] resettozero <- affparams[[3]] u_new <- affparams[[4]] v_new <- affparams[[5]] v_old <- v_new w_new <- affparams[[6]] affmean_new <- affparams[[7]] m_new <- affmean_new*w_new affvar_new <- affparams[[8]] low_bound <- affparams[[9]] up_bound <- affparams[[10]] signchosen <- affparams[[11]] alpha <- affparams[[12]] xbar_new_deriv <- 0 Delta_new <- 0 Omega_new <- 0 streampos <- 0 N <- length(stream) detected_count <- 0 detect_pos_vec <- rep(0, 1) inv_AFFderiv_estim_BL <- 0 inv_var_burn <- 0 lambda_vec <- rep(0, N) jumpdetected <- FALSE while ( (streampos < N) && (jumpdetected==FALSE) ){ lambda_beforeBL <- 1 w_BL_new <- 0 u_BL_new <- 0 v_BL_new <- 0 v_BL_old <- 0 mean_BL_new <- 0 var_BL_new <- 0 AFFderiv_estim_BL <- 0 BLcount <- 0 mean_burn <- mu0 var_burn <- sigma0^2 burnvec <- c(p, mean_burn, var_burn) if (var_burn > 0){ inv_var_burn <- 1 / var_burn } else { inv_var_burn <- 1 } thelimits <- c(0,0) jumpdetected <- FALSE while((jumpdetected==FALSE) && (streampos < N)){ streampos <- update_streampos(streampos) x_new <- get_nextobs_fromstream(stream, streampos) Delta_new <- update_Delta(Delta_new, lambda, m_new) Omega_new <- update_Omega(Omega_new, lambda, w_new) m_new <- update_m(m_new, lambda, x_new) w_new <- update_w(w_new, lambda) u_new <- update_u(u_new, w_new) v_old <- v_new v_new <- getv_from_u_and_w(u_new, w_new) affmean_old <- affmean_new affmean_new <- get_xbar(m_new, w_new) xbar_old_deriv <- xbar_new_deriv xbar_new_deriv <- get_xbar_deriv(Delta_new, affmean_new, Omega_new, w_new) affvar_old <- affvar_new affvar_new <- update_var(affvar_old, affmean_old, lambda, v_old, v_new, w_new, x_new) thelimits <- getNormalLimitsFromList(burnvec, u_new) inLimitsBool <- isInLimitsNormal(affmean_new, thelimits) if(inLimitsBool == FALSE) { jumpdetected <- TRUE detected_count <- detected_count + 1 detect_pos_vec[detected_count] <- streampos } L_deriv_new <- get_L_deriv(affmean_old, xbar_old_deriv, x_new) L_deriv_scaled <- L_deriv_new*inv_var_burn lambda <- update_lambda(lambda, signchosen, alpha, L_deriv_scaled) lambda <- inbounds(lambda, low_bound, up_bound) lambda_vec[streampos] <- lambda } } detect_pos_vec <- detect_pos_vec[1:detected_count] return( list(tau=detect_pos_vec, lambda=lambda_vec) ) }
expected <- eval(parse(text="structure(list(name = \"list\", objs = structure(list(`package:base` = .Primitive(\"list\"), .Primitive(\"list\")), .Names = c(\"package:base\", \"\")), where = c(\"package:base\", \"namespace:base\"), visible = c(TRUE, FALSE), dups = c(FALSE, TRUE)), .Names = c(\"name\", \"objs\", \"where\", \"visible\", \"dups\"))")); test(id=0, code={ argv <- eval(parse(text="list(name = \"list\", objs = structure(list(`package:base` = .Primitive(\"list\"), .Primitive(\"list\")), .Names = c(\"package:base\", \"\")), where = c(\"package:base\", \"namespace:base\"), visible = c(TRUE, FALSE), dups = c(FALSE, TRUE))")); do.call(`list`, argv); }, o=expected);
.D_0 <- function(log.p) if(log.p) -Inf else 0 .D_1 <- function(log.p) as.integer(!log.p) .DT_0 <- function(lower.tail, log.p) if(lower.tail) .D_0(log.p) else .D_1(log.p) .DT_1 <- function(lower.tail, log.p) if(lower.tail) .D_1(log.p) else .D_0(log.p) .D_Lval <- function(p, lower.tail) if(lower.tail) p else (1 - p) .D_Cval <- function(p, lower.tail) if(lower.tail) (1 - p) else p .D_val <- function(x, log.p) if(log.p) log(x) else x .D_qIv <- function(p, log.p) if(log.p) exp(p) else p .D_exp <- function(x, log.p) if(log.p) x else exp(x) .D_log <- function(p, log.p) if(log.p) p else log(p) .D_Clog<- function(p, log.p) if(log.p) log1p(-p) else ((0.5 - p) + 0.5) M_LN2 <- log(2) M_SQRT2 <- sqrt(2) log1mexp <- function(x) ifelse(x <= M_LN2, log(-expm1(-x)), log1p(-exp(-x))) .D_LExp <- function(x, log.p) if(log.p) log1mexp(-x) else log1p(-x) .DT_val <- function(x, lower.tail, log.p) .D_val(.D_Lval(x, lower.tail), log.p) .DT_Cval <- function(x, lower.tail, log.p) .D_val(.D_Cval(x, lower.tail), log.p) .DT_qIv <- function(p, lower.tail, log.p) { if(log.p) if(lower.tail) exp(p) else - expm1(p) else .D_Lval(p, lower.tail) } .DT_CIv <- function(p, lower.tail, log.p) { if(log.p) if(lower.tail) -expm1(p) else exp(p) else .D_Cval(p, lower.tail) } .DT_exp <- function(x, lower.tail, log.p) .D_exp(.D_Lval(x, lower.tail), log.p) .DT_Cexp <- function(x, lower.tail, log.p) .D_exp(.D_Cval(x, lower.tail), log.p) .DT_log <- function(p, lower.tail, log.p) if(lower.tail) .D_log(p, log.p) else .D_LExp(p, log.p) .DT_Clog <- function(p, lower.tail, log.p) if(lower.tail) .D_LExp(p, log.p) else .D_log(p, log.p) .DT_Log <- function(p, lower.tail) if(lower.tail) p else log1mexp(-p) .D_fexp <- function(f, x, log.p) if(log.p) -0.5*log(f)+ x else exp(x)/sqrt(f) .D_rtxp <- function(rf, x, log.p) if(log.p) -log(rf) + x else exp(x)/rf
find_scale <- function(aes, x, env = parent.frame()) { type <- scale_type(x) candidates <- paste("scale", aes, type, sep = "_") for (scale in candidates) { scale_f <- find_global(scale, env, mode = "function") if (!is.null(scale_f)) return(scale_f()) } return(NULL) } find_global <- function(name, env, mode = "any") { if (exists(name, envir = env, mode = mode)) { return(get(name, envir = env, mode = mode)) } nsenv <- asNamespace("animint2") if (exists(name, envir = nsenv, mode = mode)) { return(get(name, envir = nsenv, mode = mode)) } NULL } scale_type <- function(x) UseMethod("scale_type") scale_type.default <- function(x) { message("Don't know how to automatically pick scale for object of type ", paste(class(x), collapse = "/"), ". Defaulting to continuous.") "continuous" } scale_type.AsIs <- function(x) "identity" scale_type.logical <- function(x) "discrete" scale_type.character <- function(x) "discrete" scale_type.ordered <- function(x) c("ordinal", "discrete") scale_type.factor <- function(x) "discrete" scale_type.POSIXt <- function(x) c("datetime", "continuous") scale_type.Date <- function(x) c("date", "continuous") scale_type.numeric <- function(x) "continuous"
SeSpPPVNPV <-function(cutpoint,T,delta,marker,other_markers=NULL,cause,weighting="marginal",times,iid=FALSE){ if (length(delta)!=length(T) | length(marker)!=length(T) | length(delta)!=length(T)){ stop("lengths of vector T, delta and marker have to be equal\n") } if (missing(times)){ stop("Choose at least one time for computing the time-dependent AUC\n") } if (!weighting %in% c("marginal","cox","aalen")){ stop("the weighting argument must be marginal (default), cox or aalen.\n") } if (weighting %in% c("cox","aalen") & !missing(other_markers) & !("matrix" %in% class(other_markers))){ stop("argument other_markers must be a matrix\n") } if (weighting %in% c("cox","aalen") & !missing(other_markers)){ if(!nrow(other_markers)==length(marker)) stop("lengths of vector T, delta, marker and number of rows of other_markers have to be equal\n") } if(weighting!="marginal" & iid){ stop("Weighting must be marginal for computing the iid representation \n Choose iid=FALSE or weighting=marginal in the input arguments") } if (weighting %in% c("cox","aalen") & !missing(other_markers) ){ is_not_na <- as.logical(apply(!is.na(cbind(T,delta,marker,other_markers)),1,prod)) T <- T[is_not_na] delta <- delta[is_not_na] marker <- marker[is_not_na] other_markers <- as.matrix(other_markers[is_not_na,]) }else{ is_not_na <- as.logical(apply(!is.na(cbind(T,delta,marker)),1,prod)) T <- T[is_not_na] delta <- delta[is_not_na] marker <- marker[is_not_na] } start_computation_time <- Sys.time() n <- length(T) n_times <- length(times) if (n_times==1){times<-c(0,times) n_times<-2} times <- times[order(times)] times_names <- paste("t=",times,sep="") CumInci <- rep(NA,n_times) surv <- rep(NA,n_times) names(CumInci) <- times_names names(surv) <- times_names Stats <- matrix(NA,nrow=n_times,ncol=6) colnames(Stats) <- c("Cases","survivor at t","Other events at t","Censored at t","Positive (X>c)","Negative (X<=c)") rownames(Stats) <- times_names Stats[,c("Positive (X>c)","Negative (X<=c)")] <- matrix(c(sum(marker>cutpoint),sum(marker<=cutpoint)),byrow=TRUE,ncol=2,nrow=nrow(Stats)) order_T<-order(T) T <- T[order_T] delta <- delta[order_T] marker<- marker[order_T] if(weighting=="marginal"){ weights <- pec::ipcw(Surv(failure_time,status)~1,data=data.frame(failure_time=T,status=as.numeric(delta!=0)),method="marginal",times=times,subjectTimes=T,subjectTimesLag=1) } if(weighting=="cox"){ if (missing(other_markers)){marker_censoring<-marker } other_markers<-other_markers[order_T,] marker_censoring<-cbind(marker,other_markers) colnames(marker_censoring)<-paste("X", 1:ncol(marker_censoring), sep="") fmla <- as.formula(paste("Surv(T,status)~", paste(paste("X", 1:ncol(marker_censoring), sep=""), collapse= "+"))) data_weight<-as.data.frame(cbind(data.frame(T=T,status=as.numeric(delta!=0)),marker_censoring)) weights <- pec::ipcw(fmla,data=data_weight,method="cox",times=as.matrix(times),subjectTimes=data_weight[,"T"],subjectTimesLag=1) } if(weighting=="aalen"){ if (missing(other_markers)){marker_censoring<-marker } other_markers<-other_markers[order_T,] marker_censoring<-cbind(marker,other_markers) colnames(marker_censoring)<-paste("X", 1:ncol(marker_censoring), sep="") fmla <- as.formula(paste("Surv(T,status)~", paste(paste("X", 1:ncol(marker_censoring), sep=""), collapse= "+"))) data_weight<-as.data.frame(cbind(data.frame(T=T,status=as.numeric(delta!=0)),marker_censoring)) weights <- pec::ipcw(fmla,data=data_weight,method="aalen",times=as.matrix(times),subjectTimes=data_weight[,"T"],subjectTimesLag=1) } Mat.data<-cbind(T,delta,marker) colnames(Mat.data)<-c("T","delta","marker") Weights_cases_all<-1/(weights$IPCW.subjectTimes*n) Weights_cases_all<-Weights_cases_all FP_1 <- rep(NA,n_times) TP <- rep(NA,n_times) FP_2 <- rep(NA,n_times) PPV <- rep(NA,n_times) NPV_1<- rep(NA,n_times) NPV_2<- rep(NA,n_times) names(FP_1) <- times_names names(TP) <- times_names names(FP_2) <- times_names names(PPV) <- times_names names(NPV_1) <- times_names names(NPV_2) <- times_names if (iid){ MatInt0TcidhatMCksurEff <- Compute.iid.KM(T,delta!=0) epsiloni.Se <- matrix(NA,nrow=n,ncol=n_times) epsiloni.Sp1 <- matrix(NA,nrow=n,ncol=n_times) epsiloni.Sp2 <- matrix(NA,nrow=n,ncol=n_times) epsiloni.PPV <- matrix(NA,nrow=n,ncol=n_times) epsiloni.NPV1 <- matrix(NA,nrow=n,ncol=n_times) epsiloni.NPV2 <- matrix(NA,nrow=n,ncol=n_times) se.Se <- rep(NA,n_times) se.Sp1 <- rep(NA,n_times) se.Sp2 <- rep(NA,n_times) names(se.Sp1) <- times_names names(se.Sp2) <- times_names names(se.Se) <- times_names colnames(epsiloni.Se) <- times_names colnames(epsiloni.Sp1) <- times_names colnames(epsiloni.Sp2) <- times_names colnames(epsiloni.PPV) <- times_names colnames(epsiloni.NPV1) <- times_names colnames(epsiloni.NPV2) <- times_names } for(t in 1:n_times){ Cases<-(Mat.data[,"T"]< times[t] & Mat.data[,"delta"]==cause) Controls_1<-(Mat.data[,"T"]> times[t] ) Controls_2<-(Mat.data[,"T"]< times[t] & Mat.data[,"delta"]!=cause & Mat.data[,"delta"]!=0) if (weights$method!="marginal"){ Weights_controls_1<-1/(weights$IPCW.times[,t]*n) }else{ Weights_controls_1<-rep(1/(weights$IPCW.times[t]*n),times=n) } Weights_controls_1<-Weights_controls_1 Weights_cases<-Weights_cases_all Weights_controls_2<-Weights_cases_all Weights_cases[!Cases]<-0 Weights_controls_1[!Controls_1]<-0 Weights_controls_2[!Controls_2]<-0 den_TP_t<-sum(Weights_cases) den_FP_1_t<-sum(Weights_controls_1) den_FP_2_t<-sum(Weights_controls_2)+sum(Weights_controls_1) den_PPV_t <- sum(Weights_cases[which(Mat.data[,"marker"] > cutpoint)] + Weights_controls_1[which(Mat.data[,"marker"] > cutpoint)] + Weights_controls_2[which(Mat.data[,"marker"] > cutpoint)]) den_NPV_t <- sum(Weights_cases[which(Mat.data[,"marker"] <= cutpoint)] + Weights_controls_1[which(Mat.data[,"marker"] <= cutpoint)] + Weights_controls_2[which(Mat.data[,"marker"] <= cutpoint)]) if(den_TP_t!=0){ TP[t] <- sum(Weights_cases[which(Mat.data[,"marker"] > cutpoint)])/den_TP_t } if(den_FP_1_t!=0){ FP_1[t] <- sum(Weights_controls_1[which(Mat.data[,"marker"] > cutpoint)])/den_FP_1_t } if(den_FP_2_t!=0){ FP_2[t] <- sum(Weights_controls_1[which(Mat.data[,"marker"] > cutpoint)] + Weights_controls_2[which(Mat.data[,"marker"] > cutpoint)])/den_FP_2_t NPV_2[t] <- ((1-FP_2[t])*den_FP_2_t)/den_NPV_t } CumInci[t] <- c(den_TP_t) surv[t] <- c(den_FP_1_t) Stats[t,1:4] <- c(sum(Cases),sum(Controls_1),sum(Controls_2),n-sum(Cases)-sum(Controls_1)-sum(Controls_2)) PPV[t] <- (TP[t]*CumInci[t])/den_PPV_t NPV_1[t] <- ((1-FP_1[t])*surv[t])/den_NPV_t if (iid){ Int0tdMCsurEffARisk <- NA Int0tdMCsurEffARisk <- MatInt0TcidhatMCksurEff[max(which(Mat.data[,"T"] <= times[t])),] Weights_cases <- Weights_cases Weights_controls_2 <- Weights_controls_2 Weights_controls_1 <- Weights_controls_1 epsiloni.Se[,t] <- Weights_cases*n*(as.numeric(Mat.data[,"marker"] > cutpoint)-TP[t])/CumInci[t] + colMeans(MatInt0TcidhatMCksurEff*(Weights_cases*n*(as.numeric(Mat.data[,"marker"] > cutpoint)-TP[t])/CumInci[t])) epsiloni.Sp1[,t] <- (n/sum(Controls_1))*as.numeric(Mat.data[,"T"]>times[t])*(as.numeric(Mat.data[,"marker"] <= cutpoint)-(1-FP_1[t])) epsiloni.Sp2[,t] <- (Weights_controls_2*n + Weights_controls_1*n)*(as.numeric(Mat.data[,"marker"] <= cutpoint)-(1-FP_2[t]))/(1-CumInci[t]) + colMeans(MatInt0TcidhatMCksurEff*((Weights_controls_2*n)*(as.numeric(Mat.data[,"marker"] <= cutpoint)-(1-FP_2[t]))/(1-CumInci[t]))) + mean((Weights_controls_1*n)*(as.numeric(Mat.data[,"marker"] <= cutpoint)-(1-FP_2[t]))/(1-CumInci[t]))*Int0tdMCsurEffARisk epsiloni.PPV[,t] <- (as.numeric(Mat.data[,"marker"] > cutpoint)/den_PPV_t)*((Weights_cases*n + Weights_controls_2*n)*(as.numeric(Mat.data[,"delta"]==cause)-as.numeric(Mat.data[,"delta"]!=0)*PPV[t] ) - Weights_controls_1*n*PPV[t] ) + colMeans(MatInt0TcidhatMCksurEff*((as.numeric(Mat.data[,"marker"] > cutpoint)/den_PPV_t )*(Weights_cases*n + Weights_controls_2*n )*(as.numeric(Mat.data[,"delta"]==cause)-as.numeric(Mat.data[,"delta"]!=0)*PPV[t] )) )-mean((as.numeric(Mat.data[,"marker"] > cutpoint)/den_PPV_t )* Weights_controls_1*n*PPV[t] )*Int0tdMCsurEffARisk epsiloni.NPV2[,t] <- (as.numeric(Mat.data[,"marker"] <= cutpoint)/den_NPV_t)*((Weights_cases*n + Weights_controls_2*n)*(as.numeric(Mat.data[,"delta"]!=0 & Mat.data[,"delta"]!=cause)-as.numeric(Mat.data[,"delta"]!=0)*NPV_2[t] ) + Weights_controls_1*n*(1-NPV_2[t]) ) + colMeans(MatInt0TcidhatMCksurEff*((as.numeric(Mat.data[,"marker"] <= cutpoint)/den_NPV_t )*(Weights_cases*n + Weights_controls_2*n )*(as.numeric(Mat.data[,"delta"]!=0 & Mat.data[,"delta"]!=cause)-as.numeric(Mat.data[,"delta"]!=0)*NPV_2[t] )) )+mean((as.numeric(Mat.data[,"marker"] <= cutpoint)/den_NPV_t )* Weights_controls_1*n*(1-NPV_2[t]))*Int0tdMCsurEffARisk epsiloni.NPV1[,t] <- (as.numeric(Mat.data[,"marker"] <= cutpoint)/den_NPV_t)*((Weights_cases*n + Weights_controls_2*n)*(-as.numeric(Mat.data[,"delta"]!=0)*NPV_1[t] ) + Weights_controls_1*n*(1-NPV_1[t]) ) + colMeans(MatInt0TcidhatMCksurEff* ((as.numeric(Mat.data[,"marker"] <= cutpoint)/den_NPV_t )*(Weights_cases*n + Weights_controls_2*n )*(-as.numeric(Mat.data[,"delta"]!=0)*NPV_1[t] )) )+mean((as.numeric(Mat.data[,"marker"] <= cutpoint)/den_NPV_t )*Weights_controls_1*n*(1-NPV_1[t]) )*Int0tdMCsurEffARisk } } if (iid){ se.Se <- apply(epsiloni.Se,2,sd)/sqrt(n) se.Sp1 <- apply(epsiloni.Sp1,2,sd)/sqrt(n) se.Sp2 <- apply(epsiloni.Sp2,2,sd)/sqrt(n) se.PPV <- apply(epsiloni.PPV,2,sd)/sqrt(n) se.NPV1 <- apply(epsiloni.NPV1,2,sd)/sqrt(n) se.NPV2 <- apply(epsiloni.NPV2,2,sd)/sqrt(n) } if (iid){ inference<-list(mat_iid_rep_Se=epsiloni.Se, mat_iid_rep_Sp1=epsiloni.Sp1, mat_iid_rep_Sp2=epsiloni.Sp2, mat_iid_rep_PPV=epsiloni.PPV, mat_iid_rep_NPV1=epsiloni.NPV1, mat_iid_rep_NPV2=epsiloni.NPV2, vect_se_Se=se.Se, vect_se_Sp1=se.Sp1, vect_se_Sp2=se.Sp2, vect_se_PPV=se.PPV, vect_se_NPV1=se.NPV1, vect_se_NPV2=se.NPV2 ) }else{ inference<-NA } stop_computation_time<-Sys.time() if (max(Stats[,3])==0){ out <- list(TP=TP,FP=FP_1,PPV=PPV,NPV=NPV_1,Stats=Stats[,-3], inference=inference, computation_time=difftime(stop_computation_time,start_computation_time,units="secs"), iid=iid, n=n,times=times,weights=weights, cutpoint=cutpoint) class(out) <- "ipcwsurvivalSeSpPPVNPV" out }else{ out <- list(TP=TP,FP_1=FP_1,FP_2=FP_2,PPV=PPV,NPV_1=NPV_1,NPV_2=NPV_2, Stats=Stats, inference=inference, computation_time=difftime(stop_computation_time,start_computation_time,units="secs"), iid=iid, n=n,times=times,weights=weights, cutpoint=cutpoint) class(out) <- "ipcwcompetingrisksSeSpPPVNPV" out } }
"wic_col6"
noiseParamInit <- function(noise, y) { noise$spherical = 0 noise$logconcave = 1 fhandle <- get(paste(noise$type, "NoiseParamInit", sep=""), mode="function") if (nargs() > 1) noise = fhandle(noise, y) else noise = fhandle(noise) return (noise) }
modelAvg <- function(fitList,ID,nonCon=TRUE){ fitList$distribution<-as.character(fitList$distribution) dists<-unique(fitList[,ID]) outAIC<-c() outBIC<-c() outAICavg<-c() outBICavg<-c() outWeightsAIC<-c() outWeightsBIC<-c() outWeightsAIC<-rep(NA, nrow(fitList)) outWeightsBIC<-rep(NA, nrow(fitList)) for(i in dists){ use.i<-which(fitList[,ID]==i) dat.i<-fitList[use.i,] if(nonCon==TRUE){ con.i<-which(dat.i$didConverge==TRUE&is.na(dat.i$estMean)==FALSE) }else{ con.i<-which(is.na(dat.i$est)==FALSE) } if(length(con.i)==0){ bestMod<-'nothingConverged' avgAIC.i<-'nothingConverged' avgBIC.i<-'nothingConverged' }else{ bestMod.aic<-which(dat.i$aic[con.i]==min(dat.i$aic[con.i],na.rm=TRUE)) bestMod.bic<-which(dat.i$bic[con.i]==min(dat.i$bic[con.i],na.rm=TRUE)) use.AIC.i<-which(fitList[,ID]==i&fitList$distribution==dat.i$distribution[con.i][bestMod.aic])[1] use.BIC.i<-which(fitList[,ID]==i&fitList$distribution==dat.i$distribution[con.i][bestMod.bic])[1] wAIC.i<-makeWeightsAIC(dat.i$aic[con.i]) wBIC.i<-makeWeightsAIC(dat.i$bic[con.i]) avgAIC.i<-mAvg(dat.i$estMean[con.i],wAIC.i) avgBIC.i<-mAvg(dat.i$estMean[con.i],wBIC.i) outAIC<-c(outAIC, use.AIC.i) outBIC<-c(outBIC, use.BIC.i) outWeightsAIC[use.i[con.i]]<-wAIC.i outWeightsBIC[use.i[con.i]]<-wBIC.i } outAICavg<-c(outAICavg,avgAIC.i) outBICavg<-c(outBICavg,avgBIC.i) } aicOut<-matrix(NA, ncol=ncol(fitList), nrow=length(dists)) aicOut<-as.data.frame(aicOut) use.aic<-which(outAICavg!='nothingConverged') if(length(use.aic)>0){ aicOut[use.aic,]<-fitList[outAIC,] } aicOut[,1]<-dists colnames(aicOut)<-colnames(fitList) bicOut<-matrix(NA, ncol=ncol(fitList), nrow=length(dists)) bicOut<-as.data.frame(bicOut) use.bic<-which(outBICavg!='nothingConverged') if(length(use.bic)>0){ bicOut[use.bic,]<- fitList[outBIC,] } bicOut[,1]<-dists colnames(bicOut)<-colnames(fitList) out<-list('aic'= aicOut,'bic'= bicOut,'aicAvg'=outAICavg,'bicAvg'=outBICavg,'waic'=outWeightsAIC,'wbic'=outWeightsBIC) return(out) }
library("PEcAn.all") library("PEcAn.utils") library("RCurl") library("REddyProc") library("tidyverse") library("furrr") library("R.utils") library("dynutils") plan(multisession) outputPath <- "/projectnb/dietzelab/kzarada/US_WCr_SDA_output/NoData/" nodata <- TRUE restart <- FALSE days.obs <- 1 setwd(outputPath) c( 'Utils.R', 'download_WCr.R', "gapfill_WCr.R", 'prep.data.assim.R' ) %>% walk( ~ source( system.file("WillowCreek", .x, package = "PEcAn.assim.sequential") )) setwd("/projectnb/dietzelab/kzarada/US_WCr_SDA_output/NoData/") settings <- read.settings("/fs/data3/kzarada/pecan/modules/assim.sequential/inst/WillowCreek/nodata.xml") con <-try(PEcAn.DB::db.open(settings$database$bety), silent = TRUE) sda.start <- Sys.Date() sda.end <- sda.start + lubridate::days(3) met.start <- sda.start - lubridate::days(2) met.end <- met.start + lubridate::days(16) date <- seq( from = lubridate::with_tz(as.POSIXct(sda.start, format = "%Y-%m-%d %H:%M:%S"), tz = "UTC"), to = lubridate::with_tz(as.POSIXct(sda.end, format = "%Y-%m-%d %H:%M:%S"), tz = "UTC"), by = "1 hour" ) pad.prep <- as.data.frame(cbind(Date = as.character(date), means = rep("NA", length(date)), covs = rep("NA", length(date)))) %>% dynutils::tibble_as_list() names(pad.prep) <-date prep.data = pad.prep obs.mean <- prep.data %>% purrr::map('means') %>% setNames(names(prep.data)) obs.cov <- prep.data %>% purrr::map('covs') %>% setNames(names(prep.data)) if (nodata) { obs.mean <- obs.mean %>% purrr::map(function(x) return(NA)) obs.cov <- obs.cov %>% purrr::map(function(x) return(NA)) } sapply(paste0("/projectnb/dietzelabe/pecan.data/dbfiles/IC_site_0-676_", 1:100, ".nc"), unlink) settings$run$start.date <- as.character(met.start) settings$run$end.date <- as.character(met.end) settings$run$site$met.start <- as.character(met.start) settings$run$site$met.end <- as.character(met.end) settings$info$date <- paste0(format(Sys.time(), "%Y/%m/%d %H:%M:%S"), " +0000") settings <- PEcAn.settings::prepare.settings(settings, force=FALSE) setwd(settings$outdir) PEcAn.settings::write.settings(settings, outputfile = "pecan.CHECKED.xml") statusFile <- file.path(settings$outdir, "STATUS") if (length(which(commandArgs() == "--continue")) == 0 && file.exists(statusFile)) { file.remove(statusFile) } settings <- PEcAn.workflow::do_conversions(settings, T, T, T) if (PEcAn.utils::status.check("TRAIT") == 0) { PEcAn.utils::status.start("TRAIT") settings <- PEcAn.workflow::runModule.get.trait.data(settings) PEcAn.settings::write.settings(settings, outputfile = 'pecan.TRAIT.xml') PEcAn.utils::status.end() } else if (file.exists(file.path(settings$outdir, 'pecan.TRAIT.xml'))) { settings <- PEcAn.settings::read.settings(file.path(settings$outdir, 'pecan.TRAIT.xml')) } if (!is.null(settings$meta.analysis)) { if (PEcAn.utils::status.check("META") == 0) { PEcAn.utils::status.start("META") PEcAn.MA::runModule.run.meta.analysis(settings) PEcAn.utils::status.end() } } get.parameter.samples(settings, ens.sample.method = settings$ensemble$samplingspace$parameters$method) settings$state.data.assimilation$start.date <-as.character(first(names(obs.mean))) settings$state.data.assimilation$end.date <-as.character(last(names(obs.mean))) if(restart == TRUE){ if(!dir.exists("SDA")) dir.create("SDA",showWarnings = F) temp<- new.env() load(file.path(restart.path, "SDA", "sda.output.Rdata"), envir = temp) temp <- as.list(temp) if(length(temp$ANALYSIS) > 1){ for(i in 1:days.obs + 1){ temp$ANALYSIS[[i]] <- temp$ANALYSIS[[i + 24]] } for(i in rev((days.obs + 2):length(temp$ANALYSIS))){ temp$ANALYSIS[[i]] <- NULL } for(i in 1:days.obs + 1){ temp$FORECAST[[i]] <- temp$FORECAST[[i + 24]] } for(i in rev((days.obs + 2):length(temp$FORECAST))){ temp$FORECAST[[i]] <- NULL } for(i in 1:days.obs + 1){ temp$enkf.params[[i]] <- temp$enkf.params[[i + 24]] } for(i in rev((days.obs + 2):length(temp$enkf.params))){ temp$enkf.params[[i]] <- NULL } } temp$t = 1 for(i in 1: length(temp$inputs$ids)){ temp$inputs$samples[i] <- settings$run$inputs$met$path[temp$inputs$ids[i]] } temp1<- new.env() list2env(temp, envir = temp1) save(list = c("ANALYSIS", "enkf.params", "ensemble.id", "ensemble.samples", 'inputs', 'new.params', 'new.state', 'run.id', 'site.locs', 't', 'Viz.output', 'X'), envir = temp1, file = file.path(settings$outdir, "SDA", "sda.output.Rdata")) temp.out <- new.env() load(file.path(restart.path, "SDA", 'outconfig.Rdata'), envir = temp.out) temp.out <- as.list(temp.out) temp.out$outconfig$samples <- NULL temp.out1 <- new.env() list2env(temp.out, envir = temp.out1) save(list = c('outconfig'), envir = temp.out1, file = file.path(settings$outdir, "SDA", "outconfig.Rdata")) if(!dir.exists("run")) dir.create("run",showWarnings = F) files <- list.files(path = file.path(restart.path, "run/"), full.names = T, recursive = T, include.dirs = T, pattern = "sipnet.clim") readfiles <- list.files(path = file.path(restart.path, "run/"), full.names = T, recursive = T, include.dirs = T, pattern = "README.txt") newfiles <- gsub(pattern = restart.path, settings$outdir, files) readnewfiles <- gsub(pattern = restart.path, settings$outdir, readfiles) rundirs <- gsub(pattern = "/sipnet.clim", "", files) rundirs <- gsub(pattern = restart.path, settings$outdir, rundirs) for(i in 1 : length(rundirs)){ dir.create(rundirs[i]) file.copy(from = files[i], to = newfiles[i]) file.copy(from = readfiles[i], to = readnewfiles[i])} file.copy(from = paste0(restart.path, '/run/runs.txt'), to = paste0(settings$outdir,'/run/runs.txt' )) if(!dir.exists("out")) dir.create("out",showWarnings = F) files <- list.files(path = file.path(restart.path, "out/"), full.names = T, recursive = T, include.dirs = T, pattern = "sipnet.out") newfiles <- gsub(pattern = restart.path, settings$outdir, files) outdirs <- gsub(pattern = "/sipnet.out", "", files) outdirs <- gsub(pattern = restart.path, settings$outdir, outdirs) for(i in 1 : length(outdirs)){ dir.create(outdirs[i]) file.copy(from = files[i], to = newfiles[i])} } settings$host$name <- "geo.bu.edu" settings$host$user <- 'kzarada' settings$host$folder <- "/projectnb/dietzelab/kzarada/US_WCr_SDA_output" settings$host$job.sh <- "module load udunits/2.2.26 R/3.5.1" settings$host$qsub <- 'qsub -l h_rt=24:00:00 -V -N @NAME@ -o @STDOUT@ -e @STDERR@' settings$host$qsub.jobid <- 'Your job ([0-9]+) .*' settings$host$qstat <- 'qstat -j @JOBID@ || echo DONE' settings$host$tunnel <- '/tmp/tunnel' settings$model$binary = "/usr2/postdoc/istfer/SIPNET/1023/sipnet" unlink(c('run','out'), recursive = T) if ('state.data.assimilation' %in% names(settings)) { if (PEcAn.utils::status.check("SDA") == 0) { PEcAn.utils::status.start("SDA") PEcAn.assim.sequential::sda.enkf( settings, restart=restart, Q=0, obs.mean = obs.mean, obs.cov = obs.cov, control = list( trace = TRUE, interactivePlot =FALSE, TimeseriesPlot =TRUE, BiasPlot =FALSE, debug = FALSE, pause=FALSE ) ) PEcAn.utils::status.end() } }
library(hamcrest) expected <- c(0x1.44bb4ae97c518p+5 + 0x1.91e58e87adfbap-1i, -0x1.626c2c360043p+5 + -0x1.947a06bc775a3p-1i, 0x1.35158d8000922p+5 + 0x1.96a84ef60e64ap-1i, -0x1.17b23a8683d72p+5 + -0x1.986fda28ed77ep-1i, 0x1.70d326f5b4514p+5 + 0x1.99d0353e47574p-1i, -0x1.55cb510aecc68p+5 + -0x1.9ac907311aa09p-1i, 0x1.8370f08eb310dp+4 + 0x1.9b5a1124af155p-1i, -0x1.bda50ebeee6c8p+4 + -0x1.9b832e7477924p-1i, 0x1.2e7864fb7c5c6p+5 + 0x1.9b4454bd53cbep-1i, -0x1.0af35401e355ep+5 + -0x1.9a9d93e0301acp-1i, 0x1.918f08e743c4ap+5 + 0x1.998f15fe02935p-1i, -0x1.4d0150cb65e6p+5 + -0x1.98191f6d262eep-1i, 0x1.afc81e864128fp+5 + 0x1.963c0ea81746ep-1i, -0x1.6cf38b042cb57p+5 + -0x1.93f85c3594beap-1i, 0x1.f5640f9e0432ap+4 + 0x1.914e9a8a2d094p-1i, -0x1.3e7a73fae9b7cp+5 + -0x1.8e3f75e33e022p-1i, 0x1.9c864b8d39404p+5 + 0x1.8acbb41b70ee3p-1i, -0x1.097cedbfbc078p+5 + -0x1.86f43478be625p-1i, 0x1.47e436da70c71p+5 + 0x1.82b9ef740576ep-1i, -0x1.6714c0b457a5ep+5 + -0x1.7e1df67a45bfcp-1i, 0x1.32fa6b4fe51f7p+5 + 0x1.792173a78b4fep-1i, -0x1.863cb817c2386p+4 + -0x1.73c5a97b9dae1p-1i, 0x1.bb57629f4b85p+3 + 0x1.6e0bf2888674ep-1i, -0x1.06421c5899433p+5 + -0x1.67f5c11b0205p-1i, 0x1.32d7d4c216a0cp+5 + 0x1.61849edcf2298p-1i, -0x1.7b88d8461e664p+5 + -0x1.5aba2c71e9783p-1i, 0x1.dde30e7a0255p+5 + 0x1.5398210de8a1bp-1i, -0x1.4ec56e8c709ffp+5 + -0x1.4c204a06689e8p-1i, 0x1.0f51eb688f2eep+2 + 0x1.44548a5dcd442p-1i, -0x1.364fcf88478b7p+4 + -0x1.3c36da495e284p-1i, 0x1.cac6dc9ea6418p+5 + 0x1.33c946b1e484cp-1i, -0x1.26f1dac561a51p+5 + -0x1.2b0df0af0dd18p-1i, 0x1.92e187428b8bp+1 + 0x1.22070cfdb5aaap-1i, -0x1.3574ce42f861fp+4 + -0x1.18b6e3713881cp-1i, 0x1.d7f15cff6a3bcp+4 + 0x1.0f1fce5ff415ap-1i, -0x1.5d3052395742p+0 + -0x1.05443a0b1ac72p-1i, 0x1.61346db077beep+4 + 0x1.f64d4803ff37cp-2i, -0x1.df78522cf1fc1p+4 + -0x1.e193350207854p-2i, 0x1.6994b84cfb498p+5 + 0x1.cc5f779899796p-2i, -0x1.958396a5aa6a5p+4 + -0x1.b6b76b0cdcce1p-2i, 0x1.e1d8148c5796ap+3 + 0x1.a0a08806654ep-2i, -0x1.d78f45b9e5b04p+5 + -0x1.8a20632d55fc8p-2i, 0x1.a7efbc0a1bbfbp+5 + 0x1.733cabc1714eep-2i, -0x1.5766bb36e786cp+5 + -0x1.5bfb2a2a70e02p-2i, 0x1.f628ae5c65bd1p+4 + 0x1.4461be8202d3cp-2i, -0x1.0f236fe739e6ep+5 + -0x1.2c765f17cac38p-2i, 0x1.27893b9ba5a93p+5 + 0x1.143f16efc508ep-2i, -0x1.755eb005a137ep+5 + -0x1.f7840876e1aa5p-3i, 0x1.6c6ee12c68db7p+4 + 0x1.c60aad9c401cbp-3i, -0x1.6a6d33900990fp+5 + -0x1.941e9d19a7f2ap-3i, 0x1.9d9fdf4e54212p+5 + 0x1.61cc73b414821p-3i, -0x1.507783f31b667p+4 + -0x1.2f20e7fbc1366p-3i, 0x1.b16c28306aac2p+4 + 0x1.f8518e2bdbbe6p-4i, -0x1.566c6b8ca731cp+5 + -0x1.91e1e301d9776p-4i, 0x1.3ebcb5f7404cbp+5 + 0x1.2b0cafa69d28ep-4i, -0x1.50945256ea418p+5 + -0x1.87d7dddbf546cp-5i, 0x1.e045e8e73cc1p+4 + 0x1.7266bb08c65fp-6i, -0x1.0359c8b61d9c6p+5 + 0x1.59fece252028p-9i, 0x1.fc5858c7b6a66p+4 + -0x1.c8db815db7cfp-6i, -0x1.ef10d2c302158p+4 + 0x1.b301de9943d0cp-5i, 0x1.277505947ab72p+5 + -0x1.40940af70790ep-4i, -0x1.4ed1f3cf15bfcp+5 + 0x1.a75628dedd1f2p-4i, 0x1.7cc6d1eac03c5p+5 + -0x1.06d6a98149086p-3i, -0x1.58b95a831e596p+5 + 0x1.39bfd732ebecbp-3i, 0x1.36229b500c72cp+5 + -0x1.6c59c0cced9afp-3i, -0x1.f4c6ea7fddba6p+4 + 0x1.9e979d9e821c7p-3i, 0x1.912c3fd11f08bp+5 + -0x1.d06cbc384c9e8p-3i, -0x1.0dafb43d44f87p+5 + 0x1.00e642d0a78c4p-2i, 0x1.921587300e703p+5 + -0x1.19554042969ap-2i, -0x1.4896dd6e68f74p+5 + 0x1.317d2a2d77a1cp-2i, 0x1.b4df3296cadf8p+4 + -0x1.4957e641bef06p-2i, -0x1.17879ae882e6bp+5 + 0x1.60df6daf85524p-2i, 0x1.34ec7af3d3962p+4 + -0x1.780dceac4eb46p-2i, -0x1.22224cd82b083p+5 + 0x1.8edd2df3822f8p-2i, 0x1.1de6f2acb56edp+4 + -0x1.a547c841308d1p-2i, -0x1.a64dda97ea832p+5 + 0x1.bb47f3c6cac3ap-2i, 0x1.ea4606fe1dcadp+5 + -0x1.d0d821996a1f3p-2i, -0x1.2df53b92874f5p+5 + 0x1.e5f2df194c83dp-2i, 0x1.5e064b44310c8p+5 + -0x1.fa92d7522bd1bp-2i, -0x1.9d15fedfcf5fp+5 + 0x1.07596a2a0abb8p-1i, 0x1.497ac870ea508p+5 + -0x1.1126e042364a4p-1i, -0x1.46f032bb31ed6p+5 + 0x1.1aaf53f36058ap-1i, 0x1.87f2d12d2c9c5p+5 + -0x1.23f05cae92dd2p-1i, -0x1.2fc6c0ce212dp+5 + 0x1.2ce7a3efdedffp-1i, 0x1.03629cfdfe445p+5 + -0x1.3592e5d5920ccp-1i, -0x1.2a39043ee8366p+5 + 0x1.3deff1b2b70a1p-1i, 0x1.1174374db5768p+4 + -0x1.45fcaa9cbc249p-1i, -0x1.0755e9de15eb2p+5 + 0x1.4db707f41b31dp-1i, 0x1.e9ef27504eed2p+4 + -0x1.551d15e7e1e2bp-1i, -0x1.d66dd4ff673aep+4 + 0x1.5c2cf5f3f7c09p-1i, 0x1.f06d6efbebc75p+4 + -0x1.62e4df5a02a3ep-1i, -0x1.b11b9e017b26ap+5 + 0x1.69431f94cb59bp-1i, 0x1.39aaa7a6d132ap+5 + -0x1.6f461ac604718p-1i, -0x1.217b095bd2e05p+5 + 0x1.74ec4c1e588aap-1i, 0x1.c2afb13318019p+4 + -0x1.7a34463fa4ddep-1i, -0x1.d2aa2cd9565b8p+4 + 0x1.7f1cb39947eeep-1i, 0x1.10fe722c71a3ep+5 + -0x1.83a456be6c93fp-1i, -0x1.dd5fedc9a5ef9p+3 + 0x1.87ca0ab63bc16p-1i, 0x1.c88b207d07798p+5 + -0x1.8b8cc345e0dfep-1i, -0x1.6960930329e97p+5 + 0x1.8eeb8d344de77p-1i, 0x1.e728958a84cfp+4 + -0x1.91e58e87adf7ap-1i, -0x1.3912929bae491p+5 + 0x1.947a06bc7766ap-1i, 0x1.4ef211cd5e8c4p+5 + -0x1.96a84ef60e69fp-1i, -0x1.2bd176a45a882p+6 + 0x1.986fda28ed848p-1i, 0x1.1f461336da6dep+5 + -0x1.99d0353e4764cp-1i, -0x1.d2bc24fd6971p+4 + 0x1.9ac907311a99dp-1i, 0x1.0d02919cf6faap+5 + -0x1.9b5a1124af1bcp-1i, -0x1.792ace20a6967p+5 + 0x1.9b832e74779e6p-1i, 0x1.87cb1c85d6353p+5 + -0x1.9b4454bd53d8ap-1i, -0x1.778e54a28166fp+4 + 0x1.9a9d93e030235p-1i, 0x1.3a2250ab2c68ap+5 + -0x1.998f15fe028dep-1i, -0x1.4e76c8a93d06ep+5 + 0x1.98191f6d263c2p-1i, 0x1.63c38e8996076p+5 + -0x1.963c0ea81751p-1i, -0x1.bffe80c53a7d1p+5 + 0x1.93f85c3594c8ep-1i, 0x1.dc10f1eafa2edp+4 + -0x1.914e9a8a2d11ep-1i, -0x1.d53bd4de3bdbfp+4 + 0x1.8e3f75e33e01ep-1i, 0x1.7ba85aab02a8ep+5 + -0x1.8acbb41b70f8cp-1i, -0x1.161ed77f84915p+5 + 0x1.86f43478be6b8p-1i, 0x1.8211085b6602ep+4 + -0x1.82b9ef74057e4p-1i, -0x1.a241385d6eca2p+4 + 0x1.7e1df67a45d28p-1i, 0x1.05b2b1e368c3cp+5 + -0x1.792173a78b4f2p-1i, -0x1.a0af9ac3297a4p+4 + 0x1.73c5a97b9db8ap-1i, 0x1.def4d7ad16e96p+4 + -0x1.6e0bf2888680ep-1i, -0x1.7791b6a8d7366p+5 + 0x1.67f5c11b020b3p-1i, 0x1.49047516b8107p+5 + -0x1.61849edcf2344p-1i, -0x1.5c7f4461f37bcp+5 + 0x1.5aba2c71e978fp-1i, 0x1.34d84eb6f01eap+5 + -0x1.5398210de8b03p-1i, -0x1.8600b95eaf6ccp+5 + 0x1.4c204a0668a35p-1i, 0x1.01f4583bf7d32p+5 + -0x1.44548a5dcd491p-1i, -0x1.0ce0999488e99p+5 + 0x1.3c36da495e355p-1i, 0x1.71f0fd11cc9ffp+5 + -0x1.33c946b1e481ap-1i, -0x1.6ca9de07c3b4ap+5 + 0x1.2b0df0af0ddcdp-1i, 0x1.6a8cdfa4b3456p+5 + -0x1.22070cfdb5b52p-1i, -0x1.9285597c6bdfbp+5 + 0x1.18b6e3713887ep-1i, 0x1.63d23a04e38aep+5 + -0x1.0f1fce5ff422p-1i, -0x1.a16758d7d889cp+4 + 0x1.05443a0b1ac4cp-1i, 0x1.6e4ab45498ca2p+5 + -0x1.f64d4803ff51ep-2i, -0x1.1c703a40efef1p+5 + 0x1.e193350207a19p-2i, 0x1.9a85242602b26p+5 + -0x1.cc5f7798998ecp-2i, -0x1.9721b3af1754fp+5 + 0x1.b6b76b0cdcda2p-2i, 0x1.157e5e4b7fafap+5 + -0x1.a0a0880665503p-2i, -0x1.299141628f355p+3 + 0x1.8a20632d561a9p-2i, 0x1.94bbc755d455dp+4 + -0x1.733cabc1715f6p-2i, -0x1.2a9d649867656p+5 + 0x1.5bfb2a2a70eap-2i, 0x1.207bfa079da6ap+5 + -0x1.4461be8202f45p-2i, -0x1.dbd8f750ad94cp+4 + 0x1.2c765f17caba6p-2i, 0x1.02e011d623e16p+5 + -0x1.143f16efc5201p-2i, -0x1.2902f52efa88bp+5 + 0x1.f7840876e1d78p-3i, 0x1.8f368a47e2517p+5 + -0x1.c60aad9c404c6p-3i, -0x1.16e5cb867a20cp+5 + 0x1.941e9d19a81bp-3i, 0x1.62e4157940336p+5 + -0x1.61cc73b414756p-3i, -0x1.54419fc4f07fep+5 + 0x1.2f20e7fbc1546p-3i, 0x1.4ff51c69111e6p+5 + -0x1.f8518e2bdc008p-4i, -0x1.9f3d64c2ae5bep+4 + 0x1.91e1e301d9a64p-4i, 0x1.6dd70dab81989p+5 + -0x1.2b0cafa69d80cp-4i, -0x1.0796f4cf1d492p+3 + 0x1.87d7dddbf4e78p-5i, 0x1.2cb0976ac80ap+3 + -0x1.7266bb08c797p-6i, -0x1.324c49c07280bp+5 + -0x1.59fece251a88p-9i, 0x1.e464b2c793c02p+4 + 0x1.c8db815db744p-6i, -0x1.553adec90351dp+5 + -0x1.b301de9942f58p-5i, 0x1.47a9daca1853ap+5 + 0x1.40940af707b18p-4i, -0x1.bae2c0981df9cp+5 + -0x1.a75628dedcd52p-4i, 0x1.1cc65b6f8613bp+5 + 0x1.06d6a98148d27p-3i, -0x1.017464175bc4ep+5 + -0x1.39bfd732ebc74p-3i, 0x1.3df621b32beeep+5 + 0x1.6c59c0cced6fp-3i, -0x1.690fe2ee5efa2p+4 + -0x1.9e979d9e821d2p-3i, 0x1.4a5484522daedp+5 + 0x1.d06cbc384c615p-3i, -0x1.6b4f355732caep+5 + -0x1.00e642d0a77eep-2i, 0x1.7d316ea69a05ep+5 + 0x1.1955404296884p-2i, -0x1.630e9a1e9dad3p+5 + -0x1.317d2a2d77813p-2i, 0x1.7ca994a25ff8bp+4 + 0x1.4957e641beee4p-2i, -0x1.ec216ae24408dp+4 + -0x1.60df6daf8535dp-2i, 0x1.108ac35bd05e3p+5 + 0x1.780dceac4e9dp-2i, -0x1.1822b5c92fa6ap+5 + -0x1.8edd2df3821aap-2i, 0x1.1f6c005cf8141p+5 + 0x1.a547c8413069ep-2i, -0x1.298d5d913716ep+5 + -0x1.bb47f3c6cac0ap-2i, 0x1.7f2a3c5ecb74cp+5 + 0x1.d0d821996a07ap-2i, -0x1.bb2caca6d191ap+5 + -0x1.e5f2df194c6edp-2i, 0x1.ab38ba7e74fbdp+5 + 0x1.fa92d7522bbc3p-2i, -0x1.a3482a780ce4p+5 + -0x1.07596a2a0ab15p-1i, 0x1.8605264b45b82p+3 + 0x1.1126e042364dfp-1i, -0x1.5b5fb5261e9c4p+5 + -0x1.1aaf53f3604afp-1i, 0x1.5e9f067ab6c07p+5 + 0x1.23f05cae92d1p-1i, -0x1.f0efcd7ba5035p+4 + -0x1.2ce7a3efded93p-1i, 0x1.bbcc2ee1735acp+4 + 0x1.3592e5d592046p-1i, -0x1.460a0b19a8dd9p+5 + -0x1.3deff1b2b70cap-1i, 0x1.04a635ab84269p+5 + 0x1.45fcaa9cbc15ep-1i, -0x1.17f3ebde3a195p+5 + -0x1.4db707f41b258p-1i, 0x1.033e1e3c1ca65p+5 + 0x1.551d15e7e1dffp-1i, -0x1.02d58c24b0638p+5 + -0x1.5c2cf5f3f7b4fp-1i, 0x1.d27e27df37f6ap+4 + 0x1.62e4df5a02a47p-1i, -0x1.3fb9a1815073cp+4 + -0x1.69431f94cb4d6p-1i, 0x1.0942c99bf5aaep+5 + 0x1.6f461ac604699p-1i, -0x1.ff1de3f252849p+4 + -0x1.74ec4c1e58838p-1i, 0x1.9c1b7296fd186p+5 + 0x1.7a34463fa4d3ap-1i, -0x1.0f96c42b7a39ap+5 + -0x1.7f1cb39947f15p-1i, 0x1.ad8dab5db6cd7p+5 + 0x1.83a456be6c882p-1i, -0x1.245005428c46fp+5 + -0x1.87ca0ab63bb42p-1i, 0x1.9601e9803eab4p+4 + 0x1.8b8cc345e0dacp-1i, -0x1.3164558f846f4p+5 + -0x1.8eeb8d344ddcp-1i ) assertThat(stats:::fft(inverse=TRUE,z=c(0+0i, 0.277990726331056+0.283859957361672i, -0.153011905862873-0.415408324585186i, 0.459263743326068-0.430763048741859i, 0.461851772200813-0.091711596079432i, -0.167776786507607+0.370355046006962i, 0.378446716359935+0.110975920435485i, 0.312154699823781-0.101547186157582i, -0.465746230618912+0.337453085650942i, -0.384894950717506+0.403299602349128i, -0.340076408840021+0.676300517817609i, -0.644257660504963-0.258692893991019i, 0.576500607755741+0.372571615416856i, 0.073085633598748-0.463636340068287i, -1.11915541580676+0.68039982767274i, 0.156431306436988-0.313673476880138i, -0.0231455247875635+0.0259451725814705i, 0.24845219819362-0.224300185153389i, 0.023646972380485+0.810092137377691i, -0.741641748046385-0.500789303827088i, -0.519816624502179+0.58303185544541i, -0.02654448381671-0.946236910402169i, 0.444207123496369+0.03171782980979i, 0.463384027617483-0.235888552565784i, 0.3763143736212-0.403201702305321i, -0.535693078225493-0.636202773896567i, -0.142675497564056+0.490069390222119i, 0.289783511076224-0.124158758345734i, -0.282704417623729-0.465017107050711i, -0.415769018174555-0.381772444428206i, -1.03024589339925-0.41698467281857i, 0.288030438328045+0.575601906066335i, -0.309207209980628-0.040881324520974i, -0.151260301949768-0.617273797141171i, 0.642233195953593-0.322709524184646i, 0.333696213297984+0.149540053726833i, 0.05981701298287+0.71361296322696i, -0.261340363994831-0.731744905820977i, -0.430523179786904+0.757394073850871i, 0.317116718075609+0.273633462041475i, 0.551180209580412-0.21910140930435i, -0.210492871735569+0.218342200645588i, -0.42769475226975-1.50951956390273i, 0.002561467029191-0.406659906517777i, -0.202365862498274+0.13985318727883i, 0.15296090668448+1.06811823766963i, -0.143870658163906+0.976274608647189i, 1.45985518907918+0.71996866389408i, 1.11788679229154-0.70541307773082i, -0.534383810365882+0.137771151980333i, -0.551585599414697-0.403257502122809i, -0.25455839313801+1.56553653000046i, 0.719753046987267-0.122283725904319i, 0.384469347000308-0.393453777608803i, 0.00797067027684-1.07575830492549i, 0.422853840141482+0.48652488107657i, -0.442834035957946-0.65341236116936i, 0.721030181504573+0.398626303920949i, -0.050204214300124+0.520265028980529i, 0.152023586580515+0.915318103628573i, -0.683951284620146+0.004869075220198i, 1.1563988545656-0.59645405526443i, 0.069937813777675-0.212604380284395i, 0.324457018413502-0.88189136951786i, -0.365209855838877-0.611261236614891i, 0.093411981615043+0.732869793898158i, -0.218765477742456+0.941883757470505i, 0.881770882849447+0.358588970530506i, 0.926140662452227-0.303620730620059i, -0.326168231797809-0.44856666670098i, -0.405782273173213-0.371235770884278i, 0.559040215684595+0.275645530453479i, -1.45146596074992+0.05132344338728i, -0.95512124328633+0.372402599370354i, 0.640253523409145+0.056129037397681i, 0.007149706953279+0.863411868993062i, 0.527101715445533+0.973904134498329i, -0.453853404127109+0.663881517303922i, -0.883458201061049+0.248226529245188i, -0.41109309505347-0.604101459375926i, 0.262569825259832-0.078811132911252i, -0.046371708147184-0.317741969635582i, 0.012073570264548+0.72682826896826i, -0.877664131420104-0.757147649834965i, 1.08210971546017+1.13487422256458i, 0.952631711895761+0.325264869163943i, -0.445200694400294-0.200414569087134i, -0.055439801078333-0.882203012370466i, 0.0078568252919-1.65786618360731i, -0.312100701694185+0.413794584883038i, 0.396106847459553+0.399590981014919i, 0.693389029661321-0.771116625581733i, 0.6129994721567+0.286482121236585i, -0.645550254889037-0.89412125572164i, 0.032166842134184+0.971338563175306i, -0.521787472359195+0.950760664700239i, -0.125868594377156+0.816985722899626i, 0.777844567079473-0.099084032938823i, 0.567010395254169-0.343194525085422i, -0.577840003363656+0i, 36.95629+0i, -0.405086760934773+0.78495450407262i, 0.567010395254169+0.343194525085422i, 0.777844567079473+0.099084032938823i, -0.125868594377156-0.816985722899625i, -0.521787472359195-0.95076066470024i, 0.032166842134184-0.971338563175306i, -0.645550254889037+0.89412125572164i, 0.612999472156701-0.286482121236585i, 0.693389029661321+0.771116625581733i, 0.396106847459553-0.399590981014919i, -0.312100701694185-0.413794584883038i, 0.0078568252919+1.65786618360731i, -0.055439801078333+0.882203012370465i, -0.445200694400294+0.200414569087134i, 0.952631711895761-0.325264869163943i, 1.08210971546017-1.13487422256458i, -0.877664131420104+0.757147649834965i, 0.012073570264548-0.72682826896826i, -0.046371708147184+0.317741969635582i, 0.262569825259832+0.078811132911252i, -0.41109309505347+0.604101459375926i, -0.883458201061049-0.248226529245188i, -0.453853404127109-0.663881517303921i, 0.527101715445533-0.973904134498329i, 0.007149706953279-0.863411868993062i, 0.640253523409145-0.056129037397681i, -0.95512124328633-0.372402599370354i, -1.45146596074992-0.05132344338728i, 0.559040215684594-0.275645530453479i, -0.405782273173213+0.371235770884278i, -0.326168231797809+0.44856666670098i, 0.926140662452227+0.303620730620059i, 0.881770882849447-0.358588970530506i, -0.218765477742456-0.941883757470505i, 0.093411981615043-0.732869793898158i, -0.365209855838877+0.611261236614892i, 0.324457018413502+0.881891369517861i, 0.069937813777675+0.212604380284395i, 1.1563988545656+0.59645405526443i, -0.683951284620148-0.004869075220198i, 0.152023586580515-0.915318103628573i, -0.050204214300124-0.520265028980529i, 0.721030181504573-0.398626303920949i, -0.442834035957946+0.65341236116936i, 0.422853840141482-0.48652488107657i, 0.00797067027684+1.07575830492549i, 0.384469347000308+0.393453777608803i, 0.719753046987268+0.122283725904319i, -0.25455839313801-1.56553653000046i, -0.551585599414697+0.403257502122809i, -0.534383810365882-0.137771151980333i, 1.11788679229154+0.70541307773082i, 1.45985518907918-0.71996866389408i, -0.143870658163906-0.97627460864719i, 0.15296090668448-1.06811823766963i, -0.202365862498275-0.13985318727883i, 0.002561467029191+0.406659906517777i, -0.42769475226975+1.50951956390273i, -0.210492871735569-0.218342200645588i, 0.551180209580412+0.21910140930435i, 0.317116718075609-0.273633462041475i, -0.430523179786904-0.757394073850871i, -0.261340363994831+0.731744905820977i, 0.05981701298287-0.713612963226961i, 0.333696213297984-0.149540053726833i, 0.642233195953593+0.322709524184647i, -0.151260301949768+0.617273797141171i, -0.309207209980628+0.040881324520974i, 0.288030438328045-0.575601906066335i, -1.03024589339925+0.41698467281857i, -0.415769018174554+0.381772444428206i, -0.282704417623729+0.465017107050711i, 0.289783511076224+0.124158758345734i, -0.142675497564056-0.490069390222119i, -0.535693078225493+0.636202773896567i, 0.3763143736212+0.403201702305321i, 0.463384027617483+0.235888552565784i, 0.444207123496369-0.03171782980979i, -0.02654448381671+0.946236910402169i, -0.519816624502177-0.583031855445408i, -0.741641748046385+0.500789303827088i, 0.023646972380485-0.810092137377691i, 0.24845219819362+0.224300185153389i, -0.0231455247875635-0.0259451725814705i, 0.156431306436988+0.313673476880138i, -1.11915541580676-0.68039982767274i, 0.073085633598748+0.463636340068287i, 0.576500607755741-0.372571615416856i, -0.644257660504964+0.258692893991019i, -0.340076408840021-0.676300517817609i, -0.384894950717507-0.403299602349128i, -0.465746230618912-0.337453085650942i, 0.312154699823781+0.101547186157582i, 0.378446716359935-0.110975920435485i, -0.167776786507607-0.370355046006963i, 0.461851772200813+0.091711596079432i, 0.459263743326068+0.430763048741859i, -0.153011905862873+0.415408324585187i, 0.277990726331056-0.283859957361672i )) , identicalTo( expected, tol = 1e-6 ) )
context("bbox") test_that("bounding box correctly calculated", { bb <- function( x, cols = NULL ) { unname( unclass( sfheaders:::rcpp_calculate_bbox( x, cols ) ) ) } expect_error( bb( 1L ), "geometries - incorrect size of bounding box") expect_error( bb( "a" ) ) expect_error( bb( matrix(1L) ), "geometries - incorrect size of bounding box") expect_error( bb( matrix(1.2) ), "geometries - incorrect size of bounding box") bbox <- bb( 1L:2L ) expect_equal( bbox, c(1,2,1,2) ) bbox <- bb( c(1.0, 2.0) ) expect_equal( bbox, c(1,2,1,2) ) bbox <- bb( 1L:2L, c(0L,1L) ) expect_equal( bbox, c(1,2,1,2) ) bbox <- bb( c(1.0, 2.0), c(0L,1L) ) expect_equal( bbox, c(1,2,1,2) ) x <- matrix(c(0,0,0,1), ncol = 2 ) bbox <- bb( x ) expect_equal( bbox, c(0,0,0,1) ) x <- matrix( c( 1, 2, 3, 4 ), ncol = 2 ) bbox <- bb( x ) expect_equal( bbox, c(1,3,2,4) ) x <- matrix( c( 1, 2, 3, 4 ), ncol = 2, byrow = T ) bbox <- bb( x ) expect_equal( bbox, c(1,2,3,4) ) x <- matrix( c( 1L:4L ), ncol = 2, byrow = T ) bbox <- bb( x ) expect_equal( bbox, c(1,2,3,4) ) x <- matrix( c( 1.2, 2, 3, 4 ), ncol = 2, byrow = T ) bbox <- bb( x, c(0,1) ) expect_equal( bbox, c(1.2,2,3,4) ) x <- matrix( c( 1L:4L ), ncol = 2, byrow = T ) bbox <- bb( x, c(0L,1L) ) expect_equal( bbox, c(1,2,3,4) ) x <- matrix( c( 1L:4L ), ncol = 2, byrow = T ) x <- as.data.frame( x ) x <- as.matrix( x ) bbox <- bb( x, c("V1","V2") ) expect_equal( bbox, c(1,2,3,4) ) x <- matrix( c( 1.2,2,3,4 ), ncol = 2, byrow = T ) x <- as.data.frame( x ) x <- as.matrix( x ) bbox <- bb( x, c("V1","V2") ) expect_equal( bbox, c(1.2,2,3,4) ) x <- 1:2 bbox <- bb( x, c("x","y") ) expect_equal( bbox, c(1,2,1,2) ) x <- c(1.1, 2) bbox <- bb( x, c("x","y") ) expect_equal( bbox, c(1.1,2,1.1,2) ) x <- data.frame( x = 1:5, y = 2:6 ) bbox <- bb( x ) expect_equal( bbox, c(1,2,5,6) ) x <- 1 expect_error( bb( x ), "geometries - incorrect size of bounding box") x <- matrix(1) expect_error( bb( x ), "geometries - incorrect size of bounding box") x <- matrix(1.1) expect_error( bb( x ), "geometries - incorrect size of bounding box") }) test_that("z_range correctly calculated", { zr <- function( x ) { sfheaders:::rcpp_calculate_z_range( x ) } err <- "sfheaders - incorrect size of z_range" expect_error( zr( 1L:2L ), err ) expect_error( zr( c(1.2,2) ), err ) expect_equal( zr(1:3), c(3,3) ) expect_equal( zr(c(1.2,2,3)), c(3,3) ) x <- matrix(c(0,0,0,1), ncol = 2 ) expect_error( zr( x ), err ) x <- matrix( c( 1, 2, 3, 4 ), ncol = 2 ) expect_error( zr( x ), err ) x <- matrix( c( 1, 2, 3, 4 ), ncol = 2, byrow = T ) expect_error( zr( x ), err ) x <- matrix( c( 1L:4L ), ncol = 2, byrow = T ) expect_error( zr( x ), err ) x <- data.frame( x = 1:5, y = 2:6 ) expect_error( zr( x ), err ) expect_equal( zr(1:3), c(3,3) ) x <- matrix(c(1L:6L), ncol = 3) expect_equal( zr(x), c(5L,6L)) x <- as.data.frame( matrix(c(1L:6L), ncol = 3) ) expect_equal( zr(x), c(5L,6L)) }) test_that("m_range correctly calculated", { mr <- function( x, xyzm = "") { sfheaders:::rcpp_calculate_m_range( x, xyzm ) } err <- "sfheaders - incorrect size of m_range" expect_error( mr( 1:2, "XY" ), err ) expect_error( mr( 1:2, "XYM" ), err ) expect_error( mr( 1:2, "XYZ" ), err ) expect_error( mr( c(1.2,2.2) ), err ) expect_equal( mr(1:4), c(4,4) ) x <- matrix(c(0,0,0,0,0,0), ncol = 3 ) expect_error( mr( x ), err ) x <- matrix( c( 1, 2, 3, 4 ), ncol = 2 ) expect_error( mr( x ), err ) x <- matrix( c( 1, 2, 3, 4 ), ncol = 2, byrow = T ) expect_error( mr( x ), err ) x <- matrix( c( 1L:4L ), ncol = 2, byrow = T ) expect_error( mr( x ), err ) x <- data.frame( x = 1:5, y = 2:6 ) expect_error( mr( x ), err ) expect_equal( mr(1:4), c(4,4) ) expect_equal( mr(c(1.2,2:4)), c(4,4) ) x <- matrix(c(1L:8L), ncol = 4) expect_equal( mr(x), c(7L,8L)) x <- matrix(c(1.1,2,3,4), ncol = 4) expect_equal( mr(x), c(4,4)) x <- as.data.frame( matrix(c(1L:8L), ncol = 4) ) expect_equal( mr(x), c(7,8)) }) test_that("bbox calculated on data.frame, sfg, sfc, sf", { df <- data.frame( id1 = c(1,1,1,1,1,1,1,1,2,2,2,2) , id2 = c(1,1,1,1,2,2,2,2,1,1,1,1) , x = c(0,0,1,1,1,1,2,2,3,4,4,3) , y = c(0,1,1,0,1,2,2,1,3,3,4,4) ) expect_equal(unclass(unname(sf_bbox( df, x = "x", y = "y" ))), c(0,0,4,4)) pt <- sfg_point(obj = df[1, ], x = "x", y = "y", z = "id1") mpt <- sfg_multipoint(obj = df, x = "x", y = "y") ls <- sfg_linestring(obj = df, x = "x", y = "y") mls <- sfg_multilinestring(obj = df, x = "x", y = "y") p <- sfg_polygon(obj = df, x = "x" , y = "y") mp <- sfg_multipolygon(obj = df, x = "x", y = "y", close = FALSE ) expect_equal(unclass(unname(sf_bbox( pt ))), c(0,0,0,0)) expect_equal(unclass(unname(sf_bbox( mpt ))), c(0,0,4,4) ) expect_equal(unclass(unname(sf_bbox( ls ))), c(0,0,4,4) ) expect_equal(unclass(unname(sf_bbox( mls ))), c(0,0,4,4) ) expect_equal(unclass(unname(sf_bbox( p ))), c(0,0,4,4) ) expect_equal(unclass(unname(sf_bbox( mp ))), c(0,0,4,4) ) pt <- sfc_point(obj = df, x = "x", y = "y", z = "id1") mpt <- sfc_multipoint(obj = df, x = "x", y = "y", multipoint_id = "id1") ls <- sfc_linestring(obj = df, x = "x", y = "y", linestring_id = "id1") mls <- sfc_multilinestring(obj = df, x = "x", y = "y", multilinestring_id = "id1") p <- sfc_polygon( obj = df , x = "x" , y = "y" , polygon_id = "id1" , linestring_id = "id2" , close = FALSE ) mp <- sfc_multipolygon( obj = df , x = "x" , y = "y" , multipolygon_id = "id1" , linestring_id = "id2" , close = FALSE ) expect_equal(sf_bbox( pt ), attr(pt, "bbox")) expect_equal(sf_bbox( mpt ), attr(mpt, "bbox")) expect_equal(sf_bbox( ls ), attr(ls, "bbox")) expect_equal(sf_bbox( mls ), attr(mls, "bbox")) expect_equal(sf_bbox( p ), attr(p, "bbox")) expect_equal(sf_bbox( mp ), attr(mp, "bbox")) pt <- sf_point(obj = df, x = "x", y = "y", z = "id1") mpt <- sf_multipoint(obj = df, x = "x", y = "y", multipoint_id = "id1") ls <- sf_linestring(obj = df, x = "x", y = "y", linestring_id = "id1") mls <- sf_multilinestring(obj = df, x = "x", y = "y", multilinestring_id = "id1") p <- sf_polygon( obj = df , x = "x" , y = "y" , polygon_id = "id1" , linestring_id = "id2" , close = FALSE ) mp <- sf_multipolygon( obj = df , x = "x" , y = "y" , multipolygon_id = "id1" , linestring_id = "id2" , close = FALSE ) expect_equal(sf_bbox( pt ), attr(pt$geometry, "bbox")) expect_equal(sf_bbox( mpt ), attr(mpt$geometry, "bbox")) expect_equal(sf_bbox( ls ), attr(ls$geometry, "bbox")) expect_equal(sf_bbox( mls ), attr(mls$geometry, "bbox")) expect_equal(sf_bbox( p ), attr(p$geometry, "bbox")) expect_equal(sf_bbox( mp ), attr(mp$geometry, "bbox")) }) test_that("z and m range correctly reported",{ df <- data.frame( id1 = c(1,1,1,1,1,1,1,1,2,2,2,2) , id2 = c(1,1,1,1,2,2,2,2,1,1,1,1) , x = c(0,0,1,1,1,1,2,2,3,4,4,3) , y = c(0,1,1,0,1,2,2,1,3,3,4,4) , z = 1:12 , m = 20:9 ) pt <- sf_point(obj = df, x = "x", y = "y", z = "z") mpt <- sf_multipoint(obj = df, x = "x", y = "y", z = "z", multipoint_id = "id1") ls <- sf_linestring(obj = df, x = "x", y = "y", z = "z", linestring_id = "id1") mls <- sf_multilinestring(obj = df, x = "x", y = "y", z = "z", multilinestring_id = "id1") p <- sf_polygon( obj = df , x = "x" , y = "y" , z = "z" , polygon_id = "id1" , linestring_id = "id2" , close = FALSE ) mp <- sf_multipolygon( obj = df , x = "x" , y = "y" , z = "z" , multipolygon_id = "id1" , linestring_id = "id2" , close = FALSE ) expect_true( all( attr( pt$geometry, "z_range" ) == c(1,12) ) ) expect_true( all( attr( mpt$geometry, "z_range" ) == c(1,12) ) ) expect_true( all( attr( ls$geometry, "z_range" ) == c(1,12) ) ) expect_true( all( attr( mls$geometry, "z_range" ) == c(1,12) ) ) expect_true( all( attr( p$geometry, "z_range" ) == c(1,12) ) ) expect_true( all( attr( mp$geometry, "z_range" ) == c(1,12) ) ) expect_true( is.null( attr( pt$geometry, "m_range" ) ) ) expect_true( is.null( attr( mp$geometry, "m_range" ) ) ) expect_true( is.null( attr( ls$geometry, "m_range" ) ) ) expect_true( is.null( attr( mls$geometry, "m_range" ) ) ) expect_true( is.null( attr( p$geometry, "m_range" ) ) ) expect_true( is.null( attr( mp$geometry, "m_range" ) ) ) pt <- sf_point(obj = df, x = "x", y = "y", m = "m") mpt <- sf_multipoint(obj = df, x = "x", y = "y", m = "m", multipoint_id = "id1") ls <- sf_linestring(obj = df, x = "x", y = "y", m = "m", linestring_id = "id1") mls <- sf_multilinestring(obj = df, x = "x", y = "y", m = "m", multilinestring_id = "id1") p <- sf_polygon( obj = df , x = "x" , y = "y" , m = "m" , polygon_id = "id1" , linestring_id = "id2" , close = FALSE ) mp <- sf_multipolygon( obj = df , x = "x" , y = "y" , m = "m" , multipolygon_id = "id1" , linestring_id = "id2" , close = FALSE ) expect_true( all( attr( pt$geometry, "m_range" ) == c(9,20) ) ) expect_true( all( attr( mpt$geometry, "m_range" ) == c(9,20) ) ) expect_true( all( attr( ls$geometry, "m_range" ) == c(9,20) ) ) expect_true( all( attr( mls$geometry, "m_range" ) == c(9,20) ) ) expect_true( all( attr( p$geometry, "m_range" ) == c(9,20) ) ) expect_true( all( attr( mp$geometry, "m_range" ) == c(9,20) ) ) expect_true( is.null( attr( pt$geometry, "z_range" ) ) ) expect_true( is.null( attr( mp$geometry, "z_range" ) ) ) expect_true( is.null( attr( ls$geometry, "z_range" ) ) ) expect_true( is.null( attr( mls$geometry, "z_range" ) ) ) expect_true( is.null( attr( p$geometry, "z_range" ) ) ) expect_true( is.null( attr( mp$geometry, "z_range" ) ) ) pt <- sf_point(obj = df, x = "x", y = "y", z = "z", m = "m") mpt <- sf_multipoint(obj = df, x = "x", y = "y", z = "z", m = "m", multipoint_id = "id1") ls <- sf_linestring(obj = df, x = "x", y = "y", z = "z", m = "m", linestring_id = "id1") mls <- sf_multilinestring(obj = df, x = "x", y = "y", z = "z", m = "m", multilinestring_id = "id1") p <- sf_polygon( obj = df , x = "x" , y = "y" , z = "z" , m = "m" , polygon_id = "id1" , linestring_id = "id2" , close = FALSE ) mp <- sf_multipolygon( obj = df , x = "x" , y = "y" , z = "z" , m = "m" , multipolygon_id = "id1" , linestring_id = "id2" , close = FALSE ) expect_true( all( attr( pt$geometry, "z_range" ) == c(1,12) ) ) expect_true( all( attr( mpt$geometry, "z_range" ) == c(1,12) ) ) expect_true( all( attr( ls$geometry, "z_range" ) == c(1,12) ) ) expect_true( all( attr( mls$geometry, "z_range" ) == c(1,12) ) ) expect_true( all( attr( p$geometry, "z_range" ) == c(1,12) ) ) expect_true( all( attr( mp$geometry, "z_range" ) == c(1,12) ) ) expect_true( all( attr( pt$geometry, "m_range" ) == c(9,20) ) ) expect_true( all( attr( mpt$geometry, "m_range" ) == c(9,20) ) ) expect_true( all( attr( ls$geometry, "m_range" ) == c(9,20) ) ) expect_true( all( attr( mls$geometry, "m_range" ) == c(9,20) ) ) expect_true( all( attr( p$geometry, "m_range" ) == c(9,20) ) ) expect_true( all( attr( mp$geometry, "m_range" ) == c(9,20) ) ) }) test_that("C++ functions correctly 'guess' the dimension", { df <- data.frame(x = 1, y = 2) res <- sfheaders:::rcpp_sfg_linestring( x = df , geometry_columns = c("x","y") , xyzm = "" ) expect_true( attr( res , "class" )[1] == "XY" ) df <- data.frame(x = 1, y = 2, z = 3) res <- sfheaders:::rcpp_sfg_linestring( x = df , geometry_columns = c("x","y","z") , xyzm = "" ) expect_true( attr( res , "class" )[1] == "XYZ" ) df <- data.frame(x = 1, y = 2, m = 3) res <- sfheaders:::rcpp_sfg_linestring( x = df , geometry_columns = c("x","y","m") , xyzm = "" ) expect_true( attr( res , "class" )[1] == "XYZ" ) df <- data.frame(x = 1, y = 2, z = 3, m = 4) res <- sfheaders:::rcpp_sfg_linestring( x = df , geometry_columns = c("x","y","m") , xyzm = "" ) expect_true( attr( res , "class" )[1] == "XYZ" ) df <- data.frame(x = 1, y = 2, z = 3, m = 4) res <- sfheaders:::rcpp_sfg_linestring( x = df , geometry_columns = c("x","y","z", "m") , xyzm = "" ) expect_true( attr( res , "class" )[1] == "XYZM" ) })
dotchartpl <- function(x, major=NULL, minor=NULL, group=NULL, mult=NULL, big=NULL, htext=NULL, num=NULL, denom=NULL, numlabel='', denomlabel='', fun=function(x) x, ifun=function(x) x, op='-', lower=NULL, upper=NULL, refgroup=NULL, sortdiff=TRUE, conf.int=0.95, minkeep=NULL, xlim=NULL, xlab='Proportion', tracename=NULL, limitstracename='Limits', nonbigtracename='Stratified Estimates', dec=3, width=800, height=NULL, col=colorspace::rainbow_hcl ) { if (!requireNamespace("plotly")) stop("This function requires the 'plotly' package.") mu <- markupSpecs$html bold <- mu$bold if(! length(xlim)) xlim <- c(min(c(x, lower), na.rm=TRUE), max(c(x, upper), na.rm=TRUE)) majorpres <- length(major) > 0 major <- if(majorpres) as.character(major) else rep(' ', length(x)) minorpres <- length(minor) > 0 if(! (majorpres || minorpres)) stop('must specify major or minor or both') grouppres <- length(group) > 0 multpres <- length(mult) > 0 limspres <- length(lower) * length(upper) > 0 rgpres <- length(refgroup) > 0 if(minorpres) minor <- as.character(minor) if(grouppres) group <- as.character(group) if(multpres) mult <- as.character(mult) ugroup <- if(grouppres) unique(group) else '' fmt <- function(x) format(round(x, dec)) if(rgpres) { if(! grouppres || multpres || length(big)) stop('when refgroup is given, group must be given and mult and big must not be used') if(length(ugroup) != 2) stop('refgroup only works for 2 groups') if(refgroup %nin% unique(group)) stop(paste('refgroup must be one of the following:', paste(unique(group), collapse=', '))) altgroup <- setdiff(ugroup, refgroup) } cols <- if(length(col)) { if(! is.function(col)) col else if(grouppres) col(length(unique(group))) else col(1) } if(! length(col) && ! grouppres) cols <- 'black' dropped <- character(0) D <- NULL if(rgpres && minorpres) { z <- pairUpDiff(x, major, minor, group, refgroup=refgroup, lower=lower, upper=upper, minkeep=minkeep, sortdiff=sortdiff, conf.int=conf.int) Z <- z$X D <- z$D dropped <- z$dropped i <- Z[,'subscripts'] x <- x[i] major <- major[i] minor <- minor[i] group <- group[i] if(length(num)) num <- num[i] if(length(denom)) denom <- denom[i] if(length(mult)) mult <- mult[i] if(length(big)) big <- big[i] if(length(lower)) lower <- lower[i] if(length(upper)) upper <- upper[i] if(length(htext)) htext <- htext[i] } ht <- htext if(numlabel != '') numlabel <- paste0(' ', numlabel) if(denomlabel != '') denomlabel <- paste0(' ', denomlabel) if(length(num)) ht <- paste0(ht, if(length(htext)) mu$lspace, fmt(fun(x)), mu$lspace, mu$frac(paste0(num, numlabel), paste0(denom, denomlabel), size=95)) if(length(ugroup) != 2 && limspres) ht <- paste0(ht, ' [', fmt(fun(lower)), ', ', fmt(fun(upper)), ']') ht <- paste0(ht, if(length(ht)) '<br>', if(majorpres) paste0(major, ': ')) if(minorpres) ht <- paste0(ht, minor) if(grouppres) ht <- paste0(ht, '<br>', gsub(' stratified<br>by .*', '', group)) if(multpres) ht <- paste0(ht, '<br>', mult) n <- length(x) minor <- if(minorpres) minor else rep('', n) group <- if(grouppres) group else rep('', n) mult <- if(multpres) mult else rep('', n) if(! length(big)) big <- rep(TRUE, n) w <- c(length(x), length(major), length(minor), length(group), length(num), length(denom), length(mult), length(big), length(htext), length(lower), length(upper)) w <- w[w > 0] if(diff(range(w)) > 0) stop('x, major, minor, group, num, denom, mult, big, htext, lower, upper must all have same length when used') y <- 1 X <- Y <- Ydiff <- Lower <- Upper <- numeric(0) Group <- Htext <- Htextl <- character(0) Big <- logical(0) yl <- numeric(0); yt <- ytnb <- character(0) difflower <- diffupper <- Diff <- numeric(0) coldiff <- htdiff <- character(0) lines <- 0 for(ma in unique(major)) { y <- y - 1 yl <- c(yl, y) yt <- c(yt, bold(ma)) ytnb <- c(ytnb, ma) lminor <- unique(minor[major == ma]) y <- y + if(all(lminor == '')) 0.4 else 0 lines <- lines + 1 for(mi in lminor) { y <- y - 0.4 lines <- lines + (mi != '') j <- which(major == ma & minor == mi) X <- c(X, x[j]) Y <- c(Y, ifelse(big[j], y, y - .14)) if(length(D)) { k <- which(D$major == ma & D$minor == mi) if(length(k) != 1) stop('must have one observation for a major/minor/group combination') diff <- D$diff[k] coldiff <- c(coldiff, ifelse(diff > 0, paste0(altgroup, ' ', htmlTranslate('>'), ' ', refgroup), paste0(refgroup, ' ', htmlTranslate('>='), ' ', altgroup))) Ydiff <- c(Ydiff, y) htd <- if(majorpres) paste0(ma, ': ') else '' if(minorpres) htd <- paste0(htd, mi) htd <- paste0(htd, '<br>', altgroup, ' ', op, ' ', refgroup, ': ', fmt(fun(diff))) if(! is.logical(conf.int) && limspres && length(D)) { dlower <- fmt(fun(D$lower[k])) dupper <- fmt(fun(D$upper[k])) htd <- paste0(htd, '<br>', conf.int, ' C.L.: [', dlower, ', ', dupper, ']') Diff <- c(Diff, diff) difflower <- c(difflower, D$lowermid[k]) diffupper <- c(diffupper, D$uppermid[k]) } htdiff <- c(htdiff, htd) } if(limspres && ! length(D)) { Lower <- c(Lower, lower[j]) Upper <- c(Upper, upper[j]) Htextl <- c(Htextl, paste0('[', fmt(fun(lower[j])), ', ', fmt(fun(upper[j])), ']' ) ) } Group <- c(Group, group[j]) Big <- c(Big, big[j]) Htext <- c(Htext, ht[j]) if(mi != '') { yl <- c(yl, y) yt <- c(yt, mi) ytnb <- c(ytnb, mi) } } } d <- data.frame(X, Y, Group, Htext, Big) if(limspres && ! length(D)) { d$Lower <- Lower d$Upper <- Upper d$Htextl <- Htextl } if(! grouppres) d$Group <- NULL if(any(d$Big)) { db <- subset(d, Big) p <- plotly::plot_ly(data=db, colors=cols, height=if(length(height)) height else plotlyParm$heightDotchart(lines), width=width) if(limspres && length(D)) { ddiff <- data.frame(Diff, difflower, diffupper, Ydiff, coldiff, htdiff) nDiff <- Diff[! is.na(Diff)] if(length(nDiff)) { if(any(nDiff > 0)) p <- plotly::add_segments(p, data=subset(ddiff, Diff > 0), x= ~ difflower, xend= ~ diffupper, y= ~ Ydiff, yend= ~ Ydiff, color = I('lightgray'), text = ~ htdiff, hoverinfo='text', name = paste0(htmlSpecial('half'), ' CL of difference<br>', coldiff[Diff > 0][1])) if(any(nDiff <= 0)) p <- plotly::add_segments(p, data=subset(ddiff, Diff <= 0), x= ~ difflower, xend= ~ diffupper, y= ~ Ydiff, yend= ~ Ydiff, color = I('lavender'), text = ~ htdiff, hoverinfo='text', name = paste0(htmlSpecial('half'), ' CL of difference<br>', coldiff[Diff <= 0][1])) } } if(limspres && ! length(D) && length(ugroup) == 2) p <- if(grouppres) plotly::add_segments(p, data=db, x=~ Lower, xend=~ Upper, y=~ Y, yend=~ Y, color=~ Group, text= ~ Htextl, colors=cols, hoverinfo='text') else plotly::add_segments(p, x=~ Lower, xend=~ Upper, y=~ Y, yend=~ Y, text= ~ Htextl, color=I('lightgray'), hoverinfo='text', name=limitstracename) p <- if(grouppres) plotly::add_markers(p, x=~ X, y=~ Y, color=~ Group, text=~ Htext, colors=cols, hoverinfo='text') else plotly::add_markers(p, x=~ X, y=~ Y, text=~ Htext, color=I('black'), hoverinfo='text', name=if(length(tracename)) tracename else if(any(! d$Big)) 'All' else '') } else p <- plotly::plot_ly(colors=cols) if(any(! d$Big)) { dnb <- subset(d, ! Big) if(limspres) p <- if(grouppres && length(ugroup) == 2) plotly::add_segments(p, data=dnb, x=~ Lower, xend=~ Upper, y=~ Y, yend=~ Y, color=~ Group, text=~ Htextl, colors=cols, hoverinfo='text') else plotly::add_segments(p, data=dnb, x=~ Lower, xend=~ Upper, y=~ Y, yend=~ Y, text=~ Htextl, color=I('lightgray'), hoverinfo='text', name=limitstracename) dnb$sGroup <- paste0(dnb$Group, '\nby ', gsub('Stratified by\n', '', nonbigtracename)) p <- if(grouppres) plotly::add_markers(p, data=dnb, x=~ X, y=~ Y, color=~ Group, text=~ Htext, colors=cols, marker=list(opacity=0.45, size=4), hoverinfo='text') else plotly::add_markers(p, data=dnb, x=~ X, y=~ Y, text=~ Htext, marker=list(opacity=0.45, size=4), color=I('black'), hoverinfo='text', name=nonbigtracename) } leftmargin <- plotlyParm$lrmargin(ytnb) tickvals <- pretty(fun(xlim), n=10) xaxis <- list(title=xlab, range=xlim, zeroline=FALSE, tickvals=ifun(tickvals), ticktext=tickvals) yaxis <- list(title='', range=c(min(Y) - 0.2, 0.2), zeroline=FALSE, tickvals=yl, ticktext=yt) p <- plotly::layout(p, xaxis=xaxis, yaxis=yaxis, margin=list(l=leftmargin), legend=list(traceorder=if(length(difflower)) 'reversed' else 'normal')) attr(p, 'levelsRemoved') <- dropped p }
context("MA 1: evalmod") test_that("m1 scores", { s1 <- c(3, 2, 2, 1) l1 <- c(1, 0, 1, 0) mdat1 <- mmdata(s1, l1) cv1 <- evalmod(mdat1, x_bins = 4) expect_equal(cv1[["rocs"]][[1]][["x"]], c(0, 0, 0.25, 0.5, 0.75, 1)) expect_equal(cv1[["rocs"]][[1]][["y"]], c(0, 0.5, 0.75, 1, 1, 1)) expect_equal(cv1[["prcs"]][[1]][["x"]], c(0, 0.25, 0.5, 0.75, 1, 1)) expect_equal(cv1[["prcs"]][[1]][["y"]], c(1, 1, 1, 0.75, 0.6666666667, 0.5), tolerance = 1e-2) }) test_that("m2 scores", { s2 <- c(4, 3, 2, 1) l2 <- c(0, 0, 1, 1) mdat2 <- mmdata(s2, l2) cv2 <- evalmod(mdat2, x_bins = 4) expect_equal(cv2[["rocs"]][[1]][["x"]], c(0, 0.25, 0.5, 0.75, 1, 1, 1)) expect_equal(cv2[["rocs"]][[1]][["y"]], c(0, 0, 0, 0, 0, 0.5, 1)) expect_equal(cv2[["prcs"]][[1]][["x"]], c(0, 0.25, 0.5, 0.75, 1)) expect_equal(cv2[["prcs"]][[1]][["y"]], c(0, 0.2, 0.3333333333, 0.4285714286, 0.5), tolerance = 1e-2) }) test_that("m3 scores", { s3 <- c(3, 3, 2, 1) l3 <- c(1, 0, 0, 1) mdat3 <- mmdata(s3, l3) cv3 <- evalmod(mdat3, x_bins = 4) expect_equal(cv3[["rocs"]][[1]][["x"]], c(0, 0.25, 0.5, 0.75, 1, 1)) expect_equal(cv3[["rocs"]][[1]][["y"]], c(0, 0.25, 0.5, 0.5, 0.5, 1)) expect_equal(cv3[["prcs"]][[1]][["x"]], c(0, 0.25, 0.5, 0.5, 0.75, 1)) expect_equal(cv3[["prcs"]][[1]][["y"]], c(0.5, 0.5, 0.5, 0.3333333333, 0.4285714286, 0.5), tolerance = 1e-2) }) test_that("'mode' must be consistent between 'mmdata' and 'evalmode'", { s1 <- c(1, 2, 3, 4) s2 <- c(5, 6, 7, 8) s3 <- c(2, 4, 6, 8) scores <- join_scores(s1, s2, s3) l1 <- c(1, 0, 1, 0) l2 <- c(1, 1, 0, 0) l3 <- c(0, 1, 0, 1) labels <- join_labels(l1, l2, l3) md1 <- mmdata(scores, labels) expect_equal(attr(md1, "args")[["mode"]], "rocprc") expect_error(evalmod(md1), NA) em1_1 <- evalmod(md1) expect_equal(attr(evalmod(md1), "args")[["mode"]], "rocprc") expect_error(evalmod(md1, mode = 'rocprc'), NA) em1_2 <- evalmod(md1, mode = 'rocprc') expect_equal(attr(em1_2, "args")[["mode"]], "rocprc") expect_error(evalmod(md1, mode = 'basic'), NA) em1_3 <- evalmod(md1, mode = 'basic') expect_equal(attr(em1_3, "args")[["mode"]], "basic") expect_error(evalmod(md1, mode = 'aucroc'), NA) em1_4 <- evalmod(md1, mode = 'aucroc') expect_equal(attr(em1_4, "args")[["mode"]], "aucroc") md2 <- mmdata(scores, labels, mode = 'basic') expect_equal(attr(md2, "args")[["mode"]], "basic") expect_error(evalmod(md2), NA) em2_1 <- evalmod(md2) expect_equal(attr(em2_1, "args")[["mode"]], "basic") expect_error(evalmod(md2, mode = 'rocprc'), NA) em2_2 <- evalmod(md2, mode = 'rocprc') expect_equal(attr(em2_2, "args")[["mode"]], "rocprc") expect_error(evalmod(md2, mode = 'basic'), NA) em2_3 <- evalmod(md2, mode = 'basic') expect_equal(attr(em2_3, "args")[["mode"]], "basic") expect_error(evalmod(md2, mode = 'aucroc'), NA) em2_4 <- evalmod(md2, mode = 'aucroc') expect_equal(attr(em2_4, "args")[["mode"]], "aucroc") md3 <- mmdata(scores, labels, mode = 'aucroc') expect_equal(attr(md3, "args")[["mode"]], "aucroc") expect_error(evalmod(md3), NA) em3_1 <- evalmod(md3) expect_equal(attr(em3_1, "args")[["mode"]], "aucroc") expect_error(evalmod(md3, mode = 'rocprc'), "Invalid 'mode':") expect_error(evalmod(md3, mode = 'basic'), "Invalid 'mode':") expect_error(evalmod(md3, mode = 'aucroc'), NA) em3_4 <- evalmod(md3, mode = 'aucroc') expect_equal(attr(em3_4, "args")[["mode"]], "aucroc") })
grep_leading <- function( pattern, x, value=FALSE ) { ind <- which( substring( x, 1, nchar(pattern) )==pattern ) if (value){ ind <- x[ind] } return(ind) }
qtlambda <- function(p, lambda, lower.tail = TRUE, log.p = FALSE) { cpp_qtlambda(p, lambda, lower.tail[1L], log.p[1L]) } rtlambda <- function(n, lambda) { if (length(n) > 1) n <- length(n) cpp_rtlambda(n, lambda) }
compute.approx.lr <- function(theta, mu, sigma, y, Py, M){ n = length(y) -M*theta - 0.5*M*theta^2 - n*log(sigma) - 0.5*sum((y -theta*Py - mu)^2)/sigma^2 }
if (keras_available()) { mod <- Sequential() mod$add(Dense(units = 50, input_shape = 10)) mod$add(Dropout(rate = 0.5)) mod$add(Activation("relu")) mod$add(Dense(units = 3)) mod$add(ActivityRegularization(l1 = 1)) mod$add(Activation("softmax")) keras_compile(mod, loss = 'categorical_crossentropy', optimizer = RMSprop()) keras_save(mod, tf <- tempfile()) mod2 <- keras_load(tf) keras_save_weights(mod, tf <- tempfile()) keras_load_weights(mod, tf) tf <- tempfile(fileext = ".json") keras_model_to_json(mod, tf) cat(readLines(tf)) mod3 <- keras_model_from_json(tf) }
is.qr <- function(x) inherits(x, "qr") qr <- function(x, ...) UseMethod("qr") qr.default <- function(x, tol = 1e-07, LAPACK = FALSE, ...) { x <- as.matrix(x) if(is.complex(x)) return(structure(.Call("La_zgeqp3", x, PACKAGE = "base"), class="qr")) if(!is.double(x)) storage.mode(x) <- "double" if(LAPACK) { res <- .Call("La_dgeqp3", x, PACKAGE = "base") if(!is.null(cn <- colnames(x))) colnames(res$qr) <- cn[res$pivot] attr(res, "useLAPACK") <- TRUE class(res) <- "qr" return(res) } p <- ncol(x) n <- nrow(x) res <- .Fortran("dqrdc2", qr=x, n, n, p, as.double(tol), rank=integer(1L), qraux = double(p), pivot = as.integer(1L:p), double(2*p), PACKAGE="base")[c(1,6,7,8)] if(!is.null(cn <- colnames(x))) colnames(res$qr) <- cn[res$pivot] class(res) <- "qr" res } qr.coef <- function(qr, y) { if( !is.qr(qr) ) stop("first argument must be a QR decomposition") n <- nrow(qr$qr) p <- ncol(qr$qr) k <- as.integer(qr$rank) im <- is.matrix(y) if (!im) y <- as.matrix(y) ny <- ncol(y) if (p == 0L) return( if (im) matrix(0, p, ny) else numeric() ) ix <- if ( p > n ) c(seq_len(n), rep(NA, p - n)) else seq_len(p) if(is.complex(qr$qr)) { if(!is.complex(y)) y[] <- as.complex(y) coef <- matrix(NA_complex_, nrow = p, ncol = ny) coef[qr$pivot,] <- .Call("qr_coef_cmplx", qr, y, PACKAGE = "base")[ix, ] return(if(im) coef else c(coef)) } a <- attr(qr, "useLAPACK") if(!is.null(a) && is.logical(a) && a) { if(!is.double(y)) storage.mode(y) <- "double" coef <- matrix(NA_real_, nrow = p, ncol = ny) coef[qr$pivot,] <- .Call("qr_coef_real", qr, y, PACKAGE = "base")[ix,] return(if(im) coef else c(coef)) } if (k == 0L) return( if (im) matrix(NA, p, ny) else rep.int(NA, p)) storage.mode(y) <- "double" if( nrow(y) != n ) stop("'qr' and 'y' must have the same number of rows") z <- .Fortran("dqrcf", as.double(qr$qr), n, k, as.double(qr$qraux), y, ny, coef=matrix(0, nrow=k,ncol=ny), info=integer(1L), NAOK = TRUE, PACKAGE="base")[c("coef","info")] if(z$info) stop("exact singularity in 'qr.coef'") if(k < p) { coef <- matrix(NA_real_, nrow=p, ncol=ny) coef[qr$pivot[1L:k],] <- z$coef } else coef <- z$coef if(!is.null(nam <- colnames(qr$qr))) if(k < p) rownames(coef)[qr$pivot] <- nam else rownames(coef) <- nam if(im && !is.null(nam <- colnames(y))) colnames(coef) <- nam if(im) coef else drop(coef) } qr.qy <- function(qr, y) { if(!is.qr(qr)) stop("argument is not a QR decomposition") if(is.complex(qr$qr)) { y <- as.matrix(y) if(!is.complex(y)) y[] <- as.complex(y) return(.Call("qr_qy_cmplx", qr, y, 0, PACKAGE = "base")) } a <- attr(qr, "useLAPACK") if(!is.null(a) && is.logical(a) && a) return(.Call("qr_qy_real", qr, as.matrix(y), 0, PACKAGE = "base")) n <- nrow(qr$qr) k <- as.integer(qr$rank) ny <- NCOL(y) storage.mode(y) <- "double" if(NROW(y) != n) stop("'qr' and 'y' must have the same number of rows") .Fortran("dqrqy", as.double(qr$qr), n, k, as.double(qr$qraux), y, ny, qy = y, PACKAGE="base")$qy } qr.qty <- function(qr, y) { if(!is.qr(qr)) stop("argument is not a QR decomposition") if(is.complex(qr$qr)){ y <- as.matrix(y) if(!is.complex(y)) y[] <- as.complex(y) return(.Call("qr_qy_cmplx", qr, y, 1, PACKAGE = "base")) } a <- attr(qr, "useLAPACK") if(!is.null(a) && is.logical(a) && a) return(.Call("qr_qy_real", qr, as.matrix(y), 1, PACKAGE = "base")) n <- nrow(qr$qr) k <- as.integer(qr$rank) ny <- NCOL(y) if(NROW(y) != n) stop("'qr' and 'y' must have the same number of rows") storage.mode(y) <- "double" .Fortran("dqrqty", as.double(qr$qr), n, k, as.double(qr$qraux), y, ny, qty = y, PACKAGE = "base")$qty } qr.resid <- function(qr, y) { if(!is.qr(qr)) stop("argument is not a QR decomposition") if(is.complex(qr$qr)) stop("not implemented for complex 'qr'") a <- attr(qr, "useLAPACK") if(!is.null(a) && is.logical(a) && a) stop("not supported for LAPACK QR") k <- as.integer(qr$rank) if (k==0) return(y) n <- nrow(qr$qr) ny <- NCOL(y) if( NROW(y) != n ) stop("'qr' and 'y' must have the same number of rows") storage.mode(y) <- "double" .Fortran("dqrrsd", as.double(qr$qr), n, k, as.double(qr$qraux), y, ny, rsd = y, PACKAGE="base")$rsd } qr.fitted <- function(qr, y, k=qr$rank) { if(!is.qr(qr)) stop("argument is not a QR decomposition") if(is.complex(qr$qr)) stop("not implemented for complex 'qr'") a <- attr(qr, "useLAPACK") if(!is.null(a) && is.logical(a) && a) stop("not supported for LAPACK QR") n <- nrow(qr$qr) k <- as.integer(k) if(k > qr$rank) stop("'k' is too large") ny <- NCOL(y) if( NROW(y) != n ) stop("'qr' and 'y' must have the same number of rows") storage.mode(y) <- "double" .Fortran("dqrxb", as.double(qr$qr), n, k, as.double(qr$qraux), y, ny, xb = y, DUP=FALSE, PACKAGE="base")$xb } qr.Q <- function (qr, complete = FALSE, Dvec = rep.int(if (cmplx) 1 + 0i else 1, if (complete) dqr[1] else min(dqr))) { if(!is.qr(qr)) stop("argument is not a QR decomposition") dqr <- dim(qr$qr) cmplx <- mode(qr$qr) == "complex" D <- if (complete) diag(Dvec, dqr[1L]) else { ncols <- min(dqr) diag(Dvec[1L:ncols], nrow = dqr[1L], ncol = ncols) } qr.qy(qr, D) } qr.R <- function (qr, complete = FALSE) { if(!is.qr(qr)) stop("argument is not a QR decomposition") R <- qr$qr if (!complete) R <- R[seq.int(min(dim(R))), , drop = FALSE] R[row(R) > col(R)] <- 0 R } qr.X <- function (qr, complete = FALSE, ncol = if (complete) nrow(R) else min(dim(R))) { if(!is.qr(qr)) stop("argument is not a QR decomposition") pivoted <- !identical(qr$pivot, ip <- seq_along(qr$pivot)) R <- qr.R(qr, complete = TRUE) if(pivoted && ncol < length(qr$pivot)) stop("need larger value of 'ncol' as pivoting occurred") cmplx <- mode(R) == "complex" p <- dim(R)[2L] if (ncol < p) R <- R[, 1L:ncol, drop = FALSE] else if (ncol > p) { tmp <- diag(if (!cmplx) 1 else 1 + 0i, nrow(R), ncol) tmp[, 1L:p] <- R R <- tmp } res <- qr.qy(qr, R) cn <- colnames(res) if(pivoted) { res[, qr$pivot] <- res[, ip] if(!is.null(cn)) colnames(res)[qr$pivot] <- cn[ip] } res }
OLS.ART <- function(x,p,h,prob) { x <- as.matrix(x) n <- nrow(x) B <- LSMT(x,p) b <- B$coef e <- B$resid f <- {}; PImat <- {} if(h > 0) { f <- ART.Fore(x,b,h) s2 <- sum(e^2)/(nrow(x)-length(b)) mf <- mainf(b,h,p) se <- as.matrix(sqrt(s2*cumsum(mf[1:h]^2))) PImat <- matrix(NA,ncol=length(prob),nrow=h) for( i in 1:length(prob)) {PImat[,i] <- f + qnorm(prob[i])*se } } return(list(coef=b,resid=e,forecast=f,PI=PImat)) }
nmkb2 <- function (par, fn, lower = -Inf, upper = Inf, control = list(), ...) { ctrl <- list(tol = 1e-06, maxfeval = min(5000, max(1500, 20 * length(par)^2)), regsimp = TRUE, maximize = FALSE, restarts.max = 3, trace = FALSE) namc <- match.arg(names(control), choices = names(ctrl), several.ok = TRUE) if (!all(namc %in% names(ctrl))) stop("unknown names in control: ", namc[!(namc %in% names(ctrl))]) if (!is.null(names(control))) ctrl[namc] <- control ftol <- ctrl$tol maxfeval <- ctrl$maxfeval regsimp <- ctrl$regsimp restarts.max <- ctrl$restarts.max maximize <- ctrl$maximize trace <- ctrl$trace n <- length(par) clipToRegion <- function(xc,lowerP,upperP) { xc = pmax(xc,lowerP+1e-13) xc = pmin(xc,upperP-1e-13) return(xc) } par = clipToRegion(par,lower,upper) g <- function(x) { gx <- x gx[c1] <- atanh(2 * (x[c1] - lower[c1]) / (upper[c1] - lower[c1]) - 1) gx[c3] <- log(x[c3] - lower[c3]) gx[c4] <- log(upper[c4] - x[c4]) gx } ginv <- function(x) { gix <- x gix[c1] <- lower[c1] + (upper[c1] - lower[c1])/2 * (1 + tanh(x[c1])) gix[c3] <- lower[c3] + exp(x[c3]) gix[c4] <- upper[c4] - exp(x[c4]) gix } if (length(lower) == 1) lower <- rep(lower, n) if (length(upper) == 1) upper <- rep(upper, n) if (any(c(par < lower, upper < par))) stop("Infeasible starting values!", call.=FALSE) low.finite <- is.finite(lower) upp.finite <- is.finite(upper) c1 <- low.finite & upp.finite c2 <- !(low.finite | upp.finite) c3 <- !(c1 | c2) & low.finite c4 <- !(c1 | c2) & upp.finite if (all(c2)) stop("Use `nmk()' for unconstrained optimization!", call.=FALSE) if (maximize) fnmb <- function(par) -fn(ginv(par), ...) else fnmb <- function(par) fn(ginv(par), ...) x0 <- g(par) if (n == 1) stop(call. = FALSE, "Use `optimize' for univariate optimization") if (n > 30) warning("Nelder-Mead should not be used for high-dimensional optimization") V <- cbind(rep(0, n), diag(n)) f <- rep(0, n + 1) f[1] <- fnmb(x0) V[, 1] <- x0 scale <- max(1, sqrt(sum(x0^2))) if (regsimp) { alpha <- scale/(n * sqrt(2)) * c(sqrt(n + 1) + n - 1, sqrt(n + 1) - 1) V[, -1] <- (x0 + alpha[2]) diag(V[, -1]) <- x0[1:n] + alpha[1] for (j in 2:ncol(V)) f[j] <- fnmb(V[, j]) } else { V[, -1] <- x0 + scale * V[, -1] for (j in 2:ncol(V)) f[j] <- fnmb(V[, j]) } f[is.nan(f)] <- Inf f[is.na(f)] <- Inf nf <- n + 1 ord <- order(f) f <- f[ord] V <- V[, ord] rho <- 1 gamma <- 0.5 chi <- 2 sigma <- 0.5 conv <- 1 oshrink <- 0 restarts <- 0 orth <- 0 dist <- f[n + 1] - f[1] v <- V[, -1] - V[, 1] delf <- f[-1] - f[1] diam <- sqrt(colSums(v^2)) sgrad <- c(crossprod(t(v), delf)) alpha <- 1e-04 * max(diam)/sqrt(sum(sgrad^2)) simplex.size <- sum(abs(V[, -1] - V[, 1]))/max(1, sum(abs(V[, 1]))) if (is.nan(simplex.size)) simplex.size=Inf if (is.na(simplex.size)) simplex.size=Inf if (is.nan(dist)) dist <- Inf if (is.na(dist)) dist <- Inf itc <- 0 conv <- 0 message <- "Succesful convergence" while (nf < maxfeval & restarts < restarts.max & dist > ftol & simplex.size > 1e-06) { fbc <- mean(f) happy <- 0 itc <- itc + 1 xbar <- rowMeans(V[, 1:n]) xr <- (1 + rho) * xbar - rho * V[, n + 1] fr <- fnmb(xr) nf <- nf + 1 if (is.nan(fr)) fr <- Inf if (is.na(fr)) fr <- Inf if (fr >= f[1] & fr < f[n]) { happy <- 1 xnew <- xr fnew <- fr } else if (fr < f[1]) { xe <- (1 + rho * chi) * xbar - rho * chi * V[, n + 1] fe <- fnmb(xe) if (is.nan(fe)) fe <- Inf if (is.na(fe)) fe <- Inf nf <- nf + 1 if (fe < fr) { xnew <- xe fnew <- fe happy <- 1 } else { xnew <- xr fnew <- fr happy <- 1 } } else if (fr >= f[n] & fr < f[n + 1]) { xc <- (1 + rho * gamma) * xbar - rho * gamma * V[, n + 1] fc <- fnmb(xc) if (is.nan(fc)) fc <- Inf if (is.na(fc)) fc <- Inf nf <- nf + 1 if (fc <= fr) { xnew <- xc fnew <- fc happy <- 1 } } else if (fr >= f[n + 1]) { xc <- (1 - gamma) * xbar + gamma * V[, n + 1] fc <- fnmb(xc) if (is.nan(fc)) fc <- Inf if (is.na(fc)) fc <- Inf nf <- nf + 1 if (fc < f[n + 1]) { xnew <- xc fnew <- fc happy <- 1 } } if (happy == 1 & oshrink == 1) { fbt <- mean(c(f[1:n], fnew)) delfb <- fbt - fbc armtst <- alpha * sum(sgrad^2) if (delfb > -armtst/n) { if (trace) cat("Trouble - restarting: \n") restarts <- restarts + 1 orth <- 1 diams <- min(diam) sx <- sign(0.5 * sign(sgrad)) happy <- 0 V[, -1] <- V[, 1] diag(V[, -1]) <- diag(V[, -1]) - diams * sx[1:n] } } if (happy == 1) { V[, n + 1] <- xnew f[n + 1] <- fnew ord <- order(f) V <- V[, ord] f <- f[ord] } else if (happy == 0 & restarts < restarts.max) { if (orth == 0) orth <- 1 V[, -1] <- V[, 1] - sigma * (V[, -1] - V[, 1]) for (j in 2:ncol(V)) f[j] <- fnmb(V[, j]) nf <- nf + n ord <- order(f) V <- V[, ord] f <- f[ord] } v <- V[, -1] - V[, 1] delf <- f[-1] - f[1] diam <- sqrt(colSums(v^2)) simplex.size <- sum(abs(v))/max(1, sum(abs(V[, 1]))) if (is.nan(simplex.size)) simplex.size=Inf if (is.na(simplex.size)) simplex.size=Inf f[is.nan(f)] <- Inf f[is.na(f)] <- Inf dist <- f[n + 1] - f[1] sgrad <- c(crossprod(t(v), delf)) if (trace & !(itc%%2)) cat("iter: ", itc, "\n", "value: ", f[1], "\n") if (is.nan(dist)) dist <- Inf if (is.na(dist)) dist <- Inf } if (dist <= ftol | simplex.size <= 1e-06) { conv <- 0 message <- "Successful convergence" } else if (nf >= maxfeval) { conv <- 1 message <- "Maximum number of fevals exceeded" } else if (restarts >= restarts.max) { conv <- 2 message <- "Stagnation in Nelder-Mead" } return(list(par = ginv(V[, 1]), value = f[1] * (-1)^maximize, feval = nf, restarts = restarts, convergence = conv, message = message)) }
inPSphere2D = function(data,paretoRadius=NULL){ if(is.null(paretoRadius)) paretoRadius = ParetoRadius(data) nData = nrow(data) nVar = ncol(data) x = data[,1] y = data[,2] noNaNInd = (!is.nan(x)&!is.nan(y)) x = x[noNaNInd] y = y[noNaNInd] xMin = min(x) xMax = max(x) yMin = min(y) yMax = max(y) xBinWidth = paretoRadius yBinWidth = paretoRadius xedge = seq(xMin,(xMax+xBinWidth),by=xBinWidth) yedge = seq(yMin,(yMax+yBinWidth),by=yBinWidth) if(min(x)<xedge[1]) xedge = rbind(min(x),xedge) if(max(x)>xedge[length(xedge)]) xedge = rbind(xedge,max(x)) if(min(y)<yedge[1]) yedge = rbind(min(y),yedge) if(max(y)>yedge[length(yedge)]) yedge = rbind(yedge,max(y)) e = hist(x,xedge,plot=FALSE) xBinNr = findInterval(x,e$breaks) e = hist(y,yedge,plot=FALSE) yBinNr = findInterval(y,e$breaks) nrXBins = length(xedge) nrYBins = length(yedge) nInPsphere = c_inPSphere2D(data, xBinNr, yBinNr, nrXBins, nrYBins, nData, paretoRadius) return (nInPsphere) }
base64url_encode <- function(bin){ text <- base64_encode(bin) sub("=+$", "", chartr('+/', '-_', text)) } base64url_decode <- function(text){ text <- fix_padding(chartr('-_', '+/', text)) base64_decode(text) } fix_padding <- function(text){ text <- gsub("[\r\n]", "", text)[[1]] mod <- nchar(text) %% 4; if(mod > 0){ padding <- paste(rep("=", (4 - mod)), collapse = "") text <- paste0(text, padding) } text }
test_that("trimmed before NA detection", { expect_equal(parse_logical(c(" TRUE ", "FALSE", " NA ")), c(TRUE, FALSE, NA)) })
.onLoad <- function(libname, pkgname) { tzdir_set() on_package_load("vctrs", { register_s3_method("vctrs", "vec_proxy", "Period") register_s3_method("vctrs", "vec_proxy_compare", "Period") register_s3_method("vctrs", "vec_proxy_equal", "Period") register_s3_method("vctrs", "vec_restore", "Period") register_s3_method("vctrs", "vec_ptype2", "Period.Period") register_s3_method("vctrs", "vec_cast", "Period.Period") register_s3_method("vctrs", "vec_proxy", "Duration") register_s3_method("vctrs", "vec_proxy_compare", "Duration") register_s3_method("vctrs", "vec_proxy_equal", "Duration") register_s3_method("vctrs", "vec_restore", "Duration") register_s3_method("vctrs", "vec_ptype2", "Duration.Duration") register_s3_method("vctrs", "vec_ptype2", "Duration.difftime") register_s3_method("vctrs", "vec_ptype2", "difftime.Duration") register_s3_method("vctrs", "vec_cast", "Duration.Duration") register_s3_method("vctrs", "vec_cast", "Duration.difftime") register_s3_method("vctrs", "vec_cast", "difftime.Duration") register_s3_method("vctrs", "vec_proxy", "Interval") register_s3_method("vctrs", "vec_proxy_compare", "Interval") register_s3_method("vctrs", "vec_proxy_equal", "Interval") register_s3_method("vctrs", "vec_restore", "Interval") register_s3_method("vctrs", "vec_ptype2", "Interval.Interval") register_s3_method("vctrs", "vec_cast", "Interval.Interval") }) } register_s3_method <- function(pkg, generic, class, fun = NULL) { stopifnot(is.character(pkg), length(pkg) == 1) stopifnot(is.character(generic), length(generic) == 1) stopifnot(is.character(class), length(class) == 1) if (is.null(fun)) { fun <- get(paste0(generic, ".", class), envir = parent.frame()) } else { stopifnot(is.function(fun)) } if (pkg %in% loadedNamespaces()) { registerS3method(generic, class, fun, envir = asNamespace(pkg)) } setHook( packageEvent(pkg, "onLoad"), function(...) { registerS3method(generic, class, fun, envir = asNamespace(pkg)) } ) } on_package_load <- function(pkg, expr) { if (isNamespaceLoaded(pkg)) { expr } else { thunk <- function(...) expr setHook(packageEvent(pkg, "onLoad"), thunk) } }
solve_block <- function(mat){ x <- mat diag(x) <- 1 g <- igraph::graph_from_adjacency_matrix(adjmatrix = as.matrix(x), mode = "directed", weighted = TRUE, diag = TRUE) groups <- Map(sort, igraph::neighborhood(g, nrow(mat))) groups <- unique(Map(as.numeric, groups)) sub.Mat <- Map(`[`, list(mat), groups, groups, drop = FALSE) inv.sub.Mat <- Map(ginv,sub.Mat) mat.inv <- matrix(0, nrow(mat), ncol(mat)) for (i in 1:length(sub.Mat)) { mat.inv[groups[[i]], groups[[i]]] <- inv.sub.Mat[[i]] } return(mat.inv) }
test_that("multiple arguments matching", { expect_error( new_interval(y = 1, m = 2, mi = 3, second = 4), "Invalid argument:" ) expect_error(new_interval(hour = NULL, minute = 30), "accepts one input") expect_error(new_interval(hour = 1:2, minute = 30), "accepts one input") }) int <- new_interval(hour = 1, minute = 30) test_that("interval class", { expect_s3_class(int, "interval") expect_equal(format(int), "1h 30m") expect_s3_class(new_interval(), "interval") expect_equal(format(new_interval()), "?") expect_s3_class(new_interval(.regular = FALSE), "interval") expect_equal(format(new_interval(.regular = FALSE)), "!") }) test_that("as.period() & as.duration()", { expect_identical( lubridate::as.period(int), lubridate::period(hour = 1, minute = 30) ) expect_identical( lubridate::as.duration(int), lubridate::as.duration(lubridate::period(hour = 1, minute = 30)) ) })
print.decomposition_X11=function (x, digits = max(3L, getOption("digits") - 3L), enable_print_style = getOption("enable_print_style"), ...){ if(enable_print_style){ bold_pre_code <- "\033[1m" bold_post_code <- "\033[22m" }else{ bold_pre_code <- bold_post_code <- "" } m <- x$mstats s_flt <- x$s_filter t_flt <- x$t_filter if (!is.null(m)){ cat(bold_pre_code, "Monitoring and Quality Assessment Statistics:", bold_post_code,"\n") printCoefmat(m, digits = digits, P.values= FALSE, na.print = "NA", ...) } cat("\n") cat("Final filters:","\n") cat("Seasonal filter: ",s_flt) cat("\n") cat("Trend filter: ",t_flt) cat("\n") } print.decomposition_SEATS=function (x, digits = max(3L, getOption("digits") - 3L), enable_print_style = getOption("enable_print_style"),...){ if(enable_print_style){ bold_pre_code <- "\033[1m" bold_post_code <- "\033[22m" }else{ bold_pre_code <- bold_post_code <- "" } model <-x$model$model sa <- x$model$sa t <- x$model$trend s <- x$model$seasonal trans <- x$model$transitory i <- x$model$irregular var <- list(model, sa, t, s, trans, i) var_names <- c("Model","SA","Trend","Seasonal","Transitory","Irregular") for (ii in 1:length(var_names)){ if (!all(sapply(var[[ii]],is.null))){ cat(bold_pre_code,var_names[ii],bold_post_code,"\n", sep="") print_formula(var[[ii]][1,-1],"AR") print_formula(var[[ii]][2,-1],"D") print_formula(var[[ii]][3,-1],"MA") if (var[[ii]][4,1]==1) { cat("\n\n") }else{ cat("Innovation variance: ",var[[ii]][4,1], "\n\n") } } } } print_formula <- function(x, var){ non_0 <- which(x != 0 ) if(length(non_0) == 0) return(NULL) polynome_degre <- paste0("B^", non_0) polynome_degre[non_0 == 1] <- "B" polynome_coef <- sprintf("%+f", x[non_0], polynome_degre) polynome_coef <- gsub("-","- ", polynome_coef) polynome_coef <- gsub("\\+","+ ", polynome_coef) polynome_coef[x[non_0] == -1] <- "-" polynome_coef[x[non_0] == 1] <- "+" polynome_formula <- paste(polynome_coef, polynome_degre, collapse = " ") polynome_formula <- paste("1", polynome_formula) cat(var,": ",polynome_formula,"\n") } print.combined_test <- function(x, digits = max(3L, getOption("digits") - 3L), ...){ tests_pval <- x$tests_for_stable_seasonality[,"P.value", drop = FALSE] cat("Non parametric tests for stable seasonality") cat("\n") cat(paste0(" ", capture.output( printCoefmat(tests_pval, digits = digits, na.print = "NA", ...) ), sep ="\n")) cat("\n") combined_test_result <- c(Present = "Identifiable seasonality present", ProbablyNone = "Identifiable seasonality probably present", None = "Identifiable seasonality not present") combined_test_result <- combined_test_result[x$combined_seasonality_test] cat(combined_test_result) invisible(x) } print.diagnostics = function (x, digits = max(3L, getOption("digits") - 3L), enable_print_style = getOption("enable_print_style"), ...){ if(enable_print_style){ bold_pre_code <- "\033[1m" bold_post_code <- "\033[22m" }else{ bold_pre_code <- bold_post_code <- "" } residuals_test <- x$residuals_test combined_test <- x$combined_test variance_decomposition <- x$variance_decomposition cat(bold_pre_code, "Relative contribution of the components to the stationary\n", "portion of the variance in the original series,\n", "after the removal of the long term trend", bold_post_code) cat("\n") cat(" Trend computed by Hodrick-Prescott filter (cycle length = 8.0 years)") cat("\n") cat(paste0(" ", capture.output( printCoefmat(variance_decomposition, digits = digits, ...) )), sep ="\n") cat("\n") cat(bold_pre_code, "Combined test in the entire series", bold_post_code) cat("\n") cat(paste0(" ", capture.output(print.combined_test(combined_test, digits = digits, ...)) ), sep ="\n") cat("\n") cat(bold_pre_code, "Residual seasonality tests", bold_post_code) cat("\n") cat(paste0(" ", capture.output( printCoefmat(residuals_test[,"P.value", drop = FALSE], digits = digits, na.print = "NA", ...) ) ), sep ="\n") invisible(x) } print.final <- function(x, calendar, n_last_obs = frequency(x$series), print_forecasts = TRUE, ...){ cat("Last observed values\n") print(tail( .preformat.ts(x[[1]], calendar = calendar), n_last_obs )) if(print_forecasts){ if(!is.null(x[[2]])){ cat("\nForecasts:\n") print(head( .preformat.ts(x[[2]], calendar = calendar), n_last_obs )) }else{ cat("\nNo forecast") } } invisible(x) } print.user_defined <- function(x, ...){ if(is.null(x) || length(x) == 0) return(invisible(x)) cat(ngettext((length(x)!= 1) + 1, "One additional variable (", "Names of additional variables (")) cat(length(x),"):","\n", sep="") cat(names(x),sep = ", ") invisible(x) } print.SA <- function(x, enable_print_style = getOption("enable_print_style"), ...){ if(enable_print_style){ style_pre_code <- "\033[4m\033[1m" style_post_code <- "\033[22m\033[24m" }else{ style_pre_code <- style_post_code <- "" } cat(style_pre_code, "RegARIMA", style_post_code,"\n",sep="") print(x$regarima, enable_print_style = enable_print_style) cat("\n\n", style_pre_code, "Decomposition", style_post_code,"\n",sep="") print(x$decomposition, enable_print_style = enable_print_style) cat("\n\n", style_pre_code, "Final", style_post_code,"\n",sep="") print(x$final, enable_print_style = enable_print_style) cat("\n\n", style_pre_code, "Diagnostics", style_post_code,"\n",sep="") print(x$diagnostics, enable_print_style = enable_print_style) cat("\n\n", style_pre_code, "Additional output variables", style_post_code,"\n",sep="") print(x$user_defined) }
set_couleur_ronds <- function(map,colorPos=" { msg_error1<-msg_error2<-msg_error3<-msg_error4 <- NULL if(any(!any(class(map) %in% "leaflet"), !any(class(map) %in% "htmlwidget"))) if(!any(class(map) %in% "leaflet_proxy")) msg_error1 <- "La carte doit etre un objet leaflet ou leaflet_proxy / " if(!is.null(colorPos)) if(any(class(colorPos)!="character")) msg_error2 <- "La couleur doit etre de type caractere (nommee ou hexadecimal) / " if(!is.null(colorNeg)) if(any(class(colorNeg)!="character")) msg_error3 <- "La couleur doit etre de type caractere (nommee ou hexadecimal) / " if(!is.null(map_leaflet)) if (any(!any(class(map_leaflet) %in% "leaflet"), !any(class(map_leaflet) %in% "htmlwidget"))) msg_error4 <- "La carte doit etre un objet leaflet / " if(any(!is.null(msg_error1),!is.null(msg_error2),!is.null(msg_error3),!is.null(msg_error4))) { stop(simpleError(paste0(msg_error1,msg_error2,msg_error3,msg_error4))) } if(!is.null(map_leaflet)) { map_proxy <- map map <- map_leaflet } idx_maille <- NULL idx_carte <- NULL classes <- F for(i in 1:length(map$x$calls)) { if(map$x$calls[[i]]$method %in% "addPolygons") { if(map$x$calls[[i]]$args[[3]] %in% c("carte_ronds","carte_ronds_elargi","carte_classes","carte_classes_elargi")) { idx_maille <- c(idx_maille,i) } if(map$x$calls[[i]]$args[[3]] %in% c("carte_classes","carte_classes_elargi")) { classes <- T } } if(map$x$calls[[i]]$method %in% "addCircles") { if(map$x$calls[[i]]$args[[5]] %in% c("carte_ronds","carte_ronds_elargi")) { idx_carte <- c(idx_carte,i) } } } if(is.null(map_leaflet)) { for(i in 1:length(idx_carte)) { if(!classes) { valeurs <- map$x$calls[[idx_carte[i]]]$args[[4]]$analyse$donnees$save val_pos <- which(valeurs>=0) if(length(val_pos)>0) { map$x$calls[[idx_carte[i]]]$args[[6]]$fillColor[val_pos] <- colorPos } val_neg <- which(valeurs<0) if(length(val_neg)>0) { map$x$calls[[idx_carte[i]]]$args[[6]]$fillColor[val_neg] <- colorNeg } } } }else { map_leaflet <- map map <- map_proxy clearGroup(map, group = "carte_ronds") clearGroup(map, group = "carte_ronds_elargi") analyse_WGS84 <- map_leaflet$x$calls[[idx_carte[2]]]$args[[4]]$analyse_WGS84 analyse <- map_leaflet$x$calls[[idx_carte[2]]]$args[[4]]$analyse code_epsg <- map_leaflet$x$calls[[idx_carte[2]]]$args[[4]]$code_epsg emprise <- map_leaflet$x$calls[[idx_carte[2]]]$args[[4]]$emprise max_var <- map_leaflet$x$calls[[idx_carte[2]]]$args[[4]]$max_var varVolume <- map_leaflet$x$calls[[idx_carte[2]]]$args[[4]]$var_volume rayonRond <- map_leaflet$x$calls[[idx_carte[2]]]$args[[4]]$rayonRond if(!classes) { if(any(map_leaflet$x$calls[[idx_carte[1]]]$args[[4]]$nom_fond %in% c("fond_ronds_pos_elargi_carte","fond_ronds_neg_elargi_carte"))) { maille_WGS84_elargi <- map_leaflet$x$calls[[idx_maille[1]]]$args[[2]]$maille_WGS84_elargi analyse_WGS84_elargi <- map_leaflet$x$calls[[idx_carte[1]]]$args[[4]]$analyse_WGS84_elargi opacityElargi <- map_leaflet$x$calls[[idx_carte[1]]]$args[[6]]$fillOpacity colBorderPos <- map_leaflet$x$calls[[idx_carte[2]]]$args[[4]]$colBorderPos colBorderNeg <- map_leaflet$x$calls[[idx_carte[2]]]$args[[4]]$colBorderNeg epaisseurBorder <- map_leaflet$x$calls[[idx_carte[2]]]$args[[4]]$epaisseurBorder map <- addPolygons(map = map, data = maille_WGS84_elargi, stroke = TRUE, color = "grey", opacity = opacityElargi, weight = 0.5, options = pathOptions(pane = "fond_maille_elargi", clickable = T), popup = paste0("<b> <font color= fill = T, fillColor = "white", fillOpacity = 0.001, group = "carte_ronds_elargi", layerId = list(maille_WGS84_elargi=maille_WGS84_elargi,code_epsg=code_epsg,nom_fond="fond_maille_elargi") ) map <- addCircles(map = map, lng = st_coordinates(analyse_WGS84_elargi)[,1], lat = st_coordinates(analyse_WGS84_elargi)[,2], stroke = TRUE, color = sapply(analyse$donnees_elargi$save, function(x) if(x>0){colBorderPos}else{colBorderNeg}), opacity = opacityElargi, weight = epaisseurBorder, radius = rayonRond*sqrt(analyse$donnees_elargi[,varVolume]/max_var), options = pathOptions(pane = "fond_ronds_elargi", clickable = T), popup = paste0("<b> <font color= fill = T, fillColor = sapply(analyse$donnees_elargi$save, function(x) if(x>0){colorPos}else{colorNeg}), fillOpacity = opacityElargi, group = "carte_ronds_elargi", layerId = list(analyse=analyse,analyse_WGS84_elargi=analyse_WGS84_elargi,rayonRond=rayonRond,code_epsg=code_epsg,emprise=emprise, nom_fond=c(if(max(analyse$donnees_elargi$save)>0){"fond_ronds_pos_elargi_carte"}else{" "}, if(min(analyse$donnees_elargi$save)<0){"fond_ronds_neg_elargi_carte"}else{" "}), max_var=max_var,var_volume=varVolume,colBorderPos=colBorderPos,colBorderNeg=colBorderNeg,epaisseurBorder=epaisseurBorder) ) } map <- addCircles(map = map, lng = st_coordinates(analyse_WGS84)[,1], lat = st_coordinates(analyse_WGS84)[,2], stroke = TRUE, color = sapply(analyse$donnees$save, function(x) if(x>0){colBorderPos}else{colBorderNeg}), opacity = 1, weight = epaisseurBorder, radius = rayonRond*sqrt(analyse$donnees[,varVolume]/max_var), options = pathOptions(pane = "fond_ronds", clickable = T), popup = paste0("<b> <font color= fill = T, fillColor = sapply(analyse$donnees$save, function(x) if(x>0){colorPos}else{colorNeg}), fillOpacity = 1, group = "carte_ronds", layerId = list(analyse=analyse,analyse_WGS84=analyse_WGS84,rayonRond=rayonRond,code_epsg=code_epsg,emprise=emprise, nom_fond=c(if(max(analyse$donnees$save)>0){"fond_ronds_pos_carte"}else{" "}, if(min(analyse$donnees$save)<0){"fond_ronds_neg_carte"}else{" "}), max_var=max_var,var_volume=varVolume,colBorderPos=colBorderPos,colBorderNeg=colBorderNeg,epaisseurBorder=epaisseurBorder) ) }else { stop(simpleWarning("L'apparence de la couleur de remplissage des ronds ne s'applique que pour les analyses en ronds. Pour les analyses en classes dans les ronds (ronds_classes) ou en ronds sur les classes (classes_ronds), passez par la fonction set_couleur_classes().")) } } return(map) }
convert.to.Claddis <- function(data) { output <- list() output$topper$head <- "List generated by dispRity::Claddis.ordination" output$matrix_1$block_name <- NA output$matrix_1$datatype <- "STANDARD" output$matrix_1$matrix <- do.call(rbind, data) output$matrix_1$ordering <- rep("unord", length(data[[1]])) output$matrix_1$character_weights <- rep(1, length(data[[1]])) op <- options(warn = -1) output$matrix_1$minimum_values <- unlist(apply(output$matrix_1$matrix, 2, function(x) min(as.numeric(x), na.rm = TRUE))) is_nas <- is.na(output$matrix_1$minimum_values) output$matrix_1$maximum_values <- unlist(apply(output$matrix_1$matrix, 2, function(x) max(as.numeric(x), na.rm = TRUE))) output$matrix_1$characters$symbols <- unique(as.numeric(unlist(data)[-which(is.na(unlist(data)))])) op <- options(warn = 0) output$matrix_1$characters$missing <- "?" output$matrix_1$characters$gap <- "-" output$matrix_1$matrix <- ifelse(output$matrix_1$matrix == "?", NA, output$matrix_1$matrix) output$matrix_1$matrix <- ifelse(output$matrix_1$matrix == "-", "", output$matrix_1$matrix) class(output) <- "cladisticMatrix" return(output) }
isNumberOrNanScalar <- function(argument, default = NULL, stopIfNot = FALSE, message = NULL, argumentName = NULL) { checkarg(argument, "N", default = default, stopIfNot = stopIfNot, nullAllowed = FALSE, n = 1, zeroAllowed = TRUE, negativeAllowed = TRUE, positiveAllowed = TRUE, nonIntegerAllowed = TRUE, naAllowed = FALSE, nanAllowed = TRUE, infAllowed = FALSE, message = message, argumentName = argumentName) }
expected <- eval(parse(text="c(0L, 0L, 1L, 0L)")); test(id=0, code={ argv <- eval(parse(text="list(1:4, 3L, 0L, NULL)")); .Internal(`match`(argv[[1]], argv[[2]], argv[[3]], argv[[4]])); }, o=expected);
Warp <- R6Class("Warp", public = list( y = NULL, t = NULL, b = NULL, lambda=NULL, ker= NULL, tw = NULL, initialize = function(y = NULL, t=NULL,b=NULL,lambda=NULL,ker=NULL) { self$y = y self$t = t self$b = b self$lambda = lambda self$ker = ker self$greet() }, greet = function() { cat(paste("warp ",self$ker$greet(),".\n")) }, showker = function () { cat(paste0("ker is", self$ker$greet(), ".\n")) }, warpLoss = function( par,len,p0,eps ) { tor = as.matrix(self$t) n = max(dim(tor)) lam=par[1] self$ker$k_par=exp(len) lambda_t = self$lambda y_r = self$y self$b = par[2:(n+1)] kw=(2*pi/ (p0 + eps*tanh(lam) ) )^2 tw = matrix(c(0),ncol = n,nrow=1) for (i in 1:n) { tw[1,i] = self$ker$kern(tor[i,1],t(tor[,1]))%*%self$b^2 } t=t(tw) h=diff(t) z_t1 = matrix(c(0),ncol = n,nrow=1) z_t2 = matrix(c(0),ncol = n,nrow=2) y_t = matrix(c(0),ncol = n,nrow=2) for(i in 2:(n-1) ) { z_t1[1,i] = (y_r[i+1]-y_r[i-1])/ (h[i]+h[i-1]) } z_t1[1,1]=(y_r[2]-y_r[1])/h[1] z_t1[1,n]=(y_r[n]-y_r[n-1])/h[n-1] for(i in 2:(n-1) ) { z_t2[1,i] = (z_t1[i+1]-z_t1[i-1])/ (h[i]+h[i-1]) } z_t2[1,1]=(z_t1[2]-z_t1[1])/h[1] z_t2[1,n]=(z_t1[n]-z_t1[n-1])/h[n-1] y_t[1,]= y_r res= sum( (z_t2[1,] + kw*y_t[1,])^2 ) + lambda_t*( (tor[1,1]- t[1,1])^2+ (tor[n,1]- t[n,1])^2 ) if( is.nan( sum(z_t1) ) ) { print(len) return(res= 100000) } if( sum(abs(z_t1) )<1000 ) { z_t2[1,] = tryCatch( { predict(sm.spline(t, y_r,df=n-5),t, 2) }, warning = function(war) { print(paste("MY_WARNING: ",war)) }, error = function(err) { print(paste("warp_ERROR: ",err,i)) return(list(-10000,0) ) },finally = { } ) if(z_t2[[1]][1]==-10000){ return(res= 100000) } y_t[1,] = predict(sm.spline(t, y_r,df=n-5),t, 0) res= sum( (z_t2[1,] + kw*y_t[1,])^2 ) + lambda_t*( (tor[1,1]- t[1,1])^2+ (tor[n,1]- t[n,1])^2 ) } res }, warpLossLen=function(par,lam,p0,eps ){ tor = as.matrix(self$t) n = max(dim(tor)) lam = lam self$ker$k_par=exp(par) lambda_t = self$lambda y_r = self$y kw=(2*pi/ (p0 + eps*tanh(lam) ) )^2 tw = matrix(c(0),ncol = n,nrow=1) for (i in 1:n) { tw[1,i] = self$ker$kern(tor[i,1],t(tor[,1]))%*%self$b^2 } t=t(tw) h=diff(t) z_t1 = matrix(c(0),ncol = n,nrow=1) z_t2 = matrix(c(0),ncol = n,nrow=2) y_t = matrix(c(0),ncol = n,nrow=2) for(i in 2:(n-1) ) { z_t1[1,i] = (y_r[i+1]-y_r[i-1])/ (h[i]+h[i-1]) } z_t1[1,1]=(y_r[2]-y_r[1])/h[1] z_t1[1,n]=(y_r[n]-y_r[n-1])/h[n-1] for(i in 2:(n-1) ) { z_t2[1,i] = (z_t1[i+1]-z_t1[i-1])/ (h[i]+h[i-1]) } z_t2[1,1]=(z_t1[2]-z_t1[1])/h[1] z_t2[1,n]=(z_t1[n]-z_t1[n-1])/h[n-1] y_t[1,]= y_r res= sum( (z_t2[1,] + kw*y_t[1,])^2 ) + lambda_t*( (tor[1,1]- t[1,1])^2+ (tor[n,1]- t[n,1])^2 ) if( is.nan( sum(z_t1) ) ) { print(len) return(res= 100000) } if( sum(abs(z_t1) )<1000 ){ z_t2[1,] = predict(sm.spline(t, y_r),t, 2) y_t[1,] = predict(sm.spline(t, y_r),t, 0) res= sum( (z_t2[1,] + kw*y_t[1,])^2 ) + lambda_t*( (tor[1,1]- t[1,1])^2+ (tor[n,1]- t[n,1])^2 ) } res }, warpSin = function( len ,lop,p0,eps ) { kw1= 1 lout = length(self$t) bw = self$b for(i in 1:lop) { par<-c(kw1,bw) test <- tryCatch({ optim(par,self$warpLoss,gr=NULL,len,p0,eps,method="BFGS") }, warning = function(war) { print(paste("MY_WARNING: ",war)) }, error = function(err) { print(paste("warp_ERROR: ",err,i)) return(list(-10000,0) ) },finally = { } ) if(test[[1]][1]==-10000) { wscore=100000 break }else { self$b= test$par[2:(lout+1)] kw1 = test$par[1] par2=len bw= self$b test2<-tryCatch({ optim(par2,self$warpLossLen,gr=NULL,kw1,p0,eps,method="L-BFGS-B") }, warning = function(war) { print(paste("MY_WARNING: ",war)) }, error = function(err) { print(paste("warp_ERROR: ",err,i)) return(list(-10000,0) ) },finally = { } ) if(test2[[1]][1]==-10000){ wscore= 100000 break } wscore=test2$value len=test2$par } } self$ker$k_par = exp(len) n = length(self$t) tw = matrix(c(0),ncol = n,nrow=1) for (i in 1:n) { tw[1,i] = self$ker$kern(self$t[i],t(self$t))%*%self$b^2 } self$tw = tw return( list( "rescore"=wscore,"len"=len) ) }, slowWarp = function(lens,p0,eps) { bw = rep(c(1),length(self$t)) kw = 1 loscore=c(0) for(iii in 1:length(lens)) { par<-c(kw,bw) len=lens[iii] ptm <- proc.time() test<-optim(par,self$warpLoss,gr=NULL,len,p0,eps,method="BFGS") proc.time() - ptm loscore[iii]= test$value } len=lens[which(loscore==min(loscore) )][1] return(list("len"=len,"loscore"=loscore)) } ) )
.Power <- function(a, b) { return(a^b) } E <- exp(1) .ksmooth2 <- function(x, v, h) { res.f <- sum((1 - (x[1] - v[, 1])^2 / h[1]^2)^2 * (1 - (x[2] - v[, 2])^2 / h[2]^2)^2 * ((v[, 1] - x[1])^2 <= h[1]^2) * ((v[, 2] - x[2])^2 <= h[2]^2)) / (h[1] * h[2]) * 15^2 / 16^2 / dim(v)[1] return(res.f) } .integrand <- function(x, Lfsample, Lbootsample, h) { res.f <- (.ksmooth2(x, Lfsample, h) - .ksmooth2(x, Lbootsample, h))^2 return(res.f) }
diffPower4slope.scRNAseq=function( slope, n, m, power, sigma.y, MAF=0.2, rho=0.8, FWER=0.05, nTests=1) { est.power=powerEQTL.scRNAseq.default( slope = slope, n = n, m = m, sigma.y = sigma.y, MAF=MAF, rho=rho, FWER=FWER, nTests=nTests) diff=est.power - power return(diff) } minSlopeEQTL.scRNAseq=function(n, m, power = 0.8, sigma.y = 0.29, MAF=0.2, rho=0.8, FWER=0.05, nTests=1) { res.root=uniroot(f=diffPower4slope.scRNAseq, interval = c(0.000001, 1.0e+30), n = n, m = m, power = power, sigma.y = sigma.y, MAF=MAF, rho=rho, FWER=FWER, nTests=nTests ) return(res.root$root) }
library(testthat) urlExists <- function(target) { tryCatch({ con <- url(target) a <- capture.output(suppressWarnings(readLines(con))) close(con) TRUE; }, error = function(err) { occur <- grep("cannot open the connection", capture.output(err)); if(length(occur) > 0) FALSE; } ) } testthat::expect_true(urlExists("https://raw.githubusercontent.com/chadwickbureau/baseballdatabank/master/core/AllstarFull.csv")) testthat::expect_true(urlExists("https://raw.githubusercontent.com/keberwein/baseballdatabank/master/core/AllstarFull.csv")) testthat::expect_true(urlExists("http://www.fangraphs.com/guts.aspx?type=cn"))
w <- matrix(c(0.1, 0.2, -0.05, 0.1)) Sigma <- Semidef(4) obj <- Maximize(t(w) %*% Sigma %*% w) constraints <- list(Sigma[1,1] == 0.2, Sigma[2,2] == 0.1, Sigma[3,3] == 0.3, Sigma[4,4] == 0.1, Sigma[1,2] >= 0, Sigma[1,3] >= 0, Sigma[2,3] <= 0, Sigma[2,4] <= 0, Sigma[3,4] >= 0) prob <- Problem(obj, constraints) result <- solve(prob, solver = "SCS") result$getValue(Sigma)
knitr::opts_chunk$set( collapse = TRUE, comment = " fig.width=10, fig.height=8.5 ) library(ggplot2) library(dplyr) library(partykit) library(StratifiedMedicine) library(survival) dat_ctns = generate_subgrp_data(family="gaussian") Y = dat_ctns$Y X = dat_ctns$X A = dat_ctns$A length(Y) table(A) dim(X) res_f <- filter_train(Y, A, X, filter="glmnet") res_f$filter.vars plot_importance(res_f) res_f2 <- filter_train(Y, A, X, filter="glmnet", hyper=list(interaction=T)) res_f2$filter.vars plot_importance(res_f2) res_p1 <- ple_train(Y, A, X, ple="ranger", meta="T-learner") summary(res_p1$mu_train) plot_ple(res_p1) plot_dependence(res_p1, X=X, vars="X1") res_p2 <- ple_train(Y, A, X, ple="ranger", meta="T-learner", hyper=list(mtry=5)) plot_dependence(res_p2, X=X, vars=c("X1", "X2")) res_s1 <- submod_train(Y, A, X, submod="lmtree") table(res_s1$Subgrps.train) plot(res_s1$fit$mod) res_s2 <- submod_train(Y, A, X, mu_train=res_p2$mu_train, submod="otr", delta=">0.10") plot(res_s2$fit$mod) param.dat1 <- param_est(Y, A, X, Subgrps = res_s1$Subgrps.train, param="lm") param.dat1 param.dat2 <- param_est(Y, A, X, Subgrps = res_s1$Subgrps.train, mu_hat = res_p1$mu_train, param="dr") param.dat2 %>% filter(estimand=="mu_1-mu_0") library(knitr) summ.table = data.frame( `Step` = c("estimand(s)", "filter", "ple", "submod", "param"), `gaussian` = c("E(Y|A=0)<br>E(Y|A=1)<br>E(Y|A=1)-E(Y|A=0)", "Elastic Net<br>(glmnet)", "X-learner: Random Forest<br>(ranger)", "MOB(OLS)<br>(lmtree)", "Double Robust<br>(dr)"), `binomial` = c("E(Y|A=0)<br>E(Y|A=1)<br>E(Y|A=1)-E(Y|A=0)", "Elastic Net<br>(glmnet)", "X-learner: Random Forest<br>(ranger)", "MOB(GLM)<br>(glmtree)", "Doubly Robust<br>(dr)"), `survival` = c("HR(A=1 vs A=0)", "Elastic Net<br>(glmnet)", "T-learner: Random Forest<br>(ranger)", "MOB(OLS)<br>(lmtree)", "Hazard Ratios<br>(cox)") ) kable( summ.table, caption = "Default PRISM Configurations (With Treatment)", full_width=T) summ.table = data.frame(`Step` = c("estimand(s)", "filter", "ple", "submod", "param"), `gaussian` = c("E(Y)", "Elastic Net<br>(glmnet)", "Random Forest<br>(ranger)", "Conditional Inference Trees<br>(ctree)", "OLS<br>(lm)"), `binomial` = c("Prob(Y)", "Elastic Net<br>(glmnet)", "Random Forest<br>(ranger)", "Conditional Inference Trees<br>(ctree)", "OLS<br>(lm)"), `survival` = c("RMST", "Elastic Net<br>(glmnet)", "Random Forest<br>(ranger)", "Conditional Inference Trees<br>(ctree)", "RMST<br>(rmst)")) kable( summ.table, caption = "Default PRISM Configurations (Without Treatment, A=NULL)", full_width=T) res0 = PRISM(Y=Y, A=A, X=X) summary(res0) plot(res0) res_prog = PRISM(Y=Y, X=X) summary(res_prog) plot(res0$filter.mod) res0$filter.vars plot_importance(res0) summary(res0$mu_train) plot_ple(res0) plot_dependence(res0, vars=c("X2")) plot(res0$submod.fit$mod, terminal_panel = NULL) table(res0$out.train$Subgrps) table(res0$out.test$Subgrps) res0$param.dat dat_bin = generate_subgrp_data(family="binomial", seed = 5558) Y = dat_bin$Y X = dat_bin$X A = dat_bin$A res0 = PRISM(Y=Y, A=A, X=X) summary(res0) data("GBSG2", package = "TH.data") surv.dat = GBSG2 Y = with(surv.dat, Surv(time, cens)) X = surv.dat[,!(colnames(surv.dat) %in% c("time", "cens")) ] set.seed(6345) A = rbinom(n = dim(X)[1], size=1, prob=0.5) res_weib = PRISM(Y=Y, A=A, X=X) summary(res_weib) plot(res_weib)
apportion_web <- function(reach_dist, w, max_dist = Inf, min_frac = 0, reach_name = NULL, dist_name = NULL) { if (!is.null(reach_name)) names(reach_dist)[names(reach_dist) == reach_name] <- "reach" if (!is.null(dist_name)) names(reach_dist)[names(reach_dist) == dist_name] <- "dist" df_out <- reach_dist %>% subset(dist <= max_dist) %>% transform(frac_depletion_pt = (1 / dist^w) / sum((1 / dist^w))) %>% dplyr::group_by(reach) %>% dplyr::summarize(frac_depletion = sum(frac_depletion_pt)) %>% dplyr::select(reach, frac_depletion) if (min(df_out$frac_depletion) < min_frac) { depl_low <- sum(df_out$frac_depletion[df_out$frac_depletion < min_frac]) df_out <- subset(df_out, frac_depletion >= min_frac) df_out$frac_depletion <- df_out$frac_depletion + depl_low * (df_out$frac_depletion / (1 - depl_low)) return(df_out) } else { return(df_out) } }
skip_on_cran() oldtz <- Sys.getenv('TZ', unset = NA) Sys.setenv(TZ = 'UTC') tests.home <- getwd() setwd(tempdir()) exampleWorkspace("exampleWorkspace") setwd("exampleWorkspace") bio <- read.csv("biometrics.csv") deployments <- read.csv("deployments.csv") spatial <- read.csv("spatial.csv") detections <- example.detections detections$ExtraCol <- NA dot <- paste(unique(spatial$Array[spatial$Type == "Hydrophone"]), collapse = "--") test_that("Correct error is triggered if datapack is not valid", { expect_error(results <- explore(datapack = "a"), "The datapack's token is invalid or missing. Please the function preload() to compile the input data. Additionally, data must to be compiled during the current R session.", fixed = TRUE) expect_error(results <- migration(datapack = "a"), "The datapack's token is invalid or missing. Please the function preload() to compile the input data. Additionally, data must to be compiled during the current R session.", fixed = TRUE) expect_error(results <- residency(datapack = "a"), "The datapack's token is invalid or missing. Please the function preload() to compile the input data. Additionally, data must to be compiled during the current R session.", fixed = TRUE) }) expect_warning(d <- preload(biometrics = bio, deployments = deployments, spatial = spatial, detections = detections, dot = dot, tz = "Europe/Copenhagen"), "No detections were found for receiver(s) 132907", fixed = TRUE) test_that("checkArguments complains if preload is used together with tz", { expect_warning(explore(datapack = d, tz = "Europe/Copenhagen"), "Argument 'tz' was set but a datapack was provided. Disregarding set arguments.", fixed = TRUE) }) test_that("checkArguments stops if wrong override is provided with preload", { expect_error(explore(datapack = d, override = 1234), "Some tag signals listed in 'override' (1234) are not listed in the biometrics data", fixed = TRUE) }) test_that("explore with preload yields the same results as with traditional loading", { results <- suppressWarnings(explore(datapack = d)) results2 <- suppressWarnings(explore(tz = "Europe/Copenhagen")) for (i in 1:length(results$valid.movements)) { expect_equal(results$movements[[i]], results2$movements[[i]]) expect_equal(results$valid.movements[[i]], results2$valid.movements[[i]]) } expect_equal(extractSignals(names(results$valid.movements)), extractSignals(names(results2$valid.movements))) expect_equal(results$arrays, results2$arrays) expect_equal(results$spatial, results2$spatial) }) test_that("migration and residency don't start if datapack is incompatible", { xspatial <- spatial[, -match("Section", colnames(spatial))] expect_warning(d <- preload(biometrics = bio, deployments = deployments, spatial = xspatial, detections = detections, tz = "Europe/Copenhagen"), "The spatial input does not contain a 'Section' column. This input is only valid for explore() analyses.", fixed = TRUE) expect_error(results <- migration(datapack = d, GUI = "never"), "To run migration(), please assign the arrays to their sections using a 'Section' column in the spatial input.", fixed = TRUE) expect_error(results <- residency(datapack = d, GUI = "never"), "To run residency(), please assign the arrays to their sections using a 'Section' column in the spatial input.", fixed = TRUE) }) test_that("migration and residency with preload yield the same results as with traditional loading", { expect_warning(d2 <- preload(biometrics = bio, deployments = deployments, spatial = spatial, detections = detections, tz = "Europe/Copenhagen"), "No detections were found for receiver(s) 132907", fixed = TRUE) results <- suppressWarnings(migration(datapack = d2)) results2 <- suppressWarnings(migration(tz = "Europe/Copenhagen")) expect_equal(extractSignals(names(results$valid.movements)), extractSignals(names(results2$valid.movements))) expect_equal(results$status.df[, -1], results2$status.df[, -1]) for (i in 1:length(results$valid.movements)) { expect_equal(results$movements[[i]], results2$movements[[i]]) expect_equal(results$valid.movements[[i]], results2$valid.movements[[i]]) } results <- suppressWarnings(residency(datapack = d2)) results2 <- suppressWarnings(residency(tz = "Europe/Copenhagen")) for (i in 1:length(results$valid.movements)) { expect_equal(results$movements[[i]], results2$movements[[i]]) expect_equal(results$valid.movements[[i]], results2$valid.movements[[i]]) } expect_equal(extractSignals(names(results$valid.movements)), extractSignals(names(results2$valid.movements))) expect_equal(results$arrays, results2$arrays) expect_equal(results$status.df[, -1], results2$status.df[, -1]) }) test_that("tz and exclude.tags stops are working", { expect_error(preload(tz = "test"), "'tz' could not be recognized as a timezone. Check available timezones with OlsonNames()", fixed = TRUE) expect_error(preload(tz = "Europe/Copenhagen", exclude.tags = "test"), "Not all contents in 'exclude.tags' could be recognized as tags (i.e. 'codespace-signal'). Valid examples: 'R64K-1234', A69-1303-1234'", fixed = TRUE) }) test_that("dot stop is working", { expect_error( expect_warning(preload(biometrics = bio, deployments = deployments, spatial = spatial, detections = detections, tz = "Europe/Copenhagen", dot = 1), "No detections were found for receiver(s) 132907", fixed = TRUE), "'dot' was set but could not recognised as a string. Please prepare a dot string and include it in the dot argument. You can use readDot to check the quality of your dot string.", fixed = TRUE) }) test_that("start.time and stop.time are working fine in preload", { expect_message(suppressWarnings(preload(biometrics = bio, deployments = deployments, spatial = spatial, detections = detections, tz = "Europe/Copenhagen", start.time = "2018-05-01 00:00")), "M: Discarding detection data previous to 2018-05-01 00:00 per user command (9866 detections discarded).", fixed = TRUE) expect_message(suppressWarnings(preload(biometrics = bio, deployments = deployments, spatial = spatial, detections = detections, tz = "Europe/Copenhagen", stop.time = "2018-05-08 00:00")), "M: Discarding detection data posterior to 2018-05-08 00:00 per user command (544 detections discarded).", fixed = TRUE) expect_message(suppressWarnings(preload(biometrics = bio, deployments = deployments, spatial = spatial, detections = detections, tz = "Europe/Copenhagen", start.time = "2018-05-01 00:00", stop.time = "2018-05-08 00:00")), "M: Data time range: 2018-05-01 00:04:30 to 2018-05-07 23:59:47 (Europe/Copenhagen).", fixed = TRUE) }) write.csv(example.distances, "distances.csv") test_that("distances are correctly handled with preload", { d2 <- suppressWarnings(preload(biometrics = bio, deployments = deployments, spatial = spatial, detections = detections, dot = dot, distances = example.distances, tz = "Europe/Copenhagen")) results <- suppressWarnings(explore(datapack = d2)) results2 <- suppressWarnings(explore(tz = "Europe/Copenhagen")) for (i in 1:length(results$valid.movements)) { expect_equal(results$movements[[i]], results2$movements[[i]]) expect_equal(results$valid.movements[[i]], results2$valid.movements[[i]]) } expect_equal(extractSignals(names(results$valid.movements)), extractSignals(names(results2$valid.movements))) expect_equal(results$arrays, results2$arrays) expect_equal(results$spatial, results2$spatial) }) test_that("preload stops if mandatory columns are missing or have NAs", { x <- detections[, -1] expect_error(suppressWarnings(preload(biometrics = bio, deployments = deployments, spatial = spatial, detections = x, dot = dot, distances = example.distances, tz = "Europe/Copenhagen")), "The following mandatory columns are missing in the detections: Timestamp", fixed = TRUE) x <- detections[, -match("Signal", colnames(detections))] expect_error(suppressWarnings(preload(biometrics = bio, deployments = deployments, spatial = spatial, detections = x, dot = dot, distances = example.distances, tz = "Europe/Copenhagen")), "The following mandatory columns are missing in the detections: Signal The functions extractSignals and extractCodeSpaces can be used to break transmitter codes apart.", fixed = TRUE) x <- detections x[1, 1] <- NA expect_error(suppressWarnings(preload(biometrics = bio, deployments = deployments, spatial = spatial, detections = x, dot = dot, distances = example.distances, tz = "Europe/Copenhagen")), "There is missing data in the following mandatory columns of the detections: Timestamp", fixed = TRUE) }) test_that("Data conversion warnings and errors kick in", { d <- detections d$Signal <- as.character(d$Signal) expect_warning(preload(biometrics = bio, deployments = deployments, spatial = spatial, detections = d, dot = dot, distances = example.distances, tz = "Europe/Copenhagen"), "The 'Signal' column in the detections is not of type integer. Attempting to convert.", fixed = TRUE) d <- detections d$Receiver <- as.character(d$Receiver) expect_warning(preload(biometrics = bio, deployments = deployments, spatial = spatial, detections = d, dot = dot, distances = example.distances, tz = "Europe/Copenhagen"), "The 'Receiver' column in the detections is not of type integer. Attempting to convert.", fixed = TRUE) d <- detections d$Receiver <- paste0("a-", d$Receiver) expect_warning(preload(biometrics = bio, deployments = deployments, spatial = spatial, detections = d, dot = dot, distances = example.distances, tz = "Europe/Copenhagen"), "Attempting to convert the 'Receiver' to integer failed. Attempting to extract only the serial numbers.", fixed = TRUE) d <- detections d$Receiver <- "a" expect_error(suppressWarnings(preload(biometrics = bio, deployments = deployments, spatial = spatial, detections = d, dot = dot, distances = example.distances, tz = "Europe/Copenhagen")), "Extracting the serial numbers failed. Aborting.", fixed = TRUE) d <- detections d$Sensor.Value <- "1" expect_warning(preload(biometrics = bio, deployments = deployments, spatial = spatial, detections = d, dot = dot, distances = example.distances, tz = "Europe/Copenhagen"), "The 'Sensor.Value' column in the detections is not of type numeric. Attempting to convert.", fixed = TRUE) d <- detections d$Sensor.Value <- "b" expect_error(suppressWarnings(preload(biometrics = bio, deployments = deployments, spatial = spatial, detections = d, dot = dot, distances = example.distances, tz = "Europe/Copenhagen")), "Attempting to convert the 'Sensor.Value' to numeric failed. Aborting.", fixed = TRUE) d <- detections d$Timestamp <- as.character(d$Timestamp) expect_message(suppressWarnings(preload(biometrics = bio, deployments = deployments, spatial = spatial, detections = d, dot = dot, distances = example.distances, tz = "Europe/Copenhagen")), "Converting detection timestamps to POSIX objects", fixed = TRUE) d <- detections d$Timestamp <- "b" expect_error(suppressWarnings(preload(biometrics = bio, deployments = deployments, spatial = spatial, detections = d, dot = dot, distances = example.distances, tz = "Europe/Copenhagen")), "Converting the timestamps failed. Aborting.", fixed = TRUE) d <- detections d$Valid <- "b" expect_warning(preload(biometrics = bio, deployments = deployments, spatial = spatial, detections = d, dot = dot, distances = example.distances, tz = "Europe/Copenhagen"), "The detections have a column named 'Valid' but its content is not logical. Resetting to Valid = TRUE.", fixed = TRUE) }) setwd("..") unlink("exampleWorkspace", recursive = TRUE) setwd(tests.home) if (is.na(oldtz)) Sys.unsetenv("TZ") else Sys.setenv(TZ = oldtz) rm(list = ls())
color.clusters = function(x, idx = seq_along(x$clusters), col = grDevices::hcl.colors(length(idx))) { if (class(x) != "scan" & class(x) != "smerc_cluster") { stop("x should be an object of class scan or smerc_cluster.") } if (min(idx) < 1 | max(idx) > length(x$clusters)) { stop("invalid idx values") } if (length(idx) != length(col)) { stop("The number of colors must match the length of idx.") } mycol = numeric(nrow(x$coords)) for (i in seq_along(x$clusters)) { mycol[x$clusters[[i]]$loc] = col[i] } return(mycol) }
Sys.ps.cmd <- function() { sys <- (si <- Sys.info())[["sysname"]] if(sys == "Linux") { s.rel <- si[["release"]] rel <- c(as.integer(strsplit(s.rel,"[[:punct:]]")[[1]][1:2]) %*% c(1000,1)) if(is.na(rel)) rel <- 3000 if(rel >= 2006) "/bin/ps w" else if(rel >= 2002) "/bin/ps --width 1000" else structure("/bin/ps w",type="BSD") } else if(sys == "SunOS") "/usr/bin/ps" else { warning("Unknown OS [Operating System]; 'ps' may not be compatible") "ps" } } u.sys <- function(..., intern=TRUE) system(paste0(...), intern=intern) u.date <- function(short = FALSE) format(Sys.time(), paste0("%d/%h/%Y", if(!short) ", %H:%M")) u.Datumvonheute <- function(W.tag = 2, Zeit = FALSE) { dat <- as.integer(strsplit(format(Sys.time(),"%w %d %m %Y %H %M"), " ")[[1]]) DMY <- paste0(dat[2], ". ", C.Monatsname[dat[3]], " ", dat[4]) r <- if (W.tag) { W <- ifelse(dat[1]==0, 7, dat[1]) if (W.tag==2) Wtag <- C.Wochentag[W] else Wtag <- C.Wochentagkurz[W] paste(Wtag, DMY, sep=", ") } else DMY if(Zeit) { paste(r, if (Zeit==2) paste(dat[5:6], collapse=":") else dat[5], sep="; ") } else r } C.Monatsname <- c("Januar", "Februar", "Maerz", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember") C.Wochentag <- c("Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag", "Sonntag") C.Wochentagkurz <- c("Mon", "Die", "Mit", "Don", "Fre", "Sam", "Son") C.weekday <- c("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun") u.datumdecode <- function(d, YMDHMnames = c("Jahr", "Monat", "Tag", "Std", "Min")) { if(length(YMDHMnames) != 5 || !is.character(YMDHMnames)) stop("invalid `YMDHMnames': must be character(5)") n <- length(d) z <- matrix(NA, n, 5, dimnames = list(names(d), YMDHMnames)) for(j in 5:1) { h <- d %/% 100 z[, j] <- d - 100 * h d <- h } drop(z) }
cut_off_point_method <- function(x, cut_points, names_activity_ranges = NA, hidden_PA_levels = NA, bout_lengths = NULL, plotting= 0) { if (is.null(bout_lengths)) { stop("Set variable 'bout_lengths' to use this function. See help-manual for further information. For example: bout_lengths=c(1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,12,13,20,21,40,41,60,61,80,81,120,121,240,241,480,481,1440,1,1440)") } cut_points <- c(0, cut_points) number_of_activity_ranges <- length(cut_points) activity_ranges <- array(data = NA, dim = c(1,2,number_of_activity_ranges)) colnames(activity_ranges) <- c("[lower boundary,","upper boundary)") bouts <- function(counts, sequence_activity_range, cut_points, bout_lengthss) { for_plotting_a <- sequence_activity_range for (i in 1:length(cut_points)) { for_plotting_a[for_plotting_a == i] <- cut_points[i] } for_plotting_a[sequence_activity_range == (length(cut_points) + 1)] <- max(counts) for_plotting_b <- sequence_activity_range for_plotting_b <- for_plotting_b - 1 for (i in 1:length(cut_points)) { for_plotting_b[for_plotting_b == i] <- cut_points[i] } for_plotting_b[for_plotting_b == 0] <- 0 dimension_columns_of_next_arry <- max(length(bout_lengthss), length(x), max(bout_lengthss)) if (dimension_columns_of_next_arry == Inf) { dimension_columns_of_next_arry <- max(bout_lengthss[!bout_lengthss == Inf], length(x)) } bout_periods <- array(0, dim = c((length(cut_points) + 1), dimension_columns_of_next_arry, 1)) if (all(!is.na(names_activity_ranges))) { dimnames(bout_periods) <- list(activity_range = names_activity_ranges, Countbouts = 1: dimension_columns_of_next_arry) } else { dimnames(bout_periods) <- list(activity_range = 1:(length(cut_points) + 1), Countbouts = 1: dimension_columns_of_next_arry) } temp_sequence_activity_range <- c(sequence_activity_range, -Inf) for (j in 1:(length(cut_points) + 1)) { temp_vec <- 0 for (i in 1:length(temp_sequence_activity_range)) { if (temp_sequence_activity_range[i] == j) { temp_vec <- temp_vec + 1 } else { temp_which_bout <- temp_vec bout_periods[j,temp_which_bout,1] <- bout_periods[j,temp_which_bout,1] + 1 temp_vec <- 0 } if (temp_vec == length(temp_sequence_activity_range)) { temp_which_bout <- temp_vec bout_periods[j,temp_which_bout,1] = bout_periods[j,temp_which_bout,1] + 1 temp_vec <- 0 } } } quantity_of_bouts <- sum(bout_periods) return(list(quantity_of_bouts = quantity_of_bouts, bout_periods = bout_periods, for_plotting_a = for_plotting_a, for_plotting_b = for_plotting_b)) } for (i in 1:number_of_activity_ranges) { activity_ranges[1,1,i] <- cut_points[i] activity_ranges[1,2,i] <- cut_points[i+1] } activity_ranges[1,2,number_of_activity_ranges] <- Inf classification <- rep(NA, times = length(x)) if (any(is.na(hidden_PA_levels))) { for (i in 1:length(x)) { for (j in 1:number_of_activity_ranges) { if (x[i] >= activity_ranges[1,1,j] & x[i] < activity_ranges[1,2,j]) { classification[i] <- c(j) } } } classification_per_activity_range <- pairlist(NA) for (i in 1:number_of_activity_ranges) { classification_per_activity_range[[i]] <- x for (j in 1:length(classification_per_activity_range[[i]])) { if (!classification[j] == i) { classification_per_activity_range[[i]][j] <- NA } } } } if (any(!is.na(hidden_PA_levels))) { for (i in 1:length(x)) { for (j in 1:number_of_activity_ranges) { if (hidden_PA_levels[i] >= activity_ranges[1,1,j] & hidden_PA_levels[i] < activity_ranges[1,2,j]) { classification[i] <- c(j) } } } classification_per_activity_range <- pairlist(NA) for (i in 1:number_of_activity_ranges) { classification_per_activity_range[[i]] <- x for (j in 1:length(classification_per_activity_range[[i]])) { if (!classification[j] == i) { classification_per_activity_range[[i]][j] <- NA } } } } freq_acitvity_range <- table(c(seq(1, number_of_activity_ranges), classification)) freq_acitvity_range <- freq_acitvity_range - 1 rel_freq_acitvity_range <- freq_acitvity_range / sum(table(classification)) if (all(!is.na(names_activity_ranges))) { rownames(freq_acitvity_range) <- names_activity_ranges rownames(rel_freq_acitvity_range) <- names_activity_ranges colnames(activity_ranges[1,,]) <- names_activity_ranges names(classification_per_activity_range ) <- names_activity_ranges } bout_extraction <- bouts(counts = x, sequence_activity_range = classification, cut_points = cut_points[c(-1)], bout_lengthss = bout_lengths) quantity_of_bouts <- bout_extraction$quantity_of_bouts bout_periods <- bout_extraction$bout_periods bout_classes <- matrix(bout_lengths, nrow = 2, byrow = FALSE) names = NULL for (i in seq(1, dim(bout_classes)[2])) { if (bout_classes[1,i] == bout_classes[2,i]) { names <- c(names, toString(bout_classes[1,i])) } else { names <- c(names, paste(toString(bout_classes[1,i]), '-', toString(bout_classes[2,i])) ) } } colnames(bout_classes) <- names rownames(bout_classes) <- c("from", "to") abs_freq_bouts_el <- rep(0, times = length(names)) for (i in 1:(length(names))) { abs_freq_bouts_el[i] <- sum(bout_periods[,seq(bout_classes[1,i], bout_classes[2,i]),1]) } names(abs_freq_bouts_el) <- names abs_freq_bouts_el <- pairlist(all_activity_ranges = abs_freq_bouts_el) for (j in 1: number_of_activity_ranges) { abs <- rep(0, times = length(names)) for (i in 1:(length(names))) { abs[i] <- sum(bout_periods[j,seq(bout_classes[1,i], bout_classes[2,i]),1]) } names(abs) <- names if (all(!is.na(names_activity_ranges))) { abs_freq_bouts_el[[names_activity_ranges[j]]] <- abs } else { abs_freq_bouts_el[[j+1]] <- abs } } if (!is.na(plotting)) { if (plotting == 0) { par(mfrow = c(2,2)) if (any(!is.na(hidden_PA_levels))) { plot(x, main = "classification (HMM)", xlab = "time", ylab= "counts", col = "white") } else { plot(x, main = "classification", xlab = "time", ylab = "counts", col = "white") } abline(h = cut_points[c(-1)], col = "grey50", lty = "dashed") for (i in 1: number_of_activity_ranges) { points(as.numeric(classification_per_activity_range[[i]]), col = i) } if (all(!is.na(names_activity_ranges))) { foo <- NULL for (i in 1: number_of_activity_ranges) { foo <- c(foo, c(paste(names_activity_ranges[i], '(', round(100 * rel_freq_acitvity_range[i], digits = 2), "%", ')'))) } } else { foo <- NULL for (i in 1: number_of_activity_ranges) { foo <- c(foo, c(paste(i, '(', round(100 * rel_freq_acitvity_range[i], digits=2), "%",')'))) } } if (any(!is.na(hidden_PA_levels))) { barplot(rel_freq_acitvity_range, main = c("fragmentation into acitvity ranges (HMM)"), xlab = "activity range", ylab = "relative frequency", names.arg = foo) } else { barplot(rel_freq_acitvity_range, main = c("fragmentation into acitvity ranges"), xlab = "activity range", ylab = "relative frequency", names.arg = foo) } if (any(!is.na(hidden_PA_levels))) { plot(x, ylim = c(0, max(x) + max(x) * 0.1), main = c(" } else { plot(x, ylim = c(0, max(x) + max(x) * 0.1), main = c(" } points(bout_extraction$for_plotting_a, col = "black", type="h") points(bout_extraction$for_plotting_a, col = "black", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_a, col = "black", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_a, col = "black", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_a, col = "black", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") if (any(!is.na(hidden_PA_levels))) { points(hidden_PA_levels, col = "green", type = "l") } abline(h = cut_points[c(-1)], col = "grey50", lty = "dashed") if (any(!is.na(hidden_PA_levels))) { barplot(ylab = ("abs. frequency"), xlab = c("length of bout [epoch period]"), ylim = c(0, max(abs_freq_bouts_el[[1]])), abs_freq_bouts_el[[1]], names.arg = names, main = "bouts in relation to their length (HMM)") } else { barplot(ylab = ("abs. frequency"), xlab = c("length of bout [epoch period]"), ylim = c(0, max(abs_freq_bouts_el[[1]])), abs_freq_bouts_el[[1]], names.arg = names, main = "bouts in relation to their length") } par(mfrow = c(1,1)) if (any(!is.na(hidden_PA_levels))) { plot(x, main = "classification (HMM)", xlab = "time", ylab = "counts", col = "white") } else { plot(x, main = "classification", xlab = "time", ylab = "counts", col = "white") } abline(h = cut_points[c(-1)], col = "grey50", lty = "dashed") for (i in 1: number_of_activity_ranges) { points(as.numeric(classification_per_activity_range[[i]]), col = i) } par(mfrow = c(1,1)) if (any(!is.na(hidden_PA_levels))) { plot(x, ylim = c(0, max(x) + max(x) * 0.1), main = c(" } else { plot(x, ylim = c(0, max(x) + max(x) * 0.1), main = c(" } points(bout_extraction$for_plotting_a, col = "black", type="h") points(bout_extraction$for_plotting_a, col = "black", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_a, col = "black", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_a, col = "black", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_a, col = "black", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") if (any(!is.na(hidden_PA_levels))) { points(hidden_PA_levels, col = "green", type = "l") } abline(h = cut_points[c(-1)], col = "grey50", lty = "dashed") par(mfrow = c(2,1)) if (all(!is.na(names_activity_ranges))) { foo <- NULL for (i in 1: number_of_activity_ranges) { foo <- c(foo, c(paste(names_activity_ranges[i] , '(', round(100 * rel_freq_acitvity_range[i], digits=2), "%", ')'))) } } else { foo <- NULL for (i in 1: number_of_activity_ranges) { foo <- c(foo, c(paste(i , '(', round(100 * rel_freq_acitvity_range[i], digits=2), "%", ')'))) } } if (any(!is.na(hidden_PA_levels))) { barplot(rel_freq_acitvity_range, main = c("fragmentation into acitvity ranges (HMM)"), xlab = "activity range", ylab = "relative frequency", names.arg = foo) } else { barplot(rel_freq_acitvity_range, main = c("fragmentation into acitvity ranges"), xlab = "activity range", ylab = "relative frequency", names.arg = foo) } if (all(!is.na(names_activity_ranges))) { foo <- NULL for (i in 1: number_of_activity_ranges) { foo <- c(foo, c(paste(names_activity_ranges[i] , '( } } else { foo <- NULL for (i in 1: number_of_activity_ranges) { foo <- c(foo, c(paste(i , '( } } if (any(!is.na(hidden_PA_levels))) { barplot(freq_acitvity_range, main = c("fragmentation into acitvity ranges (HMM)"), xlab = "activity range", ylab = "absolute frequency", names.arg = foo) } else { barplot(freq_acitvity_range, main = c("fragmentation into acitvity ranges"), xlab = "activity range", ylab = "absolute frequency", names.arg = foo) } par(mfrow = c(number_of_activity_ranges / 2 + 1, 2)) for (i in 1:(number_of_activity_ranges + 1)) { if (any(!is.na(hidden_PA_levels))) { barplot(ylab = ("abs. frequency"), xlab = c("length of bout [epoch period]"), ylim = c(0, max(abs_freq_bouts_el[[1]])), abs_freq_bouts_el[[i]], names.arg = names, main = "bouts in relation to their length (HMM)") } else { barplot(ylab = ("abs. frequency"), xlab = c("length of bout [epoch period]"), ylim = c(0, max(abs_freq_bouts_el[[1]])), abs_freq_bouts_el[[i]], names.arg = names, main = "bouts in relation to their length") } if (all(!is.na(names_activity_ranges))) { legend("topright", bg = "white", c("all", names_activity_ranges)[i], fill = c("gray")) } else { legend("topright", bg = "white", c("all",seq(1, number_of_activity_ranges))[i], fill = c("gray")) } } par(mfrow = c(1,1)) } if (plotting == 1) { par(mfrow = c(2,2)) if (any(!is.na(hidden_PA_levels))) { plot(x, main = "classification (HMM)", xlab = "time", ylab = "counts", col = "white") } else { plot(x, main = "classification", xlab = "time", ylab = "counts", col = "white") } abline(h = cut_points[c(-1)], col = "grey50", lty = "dashed") for (i in 1: number_of_activity_ranges) { points(as.numeric(classification_per_activity_range[[i]]), col = i) } if (all(!is.na(names_activity_ranges))) { foo <- NULL for (i in 1: number_of_activity_ranges) { foo <- c(foo, c(paste(names_activity_ranges[i] , '(', round( 100* rel_freq_acitvity_range[i], digits = 2), "%", ')'))) } } else { foo <- NULL for (i in 1: number_of_activity_ranges) { foo <- c(foo, c(paste(i , '(', round( 100* rel_freq_acitvity_range[i], digits = 2), "%", ')'))) } } if (any(!is.na(hidden_PA_levels))) { barplot(rel_freq_acitvity_range, main = c("fragmentation into acitvity ranges (HMM)"), xlab = "activity range", ylab = "relative frequency", names.arg = foo) } else { barplot(rel_freq_acitvity_range, main = c("fragmentation into acitvity ranges"), xlab = "activity range", ylab = "relative frequency", names.arg = foo) } if (any(!is.na(hidden_PA_levels))) { plot(x, main = c(" } else { plot(x, main = c(" } points(bout_extraction$for_plotting_a, col = "black", type="h") points(bout_extraction$for_plotting_a, col = "black", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_a, col = "black", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_a, col = "black", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_a, col = "black", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") if (any(!is.na(hidden_PA_levels))) { points(hidden_PA_levels, col = "green", type = "l") } abline(h = cut_points[c(-1)], col = "grey50", lty = "dashed") if (any(!is.na(hidden_PA_levels))) { barplot(ylab = ("abs. frequency"), xlab = c("length of bout [epoch period]"), ylim = c(0, max(abs_freq_bouts_el[[1]])), abs_freq_bouts_el[[1]], names.arg = names, main = "bouts in relation to their length (HMM)") } else { barplot(ylab = ("abs. frequency"), xlab = c("length of bout [epoch period]"), ylim = c(0, max(abs_freq_bouts_el[[1]])), abs_freq_bouts_el[[1]], names.arg = names, main = "bouts in relation to their length") } par(mfrow = c(1,1)) } if (plotting == 2) { par(mfrow = c(1,1)) if (any(!is.na(hidden_PA_levels))) { plot(x, main = "classification (HMM)", xlab = "time", ylab = "counts", col = "white") } else { plot(x, main = "classification", xlab = "time", ylab = "counts", col = "white") } abline(h = cut_points[c(-1)], col = "grey50", lty = "dashed") for (i in 1: number_of_activity_ranges) { points(as.numeric(classification_per_activity_range[[i]]), col = i) } } if (plotting == 3) { par(mfrow = c(1,1)) if (any(!is.na(hidden_PA_levels))) { plot(x, ylim = c(0, max(x) + max(x) * 0.1), main = c(" } else { plot(x, ylim = c(0, max(x) + max(x) * 0.1), main = c(" } points(bout_extraction$for_plotting_a, col = "black", type="h") points(bout_extraction$for_plotting_a, col = "black", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_a, col = "black", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_a, col = "black", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_a, col = "black", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") points(bout_extraction$for_plotting_b, col = "white", type="h") if (any(!is.na(hidden_PA_levels))) { points(hidden_PA_levels, col = "green", type = "l") } abline(h = cut_points[c(-1)], col = "grey50", lty = "dashed") } if (plotting == 4) { par(mfrow = c(2,1)) if (all(!is.na(names_activity_ranges))) { foo <- NULL for (i in 1: number_of_activity_ranges) { foo <- c(foo, c(paste(names_activity_ranges[i] , '(', round( 100* rel_freq_acitvity_range[i], digits = 2), "%", ')'))) } } else { foo <- NULL for (i in 1: number_of_activity_ranges) { foo <- c(foo, c(paste(i , '(', round( 100* rel_freq_acitvity_range[i], digits = 2), "%", ')'))) } } if (any(!is.na(hidden_PA_levels))) { barplot(rel_freq_acitvity_range, main = c("fragmentation into acitvity ranges (HMM)"), xlab = "activity range", ylab = "relative frequency", names.arg = foo) } else { barplot(rel_freq_acitvity_range, main = c("fragmentation into acitvity ranges"), xlab = "activity range", ylab = "relative frequency", names.arg = foo) } if (all(!is.na(names_activity_ranges))) { foo <- NULL for (i in 1: number_of_activity_ranges) { foo <- c(foo, c(paste(names_activity_ranges[i] ,'( } } else { foo <- NULL for (i in 1: number_of_activity_ranges) { foo <- c(foo, c(paste(i ,'( } } if (any(!is.na(hidden_PA_levels))) { barplot(freq_acitvity_range, main = c("fragmentation into acitvity ranges (HMM)"), xlab = "activity range", ylab = "absolute frequency", names.arg = foo) } else { barplot(freq_acitvity_range, main = c("fragmentation into acitvity ranges"), xlab = "activity range", ylab = "absolute frequency", names.arg = foo) } par(mfrow = c(1,1)) } if (plotting == 5) { par(mfrow = c(number_of_activity_ranges/2+1,2)) for (i in 1:(number_of_activity_ranges+1)) { if (any(!is.na(hidden_PA_levels))) { barplot(ylab = ("abs. frequency"), xlab = c("length of bout [epoch period]"), ylim = c(0, max(abs_freq_bouts_el[[1]])), abs_freq_bouts_el[[i]], names.arg = names, main = "bouts in relation to their length (HMM)") } else { barplot(ylab = ("abs. frequency"), xlab = c("length of bout [epoch period]"), ylim = c(0, max(abs_freq_bouts_el[[1]])), abs_freq_bouts_el[[i]], names.arg = names, main = "bouts in relation to their length") } if (all(!is.na(names_activity_ranges))) { legend("topright", bg = "white", c("all",names_activity_ranges)[i], fill =c("gray")) } else { legend("topright", bg = "white", c("all",seq(1, number_of_activity_ranges))[i], fill =c("gray")) } } par(mfrow = c(1,1)) } } print(list(activity_ranges = activity_ranges, classification = classification, rel_freq_acitvity_range = rel_freq_acitvity_range, quantity_of_bouts = quantity_of_bouts, abs_freq_bouts_el = abs_freq_bouts_el$all_activity_ranges)) return(list(activity_ranges = activity_ranges, classification = classification, classification_per_activity_range = classification_per_activity_range, freq_acitvity_range = freq_acitvity_range, rel_freq_acitvity_range = rel_freq_acitvity_range, quantity_of_bouts = quantity_of_bouts, bout_periods = bout_periods, abs_freq_bouts_el = abs_freq_bouts_el)) }
context("test build.panel") n=1000 attr = 7 my.dir = system.file(package = "psidR","testdata") load(file.path(my.dir,"FAM1985ER.rda")) load(file.path(my.dir,"FAM1986ER.RData")) load(file.path(my.dir,"IND2017ER.RData")) test_that("check balanced sample design", { famvars <- data.frame(year=c(1985,1986),money=c("Money85","Money86"),age=c("age85","age86")) indvars <- data.frame(year=c(1985,1986),ind.weight=c("ER30497","ER30534")) d <- build.panel(datadir=my.dir,fam.vars=famvars,ind.vars=indvars,sample=NULL,heads.only=FALSE,design="all",loglevel=DEBUG) dd = d attrited <- subset(IND2017ER,(ER30463!=0) & (ER30498 == 0) ) attrited$pernum <- attrited$ER30001*1000 + attrited$ER30002 expect_true(nrow(attrited) == attr) expect_true(dd[pid %in% attrited$pernum,unique(year)] == 1985) dd = dd[!(pid %in% attrited$pernum)] setkey(dd,pid,year) expect_true( all( dd[,list(dage=diff(age)),by=pid][,dage] == 1 )) setkey(dd,pid,year) expect_true( all( dd[,list(dage=diff(year)),by=pid][,dage] == 1 )) d <- build.panel(datadir=my.dir,fam.vars=famvars,ind.vars=indvars,sample=NULL,heads.only=FALSE,design="balanced") dd = d expect_true(any(dd[,pid] %in% attrited$pernum) == FALSE) expect_true( "relation.head" %in% names(dd) ) expect_true( !all( dd[,sequence == 1])) expect_true( !all( dd[,relation.head == 10])) } ) test_that("check subsetting to head and wife sample", { famvars <- data.frame(year=c(1985,1986),money=c("Money85","Money86"),age=c("age85","age86")) indvars <- data.frame(year=c(1985,1986),ind.weight=c("ER30497","ER30534")) core <- build.panel(datadir=my.dir,fam.vars=famvars,ind.vars=indvars,sample=NULL,heads.only=TRUE,design="all") cored = core expect_true( all( cored[,(sequence >0) & (sequence < 21) ])) expect_true( all( cored[,relation.head == 10])) }) test_that("check subsetting to current heads only", { famvars <- data.frame(year=c(1985,1986),money=c("Money85","Money86"),age=c("age85","age86")) indvars <- data.frame(year=c(1985,1986),ind.weight=c("ER30497","ER30534")) core <- build.panel(datadir=my.dir,fam.vars=famvars,ind.vars=indvars,sample=NULL,current.heads.only=TRUE,design="all") cored = core expect_true( all( cored[,sequence==1])) expect_true( all( cored[,relation.head == 10])) }) test_that("check subsetting to core/immigrant/latino", { famvars <- data.frame(year=c(1985,1986),money=c("Money85","Money86"),age=c("age85","age86")) indvars <- data.frame(year=c(1985,1986),ind.weight=c("ER30497","ER30534")) src <- build.panel(datadir=my.dir,fam.vars=famvars,ind.vars=indvars,sample="SRC",heads.only=FALSE,design="all") seo <- build.panel(datadir=my.dir,fam.vars=famvars,ind.vars=indvars,sample="SEO",heads.only=FALSE,design="all") lat <- build.panel(datadir=my.dir,fam.vars=famvars,ind.vars=indvars,sample="latino",heads.only=FALSE,design="all") imm <- build.panel(datadir=my.dir,fam.vars=famvars,ind.vars=indvars,sample="immigrant",heads.only=FALSE,design="all") expect_true( all( src[,ID1968 < 3000 ])) expect_true( all( seo[,ID1968 > 5000 & ID1968 < 7000 ])) expect_true( all( lat[,ID1968 > 7000 & ID1968 < 9308])) expect_true( all( imm[,ID1968 > 3000 & ID1968 < 7000 ])) } )
pxweb_api_name <- function(x){ UseMethod("pxweb_api_name") } pxweb_api_name.url <- function(x){ checkmate::assert_class(x, "url") x <- x$hostname assert_path(x) x } pxweb_api_name.pxweb <- function(x){ pxweb_api_name(x$url) } pxweb_api_name.pxweb_api_catalogue_entry <- function(x){ pxweb_api_name(httr::parse_url(x$url)) } pxweb_api_name.pxweb_explorer <- function(x){ if(is.null(x$pxweb)){ return("") } pxweb_api_name(x$pxweb) } pxweb_api_rootpath <- function(x){ UseMethod("pxweb_api_rootpath") } pxweb_api_rootpath.url <- function(x){ checkmate::assert_class(x, "url") x$path <- "" p <- build_pxweb_url(x) p <- gsub(pattern = "/$", replacement = "", p) assert_path(p) p } pxweb_api_rootpath.pxweb <- function(x){ checkmate::assert_class(x, "pxweb") pxweb_api_rootpath(x$url) } pxweb_api_rootpath.pxweb_explorer <- function(x){ checkmate::assert_class(x, "pxweb_explorer") pxweb_api_rootpath(x$pxweb) } pxweb_api_subpath <- function(x, init_slash = TRUE, as_vector = FALSE){ checkmate::assert_flag(init_slash) checkmate::assert_flag(as_vector) UseMethod("pxweb_api_subpath") } pxweb_api_subpath.pxweb <- function(x, init_slash = TRUE, as_vector = FALSE){ if(as_vector) { return(x$paths$api_subpath$vector) } if(init_slash) { p <- paste0("/", x$paths$api_subpath$path) } else { p <- x$paths$api_subpath$path } p <- gsub(pattern = "/$", replacement = "", p) assert_path(p) p } pxweb_api_subpath.pxweb_explorer <- function(x, init_slash = TRUE, as_vector = FALSE){ if(is.null(x$pxweb)){ return("") } pxweb_api_subpath(x$pxweb, init_slash, as_vector) } pxweb_api_path <- function(x, init_slash = TRUE, as_vector = FALSE){ checkmate::assert_flag(init_slash) checkmate::assert_flag(as_vector) UseMethod("pxweb_api_path") } pxweb_api_path.url <- function(x, init_slash = TRUE, as_vector = FALSE){ p <- x$path p <- gsub(pattern = "/$", replacement = "", p) if(as_vector) { return(strsplit(p, "/")[[1]]) } if(init_slash) { p <- paste0("/", p) } assert_path(p) p } pxweb_api_path.pxweb <- function(x, init_slash = TRUE, as_vector = FALSE){ pxweb_api_path(x$url, init_slash, as_vector) } pxweb_api_path.pxweb_explorer <- function(x, init_slash = TRUE, as_vector = FALSE){ pxweb_api_path(x$pxweb, init_slash, as_vector) } pxweb_api_dbpath <- function(x, init_slash = TRUE, as_vector = FALSE){ checkmate::assert_flag(init_slash) checkmate::assert_flag(as_vector) UseMethod("pxweb_api_dbpath") } pxweb_api_dbpath.pxweb <- function(x, init_slash = TRUE, as_vector = FALSE){ p1 <- pxweb_api_subpath(x, as_vector = TRUE) p2 <- pxweb_api_path(x, as_vector = TRUE) checkmate::assert_set_equal(p1, p2[1:length(p1)]) pv <- p2[(length(p1)+1):length(p2)] if(as_vector) { return(pv) } p <- paste(pv, collapse = "/") p <- gsub(pattern = "/$", replacement = "", p) if(init_slash) { p <- paste0("/", p) } assert_path(p) p } pxweb_api_path.pxweb_explorer <- function(x, init_slash = TRUE, as_vector = FALSE){ pxweb_api_path(x$pxweb, init_slash, as_vector) } assert_path <- function(x){ checkmate::assert_string(x) }
node.keep <- function(x, keep.list, clist) { if (!is.null(clist)) { tmp <- unlist(lapply(clist, node.parent)) } if (!x@path %in% keep.list & (x@leaf | (!is.null(clist) && !x@path %in% tmp))) { x@pruned[] <- TRUE } return(x) } node.parent <- function(x, segmented=FALSE) { if (x@order==1) { parent <- "e" } else { parent <- unlist(strsplit(x@path,"-")) parent <- parent[2:length(parent)] parent <- paste(parent, collapse="-") } if (segmented) { parent <- cbind(parent, group=rownames(x@prob)) } return(parent) } node.gain <- function(x, plist, gain, C, clist) { parent <- plist[[node.parent(x)]] if (!is.null(clist)) { tmp <- unlist(lapply(clist, node.parent)) children <- clist[which(tmp==x@path)] if (length(children)>0) { children <- unlist(lapply(children, function(x) rownames(x@prob))) } } else { children <- NULL } glist <- rownames(x@prob) for (n in 1:nrow(x@prob)) { if (!x@pruned[n] & (x@leaf[n] || (!is.null(clist) & !glist[n] %in% children))) { x@pruned[n] <- !do.call(gain, args=list(p1=x@prob[n,], p2=parent@prob[glist[n],], N=x@n[n], C=C)) } } return(x) } node.prune <- function(x) { x@pruned[] <- TRUE return(x) } node.nmin <- function(x,nmin) { x@pruned <- x@n < nmin return(x) } node.leaf <- function(x) { x@leaf[] <- TRUE return(x) } is.leaf <- function(x) { return(x@leaf) } is.pruned <- function(x) { return(x@pruned) } delete.pruned <- function(x) { if (any(x@pruned)) { idxnp <- !x@pruned x@index <- x@index[idxnp,, drop=FALSE] x@prob <- x@prob[idxnp,, drop=FALSE] x@counts <- x@counts[idxnp,, drop=FALSE] x@pruned <- x@pruned[idxnp,,drop=FALSE] x@leaf <- x@leaf[idxnp,,drop=FALSE] x@n <- x@n[idxnp,,drop=FALSE] } return(x) } select.segment <- function(x, group, position) { select <- matrix(FALSE, nrow=nrow(x@index), ncol=ncol(x@index), dimnames=dimnames(x@index)) if (!is.null(group)) { idx.group <- which(x@index[,"group"]==group) select[idx.group,"group"] <- TRUE } else { select[,"group"] <- TRUE } if (!is.null(position)) { idx.pos <- which(x@index[, "position"]==position) select[idx.pos,"position"] <- TRUE } else { select[,"position"] <- TRUE } idx <- which(rowSums(select)==2) if (length(idx)>0) { x@index <- x@index[idx,,drop=FALSE] x@prob <- x@prob[idx,, drop=FALSE] x@counts <- x@counts[idx,, drop=FALSE] x@pruned <- x@pruned[idx,, drop=FALSE] x@leaf <- x@leaf[idx,, drop=FALSE] x@n <- x@n[idx,, drop=FALSE] } else { x <- NULL } return(x) } node.mine <- function(x, pmin, pmax, state) { if (!missing(pmin)) { tmp <- rowSums(x@prob[, state, drop=FALSE]) >= pmin } else if (!missing(pmax)) { tmp <- rowSums(x@prob[, state, drop=FALSE]) < pmax } if (sum(tmp)>0) { res <- new("cprobd", x@prob[tmp, , drop=FALSE], context=x@path) } else { res <- NULL } return(res) } node.merge <- function(x, y, segmented) { if (segmented) { x@prob <- rbind(x@prob, y@prob) x@counts <- rbind(x@counts, y@counts) x@n <- c(x@n, y@n) x@pruned <- c(x@pruned, y@pruned) x@leaf <- c(x@leaf, y@leaf) } else { x@counts <- rbind(x@prob, y@counts) x@prob <- x@counts/sum(x@counts) x@n <- x@n+y@n x@pruned <- x@pruned & y@pruned x@leaf <- x@leaf & y@leaf } return(x) } set.leaves <- function(x, clist, cplist) { child <- which(x@path==cplist) pchild <- unique(as.vector(unlist(clist[child]))) leaves <- !rownames(x@leaf) %in% pchild if (sum(leaves)>0) { x@leaf[leaves] <- TRUE } return(x) } which.child <- function(PST) { class <- class(PST) child.list <- names(PST)[unlist(lapply(PST, is, class))] return(child.list) }
"dat.gatb"
convert <- function(x, ...) { if ((!is.null(attr(x, "class"))) && (attr(x, "class") == "aquaenv")) { return(convert.aquaenv(x, ...)) } else { return(convert.standard(x, ...)) } } aquaenv <- function(S, t, p=pmax((P-Pa), gauge_p(d, lat, Pa)), P=Pa, Pa=1.01325, d=0, lat=0, SumCO2=0, SumNH4=0, SumH2S=0, SumH3PO4=0, SumSiOH4=0, SumHNO3=0, SumHNO2=0, SumBOH3=NULL, SumH2SO4=NULL, SumHF=NULL, TA=NULL, pH=NULL, fCO2=NULL, CO2=NULL, speciation=TRUE, dsa=FALSE, ae=NULL, from.data.frame=FALSE, SumH2SO4_Koffset=0, SumHF_Koffset=0, revelle=FALSE, skeleton=FALSE, k_w=NULL, k_co2=NULL, k_hco3=NULL, k_boh3=NULL, k_hso4=NULL, k_hf=NULL, k1k2="lueker", khf="dickson", khso4="dickson", fCO2atm=0.000400, fO2atm=0.20946) { if (from.data.frame) { return (from.data.frame(ae)) } else if (!is.null(ae)) { return (cloneaquaenv(ae, TA=TA, pH=pH, k_co2=k_co2, k1k2=k1k2, khf=khf, khso4=khso4)) } else { aquaenv <- list() attr(aquaenv, "class") <- "aquaenv" aquaenv[["S"]] <- S ; attr(aquaenv[["S"]], "unit") <- "p2su" aquaenv[["t"]] <- t ; attr(aquaenv[["t"]], "unit") <- "deg C" aquaenv[["p"]] <- p ; attr(aquaenv[["p"]], "unit") <- "bar" aquaenv[["T"]] <- T(t) ; attr(aquaenv[["T"]], "unit") <- "deg K" aquaenv[["Cl"]] <- Cl(S) ; attr(aquaenv[["Cl"]], "unit") <- "permil" aquaenv[["I"]] <- I(S) ; attr(aquaenv[["I"]], "unit") <- "mol/kg-H2O" aquaenv[["P"]] <- p+Pa ; attr(aquaenv[["P"]], "unit") <- "bar" aquaenv[["Pa"]] <- Pa ; attr(aquaenv[["Pa"]], "unit") <- "bar" aquaenv[["d"]] <- round(watdepth(P=p+Pa, lat=lat),2) ; attr(aquaenv[["d"]], "unit") <- "m" aquaenv[["density"]] <- seadensity(S=S, t=t) ; attr(aquaenv[["density"]], "unit") <- "kg/m3" aquaenv[["SumCO2"]] <- SumCO2 aquaenv[["SumNH4"]] <- SumNH4 ; attr(aquaenv[["SumNH4"]], "unit") <- "mol/kg-soln" aquaenv[["SumH2S"]] <- SumH2S ; attr(aquaenv[["SumH2S"]], "unit") <- "mol/kg-soln" aquaenv[["SumHNO3"]] <- SumHNO3 ; attr(aquaenv[["SumHNO3"]], "unit") <- "mol/kg-soln" aquaenv[["SumHNO2"]] <- SumHNO2 ; attr(aquaenv[["SumHNO2"]], "unit") <- "mol/kg-soln" aquaenv[["SumH3PO4"]] <- SumH3PO4 ; attr(aquaenv[["SumH3PO4"]], "unit") <- "mol/kg-soln" aquaenv[["SumSiOH4"]] <- SumSiOH4 ; attr(aquaenv[["SumSiOH4"]], "unit") <- "mol/kg-soln" if (is.null(SumBOH3)) { SumBOH3 = seaconc("B", S) } else if (length(S)>1) { SumBOH3 = rep(SumBOH3, length(S)) } aquaenv[["SumBOH3"]] <- SumBOH3 ; attr(aquaenv[["SumBOH3"]], "unit") <- "mol/kg-soln" if (is.null(SumH2SO4)) { SumH2SO4 = seaconc("SO4", S) } else if (length(S)>1) { SumH2SO4 = rep(SumH2SO4, length(S)) } aquaenv[["SumH2SO4"]] <- SumH2SO4 ; attr(aquaenv[["SumH2SO4"]], "unit") <- "mol/kg-soln" if (is.null(SumHF)) { SumHF = seaconc("F", S) } else if (length(S)>1) { SumHF = rep(SumHF, length(S)) } aquaenv[["SumHF"]] <- SumHF ; attr(aquaenv[["SumHF"]], "unit") <- "mol/kg-soln" if(!skeleton) { aquaenv[["Br"]] <- seaconc("Br", S) ; attr(aquaenv[["Br"]], "unit") <- "mol/kg-soln" aquaenv[["ClConc"]] <- seaconc("Cl", S) ; attr(aquaenv[["ClConc"]], "unit") <- "mol/kg-soln" aquaenv[["Na"]] <- seaconc("Na", S) ; attr(aquaenv[["Na"]], "unit") <- "mol/kg-soln" aquaenv[["Mg"]] <- seaconc("Mg", S) ; attr(aquaenv[["Mg"]], "unit") <- "mol/kg-soln" aquaenv[["Ca"]] <- seaconc("Ca", S) ; attr(aquaenv[["Ca"]], "unit") <- "mol/kg-soln" aquaenv[["K"]] <- seaconc("K", S) ; attr(aquaenv[["K"]], "unit") <- "mol/kg-soln" aquaenv[["Sr"]] <- seaconc("Sr", S) ; attr(aquaenv[["Sr"]], "unit") <- "mol/kg-soln" aquaenv[["molal2molin"]] <- molal2molin(S) ; attr(aquaenv[["molal2molin"]], "unit") <- "(mol/kg-soln)/(mol/kg-H2O)" scaleconvs <- scaleconvert(S, t, p, SumH2SO4, SumHF, khf=khf, khso4=khso4) aquaenv[["free2tot"]] <- scaleconvs$free2tot ; attr(aquaenv[["free2tot"]], "pH scale") <- "free -> tot" aquaenv[["free2sws"]] <- scaleconvs$free2sws ; attr(aquaenv[["free2sws"]], "pH scale") <- "free -> sws" aquaenv[["tot2free"]] <- scaleconvs$tot2free ; attr(aquaenv[["tot2free"]], "pH scale") <- "total -> free" aquaenv[["tot2sws"]] <- scaleconvs$tot2sws ; attr(aquaenv[["tot2sws"]], "pH scale") <- "total -> sws" aquaenv[["sws2free"]] <- scaleconvs$sws2free ; attr(aquaenv[["sws2free"]], "pH scale") <- "sws -> free" aquaenv[["sws2tot"]] <- scaleconvs$sws2tot ; attr(aquaenv[["sws2tot"]], "pH scale") <- "sws -> total" aquaenv[["K0_CO2"]] <- K0_CO2 (S, t) aquaenv[["K0_O2"]] <- K0_O2 (S, t) aquaenv[["fCO2atm"]] <- fCO2atm ; attr(aquaenv[["fCO2atm"]], "unit") <- "atm" aquaenv[["fO2atm"]] <- fO2atm ; attr(aquaenv[["fO2atm"]], "unit") <- "atm" aquaenv[["CO2_sat"]] <- aquaenv[["fCO2atm"]] * aquaenv[["K0_CO2"]] ; attr(aquaenv[["CO2_sat"]], "unit") <- "mol/kg-soln" aquaenv[["O2_sat"]] <- aquaenv[["fO2atm"]] * aquaenv[["K0_O2"]] ; attr(aquaenv[["O2_sat"]], "unit") <- "mol/kg-soln" } len <- max(length(t), length(S), length(p)) if (is.null(k_w)) { aquaenv[["K_W"]] <- K_W(S, t, p, SumH2SO4 + SumH2SO4_Koffset, SumHF + SumHF_Koffset, khf=khf, khso4=khso4) } else { aquaenv[["K_W"]] <- eval(att(rep(k_w,len))) } if (is.null(k_hso4)) { aquaenv[["K_HSO4"]] <- K_HSO4(S, t, p, khso4) } else { aquaenv[["K_HSO4"]] <- eval(att(rep(k_hso4,len))) } if (is.null(k_hf)) { aquaenv[["K_HF"]] <- K_HF(S, t, p, SumH2SO4=(SumH2SO4 + SumH2SO4_Koffset), SumHF=(SumHF + SumHF_Koffset), khf=khf, khso4=khso4) } else { aquaenv[["K_HF"]] <- eval(att(rep(k_hf,len))) } if (is.null(k_co2)) { aquaenv[["K_CO2"]] <- K_CO2 (S, t, p, SumH2SO4 + SumH2SO4_Koffset, SumHF + SumHF_Koffset, k1k2=k1k2, khf=khf, khso4=khso4) } else { aquaenv[["K_CO2"]] <- eval(att(rep(k_co2,len))) } if (is.null(k_hco3)) { aquaenv[["K_HCO3"]] <- K_HCO3(S, t, p, SumH2SO4 + SumH2SO4_Koffset, SumHF + SumHF_Koffset, k1k2=k1k2, khf=khf, khso4=khso4) } else { aquaenv[["K_HCO3"]] <- eval(att(rep(k_hco3,len))) } if (is.null(k_boh3)) { aquaenv[["K_BOH3"]] <- K_BOH3(S, t, p, SumH2SO4 + SumH2SO4_Koffset, SumHF + SumHF_Koffset, khf=khf, khso4=khso4) } else { aquaenv[["K_BOH3"]] <- eval(att(rep(k_boh3,len))) } aquaenv[["K_NH4"]] <- K_NH4 (S, t, p, SumH2SO4 + SumH2SO4_Koffset, SumHF + SumHF_Koffset, khf=khf, khso4=khso4) aquaenv[["K_H2S"]] <- K_H2S (S, t, p, SumH2SO4 + SumH2SO4_Koffset, SumHF + SumHF_Koffset, khf=khf, khso4=khso4) aquaenv[["K_H3PO4"]] <- K_H3PO4 (S, t, p, SumH2SO4 + SumH2SO4_Koffset, SumHF + SumHF_Koffset, khf=khf, khso4=khso4) aquaenv[["K_H2PO4"]] <- K_H2PO4 (S, t, p, SumH2SO4 + SumH2SO4_Koffset, SumHF + SumHF_Koffset, khf=khf, khso4=khso4) aquaenv[["K_HPO4"]] <- K_HPO4 (S, t, p, SumH2SO4 + SumH2SO4_Koffset, SumHF + SumHF_Koffset, khf=khf, khso4=khso4) aquaenv[["K_SiOH4"]] <- K_SiOH4 (S, t, p, SumH2SO4 + SumH2SO4_Koffset, SumHF + SumHF_Koffset, khf=khf, khso4=khso4) aquaenv[["K_SiOOH3"]] <- K_SiOOH3(S, t, p, SumH2SO4 + SumH2SO4_Koffset, SumHF + SumHF_Koffset, khf=khf, khso4=khso4) aquaenv[["K_HNO2"]] <- PhysChemConst$K_HNO2 ; attr(aquaenv[["K_HNO2"]], "unit") <- "mol/kg-soln; mol/kg-H2O; mol/l" aquaenv[["K_HNO3"]] <- PhysChemConst$K_HNO3 ; attr(aquaenv[["K_HNO3"]], "unit") <- "mol/kg-soln; mol/kg-H2O; mol/l" aquaenv[["K_H2SO4"]] <- PhysChemConst$K_H2SO4 ; attr(aquaenv[["K_H2SO4"]], "unit") <- "mol/kg-soln; mol/kg-H2O; mol/l" aquaenv[["K_HS"]] <- PhysChemConst$K_HS ; attr(aquaenv[["K_HS"]], "unit") <- "mol/kg-soln; mol/kg-H2O; mol/l" if (!skeleton) { aquaenv[["Ksp_calcite"]] <- Ksp_calcite(S, t, p) aquaenv[["Ksp_aragonite"]] <- Ksp_aragonite(S, t, p) } if (!(is.null(TA) && is.null(pH) && is.null(fCO2) && is.null(CO2))) { if (is.null(SumCO2)) { if (!is.null(pH)) { if (!is.null(fCO2)) { CO2 <- aquaenv[["K0_CO2"]] * fCO2 SumCO2 <- calcSumCO2_pH_CO2(aquaenv, pH, CO2) TA <- calcTA(c(aquaenv, list(SumCO2, "SumCO2")), 10^(-pH)) } else if (!is.null(CO2)) { SumCO2 <- calcSumCO2_pH_CO2(aquaenv, pH, CO2) fCO2 <- CO2 / aquaenv[["K0_CO2"]] TA <- calcTA(c(aquaenv, list(SumCO2, "SumCO2")), 10^(-pH)) } else if (!is.null(TA)) { SumCO2 <- calcSumCO2_pH_TA(aquaenv, pH, TA) CO2 <- H2Abi(SumCO2, aquaenv[["K_CO2"]], aquaenv[["K_HCO3"]], 10^(-pH)) fCO2 <- CO2 / aquaenv[["K0_CO2"]] } else { print(paste("Error! Underdetermined system!")) print("To calculate [SumCO2], please enter one pair of: (pH/CO2), (pH,fCO2), (TA,pH), (TA/CO2), (TA/fCO2)") return(NULL) } } else if (!is.null(TA)) { if (!is.null(fCO2)) { CO2 <- aquaenv[["K0_CO2"]] * fCO2 SumCO2 <- calcSumCO2_TA_CO2(aquaenv, TA, CO2) pH <- -log10(calcH_TA(c(aquaenv, list(SumCO2, "SumCO2")), TA)) } else if (!is.null(CO2)) { SumCO2 <- calcSumCO2_TA_CO2(aquaenv, TA, CO2) fCO2 <- CO2 / aquaenv[["K0_CO2"]] pH <- -log10(calcH_TA(c(aquaenv, list(SumCO2, "SumCO2")), TA)) } else { print(paste("Error! Underdetermined system!")) print("To calculate [SumCO2], please enter one pair of: (pH/CO2), (pH,fCO2), (TA,pH), (TA/CO2), (TA/fCO2)") return(NULL) } } else { print(paste("Error! Underdetermined system!")) print("To calculate [SumCO2], please enter one pair of: (pH/CO2), (pH,fCO2), (TA,pH), (TA/CO2), (TA/fCO2)") return(NULL) } } else { if (is.null(fCO2) && is.null(CO2) && !is.null(pH) && !is.null(TA)) { TAcalc <- calcTA(aquaenv, 10^(-pH)) print(paste("Error! Overdetermined system: entered TA:", TA, ", calculated TA:", TAcalc)) print("Please enter only one of: pH, TA, CO2, or fCO2.") return(NULL) } if ((!is.null(pH) || !is.null(TA)) && (is.null(fCO2) && is.null(CO2))) { if (!is.null(pH)) { H <- 10^(-pH) TA <- calcTA(aquaenv, H) attributes(TA) <- NULL } else { pH <- -log10(calcH_TA(aquaenv, TA)) } CO2 <- H2Abi(SumCO2, aquaenv[["K_CO2"]], aquaenv[["K_HCO3"]], 10^(-pH)) attributes(CO2) <- NULL fCO2 <- CO2 / aquaenv[["K0_CO2"]] attributes(fCO2) <- NULL } else if (!is.null(fCO2) && !is.null(CO2) && is.null(pH) && is.null(TA)) { fCO2calc <- CO2 / aquaenv[["K0_CO2"]] print(paste("Error! Overdetermined system: entered fCO2:", fCO2, ", calculated fCO2:", fCO2calc)) print("Please enter only one of: pH, TA, CO2, or fCO2.") return(NULL) } else if ((!is.null(fCO2) || !is.null(CO2)) && (is.null(pH) && is.null(TA))) { if(!is.null(fCO2)) { CO2 <- aquaenv[["K0_CO2"]] * fCO2 attributes(CO2) <- NULL } else { fCO2 <- CO2 / aquaenv[["K0_CO2"]] attributes(fCO2) <- NULL } H <- calcH_CO2(aquaenv, CO2) TA <- calcTA(aquaenv, H) pH <- -log10(H) } else if ((!is.null(fCO2) || !is.null(CO2)) && !is.null(pH) && is.null(TA)) { if (!is.null(fCO2)) { CO2 <- aquaenv[["K0_CO2"]] * fCO2 } pHcalc <- -log10(calcH_CO2(aquaenv, CO2)) print(paste("Error! Overdetermined system: entered pH:", pH, ", calculated pH:", pHcalc)) print("Please enter only one of: pH, TA, CO2, or fCO2.") return(NULL) } else if ((!is.null(fCO2) || !is.null(CO2)) && is.null(pH) && !is.null(TA)) { if (!is.null(fCO2)) { CO2 <- aquaenv[["K0_CO2"]] * fCO2 } H <- calcH_CO2(aquaenv, CO2) TAcalc <- calcTA(aquaenv, H) print(paste("Error! Overdetermined system: entered TA:", TA, ", calculated TA:", TAcalc)) print("Please enter only one of: pH, TA, CO2, or fCO2.") return(NULL) } } aquaenv[["TA"]] <- TA ; attr(aquaenv[["TA"]], "unit") <- "mol/kg-soln" aquaenv[["pH"]] <- pH ; attr(aquaenv[["pH"]], "pH scale") <- "free" aquaenv[["SumCO2"]] <- SumCO2 ; attr(aquaenv[["SumCO2"]], "unit") <- "mol/kg-soln" aquaenv[["fCO2"]] <- fCO2 ; attr(aquaenv[["fCO2"]], "unit") <- "atm" aquaenv[["CO2"]] <- CO2 ; attr(aquaenv[["CO2"]], "unit") <- "mol/kg-soln" if (speciation) { H <- 10^(-pH) with (aquaenv, { aquaenv[["HCO3"]] <<- HAbi (SumCO2, K_CO2, K_HCO3, H) ; attr(aquaenv[["HCO3"]], "unit") <<- "mol/kg-soln" aquaenv[["CO3"]] <<- Abi (SumCO2, K_CO2, K_HCO3, H) ; attr(aquaenv[["CO3"]], "unit") <<- "mol/kg-soln" aquaenv[["BOH3"]] <<- HAuni (SumBOH3, K_BOH3, H) ; attr(aquaenv[["BOH3"]], "unit") <<- "mol/kg-soln" aquaenv[["BOH4"]] <<- Auni (SumBOH3, K_BOH3, H) ; attr(aquaenv[["BOH4"]], "unit") <<- "mol/kg-soln" aquaenv[["OH"]] <<- K_W / H ; attr(aquaenv[["OH"]], "unit") <<- "mol/kg-soln" aquaenv[["H3PO4"]] <<- H3Atri(SumH3PO4, K_H3PO4, K_H2PO4, K_HPO4, H) ; attr(aquaenv[["H3PO4"]], "unit") <<- "mol/kg-soln" aquaenv[["H2PO4"]] <<- H2Atri(SumH3PO4, K_H3PO4, K_H2PO4, K_HPO4, H) ; attr(aquaenv[["H2PO4"]], "unit") <<- "mol/kg-soln" aquaenv[["HPO4"]] <<- HAtri (SumH3PO4, K_H3PO4, K_H2PO4, K_HPO4, H) ; attr(aquaenv[["HPO4"]], "unit") <<- "mol/kg-soln" aquaenv[["PO4"]] <<- Atri (SumH3PO4, K_H3PO4, K_H2PO4, K_HPO4, H) ; attr(aquaenv[["PO4"]], "unit") <<- "mol/kg-soln" aquaenv[["SiOH4"]] <<- H2Abi (SumSiOH4, K_SiOH4, K_SiOOH3, H) ; attr(aquaenv[["SiOH4"]], "unit") <<- "mol/kg-soln" aquaenv[["SiOOH3"]] <<- HAbi (SumSiOH4, K_SiOH4, K_SiOOH3, H) ; attr(aquaenv[["SiOOH3"]], "unit") <<- "mol/kg-soln" aquaenv[["SiO2OH2"]]<<- Abi (SumSiOH4, K_SiOH4, K_SiOOH3, H) ; attr(aquaenv[["SiO2OH2"]], "unit") <<- "mol/kg-soln" aquaenv[["H2S"]] <<- H2Abi (SumH2S, K_H2S, K_HS, H) ; attr(aquaenv[["H2S"]], "unit") <<- "mol/kg-soln" aquaenv[["HS"]] <<- HAbi (SumH2S, K_H2S, K_HS, H) ; attr(aquaenv[["HS"]], "unit") <<- "mol/kg-soln" aquaenv[["S2min"]] <<- Abi (SumH2S, K_H2S, K_HS, H) ; attr(aquaenv[["S2min"]], "unit") <<- "mol/kg-soln" aquaenv[["NH4"]] <<- HAuni (SumNH4, K_NH4, H) ; attr(aquaenv[["NH4"]], "unit") <<- "mol/kg-soln" aquaenv[["NH3"]] <<- Auni (SumNH4, K_NH4, H) ; attr(aquaenv[["NH3"]], "unit") <<- "mol/kg-soln" aquaenv[["H2SO4"]] <<- H2Abi (SumH2SO4, K_H2SO4, K_HSO4, H) ; attr(aquaenv[["H2SO4"]], "unit") <<- "mol/kg-soln" aquaenv[["HSO4"]] <<- HAbi (SumH2SO4, K_H2SO4, K_HSO4, H) ; attr(aquaenv[["HSO4"]], "unit") <<- "mol/kg-soln" aquaenv[["SO4"]] <<- Abi (SumH2SO4, K_H2SO4, K_HSO4, H) ; attr(aquaenv[["SO4"]], "unit") <<- "mol/kg-soln" aquaenv[["HF"]] <<- HAuni (SumHF, K_HF, H) ; attr(aquaenv[["HF"]], "unit") <<- "mol/kg-soln" aquaenv[["F"]] <<- Auni (SumHF, K_HF, H) ; attr(aquaenv[["F"]], "unit") <<- "mol/kg-soln" aquaenv[["HNO3"]] <<- HAuni (SumHNO3, K_HNO3, H) ; attr(aquaenv[["HNO3"]], "unit") <<- "mol/kg-soln" aquaenv[["NO3"]] <<- Auni (SumHNO3, K_HNO3, H) ; attr(aquaenv[["NO3"]], "unit") <<- "mol/kg-soln" aquaenv[["HNO2"]] <<- HAuni (SumHNO2, K_HNO2, H) ; attr(aquaenv[["HNO2"]], "unit") <<- "mol/kg-soln" aquaenv[["NO2"]] <<- Auni (SumHNO2, K_HNO2, H) ; attr(aquaenv[["NO2"]], "unit") <<- "mol/kg-soln" aquaenv[["omega_calcite"]] <<- aquaenv[["Ca"]]*aquaenv[["CO3"]]/aquaenv[["Ksp_calcite"]] attributes(aquaenv[["omega_calcite"]]) <<- NULL aquaenv[["omega_aragonite"]] <<- aquaenv[["Ca"]]*aquaenv[["CO3"]]/aquaenv[["Ksp_aragonite"]] attributes(aquaenv[["omega_aragonite"]]) <<- NULL }) if (revelle) { aquaenv[["revelle"]] <- revelle(aquaenv) attributes(aquaenv[["revelle"]]) <- NULL } } if (dsa) { with (aquaenv, { if (!((length(SumCO2)==1) && (SumCO2==0))) { aquaenv[["c1"]] <<- CO2 /SumCO2 ; attributes(aquaenv[["c1"]]) <<- NULL aquaenv[["c2"]] <<- HCO3/SumCO2 ; attributes(aquaenv[["c2"]]) <<- NULL aquaenv[["c3"]] <<- CO3 /SumCO2 ; attributes(aquaenv[["c3"]]) <<- NULL aquaenv[["dTAdSumCO2"]] <<- aquaenv[["c2"]] + 2*aquaenv[["c3"]] attr(aquaenv[["dTAdSumCO2"]], "unit") <<- "(mol-TA/kg-soln)/(mol-SumCO2/kg-soln)" } if(!((length(SumBOH3)==1) && (SumBOH3==0))) { aquaenv[["b1"]] <<- BOH3/SumBOH3 ; attributes(aquaenv[["b1"]]) <<- NULL aquaenv[["b2"]] <<- BOH4/SumBOH3 ; attributes(aquaenv[["b2"]]) <<- NULL aquaenv[["dTAdSumBOH3"]] <<- aquaenv[["b2"]] attr(aquaenv[["dTAdSumBOH3"]], "unit") <<- "(mol-TA/kg-soln)/(mol-SumBOH3/kg-soln)" } if(!((length(SumH3PO4)==1) && (SumH3PO4==0))) { aquaenv[["p1"]] <<- H3PO4/SumH3PO4 ; attributes(aquaenv[["p1"]]) <<- NULL aquaenv[["p2"]] <<- H2PO4/SumH3PO4 ; attributes(aquaenv[["p2"]]) <<- NULL aquaenv[["p3"]] <<- HPO4 /SumH3PO4 ; attributes(aquaenv[["p3"]]) <<- NULL aquaenv[["p4"]] <<- PO4 /SumH3PO4 ; attributes(aquaenv[["p4"]]) <<- NULL aquaenv[["dTAdSumH3PO4"]] <<- aquaenv[["p3"]] + 2*aquaenv[["p4"]] - aquaenv[["p1"]] attr(aquaenv[["dTAdSumH3PO4"]], "unit") <<- "(mol-TA/kg-soln)/(mol-SumH3PO4/kg-soln)" } if(!((length(SumSiOH4)==1) && (SumSiOH4==0))) { aquaenv[["si1"]] <<- SiOH4 /SumSiOH4 ; attributes(aquaenv[["si1"]]) <<- NULL aquaenv[["si2"]] <<- SiOOH3 /SumSiOH4 ; attributes(aquaenv[["si2"]]) <<- NULL aquaenv[["si3"]] <<- SiO2OH2/SumSiOH4 ; attributes(aquaenv[["si3"]]) <<- NULL aquaenv[["dTAdSumSumSiOH4"]] <<- aquaenv[["si2"]] attr(aquaenv[["dTAdSumSumSiOH4"]], "unit") <<- "(mol-TA/kg-soln)/(mol-SumSiOH4/kg-soln)" } if(!((length(SumH2S)==1) && (SumH2S==0))) { aquaenv[["s1"]] <<- H2S /SumH2S ; attributes(aquaenv[["s1"]]) <<- NULL aquaenv[["s2"]] <<- HS /SumH2S ; attributes(aquaenv[["s2"]]) <<- NULL aquaenv[["s3"]] <<- S2min/SumH2S ; attributes(aquaenv[["s3"]]) <<- NULL aquaenv[["dTAdSumH2S"]] <<- aquaenv[["s2"]] + 2*aquaenv[["s3"]] attr(aquaenv[["dTAdSumH2S"]], "unit") <<- "(mol-TA/kg-soln)/(mol-SumH2S/kg-soln)" } if(!((length(SumNH4)==1) && (SumNH4==0))) { aquaenv[["n1"]] <<- NH4/SumNH4 ; attributes(aquaenv[["n1"]]) <<- NULL aquaenv[["n2"]] <<- NH3/SumNH4 ; attributes(aquaenv[["n2"]]) <<- NULL aquaenv[["dTAdSumNH4"]] <<- aquaenv[["n2"]] attr(aquaenv[["dTAdSumNH4"]], "unit") <<- "(mol-TA/kg-soln)/(mol-SumNH4/kg-soln)" } if(!((length(SumH2SO4)==1) && (SumH2SO4==0))) { aquaenv[["so1"]] <<- H2SO4/SumH2SO4 ; attributes(aquaenv[["so1"]]) <<- NULL aquaenv[["so2"]] <<- HSO4 /SumH2SO4 ; attributes(aquaenv[["so2"]]) <<- NULL aquaenv[["so3"]] <<- SO4 /SumH2SO4 ; attributes(aquaenv[["so3"]]) <<- NULL aquaenv[["dTAdSumH2SO4"]] <<- -aquaenv[["so2"]] attr(aquaenv[["dTAdSumH2SO4"]], "unit") <<- "(mol-TA/kg-soln)/(mol-SumH2SO4/kg-soln)" } if(!((length(SumHF)==1) && (SumHF==0))) { aquaenv[["f1"]] <<- HF/SumHF ; attributes(aquaenv[["f1"]]) <<- NULL aquaenv[["f2"]] <<- F /SumHF ; attributes(aquaenv[["f2"]]) <<- NULL aquaenv[["dTAdSumHF"]] <<- -aquaenv[["f1"]] attr(aquaenv[["dTAdSumHF"]], "unit") <<- "(mol-TA/kg-soln)/(mol-SumHF/kg-soln)" } if(!((length(SumHNO3)==1) && (SumHNO3==0))) { aquaenv[["na1"]] <<- HNO3/SumHNO3 ; attributes(aquaenv[["na1"]]) <<- NULL aquaenv[["na2"]] <<- NO3 /SumHNO3 ; attributes(aquaenv[["na2"]]) <<- NULL aquaenv[["dTAdSumHNO3"]] <<- -aquaenv[["na1"]] attr(aquaenv[["dTAdSumHNO3"]], "unit") <<- "(mol-TA/kg-soln)/(mol-SumHNO3/kg-soln)" } if(!((length(SumHNO2)==1) && (SumHNO2==0))) { aquaenv[["ni1"]] <<- HNO2/SumHNO2 ; attributes(aquaenv[["ni1"]]) <<- NULL aquaenv[["ni2"]] <<- NO2 /SumHNO2 ; attributes(aquaenv[["ni2"]]) <<- NULL aquaenv[["dTAdSumHNO2"]] <<- -aquaenv[["ni1"]] attr(aquaenv[["dTAdSumHNO2"]], "unit") <<- "(mol-TA/kg-soln)/(mol-SumHNO2/kg-soln)" } }) aquaenv[["dTAdH"]] <- dTAdH(aquaenv) ; attr(aquaenv[["dTAdH"]], "unit") <- "(mol-TA/kg-soln)/(mol-H/kg-soln)" aquaenv[["dTAdKdKdS"]] <- dTAdKdKdS(aquaenv) ; attr(aquaenv[["dTAdKdKdS"]], "unit") <- "(mol-TA/kg-soln)/\"psu\"" aquaenv[["dTAdKdKdT"]] <- dTAdKdKdT(aquaenv) ; attr(aquaenv[["dTAdKdKdT"]], "unit") <- "(mol-TA/kg-soln)/K" aquaenv[["dTAdKdKdp"]] <- dTAdKdKdp(aquaenv) ; attr(aquaenv[["dTAdKdKdp"]], "unit") <- "(mol-TA/kg-soln)/m" aquaenv[["dTAdKdKdSumH2SO4"]] <- dTAdKdKdSumH2SO4(aquaenv) ; attr(aquaenv[["dTAdKdKdSumH2SO4"]], "unit") <- "(mol-TA/kg-soln)/(mol-SumH2SO4/kg-soln)" aquaenv[["dTAdKdKdSumHF"]] <- dTAdKdKdSumHF(aquaenv) ; attr(aquaenv[["dTAdKdKdSumHF"]], "unit") <- "(mol-TA/kg-soln)/(mol-SumHF/kg-soln)" } } return(aquaenv) } } plot.aquaenv <- function(x, xval, what=NULL, bjerrum=FALSE, cumulative=FALSE, newdevice=TRUE, setpar=TRUE, device="x11", ...) { if ((!bjerrum) && (!cumulative)) { if (is.null(what)) { plotall(aquaenv=x, xval=xval, newdevice=newdevice, setpar=setpar, device=device, ...) } else { selectplot(aquaenv=x, xval=xval, what=what, newdevice=newdevice, setpar=setpar, device=device, ...) } } else if (bjerrum) { bjerrumplot(aquaenv=x, what=what, newdevice=newdevice, setpar=setpar, device=device, ...) } else { cumulativeplot(aquaenv=x, xval=xval, what=what, newdevice=newdevice, setpar=setpar, device=device, ...) } if (!(device=="x11")) { dev.off() } } as.data.frame.aquaenv <- function(x, ...) { len <- length(x) temp <- list() for (e in x) { if (length(e) > 1) { temp <- c(temp, list(e)) } else { temp <- c(temp, list(rep(e,len))) } } names(temp) <- names(x) return(as.data.frame(temp)) } BufferFactors <- function(ae = NULL, parameters = NA, species = c("SumCO2"), k_w = NULL, k_co2 = NULL, k_hco3 = NULL, k_boh3 = NULL, k_hso4 = NULL, k_hf = NULL, k1k2 = "lueker", khf = "dickson", khso4 = "dickson") { if(!is.null(ae)) { if((class(ae)=="aquaenv")==FALSE) { print(paste("Error! Object 'ae' is not of class 'aquaenv")) return(NULL) } else { if(is.na(parameters["DIC"])) { parameters["DIC"] <- ae$SumCO2} if(is.na(parameters["TotNH3"])) { parameters["TotNH3"] <- ae$SumNH4} if(is.na(parameters["TotP"])) { parameters["TotP"] <- ae$SumH3PO4} if(is.na(parameters["TotNO3"])) { parameters["TotNO3"] <- ae$SumHNO3} if(is.na(parameters["TotNO2"])) { parameters["TotNO2"] <- ae$SumHNO2} if(is.na(parameters["TotS"])) { parameters["TotS"] <- ae$SumH3PO4} if(is.na(parameters["TotSi"])) { parameters["TotSi"] <- ae$SumSiOH4} if(is.na(parameters["TB"])) { parameters["TB"] <- ae$SumBOH3} if(is.na(parameters["TotF"])) { parameters["TotF"] <- ae$SumHF} if(is.na(parameters["TotSO4"])) { parameters["TotSO4"] <- ae$SumH2SO4} if(is.na(parameters["sal"])) { parameters["sal"] <- ae$S} if(is.na(parameters["temp"])) { parameters["temp"] <- ae$t} if(is.na(parameters["pres"])) { parameters["pres"] <- ae$p} if(is.na(parameters["Alk"])) { parameters["Alk"] <- ae$TA} } } else { if(is.na(parameters["DIC"])) { parameters["DIC"] <- 1e-6*2017.14} if(is.na(parameters["TotNH3"])) {parameters["TotNH3"] <- convert(1e-6*0.3, "conc", "molar2molin", S = 34.617, t = 18.252, p = 0.1*1.008)} if(is.na(parameters["TotP"])) {parameters["TotP"] <- convert(1e-6*0.530, "conc", "molar2molin", S = 34.617, t = 18.252, p = 0.1*1.008)} if(is.na(parameters["TotNO3"])) {parameters["TotNO3"] <- convert(1e-6*5.207, "conc", "molar2molin", S = 34.617, t = 18.252, p = 0.1*1.008)} if(is.na(parameters["TotNO2"])) {parameters["TotNO2"] <- convert(1e-6*0.1, "conc", "molar2molin", S = 34.617, t = 18.252, p = 0.1*1.008)} if(is.na(parameters["TotS"])) {parameters["TotS"] <- convert(1e-9*2.35, "conc", "molar2molin", S = 34.617, t = 18.252, p = 0.1*1.008)} if(is.na(parameters["TotSi"])) {parameters["TotSi"] <- convert(1e-6*7.466, "conc", "molar2molin", S = 34.617, t = 18.252, p = 0.1*1.008)} if(is.na(parameters["TB"])) { parameters["TB"] <- 1e-6*428.4} if(is.na(parameters["TotF"])) { parameters["TotF"] <- 1e-6*67.579} if(is.na(parameters["TotSO4"])) { parameters["TotSO4"] <- 0.02793} if(is.na(parameters["sal"])) { parameters["sal"] <- 34.617} if(is.na(parameters["temp"])) { parameters["temp"] <- 18.252} if(is.na(parameters["pres"])) { parameters["pres"] <- 0.1*1.008} if(is.na(parameters["Alk"])) { parameters["Alk"] <- 1e-6*2304.91} } with(as.list(parameters), { ae <- aquaenv(S=sal, t=temp, p=pres, TA=Alk, SumCO2=DIC, SumBOH3 = TB, SumNH4 = TotNH3, SumH3PO4 = TotP, SumHNO3 = TotNO3, SumHNO2 = TotNO2, SumH2S = TotS, SumSiOH4 = TotSi, SumH2SO4 = TotSO4, SumHF = TotF, speciation = TRUE, dsa = TRUE, k_w = k_w, k_co2 = k_co2, k_hco3 = k_hco3, k_boh3 = k_boh3, k_hso4 = k_hso4, k_hf = k_hf, k1k2 = k1k2, khf = khf, khso4 = khso4) with(as.list(ae), { H <- 10^(-pH) dTA.dH <- dtotX.dH <- dTA.dX <- dtotX.dX <- dTA.dpH <- dtotX.dpH <- dH.dTA <- dX.dTA <- dX.dtotX <- dpH.dTA <- rep(NA, length.out = length(species)) dH.dtotX <- dpH.dtotX <- rep(NA, length.out = length(species) + 5) names(dTA.dH) <- names(dtotX.dH) <- names(dTA.dX) <- names(dtotX.dX) <- names(dTA.dpH) <- names(dtotX.dpH) <- names(dH.dTA) <- names(dX.dTA) <- names(dX.dtotX) <- names(dpH.dTA) <- species names(dH.dtotX) <- names(dpH.dtotX) <- c(species,"sal", "temp", "pres", "SumH2SO4_scaleconv", "SumHF_scaleconv") TA.species <- function(X.name) { if(X.name == "CO2" || X.name == "HCO3" || X.name == "CO3" || X.name == "SumCO2") {HCO3 + 2*CO3} else if(X.name == "NH3" || X.name == "NH4" || X.name == "SumNH4") { NH3} else if(X.name == "H2PO4" || X.name == "H3PO4" || X.name == "HPO4" || X.name == "PO4" || X.name == "SumH3PO4") {-H3PO4 + HPO4 + 2*PO4} else if(X.name == "NO3" || X.name == "HNO3" || X.name == "SumHNO3") {-HNO3} else if(X.name == "NO2" || X.name == "HNO2" || X.name == "SumHNO2") {-HNO2} else if(X.name == "H2S" || X.name == "HS" || X.name == "S2min" || X.name == "SumH2S") { HS + 2*S2min} else if(X.name == "SiOH4" || X.name == "SiOOH3" || X.name == "SiO2OH2" || X.name == "SumSiOH4") { SiOOH3 + 2*SiO2OH2} else if(X.name == "BOH3" || X.name == "BOH4" || X.name == "SumBOH3") {BOH4} else if(X.name == "F" || X.name == "HF" || X.name == "SumHF") {-HF} else if(X.name == "SO4" || X.name == "H2SO4" || X.name == "HSO4" || X.name == "SumH2SO4") { -2*H2SO4 - HSO4} else NULL } n.function <- function(X.name) { if(X.name == "CO2" || X.name == "BOH3" || X.name == "NH4" || X.name == "H2PO4" || X.name == "NO3" || X.name == "NO2" || X.name == "H2S" || X.name == "SiOH4" || X.name == "F" || X.name == "SO4" || X.name == "SumCO2" || X.name == "SumBOH3" || X.name == "SumNH4" || X.name == "SumH3PO4" || X.name == "SumHNO3" || X.name == "SumHNO2" || X.name == "SumH2S" || X.name == "SumSiOH4" || X.name == "SumHF" || X.name == "SumH2SO4") {n <- 0} else if(X.name == "HCO3" || X.name == "NH3" || X.name == "HPO4" || X.name == "HS" || X.name == "SiOOH3" || X.name == "BOH4") {n <- 1} else if(X.name == "CO3" || X.name == "PO4" || X.name == "S2min" || X.name == "SiO2OH2") {n <- 2} else if(X.name == "H3PO4" || X.name == "HNO3" || X.name == "HNO2" || X.name == "HF" || X.name == "HSO4") { n <- -1} else if(X.name == "H2SO4") {n <- -2} else NULL } dTAdH.function <- function(X.name) { n <- n.function(X.name) TA.X <- TA.species(X.name) if(parameters["DIC"]!=0) { if(X.name == "CO2" || X.name == "HCO3" || X.name == "CO3" || X.name == "SumCO2") { dTAdH.CO2 <- (-1/H)*(-n*TA.X + HCO3 + 4*CO3)} else { dTAdH.CO2 <- (-1/H)*(HCO3*(c1-c3) + 2*CO3*(2*c1+c2))} } else dTAdH.CO2 <- 0 if(parameters["TotNH3"]!=0) { if(X.name == "NH3" || X.name == "NH4" || X.name == "SumNH4") { dTAdH.NH4 <- (-1/H)*(-n*TA.X + NH3)} else { dTAdH.NH4 <- (-1/H)*(NH3*n1)} } else dTAdH.NH4 <- 0 if(parameters["TotP"]!=0) { if(X.name == "H2PO4" || X.name == "H3PO4" || X.name == "HPO4" || X.name == "PO4" || X.name == "SumH3PO4") { dTAdH.H2PO4 <- (-1/H)*(-n*TA.X + H3PO4 + HPO4 + 4*PO4)} else { dTAdH.H2PO4 <- (-1/H)*(-H3PO4*(-p2-2*p3-3*p4) + HPO4*(2*p1+p2-p4) + 2*PO4*(3*p1+2*p2+p3))} } else dTAdH.H2PO4 <- 0 if(parameters["TotNO3"]!=0) { if(X.name == "NO3" || X.name == "HNO3" || X.name == "SumHNO3") { dTAdH.NO3 <- (-1/H)*(-n*TA.X + HNO3)} else { dTAdH.NO3 <- (-1/H)*(-HNO3*na2)} } else dTAdH.NO3 <- 0 if(parameters["TotNO2"]!=0) { if(X.name == "NO2" || X.name == "HNO2" || X.name == "SumHNO2") { dTAdH.NO2 <- (-1/H)*(-n*TA.X + HNO2)} else { dTAdH.NO2 <- (-1/H)*(-HNO2*ni2)} } else dTAdH.NO2 <- 0 if(parameters["TotS"]!=0) { if(X.name == "H2S" || X.name == "HS" || X.name == "S2min" || X.name == "SumH2S") { dTAdH.H2S <- (-1/H)*(-n*TA.X + HS + 4*S2min)} else { dTAdH.H2S <- (-1/H)*(HS*(s1-s3) + 2*S2min*(2*s1+s2))} } else dTAdH.H2S <- 0 if(parameters["TotSi"]!=0) { if(X.name == "SiOH4" || X.name == "SiOOH3" || X.name == "SiO2OH2" || X.name == "SumSiOH4") { dTAdH.SiOH4 <- (-1/H)*(-n*TA.X + SiOOH3 + 4*SiO2OH2)} else { dTAdH.SiOH4 <- (-1/H)*(SiOOH3*(si1-si3) + 2*SiO2OH2*(2*si1+si2))} } else dTAdH.SiOH4 <- 0 if(parameters["TB"]!=0) { if(X.name == "BOH3" || X.name == "BOH4" || X.name == "SumBOH3") { dTAdH.BOH3 <- (-1/H)*(-n*TA.X + BOH4)} else { dTAdH.BOH3 <-(-1/H)*(BOH4*b1)} } else dTAdH.BOH3 <- 0 if(parameters["TotF"]!=0) { if(X.name == "F" || X.name == "HF" || X.name == "SumHF") { dTAdH.F <- (-1/H)*(-n*TA.X + HF)} else { dTAdH.F <- (-1/H)*(-HF*f2)} } else dTAdH.F <- 0 if(parameters["TotSO4"]!=0) { if(X.name == "SO4" || X.name == "H2SO4" || X.name == "HSO4" || X.name == "SumH2SO4") { dTAdH.SO4 <- (-1/H)*(-n*TA.X + 4*H2SO4 + HSO4)} else { dTAdH.SO4 <- (-1/H)*(-2*H2SO4*(-so2-2*so3) - HSO4*(so1-so3))} } else dTAdH.SO4 <- 0 dTAdH.H <- (-1/H)*(OH+H) return(dTAdH.CO2 + dTAdH.NH4 + dTAdH.H2PO4 + dTAdH.NO3 + dTAdH.NO2 + dTAdH.H2S + dTAdH.SiOH4 + dTAdH.BOH3 + dTAdH.F + dTAdH.SO4 + dTAdH.H) } totX.function <- function(X.name) { if(X.name == "CO2" || X.name == "HCO3" || X.name == "CO3" || X.name == "SumCO2") {SumCO2} else if(X.name == "NH3" || X.name == "NH4" || X.name == "SumNH4") { SumNH4} else if(X.name == "H2PO4" || X.name == "H3PO4" || X.name == "HPO4" || X.name == "PO4" || X.name == "SumH3PO4") {SumH3PO4} else if(X.name == "NO3" || X.name == "HNO3" || X.name == "SumHNO3") {SumHNO3} else if(X.name == "NO2" || X.name == "HNO2" || X.name == "SumHNO2") {SumHNO2} else if(X.name == "H2S" || X.name == "HS" || X.name == "S2min" || X.name == "SumH2S") {SumH2S} else if(X.name == "SiOH4" || X.name == "SiOOH3" || X.name == "SiO2OH2" || X.name == "SumSiOH4") { SumSiOH4} else if(X.name == "BOH3" || X.name == "BOH4" || X.name == "SumBOH3") {SumBOH3} else if(X.name == "F" || X.name == "HF" || X.name == "SumHF") {SumHF} else if(X.name == "SO4" || X.name == "H2SO4" || X.name == "HSO4" || X.name == "SumH2SO4") { SumH2SO4} else NULL } Revelle_func <- function(species) { X.name <- "CO2" X <- get(X.name) n <- n.function(X.name) TA.X <- TA.species(X.name) totX <- totX.function(X.name) dTA.dH <- dTAdH.function(X.name) dX.dtotX <- X * H * dTA.dH / (TA.X^2 + (H*dTA.dH - n*TA.X)*totX) RF <- as.numeric(ae$SumCO2 / ae$CO2 * dX.dtotX) return(RF) } for (i in 1:length(species)) { X.name <- species[i] if(X.name == "SumCO2") X <- get("CO2") else if(X.name == "SumNH4") X <- get("NH4") else if(X.name == "SumH3PO4") X <- get("H2PO4") else if(X.name == "SumHNO3") X <- get("NO3") else if(X.name == "SumHNO2") X <- get("NO2") else if(X.name == "SumH2S") X <- get("H2S") else if(X.name == "SumSiOH4") X <- get("SiOH4") else if(X.name == "SumBOH3") X <- get("BOH3") else if(X.name == "SumHF") X <- get("F") else if(X.name == "SumH2SO4") X <- get("SO4") else X <- get(species[i]) n <- n.function(X.name) TA.X <- TA.species(X.name) totX <- totX.function(X.name) dTA.dH[i] <- dTAdH.function(X.name) dtotX.dH[i] <- (n*totX - TA.X) / H dTA.dX[i] <- TA.X / X dtotX.dX[i] <- totX / X dH.dpH <- -log(10)*H dTA.dpH[i] <- dH.dpH * dTA.dH[i] dtotX.dpH[i] <- dH.dpH * dtotX.dH[i] dH.dTA[i] <- totX*H / (TA.X^2 + (H*dTA.dH[i] - n*TA.X)*totX) dH.dtotX[i] <- -TA.X*H / (TA.X^2 + (H*dTA.dH[i] - n*TA.X)*totX) dX.dTA[i] <- -X * (n*totX - TA.X) / (TA.X^2 + (H*dTA.dH[i] - n*TA.X)*totX) dX.dtotX[i] <- X * H * dTA.dH[i] / (TA.X^2 + (H*dTA.dH[i] - n*TA.X)*totX) dpH.dH <- 1/(-log(10)*H) dpH.dTA[i] <- dpH.dH * dH.dTA[i] dpH.dtotX[i] <- dpH.dH * dH.dtotX[i] } RF <- Revelle_func(species) dH.dtotX[1+length(species)] <- (dTAdKdKdS) / (-dTAdH) dH.dtotX[2+length(species)] <- (dTAdKdKdT) / (-dTAdH) dH.dtotX[3+length(species)] <- (dTAdKdKdp) / (-dTAdH) dH.dtotX[4+length(species)] <- (dTAdKdKdSumH2SO4) / (-dTAdH) dH.dtotX[5+length(species)] <- (dTAdKdKdSumHF) / (-dTAdH) dpH.dtotX[1+length(species)] <- dpH.dH * dH.dtotX[1+length(species)] dpH.dtotX[2+length(species)] <- dpH.dH * dH.dtotX[2+length(species)] dpH.dtotX[3+length(species)] <- dpH.dH * dH.dtotX[3+length(species)] dpH.dtotX[4+length(species)] <- dpH.dH * dH.dtotX[4+length(species)] dpH.dtotX[5+length(species)] <- dpH.dH * dH.dtotX[5+length(species)] return(list(ae = ae, dTA.dH = dTA.dH, dtotX.dH = dtotX.dH, dTA.dX = dTA.dX, dtotX.dX = dtotX.dX, dTA.dpH = dTA.dpH, dtotX.dpH = dtotX.dpH, dH.dTA = dH.dTA, dH.dtotX = dH.dtotX, dX.dTA = dX.dTA, dX.dtotX = dX.dtotX, dpH.dTA = dpH.dTA, dpH.dtotX = dpH.dtotX, beta.H = as.numeric(dTAdH), RF = RF)) }) }) }
context("download_r5") testthat::skip_on_cran() test_that("download_r5 - expected behavior", { testthat::expect_vector(download_r5(force_update = TRUE, temp_dir = TRUE)) testthat::expect_vector(download_r5(force_update = TRUE, temp_dir = FALSE)) testthat::expect_vector(download_r5(force_update = FALSE, temp_dir = TRUE)) testthat::expect_vector(download_r5(force_update = FALSE, quiet = TRUE)) }) test_that("download_r5 - expected errors", { testthat::expect_error( download_r5(version = "0") ) testthat::expect_error( download_r5(version = NULL ) ) testthat::expect_error(download_r5(force_update = 'a')) testthat::expect_error(download_r5(quiet = 'a')) testthat::expect_error(download_r5(temp_dir = 'a')) })
context("Checking misc: to.long() function") source("settings.r") test_that("to.long() works correctly for measure='MD'", { dat <- dat.normand1999 sav <- to.long(measure="MD", m1i=m1i, sd1i=sd1i, n1i=n1i, m2i=m2i, sd2i=sd2i, n2i=n2i, data=dat, subset=1:4) sav <- sav[,c(1,10:13)] expected <- structure(list(study = c(1L, 1L, 2L, 2L, 3L, 3L, 4L, 4L), group = structure(c(2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L), .Label = c("2", "1"), class = "factor"), mean = c(55L, 75L, 27L, 29L, 64L, 119L, 66L, 137L), sd = c(47L, 64L, 7L, 4L, 17L, 29L, 20L, 48L), n = c(155L, 156L, 31L, 32L, 75L, 71L, 18L, 18L)), class = "data.frame", row.names = c(NA, 8L)) expect_equivalent(sav, expected) }) test_that("to.table() works correctly for measure='MD'", { dat <- dat.normand1999 sav <- to.table(measure="MD", m1i=m1i, sd1i=sd1i, n1i=n1i, m2i=m2i, sd2i=sd2i, n2i=n2i, data=dat, subset=1:4) expected <- structure(c(55L, 75L, 47L, 64L, 155L, 156L, 27L, 29L, 7L, 4L, 31L, 32L, 64L, 119L, 17L, 29L, 75L, 71L, 66L, 137L, 20L, 48L, 18L, 18L), .Dim = 2:4, .Dimnames = list(c("Grp1", "Grp2"), c("Mean", "SD", "n"), c("1", "2", "3", "4"))) expect_equivalent(sav, expected) }) test_that("to.long() works correctly for measure='COR'", { dat <- dat.molloy2014 sav <- to.long(measure="COR", ri=ri, ni=ni, data=dat, subset=1:4) sav <- sav[,c(11:13)] expected <- structure(list(study = structure(1:4, .Label = c("1", "2", "3", "4"), class = "factor"), r = c(0.187, 0.162, 0.34, 0.32), n = c(109L, 749L, 55L, 107L)), class = "data.frame", row.names = c(NA, 4L )) expect_equivalent(sav, expected) }) test_that("to.table() works correctly for measure='COR'", { dat <- dat.molloy2014 sav <- to.table(measure="COR", ri=ri, ni=ni, data=dat, subset=1:4) expected <- structure(c(0.187, 109, 0.162, 749, 0.34, 55, 0.32, 107), .Dim = c(1L, 2L, 4L), .Dimnames = list("Grp", c("r", "n"), c("1", "2", "3", "4"))) expect_equivalent(sav, expected) }) test_that("to.long() works correctly for measure='PR'", { dat <- dat.debruin2009 sav <- to.long(measure="PR", xi=xi, ni=ni, data=dat, subset=1:4) sav <- sav[,c(11:13)] expected <- structure(list(study = structure(1:4, .Label = c("1", "2", "3", "4"), class = "factor"), out1 = c(11L, 24L, 179L, 82L), out2 = c(18L, 9L, 147L, 158L)), class = "data.frame", row.names = c(NA, 4L)) expect_equivalent(sav, expected) }) test_that("to.table() works correctly for measure='PR'", { dat <- dat.debruin2009 sav <- to.table(measure="PR", xi=xi, ni=ni, data=dat, subset=1:4) expected <- structure(c(11, 18, 24, 9, 179, 147, 82, 158), .Dim = c(1, 2, 4), .Dimnames = list("Grp", c("Out1", "Out2"), c("1", "2", "3", "4"))) expect_equivalent(sav, expected) }) test_that("to.long() works correctly for measure='IR'", { dat <- dat.hart1999 sav <- to.long(measure="IR", xi=x1i, ti=t1i, data=dat, subset=1:4) sav <- sav[,c(1,14:15)] expected <- structure(list(trial = 1:4, events = c(9L, 8L, 3L, 6L), ptime = c(413L, 263L, 487L, 237L)), class = "data.frame", row.names = c(NA, 4L)) expect_equivalent(sav, expected) }) test_that("to.table() works correctly for measure='IR'", { dat <- dat.hart1999 sav <- to.table(measure="IR", xi=x1i, ti=t1i, data=dat, subset=1:4) expected <- structure(c(9, 413, 8, 263, 3, 487, 6, 237), .Dim = c(1, 2, 4), .Dimnames = list("Grp", c("Events", "Person-Time"), c("1", "2", "3", "4"))) expect_equivalent(sav, expected) }) test_that("to.long() works correctly for measure='MN'", { dat <- dat.normand1999 sav <- to.long(measure="MN", mi=m1i, sdi=sd1i, ni=n1i, data=dat, subset=1:4) sav <- sav[,c(1,10:12)] expected <- structure(list(study = 1:4, mean = c(55L, 27L, 64L, 66L), sd = c(47L, 7L, 17L, 20L), n = c(155L, 31L, 75L, 18L)), class = "data.frame", row.names = c(NA, 4L)) expect_equivalent(sav, expected) }) test_that("to.table() works correctly for measure='MN'", { dat <- dat.normand1999 sav <- to.table(measure="MN", mi=m1i, sdi=sd1i, ni=n1i, data=dat, subset=1:4) expected <- structure(c(55, 47, 155, 27, 7, 31, 64, 17, 75, 66, 20, 18), .Dim = c(1, 3, 4), .Dimnames = list("Grp", c("Mean", "SD", "n"), c("1", "2", "3", "4"))) expect_equivalent(sav, expected) }) datT <- data.frame( m_pre = c(30.6, 23.5, 0.5, 53.4, 35.6), m_post = c(38.5, 26.8, 0.7, 75.9, 36.0), sd_pre = c(15.0, 3.1, 0.1, 14.5, 4.7), sd_post = c(11.6, 4.1, 0.1, 4.4, 4.6), ni = c(20, 50, 9, 10, 14), ri = c(.47, .64, .77, .89, .44)) test_that("to.long() works correctly for measure='SMCR'", { sav <- to.long(measure="SMCR", m1i=m_post, m2i=m_pre, sd1i=sd_pre, ni=ni, ri=ri, data=datT, subset=2:4) sav <- sav[,c(7:12)] expected <- structure(list(study = structure(1:3, .Label = c("2", "3", "4"), class = "factor"), mean1 = c(26.8, 0.7, 75.9), mean2 = c(23.5, 0.5, 53.4), sd1 = c(3.1, 0.1, 14.5), n = c(50, 9, 10), r = c(0.64, 0.77, 0.89)), class = "data.frame", row.names = c(NA, 3L)) expect_equivalent(sav, expected) }) test_that("to.table() works correctly for measure='SMCR'", { sav <- to.table(measure="SMCR", m1i=m_post, m2i=m_pre, sd1i=sd_pre, ni=ni, ri=ri, data=datT, subset=2:4) expected <- structure(c(26.8, 23.5, 3.1, 50, 0.64, 0.7, 0.5, 0.1, 9, 0.77, 75.9, 53.4, 14.5, 10, 0.89), .Dim = c(1, 5, 3), .Dimnames = list("Grp", c("Mean1", "Mean2", "SD1", "n", "r"), c("2", "3", "4"))) expect_equivalent(sav, expected) }) test_that("to.long() works correctly for measure='ARAW'", { dat <- dat.bonett2010 sav <- to.long(measure="AHW", ai=ai, mi=mi, ni=ni, data=dat, subset=1:4) sav <- sav[,c(1,8:10)] expected <- structure(list(study = 1:4, alpha = c(0.93, 0.91, 0.94, 0.89), m = c(20L, 20L, 20L, 20L), n = c(103L, 64L, 118L, 401L)), class = "data.frame", row.names = c(NA, 4L)) expect_equivalent(sav, expected) }) test_that("to.table() works correctly for measure='ARAW'", { dat <- dat.bonett2010 sav <- to.table(measure="AHW", ai=ai, mi=mi, ni=ni, data=dat, subset=1:4) expected <- structure(c(0.93, 20, 103, 0.91, 20, 64, 0.94, 20, 118, 0.89, 20, 401), .Dim = c(1, 3, 4), .Dimnames = list("Grp", c("alpha", "m", "n"), c("1", "2", "3", "4"))) expect_equivalent(sav, expected) }) test_that("to.wide() works correctly.", { dat.l <- dat.hasselblad1998 dat.c <- to.wide(dat.l, study="study", grp="trt", ref="no_contact", grpvars=6:7) expect_equivalent(dat.c$xi.1, c(363, 10, 23, 9, 237, 9, 16, 31, 26, 29, 12, 17, 77, 21, 107, 20, 3, 32, 8, 34, 9, 19, 143, 36, 73, 54)) expect_equivalent(dat.c$xi.2, c(75, 9, 9, 2, 58, 0, 20, 3, 1, 11, 11, 6, 79, 18, 64, 12, 9, 7, 5, 20, 0, 8, 95, 15, 78, 69)) expect_equivalent(dat.c$comp, c("in-no", "gr-no", "in-no", "in-no", "in-no", "in-no", "in-se", "in-no", "in-no", "gr-se", "in-se", "in-no", "se-no", "se-no", "in-no", "gr-in", "gr-in", "gr-se", "in-no", "in-no", "gr-no", "se-no", "in-no", "in-no", "in-no", "in-no")) expect_equivalent(dat.c$design, c("in-no", "gr-in-no", "gr-in-no", "in-no", "in-no", "in-no", "in-se", "in-no", "in-no", "gr-in-se", "gr-in-se", "in-no", "se-no", "se-no", "in-no", "gr-in", "gr-in", "gr-se", "in-no", "in-no", "gr-no", "se-no", "in-no", "in-no", "in-no", "in-no")) dat.l$trt <- factor(dat.l$trt, levels=c("no_contact", "ind_counseling", "grp_counseling", "self_help")) dat.c <- to.wide(dat.l, study="study", grp="trt", grpvars=5:7, postfix=c(".T",".C"), minlen=1) expect_equivalent(dat.c$xi.T, c(363, 23, 10, 9, 237, 9, 16, 31, 26, 12, 29, 17, 77, 21, 107, 12, 9, 32, 8, 34, 9, 19, 143, 36, 73, 54)) expect_equivalent(dat.c$xi.C, c(75, 9, 9, 2, 58, 0, 20, 3, 1, 11, 11, 6, 79, 18, 64, 20, 3, 7, 5, 20, 0, 8, 95, 15, 78, 69)) expect_equivalent(dat.c$comp, c("i-n", "i-n", "g-n", "i-n", "i-n", "i-n", "i-s", "i-n", "i-n", "i-s", "g-s", "i-n", "s-n", "s-n", "i-n", "i-g", "i-g", "g-s", "i-n", "i-n", "g-n", "s-n", "i-n", "i-n", "i-n", "i-n")) expect_equivalent(dat.c$design, c("i-n", "i-g-n", "i-g-n", "i-n", "i-n", "i-n", "i-s", "i-n", "i-n", "i-g-s", "i-g-s", "i-n", "s-n", "s-n", "i-n", "i-g", "i-g", "g-s", "i-n", "i-n", "g-n", "s-n", "i-n", "i-n", "i-n", "i-n")) }) rm(list=ls())
eachcol.apply<-function(x,y,indices = NULL,oper = "*",apply = "sum"){ .Call(Rfast_eachcol_apply,x,y,indices,oper,apply) }
sjplot <- function(data, ..., fun = c("grpfrq", "xtab", "aov1", "likert")) { if (!is.data.frame(data)) stop("`data` must be a data frame.", call. = F) fun <- match.arg(fun) x <- get_dot_data(data, match.call(expand.dots = FALSE)$`...`) args <- match.call(expand.dots = FALSE)$`...` args <- args[names(args) != ""] p <- NULL pl <- NULL if (inherits(x, "grouped_df")) { grps <- get_grouped_data(x) for (i in seq_len(nrow(grps))) { tmp <- sjlabelled::copy_labels(grps$data[[i]], x) tmp.args <- get_grouped_title(x, grps, args, i, sep = "\n") plots <- plot_sj(tmp, fun, tmp.args) if (!is.null(plots$p)) pl <- c(pl, list(plots$p)) if (!is.null(plots$pl)) pl <- c(pl, plots$pl) } } else { plots <- plot_sj(x, fun, args) p <- plots$p pl <- plots$pl } if (!is.null(pl)) { for (p in pl) suppressWarnings(graphics::plot(p)) invisible(pl) } else { suppressWarnings(graphics::plot(p)) invisible(p) } } sjtab <- function(data, ..., fun = c("xtab", "stackfrq")) { if (!is.data.frame(data)) stop("`data` must be a data frame.", call. = F) fun <- match.arg(fun) x <- get_dot_data(data, match.call(expand.dots = FALSE)$`...`) tabs.list <- list() args <- match.call(expand.dots = FALSE)$`...` args <- args[names(args) != ""] if (inherits(x, "grouped_df")) { grps <- get_grouped_data(x) for (i in seq_len(nrow(grps))) { tmp <- sjlabelled::copy_labels(grps$data[[i]], x) tmp.args <- get_grouped_title(x, grps, args, i, sep = "<br>") tl <- tab_sj(tmp, fun, tmp.args) tabs.list[[length(tabs.list) + 1]] <- tl } final.table <- paste0( tl$header, tl$page.style, "\n</head>\n<body>\n" ) final.knitr <- "" for (i in seq_len(length(tabs.list))) { final.table <- paste0(final.table, tabs.list[[i]]$page.content, sep = "\n<p>&nbsp;</p>\n") final.knitr <- paste0(final.knitr, tabs.list[[i]]$knitr, sep = "\n<p>&nbsp;</p>\n") } final.table <- paste0(final.table, "\n</body>\n</html>") return(structure( class = c("sjTable", "sjtab"), list( page.style = tl$page.style, header = tl$header, page.content = final.table, page.complete = final.table, knitr = final.knitr, file = eval(args[["file"]]), viewer = if (is.null(args[["use.viewer"]])) TRUE else eval(args[["use.viewer"]]) ) )) } else { tab_sj(x, fun, args) } } get_grouped_plottitle <- function(x, grps, i, sep = "\n") { tp <- get_title_part(x, grps, 1, i) title <- sprintf("%s: %s", tp[1], tp[2]) if (length(dplyr::group_vars(x)) > 1) { tp <- get_title_part(x, grps, 2, i) title <- sprintf("%s%s%s: %s", title, sep, tp[1], tp[2]) } title } get_grouped_title <- function(x, grps, args, i, sep = "\n") { tp <- get_title_part(x, grps, 1, i) title <- sprintf("%s: %s", tp[1], tp[2]) if (length(dplyr::group_vars(x)) > 1) { tp <- get_title_part(x, grps, 2, i) title <- sprintf("%s%s%s: %s", title, sep, tp[1], tp[2]) } c(args, `title` = title) } get_title_part <- function(x, grps, level, i) { var.name <- colnames(grps)[level] vals <- sjlabelled::get_values(x[[var.name]]) if (is.null(vals)) vals <- unique(x[[var.name]]) lab.pos <- which(vals == grps[[var.name]][i]) t1 <- sjlabelled::get_label(x[[var.name]], def.value = var.name) t2 <- sjlabelled::get_labels(x[[var.name]])[lab.pos] if (is.null(t2)) t2 <- vals[lab.pos] c(t1, t2) } get_grouped_data <- function(x) { grps <- x %>% dplyr::group_modify(~ dplyr::filter(.x, stats::complete.cases(.y))) %>% tidyr::nest() if (length(dplyr::group_vars(x)) == 1) reihe <- order(grps[[1]]) else reihe <- order(grps[[1]], grps[[2]]) grps <- grps[reihe, ] grps } plot_sj <- function(x, fun, args) { p <- NULL pl <- NULL if (sjmisc::is_empty(args)) { if (fun == "grpfrq") { p <- plot_grpfrq(x[[1]], x[[2]]) } else if (fun == "likert") { p <- plot_likert(x) } else if (fun == "xtab") { p <- plot_xtab(x[[1]], x[[2]]) } else if (fun == "aov1") { p <- sjp.aov1(x[[1]], x[[2]]) } } else { if (fun == "grpfrq") { p <- do.call(plot_grpfrq, args = c(list(var.cnt = x[[1]], var.grp = x[[2]]), args)) } else if (fun == "likert") { p <- do.call(plot_likert, args = c(list(items = x), args)) } else if (fun == "xtab") { p <- do.call(plot_xtab, args = c(list(x = x[[1]], grp = x[[2]]), args)) } else if (fun == "aov1") { p <- do.call(sjp.aov1, args = c(list(var.dep = x[[1]], var.grp = x[[2]]), args)) } } list(p = p, pl = pl) } tab_sj <- function(x, fun, args) { if (sjmisc::is_empty(args)) { if (fun == "xtab") { tab_xtab(x[[1]], x[[2]]) } else if (fun == "stackfrq") { tab_stackfrq(x) } } else { if (fun == "stackfrq") { do.call(tab_stackfrq, args = c(list(items = x), args)) } else if (fun == "xtab") { do.call(tab_xtab, args = c(list(var.row = x[[1]], var.col = x[[2]]), args)) } } }
print.fpcad <- function(x, mean.print=FALSE, var.print=FALSE, cor.print=FALSE, skewness.print=FALSE, kurtosis.print=FALSE, digits=2, ...) { cat("group variable: ",x$group, "\n") cat("variables: ", x$variables, "\n") cat("---------------------------------------------------------------\n") cat("inertia\n"); print(x$inertia, digits=3, ...) cat("---------------------------------------------------------------\n") cat("contributions\n"); print(x$contributions, ...) cat("---------------------------------------------------------------\n") cat("qualities\n"); print(x$qualities, ...) cat("---------------------------------------------------------------\n") cat("scores\n"); print(x$scores, ...) if (mean.print) {n.group <- length(x$means) n.var <- length(x$means[[1]]) Means <- matrix(unlist(x$means), nrow = n.group, ncol = n.var, byrow = TRUE, dimnames = list(NULL, paste("mean", x$variables, sep = "."))) Means <- data.frame(group=names(x$means), Means, stringsAsFactors = TRUE) colnames(Means)[1]=colnames(x$contributions)[1] if (n.var > 1) { st.dev <- unlist(lapply(lapply(x$variances, diag), sqrt)) } else { st.dev <- unlist(lapply(x$variances, sqrt)) } Means <- data.frame(Means, matrix(st.dev, nrow = n.group, ncol = n.var, byrow = TRUE, dimnames = list(NULL, paste("sd", x$variables))), stringsAsFactors = TRUE) Means <- data.frame(Means, norm = x$norm$norm, stringsAsFactors = TRUE) cat("---------------------------------------------------------------\n") cat("means, standard deviations and norm by group\n") print(Means, digits=digits, ...) } if (var.print) {cat("---------------------------------------------------------------\n") cat("variances/covariances by group\n"); print(x$variances, digits=digits, ...) } if (cor.print) {cat("---------------------------------------------------------------\n") cat("correlations by group\n"); print(x$correlations, digits=digits, ...) } if (skewness.print) {cat("---------------------------------------------------------------\n") cat("skewness coefficients by group\n"); print(x$skewness, digits=digits, ...) } if (kurtosis.print) {cat("---------------------------------------------------------------\n") cat("kurtosis coefficients by group\n"); print(x$kurtosis, digits=digits, ...) } return(invisible(x)) }
library(testthat) escapeString <- function(s) { t <- gsub("(\\\\)", "\\\\\\\\", s) t <- gsub("(\n)", "\\\\n", t) t <- gsub("(\r)", "\\\\r", t) t <- gsub("(\")", "\\\\\"", t) return(t) } prepStr <- function(s) { t <- escapeString(s) u <- eval(parse(text=paste0("\"", t, "\""))) if(s!=u) stop("Unable to escape string!") t <- paste0("\thtml <- \"", t, "\"") utils::writeClipboard(t) return(invisible()) } evaluationMode <- "sequential" processingLibrary <- "dplyr" description <- "test: sequential dplyr" countFunction <- "n()" isDevelopmentVersion <- (length(strsplit(packageDescription("pivottabler")$Version, "\\.")[[1]]) > 3) testScenarios <- function(description="test", releaseEvaluationMode="batch", releaseProcessingLibrary="dplyr", runAllForReleaseVersion=FALSE) { isDevelopmentVersion <- (length(strsplit(packageDescription("pivottabler")$Version, "\\.")[[1]]) > 3) if(isDevelopmentVersion||runAllForReleaseVersion) { evaluationModes <- c("sequential", "batch") processingLibraries <- c("dplyr", "data.table") } else { evaluationModes <- releaseEvaluationMode processingLibraries <- releaseProcessingLibrary } testCount <- length(evaluationModes)*length(processingLibraries) c1 <- character(testCount) c2 <- character(testCount) c3 <- character(testCount) c4 <- character(testCount) testCount <- 0 for(evaluationMode in evaluationModes) for(processingLibrary in processingLibraries) { testCount <- testCount + 1 c1[testCount] <- evaluationMode c2[testCount] <- processingLibrary c3[testCount] <- paste0(description, ": ", evaluationMode, " ", processingLibrary) c4[testCount] <- ifelse(processingLibrary=="data.table", ".N", "n()") } df <- data.frame(evaluationMode=c1, processingLibrary=c2, description=c3, countFunction=c4, stringsAsFactors=FALSE) return(df) } context("EXPORT TESTS") scenarios <- testScenarios("export tests: as Matrix (without row headings)") for(i in 1:nrow(scenarios)) { if(!isDevelopmentVersion) break evaluationMode <- scenarios$evaluationMode[i] processingLibrary <- scenarios$processingLibrary[i] description <- scenarios$description[i] countFunction <- scenarios$countFunction[i] test_that(description, { library(pivottabler) pt <- PivotTable$new(processingLibrary=processingLibrary, evaluationMode=evaluationMode, compatibility=list(totalStyleIsCellStyle=TRUE, explicitHeaderSpansOfOne=TRUE, noDataGroupNBSP=TRUE)) pt$addData(bhmtrains) pt$addColumnDataGroups("TrainCategory") pt$addColumnDataGroups("PowerType") pt$addRowDataGroups("TOC") pt$defineCalculation(calculationName="TotalTrains", summariseExpression=countFunction) pt$evaluatePivot() text <- "3079 22133 5638 2137 32987 NA NA 8849 6457 15306 NA 732 NA NA 732 3079 22865 14487 8594 49025 830 63 5591 NA 6484 NA NA 28201 NA 28201 830 63 33792 NA 34685 3909 22928 48279 8594 83710" expect_equal(sum(pt$cells$asMatrix(), na.rm=TRUE), 502260) expect_equal(mean(pt$cells$asMatrix(), na.rm=TRUE), 16742) expect_equal(min(pt$cells$asMatrix(), na.rm=TRUE), 63) expect_equal(max(pt$cells$asMatrix(), na.rm=TRUE), 83710) expect_identical(paste(as.character(pt$asMatrix(includeHeaders=FALSE, rawValue=TRUE)), sep=" ", collapse=" "), text) }) } scenarios <- testScenarios("export tests: as Matrix (with row headings)") for(i in 1:nrow(scenarios)) { if(!isDevelopmentVersion) break evaluationMode <- scenarios$evaluationMode[i] processingLibrary <- scenarios$processingLibrary[i] description <- scenarios$description[i] countFunction <- scenarios$countFunction[i] test_that(description, { library(pivottabler) pt <- PivotTable$new(processingLibrary=processingLibrary, evaluationMode=evaluationMode, compatibility=list(totalStyleIsCellStyle=TRUE, explicitHeaderSpansOfOne=TRUE, noDataGroupNBSP=TRUE)) pt$addData(bhmtrains) pt$addColumnDataGroups("TrainCategory") pt$addColumnDataGroups("PowerType") pt$addRowDataGroups("TOC") pt$defineCalculation(calculationName="TotalTrains", summariseExpression=countFunction) pt$evaluatePivot() text <- " Arriva Trains Wales CrossCountry London Midland Virgin Trains Total Express Passenger DMU 3079 22133 5638 2137 32987 EMU 8849 6457 15306 HST 732 732 Total 3079 22865 14487 8594 49025 Ordinary Passenger DMU 830 63 5591 6484 EMU 28201 28201 Total 830 63 33792 34685 Total 3909 22928 48279 8594 83710" expect_identical(paste(as.character(pt$asMatrix(includeHeaders=TRUE)), sep=" ", collapse=" "), text) }) } scenarios <- testScenarios("export tests: as Data Matrix") for(i in 1:nrow(scenarios)) { evaluationMode <- scenarios$evaluationMode[i] processingLibrary <- scenarios$processingLibrary[i] description <- scenarios$description[i] countFunction <- scenarios$countFunction[i] test_that(description, { library(dplyr) library(pivottabler) data <- filter(bhmtrains, (Status=="A")|(Status=="C")) pt <- PivotTable$new(processingLibrary=processingLibrary, evaluationMode=evaluationMode, compatibility=list(noDataGroupNBSP=TRUE)) pt$addData(data) pt$addColumnDataGroups("PowerType", addTotal=FALSE) pt$addColumnDataGroups("Status", addTotal=FALSE) pt$addRowDataGroups("TOC") pt$defineCalculation(calculationName="TotalTrains", summariseExpression=countFunction) pt$evaluatePivot() text <- " DMU|A DMU|C EMU|A EMU|C HST|A HST|C Arriva Trains Wales 3833 74 NA NA NA NA CrossCountry 21621 548 NA NA 709 23 London Midland 11054 168 35930 1082 NA NA Virgin Trains 2028 107 6331 119 NA NA Total 38536 897 42261 1201 709 23" expect_identical(paste(capture.output(print(pt$asDataMatrix(separator="|"))), sep=" ", collapse=" "), text) }) } scenarios <- testScenarios("export tests: as Data Frame") for(i in 1:nrow(scenarios)) { evaluationMode <- scenarios$evaluationMode[i] processingLibrary <- scenarios$processingLibrary[i] description <- scenarios$description[i] countFunction <- scenarios$countFunction[i] test_that(description, { library(pivottabler) pt <- PivotTable$new(processingLibrary=processingLibrary, evaluationMode=evaluationMode, compatibility=list(totalStyleIsCellStyle=TRUE, explicitHeaderSpansOfOne=TRUE, noDataGroupNBSP=TRUE)) pt$addData(bhmtrains) pt$addColumnDataGroups("TrainCategory") pt$addColumnDataGroups("PowerType") pt$addRowDataGroups("TOC") pt$defineCalculation(calculationName="TotalTrains", summariseExpression=countFunction) pt$evaluatePivot() text <- "c(3079, 22133, 5638, 2137, 32987) c(NA, NA, 8849, 6457, 15306) c(NA, 732, NA, NA, 732) c(3079, 22865, 14487, 8594, 49025) c(830, 63, 5591, NA, 6484) c(NA, NA, 28201, NA, 28201) c(830, 63, 33792, NA, 34685) c(3909, 22928, 48279, 8594, 83710)" text2 <- "c(\"Arriva Trains Wales\", \"CrossCountry\", \"London Midland\", \"Virgin Trains\", \"Total\") c(3079, 22133, 5638, 2137, 32987) c(NA, NA, 8849, 6457, 15306) c(NA, 732, NA, NA, 732) c(3079, 22865, 14487, 8594, 49025) c(830, 63, 5591, NA, 6484) c(NA, NA, 28201, NA, 28201) c(830, 63, 33792, NA, 34685) c(3909, 22928, 48279, 8594, 83710)" expect_equal(sum(pt$asDataFrame(), na.rm=TRUE), 502260) expect_identical(paste(as.character(pt$asDataFrame()), sep=" ", collapse=" "), text) expect_identical(paste(as.character(pt$asDataFrame(stringsAsFactors=FALSE, rowGroupsAsColumns=TRUE)), sep=" ", collapse=" "), text2) }) } scenarios <- testScenarios("export tests: as Tidy Data Frame") for(i in 1:nrow(scenarios)) { if(!isDevelopmentVersion) break evaluationMode <- scenarios$evaluationMode[i] processingLibrary <- scenarios$processingLibrary[i] description <- scenarios$description[i] countFunction <- scenarios$countFunction[i] test_that(description, { library(pivottabler) pt <- PivotTable$new(processingLibrary=processingLibrary, evaluationMode=evaluationMode, compatibility=list(totalStyleIsCellStyle=TRUE, explicitHeaderSpansOfOne=TRUE, noDataGroupNBSP=TRUE)) pt$addData(bhmtrains) pt$addColumnDataGroups("TrainCategory") pt$addColumnDataGroups("PowerType") pt$addRowDataGroups("TOC") pt$defineCalculation(calculationName="TotalTrains", summariseExpression=countFunction) pt$evaluatePivot() text <- paste0("c(1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5) c(1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8) c(FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, TRUE, TRUE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, TRUE, TRUE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, TRUE, TRUE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE) c(\"Arriva Trains Wales\", \"Arriva Trains Wales\", \"Arriva Trains Wales\", \"Arriva Trains Wales\", \"Arriva Trains Wales\", \"Arriva Trains Wales\", \"Arriva Trains Wales\", \"Arriva Trains Wales\", \"CrossCountry\", \"CrossCountry\", \"CrossCountry\", \"CrossCountry\", \"CrossCountry\", \"CrossCountry\", \"CrossCountry\", \"CrossCountry\", \"London Midland\", \"London Midland\", \"London Midland\", \"London Midland\", \"London Midland\", \"London Midland\", \"London Midland\", \"London Midland\", \"Virgin Trains\", \"Virgin Trains\", \"Virgin Trains\", \n\"Virgin Trains\", \"Virgin Trains\", \"Virgin Trains\", \"Virgin Trains\", \"Virgin Trains\", \"Total\", \"Total\", \"Total\", \"Total\", \"Total\", \"Total\", \"Total\", \"Total\") c(\"Express Passenger\", \"Express Passenger\", \"Express Passenger\", \"Express Passenger\", \"Ordinary Passenger\", \"Ordinary Passenger\", \"Ordinary Passenger\", \"Total\", \"Express Passenger\", \"Express Passenger\", \"Express Passenger\", \"Express Passenger\", \"Ordinary Passenger\", \"Ordinary Passenger\", \"Ordinary Passenger\", \"Total\", \"Express Passenger\", \"Express Passenger\", \"Express Passenger\", \"Express Passenger\", \"Ordinary Passenger\", \"Ordinary Passenger\", \"Ordinary Passenger\", \"Total\", \"Express Passenger\", \"Express Passenger\", \n\"Express Passenger\", \"Express Passenger\", \"Ordinary Passenger\", \"Ordinary Passenger\", \"Ordinary Passenger\", \"Total\", \"Express Passenger\", \"Express Passenger\", \"Express Passenger\", \"Express Passenger\", \"Ordinary Passenger\", \"Ordinary Passenger\", \"Ordinary Passenger\", \"Total\") c(\"DMU\", \"EMU\", \"HST\", \"Total\", \"DMU\", \"EMU\", \"Total\", \"\", \"DMU\", \"EMU\", \"HST\", \"Total\", \"DMU\", \"EMU\", \"Total\", \"\", \"DMU\", \"EMU\", \"HST\", \"Total\", \"DMU\", \"EMU\", \"Total\", \"\", \"DMU\", \"EMU\", \"HST\", \"Total\", \"DMU\", \"EMU\", \"Total\", \"\", \"DMU\", \"EMU\", \"HST\", \"Total\", \"DMU\", \"EMU\", \"Total\", \"\") c(\"Arriva Trains Wales\", \"Arriva Trains Wales\", \"Arriva Trains Wales\", \"Arriva Trains Wales\", \"Arriva Trains Wales\", \"Arriva Trains Wales\", \"Arriva Trains Wales\", \"Arriva Trains Wales\", \"CrossCountry\", \"CrossCountry\", \"CrossCountry\", \"CrossCountry\", \"CrossCountry\", \"CrossCountry\", \"CrossCountry\", \"CrossCountry\", \"London Midland\", \"London Midland\", \"London Midland\", \"London Midland\", \"London Midland\", \"London Midland\", \"London Midland\", \"London Midland\", \"Virgin Trains\", \"Virgin Trains\", \"Virgin Trains\", \n\"Virgin Trains\", \"Virgin Trains\", ", "\"Virgin Trains\", \"Virgin Trains\", \"Virgin Trains\", \"NA\", \"NA\", \"NA\", \"NA\", \"NA\", \"NA\", \"NA\", \"NA\") c(\"Express Passenger\", \"Express Passenger\", \"Express Passenger\", \"Express Passenger\", \"Ordinary Passenger\", \"Ordinary Passenger\", \"Ordinary Passenger\", \"NA\", \"Express Passenger\", \"Express Passenger\", \"Express Passenger\", \"Express Passenger\", \"Ordinary Passenger\", \"Ordinary Passenger\", \"Ordinary Passenger\", \"NA\", \"Express Passenger\", \"Express Passenger\", \"Express Passenger\", \"Express Passenger\", \"Ordinary Passenger\", \"Ordinary Passenger\", \"Ordinary Passenger\", \"NA\", \"Express Passenger\", \"Express Passenger\", \n\"Express Passenger\", \"Express Passenger\", \"Ordinary Passenger\", \"Ordinary Passenger\", \"Ordinary Passenger\", \"NA\", \"Express Passenger\", \"Express Passenger\", \"Express Passenger\", \"Express Passenger\", \"Ordinary Passenger\", \"Ordinary Passenger\", \"Ordinary Passenger\", \"NA\") c(\"DMU\", \"EMU\", \"HST\", \"NA\", \"DMU\", \"EMU\", \"NA\", \"NA\", \"DMU\", \"EMU\", \"HST\", \"NA\", \"DMU\", \"EMU\", \"NA\", \"NA\", \"DMU\", \"EMU\", \"HST\", \"NA\", \"DMU\", \"EMU\", \"NA\", \"NA\", \"DMU\", \"EMU\", \"HST\", \"NA\", \"DMU\", \"EMU\", \"NA\", \"NA\", \"DMU\", \"EMU\", \"HST\", \"NA\", \"DMU\", \"EMU\", \"NA\", \"NA\") c(\"TotalTrains\", \"TotalTrains\", \"TotalTrains\", \"TotalTrains\", \"TotalTrains\", \"TotalTrains\", \"TotalTrains\", \"TotalTrains\", \"TotalTrains\", \"TotalTrains\", \"TotalTrains\", \"TotalTrains\", \"TotalTrains\", \"TotalTrains\", \"TotalTrains\", \"TotalTrains\", \"TotalTrains\", \"TotalTrains\", \"TotalTrains\", \"TotalTrains\", \"TotalTrains\", \"TotalTrains\", \"TotalTrains\", \"TotalTrains\", \"TotalTrains\", \"TotalTrains\", \"TotalTrains\", \"TotalTrains\", \"TotalTrains\", \"TotalTrains\", \"TotalTrains\", \"TotalTrains\", \"TotalTrains\", \"TotalTrains\", \n\"TotalTrains\", \"TotalTrains\", \"TotalTrains\", \"TotalTrains\", \"TotalTrains\", \"TotalTrains\") c(\"default\", \"default\", \"default\", \"default\", \"default\", \"default\", \"default\", \"default\", \"default\", \"default\", \"default\", \"default\", \"default\", \"default\", \"default\", \"default\", \"default\", \"default\", \"default\", \"default\", \"default\", \"default\", \"default\", \"default\", \"default\", \"default\", \"default\", \"default\", \"default\", \"default\", \"default\", \"default\", \"default\", \"default\", \"default\", \"default\", \"default\", \"default\", \"default\", \"default\") c(3079, NA, NA, 3079, 830, NA, 830, 3909, 22133, NA, 732, 22865, 63, NA, 63, 22928, 5638, 8849, NA, 14487, 5591, 28201, 33792, 48279, 2137, 6457, NA, 8594, NA, NA, NA, 8594, 32987, 15306, 732, 49025, 6484, 28201, 34685, 83710) c(\"3079\", NA, NA, \"3079\", \"830\", NA, \"830\", \"3909\", \"22133\", NA, \"732\", \"22865\", \"63\", NA, \"63\", \"22928\", \"5638\", \"8849\", NA, \"14487\", \"5591\", \"28201\", \"33792\", \"48279\", \"2137\", \"6457\", NA, \"8594\", NA, NA, NA, \"8594\", \"32987\", \"15306\", \"732\", \"49025\", \"6484\", \"28201\", \"34685\", \"83710\")") expect_equal(sum(pt$asTidyDataFrame()$rawValue, na.rm=TRUE), 502260) expect_identical(paste(as.character(pt$asTidyDataFrame(stringsAsFactors=FALSE)), sep=" ", collapse=" "), text) }) } scenarios <- testScenarios("export tests: NA, NaN, -Inf and Inf") for(i in 1:nrow(scenarios)) { if(!isDevelopmentVersion) break evaluationMode <- scenarios$evaluationMode[i] processingLibrary <- scenarios$processingLibrary[i] description <- scenarios$description[i] countFunction <- scenarios$countFunction[i] test_that(description, { someData <- data.frame(Colour=c("Red", "Yellow", "Green", "Blue", "White", "Black"), SomeNumber=c(1, 2, NA, NaN, -Inf, Inf)) library(pivottabler) pt <- PivotTable$new(processingLibrary=processingLibrary, evaluationMode=evaluationMode, compatibility=list(totalStyleIsCellStyle=TRUE, explicitHeaderSpansOfOne=TRUE)) pt$addData(someData) pt$addRowDataGroups("Colour") pt$defineCalculation(calculationName="Total", summariseExpression="sum(SomeNumber)") pt$evaluatePivot() html <- "<table class=\"Table\">\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\" colspan=\"1\">&nbsp;</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Total</th>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Black</th>\n <td class=\"Cell\">Inf</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Blue</th>\n <td class=\"Cell\">NaN</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Green</th>\n <td class=\"Cell\">NA</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Red</th>\n <td class=\"Cell\">1</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">White</th>\n <td class=\"Cell\">-Inf</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Yellow</th>\n <td class=\"Cell\">2</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Total</th>\n <td class=\"Cell\">NA</td>\n </tr>\n</table>" expect_identical(as.character(pt$getHtml()), html) html <- "<table class=\"Table\">\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\" colspan=\"1\">&nbsp;</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Total</th>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Black</th>\n <td class=\"Cell\"></td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Blue</th>\n <td class=\"Cell\"></td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Green</th>\n <td class=\"Cell\"></td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Red</th>\n <td class=\"Cell\">1</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">White</th>\n <td class=\"Cell\"></td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Yellow</th>\n <td class=\"Cell\">2</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Total</th>\n <td class=\"Cell\"></td>\n </tr>\n</table>" expect_identical(as.character(pt$getHtml(exportOptions=list(skipNegInf=TRUE, skipPosInf=TRUE, skipNA=TRUE, skipNaN=TRUE))), html) html <- "<table class=\"Table\">\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\" colspan=\"1\">&nbsp;</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Total</th>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Black</th>\n <td class=\"Cell\">Infinity</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Blue</th>\n <td class=\"Cell\">Not a Number</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Green</th>\n <td class=\"Cell\">Nothing</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Red</th>\n <td class=\"Cell\">1</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">White</th>\n <td class=\"Cell\">-Infinity</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Yellow</th>\n <td class=\"Cell\">2</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Total</th>\n <td class=\"Cell\">Nothing</td>\n </tr>\n</table>" expect_identical(as.character(pt$getHtml(exportOptions=list(exportNegInfAs="-Infinity", exportPosInfAs="Infinity", exportNAAs="Nothing", exportNaNAs="Not a Number"))), html) }) } basictblrversion <- utils::packageDescription("basictabler")$Version if (requireNamespace("lubridate", quietly = TRUE) && requireNamespace("basictabler", quietly = TRUE) && (numeric_version(basictblrversion) >= numeric_version("0.2.0"))) { scenarios <- testScenarios("export tests: as basictable") for(i in 1:nrow(scenarios)) { evaluationMode <- scenarios$evaluationMode[i] processingLibrary <- scenarios$processingLibrary[i] description <- scenarios$description[i] countFunction <- scenarios$countFunction[i] test_that(description, { library(pivottabler) library(basictabler) library(dplyr) library(lubridate) trains <- mutate(bhmtrains, GbttDate=if_else(is.na(GbttArrival), GbttDeparture, GbttArrival), GbttMonth=make_date(year=year(GbttDate), month=month(GbttDate), day=1)) pt <- PivotTable$new(processingLibrary=processingLibrary, evaluationMode=evaluationMode, compatibility=list(noDataGroupNBSP=TRUE)) pt$addData(trains) pt$addColumnDataGroups("GbttMonth", dataFormat=list(format="%B %Y")) pt$addColumnDataGroups("PowerType") pt$addRowDataGroups("TOC") pt$defineCalculation(calculationName="TotalTrains", summariseExpression=countFunction) pt$evaluatePivot() bt <- pt$asBasicTable() bt$cells$insertRow(5) bt$cells$setCell(5, 2, rawValue="The values below are significantly higher than expected.", styleDeclarations=list("text-align"="left", "background-color"="yellow", "font-weight"="bold", "font-style"="italic")) bt$mergeCells(rFrom=5, cFrom=2, rSpan=1, cSpan=13) bt$setStyling(rFrom=6, cFrom=2, rTo=6, cTo=14, declarations=list("text-align"="left", "background-color"="yellow")) if (numeric_version(basictblrversion) >= numeric_version("0.3.0")) { html <- "<table class=\"Table\">\n <tr>\n <th rowspan=\"2\" class=\"RowHeader\">&nbsp;</th>\n <th colspan=\"4\" class=\"ColumnHeader\">December 2016</th>\n <th colspan=\"4\" class=\"ColumnHeader\">January 2017</th>\n <th colspan=\"4\" class=\"ColumnHeader\">February 2017</th>\n <th class=\"ColumnHeader\">Total</th>\n </tr>\n <tr>\n <th class=\"ColumnHeader\">DMU</th>\n <th class=\"ColumnHeader\">EMU</th>\n <th class=\"ColumnHeader\">HST</th>\n <th class=\"ColumnHeader\">Total</th>\n <th class=\"ColumnHeader\">DMU</th>\n <th class=\"ColumnHeader\">EMU</th>\n <th class=\"ColumnHeader\">HST</th>\n <th class=\"ColumnHeader\">Total</th>\n <th class=\"ColumnHeader\">DMU</th>\n <th class=\"ColumnHeader\">EMU</th>\n <th class=\"ColumnHeader\">HST</th>\n <th class=\"ColumnHeader\">Total</th>\n <th class=\"ColumnHeader\"></th>\n </tr>\n <tr>\n <th class=\"RowHeader\">Arriva Trains Wales</th>\n <td class=\"Cell\">1291</td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Total\">1291</td>\n <td class=\"Cell\">1402</td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Total\">1402</td>\n <td class=\"Cell\">1216</td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Total\">1216</td>\n <td class=\"Total\">3909</td>\n </tr>\n <tr>\n <th class=\"RowHeader\">CrossCountry</th>\n <td class=\"Cell\">7314</td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\">236</td>\n <td class=\"Total\">7550</td>\n <td class=\"Cell\">7777</td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\">256</td>\n <td class=\"Total\">8033</td>\n <td class=\"Cell\">7105</td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\">240</td>\n <td class=\"Total\">7345</td>\n <td class=\"Total\">22928</td>\n </tr>\n <tr>\n <th class=\"RowHeader\"></th>\n <td colspan=\"13\" class=\"Cell\" style=\"text-align: left; background-color: yellow; font-weight: bold; font-style: italic; \">The values below are significantly higher than expected.</td>\n </tr>\n <tr>\n <th class=\"RowHeader\">London Midland</th>\n <td class=\"Cell\" style=\"text-align: left; background-color: yellow; \">3635</td>\n <td class=\"Cell\" style=\"text-align: left; background-color: yellow; \">11967</td>\n <td class=\"Cell\" style=\"text-align: left; background-color: yellow; \"></td>\n <td class=\"Total\" style=\"text-align: left; background-color: yellow; \">15602</td>\n <td class=\"Cell\" style=\"text-align: left; background-color: yellow; \">3967</td>\n <td class=\"Cell\" style=\"text-align: left; background-color: yellow; \">13062</td>\n <td class=\"Cell\" style=\"text-align: left; background-color: yellow; \"></td>\n <td class=\"Total\" style=\"text-align: left; background-color: yellow; \">17029</td>\n <td class=\"Cell\" style=\"text-align: left; background-color: yellow; \">3627</td>\n <td class=\"Cell\" style=\"text-align: left; background-color: yellow; \">12021</td>\n <td class=\"Cell\" style=\"text-align: left; background-color: yellow; \"></td>\n <td class=\"Total\" style=\"text-align: left; background-color: yellow; \">15648</td>\n <td class=\"Total\" style=\"text-align: left; background-color: yellow; \">48279</td>\n </tr>\n <tr>\n <th class=\"RowHeader\">Virgin Trains</th>\n <td class=\"Cell\">740</td>\n <td class=\"Cell\">2137</td>\n <td class=\"Cell\"></td>\n <td class=\"Total\">2877</td>\n <td class=\"Cell\">728</td>\n <td class=\"Cell\">2276</td>\n <td class=\"Cell\"></td>\n <td class=\"Total\">3004</td>\n <td class=\"Cell\">669</td>\n <td class=\"Cell\">2044</td>\n <td class=\"Cell\"></td>\n <td class=\"Total\">2713</td>\n <td class=\"Total\">8594</td>\n </tr>\n <tr>\n <th class=\"RowHeader\">Total</th>\n <td class=\"Total\">12980</td>\n <td class=\"Total\">14104</td>\n <td class=\"Total\">236</td>\n <td class=\"Total\">27320</td>\n <td class=\"Total\">13874</td>\n <td class=\"Total\">15338</td>\n <td class=\"Total\">256</td>\n <td class=\"Total\">29468</td>\n <td class=\"Total\">12617</td>\n <td class=\"Total\">14065</td>\n <td class=\"Total\">240</td>\n <td class=\"Total\">26922</td>\n <td class=\"Total\">83710</td>\n </tr>\n</table>" css <- ".Table {display: table; border-collapse: collapse; }\r\n.ColumnHeader {font-family: Arial; font-size: 0.75em; border: 1px solid lightgray; vertical-align: middle; font-weight: bold; background-color: } else { html <- "<table class=\"Table\">\n <tr>\n <td rowspan=\"2\" colspan=\"1\" class=\"RowHeader\"></td>\n <td rowspan=\"1\" colspan=\"4\" class=\"ColumnHeader\">December 2016</td>\n <td rowspan=\"1\" colspan=\"4\" class=\"ColumnHeader\">January 2017</td>\n <td rowspan=\"1\" colspan=\"4\" class=\"ColumnHeader\">February 2017</td>\n <td class=\"ColumnHeader\">Total</td>\n </tr>\n <tr>\n <td class=\"ColumnHeader\">DMU</td>\n <td class=\"ColumnHeader\">EMU</td>\n <td class=\"ColumnHeader\">HST</td>\n <td class=\"ColumnHeader\">Total</td>\n <td class=\"ColumnHeader\">DMU</td>\n <td class=\"ColumnHeader\">EMU</td>\n <td class=\"ColumnHeader\">HST</td>\n <td class=\"ColumnHeader\">Total</td>\n <td class=\"ColumnHeader\">DMU</td>\n <td class=\"ColumnHeader\">EMU</td>\n <td class=\"ColumnHeader\">HST</td>\n <td class=\"ColumnHeader\">Total</td>\n <td class=\"ColumnHeader\"></td>\n </tr>\n <tr>\n <td class=\"RowHeader\">Arriva Trains Wales</td>\n <td class=\"Cell\">1291</td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Total\">1291</td>\n <td class=\"Cell\">1402</td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Total\">1402</td>\n <td class=\"Cell\">1216</td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Total\">1216</td>\n <td class=\"Total\">3909</td>\n </tr>\n <tr>\n <td class=\"RowHeader\">CrossCountry</td>\n <td class=\"Cell\">7314</td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\">236</td>\n <td class=\"Total\">7550</td>\n <td class=\"Cell\">7777</td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\">256</td>\n <td class=\"Total\">8033</td>\n <td class=\"Cell\">7105</td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\">240</td>\n <td class=\"Total\">7345</td>\n <td class=\"Total\">22928</td>\n </tr>\n <tr>\n <td class=\"RowHeader\"></td>\n <td rowspan=\"1\" colspan=\"13\" class=\"Cell\" style=\"text-align: left; background-color: yellow; font-weight: bold; font-style: italic; \">The values below are significantly higher than expected.</td>\n </tr>\n <tr>\n <td class=\"RowHeader\">London Midland</td>\n <td class=\"Cell\" style=\"text-align: left; background-color: yellow; \">3635</td>\n <td class=\"Cell\" style=\"text-align: left; background-color: yellow; \">11967</td>\n <td class=\"Cell\" style=\"text-align: left; background-color: yellow; \"></td>\n <td class=\"Total\" style=\"text-align: left; background-color: yellow; \">15602</td>\n <td class=\"Cell\" style=\"text-align: left; background-color: yellow; \">3967</td>\n <td class=\"Cell\" style=\"text-align: left; background-color: yellow; \">13062</td>\n <td class=\"Cell\" style=\"text-align: left; background-color: yellow; \"></td>\n <td class=\"Total\" style=\"text-align: left; background-color: yellow; \">17029</td>\n <td class=\"Cell\" style=\"text-align: left; background-color: yellow; \">3627</td>\n <td class=\"Cell\" style=\"text-align: left; background-color: yellow; \">12021</td>\n <td class=\"Cell\" style=\"text-align: left; background-color: yellow; \"></td>\n <td class=\"Total\" style=\"text-align: left; background-color: yellow; \">15648</td>\n <td class=\"Total\" style=\"text-align: left; background-color: yellow; \">48279</td>\n </tr>\n <tr>\n <td class=\"RowHeader\">Virgin Trains</td>\n <td class=\"Cell\">740</td>\n <td class=\"Cell\">2137</td>\n <td class=\"Cell\"></td>\n <td class=\"Total\">2877</td>\n <td class=\"Cell\">728</td>\n <td class=\"Cell\">2276</td>\n <td class=\"Cell\"></td>\n <td class=\"Total\">3004</td>\n <td class=\"Cell\">669</td>\n <td class=\"Cell\">2044</td>\n <td class=\"Cell\"></td>\n <td class=\"Total\">2713</td>\n <td class=\"Total\">8594</td>\n </tr>\n <tr>\n <td class=\"RowHeader\">Total</td>\n <td class=\"Total\">12980</td>\n <td class=\"Total\">14104</td>\n <td class=\"Total\">236</td>\n <td class=\"Total\">27320</td>\n <td class=\"Total\">13874</td>\n <td class=\"Total\">15338</td>\n <td class=\"Total\">256</td>\n <td class=\"Total\">29468</td>\n <td class=\"Total\">12617</td>\n <td class=\"Total\">14065</td>\n <td class=\"Total\">240</td>\n <td class=\"Total\">26922</td>\n <td class=\"Total\">83710</td>\n </tr>\n</table>" css <- ".Table {display: table; border-collapse: collapse; }\r\n.ColumnHeader {font-family: Arial; font-size: 0.75em; border: 1px solid lightgray; vertical-align: middle; font-weight: bold; background-color: } expect_identical(as.character(bt$getHtml()), html) expect_identical(bt$getCss(), css) }) } } basictblrversion <- utils::packageDescription("basictabler")$Version if (requireNamespace("basictabler", quietly = TRUE) && (numeric_version(basictblrversion) >= numeric_version("0.3.0"))) { scenarios <- testScenarios("export tests: same html for pivottable and basictable") for(i in 1:nrow(scenarios)) { if(!isDevelopmentVersion) break evaluationMode <- scenarios$evaluationMode[i] processingLibrary <- scenarios$processingLibrary[i] description <- scenarios$description[i] countFunction <- scenarios$countFunction[i] test_that(description, { library(pivottabler) library(basictabler) pt <- qpvt(bhmtrains, "TOC", "TrainCategory", "n()", compatibility=list(noDataGroupNBSP=TRUE)) pthtml <- as.character(pt$getHtml()) ptcss <- as.character(pt$getCss()) bt <- pt$asBasicTable() bthtml <- as.character(bt$getHtml()) btcss <- as.character(bt$getCss()) exppthtml <- "<table class=\"Table\">\n <tr>\n <th class=\"RowHeader\">&nbsp;</th>\n <th class=\"ColumnHeader\">Express Passenger</th>\n <th class=\"ColumnHeader\">Ordinary Passenger</th>\n <th class=\"ColumnHeader\">Total</th>\n </tr>\n <tr>\n <th class=\"RowHeader\">Arriva Trains Wales</th>\n <td class=\"Cell\">3079</td>\n <td class=\"Cell\">830</td>\n <td class=\"Total\">3909</td>\n </tr>\n <tr>\n <th class=\"RowHeader\">CrossCountry</th>\n <td class=\"Cell\">22865</td>\n <td class=\"Cell\">63</td>\n <td class=\"Total\">22928</td>\n </tr>\n <tr>\n <th class=\"RowHeader\">London Midland</th>\n <td class=\"Cell\">14487</td>\n <td class=\"Cell\">33792</td>\n <td class=\"Total\">48279</td>\n </tr>\n <tr>\n <th class=\"RowHeader\">Virgin Trains</th>\n <td class=\"Cell\">8594</td>\n <td class=\"Cell\"></td>\n <td class=\"Total\">8594</td>\n </tr>\n <tr>\n <th class=\"RowHeader\">Total</th>\n <td class=\"Total\">49025</td>\n <td class=\"Total\">34685</td>\n <td class=\"Total\">83710</td>\n </tr>\n</table>" expptcss <- ".Table {display: table; border-collapse: collapse; }\r\n.ColumnHeader {font-family: Arial; font-size: 0.75em; border: 1px solid lightgray; vertical-align: middle; font-weight: bold; background-color: expbthtml <- "<table class=\"Table\">\n <tr>\n <th class=\"RowHeader\">&nbsp;</th>\n <th class=\"ColumnHeader\">Express Passenger</th>\n <th class=\"ColumnHeader\">Ordinary Passenger</th>\n <th class=\"ColumnHeader\">Total</th>\n </tr>\n <tr>\n <th class=\"RowHeader\">Arriva Trains Wales</th>\n <td class=\"Cell\">3079</td>\n <td class=\"Cell\">830</td>\n <td class=\"Total\">3909</td>\n </tr>\n <tr>\n <th class=\"RowHeader\">CrossCountry</th>\n <td class=\"Cell\">22865</td>\n <td class=\"Cell\">63</td>\n <td class=\"Total\">22928</td>\n </tr>\n <tr>\n <th class=\"RowHeader\">London Midland</th>\n <td class=\"Cell\">14487</td>\n <td class=\"Cell\">33792</td>\n <td class=\"Total\">48279</td>\n </tr>\n <tr>\n <th class=\"RowHeader\">Virgin Trains</th>\n <td class=\"Cell\">8594</td>\n <td class=\"Cell\"></td>\n <td class=\"Total\">8594</td>\n </tr>\n <tr>\n <th class=\"RowHeader\">Total</th>\n <td class=\"Total\">49025</td>\n <td class=\"Total\">34685</td>\n <td class=\"Total\">83710</td>\n </tr>\n</table>" expbtcss <- ".Table {display: table; border-collapse: collapse; }\r\n.ColumnHeader {font-family: Arial; font-size: 0.75em; border: 1px solid lightgray; vertical-align: middle; font-weight: bold; background-color: htmlMatch <- pthtml==bthtml cssMatch <- ptcss==btcss expect_identical(pthtml, exppthtml) expect_identical(ptcss, expptcss) expect_identical(bthtml, expbthtml) expect_identical(btcss, expbtcss) expect_identical(htmlMatch, TRUE) expect_identical(cssMatch, TRUE) }) } } basictblrversion <- utils::packageDescription("basictabler")$Version if (requireNamespace("lubridate", quietly = TRUE) && requireNamespace("basictabler", quietly = TRUE) && (numeric_version(basictblrversion) >= numeric_version("0.2.0"))) { scenarios <- testScenarios("export tests: basictable with row group headings") for(i in 1:nrow(scenarios)) { if(!isDevelopmentVersion) break evaluationMode <- scenarios$evaluationMode[i] processingLibrary <- scenarios$processingLibrary[i] description <- scenarios$description[i] countFunction <- scenarios$countFunction[i] test_that(description, { library(dplyr) library(lubridate) library(pivottabler) trains <- mutate(bhmtrains, GbttDate=if_else(is.na(GbttArrival), GbttDeparture, GbttArrival), GbttMonth=make_date(year=year(GbttDate), month=month(GbttDate), day=1)) trains <- filter(trains, GbttMonth>=make_date(year=2017, month=1, day=1)) pt <- PivotTable$new(processingLibrary=processingLibrary, evaluationMode=evaluationMode, compatibility=list(noDataGroupNBSP=TRUE)) pt$addData(trains) pt$addColumnDataGroups("GbttMonth", dataFormat=list(format="%B %Y")) pt$addColumnDataGroups("PowerType") pt$addRowDataGroups("TOC", header="Train Company", addTotal=FALSE) pt$addRowDataGroups("TrainCategory", header="Train Category", addTotal=FALSE) pt$defineCalculation(calculationName="TotalTrains", summariseExpression=countFunction) pt$theme <- getStandardTableTheme(pt) pt$evaluatePivot() bt <- pt$asBasicTable(showRowGroupHeaders=TRUE) if (numeric_version(basictblrversion) >= numeric_version("0.3.0")) { html <- "<table class=\"Table\">\n <tr>\n <th rowspan=\"2\" class=\"LeftColumnHeader\">Train Company</th>\n <th rowspan=\"2\" class=\"LeftColumnHeader\">Train Category</th>\n <th colspan=\"4\" class=\"CentreColumnHeader\">January 2017</th>\n <th colspan=\"4\" class=\"CentreColumnHeader\">February 2017</th>\n <th class=\"CentreColumnHeader\">Total</th>\n </tr>\n <tr>\n <th class=\"CentreColumnHeader\">DMU</th>\n <th class=\"CentreColumnHeader\">EMU</th>\n <th class=\"CentreColumnHeader\">HST</th>\n <th class=\"CentreColumnHeader\">Total</th>\n <th class=\"CentreColumnHeader\">DMU</th>\n <th class=\"CentreColumnHeader\">EMU</th>\n <th class=\"CentreColumnHeader\">HST</th>\n <th class=\"CentreColumnHeader\">Total</th>\n <th class=\"CentreColumnHeader\"></th>\n </tr>\n <tr>\n <th rowspan=\"2\" class=\"LeftCell\">Arriva Trains Wales</th>\n <th class=\"LeftCell\">Express Passenger</th>\n <td class=\"RightCell\">1088</td>\n <td class=\"RightCell\"></td>\n <td class=\"RightCell\"></td>\n <td class=\"Total\">1088</td>\n <td class=\"RightCell\">974</td>\n <td class=\"RightCell\"></td>\n <td class=\"RightCell\"></td>\n <td class=\"Total\">974</td>\n <td class=\"Total\">2062</td>\n </tr>\n <tr>\n <th class=\"LeftCell\">Ordinary Passenger</th>\n <td class=\"RightCell\">314</td>\n <td class=\"RightCell\"></td>\n <td class=\"RightCell\"></td>\n <td class=\"Total\">314</td>\n <td class=\"RightCell\">242</td>\n <td class=\"RightCell\"></td>\n <td class=\"RightCell\"></td>\n <td class=\"Total\">242</td>\n <td class=\"Total\">556</td>\n </tr>\n <tr>\n <th rowspan=\"2\" class=\"LeftCell\">CrossCountry</th>\n <th class=\"LeftCell\">Express Passenger</th>\n <td class=\"RightCell\">7755</td>\n <td class=\"RightCell\"></td>\n <td class=\"RightCell\">256</td>\n <td class=\"Total\">8011</td>\n <td class=\"RightCell\">7085</td>\n <td class=\"RightCell\"></td>\n <td class=\"RightCell\">240</td>\n <td class=\"Total\">7325</td>\n <td class=\"Total\">15336</td>\n </tr>\n <tr>\n <th class=\"LeftCell\">Ordinary Passenger</th>\n <td class=\"RightCell\">22</td>\n <td class=\"RightCell\"></td>\n <td class=\"RightCell\"></td>\n <td class=\"Total\">22</td>\n <td class=\"RightCell\">20</td>\n <td class=\"RightCell\"></td>\n <td class=\"RightCell\"></td>\n <td class=\"Total\">20</td>\n <td class=\"Total\">42</td>\n </tr>\n <tr>\n <th rowspan=\"2\" class=\"LeftCell\">London Midland</th>\n <th class=\"LeftCell\">Express Passenger</th>\n <td class=\"RightCell\">1956</td>\n <td class=\"RightCell\">3108</td>\n <td class=\"RightCell\"></td>\n <td class=\"Total\">5064</td>\n <td class=\"RightCell\">1793</td>\n <td class=\"RightCell\">2879</td>\n <td class=\"RightCell\"></td>\n <td class=\"Total\">4672</td>\n <td class=\"Total\">9736</td>\n </tr>\n <tr>\n <th class=\"LeftCell\">Ordinary Passenger</th>\n <td class=\"RightCell\">2011</td>\n <td class=\"RightCell\">9954</td>\n <td class=\"RightCell\"></td>\n <td class=\"Total\">11965</td>\n <td class=\"RightCell\">1834</td>\n <td class=\"RightCell\">9142</td>\n <td class=\"RightCell\"></td>\n <td class=\"Total\">10976</td>\n <td class=\"Total\">22941</td>\n </tr>\n <tr>\n <th class=\"LeftCell\">Virgin Trains</th>\n <th class=\"LeftCell\">Express Passenger</th>\n <td class=\"RightCell\">728</td>\n <td class=\"RightCell\">2276</td>\n <td class=\"RightCell\"></td>\n <td class=\"Total\">3004</td>\n <td class=\"RightCell\">669</td>\n <td class=\"RightCell\">2044</td>\n <td class=\"RightCell\"></td>\n <td class=\"Total\">2713</td>\n <td class=\"Total\">5717</td>\n </tr>\n</table>" css <- ".Table {display: table; border-collapse: collapse; }\r\n.LeftColumnHeader {font-family: Arial; font-size: 0.75em; padding: 2px; border: 1px solid lightgray; vertical-align: middle; font-weight: bold; background-color: expect_identical(as.character(bt$getHtml()), html) expect_identical(bt$getCss(), css) } else { expect_identical(1, 1) } }) } }
hache.barycenter <- function(ratios, weights, xreg, method, tol, maxit, echo) { weights.s <- rowSums(weights, na.rm = TRUE) has.data <- which(weights.s > 0) ncontracts <- nrow(ratios) eff.ncontracts <- length(has.data) p <- ncol(xreg) n <- nrow(xreg) w <- colSums(weights, na.rm = TRUE)/sum(weights.s) Xqr <- qr(xreg * sqrt(w)) R <- qr.R(Xqr) x <- qr.Q(Xqr) / sqrt(w) f <- function(i) { z <- if (i %in% has.data) { y <- ratios[i, ] not.na <- !is.na(y) lm.wfit(x[not.na, , drop = FALSE], y[not.na], weights[i, not.na]) } else lm.fit(x, rep.int(0, n)) z[c("coefficients", "residuals", "weights", "rank", "qr")] } fits <- lapply(seq_len(ncontracts), f) ind <- sapply(fits, coef) ind[is.na(ind)] <- 0 S <- function(z) { nQr <- NROW(z$qr$qr) rank <- z$rank r <- z$residuals w <- z$weights sum(w * r^2) / (nQr - rank) } sigma2 <- sapply(fits[has.data], S) sigma2[is.nan(sigma2)] <- 0 cred <- W <- array(0, c(p, p, ncontracts)) A <- W.s <- matrix(0, p, p) coll <- numeric(p) W[1, 1, ] <- weights.s for (i in 2:p) W[i, i, has.data] <- colSums(t(weights[has.data, ]) * x[, i]^2, na.rm = TRUE) s2 <- mean(sigma2) do.iter <- method == "iterative" && diff(range(weights, na.rm = TRUE)) > .Machine$double.eps^0.5 for (i in seq_len(p)) { a <- A[i, i] <- bvar.unbiased(ind[i, has.data], W[i, i, has.data], s2, eff.ncontracts) if (do.iter) { a <- A[i, i] <- if (a > 0) bvar.iterative(ind[i, has.data], W[i, i, has.data], s2, eff.ncontracts, start = a, tol = tol, maxit = maxit, echo = echo) else 0 } if (a > 0) { z <- cred[i, i, has.data] <- 1/(1 + s2/(W[i, i, has.data] * a)) z. <- W.s[i, i] <- sum(z) coll[i] <- drop(crossprod(z, ind[i, has.data])) / z. } else { w <- W[i, i, has.data] w. <- W.s[i, i] <- sum(w) coll[i] <- drop(crossprod(w, ind[i, ])) / w. } } for (i in seq_len(ncontracts)) fits[[i]]$coefficients <- coll + drop(cred[, , i] %*% (ind[, i] - coll)) names(coll) <- rownames(ind) list(means = list(coll, ind), weights = list(W.s, W), unbiased = if (method == "unbiased") list(A, s2), iterative = if (method == "iterative") list(A, s2), cred = cred, nodes = list(ncontracts), adj.models = fits, transition = R) }
completeWord <- function(tree, string){ UseMethod("completeWord",tree) }
listn <- function(...) { input <- sapply(match.call(), deparse)[-1] if (is.null(names(input))) { names(input) <- rep("", times=length(input)) } names(input) <- ifelse(names(input)=="", input, names(input)) listWithName <- list(...) names(listWithName) <- names(input) return(listWithName) }
data('ARG_TRE', package = 'sapfluxnetr') data('ARG_MAZ', package = 'sapfluxnetr') data('AUS_CAN_ST2_MIX', package = 'sapfluxnetr') test_that("sfn_filter returns correct results", { foo_timestamp <- get_timestamp(ARG_TRE) foo_timestamp_trimmed <- foo_timestamp[1:100] foo_solar_timestamp <- get_solar_timestamp(ARG_TRE) foo_solar_timestamp_trimmed <- foo_solar_timestamp[1:100] ws_threshold <- 25 foo_subset <- sfn_filter(ARG_TRE, TIMESTAMP %in% foo_timestamp_trimmed) foo_subset_2 <- sfn_filter(ARG_TRE, ws <= ws_threshold) foo_subset_3 <- sfn_filter( ARG_TRE, TIMESTAMP %in% foo_solar_timestamp_trimmed, solar = TRUE ) multi_sfn <- sfn_data_multi(ARG_TRE, ARG_MAZ) multi_sfn_filter <- sfn_filter( multi_sfn, dplyr::between(lubridate::day(TIMESTAMP), 19, 23) ) multi_sfn_filter_2 <- sfn_filter(multi_sfn, ws <= ws_threshold) multi_sfn_2 <- sfn_data_multi(ARG_TRE, ARG_MAZ, AUS_CAN_ST2_MIX) suppressWarnings(multi_sfn_filter_3 <- sfn_filter( multi_sfn_2, dplyr::between(lubridate::year(TIMESTAMP), 1998, 1999) )) suppressWarnings(multi_sfn_filter_4 <- sfn_filter( multi_sfn_2, dplyr::between(lubridate::year(TIMESTAMP), 2008, 2009) )) suppressWarnings(multi_sfn_filter_5 <- sfn_filter( multi_sfn_2, dplyr::between(lubridate::year(TIMESTAMP), 2006, 2007) )) expect_s4_class(foo_subset, 'sfn_data') expect_length(get_solar_timestamp(foo_subset), 100) expect_s4_class(foo_subset_2, 'sfn_data') expect_true(all(get_env_data(foo_subset_2)[['ws']] <= 25)) expect_length(get_solar_timestamp(foo_subset_2), 212) expect_s4_class(foo_subset_3, 'sfn_data') expect_length(get_solar_timestamp(foo_subset_3), 100) expect_identical(foo_subset, foo_subset_3) expect_s4_class(multi_sfn_filter, 'sfn_data_multi') expect_length(multi_sfn_filter, 2) expect_s4_class(multi_sfn_filter[[1]], 'sfn_data') expect_s4_class(multi_sfn_filter[[2]], 'sfn_data') expect_length(get_timestamp(multi_sfn_filter[[1]]), 24*5) expect_length(get_timestamp(multi_sfn_filter[[2]]), 24*5) expect_s4_class(multi_sfn_filter_2, 'sfn_data_multi') expect_length(multi_sfn_filter_2, 2) expect_s4_class(multi_sfn_filter_2[[1]], 'sfn_data') expect_s4_class(multi_sfn_filter_2[[2]], 'sfn_data') expect_length(get_solar_timestamp(multi_sfn_filter_2[[1]]), 212) expect_length(get_solar_timestamp(multi_sfn_filter_2[[2]]), 210) expect_s4_class(multi_sfn_filter_3, 'sfn_data_multi') expect_length(multi_sfn_filter_3, 0) expect_warning( sfn_filter( multi_sfn_2, dplyr::between(lubridate::year(TIMESTAMP), 1998, 1999) ), 'Any sites met the criteria, returning empty results' ) expect_s4_class(multi_sfn_filter_4, 'sfn_data_multi') expect_length(multi_sfn_filter_4, 2) expect_warning( sfn_filter( multi_sfn_2, dplyr::between(lubridate::year(TIMESTAMP), 2008, 2009) ), 'AUS_CAN_ST2_MIX' ) expect_s4_class(multi_sfn_filter_5, 'sfn_data_multi') expect_length(multi_sfn_filter_5, 1) expect_warning( sfn_filter( multi_sfn_2, dplyr::between(lubridate::year(TIMESTAMP), 2006, 2007) ), 'ARG_TRE' ) }) test_that('sfn_mutate returns correct results', { foo_mutated <- sfn_mutate(ARG_TRE, ws = dplyr::if_else(ws > 25, NA_real_, ws)) multi_sfn <- sfn_data_multi(ARG_TRE, ARG_MAZ, AUS_CAN_ST2_MIX) multi_mutated <- sfn_mutate( multi_sfn, ws = dplyr::if_else(ws > 25, NA_real_, ws) ) expect_s4_class(foo_mutated, 'sfn_data') expect_equal(sum(is.na(get_env_data(foo_mutated)[['ws']])), 100) expect_match(get_env_flags(foo_mutated)[['ws']], 'USER_MODF', all = TRUE) expect_match(get_env_flags(foo_mutated)[['ws']], 'RANGE_WARN', all = FALSE) expect_equal(sum(is.na(get_env_data(foo_mutated)[['ta']])), 0) expect_failure( expect_match(get_env_flags(foo_mutated)[['ta']], 'USER_MODF', all = TRUE) ) expect_identical(attr(get_timestamp(foo_mutated), 'tz'), 'Etc/GMT+3') expect_identical(attr(get_solar_timestamp(foo_mutated), 'tz'), 'UTC') expect_s4_class(multi_mutated, 'sfn_data_multi') expect_length(multi_mutated, 3) expect_s4_class(multi_mutated[[1]], 'sfn_data') expect_s4_class(multi_mutated[[2]], 'sfn_data') expect_s4_class(multi_mutated[[3]], 'sfn_data') expect_identical(attr(get_timestamp(multi_mutated[[1]]), 'tz'), 'Etc/GMT+3') expect_identical(attr(get_solar_timestamp(multi_mutated[[1]]), 'tz'), 'UTC') expect_identical(attr(get_timestamp(multi_mutated[[2]]), 'tz'), 'Etc/GMT+3') expect_identical(attr(get_solar_timestamp(multi_mutated[[2]]), 'tz'), 'UTC') expect_identical(attr(get_timestamp(multi_mutated[[3]]), 'tz'), 'Etc/GMT-10') expect_identical(attr(get_solar_timestamp(multi_mutated[[3]]), 'tz'), 'UTC') expect_equal(sum(is.na(get_env_data(multi_mutated[[1]])[['ws']])), 100) expect_match(get_env_flags(multi_mutated[[1]])[['ws']], 'USER_MODF', all = TRUE) expect_match(get_env_flags(multi_mutated[[1]])[['ws']], 'RANGE_WARN', all = FALSE) expect_equal(sum(is.na(get_env_data(multi_mutated[[2]])[['ws']])), 78) expect_match(get_env_flags(multi_mutated[[2]])[['ws']], 'USER_MODF', all = TRUE) expect_match(get_env_flags(multi_mutated[[2]])[['ws']], 'RANGE_WARN', all = FALSE) expect_failure( expect_match(get_env_flags(multi_mutated[[3]])[['ws']], 'USER_MODF', all = TRUE) ) expect_match(get_env_flags(multi_mutated[[3]])[['ws']], 'OUT_WARN', all = FALSE) expect_identical(multi_sfn[['AUS_CAN_ST2_MIX']], multi_mutated[['AUS_CAN_ST2_MIX']]) }) test_that('sfn_mutate_at returns correct results', { vars_to_mutate <- names(get_sapf_data(ARG_TRE)[,-1]) foo_mutated <- sfn_mutate_at( ARG_TRE, .vars = dplyr::vars(dplyr::one_of(vars_to_mutate)), .funs = list( ~ dplyr::case_when( ws > 25 ~ NA_real_, TRUE ~ . ) ) ) vars_to_not_mutate <- names(get_env_data(ARG_TRE)) multi_sfn <- sfn_data_multi(ARG_TRE, ARG_MAZ, AUS_CAN_ST2_MIX) multi_mutated <- suppressWarnings(sfn_mutate_at( multi_sfn, .vars = dplyr::vars(-dplyr::one_of(vars_to_not_mutate)), .funs = list( ~ dplyr::case_when( ws > 25 ~ NA_real_, TRUE ~ . ) ) )) expect_s4_class(foo_mutated, 'sfn_data') expect_equal(sum(is.na(get_sapf_data(foo_mutated)[[2]])), 100) expect_equal(sum(is.na(get_sapf_data(foo_mutated)[[3]])), 100) expect_equal(sum(is.na(get_sapf_data(foo_mutated)[[4]])), 100) expect_equal(sum(is.na(get_sapf_data(foo_mutated)[[5]])), 100) expect_match(get_sapf_flags(foo_mutated)[[2]], 'USER_MODF', all = TRUE) expect_match(get_sapf_flags(foo_mutated)[[3]], 'USER_MODF', all = TRUE) expect_match(get_sapf_flags(foo_mutated)[[4]], 'USER_MODF', all = TRUE) expect_match(get_sapf_flags(foo_mutated)[[5]], 'USER_MODF', all = TRUE) expect_s4_class(multi_mutated, 'sfn_data_multi') expect_length(multi_mutated, 3) expect_s4_class(multi_mutated[[1]], 'sfn_data') expect_s4_class(multi_mutated[[2]], 'sfn_data') expect_s4_class(multi_mutated[[3]], 'sfn_data') expect_equal(sum(is.na(get_sapf_data(multi_mutated[[1]])[[2]])), 100) expect_equal(sum(is.na(get_sapf_data(multi_mutated[[1]])[[3]])), 100) expect_equal(sum(is.na(get_sapf_data(multi_mutated[[1]])[[4]])), 100) expect_equal(sum(is.na(get_sapf_data(multi_mutated[[1]])[[5]])), 100) expect_equal(sum(is.na(get_sapf_data(multi_mutated[[2]])[[2]])), 78) expect_equal(sum(is.na(get_sapf_data(multi_mutated[[2]])[[3]])), 78) expect_equal(sum(is.na(get_sapf_data(multi_mutated[[2]])[[4]])), 78) expect_equal(sum(is.na(get_sapf_data(multi_mutated[[2]])[[5]])), 78) expect_match(get_sapf_flags(multi_mutated[[1]])[[2]], 'USER_MODF', all = TRUE) expect_match(get_sapf_flags(multi_mutated[[1]])[[3]], 'USER_MODF', all = TRUE) expect_match(get_sapf_flags(multi_mutated[[1]])[[4]], 'USER_MODF', all = TRUE) expect_match(get_sapf_flags(multi_mutated[[1]])[[5]], 'USER_MODF', all = TRUE) expect_match(get_sapf_flags(multi_mutated[[2]])[[2]], 'USER_MODF', all = TRUE) expect_match(get_sapf_flags(multi_mutated[[2]])[[3]], 'USER_MODF', all = TRUE) expect_match(get_sapf_flags(multi_mutated[[2]])[[4]], 'USER_MODF', all = TRUE) expect_match(get_sapf_flags(multi_mutated[[2]])[[5]], 'USER_MODF', all = TRUE) expect_failure( expect_match(get_sapf_flags(multi_mutated[[3]])[[2]], 'USER_MODF', all = TRUE) ) expect_failure( expect_match(get_sapf_flags(multi_mutated[[3]])[[3]], 'USER_MODF', all = TRUE) ) expect_failure( expect_match(get_sapf_flags(multi_mutated[[3]])[[4]], 'USER_MODF', all = TRUE) ) expect_failure( expect_match(get_sapf_flags(multi_mutated[[3]])[[5]], 'USER_MODF', all = TRUE) ) expect_identical(multi_sfn[['AUS_CAN_ST2_MIX']], multi_mutated[['AUS_CAN_ST2_MIX']]) })
single_realtime_station <- function(station_number) { if (!is.null(station_number)) { sym_STATION_NUMBER <- sym("STATION_NUMBER") if (any(tidyhydat::allstations$STATION_NUMBER %in% station_number)) { choose_df <- dplyr::filter(tidyhydat::allstations, !!sym_STATION_NUMBER %in% station_number) STATION_NUMBER_SEL <- choose_df$STATION_NUMBER PROV <- choose_df$PROV_TERR_STATE_LOC } else { choose_df <- dplyr::filter(realtime_stations(), !!sym_STATION_NUMBER %in% station_number) STATION_NUMBER_SEL <- choose_df$STATION_NUMBER PROV <- choose_df$PROV_TERR_STATE_LOC } } base_url <- "https://dd.weather.gc.ca/hydrometric" type <- c("hourly", "daily") url <- sprintf("%s/csv/%s/%s", base_url, PROV, type) infile <- sprintf( "%s/%s_%s_%s_hydrometric.csv", url, PROV, STATION_NUMBER_SEL, type ) colHeaders <- c( "STATION_NUMBER", "Date", "Level", "Level_GRADE", "Level_SYMBOL", "Level_CODE", "Flow", "Flow_GRADE", "Flow_SYMBOL", "Flow_CODE" ) url_check <- httr::GET(infile[1], httr::user_agent("https://github.com/ropensci/tidyhydat")) if (httr::http_error(url_check) == TRUE) { info(paste0("No hourly data found for ", STATION_NUMBER_SEL)) h <- dplyr::tibble( A = STATION_NUMBER_SEL, B = NA, C = NA, D = NA, E = NA, F = NA, G = NA, H = NA, I = NA, J = NA ) colnames(h) <- colHeaders } else { h <- httr::content( url_check, type = "text/csv", encoding = "UTF-8", skip = 1, col_names = colHeaders, col_types = readr::cols( STATION_NUMBER = readr::col_character(), Date = readr::col_datetime(), Level = readr::col_double(), Level_GRADE = readr::col_character(), Level_SYMBOL = readr::col_character(), Level_CODE = readr::col_integer(), Flow = readr::col_double(), Flow_GRADE = readr::col_character(), Flow_SYMBOL = readr::col_character(), Flow_CODE = readr::col_integer() ) ) } url_check_d <- httr::GET(infile[2], httr::user_agent("https://github.com/ropensci/tidyhydat")) if (httr::http_error(url_check_d) == TRUE) { info(paste0("No daily data found for ", STATION_NUMBER_SEL)) d <- dplyr::tibble( A = STATION_NUMBER_SEL, B = NA, C = NA, D = NA, E = NA, F = NA, G = NA, H = NA, I = NA, J = NA ) colnames(d) <- colHeaders } else { d <- httr::content( url_check_d, type = "text/csv", encoding = "UTF-8", skip = 1, col_names = colHeaders, col_types = readr::cols( STATION_NUMBER = readr::col_character(), Date = readr::col_datetime(), Level = readr::col_double(), Level_GRADE = readr::col_character(), Level_SYMBOL = readr::col_character(), Level_CODE = readr::col_integer(), Flow = readr::col_double(), Flow_GRADE = readr::col_character(), Flow_SYMBOL = readr::col_character(), Flow_CODE = readr::col_integer() ) ) } p <- dplyr::filter(d, .data$Date < min(h$Date)) output <- dplyr::bind_rows(p, h) realtime_tidy_data(output, PROV) } all_realtime_station <- function(PROV){ base_url <- "https://dd.weather.gc.ca/hydrometric/csv/" prov_url <- paste0(base_url, PROV,"/daily/",PROV,"_daily_hydrometric.csv") res <- httr::GET(prov_url, httr::progress("down"), httr::user_agent("https://github.com/ropensci/tidyhydat")) httr::stop_for_status(res) colHeaders <- c( "STATION_NUMBER", "Date", "Level", "Level_GRADE", "Level_SYMBOL", "Level_CODE", "Flow", "Flow_GRADE", "Flow_SYMBOL", "Flow_CODE" ) output <- httr::content( res, type = "text/csv", encoding = "UTF-8", skip = 1, col_names = colHeaders, col_types = readr::cols( STATION_NUMBER = readr::col_character(), Date = readr::col_datetime(), Level = readr::col_double(), Level_GRADE = readr::col_character(), Level_SYMBOL = readr::col_character(), Level_CODE = readr::col_integer(), Flow = readr::col_double(), Flow_GRADE = readr::col_character(), Flow_SYMBOL = readr::col_character(), Flow_CODE = readr::col_integer() ) ) realtime_tidy_data(output, PROV) } realtime_tidy_data <- function(data, prov){ sym_temp <- sym("temp") sym_val <- sym("val") sym_key <- sym("key") data <- dplyr::rename(data, `Level_` = .data$Level, `Flow_` = .data$Flow) data <- tidyr::gather(data, !!sym_temp, !!sym_val, -.data$STATION_NUMBER, -.data$Date) data <- tidyr::separate(data, !!sym_temp, c("Parameter", "key"), sep = "_", remove = TRUE) data <- dplyr::mutate(data, key = ifelse(.data$key == "", "Value", .data$key)) data <- tidyr::spread(data, !!sym_key, !!sym_val) data <- dplyr::rename(data, Code = .data$CODE, Grade = .data$GRADE, Symbol = .data$SYMBOL) data <- dplyr::mutate(data, PROV_TERR_STATE_LOC = prov) data <- dplyr::select( data, .data$STATION_NUMBER, .data$PROV_TERR_STATE_LOC, .data$Date, .data$Parameter, .data$Value, .data$Grade, .data$Symbol, .data$Code ) data <- dplyr::arrange(data, .data$Parameter, .data$STATION_NUMBER, .data$Date) data$Value <- as.numeric(data$Value) data } has_internet <- function() { z <- try(suppressWarnings(readLines('https://www.google.ca', n = 1)), silent = TRUE) !inherits(z, "try-error") }
optimize_knots <- function(lambda, rho, alpha, gams, d, n.ints, n.nodes, natural){ c.alpha <- stats::qnorm(1 - alpha/2) start <- standard_CI(d, n.ints, alpha) low <- c(rep(-100, n.ints - 1), rep(0.5, n.ints)) up <- c(rep(100, n.ints - 1), rep(200, n.ints)) obj_fun <- functional::Curry(objective, lambda = lambda, d = d, n.ints = n.ints, n.nodes = n.nodes, alpha = alpha, natural = natural) cons_fun <- functional::Curry(constraints_slsqp_gausslegendre, gams = gams, rho = rho, d = d, n.ints = n.ints, alpha = alpha, n.nodes = n.nodes, natural = natural) res <- nloptr::slsqp(start, obj_fun, hin = cons_fun, lower = low, upper = up, nl.info = FALSE) new.par <- res$par out <- new.par }
knitr::opts_chunk$set( message = FALSE, digits = 3, collapse = TRUE, comment = " ) options(digits = 3) library(tidymodels) library(tidymodels) tag_show()
context("tinter") test_that("package", { expect_length(tinter("blue", 10, 1, adjust = 0.2), 19) expect_length(tinter("blue", 10, 1, "shades", adjust = 0.1), 10) expect_length(tinter("blue", 10, 1, "tints", adjust = 0.2), 10) expect_true(" expect_false(" expect_false(" expect_true(" expect_true(" expect_true(" expect_true(" expect_is(tinter("blue"), "character") expect_length(darken(tinter("blue"), amount = 0.1), 9L) expect_length(lighten(tinter("blue"), amount = 0.1), 9L) })
setMethod("residuals", "lavaan", function(object, type = "raw", labels = TRUE) { type <- tolower(type) if(type %in% c("casewise","case","obs","observations","ov")) { return( lav_residuals_casewise(object, labels = labels) ) } else { out <- lav_residuals(object = object, type = type, h1 = TRUE, add.type = TRUE, rename.cov.cor = FALSE, add.labels = labels, add.class = TRUE, drop.list.single.group = TRUE) } out }) setMethod("resid", "lavaan", function(object, type = "raw") { residuals(object, type = type, labels = TRUE) }) lavResiduals <- function(object, type = "cor.bentler", custom.rmr = NULL, se = FALSE, zstat = TRUE, summary = TRUE, h1.acov = "unstructured", add.type = TRUE, add.labels = TRUE, add.class = TRUE, drop.list.single.group = TRUE, maximum.number = length(res.vech), output = "list") { out <- lav_residuals(object = object, type = type, h1 = TRUE, custom.rmr = custom.rmr, se = se, zstat = zstat, summary = summary, summary.options = list(se = TRUE, zstat = TRUE, pvalue = TRUE, unbiased = TRUE, unbiased.se = TRUE, unbiased.ci = TRUE, unbiased.ci.level = 0.90, unbiased.zstat = TRUE, unbiased.test.val = 0.05, unbiased.pvalue = TRUE), h1.acov = h1.acov, add.type = add.type, add.labels = add.labels, add.class = add.class, drop.list.single.group = drop.list.single.group) if(output == "table") { res <- out$cov res.vech <- lav_matrix_vech(res, diagonal = FALSE) P <- nrow(res) NAMES <- colnames(res) nam <- expand.grid(NAMES, NAMES)[lav_matrix_vech_idx(P, diagonal = FALSE),] NAMES.vech <- paste(nam[,1], "~~", nam[,2], sep = "") TAB <- data.frame(name = NAMES.vech, res = round(res.vech, 3), stringsAsFactors = FALSE) idx <- sort.int(abs(TAB$res), decreasing = TRUE, index.return = TRUE)$ix out.sorted <- TAB[idx,] if(maximum.number == 0L || maximum.number > length(res.vech)) { maximum.number <- length(res.vech) } out <- out.sorted[seq_len(maximum.number), ] } else { } out } lav_residuals <- function(object, type = "raw", h1 = TRUE, custom.rmr = NULL, se = FALSE, zstat = FALSE, summary = FALSE, summary.options = list(se = TRUE, zstat = TRUE, pvalue = TRUE, unbiased = TRUE, unbiased.se = TRUE, unbiased.ci = TRUE, unbiased.ci.level = 0.90, unbiased.zstat = FALSE, unbiased.test.val = 0.05, unbiased.pvalue = FALSE), h1.acov = "unstructured", add.type = FALSE, rename.cov.cor = FALSE, add.labels = FALSE, add.class = FALSE, drop.list.single.group = FALSE) { type <- tolower(type)[1] if(!type %in% c("raw", "cor", "cor.bollen", "cor.bentler", "cor.eqs", "rmr", "srmr", "crmr", "normalized", "standardized", "standardized.mplus")) { stop("lavaan ERROR: unknown argument for type: ", dQuote(type)) } if(type == "cor") { if(object@Options$mimic == "EQS") { type <- "cor.bentler" } else { type <- "cor.bollen" } } if(type == "cor.eqs") { type <- "cor.bentler" } if(type == "rmr") { type <- "raw" } if(type == "srmr") { type <- "cor.bentler" } if(type == "crmr") { type <- "cor.bollen" } lavdata <- object@Data lavmodel <- object@Model if(lavmodel@categorical) { if([email protected] || length(unlist([email protected])) > 0L) { zstat <- se <- FALSE summary <- FALSE summary.options <- list(se = FALSE, zstat = FALSE, pvalue = FALSE, unbiased = FALSE, unbiased.se = FALSE, unbiased.ci = FALSE, unbiased.ci.level = 0.90, unbiased.zstat = FALSE, unbiased.test.val = 0.05, unbiased.pvalue = FALSE) } } if(!lavmodel@categorical && [email protected]) { zstat <- se <- FALSE summary <- FALSE summary.options <- list(se = FALSE, zstat = FALSE, pvalue = FALSE, unbiased = FALSE, unbiased.se = FALSE, unbiased.ci = FALSE, unbiased.ci.level = 0.90, unbiased.zstat = FALSE, unbiased.test.val = 0.05, unbiased.pvalue = FALSE) } obsList <- lav_object_inspect_sampstat(object, h1 = h1, add.labels = add.labels, add.class = add.class, drop.list.single.group = FALSE) estList <- lav_object_inspect_implied(object, add.labels = add.labels, add.class = add.class, drop.list.single.group = FALSE) nblocks <- length(obsList) if(type %in% c("cor.bentler", "cor.bollen")) { for(b in seq_len(nblocks)) { var.obs <- if([email protected]) { diag(obsList[[b]][["res.cov"]]) } else { diag(obsList[[b]][["cov"]]) } var.est <- if([email protected]) { diag(estList[[b]][["res.cov"]]) } else { diag(estList[[b]][["cov"]]) } obsList[[b]] <- lav_residuals_rescale(x = obsList[[b]], diag.cov = var.obs) if(type == "cor.bentler") { estList[[b]] <- lav_residuals_rescale(x = estList[[b]], diag.cov = var.obs) } else if(type == "cor.bollen") { estList[[b]] <- lav_residuals_rescale(x = estList[[b]], diag.cov = var.est, diag.cov2 = var.obs) } } } resList <- vector("list", length = nblocks) for(b in seq_len(nblocks)) { resList[[b]] <- lapply(seq_len(length(obsList[[b]])), FUN = function(el) { obsList[[b]][[el]] - estList[[b]][[el]]}) NAMES <- names(obsList[[b]]) names(resList[[b]]) <- NAMES } if(se || zstat) { seList <- lav_residuals_se(object, type = type, z.type = "standardized", h1.acov = h1.acov, add.class = add.class, add.labels = add.labels) } else if(type %in% c("normalized", "standardized", "standardized.mplus")) { seList <- lav_residuals_se(object, type = "raw", z.type = type, h1.acov = h1.acov, add.class = add.class, add.labels = add.labels) } else { seList <- NULL } if(type %in% c("normalized", "standardized", "standardized.mplus")) { for(b in seq_len(nblocks)) { if(add.labels) { NAMES <- names(resList[[b]]) } resList[[b]] <- lapply(seq_len(length(resList[[b]])), FUN = function(el) { A <- resList[[b]][[el]] B <- seList[[b]][[el]] near.zero.idx <- which(abs(A) < 1e-05) if(length(near.zero.idx) > 0L) { B[near.zero.idx] <- 1 } A/B }) if(add.labels) { names(resList[[b]]) <- NAMES } } } resList.orig <- resList if(se) { for(b in seq_len(nblocks)) { NAMES.res <- names(resList[[b]]) NAMES.se <- paste0(NAMES.res, ".se") resList[[b]] <- c(resList[[b]], seList[[b]]) names(resList[[b]]) <- c(NAMES.res, NAMES.se) } } if(zstat) { for(b in seq_len(nblocks)) { NAMES.res <- names(resList[[b]]) NAMES.z <- paste0(names(resList.orig[[b]]), ".z") tmp <- lapply(seq_len(length(resList.orig[[b]])), FUN = function(el) { A <- resList.orig[[b]][[el]] B <- seList[[b]][[el]] near.zero.idx <- which(abs(A) < 1e-04) if(length(near.zero.idx) > 0L) { B[near.zero.idx] <- 1.0 } A/B }) resList[[b]] <- c(resList[[b]], tmp) names(resList[[b]]) <- c(NAMES.res, NAMES.z) } } if(summary) { args <- c(list(object = object, type = type, h1.acov = h1.acov, add.class = add.class, custom.rmr = custom.rmr), summary.options) sumStat <- do.call("lav_residuals_summary", args) for(b in seq_len(nblocks)) { NAMES <- names(resList[[b]]) resList[[b]] <- c(resList[[b]], list(sumStat[[b]][[1]])) NAMES <- c(NAMES, "summary") names(resList[[b]]) <- NAMES } } if(add.type) { for(b in seq_len(nblocks)) { NAMES <- names(resList[[b]]) resList[[b]] <- c(type, resList[[b]]) NAMES <- c("type", NAMES) names(resList[[b]]) <- NAMES } } if(rename.cov.cor && type %in% c("cor.bentler", "cor.bollen")) { for(b in seq_len(nblocks)) { NAMES <- names(resList[[b]]) NAMES <- gsub("cov", "cor", NAMES) names(resList[[b]]) <- NAMES } } OUT <- resList if(nblocks == 1L && drop.list.single.group) { OUT <- OUT[[1]] } else { if(lavdata@nlevels == 1L && length([email protected]) > 0L) { names(OUT) <- unlist([email protected]) } else if(lavdata@nlevels > 1L && length([email protected]) == 0L) { names(OUT) <- [email protected] } } OUT } lav_residuals_acov <- function(object, type = "raw", z.type = "standardized", h1.acov = "unstructured") { if(z.type %in% c("normalized", "standardized.mplus") && type != "raw") { stop("lavaan ERROR: z.type = ", dQuote(z.type), " can only be used ", "with type = ", dQuote("raw")) } lavdata <- object@Data lavmodel <- object@Model lavsamplestats <- object@SampleStats ACOV.res <- vector("list", length = lavdata@ngroups) if(lavmodel@categorical) { NACOV.obs <- lavsamplestats@NACOV ACOV.obs <- lapply(NACOV.obs, function(x) x / lavsamplestats@ntotal) } else { ACOV.obs <- lav_model_h1_acov(lavobject = object, h1.information = h1.acov) } if(z.type == "normalized") { ACOV.res <- ACOV.obs return(ACOV.res) } else { if(z.type == "standardized") { A1 <- lav_model_h1_information(object) if(lavmodel@estimator == "DWLS" || lavmodel@estimator == "ULS") { A1 <- lapply(A1, diag) } if(type %in% c("cor.bentler", "cor.bollen")) { sampstat <- lavTech(object, "sampstat") } } else if(z.type == "standardized.mplus") { VCOV <- lavTech(object, "vcov") } DELTA <- lavTech(object, "delta") } for(g in seq_len(lavdata@ngroups)) { gw <- object@SampleStats@nobs[[g]] / object@SampleStats@ntotal if(z.type == "standardized.mplus") { ACOV.est.g <- DELTA[[g]] %*% VCOV %*% t(DELTA[[g]]) ACOV.res[[g]] <- ACOV.obs[[g]] - ACOV.est.g } else if(z.type == "standardized") { this.options <- object@Options this.options$observed.information[1] <- "h1" A0.g.inv <- lav_model_information(lavmodel = lavmodel, lavsamplestats = object@SampleStats, lavdata = lavdata, lavcache = object@Cache, lavimplied = object@implied, lavh1 = object@h1, lavoptions = this.options, extra = FALSE, augmented = TRUE, inverted = TRUE, use.ginv = TRUE) ACOV.est.g <- gw * (DELTA[[g]] %*% A0.g.inv %*% t(DELTA[[g]])) Q <- diag(nrow = nrow(ACOV.est.g)) - ACOV.est.g %*% A1[[g]] ACOV.res[[g]] <- Q %*% ACOV.obs[[g]] %*% t(Q) if(type == "cor.bentler") { if(lavmodel@categorical) { if([email protected] || length(unlist([email protected])) > 0L) { stop("lavaan ERROR: SE for cor.bentler not available (yet) if categorical = TRUE, and conditional.x = TRUE OR some endogenous variables are continuous") } else { } } else { COV <- if([email protected]) { sampstat[[g]][["res.cov"]] } else { sampstat[[g]][["cov"]] } SS <- 1/sqrt(diag(COV)) tmp <- lav_matrix_vech(tcrossprod(SS)) G.inv.sqrt <- diag( tmp, nrow = length(tmp) ) if(lavmodel@meanstructure) { GG <- lav_matrix_bdiag(diag(SS, nrow = length(SS)), G.inv.sqrt) } else { GG <- G.inv.sqrt } ACOV.res[[g]] <- GG %*% ACOV.res[[g]] %*% GG } } else if(type == "cor.bollen") { if(lavmodel@categorical) { if([email protected] || length(unlist([email protected])) > 0L) { stop("lavaan ERROR: SE for cor.bentler not available (yet) if categorical = TRUE, and conditional.x = TRUE OR some endogenous variables are continuous") } else { } } else { COV <- if([email protected]) { sampstat[[g]][["res.cov"]] } else { sampstat[[g]][["cov"]] } F1 <- lav_deriv_cov2corB(COV) if(lavmodel@meanstructure) { SS <- 1/sqrt(diag(COV)) FF <- lav_matrix_bdiag(diag(SS, nrow = length(SS)), F1) } else { FF <- F1 } ACOV.res[[g]] <- FF %*% ACOV.res[[g]] %*% t(FF) } } } } ACOV.res } lav_residuals_se <- function(object, type = "raw", z.type = "standardized", h1.acov = "unstructured", add.class = FALSE, add.labels = FALSE) { lavdata <- object@Data lavmodel <- object@Model lavpta <- object@pta seList <- vector("list", length = lavdata@ngroups) ACOV.res <- lav_residuals_acov(object = object, type = type, z.type = z.type, h1.acov = h1.acov) if(add.labels) { ov.names <- object@pta$vnames$ov ov.names.res <- object@pta$vnames$ov.nox ov.names.x <- object@pta$vnames$ov.x } for(g in seq_len(lavdata@ngroups)) { nvar <- object@pta$nvar[[g]] diag.ACOV <- diag(ACOV.res[[g]]) diag.ACOV[!is.finite(diag.ACOV)] <- NA diag.ACOV[ diag.ACOV < 0 ] <- NA if(lavmodel@categorical) { if([email protected] || length(unlist([email protected])) > 0L) { stop("not ready yet!") } nth <- length([email protected][[g]]) tmp <- sqrt(diag.ACOV[-(1:nth)]) cov.se <- lav_matrix_vech_reverse(tmp, diagonal = FALSE) mean.se <- rep(as.numeric(NA), nth) th.se <- sqrt(diag.ACOV[1:nth]) if(add.class) { class(cov.se) <- c("lavaan.matrix.symmetric", "matrix") class(mean.se) <- c("lavaan.vector", "numeric") class(th.se) <- c("lavaan.vector", "numeric") } if(add.labels) { rownames(cov.se) <- colnames(cov.se) <- ov.names[[g]] names(mean.se) <- ov.names[[g]] names(th.se) <- lavpta$vnames$th.mean[[g]] } seList[[g]] <- list(cov.se = cov.se, mean.se = mean.se, th.se = th.se) } else if(lavdata@nlevels == 1L) { if([email protected]) { stop("not ready yet") } else { if(lavmodel@meanstructure) { tmp <- sqrt(diag.ACOV[-(1:nvar)]) cov.se <- lav_matrix_vech_reverse(tmp) mean.se <- sqrt(diag.ACOV[1:nvar]) if(add.class) { class(cov.se) <- c("lavaan.matrix.symmetric", "matrix") class(mean.se) <- c("lavaan.vector", "numeric") } if(add.labels) { rownames(cov.se) <- colnames(cov.se) <- ov.names[[g]] names(mean.se) <- ov.names[[g]] } seList[[g]] <- list(cov.se = cov.se, mean.se = mean.se) } else { cov.se <- lav_matrix_vech_reverse(sqrt(diag.ACOV)) if(add.class) { class(cov.se) <- c("lavaan.matrix.symmetric", "matrix") } if(add.labels) { rownames(cov.se) <- colnames(cov.se) <- ov.names[[g]] } seList[[g]] <- list(cov.se = cov.se) } } } else if(lavdata@nlevels > 1L) { stop("not ready yet") } } seList } lav_residuals_summary <- function(object, type = c("rmr", "srmr", "crmr"), h1.acov = "unstructured", custom.rmr = NULL, se = FALSE, zstat = FALSE, pvalue = FALSE, unbiased = FALSE, unbiased.se = FALSE, unbiased.ci = FALSE, unbiased.ci.level = 0.90, unbiased.zstat = FALSE, unbiased.test.val = 0.05, unbiased.pvalue = FALSE, add.class = FALSE) { if (length(custom.rmr)) { if (!is.list(custom.rmr)) stop('custom.rmr must be a list') customNAMES <- names(custom.rmr) if (is.null(customNAMES)) stop('custom.rmr list must have names') if (length(unique(customNAMES)) < length(custom.rmr)) { stop('custom.rmr must have a unique name for each summary') } for (i in seq_along(custom.rmr)) { if (!is.list(custom.rmr[[i]])) { stop('Each element in custom.rmr must be a list') } if (is.null(names(custom.rmr[[i]]))) { stop('The list in custom.rmr must have names') } if (!all(names(custom.rmr[[i]]) %in% c("cov","mean"))) { stop('Elements in custom.rmr must be names "cov" and/or "mean"') } } } else { customNAMES <- NULL } if(pvalue) { zstat <- TRUE } if(zstat) { se <- TRUE } if(unbiased.pvalue) { unbiased.zstat <- TRUE } if(unbiased.zstat) { unbiased.se <- TRUE } if(!all(type %in% c("rmr", "srmr", "crmr", "raw", "cor.bentler", "cor.bollen"))) { stop("lavaan ERROR: unknown type: ", dQuote(type)) } idx <- which(type == "raw") if(length(idx) > 0L) { type[idx] <- "rmr" } idx <- which(type == "cor.bentler") if(length(idx) > 0L) { type[idx] <- "srmr" } idx <- which(type == "cor.bollen") if(length(idx) > 0L) { type[idx] <- "crmr" } lavdata <- object@Data lavmodel <- object@Model rmrFlag <- srmrFlag <- crmrFlag <- FALSE if("rmr" %in% type || "raw" %in% type) { rmrList <- lav_residuals(object = object, type = "raw") if(se || unbiased) { rmrList.se <- lav_residuals_acov(object = object, type = "raw", z.type = "standardized", h1.acov = "unstructured") } } if("srmr" %in% type || "cor.bentler" %in% type || "cor" %in% type) { srmrList <- lav_residuals(object = object, type = "cor.bentler") if(se || unbiased) { srmrList.se <- lav_residuals_acov(object = object, type = "cor.bentler", z.type = "standardized", h1.acov = "unstructured") } } if("crmr" %in% type || "cor.bollen" %in% type) { crmrList <- lav_residuals(object = object, type = "cor.bollen") if(se || unbiased) { crmrList.se <- lav_residuals_acov(object = object, type = "cor.bollen", z.type = "standardized", h1.acov = "unstructured") } } sumStat <- vector("list", length = lavdata@ngroups) for(g in seq_len(lavdata@ngroups)) { nvar <- object@pta$nvar[[g]] if(lavdata@nlevels == 1L && lavmodel@categorical) { if([email protected] || length(unlist([email protected])) > 0L) { stop("not ready yet") } else { OUT <- vector("list", length(type)) names(OUT) <- type for(typ in seq_len(length(type))) { if(type[typ] == "rmr") { rmsList.g <- rmrList[[g]] if(se || unbiased) { rmsList.se.g <- rmrList.se[[g]] } } else if(type[typ] == "srmr") { rmsList.g <- srmrList[[g]] if(se || unbiased) { rmsList.se.g <- srmrList.se[[g]] } } else if(type[typ] == "crmr") { rmsList.g <- crmrList[[g]] if(se || unbiased) { rmsList.se.g <- crmrList.se[[g]] } } nth <- length([email protected][[g]]) STATS <- lav_matrix_vech(rmsList.g[["cov"]], diagonal = FALSE) if(type == "crmr") { pstar <- length(STATS) } else { pstar <- length(STATS) + nvar } ACOV <- NULL if(se || unbiased) { ACOV <- rmsList.se.g[-seq_len(nth), -seq_len(nth), drop = FALSE] } RMS.COR <- lav_residuals_summary_rms(STATS = STATS, ACOV = ACOV, se = se, zstat = zstat, pvalue = pvalue, unbiased = unbiased, unbiased.se = unbiased.se, unbiased.ci = unbiased.ci, unbiased.ci.level = unbiased.ci.level, unbiased.zstat = unbiased.zstat, unbiased.test.val = unbiased.test.val, unbiased.pvalue = unbiased.pvalue, pstar = pstar, type = type[typ]) STATS <- rmsList.g[["th"]] pstar <- length(STATS) ACOV <- NULL if(se || unbiased) { ACOV <- rmsList.se.g[seq_len(nth), seq_len(nth), drop = FALSE] } RMS.TH <- lav_residuals_summary_rms(STATS = STATS, ACOV = ACOV, se = se, zstat = zstat, pvalue = pvalue, unbiased = unbiased, unbiased.se = unbiased.se, unbiased.ci = unbiased.ci, unbiased.ci.level = unbiased.ci.level, unbiased.zstat = unbiased.zstat, unbiased.test.val = unbiased.test.val, unbiased.pvalue = unbiased.pvalue, pstar = pstar, type = type[typ]) STATS <- numeric(0L) pstar <- length(STATS) ACOV <- NULL if(se || unbiased) { } RMS.MEAN <- lav_residuals_summary_rms(STATS = STATS, ACOV = ACOV, se = se, zstat = zstat, pvalue = pvalue, unbiased = unbiased, unbiased.se = unbiased.se, unbiased.ci = unbiased.ci, unbiased.ci.level = unbiased.ci.level, unbiased.zstat = unbiased.zstat, unbiased.test.val = unbiased.test.val, unbiased.pvalue = unbiased.pvalue, pstar = pstar, type = type[typ]) STATS <- numeric(0L) pstar <- length(STATS) ACOV <- NULL if(se || unbiased) { } RMS.VAR <- lav_residuals_summary_rms(STATS = STATS, ACOV = ACOV, se = se, zstat = zstat, pvalue = pvalue, unbiased = unbiased, unbiased.se = unbiased.se, unbiased.ci = unbiased.ci, unbiased.ci.level = unbiased.ci.level, unbiased.zstat = unbiased.zstat, unbiased.test.val = unbiased.test.val, unbiased.pvalue = unbiased.pvalue, pstar = pstar, type = type[typ]) STATS <- c(lav_matrix_vech(rmsList.g[["cov"]], diagonal = FALSE), rmsList.g[["th"]]) pstar <- length(STATS) ACOV <- NULL if(se || unbiased) { ACOV <- rmsList.se.g } RMS.TOTAL <- lav_residuals_summary_rms(STATS = STATS, ACOV = ACOV, se = se, zstat = zstat, pvalue = pvalue, unbiased = unbiased, unbiased.se = unbiased.se, unbiased.ci = unbiased.ci, unbiased.ci.level = unbiased.ci.level, unbiased.zstat = unbiased.zstat, unbiased.test.val = unbiased.test.val, unbiased.pvalue = unbiased.pvalue, pstar = pstar, type = type[typ]) TABLE <- as.data.frame(cbind(RMS.COR, RMS.TH, RMS.TOTAL)) colnames(TABLE) <- c("cor", "thresholds", "total") if(add.class) { class(TABLE) <- c("lavaan.data.frame", "data.frame") } OUT[[typ]] <- TABLE } } } else if(lavdata@nlevels == 1L) { if([email protected]) { stop("not ready yet") } else { nvar.x <- pstar.x <- 0L if([email protected]) { nvar.x <- lavmodel@nexo[g] pstar.x <- nvar.x * (nvar.x + 1) / 2 } OUT <- vector("list", length(type)) names(OUT) <- type for(typ in seq_len(length(type))) { if(type[typ] == "rmr") { rmsList.g <- rmrList[[g]] if(se || unbiased) { rmsList.se.g <- rmrList.se[[g]] } } else if(type[typ] == "srmr") { rmsList.g <- srmrList[[g]] if(se || unbiased) { rmsList.se.g <- srmrList.se[[g]] } } else if(type[typ] == "crmr") { rmsList.g <- crmrList[[g]] if(se || unbiased) { rmsList.se.g <- crmrList.se[[g]] } } STATS <- lav_matrix_vech(rmsList.g[["cov"]]) pstar <- ( length(STATS) - pstar.x ) if(type[typ] == "crmr") { pstar <- pstar - ( nvar - nvar.x ) } ACOV <- NULL if(se || unbiased) { ACOV <- if(lavmodel@meanstructure) { rmsList.se.g[-seq_len(nvar), -seq_len(nvar), drop = FALSE] } else { rmsList.se.g } } RMS.COV <- lav_residuals_summary_rms(STATS = STATS, ACOV = ACOV, se = se, zstat = zstat, pvalue = pvalue, unbiased = unbiased, unbiased.se = unbiased.se, unbiased.ci = unbiased.ci, unbiased.ci.level = unbiased.ci.level, unbiased.zstat = unbiased.zstat, unbiased.test.val = unbiased.test.val, unbiased.pvalue = unbiased.pvalue, pstar = pstar, type = type[typ]) if(lavmodel@meanstructure) { STATS <- rmsList.g[["mean"]] pstar <- ( length(STATS) - nvar.x ) ACOV <- NULL if(se || unbiased) { ACOV <- rmsList.se.g[seq_len(nvar), seq_len(nvar), drop = FALSE] } RMS.MEAN <- lav_residuals_summary_rms(STATS = STATS, ACOV = ACOV, se = se, zstat = zstat, pvalue = pvalue, unbiased = unbiased, unbiased.se = unbiased.se, unbiased.ci = unbiased.ci, unbiased.ci.level = unbiased.ci.level, unbiased.zstat = unbiased.zstat, unbiased.test.val = unbiased.test.val, unbiased.pvalue = unbiased.pvalue, pstar = pstar, type = type[typ]) } if(lavmodel@meanstructure) { STATS <- c(rmsList.g[["mean"]], lav_matrix_vech(rmsList.g[["cov"]])) pstar <- ( length(STATS) - ( pstar.x + nvar.x) ) if(type[typ] == "crmr") { pstar <- pstar - ( nvar - nvar.x ) } ACOV <- NULL if(se || unbiased) { ACOV <- rmsList.se.g } RMS.TOTAL <- lav_residuals_summary_rms(STATS = STATS, ACOV = ACOV, se = se, zstat = zstat, pvalue = pvalue, unbiased = unbiased, unbiased.se = unbiased.se, unbiased.ci = unbiased.ci, unbiased.ci.level = unbiased.ci.level, unbiased.zstat = unbiased.zstat, unbiased.test.val = unbiased.test.val, unbiased.pvalue = unbiased.pvalue, pstar = pstar, type = type[typ]) } if (length(custom.rmr)) { if ([email protected] && [email protected]) { x.idx <- which(rownames(rmsList.g$cov) %in% object@[email protected][[g]]) } RMS.CUSTOM.LIST <- vector("list", length(customNAMES)) for (cus in customNAMES) { STATS <- NULL ACOV.idx <- NULL if (lavmodel@meanstructure) { if ("mean" %in% names(custom.rmr[[cus]])) { if (is.logical(custom.rmr[[cus]]$mean)) { if (length(custom.rmr[[cus]]$mean) != length(rmsList.g[["mean"]])) { stop('length(custom.rmr$', cus, '$mean) must ', 'match length(lavResiduals(fit)$mean)') } ACOV.idx <- which(custom.rmr[[cus]]$mean) if ([email protected] && [email protected]) { ACOV.idx[x.idx] <- FALSE } } else if (!is.numeric(custom.rmr[[cus]]$mean)) { stop('custom.rmr$', cus, '$mean must contain ', 'logical or numeric indices.') } else { ACOV.idx <- custom.rmr[[cus]]$mean if ([email protected] && [email protected]) { ACOV.idx <- setdiff(ACOV.idx, x.idx) } ACOV.idx <- ACOV.idx[!is.na(ACOV.idx)] if (max(ACOV.idx) > length(rmsList.g[["mean"]])) { stop('custom.rmr$', cus, '$mean[', which.max(ACOV.idx), '] is an out-of-bounds index') } } STATS <- rmsList.g[["mean"]][ACOV.idx] } } if ("cov" %in% names(custom.rmr[[cus]])) { if (is.numeric(custom.rmr[[cus]]$cov)) { cusCOV <- rmsList.g[["cov"]] == "start with all FALSE" if (length(dim(custom.rmr[[cus]]$cov))) { if (max(custom.rmr[[cus]]$cov[,1:2] > nrow(rmsList.g[["cov"]]))) { stop('numeric indices in custom.rmr$', cus, '$cov', ' cannot exceed ', nrow(rmsList.g[["cov"]])) } for (RR in 1:nrow(custom.rmr[[cus]]$cov)) { cusCOV[ custom.rmr[[cus]]$cov[RR, 1] , custom.rmr[[cus]]$cov[RR, 2] ] <- TRUE } } else { if (max(custom.rmr[[cus]]$cov > length(rmsList.g[["cov"]]))) { stop('numeric indices in custom.rmr$', cus, '$cov', ' cannot exceed ', length(rmsList.g[["cov"]])) } cusCOV[custom.rmr[[cus]]$cov] <- TRUE } custom.rmr[[cus]]$cov <- cusCOV } else if (!is.logical(custom.rmr[[cus]]$cov)) { stop('custom.rmr$', cus, '$cov must be a logical ', 'square matrix or a numeric matrix of ', '(row/column) indices.') } if (!all(dim(custom.rmr[[cus]]$cov) == dim(rmsList.g[["cov"]]))) { stop('dim(custom.rmr$', cus, '$cov) must ', 'match dim(lavResiduals(fit)$cov)') } custom.rmr[[cus]]$cov <- custom.rmr[[cus]]$cov | t(custom.rmr[[cus]]$cov) custom.rmr[[cus]]$cov[upper.tri(custom.rmr[[cus]]$cov)] <- FALSE if (type[typ] == "crmr") diag(custom.rmr[[cus]]$cov) <- FALSE vech.idx <- which(lav_matrix_vech(custom.rmr[[cus]]$cov)) STATS <- c(STATS, lav_matrix_vech(rmsList.g[["cov"]])[vech.idx]) ACOV.idx <- c(ACOV.idx, vech.idx) } pstar <- length(STATS) ACOV <- NULL if (se || unbiased) { ACOV <- rmsList.se.g[ACOV.idx, ACOV.idx, drop = FALSE] } RMS.CUSTOM.LIST[[cus]] <- lav_residuals_summary_rms(STATS = STATS, ACOV = ACOV, se = se, zstat = zstat, pvalue = pvalue, unbiased = unbiased, unbiased.se = unbiased.se, unbiased.ci = unbiased.ci, unbiased.ci.level = unbiased.ci.level, unbiased.zstat = unbiased.zstat, unbiased.test.val = unbiased.test.val, unbiased.pvalue = unbiased.pvalue, pstar = pstar, type = type[typ]) } RMS.CUSTOM <- do.call(rbind, RMS.CUSTOM.LIST) } else { RMS.CUSTOM <- NULL } if(lavmodel@meanstructure) { TABLE <- as.data.frame(cbind(RMS.COV, RMS.MEAN, RMS.TOTAL, RMS.CUSTOM)) colnames(TABLE) <- c("cov", "mean", "total", customNAMES) } else { TABLE <- as.data.frame(cbind(RMS.COV, RMS.CUSTOM)) colnames(TABLE) <- c("cov", customNAMES) } if(add.class) { class(TABLE) <- c("lavaan.data.frame", "data.frame") } OUT[[typ]] <- TABLE } } } else if(lavdata@nlevels > 1L) { stop("not ready yet") } sumStat[[g]] <- OUT } sumStat } lav_residuals_summary_rms <- function(STATS = NULL, ACOV = NULL, se = FALSE, level = 0.90, zstat = FALSE, pvalue = FALSE, unbiased = FALSE, unbiased.se = FALSE, unbiased.ci = FALSE, unbiased.ci.level = 0.90, unbiased.zstat = FALSE, unbiased.test.val = 0.05, unbiased.pvalue = FALSE, pstar = 0, type = "rms") { OUT <- vector("list", length = 0L) if(length(STATS) > 0L) { rms <- sqrt(sum(STATS * STATS)/pstar) } else { rms <- 0 se <- unbiased <- zstat <- FALSE } rms.se <- rms.z <- rms.pvalue <- NULL urms <- urms.se <- urms.z <- urms.pvalue <- NULL urms.ci.lower <- urms.ci.upper <- NULL if(!unbiased.zstat) { unbiased.test.val <- NULL } if(se || unbiased) { TR2 <- sum(diag( ACOV %*% ACOV )) TR1 <- sum(diag( ACOV )) if(se) { rms.avar <- TR2/(TR1 * 2 * pstar) if(!is.finite(rms.avar) || rms.avar < .Machine$double.eps) { rms.se <- as.numeric(NA) } else { rms.se <- sqrt(rms.avar) } } } if(zstat) { E.rms <- ( sqrt(TR1/pstar) * (4 * TR1 * TR1 - TR2) / (4 * TR1 * TR1) ) rms.z <- max((rms - E.rms), 0) / rms.se if(pvalue) { rms.pvalue <- 1 - pnorm(rms.z) } } if(unbiased) { T.cov <- as.numeric( crossprod(STATS) ) eVe <- as.numeric(t(STATS) %*% ACOV %*% STATS) k.cov <- 1 - (TR2 + 2 * eVe) / (4 * T.cov * T.cov) urms <- ( 1/k.cov * sqrt( max((T.cov - TR1), 0) / pstar ) ) if(unbiased.se) { urms.avar <- ( 1/(k.cov*k.cov) * (TR2 + 2*eVe) / (2*pstar * T.cov) ) if(!is.finite(urms.avar) || urms.avar < .Machine$double.eps) { urms.se <- as.numeric(NA) } else { urms.se <- sqrt(urms.avar) } if(unbiased.ci) { a <- (1 - unbiased.ci.level)/2 a <- c(a, 1-a) fac <- stats::qnorm(a) urms.ci.lower <- urms + urms.se * fac[1] urms.ci.upper <- urms + urms.se * fac[2] } if(unbiased.zstat) { urms.z <- (urms - unbiased.test.val) / urms.se if(unbiased.pvalue) { urms.pvalue <- 1 - pnorm(urms.z) } } } } if(type == "rmr") { OUT <- list(rmr = rms, rmr.se = rms.se, rmr.exactfit.z = rms.z, rmr.exactfit.pvalue = rms.pvalue, urmr = urms, urmr.se = urms.se, urmr.ci.lower = urms.ci.lower, urmr.ci.upper = urms.ci.upper, urmr.closefit.h0.value = unbiased.test.val, urmr.closefit.z = urms.z, urmr.closefit.pvalue = urms.pvalue) } else if(type == "srmr") { OUT <- list(srmr = rms, srmr.se = rms.se, srmr.exactfit.z = rms.z, srmr.exactfit.pvalue = rms.pvalue, usrmr = urms, usrmr.se = urms.se, usrmr.ci.lower = urms.ci.lower, usrmr.ci.upper = urms.ci.upper, usrmr.closefit.h0.value = unbiased.test.val, usrmr.closefit.z = urms.z, usrmr.closefit.pvalue = urms.pvalue) } else if(type == "crmr") { OUT <- list(crmr = rms, crmr.se = rms.se, crmr.exactfit.z = rms.z, crmr.exactfit.pvalue = rms.pvalue, ucrmr = urms, ucrmr.se = urms.se, ucrmr.ci.lower = urms.ci.lower, ucrmr.cilupper = urms.ci.upper, ucrmr.closefit.h0.value = unbiased.test.val, ucrmr.closefit.z = urms.z, ucrmr.closefit.pvalue = urms.pvalue) } unlist(OUT) } lav_residuals_summary_old <- function(resList = NULL, add.class = FALSE, add.labels = FALSE) { nblocks <- length(resList) for(b in seq_len(nblocks)) { x <- vector("list", length = 0L) nel <- length(resList[[b]]) NAMES <- names(resList[[b]]) for(el in seq_len(nel)) { EL <- resList[[b]][[el]] if(!is.null(NAMES)) { NAME <- NAMES[el] } if(is.character(EL)) { new.x <- list(EL); if(add.labels) { names(new.x) <- "type" } x <- c(x, new.x) } else if(is.matrix(EL) && isSymmetric(EL)) { tmp <- na.omit(lav_matrix_vech(EL)) rms <- sqrt(sum(tmp*tmp)/length(tmp)) mabs <- mean(abs(tmp)) tmp2 <- na.omit(lav_matrix_vech(EL, diagonal = FALSE)) rms.nodiag <- sqrt(sum(tmp2*tmp2)/length(tmp2)) mabs.nodiag <- mean(abs(tmp2)) cov.summary <- c(rms, rms.nodiag, mabs, mabs.nodiag) if(add.labels) { names(cov.summary) <- c("rms", "rms.nodiag", "mabs", "mabs.nodiag") } if(add.class) { class(cov.summary) <- c("lavaan.vector", "numeric") } new.x <- list(EL, cov.summary) if(add.labels && !is.null(NAMES)) { names(new.x) <- c(NAME, paste0(NAME,".summary")) } x <- c(x, new.x) } else { tmp <- na.omit(EL) rms <- sqrt(sum(tmp*tmp)/length(tmp)) mabs <- mean(abs(tmp)) mean.summary <- c(rms, mabs) if(add.labels) { names(mean.summary) <- c("rms", "mabs") } if(add.class) { class(mean.summary) <- c("lavaan.vector", "numeric") } new.x <- list(EL, mean.summary) if(add.labels && !is.null(NAMES)) { names(new.x) <- c(NAME, paste0(NAME,".summary")) } x <- c(x, new.x) } } resList[[b]] <- x } resList } lav_residuals_rescale <- function(x, diag.cov = NULL, diag.cov2 = NULL) { if(is.null(diag.cov2)) { diag.cov2 <- diag.cov } diag.cov[!is.finite(diag.cov)] <- NA diag.cov[ diag.cov < .Machine$double.eps ] <- NA scale.cov <- tcrossprod(1/sqrt(diag.cov)) diag.cov2[!is.finite(diag.cov2)] <- NA diag.cov2[ diag.cov2 < .Machine$double.eps ] <- NA scale.mean <- 1/sqrt(diag.cov2) if(!is.null(x[["cov"]])) { near.zero.idx <- which(abs(x[["cov"]]) < 1e-05) scale.cov[near.zero.idx] <- 1 x[["cov"]][] <- x[["cov"]] * scale.cov } if(!is.null(x[["res.cov"]])) { near.zero.idx <- which(abs(x[["res.cov"]]) < 1e-05) scale.cov[near.zero.idx] <- 1 x[["res.cov"]][] <- x[["res.cov"]] * scale.cov } if(!is.null(x[["res.int"]])) { near.zero.idx <- which(abs(x[["res.int"]]) < 1e-05) scale.mean[near.zero.idx] <- 1 x[["res.int"]] <- x[["res.int"]] * scale.mean } if(!is.null(x[["mean"]])) { near.zero.idx <- which(abs(x[["mean"]]) < 1e-05) scale.mean[near.zero.idx] <- 1 x[["mean"]] <- x[["mean"]] * scale.mean } x }
smi <- function(object, ...) UseMethod("smi") smi.table <- function(object, normalize=TRUE, ...) { stopifnot(length(dim(object)) == 3) if( dim(object)[1] != 2 ) stop("currently 'smi' supports only two groups") pmm <- prop.table(object, c(1,2)) r <- diag( pmm[,,2] ) / pmm[1,2,2] if( normalize ) return( (r - 1) / (r + 1) ) else return(r) } smi.igraph <- function(object, vattr, ...) { stopifnot(is.directed(object)) m <- mixingm(object, rattr=vattr, full=TRUE) smi(m, ...) } smi.default <- function(object, ...) { smi.table(as.table(object), ...) }
wmonfromx <- function (xd, prior = "laplace", a = 0.5, tol = 1e-08, maxits = 20) { pr <- substring(prior, 1, 1) nx <- length(xd) wmin <- wfromt(sqrt(2 * log(length(xd))), prior=prior, a=a) winit <- 1 if(pr == "l") beta <- beta.laplace(xd, a=a) if(pr == "c") beta <- beta.cauchy(xd) w <- rep(winit, length(beta)) for(j in (1:maxits)) { aa <- w + 1/beta ps <- w + aa ww <- 1/aa^2 wnew <- isotone(ps, ww, increasing = FALSE) wnew <- pmax(wmin, wnew) wnew <- pmin(1, wnew) zinc <- max(abs(range(wnew - w))) w <- wnew if(zinc < tol) return(w) } warning("More iterations required to achieve convergence") return(w) }
`%entails%` <- function(imps, imps2) { conclusions <- imps2$get_RHS_matrix() premises <- imps2$get_LHS_matrix() entails <- sapply(seq(ncol(premises)), function(i) { p <- .extract_column(premises, i) cl <- .compute_closure( S = p, LHS = imps$get_LHS_matrix(), RHS = imps$get_RHS_matrix(), attributes = imps$get_attributes())$closure .subset(.extract_column(conclusions, i), cl) }) %>% purrr::reduce(cbind) %>% Matrix::as.matrix() return(entails) } `%~%` <- function(imps, imps2) { all(imps %entails% imps2) && all(imps2 %entails% imps) }
adorn_totals <- function(dat, where = "row", fill = "-", na.rm = TRUE, name = "Total", ...) { if("both" %in% where){ where <- c("row", "col") } if (is.list(dat) && !is.data.frame(dat)) { purrr::map(dat, adorn_totals, where, fill, na.rm, name) } else { if (!is.data.frame(dat)) { stop("adorn_totals() must be called on a data.frame or list of data.frames") } numeric_cols <- which(vapply(dat, is.numeric, logical(1))) non_numeric_cols <- setdiff(1:ncol(dat), numeric_cols) if (rlang::dots_n(...) == 0) { numeric_cols <- setdiff(numeric_cols, 1) non_numeric_cols <- unique(c(1, non_numeric_cols)) cols_to_total <- numeric_cols } else { expr <- rlang::expr(c(...)) cols_to_total <- tidyselect::eval_select(expr, data = dat) if (any(cols_to_total %in% non_numeric_cols)) { cols_to_total <- setdiff(cols_to_total, non_numeric_cols) } } if (length(cols_to_total) == 0) { stop("at least one targeted column must be of class numeric. Control target variables with the ... argument. adorn_totals should be called before other adorn_ functions.") } if (sum(where %in% c("row", "col")) != length(where)) { stop("\"where\" must be one of \"row\", \"col\", or c(\"row\", \"col\")") } if (length(name) == 1) name <- rep(name, 2) if ("grouped_df" %in% class(dat)) { dat <- dplyr::ungroup(dat) } dat <- as_tabyl(dat) if (sum(where %in% attr(dat, "totals")) > 0) { stop("trying to re-add a totals dimension that is already been added") } else if (length(attr(dat, "totals")) == 1) { attr(dat, "totals") <- c(attr(dat, "totals"), where) } else { attr(dat, "totals") <- where } if ("row" %in% where) { col_sum <- function(a_col, na_rm = na.rm) { if (is.numeric(a_col)) { sum(a_col, na.rm = na_rm) } else { if (!is.character(fill)) { switch(typeof(a_col), "character" = NA_character_, "integer" = NA_integer_, "double" = if(inherits(a_col, "Date") || inherits(a_col, "POSIXt")) { as.Date(NA_real_, origin = "1970-01-01") } else { NA_real_ }, "complex" = NA_complex_, NA) } else { fill } } } if (is.character(fill)) { col_totals <- purrr::map_df(dat, col_sum) not_totaled_cols <- setdiff(1:length(col_totals), cols_to_total) col_totals[not_totaled_cols] <- fill dat[not_totaled_cols] <- lapply(dat[not_totaled_cols], as.character) } else { cols_idx <- seq_along(dat) names(cols_idx) <- names(dat) col_totals <- purrr::map_df(cols_idx, function(i) { if (is.numeric(dat[[i]]) && !i %in% cols_to_total) { switch(typeof(dat[[i]]), "integer" = NA_integer_, "double" = NA_real_, NA) } else { col_sum(dat[[i]]) } }) if (!is.character(dat[[1]]) && !1 %in% cols_to_total) { dat[[1]] <- as.character(dat[[1]]) col_totals[[1]] <- as.character(col_totals[[1]]) } } if (! 1 %in% cols_to_total) { col_totals[1, 1] <- name[1] } else { message("Because the first column was specified to be totaled, it does not contain the label 'Total' (or user-specified name) in the totals row") } dat[(nrow(dat) + 1), ] <- col_totals[1, ] } if ("col" %in% where) { row_totals <- dat %>% dplyr::select(cols_to_total) %>% dplyr::select_if(is.numeric) %>% dplyr::transmute(Total = rowSums(., na.rm = na.rm)) dat[[name[2]]] <- row_totals$Total } dat } }
lpp <- function(X, L, ...) { stopifnot(inherits(L, "linnet")) if(missing(X) || is.null(X)) { df <- data.frame(x=numeric(0), y=numeric(0)) lo <- data.frame(seg=integer(0), tp=numeric(0)) } else { localnames <- c("seg", "tp") spatialnames <- c("x", "y") allcoordnames <- c(spatialnames, localnames) if(is.matrix(X)) X <- as.data.frame(X) if(checkfields(X, localnames)) { X <- as.data.frame(X) if(nrow(X) > 0) { nedge <- nsegments(L) if(with(X, any(seg < 1 | seg > nedge))) stop("Segment index coordinate 'seg' exceeds bounds") if(with(X, any(tp < 0 | tp > 1))) stop("Local coordinate 'tp' outside [0,1]") } if(!checkfields(X, spatialnames)) { Y <- local2lpp(L, X$seg, X$tp, df.only=TRUE) X[,spatialnames] <- Y[,spatialnames,drop=FALSE] } lo <- X[ , localnames, drop=FALSE] marknames <- setdiff(names(X), allcoordnames) df <- X[, c(spatialnames, marknames), drop=FALSE] } else { if(!is.ppp(X)) X <- as.ppp(X, W=L$window, ...) pro <- project2segment(X, as.psp(L)) df <- as.data.frame(pro$Xproj) lo <- data.frame(seg=pro$mapXY, tp=pro$tp) } } nmark <- ncol(df) - 2 if(nmark == 0) { df <- cbind(df, lo) ctype <- c(rep("s", 2), rep("l", 2)) } else { df <- cbind(df[,1:2], lo, df[, -(1:2), drop=FALSE]) ctype <- c(rep("s", 2), rep("l", 2), rep("m", nmark)) } out <- ppx(data=df, domain=L, coord.type=ctype) class(out) <- c("lpp", class(out)) return(out) } print.lpp <- function(x, ...) { stopifnot(inherits(x, "lpp")) splat("Point pattern on linear network") sd <- summary(x$data) np <- sd$ncases nama <- sd$col.names splat(np, ngettext(np, "point", "points")) ctype <- x$ctype nam.m <- nama[ctype == "mark"] nam.t <- nama[ctype == "temporal"] nam.c <- setdiff(nama[ctype == "spatial"], c("x","y")) nam.l <- setdiff(nama[ctype == "local"], c("seg", "tp")) if(length(nam.c) > 0) splat("Additional spatial coordinates", commasep(sQuote(nam.c))) if(length(nam.l) > 0) splat("Additional local coordinates", commasep(sQuote(nam.l))) if(length(nam.t) > 0) splat("Additional temporal coordinates", commasep(sQuote(nam.t))) if((nmarks <- length(nam.m)) > 0) { if(nmarks > 1) { splat(nmarks, "columns of marks:", commasep(sQuote(nam.m))) } else { marx <- marks(x) if(is.factor(marx)) { exhibitStringList("Multitype, with possible types:", levels(marx)) } else splat("Marks of type", sQuote(typeof(marx))) } } print(x$domain, ...) return(invisible(NULL)) } plot.lpp <- function(x, ..., main, add=FALSE, use.marks=TRUE, which.marks=NULL, show.all=!add, show.window=FALSE, show.network=TRUE, do.plot=TRUE, multiplot=TRUE) { if(missing(main)) main <- short.deparse(substitute(x)) mx <- marks(x) if(use.marks && !is.null(dim(mx))) { implied.all <- is.null(which.marks) want.several <- implied.all || !is.null(dim(mx <- mx[,which.marks,drop=TRUE])) do.several <- want.several && !add && multiplot if(want.several) mx <- as.data.frame(mx) if(do.several) { y <- solapply(mx, setmarks, x=x) out <- do.call(plot, c(list(x=y, main=main, do.plot=do.plot, show.window=show.window), list(...))) return(invisible(out)) } if(is.null(which.marks)) { which.marks <- 1 if(do.plot) message("Plotting the first column of marks") } } P <- as.ppp(x) a <- plot(P, ..., do.plot=FALSE, use.marks=use.marks, which.marks=which.marks) if(!do.plot) return(a) if(!add) { if(show.window) { plot(Window(P), main=main, invert=TRUE, ...) } else { b <- attr(a, "bbox") plot(b, type="n", main=main, ..., show.all=FALSE) } } if(show.network) { L <- as.linnet(x) dont.complain.about(L) do.call.matched(plot.linnet, resolve.defaults(list(x=quote(L), add=TRUE), list(...)), extrargs=c("lty", "lwd", "col")) } ans <- do.call.matched(plot.ppp, c(list(x=P, add=TRUE, main=main, use.marks=use.marks, which.marks=which.marks, show.all=show.all, show.window=FALSE), list(...)), extrargs=c("shape", "size", "pch", "cex", "fg", "bg", "cols", "lty", "lwd", "etch", "cex.main", "col.main", "line", "outer", "sub")) return(invisible(ans)) } summary.lpp <- function(object, ...) { stopifnot(inherits(object, "lpp")) L <- object$domain result <- summary(L) np <- npoints(object) result$npoints <- np <- npoints(object) result$intensity <- np/result$totlength result$is.marked <- is.marked(object) result$is.multitype <- is.multitype(object) mks <- marks(object) result$markformat <- mkf <- markformat(mks) switch(mkf, none = { result$multiple.marks <- FALSE }, vector = { result$multiple.marks <- FALSE if(result$is.multitype) { tm <- as.vector(table(mks)) tfp <- data.frame(frequency=tm, proportion=tm/sum(tm), intensity=tm/result$totlength, row.names=levels(mks)) result$marks <- tfp result$is.numeric <- FALSE } else { result$marks <- summary(mks) result$is.numeric <- is.numeric(mks) } result$marknames <- "marks" result$marktype <- typeof(mks) }, dataframe = , hyperframe = { result$multiple.marks <- TRUE result$marknames <- names(mks) result$is.numeric <- FALSE result$marktype <- mkf result$is.multitype <- FALSE result$marks <- summary(mks) }) class(result) <- "summary.lpp" return(result) } print.summary.lpp <- function(x, ...) { what <- if(x$is.multitype) "Multitype point pattern" else if(x$is.marked) "Marked point pattern" else "Point pattern" splat(what, "on linear network") splat(x$npoints, "points") splat("Linear network with", x$nvert, "vertices and", x$nline, "lines") u <- x$unitinfo dig <- getOption('digits') splat("Total length", signif(x$totlength, dig), u$plural, u$explain) splat("Average intensity", signif(x$intensity, dig), "points per", if(u$vanilla) "unit length" else u$singular) if(x$is.marked) { if(x$multiple.marks) { splat("Mark variables:", commasep(x$marknames, ", ")) cat("Summary of marks:\n") print(x$marks) } else if(x$is.multitype) { cat("Types of points:\n") print(signif(x$marks,dig)) } else { splat("marks are ", if(x$is.numeric) "numeric, ", "of type ", sQuote(x$marktype), sep="") cat("Summary:\n") print(x$marks) } } else splat("Unmarked") print(x$win, prefix="Enclosing window: ") invisible(NULL) } intensity.lpp <- function(X, ...) { len <- sum(lengths_psp(as.psp(as.linnet(X)))) if(is.multitype(X)) table(marks(X))/len else npoints(X)/len } is.lpp <- function(x) { inherits(x, "lpp") } is.multitype.lpp <- function(X, na.action="warn", ...) { marx <- marks(X) if(is.null(marx)) return(FALSE) if((is.data.frame(marx) || is.hyperframe(marx)) && ncol(marx) > 1) return(FALSE) if(!is.factor(marx)) return(FALSE) if((length(marx) > 0) && anyNA(marx)) switch(na.action, warn = { warning(paste("some mark values are NA in the point pattern", short.deparse(substitute(X)))) }, fatal = { return(FALSE) }, ignore = {} ) return(TRUE) } as.lpp <- function(x=NULL, y=NULL, seg=NULL, tp=NULL, ..., marks=NULL, L=NULL, check=FALSE, sparse) { nomore <- is.null(y) && is.null(seg) && is.null(tp) if(inherits(x, "lpp") && nomore) { X <- x if(!missing(sparse) && !is.null(sparse)) X$domain <- as.linnet(domain(X), sparse=sparse) } else { if(!inherits(L, "linnet")) stop("L should be a linear network") if(!missing(sparse) && !is.null(sparse)) L <- as.linnet(L, sparse=sparse) if(is.ppp(x) && nomore) { X <- lpp(x, L) } else if(is.data.frame(x) && nomore) { X <- do.call(as.lpp, resolve.defaults(as.list(x), list(...), list(marks=marks, L=L, check=check))) } else if(is.null(x) && is.null(y) && !is.null(seg) && !is.null(tp)){ X <- lpp(data.frame(seg=seg, tp=tp), L=L) } else { if(is.numeric(x) && length(x) == 2 && is.null(y)) { xy <- list(x=x[1L], y=x[2L]) } else { xy <- xy.coords(x,y)[c("x", "y")] } if(!is.null(seg) && !is.null(tp)) { xy <- append(xy, list(seg=seg, tp=tp)) } else { xy <- as.ppp(xy, W=as.owin(L), check=check) } X <- lpp(xy, L) } } if(!is.null(marks)) marks(X) <- marks return(X) } as.ppp.lpp <- function(X, ..., fatal=TRUE) { verifyclass(X, "lpp", fatal=fatal) L <- X$domain Y <- as.ppp(coords(X, temporal=FALSE, local=FALSE), W=L$window, check=FALSE) if(!is.null(marx <- marks(X))) { if(is.hyperframe(marx)) marx <- as.data.frame(marx) marks(Y) <- marx } return(Y) } Window.lpp <- function(X, ...) { as.owin(X) } "Window<-.lpp" <- function(X, ..., check=TRUE, value) { if(check) { X <- X[value] } else { Window(X$domain, check=FALSE) <- value } return(X) } as.owin.lpp <- function(W, ..., fatal=TRUE) { as.owin(as.ppp(W, ..., fatal=fatal)) } domain.lpp <- function(X, ...) { as.linnet(X) } as.linnet.lpp <- function(X, ..., fatal=TRUE, sparse) { verifyclass(X, "lpp", fatal=fatal) L <- X$domain if(!missing(sparse)) L <- as.linnet(L, sparse=sparse) return(L) } unitname.lpp <- function(x) { u <- unitname(x$domain) return(u) } "unitname<-.lpp" <- function(x, value) { w <- x$domain unitname(w) <- value x$domain <- w return(x) } "marks<-.lpp" <- function(x, ..., value) { NextMethod("marks<-") } unmark.lpp <- function(X) { NextMethod("unmark") } as.psp.lpp <- function(x, ..., fatal=TRUE){ verifyclass(x, "lpp", fatal=fatal) return(x$domain$lines) } nsegments.lpp <- function(x) { return(x$domain$lines$n) } local2lpp <- function(L, seg, tp, X=NULL, df.only=FALSE) { stopifnot(inherits(L, "linnet")) if(is.null(X)) { Ldf <- as.data.frame(L$lines) dx <- with(Ldf, x1-x0) dy <- with(Ldf, y1-y0) x <- with(Ldf, x0[seg] + tp * dx[seg]) y <- with(Ldf, y0[seg] + tp * dy[seg]) } else { x <- X$x y <- X$y } data <- data.frame(x=x, y=y, seg=seg, tp=tp) if(df.only) return(data) ctype <- c("s", "s", "l", "l") out <- ppx(data=data, domain=L, coord.type=ctype) class(out) <- c("lpp", class(out)) return(out) } "[.lpp" <- function (x, i, j, drop=FALSE, ..., snip=TRUE) { if(!missing(i) && !is.null(i)) { if(is.owin(i)) { xi <- x[,i,snip=snip] } else { da <- x$data daij <- da[i, , drop=FALSE] xi <- ppx(data=daij, domain=x$domain, coord.type=as.character(x$ctype)) if(drop) xi <- xi[drop=TRUE] class(xi) <- c("lpp", class(xi)) } x <- xi } if(missing(j) || is.null(j)) return(x) stopifnot(is.owin(j)) x <- repairNetwork(x) w <- j L <- x$domain if(is.vanilla(unitname(w))) unitname(w) <- unitname(x) vertinside <- inside.owin(L$vertices, w=w) from <- L$from to <- L$to if(snip) { okedge <- vertinside[from] | vertinside[to] x <- thinNetwork(x, retainedges=okedge) b <- crossing.psp(as.psp(L), edges(w)) x <- insertVertices(x, unique(b)) boundarypoints <- attr(x, "id") L <- x$domain from <- L$from to <- L$to vertinside <- inside.owin(L$vertices, w=w) vertinside[boundarypoints] <- TRUE } edgeinside <- vertinside[from] & vertinside[to] xnew <- thinNetwork(x, retainedges=edgeinside) Window(xnew, check=FALSE) <- w return(xnew) } scalardilate.lpp <- function(X, f, ...) { trap.extra.arguments(..., .Context="In scalardilate(X,f)") check.1.real(f, "In scalardilate(X,f)") stopifnot(is.finite(f) && f > 0) Y <- X Y$data$x <- f * as.numeric(X$data$x) Y$data$y <- f * as.numeric(X$data$y) Y$domain <- scalardilate(X$domain, f) return(Y) } affine.lpp <- function(X, mat=diag(c(1,1)), vec=c(0,0), ...) { verifyclass(X, "lpp") Y <- X Y$data[, c("x","y")] <- affinexy(X$data[, c("x","y")], mat=mat, vec=vec) Y$domain <- affine(X$domain, mat=mat, vec=vec, ...) return(Y) } shift.lpp <- function(X, vec=c(0,0), ..., origin=NULL) { verifyclass(X, "lpp") Y <- X Y$domain <- if(missing(vec)) { shift(X$domain, ..., origin=origin) } else { shift(X$domain, vec=vec, ..., origin=origin) } vec <- getlastshift(Y$domain) Y$data[, c("x","y")] <- shiftxy(X$data[, c("x","y")], vec=vec) attr(Y, "lastshift") <- vec return(Y) } rotate.lpp <- function(X, angle=pi/2, ..., centre=NULL) { verifyclass(X, "lpp") if(!is.null(centre)) { X <- shift(X, origin=centre) negorigin <- getlastshift(X) } else negorigin <- NULL Y <- X Y$data[, c("x","y")] <- rotxy(X$data[, c("x","y")], angle=angle) Y$domain <- rotate(X$domain, angle=angle, ...) if(!is.null(negorigin)) Y <- shift(Y, -negorigin) return(Y) } rescale.lpp <- function(X, s, unitname) { if(missing(unitname)) unitname <- NULL if(missing(s)) s <- 1/unitname(X)$multiplier Y <- scalardilate(X, f=1/s) unitname(Y) <- rescale(unitname(X), s, unitname) return(Y) } superimpose.lpp <- function(..., L=NULL) { objects <- list(...) if(!is.null(L) && !inherits(L, "linnet")) stop("L should be a linear network") if(length(objects) == 0) { if(is.null(L)) return(NULL) emptyX <- lpp(list(x=numeric(0), y=numeric(0)), L) return(emptyX) } islpp <- unlist(lapply(objects, is.lpp)) if(is.null(L) && !any(islpp)) stop("Cannot determine linear network: no lpp objects given") nets <- unique(lapply(objects[islpp], as.linnet)) if(length(nets) > 1) stop("Point patterns are defined on different linear networks") if(!is.null(L)) { nets <- unique(append(nets, list(L))) if(length(nets) > 1) stop("Argument L is a different linear network") } L <- nets[[1L]] if(any(!islpp)) objects[!islpp] <- lapply(objects[!islpp], lpp, L=L) locns <- do.call(rbind, lapply(objects, coords)) marx <- superimposeMarks(objects, sapply(objects, npoints)) Y <- lpp(locns, L) marks(Y) <- marx return(Y) } identify.lpp <- function(x, ...) { verifyclass(x, "lpp") P <- as.ppp(x) id <- identify(P$x, P$y, ...) if(!is.marked(x)) return(id) marks <- as.data.frame(P)[id, -(1:2)] out <- cbind(data.frame(id=id), marks) row.names(out) <- NULL return(out) } cut.lpp <- function(x, z=marks(x), ...) { if(missing(z) || is.null(z)) { z <- marks(x, dfok=TRUE) if(is.null(z)) stop("no data for grouping: z is missing, and x has no marks") } else { if(inherits(z, "linim")) { z <- z[x, drop=FALSE] } else if(inherits(z, "linfun")) { z <- z(x) } else if(inherits(z, "lintess")) { z <- (as.linfun(z))(x) } } if(is.character(z)) { if(length(z) == npoints(x)) { z <- factor(z) } else if((length(z) == 1) && (z %in% colnames(df <- as.data.frame(x)))) { zname <- z z <- df[, zname] if(zname == "seg") z <- factor(z) } else stop("format of argument z not understood") } switch(markformat(z), none = stop("No data for grouping"), vector = { stopifnot(length(z) == npoints(x)) g <- if(is.factor(z)) z else if(is.numeric(z)) cut(z, ...) else factor(z) marks(x) <- g return(x) }, dataframe = , hyperframe = { stopifnot(nrow(z) == npoints(x)) z <- as.data.frame(z) if(ncol(z) < 1) stop("No suitable data for grouping") z <- z[,1L,drop=TRUE] g <- if(is.numeric(z)) cut(z, ...) else factor(z) marks(x) <- g return(x) }, list = stop("Don't know how to cut according to a list")) stop("Format of z not understood") } points.lpp <- function(x, ...) { points(coords(x, spatial=TRUE, local=FALSE), ...) } connected.lpp <- function(X, R=Inf, ..., dismantle=TRUE) { if(!dismantle) { if(is.infinite(R)) { Y <- X %mark% factor(1) attr(Y, "retainpoints") <- attr(X, "retainpoints") return(Y) } check.1.real(R) stopifnot(R >= 0) nv <- npoints(X) close <- (pairdist(X) <= R) diag(close) <- FALSE ij <- which(close, arr.ind=TRUE) lab0 <- cocoEngine(nv, ij[,1] - 1L, ij[,2] - 1L, "connected.lpp") lab <- lab0 + 1L lab <- as.integer(factor(lab)) lab <- factor(lab) Y <- X %mark% lab attr(Y, "retainpoints") <- attr(X, "retainpoints") return(Y) } L <- domain(X) lab <- connected(L, what="labels") if(length(levels(lab)) == 1) { XX <- solist(X) } else { subsets <- split(seq_len(nvertices(L)), lab) XX <- solist() for(i in seq_along(subsets)) XX[[i]] <- thinNetwork(X, retainvertices=subsets[[i]]) } YY <- solapply(XX, connected.lpp, R=R, dismantle=FALSE) if(length(YY) == 1) YY <- YY[[1]] return(YY) } text.lpp <- function(x, ...) { co <- coords(x) graphics::text.default(x=co$x, y=co$y, ...) }
knitr::opts_chunk$set( collapse = TRUE, comment = " ) library(MultivariateAnalysis) data("Dados.DBC.Misto") head(Dados.DBC.Misto) Res=MANOVA(Dados.DBC.Misto[,1:5],Modelo=2) Res DadosMed=Res$Med DistMaha=Distancia(DadosMed,Metodo = 7,Cov = Res$CovarianciaResidual) DistMaha resumo=SummaryDistancia(DistMaha) resumo Dadosquali=Dados.DBC.Misto[,6:11] id=is.na(Dadosquali$CorFolha)==FALSE Dadosquali2=Dadosquali[id,] rownames(Dadosquali2)=Dados.DBC.Misto[id,1] Distquali=Distancia(Dadosquali2,Metodo = 10) round(Distquali$Distancia,3) dissimilaridades=list(DistMaha,Distquali) n=c(ncol(DadosMed),ncol(Dadosquali2)) DistMisto=MediaDistancia(dissimilaridades,n) DistMisto Dendrograma(DistMaha,Metodo=3,Titulo="Dados quantiativos") Dendrograma(Distquali,Metodo=3, Titulo="Dados qualitativos") Dendrograma(DistMisto,Metodo=3,Titulo= "Qualitativos + Quantiativos") Tocher(DistMisto) CorrelacaoMantel(DistMaha,DistMisto) CorrelacaoMantel(DistMaha,Distquali) CorrelacaoMantel(Distquali,DistMisto)
test_that("daily - on a yweek", { base <- daily() rrule <- base %>% recur_on_yweek(1) start <- "1990-01-01" stop <- "1990-01-31" x <- alma_search(start, stop, rrule) expect_equal(x[1], as.Date("1990-01-01")) expect_equal(x[length(x)], as.Date("1990-01-07")) expect_length(x, 7) }) test_that("weekly - on a yweek", { base <- weekly() rrule <- base %>% recur_on_yweek(1) start <- "1990-01-01" stop <- "1990-01-31" x <- alma_search(start, stop, rrule) expect_equal(x[1], as.Date("1990-01-01")) expect_equal(x[length(x)], as.Date("1990-01-07")) expect_length(x, 7) }) test_that("monthly - on a yweek", { base <- monthly() rrule <- base %>% recur_on_yweek(1) start <- "1990-01-01" stop <- "1990-01-31" x <- alma_search(start, stop, rrule) expect_equal(x[1], as.Date("1990-01-01")) expect_equal(x[length(x)], as.Date("1990-01-07")) expect_length(x, 7) }) test_that("yearly - on a yweek", { base <- yearly() rrule <- base %>% recur_on_yweek(1) start <- "1990-01-01" stop <- "1990-01-31" x <- alma_search(start, stop, rrule) expect_equal(x[1], as.Date("1990-01-01")) expect_equal(x[length(x)], as.Date("1990-01-07")) expect_length(x, 7) }) test_that("first week of the year correctly defaults to use a week start of Monday", { rrule <- daily() %>% recur_on_yweek(1) x <- alma_search("2017-01-01", "2017-01-31", rrule) expect_equal(x[1], as.Date("2017-01-02")) expect_length(x, 7) x <- alma_search("2014-12-25", "2015-01-31", rrule) expect_equal(x[1], as.Date("2014-12-29")) expect_length(x, 7) }) test_that("logic is correct when selecting from the back", { rrule <- daily() %>% recur_on_yweek(-1) x <- alma_search("2017-12-01", "2018-01-31", rrule) expect_equal(x[1], as.Date("2017-12-25")) expect_equal(x[length(x)], as.Date("2017-12-31")) x <- alma_search("2014-12-01", "2015-01-31", rrule) expect_equal(x[1], as.Date("2014-12-22")) expect_equal(x[length(x)], as.Date("2014-12-28")) }) test_that("week start option is respected", { rrule <- daily() %>% recur_on_yweek(1) %>% recur_with_week_start("Tuesday") x <- alma_search("2017-01-01", "2017-01-31", rrule) expect_equal(x[1], as.Date("2017-01-03")) rrule <- daily() %>% recur_on_yweek(1) %>% recur_with_week_start("Sunday") x <- alma_search("2014-12-25", "2015-01-31", rrule) expect_equal(x[1], as.Date("2015-01-04")) }) test_that("cannot use `yweek > 53` or `yweek < -53` or `yweek == 0`", { expect_error(yearly() %>% recur_on_yweek(54), "can only take values") expect_error(yearly() %>% recur_on_yweek(-54), "can only take values") expect_error(yearly() %>% recur_on_yweek(0), "can only take values") }) test_that("yweek must be an integer", { expect_error(yearly() %>% recur_on_yweek(30.5), class = "vctrs_error_cast_lossy") })
print.SimBIID_model <- function(x, ...) { writeLines(x$code) }
modelDisable <- function(factory){ command <- paste("UpdaterMethods.SetFactory('", factory,"');UpdaterMethods.Disable", sep = "") invisible(.CmdInterpreter(command)) } modelEnable <- function(factory){ command <- paste("UpdaterMethods.SetFactory('", factory,"');UpdaterMethods.Enable", sep = "") invisible(.CmdInterpreter(command)) }
als.mg.ho2.imp <- function (Z, rawz0, W01, W02, A0, W1, W2, A, V, I, PHT, nvar, nlv1, nlv, ng, missingvalue, itmax, ceps) { sizez <- ncol(Z) sizea <- ncol(A) aindex0 <- which(A0 >= 1) W <- W1%*%W2 Psi <- Z%*%V%*%I Gamma <- Z%*%W it <- 0 imp <- 100000 f0 <- 10^10 while (it <= itmax && imp > ceps) { it <- it + 1 for (t in 1:sizea) { if ( !all(A0[,t] == 0) ) { H1 <- diag(1,sizea) H1[t,t] <- 0 aindex <- which(A0[,t] >= 1) if(length(aindex) != 0) { a <- A[,t,drop=FALSE] a[aindex] <- 0 e <- matrix(0,1,sizea) e[t] <- 1 Y <- Psi - Gamma%*%(A%*%H1 + a%*%e) X <- Gamma[,aindex,drop=FALSE] A[aindex,t] <- solve(t(X)%*%X, t(X)%*%Y%*%t(e)) } } } vecA <- A[aindex0] A[aindex0] <- PHT%*%vecA W2A <- W2%*%A kk <- 0 ii <- 0 ll <- 0 for (g in 1:ng) { k <- kk + 1 kk <- kk + nlv1 i <- ii + 1 ii <- ii + nvar l <- ll + 1 ll <- ll + nlv s <- 0 for (j in k:kk) { s <- s + 1 t <- sizea*(g-1) + 1 tt <- sizea*(g-1) + sizea windex1 <- which(W01[,j] == 99) w1 <- W1[,j,drop=FALSE] w1[windex1] <- 0 m <- cbind(matrix(0,1,nvar),W2[j,l:ll,drop=FALSE]) H2 <- diag(1,nlv1) H2[s,s] <- 0 Dj <- cbind(diag(1,nvar),W1[i:ii,k:kk,drop=FALSE]%*%H2%*%W2[k:kk,l:ll,drop=FALSE]) D <- V D[i:ii,t:tt] <- Dj beta <- m - W2A[j,,drop=FALSE] H3 <- diag(1,ng*nlv1) H3[j,j] <- 0 Delta <- W1%*%H3%*%W2A - D%*%I - w1%*%beta Y <- Z%*%Delta X <- Z[,windex1] temptheta <- solve(t(X)%*%X,t(X)) %*% Y %*% t(beta) theta <- t(solve(t(beta%*%t(beta)),t(temptheta))) zw <- X%*%theta theta <- theta%*%(1/sqrt(t(zw)%*%zw)) W1[windex1,j] <- theta V[i:ii,t:tt] <- cbind(diag(1,nvar),W1[i:ii,k:kk]%*%W2[k:kk,l:ll]) } } ZW1 <- Z%*%W1 kk <- 0 ii <- 0 ll <- 0 for (g in 1:ng) { k <- kk + 1 kk <- kk + nlv1 i <- ii + 1 ii <- ii + nvar l <- ll + 1 ll <- ll + nlv s <- 0 for (j in l:ll) { s <- s + 1 t <- sizea*(g-1) + 1 tt <- sizea*(g-1) + sizea windex2 <- which(W02[,j] == 99) if ( nrow(as.matrix(windex2)) != 0 ) { w2 <- W2[,j,drop=FALSE] w2[windex2] <- 0 e <- matrix(0,1,nlv) e[s] <- 1 m <- cbind(matrix(0,1,nvar),e) H4 <- diag(1,nlv) H4[s,s] <- 0 Dj <- cbind(diag(1,nvar),W1[i:ii,k:kk,drop=FALSE]%*%W2[k:kk,l:ll,drop=FALSE]%*%H4) D <- V D[i:ii,t:tt] <- Dj beta <- m - A[j,,drop=FALSE] H5 <- diag(1,ng*nlv) H5[j,j] <- 0 Delta <- W1%*%W2%*%H5%*%A - D%*%I Y <- Z%*%Delta - ZW1%*%w2%*%beta X <- ZW1[,windex2,drop=FALSE] temptheta <- solve(t(X)%*%X,t(X)) %*% Y %*% t(beta) theta <- t(solve(t(beta%*%t(beta)),t(temptheta))) zw <- X%*%theta theta <- theta%*%(1/sqrt(t(zw)%*%zw)) W2[windex2,j] <- theta V[i:ii,t:tt] <- cbind(diag(1,nvar),W1[i:ii,k:kk]%*%W2[k:kk,l:ll]) } } } W <- W1%*%W2 Q <- V%*%I - W%*%A for (j in 1:sizez) { zindex <- which(rawz0[,j] == missingvalue) if ( nrow(as.matrix(zindex)) != 0 ) { z <- Z[,j,drop=FALSE] q <- Q[j,,drop=FALSE] H6 <- diag(1, sizez) H6[j,j] <- 0 Y <- -Z%*%H6%*%Q mz <- (Y%*%t(q))%*%(1/q%*%t(q)) z[zindex] <- mz[zindex] Z[,j] <- z%*%(1/sqrt(t(z)%*%z)) } } Gamma <- Z%*%W Psi <- Z%*%V%*%I dif <- Psi-Gamma%*%A f <- sum(diag(t(dif)%*%dif)) imp <- f0-f info <- c(it,f,f0,imp) f0 <- f } output.als.mg.ho2.imp <- list(W = W, W1 = W1, W2 = W2, A = A, Z = Z, Psi = Psi, Gamma = Gamma, f = f, it = it, imp = imp) output.als.mg.ho2.imp }
snmatch <- function(x, y, p = c(0.025, 0.5, 0.975)){ if(!is.vector(x, mode = "numeric") || !is.vector(y, mode = "numeric") || !is.vector(p, mode = "numeric")) stop("x, y, p must be numeric vectors") if(length(x) != length(y)) stop("x and y must have the same length") if(any(is.infinite(x)) | any(is.infinite(y))) stop("x, y must contain finite values") if(anyNA(x) | anyNA(y) | anyNA(p)) stop("x or y or p contain NA or NaN") if(any(p < 0) | any(p > 1)) stop("probabilities must be between 0 and 1") x <- sort(x) y <- y[order(x)] cubroot <- function(x) sign(x) * (abs(x)) ^ (1 / 3) n <- length(x) - 1 dx <- diff(x) gx <- x * y trapezoid.vec <- rowSums(cbind(gx[1:n], gx[-1])) * .5 mom1 <- sum(trapezoid.vec * dx) gx2 <- ((x - mom1) ^ 2) * y trapezoid.vec <- rowSums(cbind(gx2[1:n], gx2[-1])) * .5 mom2 <- sum(trapezoid.vec * dx) gx3 <- ((x - mom1) ^ 3) * y trapezoid.vec <- rowSums(cbind(gx3[1:n], gx3[-1])) * .5 mom3 <- sum(trapezoid.vec * dx) const.kappa <- (cubroot(mom3) * sqrt(pi)) / (cubroot(4 - pi) * (2 ^ (1 / 6)) * sqrt(mom2)) psi.star <- sign(mom3) * sqrt(4 * (const.kappa ^ 2 + (2 * (const.kappa ^ 4) / pi))) / (2 + (4 * const.kappa ^ 2) / pi) if (psi.star < -1) { psi.star <- (-1 + 1e-3) } if (psi.star > 1) { psi.star <- (1 - 1e-3) } rho.star <- psi.star / (sqrt(1 - psi.star ^ 2)) zeta.star <- sqrt(mom2 / (1 - (2 / pi) * (psi.star ^ 2))) mu.star <- mom1 - zeta.star * sqrt(2 / pi) * psi.star xfine <- seq(min(x), max(x), length = 500) snfit <- 2 * stats::dnorm(xfine, mean = mu.star, sd = zeta.star) * stats::pnorm(rho.star * (xfine - mu.star) / zeta.star) quantiles <- sapply(p, sn::qsn, xi = mu.star, omega = zeta.star, alpha = rho.star) list.out <- list(location = mu.star, scale = zeta.star, shape = rho.star, snfit = snfit, quant = quantiles, xgrid = xfine) return(list.out) }
test_that("raw_gen", { testthat::expect_true(ncol(Cremains_measurements %>% mutate(Pop = rep("A", nrow(.))) %>% raw_gen( Pop = ncol(.) )) == 23) set.seed(123) testthat::expect_true(round(raw_gen(baboon.parms_df, dist = "log")[1, 6][[1]], 2) == 43.96) set.seed(123) testthat::expect_true(round(raw_gen(baboon.parms_df, dist = "trunc")[1, 6][[1]], 2) == 45.39) set.seed(123) testthat::expect_true(round(raw_gen(baboon.parms_list)[1, 6][[1]], 2) == 58.55) set.seed(123) testthat::expect_true(round(raw_gen(baboon.parms_df, R.res = baboon.parms_R)[1, 6][[1]], 2) == 58.55) testthat::expect_error(raw_gen(baboon.parms_R)) testthat::expect_error(raw_gen(baboon.parms_df, complete_cases = 95)) testthat::expect_error(raw_gen(baboon.parms_df, Pop = 500)) testthat::expect_error(raw_gen(baboon.parms_df, Trait = 500)) testthat::expect_true(ncol(raw_gen(baboon.parms_df, format = "long")) == 4) testthat::expect_error(raw_gen(baboon.parms_df, R.res = baboon.parms_list)) testthat::expect_error(raw_gen(baboon.parms_list[1:5])) })
calcICLNoPlots <- function(consensus_results){ ff <- tempfile() grDevices::png(filename=ff) res <- calcICL(consensus_results) grDevices::dev.off() unlink(ff) return(res) }
gamcen.11 <- function (x, mu = 0, sig = 1, eta = 0, kappa = 1, alf = 2, bet = 2) { r <- (x - mu)/sig 1/sig^2 * (s.1.m.singly.censored(r, alf, bet) - s.0.m.singly.censored(r, alf, bet)^2) }
setCgram = function(type, nugget=sill*0, sill, anisRanges, extraPar=0){ utils::data("variogramModels") stopifnot(all(dim(sill)==dim(nugget)), ncol(sill)==nrow(sill), type %in% gsi.validModels) dim(sill) = c(1,dim(sill)) dim(anisRanges) = c(1,dim(anisRanges)) vgout <- list(type=type, data=extraPar, nugget=nugget, sill=sill, M=anisRanges ) class(vgout) = "gmCgram" return(vgout) } "[[.gmCgram"<- function(x,i,...){ nG = dim(x$M)[3] nD = dim(x$nugget)[1] nSo = length(i) nSi = dim(x$M)[1] if(i==0){ out = with(x, list(type=type[i], data=data[i], nugget=nugget, sill=structure(0*sill[1,,], dim=c(nSo, nD, nD)), M=structure(M[1,,], dim=c(nSo, nG, nG)))) }else if( (0 %in% i) & !any(i<0)){ j = i[i>0] out = with(x, list(type=type[j], data=data[j], nugget=nugget, sill=structure(sill[j,,], dim=c(nSo-1, nD, nD)), M=structure(M[j,,], dim=c(nSo-1, nG, nG)))) }else if(all(i>0) | all(i<0)){ if(all(i<0)) nSo = nSi-nSo out = with(x, list(type=type[i], data=data[i], nugget=nugget*0, sill=structure(sill[i,,], dim=c(nSo, nD, nD)), M=structure(M[i,,], dim=c(nSo, nG, nG)))) }else{ stop("index set i cannot merge 0 and negative numbers") } class(out) = class(x) return(out) } "+.gmCgram" <- function(x,y) { y = as.gmCgram(y) stopifnot(class(y)=="gmCgram", dim(x$sill)[-1]==dim(y$sill)[-1], dim(x$M)[-1]==dim(y$M)[-1]) myfun = function(A,B){ D = dim(A)[2] nA = dim(A)[1] nB = dim(B)[1] dim(A) = c(nA, D^2) dim(B) = c(nB, D^2) out = rbind(A, B) dim(out) = c(nA+nB, D, D) return(out) } x$type = c(x$type, y$type) x$data= c(x$data, y$data) x$nugget = x$nugget + y$nugget x$sill = myfun(x$sill, y$sill) x$M = myfun(x$M, y$M) return(x) } "[.gmCgram"<- function(x,i,j=i,...){ nDi = length(i) nDj = length(j) nS = dim(x$M)[1] out = with(x, list(type=type, data=data, nugget=structure(nugget[i,j, drop=F], dim=c(nDi, nDj)), sill=structure(sill[,i,j, drop=F], dim=c(nS, nDi, nDj)), M=M)) class(out) = class(x) if(!all(i==j)) class(out) = unique(c("gmXCgram", class(out))) return(out) } length.gmCgram = function(x) length(x$type) if(!isGeneric("ncol")){ ncol <- function(x) UseMethod("ncol",x) ncol.default <- base::ncol } if(!isGeneric("nrow")){ nrow <- function(x) UseMethod("nrow",x) nrow.default <- base::nrow } ncol.gmCgram = function(x) ncol(x$nugget) nrow.gmCgram = function(x) nrow(x$nugget) as.function.gmCgram = function(x,...){ f <- function(X,Y=X){ if(is(X,"Spatial")) X = sp::coordinates(X) X = as.matrix(X) if(is(Y,"Spatial")) Y = sp::coordinates(Y) Y = as.matrix(Y) stopifnot(ncol(X)==ncol(Y), ncol(X)==dim(x$M)[3]) ijEqual = ifelse(nrow(X)==nrow(Y), all(X==Y), FALSE) o = gsi.calcCgram(X,Y,x,ijEqual) return(o) } return(f) } predict.gmCgram = function(object, newdata, ...){ as.function(object)(X=newdata) } as.gmCgram <- function(m, ...) UseMethod("as.gmCgram",m) as.gmCgram.default <- function(m,...) m plot.gmCgram = function(x, xlim.up=NULL, xlim.lo=NULL, vdir.up= NULL, vdir.lo= NULL, xlength=200, varnames = colnames(x$nugget), add=FALSE, commonAxis=TRUE, cov =TRUE, closeplot=TRUE, ...){ Dg = dim(x$M)[2] Ns = dim(x$M)[1] Dv = dim(x$nugget)[1] if(is.null(varnames)) varnames = paste("v", 1:Dv, sep="") if(is.null(vdir.up) & is.null(vdir.lo)){ vdir.lo = rep(0, Dg) vdir.lo[1] = 1 dim(vdir.lo) = c(1,Dg) if(!is.isotropic(x)){ aux = diag(Dg) if(Dg==3){ vdir.lo = aux[3,] vdir.up = aux[-3,] }else vdir.lo = aux } } if(!is.null(vdir.up)) vdir.up = compositions::oneOrDataset(compositions::normalize(vdir.up)) if(!is.null(vdir.lo)) vdir.lo = compositions::oneOrDataset(compositions::normalize(vdir.lo)) fk = c(sqrt(3),1,3)[x$type+1]*1.25 if(is.null(xlim.up)){ if(add){ par(mfg=c(1,2)) xlim.up = par()$usr[1:2] }else if(!is.null(vdir.up)){ maxdist = sapply(1:Ns, function(i) max(sapply(1:nrow(vdir.up), function(j) vdir.up[j,]%*%x$M[i,,]%*%vdir.up[j,]))) xlim.up = c(0, max(fk*maxdist)) } } if(is.null(xlim.lo)){ if(add){ par(mfg=c(2,1)) xlim.lo = par()$usr[1:2] }else if(!is.null(vdir.lo)){ maxdist = sapply(1:Ns, function(i) max(sapply(1:nrow(vdir.lo), function(j) vdir.lo[j,]%*%x$M[i,,]%*%vdir.lo[j,]))) xlim.lo = c(0, max(fk*maxdist)) } } if(!is.null(xlim.up)){ xseq.up = seq(from=xlim.up[1], to=xlim.up[2], length.out=xlength) }else{ xseq.up=NULL} if(!is.null(xlim.lo)){ xseq.lo = seq(from=xlim.lo[1], to=xlim.lo[2], length.out=xlength) }else{ xseq.lo=NULL} opar = par() opar = par_remove_readonly(opar) if(closeplot) on.exit(par(opar)) getVdens = function(vdir, xseq){ if(is.null(vdir)|is.null(xseq)) return(NULL) Vdens = sapply(1:nrow(vdir), function(k){ X = outer(xseq, vdir[k,]) Y = X[1,,drop=F]*0 gsi.calcCgram(X,Y,x,FALSE) }) dim(Vdens) = c(Dv,xlength,Dv,nrow(vdir)) if(!cov){ Y = matrix(rep(0,Dg), ncol=Dg) C0 = gsi.calcCgram(Y,Y,x,FALSE) dim(C0) = c(Dv,Dv) Vdens = sweep(-Vdens, c(1,3), C0, "+") } return(Vdens) } Vdens.up = getVdens(vdir.up, xseq.up) Vdens.lo = getVdens(vdir.lo, xseq.lo) myplot = function(...) matplot(type="l",ylab="", xlab="",xaxt="n", ...) if(add) myplot = function(...) matlines(...) if(!add){ par(mfrow=c(Dv+1,Dv+1), mar=c(2,3,0,0), oma=c(1,4,1,1), xpd=NA) myplot(c(0,0), c(0,0), pch="", ann=FALSE, bty="n", yaxt="n") } for(i in 1:Dv){ for(j in 1:Dv){ if((i>=j)&!(is.null(vdir.lo)|is.null(xlim.lo))){ par(mfg=c(i+1,j,Dv+1,Dv+1)) ylim = range(Vdens.lo[,,j,]) if(commonAxis) ylim=range(Vdens.lo[,,j,]) myplot(xseq.lo, Vdens.lo[i,,j,], ylim=ylim, ...) if(i==j & !add){ axis(side = 3) mtext(text=varnames[i], side = 3, line=3) mtext(text=varnames[i], side = 4, line=3) } } if((i<=j)&!(is.null(vdir.up)|is.null(xlim.up))){ par(mfg=c(i,j+1,Dv+1,Dv+1)) ylim = range(Vdens.up[,,j,]) if(commonAxis) ylim=range(Vdens.up[,,j,]) myplot(xseq.up, Vdens.up[i,,j,], ylim=ylim,...) if(i==j & !add){ axis(side = 1) mtext(text=varnames[i], side = 1, line=3) mtext(text=varnames[i], side = 2, line=3) } } }} mtext(text="lag distance", side=1, outer = TRUE, line=0) mtext(text=c("semivariogram","covariance")[cov+1], side=2, outer = TRUE, line=2) invisible(opar) } is.isotropic <- function(x, tol=1e-10, ...){ UseMethod("is.isotropic", x) } is.isotropic.default = function(x, tol=1e-10, ...) NA is.isotropic.gmCgram = function(x, tol=1e-10, ...){ all(apply(x$M, 1, function(y){ ev = eigen(y, only.values=TRUE)[[1]] all(abs(ev-ev[1])<tol) })) } is.isotropic.variogramModel = function(x, tol=1e-10, ...){ anis = x[,grep("anis", colnames(x))] all(apply(anis, 2, function(y) all(abs(y-y[1])<tol) ) ) } is.isotropic.variogramModelList = function(x, tol=1e-10, ...) is.isotropic(x[[1]], tol=tol) is.isotropic.LMCAnisCompo = function(x, tol=1e-10, ...){ all(sapply(x["A",], 1, function(y){ ev = eigen(y$A, only.values=TRUE)[[1]] all(abs(ev-ev[1])<tol) })) } variogram_gmSpatialModel <- function(object, methodPars=NULL, ...){ if(!is.null(methodPars)) stop("use 'variogram' with named parameters only") gstat::variogram(as.gstat(object), ...) } gsi.EVario2D = function(X,Z,Ff=rep(1, nrow(X)), maxdist= max(dist(X[sample(nrow(X),min(nrow(X),1000)),]))/2, lagNr = 15, lags = seq(from=0, to=maxdist, length.out=lagNr+1), azimuthNr=4, azimuths = seq(from=0, to=180, length.out=azimuthNr+1)[1:azimuthNr], maxbreadth=Inf, minpairs=10, cov=FALSE){ N = nrow(X) Dv = ncol(Z) Dg = ncol(X) stopifnot(N==nrow(Z)) if(length(dim(Ff))==0){ stopifnot(N==length(Ff)) }else{ stopifnot(N==nrow(Ff)) } if(length(dim(lags))==0){ lags = data.frame(minlag=lags[-length(lags)], maxlag=lags[-1]) if(maxbreadth!=Inf) lags[,"maxbreadth"]=maxbreadth }else if(dim(lags)==2){ lags = data.frame(lags) colnames(lags) = c("minlag","maxlag","maxbreadth")[1:ncol(lags)] }else stop("lags can be either a vector of lags or a data.frame, see ?gsi.EVario2D") if(length(dim(azimuths))==0){ tol = (azimuths[2]-azimuths[1])/2 if(is.na(tol)) tol=180 azimuths = data.frame(minaz=azimuths-tol, maxaz=azimuths+tol) }else if(dim(azimuths)==2){ azimuths = data.frame(azimuths) colnames(azimuths) = c("minaz","maxaz") }else stop("azimuths can be either a vector of lags or a data.frame, see ?gsi.EVario2D") if(cov){ kk = 1 if(dim(Z)==dim(Ff)){ Z = Z-Ff }else if(ncol(Z)==length(c(unlist(Ff)))){ Z = sweep(Z, 2, Ff, "-") } }else{ kk = 1 Z = lm(as.matrix(Z)~as.matrix(Ff)+0)$residuals } ij = expand.grid(1:nrow(X), 1:nrow(X)) op = ifelse(cov, "*", "-") ZZ = outer(as.matrix(Z),as.matrix(Z), op) ZZ = aperm(ZZ, c(1,3,2,4)) dim(ZZ) = c(N*N, Dv, Dv) XX = X[ij[,1],]-X[ij[,2],] XXabs = gmApply(XX, 1, function(x) sqrt(sum(x^2))) XXaz = gmApply(XX, 1, function(x) pi/2-atan2(x[2],x[1])) +2*pi XXaz = XXaz %% pi Nh = nrow(lags) Na = nrow(azimuths) vg = array(0, dim=c(Nh, Dv, Dv, Na)) n = array(0, dim=c(Nh, Na)) azs = azimuths * pi/180 res = sapply(1:Na, function(i){ tk_a = (azs[i,1]<=XXaz) & (azs[i,2]>=XXaz) zz = ZZ[tk_a,,] xxabs = XXabs[tk_a] xxaz = XXaz[tk_a] tk_h = outer(xxabs, lags[,1],">=") & outer(xxabs, lags[,2],"<=") if(ncol(lags)>2){ tk_b = outer(xxabs * abs(sin((xxaz-(azs[i,2]-azs[i,1])))), lags[,3], "<=") tk_h = tk_h & tk_b } n[,i] = colSums(tk_h) for(j in 1:Nh){ if(n[j,i]>minpairs){ vg[j,,,i] = gmApply(zz[tk_h[,j],,], c(2,3),"sum")/(kk*n[j,i]) }else{ vg[j,,,i]=NA } } return(list(gamma=vg[,,,i], lags=gsi.lagClass(lags), npairs =n[,i])) }) attr(res, "directions") = gsi.azimuthInterval(azimuths) attr(res, "type") = ifelse(cov, "covariance","semivariogram") class(res) = "gmEVario" return(res) } plot.gmEVario = function(x, xlim.up=NULL, xlim.lo=NULL, vdir.up= NULL, vdir.lo= NULL, varnames = dimnames(x$gamma)[[2]], type="o", add=FALSE, commonAxis=TRUE, cov =attr(x,"type")=="covariance", closeplot=TRUE, ...){ Dv = dim(x[1,1][[1]])[2] if(is.null(varnames)) varnames = paste("v", 1:Dv, sep="") if(is.null(vdir.up)&is.null(vdir.lo)) vdir.lo <- 1:ndirections(x) if( any(c(vdir.up, vdir.lo)>ndirections(x))){ stop("indicated directions (vdir.up or vdir.lo) do not exist in x") } if(is.null(xlim.up)){ if(add){ par(mfg=c(1,2)) xlim.up = par()$usr[1:2] }else if(!is.null(vdir.up)){ maxdist = max(sapply(x["lags",], gsi.midValues.lagClass ) ) xlim.up = c(0, maxdist) } } if(is.null(xlim.lo)){ if(add){ par(mfg=c(2,1)) xlim.lo = par()$usr[1:2] }else if(!is.null(vdir.lo)){ maxdist = max(sapply(x["lags",], gsi.midValues.lagClass ) ) xlim.lo = c(0, maxdist) } } opar = par() opar = par_remove_readonly(opar) if(closeplot) on.exit(par(opar)) myplot = function(...) matplot(type=type, ylab="", xlab="",xaxt="n", ...) if(add) myplot = function(...) matpoints(type=type, ...) if(!add){ myplot(c(0,0), c(0,0), pch="", ann=FALSE, bty="n", yaxt="n") par(mfrow=c(Dv+1,Dv+1), mar=c(2,3,0,0), oma=c(1,4,1,1), xpd=NA) } for(i in 1:Dv){ for(j in 1:Dv){ if((i>=j)&(!is.null(vdir.lo))){ par(mfg=c(i+1,j,Dv+1,Dv+1)) ylim = range(sapply(vdir.lo, function(kk) x["gamma",kk][[1]][,i,j])) if(commonAxis) ylim=range(sapply(vdir.lo, function(kk) x["gamma",kk][[1]][,,j])) myplot( sapply(vdir.lo, function(kk) gsi.midValues.lagClass(x["lags",kk][[1]])), sapply(vdir.lo, function(kk) x["gamma",kk][[1]][,i,j]), ylim=ylim, ...) if(i==j){ axis(side = 3) mtext(text=varnames[i], side = 3, line=3) mtext(text=varnames[i], side = 4, line=3) } } if((i<=j)&(!is.null(vdir.up))){ par(mfg=c(i,j+1,Dv+1,Dv+1)) ylim = range(sapply(vdir.up, function(kk) x["gamma",kk][[1]][,i,j])) if(commonAxis) ylim=range(sapply(vdir.up, function(kk) x["gamma",kk][[1]][,,j])) myplot( sapply(vdir.up, function(kk) gsi.midValues.lagClass(x["lags",kk][[1]])), sapply(vdir.up, function(kk) x["gamma",kk][[1]][,i,j]), ylim=ylim, ...) if(i==j){ axis(side = 1) mtext(text=varnames[i], side = 1, line=3) mtext(text=varnames[i], side = 2, line=3) } } }} mtext(text="lag distance", side=1, outer = TRUE, line=0) mtext(text=c("semivariogram","covariance")[cov+1], side=2, outer = TRUE, line=2) attr(opar, "vdir.up")=vdir.up attr(opar, "vdir.lo")=vdir.lo invisible(opar) } as.gmEVario <- function(vgemp,...){ UseMethod("as.gmEVario",vgemp)} as.gmEVario.default <- function(vgemp,...) vgemp variogramModelPlot <- function(vg, ...) UseMethod("variogramModelPlot", vg) variogramModelPlot.gmEVario <- function(vg, model = NULL, col = rev(rainbow(ndirections(vg))), commonAxis = FALSE, newfig = TRUE, closeplot=TRUE, ...){ opar = plot(vg, commonAxis=commonAxis, add=!newfig, col=col, closeplot=is.null(model), ...) opar = par_remove_readonly(opar) if(closeplot) on.exit(par(opar)) vdir.lo = attr(opar, "vdir.lo") vdir.up = attr(opar, "vdir.up") if(is.null(model)) return(invisible(opar)) aux = as.directorVector(attr(vg, "directions")) if(!is.null(vdir.lo)) vdir.lo = aux[vdir.lo,] if(!is.null(vdir.up)) vdir.up = aux[vdir.up,] opar = plot(as.gmCgram(model), vdir.up= vdir.up, vdir.lo= vdir.lo, add=TRUE, cov =FALSE, ...) invisible(opar) } ndirections <- function(x){ UseMethod("ndirections", x) } ndirections.default = function(x) nrow(x) ndirections.azimuth = function(x) length(x) ndirections.azimuthInterval = function(x) length(x[[1]]) ndirections.logratioVariogramAnisotropy = function(x) ndirections(attr(x,"directions")) ndirections.logratioVariogram = function(x) 1 ndirections.gmEVario = function(x) ndirections(attr(x,"directions")) ndirections.gstatVariogram = function(x){ length(unique(paste(x$dir.hor, x$dir.ver))) } gsi.azimuth = function(x){ class(x) = c("azimuth","directionClass") return(x) } gsi.azimuthInterval = function(x){ class(x) = c("azimuthInterval","directionClass") return(x) } gsi.directorVector = function(x){ if(length(dim(x))!=2) stop("provided director vectors are not a matrix!") class(x) = c("directorVector", "directionClass") return(x) } print.directionClass = function(x, complete=TRUE, ...){ cat(paste("with",nrow(as.directorVector(x)),"directions\n")) if(complete){ print(unclass(x), ...) } } as.directorVector <- function(x){ UseMethod("as.directorVector",x) } as.directorVector.default = function(x,...) x as.directorVector.azimuth = function(x, D=2){ res = cbind(cos(pi/2-x), sin(pi/2-x)) if(D>2){ res = cbind(res, matrix(0, ncol=D-2, nrow=nrow(res))) } colnames(res) = paste("v", 1:ncol(res), sep="") return(gsi.directorVector(res)) } as.directorVector.azimuthInterval = function(x, D=2){ res = (x[[1]]+x[[2]])/2 return(as.directorVector.azimuth(res)) } gsi.lagdists = function(x){ class(x) = c("lagdist","lagClass") return(x) } gsi.lagClass = function(x){ if(length(dim(x))!=2) stop("provided lag classes are not matrix-like!") class(x) = c("lagClass") return(x) } print.lagClass = function(x,...){ if(is.list(x)){ print(as.data.frame(unclass(x)), ...) }else{ print(unclass(x), ...) } } gsi.midValues <- function(x) UseMethod("gsi.midValues",x) gsi.midValues.default = function(x) x gsi.midValues.lagClass <- function(x){ (x[[1]]+x[[2]])/2 } gsi.midValues.azimuthInterval <- function(x){ (x[[1]]+x[[2]])/2 } setClassUnion(name="ModelStructuralFunctionSpecification", members=c("NULL","gmCgram", "LMCAnisCompo", "variogramModelList", "variogramModel")) setClass("gmGaussianModel", slots = list(structure = "ModelStructuralFunctionSpecification", formula="formula", beta = "numeric") ) setClassUnion(name="EmpiricalStructuralFunctionSpecification", members=c("NULL","gmEVario", "logratioVariogram", "logratioVariogramAnisotropy", "gstatVariogram"))
mniRL <- readNIfTI(file.path(system.file("nifti", package="oro.nifti"), "mniRL")) image(mniRL) orthographic(mniRL)
rtnorm <- function(mu, sd, MIN) { x <- rnorm(1, mu, sd) if (x < MIN) { x <- qnorm(runif(1, pnorm(MIN, mu, sd, 1, 0), 1), mu, sd, 1, 0) } return(x) } dtnorm <- function(x, mu, sd, MIN) { if (x < MIN) { return(-1e+15) } else { return(dnorm(x, mu, sd, 1) - log(1 - pnorm(MIN, mu, sd, 1, 0))) } }
BTD_cov <- function (case_task, case_covar, control_task, control_covar, alternative = c("less", "two.sided", "greater"), int_level = 0.95, iter = 10000, use_sumstats = FALSE, cor_mat = NULL, sample_size = NULL) { if (use_sumstats & (is.null(cor_mat) | is.null(sample_size))) stop("Please supply both correlation matrix and sample size") if (int_level < 0 | int_level > 1) stop("Interval level must be between 0 and 1") if (length(case_task) != 1) stop("case_task should be single value") if (!is.null(cor_mat)) if (sum(eigen(cor_mat)$values > 0) < length(diag(cor_mat))) stop("cor_mat is not positive definite") if (!is.null(cor_mat) | !is.null(sample_size)) if (use_sumstats == FALSE) stop("If input is summary data, set use_sumstats = TRUE") if (is.data.frame(control_covar)) control_covar <- as.matrix(control_covar) alternative <- match.arg(alternative) if (use_sumstats) { sum_stats <- rbind(control_task, control_covar) if (length(sum_stats[ , 2]) != nrow(cor_mat)) stop("Number of variables and number of correlations does not match") cov_mat <- diag(sum_stats[ , 2]) %*% cor_mat %*% diag(sum_stats[ , 2]) lazy_gen <- MASS::mvrnorm(sample_size, mu = sum_stats[ , 1], Sigma = cov_mat, empirical = TRUE) control_task <- lazy_gen[ , 1] control_covar <- lazy_gen[ , -1] } alpha <- 1 - int_level n <- length(control_task) m <- length(case_covar) k <- length(case_task) m_ct <- mean(control_task) sd_ct <- stats::sd(control_task) df <- (n - m + k - 2) X <- cbind(rep(1, n), control_covar) Y <- control_task B_ast <- solve(t(X) %*% X) %*% t(X) %*% Y Sigma_ast <- t(Y - X %*% B_ast) %*% (Y - X %*% B_ast) Sigma_hat <- c(CholWishart::rInvWishart(iter, df = (n - m + k - 2), Sigma_ast)) B_ast_vec <- c(B_ast) lazy <- Sigma_hat[1] %x% solve(t(X) %*% X) Lambda <- array(dim = c(nrow(lazy), ncol(lazy), iter)) for(i in 1:iter) Lambda[ , , i] <- Sigma_hat[i] %x% solve(t(X) %*% X) rm(lazy) B_vec <- matrix(ncol = (m+1)*k, nrow = iter) for(i in 1:iter) B_vec[i, ] <- MASS::mvrnorm(1, mu = B_ast_vec, Lambda[ , , i]) mu_hat <- vector(length = iter) for (i in 1:iter) mu_hat[i] <- matrix(B_vec[i, ], ncol = (m+1), byrow = TRUE) %*% c(1, case_covar) z_hat_ccc <- (case_task - mu_hat) / sqrt(Sigma_hat) if (alternative == "less") { pval <- stats::pnorm(z_hat_ccc) } else if (alternative == "greater") { pval <- stats::pnorm(z_hat_ccc, lower.tail = FALSE) } else if (alternative == "two.sided") { pval <- 2 * stats::pnorm(abs(z_hat_ccc), lower.tail = FALSE) } mu_ast <- t(B_ast) %*% c(1, case_covar) var_ast <- Sigma_ast/(n - 1) zccc <- (case_task - mu_ast) / sqrt(var_ast) zccc_int <- stats::quantile(z_hat_ccc, c(alpha/2, (1 - alpha/2))) names(zccc_int) <- c("Lower Z-CCC CI", "Upper Z-CCC CI") p_est <- mean(pval) p_int <- stats::quantile(pval, c(alpha/2, (1 - alpha/2)))*100 if (alternative == "two.sided") p_int <- stats::quantile(pval/2, c(alpha/2, (1 - alpha/2)))*100 names(p_int) <- c("Lower p CI", "Upper p CI") estimate <- round(c(zccc, p_est*100), 6) if (alternative == "two.sided") estimate <- c(zccc, (p_est/2)*100) zccc.name <- paste0("Std. case score (Z-CCC), ", 100*int_level, "% CI [", format(round(zccc_int[1], 2), nsmall = 2),", ", format(round(zccc_int[2], 2), nsmall = 2),"]") if (alternative == "less") { alt.p.name <- "Proportion below case (%), " } else if (alternative == "greater") { alt.p.name <- "Proportion above case (%), " } else { if (zccc < 0) { alt.p.name <- "Proportion below case (%), " } else { alt.p.name <- "Proportion above case (%), " } } p.name <- paste0(alt.p.name, 100*int_level, "% CI [", format(round(p_int[1], 2), nsmall = 2),", ", format(round(p_int[2], 2), nsmall = 2),"]") names(estimate) <- c(zccc.name, p.name) control_task <- matrix(control_task, ncol = 1, dimnames = list(NULL, "Task")) xname <- c() for (i in 1:length(case_covar)) xname[i] <- paste0("COV", i) control_covar <- matrix(control_covar, ncol = length(case_covar), dimnames = list(NULL, xname)) cor.mat <- stats::cor(cbind(control_task, control_covar)) desc <- data.frame(Means = colMeans(cbind(control_task, control_covar)), SD = apply(cbind(control_task, control_covar), 2, stats::sd), Case_score = c(case_task, case_covar)) typ.int <- 100*int_level names(typ.int) <- "Interval level (%)" interval <- c(typ.int, zccc_int, p_int) names(df) <- "df" null.value <- 0 names(null.value) <- "diff. between case and controls" output <- list(parameter = df, p.value = p_est, estimate = estimate, null.value = null.value, interval = interval, desc = desc, cor.mat = cor.mat, sample.size = n, alternative = alternative, method = paste("Bayesian Test of Deficit with Covariates"), data.name = paste0("Case = ", format(round(case_task, 2), nsmall = 2), ", Controls (m = ", format(round(m_ct, 2), nsmall = 2), ", sd = ", format(round(sd_ct, 2), nsmall = 2), ", n = ", n, ")")) class(output) <- "htest" output }